text:
"use strict";

const Position = require("./ast/position");

/**
 * @private
 */
function isNumber(n) {
  return n != "." && n != "," && !isNaN(parseFloat(n)) && isFinite(n);
}

/**
 * The PHP Parser class that build the AST tree from the lexer
 *
 * @constructor Parser
 * @memberOf module:php-parser
 * @tutorial Parser
 * @property {Lexer} lexer - current lexer instance
 * @property {AST} ast - the AST factory instance
 * @property {number|string} token - current token
 * @property {boolean} extractDoc - should extract documentation as AST node
 * @property {boolean} extractTokens - should extract each token
 * @property {boolean} suppressErrors - should ignore parsing errors and continue
 * @property {boolean} debug - should output debug informations
 */
const Parser = function (lexer, ast) {
  this.lexer = lexer;
  this.ast = ast;
  this.tok = lexer.tok;
  this.EOF = lexer.EOF;
  this.token = null;
  this.prev = null;
  this.debug = false;
  this.version = 801;
  this.extractDoc = false;
  this.extractTokens = false;
  this.suppressErrors = false;
  const mapIt = function (item) {
    return [item, null];
  };
  this.entries = {
    // reserved_non_modifiers
    IDENTIFIER: new Map(
      [
        this.tok.T_ABSTRACT,
        this.tok.T_ARRAY,
        this.tok.T_AS,
        this.tok.T_BREAK,
        this.tok.T_CALLABLE,
        this.tok.T_CASE,
        this.tok.T_CATCH,
        this.tok.T_CLASS,
        this.tok.T_CLASS_C,
        this.tok.T_CLONE,
        this.tok.T_CONST,
        this.tok.T_CONTINUE,
        this.tok.T_DECLARE,
        this.tok.T_DEFAULT,
        this.tok.T_DIR,
        this.tok.T_DO,
        this.tok.T_ECHO,
        this.tok.T_ELSE,
        this.tok.T_ELSEIF,
        this.tok.T_EMPTY,
        this.tok.T_ENDDECLARE,
        this.tok.T_ENDFOR,
        this.tok.T_ENDFOREACH,
        this.tok.T_ENDIF,
        this.tok.T_ENDSWITCH,
        this.tok.T_ENDWHILE,
        this.tok.T_ENUM,
        this.tok.T_EVAL,
        this.tok.T_EXIT,
        this.tok.T_EXTENDS,
        this.tok.T_FILE,
        this.tok.T_FINAL,
        this.tok.T_FINALLY,
        this.tok.T_FN,
        this.tok.T_FOR,
        this.tok.T_FOREACH,
        this.tok.T_FUNC_C,
        this.tok.T_FUNCTION,
        this.tok.T_GLOBAL,
        this.tok.T_GOTO,
        this.tok.T_IF,
        this.tok.T_IMPLEMENTS,
        this.tok.T_INCLUDE,
        this.tok.T_INCLUDE_ONCE,
        this.tok.T_INSTANCEOF,
        this.tok.T_INSTEADOF,
        this.tok.T_INTERFACE,
        this.tok.T_ISSET,
        this.tok.T_LINE,
        this.tok.T_LIST,
        this.tok.T_LOGICAL_AND,
        this.tok.T_LOGICAL_OR,
        this.tok.T_LOGICAL_XOR,
        this.tok.T_MATCH,
        this.tok.T_METHOD_C,
        this.tok.T_NAMESPACE,
        this.tok.T_NEW,
        this.tok.T_NS_C,
        this.tok.T_PRINT,
        this.tok.T_PRIVATE,
        this.tok.T_PROTECTED,
        this.tok.T_PUBLIC,
        this.tok.T_READ_ONLY,
        this.tok.T_REQUIRE,
        this.tok.T_REQUIRE_ONCE,
        this.tok.T_RETURN,
        this.tok.T_STATIC,
        this.tok.T_SWITCH,
        this.tok.T_THROW,
        this.tok.T_TRAIT,
        this.tok.T_TRY,
        this.tok.T_UNSET,
        this.tok.T_USE,
        this.tok.T_VAR,
        this.tok.T_WHILE,
        this.tok.T_YIELD,
      ].map(mapIt)
    ),
    VARIABLE: new Map(
      [
        this.tok.T_VARIABLE,
        "$",
        "&",
        this.tok.T_STRING,
        this.tok.T_NAME_RELATIVE,
        this.tok.T_NAME_QUALIFIED,
        this.tok.T_NAME_FULLY_QUALIFIED,
        this.tok.T_NAMESPACE,
        this.tok.T_STATIC,
      ].map(mapIt)
    ),
    SCALAR: new Map(
      [
        this.tok.T_CONSTANT_ENCAPSED_STRING,
        this.tok.T_START_HEREDOC,
        this.tok.T_LNUMBER,
        this.tok.T_DNUMBER,
        this.tok.T_ARRAY,
        "[",
        this.tok.T_CLASS_C,
        this.tok.T_TRAIT_C,
        this.tok.T_FUNC_C,
        this.tok.T_METHOD_C,
        this.tok.T_LINE,
        this.tok.T_FILE,
        this.tok.T_DIR,
        this.tok.T_NS_C,
        '"',
        'b"',
        'B"',
        "-",
        this.tok.T_NS_SEPARATOR,
      ].map(mapIt)
    ),
    T_MAGIC_CONST: new Map(
      [
        this.tok.T_CLASS_C,
        this.tok.T_TRAIT_C,
        this.tok.T_FUNC_C,
        this.tok.T_METHOD_C,
        this.tok.T_LINE,
        this.tok.T_FILE,
        this.tok.T_DIR,
        this.tok.T_NS_C,
      ].map(mapIt)
    ),
    T_MEMBER_FLAGS: new Map(
      [
        this.tok.T_PUBLIC,
        this.tok.T_PRIVATE,
        this.tok.T_PROTECTED,
        this.tok.T_STATIC,
        this.tok.T_ABSTRACT,
        this.tok.T_FINAL,
      ].map(mapIt)
    ),
    EOS: new Map([";", this.EOF, this.tok.T_INLINE_HTML].map(mapIt)),
    EXPR: new Map(
      [
        "@",
        "-",
        "+",
        "!",
        "~",
        "(",
        "`",
        this.tok.T_LIST,
        this.tok.T_CLONE,
        this.tok.T_INC,
        this.tok.T_DEC,
        this.tok.T_NEW,
        this.tok.T_ISSET,
        this.tok.T_EMPTY,
        this.tok.T_MATCH,
        this.tok.T_INCLUDE,
        this.tok.T_INCLUDE_ONCE,
        this.tok.T_REQUIRE,
        this.tok.T_REQUIRE_ONCE,
        this.tok.T_EVAL,
        this.tok.T_INT_CAST,
        this.tok.T_DOUBLE_CAST,
        this.tok.T_STRING_CAST,
        this.tok.T_ARRAY_CAST,
        this.tok.T_OBJECT_CAST,
        this.tok.T_BOOL_CAST,
        this.tok.T_UNSET_CAST,
        this.tok.T_EXIT,
        this.tok.T_PRINT,
        this.tok.T_YIELD,
        this.tok.T_STATIC,
        this.tok.T_FUNCTION,
        this.tok.T_FN,
        // using VARIABLES :
        this.tok.T_VARIABLE,
        "$",
        this.tok.T_NS_SEPARATOR,
        this.tok.T_STRING,
        this.tok.T_NAME_RELATIVE,
        this.tok.T_NAME_QUALIFIED,
        this.tok.T_NAME_FULLY_QUALIFIED,
        // using SCALAR :
        this.tok.T_STRING, // @see variable.js line 45 > conflict with variable = shift/reduce :)
        this.tok.T_CONSTANT_ENCAPSED_STRING,
        this.tok.T_START_HEREDOC,
        this.tok.T_LNUMBER,
        this.tok.T_DNUMBER,
        this.tok.T_ARRAY,
        "[",
        this.tok.T_CLASS_C,
        this.tok.T_TRAIT_C,
        this.tok.T_FUNC_C,
        this.tok.T_METHOD_C,
        this.tok.T_LINE,
        this.tok.T_FILE,
        this.tok.T_DIR,
        this.tok.T_NS_C,
        '"',
        'b"',
        'B"',
        "-",
        this.tok.T_NS_SEPARATOR,
      ].map(mapIt)
    ),
  };
};

/**
 * helper : gets a token name
 * @function Parser#getTokenName
 * @memberOf module:php-parser
 */
Parser.prototype.getTokenName = function (token) {
  if (!isNumber(token)) {
    return "'" + token + "'";
  } else {
    if (token == this.EOF) return "the end of file (EOF)";
    return this.lexer.engine.tokens.values[token];
  }
};

/**
 * main entry point : converts a source code to AST
 * @function Parser#parse
 * @memberOf module:php-parser
 */
Parser.prototype.parse = function (code, filename) {
  this._errors = [];
  this.filename = filename || "eval";
  this.currentNamespace = [""];
  if (this.extractDoc) {
    this._docs = [];
  } else {
    this._docs = null;
  }
  if (this.extractTokens) {
    this._tokens = [];
  } else {
    this._tokens = null;
  }
  this._docIndex = 0;
  this._lastNode = null;
  this.lexer.setInput(code);
  this.lexer.all_tokens = this.extractTokens;
  this.lexer.comment_tokens = this.extractDoc;
  this.length = this.lexer._input.length;
  this.innerList = false;
  this.innerListForm = false;
  const program = this.node("program");
  const childs = [];
  this.next();
  while (this.token != this.EOF) {
    childs.push(this.read_start());
  }
  // append last comment
  if (
    childs.length === 0 &&
    this.extractDoc &&
    this._docs.length > this._docIndex
  ) {
    childs.push(this.node("noop")());
  }
  // #176 : register latest position
  this.prev = [
    this.lexer.yylloc.last_line,
    this.lexer.yylloc.last_column,
    this.lexer.offset,
  ];
  const result = program(childs, this._errors, this._docs, this._tokens);
  if (this.debug) {
    const errors = this.ast.checkNodes();
    /* istanbul ignore next */
    if (errors.length > 0) {
      errors.forEach(function (error) {
        if (error.position) {
          // eslint-disable-next-line no-console
          console.log(
            "Node at line " +
              error.position.line +
              ", column " +
              error.position.column
          );
        }
        // eslint-disable-next-line no-console
        console.log(error.stack.join("\n"));
      });
      throw new Error("Some nodes are not closed");
    }
  }
  return result;
};

/**
 * Raise an error
 * @function Parser#raiseError
 * @memberOf module:php-parser
 */
Parser.prototype.raiseError = function (message, msgExpect, expect, token) {
  message += " on line " + this.lexer.yylloc.first_line;
  if (!this.suppressErrors) {
    const err = new SyntaxError(
      message,
      this.filename,
      this.lexer.yylloc.first_line
    );
    err.lineNumber = this.lexer.yylloc.first_line;
    err.fileName = this.filename;
    err.columnNumber = this.lexer.yylloc.first_column;
    throw err;
  }
  // Error node :
  const node = this.ast.prepare("error", null, this)(
    message,
    token,
    this.lexer.yylloc.first_line,
    expect
  );
  this._errors.push(node);
  return node;
};

/**
 * handling errors
 * @function Parser#error
 * @memberOf module:php-parser
 */
Parser.prototype.error = function (expect) {
  let msg = "Parse Error : syntax error";
  let token = this.getTokenName(this.token);
  let msgExpect = "";

  if (this.token !== this.EOF) {
    if (isNumber(this.token)) {
      let symbol = this.text();
      /* istanbul ignore next */
      if (symbol.length > 10) {
        symbol = symbol.substring(0, 7) + "...";
      }
      token = "'" + symbol + "' (" + token + ")";
    }
    msg += ", unexpected " + token;
  }
  if (expect && !Array.isArray(expect)) {
    if (isNumber(expect) || expect.length === 1) {
      msgExpect = ", expecting " + this.getTokenName(expect);
    }
    msg += msgExpect;
  }
  return this.raiseError(msg, msgExpect, expect, token);
};

/**
 * Create a position node from the lexers position
 *
 * @function Parser#position
 * @memberOf module:php-parser
 * @return {Position}
 */
Parser.prototype.position = function () {
  return new Position(
    this.lexer.yylloc.first_line,
    this.lexer.yylloc.first_column,
    this.lexer.yylloc.first_offset
  );
};

/**
 * Creates a new AST node
 * @function Parser#node
 * @memberOf module:php-parser
 */
Parser.prototype.node = function (name) {
  if (this.extractDoc) {
    let docs = null;
    if (this._docIndex < this._docs.length) {
      docs = this._docs.slice(this._docIndex);
      this._docIndex = this._docs.length;
      /* istanbul ignore next */
      if (this.debug) {
        // eslint-disable-next-line no-console
        console.log(new Error("Append docs on " + name));
        // eslint-disable-next-line no-console
        console.log(docs);
      }
    }
    const node = this.ast.prepare(name, docs, this);
    /*
     * TOKENS :
     * node1 commentA token commmentB node2 commentC token commentD node3 commentE token
     *
     * AST :
     * structure:S1 [
     *    left: node1 ( trail: commentA ),
     *    right: structure:S2 [
     *       node2 (lead: commentB, trail: commentC),
     *       node3 (lead: commentD)
     *    ],
     *    trail: commentE
     * ]
     *
     * Algorithm :
     *
     * Attach the last comments on parent of current node
     * If a new node is started and the parent has a trailing comment
     * the move it on previous node
     *
     * start S2
     * start node1
     * consume node1 & set commentA as trailingComment on S2
     * start S2
     * S1 has a trailingComment, attach it on node1
     * ...
     * NOTE : As the trailingComment Behavior depends on AST, it will be build on
     * the AST layer - last child node will keep it's trailingComment nodes
     */
    node.postBuild = function (self) {
      if (this._docIndex < this._docs.length) {
        if (this._lastNode) {
          const offset = this.prev[2];
          let max = this._docIndex;
          for (; max < this._docs.length; max++) {
            if (this._docs[max].offset > offset) {
              break;
            }
          }
          if (max > this._docIndex) {
            // inject trailing comment on child node
            this._lastNode.setTrailingComments(
              this._docs.slice(this._docIndex, max)
            );
            this._docIndex = max;
          }
        } else if (this.token === this.EOF) {
          // end of content
          self.setTrailingComments(this._docs.slice(this._docIndex));
          this._docIndex = this._docs.length;
        }
      }
      this._lastNode = self;
    }.bind(this);
    return node;
  }
  return this.ast.prepare(name, null, this);
};

/**
 * expects an end of statement or end of file
 * @function Parser#expectEndOfStatement
 * @memberOf module:php-parser
 * @return {boolean}
 */
Parser.prototype.expectEndOfStatement = function (node) {
  if (this.token === ";") {
    // include only real ';' statements
    // https://github.com/glayzzle/php-parser/issues/164
    if (node && this.lexer.yytext === ";") {
      node.includeToken(this);
    }
  } else if (this.token !== this.tok.T_INLINE_HTML && this.token !== this.EOF) {
    this.error(";");
    return false;
  }
  this.next();
  return true;
};

const ignoreStack = ["parser.next", "parser.node", "parser.showlog"];
/**
 * outputs some debug information on current token
 * @private
 * @function Parser#showlog
 * @memberOf module:php-parser
 */
Parser.prototype.showlog = function () {
  const stack = new Error().stack.split("\n");
  let line;
  for (let offset = 2; offset < stack.length; offset++) {
    line = stack[offset].trim();
    let found = false;
    for (let i = 0; i < ignoreStack.length; i++) {
      /* istanbul ignore next */
      if (line.substring(3, 3 + ignoreStack[i].length) === ignoreStack[i]) {
        found = true;
        break;
      }
    }
    /* istanbul ignore next */
    if (!found) {
      break;
    }
  }
  // eslint-disable-next-line no-console
  console.log(
    "Line " +
      this.lexer.yylloc.first_line +
      " : " +
      this.getTokenName(this.token) +
      ">" +
      this.lexer.yytext +
      "<" +
      " @-->" +
      line
  );
  return this;
};

/**
 * Force the parser to check the current token.
 *
 * If the current token does not match to expected token,
 * the an error will be raised.
 *
 * If the suppressError mode is activated, then the error will
 * be added to the program error stack and this function will return `false`.
 *
 * @function Parser#expect
 * @memberOf module:php-parser
 * @param {String|Number} token
 * @return {boolean}
 * @throws Error
 */
Parser.prototype.expect = function (token) {
  if (Array.isArray(token)) {
    if (token.indexOf(this.token) === -1) {
      this.error(token);
      return false;
    }
  } else if (this.token != token) {
    this.error(token);
    return false;
  }
  return true;
};

/**
 * Returns the current token contents
 * @function Parser#text
 * @memberOf module:php-parser
 * @return {String}
 */
Parser.prototype.text = function () {
  return this.lexer.yytext;
};

/**
 * consume the next token
 * @function Parser#next
 * @memberOf module:php-parser
 */
Parser.prototype.next = function () {
  // prepare the back command
  if (this.token !== ";" || this.lexer.yytext === ";") {
    // ignore '?>' from automated resolution
    // https://github.com/glayzzle/php-parser/issues/168
    this.prev = [
      this.lexer.yylloc.last_line,
      this.lexer.yylloc.last_column,
      this.lexer.offset,
    ];
  }

  // eating the token
  this.lex();

  // showing the debug
  if (this.debug) {
    this.showlog();
  }

  // handling comments
  if (this.extractDoc) {
    while (
      this.token === this.tok.T_COMMENT ||
      this.token === this.tok.T_DOC_COMMENT
    ) {
      // APPEND COMMENTS
      if (this.token === this.tok.T_COMMENT) {
        this._docs.push(this.read_comment());
      } else {
        this._docs.push(this.read_doc_comment());
      }
    }
  }

  return this;
};

/**
 * Peek at the next token.
 * @function Parser#peek
 * @memberOf module:php-parser
 * @returns {string|number} Next Token
 */
Parser.prototype.peek = function () {
  const lexerState = this.lexer.getState();
  const nextToken = this.lexer.lex();
  this.lexer.setState(lexerState);
  return nextToken;
};

/**
 * Eating a token
 * @function Parser#lex
 * @memberOf module:php-parser
 */
Parser.prototype.lex = function () {
  // append on token stack
  if (this.extractTokens) {
    do {
      // the token
      this.token = this.lexer.lex() || /* istanbul ignore next */ this.EOF;
      if (this.token === this.EOF) return this;
      let entry = this.lexer.yytext;
      if (
        Object.prototype.hasOwnProperty.call(
          this.lexer.engine.tokens.values,
          this.token
        )
      ) {
        entry = [
          this.lexer.engine.tokens.values[this.token],
          entry,
          this.lexer.yylloc.first_line,
          this.lexer.yylloc.first_offset,
          this.lexer.offset,
        ];
      } else {
        entry = [
          null,
          entry,
          this.lexer.yylloc.first_line,
          this.lexer.yylloc.first_offset,
          this.lexer.offset,
        ];
      }
      this._tokens.push(entry);
      if (this.token === this.tok.T_CLOSE_TAG) {
        // https://github.com/php/php-src/blob/7ff186434e82ee7be7c59d0db9a976641cf7b09c/Zend/zend_compile.c#L1680
        this.token = ";";
        return this;
      } else if (this.token === this.tok.T_OPEN_TAG_WITH_ECHO) {
        this.token = this.tok.T_ECHO;
        return this;
      }
    } while (
      this.token === this.tok.T_WHITESPACE || // ignore white space
      (!this.extractDoc &&
        (this.token === this.tok.T_COMMENT || // ignore single lines comments
          this.token === this.tok.T_DOC_COMMENT)) || // ignore doc comments
      // ignore open tags
      this.token === this.tok.T_OPEN_TAG
    );
  } else {
    this.token = this.lexer.lex() || /* istanbul ignore next */ this.EOF;
  }
  return this;
};

/**
 * Check if token is of specified type
 * @function Parser#is
 * @memberOf module:php-parser
 */
Parser.prototype.is = function (type) {
  if (Array.isArray(type)) {
    return type.indexOf(this.token) !== -1;
  }
  return this.entries[type].has(this.token);
};

// extends the parser with syntax files
[
  require("./parser/array.js"),
  require("./parser/class.js"),
  require("./parser/comment.js"),
  require("./parser/expr.js"),
  require("./parser/enum.js"),
  require("./parser/function.js"),
  require("./parser/if.js"),
  require("./parser/loops.js"),
  require("./parser/main.js"),
  require("./parser/namespace.js"),
  require("./parser/scalar.js"),
  require("./parser/statement.js"),
  require("./parser/switch.js"),
  require("./parser/try.js"),
  require("./parser/utils.js"),
  require("./parser/variable.js"),
].forEach(function (ext) {
  for (const k in ext) {
    /* istanbul ignore next */
    if (Object.prototype.hasOwnProperty.call(Parser.prototype, k)) {
      // @see https://github.com/glayzzle/php-parser/issues/234
      throw new Error("Function " + k + " is already defined - collision");
    }
    Parser.prototype[k] = ext[k];
  }
});

module.exports = Parser;


text:
import re

class Geocoder:
    def __init__(self, state_abbr_filepath, city_filepath):
        self.state_abbr_filepath = state_abbr_filepath
        self.city_filepath = city_filepath
        self.location_dict = self.make_location_dict()
        self.state_abbr_dict = self.make_state_abbr_dict()

    def make_location_dict(self):
        location_dict = {}
        for line in open(self.city_filepath, 'r'):
            name, point = line.rstrip().split(':')
            city, state = name.lower().split('\t')
            point = point.split('\t')
            if not state in location_dict: location_dict[state] = {}
            location_dict[state][city] = point
        return location_dict

    def make_state_abbr_dict(self):
        state_abbr_dict = {}
        for line in open(self.state_abbr_filepath, 'r'):
            full, abbr = line.rstrip().lower().split(',')
            state_abbr_dict[full] = abbr
        return state_abbr_dict

    def geocode(self, location_text):
        match = re.match('\s*(\w+)\s*,\s*(\w+\.?\w+\.?)\s?', location_text.lower())
        if match == None:
            return None
        else:
            state = re.sub('\.','',match.group(2))
            city = match.group(1)
            if state in self.state_abbr_dict:
                """ full name -> abbr """
                state = self.state_abbr_dict[state]
            if state in self.location_dict:
                if city in self.location_dict[state]:
                    point = self.location_dict[state][city]
                    return point
            return None

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Decoder.Params
</TITLE>

<META NAME="keywords" CONTENT="javazoom.jl.decoder.Decoder.Params class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

javazoom.jl.decoder

Class Decoder.Params

java.lang.Object
  javazoom.jl.decoder.Decoder.Params

All Implemented Interfaces:
java.lang.Cloneable

Enclosing class:
Decoder

public static class Decoder.Params
extends java.lang.Object
implements java.lang.Cloneable

The Params class presents the customizable
 aspects of the decoder.

 Instances of this class are not thread safe.

Constructor Summary

Decoder.Params()

Method Summary

 java.lang.Object
clone()

 Equalizer
getInitialEqualizerSettings()

          Retrieves the equalizer settings that the decoder's equalizer
 will be initialized from.

 OutputChannels
getOutputChannels()

 void
setOutputChannels(OutputChannels out)

Methods inherited from class java.lang.Object

equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Decoder.Params

public Decoder.Params()

Method Detail

clone

public java.lang.Object clone()

setOutputChannels

public void setOutputChannels(OutputChannels out)

getOutputChannels

public OutputChannels getOutputChannels()

getInitialEqualizerSettings

public Equalizer getInitialEqualizerSettings()

Retrieves the equalizer settings that the decoder's equalizer
 will be initialized from.

 The Equalizer instance returned
 cannot be changed in real time to affect the
 decoder output as it is used only to initialize the decoders
 EQ settings. To affect the decoder's output in realtime,
 use the Equalizer returned from the getEqualizer() method on
 the decoder.

Returns:
The Equalizer used to initialize the
			EQ settings of the decoder.

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

JavaZOOM 1999-2005


text:
/*
 * Maintained by brightSPARK Labs.
 * www.brightsparklabs.com
 *
 * Refer to LICENSE at repository root for license details.
 */

package com.brightsparklabs.asanti.reader.parser;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import com.brightsparklabs.asanti.model.schema.AsnModuleTaggingMode;
import com.brightsparklabs.asanti.model.schema.type.AsnSchemaType;
import com.brightsparklabs.asanti.model.schema.typedefinition.AsnSchemaTypeDefinition;
import java.text.ParseException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

/**
 * Unit tests for {@link AsnSchemaTypeDefinitionParser}
 *
 * @author brightSPARK Labs
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest(AsnSchemaTypeParser.class)
public class AnSchemaTypeDefinitionParserTest {
    // -------------------------------------------------------------------------
    // FIXTURES
    // -------------------------------------------------------------------------

    /** an argument capture helper for AsnSchemaTypeParser */
    private ArgumentCaptor<String> parserArgument;

    // -------------------------------------------------------------------------
    // SETUP/TEAR-DOWN
    // -------------------------------------------------------------------------

    @Before
    public void setUpBeforeTest() throws Exception {
        // Mockito does a tear down after each test, so we can't do this as a BeforeClass

        // Setup the mock child parser.
        // We do want to test that the child parser gets passed the correct information,
        // so we setup the argument captors.

        // mock AsnSchemaConstraintParser.parse static method
        PowerMockito.mockStatic(AsnSchemaTypeParser.class);
        // we want to capture the parserArgument that gets passed to the AsnSchemaTypeParser
        parserArgument = ArgumentCaptor.forClass(String.class);
        ArgumentCaptor<AsnModuleTaggingMode> taggingMode =
                ArgumentCaptor.forClass(AsnModuleTaggingMode.class);
        when(AsnSchemaTypeParser.parse(parserArgument.capture(), taggingMode.capture()))
                .thenReturn(AsnSchemaType.NULL);
    }

    // -------------------------------------------------------------------------
    // TESTS
    // -------------------------------------------------------------------------

    @Test
    public void testParseErrors() throws Exception {
        // null name
        try {
            AsnSchemaTypeDefinitionParser.parse(null, "SomeType", AsnModuleTaggingMode.DEFAULT);
            fail("ParseException not thrown");
        } catch (final ParseException ex) {
        }

        // blank name
        try {
            AsnSchemaTypeDefinitionParser.parse("", "SomeType", AsnModuleTaggingMode.DEFAULT);
            fail("ParseException not thrown");
        } catch (final ParseException ex) {
        }
        try {
            AsnSchemaTypeDefinitionParser.parse(" ", "SomeType", AsnModuleTaggingMode.DEFAULT);
            fail("ParseException not thrown");
        } catch (final ParseException ex) {
        }

        // blank value
        try {
            AsnSchemaTypeDefinitionParser.parse("TEST_NAME", "", AsnModuleTaggingMode.DEFAULT);
            fail("ParseException not thrown");
        } catch (final ParseException ex) {
        }
        // nulll value
        try {
            AsnSchemaTypeDefinitionParser.parse("TEST_NAME", null, AsnModuleTaggingMode.DEFAULT);
            fail("ParseException not thrown");
        } catch (final ParseException ex) {
        }
        // nulll tagging mode
        try {
            AsnSchemaTypeDefinitionParser.parse("TEST_NAME", "SomeType", null);
            fail("NullPointerException not thrown");
        } catch (final NullPointerException ex) {
        }
    }

    @Test
    public void testParse() throws Exception {
        final AsnSchemaTypeDefinition result =
                AsnSchemaTypeDefinitionParser.parse(
                        "TEST_NAME", "IA5String (SIZE (10))", AsnModuleTaggingMode.DEFAULT);

        assertEquals("TEST_NAME", result.getName());
        assertEquals("IA5String (SIZE (10))", parserArgument.getValue());
    }

    @Test
    public void testArgumentPassing() throws Exception {
        final String toParser =
                "It does not matter what the content, the AsnSchemaTypeDefinitionParser "
                        + "should just pass it straight through to the parser.\n"
                        + "That is where all the real parsing is done.";

        final AsnSchemaTypeDefinition result =
                AsnSchemaTypeDefinitionParser.parse(
                        "TEST_NAME", toParser, AsnModuleTaggingMode.DEFAULT);

        assertEquals("TEST_NAME", result.getName());
        assertEquals(toParser, parserArgument.getValue());
    }
}


text:
module.exports = function(app, Rx) {

    var posts = []

    /**
     * взяь массив постов, которые прилетели и отображены на странице в текущий момент
     * Как только в одном из постов меняется флаг hasBeenJustUpdated на true, наблюдатель срабатывает
     * @returns {*}
     */
    function getAllPosts() {

        posts = [
            { id: 1, title: "Post 1", hasBeenJustUpdated: false },
            { id: 12, title: "Post 2", hasBeenJustUpdated: false },
            { id: 13, title: "Post 3", hasBeenJustUpdated: false },
            { id: 14, title: "Post 4", hasBeenJustUpdated: false },
        ]

        return posts
    }

    /**
     *  Создаем поток всех постов
     *
     * @returns {*}
     */
    function createStreamFromPosts() /*: Observable<post[]> */ {
        return Rx.Observable.from( getAllPosts() );
    }

    function updatePosts(post){

        console.log('update post ', post)

        // todo: delete post from posts arr

        posts.push(post)

        console.log(posts)
    }

    fetchPost = function (id, callback) {
        console.log('fetch post')

        callback()
    }

    renderPost = function (id) {
        console.log('Render post ' + id)
    }
        /**
     * запросить конкретный пост и перерисовать его view
     */
    var doSomeAction = Rx.Observer.create(
        post => {
            // Всё Ок, пост получен

            fetchPost(post.id, function(){
                // перерисовать пост
                renderPost(post.id)

                // сбрость флаг обновления
                post.hasBeenJustUpdated = 0

                // обновить данный пост в массиве posts
                updatePosts(post)
            })
        },
        error => {
            var mesg = error.message || 'что-то пошло не так'
            console.log(mesg);
        },
        () => {
            console.log('onCompleted is Done');
        }
    );

    /**
     * Наконец, клиентский код:
     * В потоке постов ищем обновленный айтем и применяем к нему действие
     * Предполагается, что поток генерирует объекты типа post
     */
    createStreamFromPosts().where( post => post.hasBeenJustUpdated === true ).subscribe( doSomeAction )

};


text:
using namespace mage;

MAGE_GAME_APP( MarioClone );

//---------------------------------------
MarioClone::MarioClone()
	: MageGame( "Super Mario Clone", 0, 0, 800, 600, false )
{
	mDataRoot = "../MarioClone/data/";
	AddPathToData( "../MarioClone/data" );
	//SetDataArchivePassword( "password", 1 );
}
//---------------------------------------
MarioClone::~MarioClone()
{}
//---------------------------------------
bool MarioClone::OnInitialize()
{
	// @TODO fix job manager from burning out the cpu
	JobManager::GetInstance()->SetMaxWorkerThreads( 0 );
	//mSpriteManager.LoadSpriteDefinition( "../MarioClone/data/sprites/mario.sprites" );
	//mSpriteManager.LoadSpriteAnimations( "../MarioClone/data/sprites/mario.anim" );

	// Do this in data
	mCamera->SetViewport( 320, 224 );
	//RectI worldBounds = mGameMap.GetWorldBounds();
	//mCamera->SetWorldBounds( 0, worldBounds.Right, 0, 224 );

	return true;
}
//---------------------------------------


text:
'use strict';

var data = document.getElementById('data');

fetch('json/foo.json').then(function(response) {
  return response.json();
}).then(function(j) {
  data.textContent = 'JSON fetched:\n\n' + JSON.stringify(j, null, 2);
});


text:
LUYA admin UI is currently supported by following operating systems and browsers:

## Mac OSX Sierra and up

+ Firefox 47
+ Chrome 52
+ Opera 47
+ Safari (10.1)
+ Yandex 14.12

## Windows 10 and up

+ Edge 14
+ Firefox 47
+ Chrome 52
+ Opera 47
+ IE 11
+ Yandex 14.12

## Windows 7

+ Edge 14
+ Firefox 47
+ Chrome 52
+ Opera 47
+ IE 10
+ Yandex 14.12

## Mobile Systems

iPad Pro iOS 10.3
+ Safari

Android 4.4 and up
+ Chrome
(for example Galaxy Tab 4 10.4)

Admin UI is only partially supported by mobile devices.

> For the best *LUYA* experience we currently recommend you to use `Google Chrome` or `Firefox`.

### Test protocol

Current test protocol from 2017-12-11:

| System/Browser   | Works      | Display error  |
|:----------|:-------------|------|
|WIn 7 - IE 10    |Yes    |No
|Win 7 - IE 11    |Yes    |No
|Win 7 - Firefox 47    |Yes    |No
|Win 7 - Firefox 57    |Yes    |No
|Win 7 - Chrome 52    |Yes    |No
|Win 7 - Chrome 62    |Yes    |No
|Win 7 - Opera 47    |Yes    |No
|Win 7 - Opera 49    |Yes    |No
|Win 7 - Yandex 14.12    |Yes    |No
|Win 10 - Edge 14    |Yes    |No
|Win 10 - Edge 15    |Yes    |No
|Win 10 - Edge 16    | Yes    |No
|Win 10 - IE 11    |Yes    |No
|Win 10 - Firefox 57    |Yes    |No
|Win 10 - Firefox 47    |Yes    |No
|Win 10 - Chrome 52    |Yes    |No
|Win 10 - Chrome 62    |Yes    |No
|Win 10 - Opera 47    |Yes    |No
|Win 10 - Opera 49    |Yes    |No
|Win 10 - Yandex 14.12    |Yes    |No
|Mac Sierra - Safari (10.1)    |Yes    |No
|Mac Sierra - Firefox 47    |Yes    |No
|Mac Sierra - Firefox 57    |Yes    |No
|Mac Sierra - Chrome 52    |Yes    |No
|Mac Sierra - Chrome 62    |Yes    |No
|Mac Sierra - Opera 47    |Yes    |No
|Mac Sierra - Opera 49    |Yes    |No
|Mac Sierra - Yandex 14.12    |Yes    |No
|iPad Air 2, iPad 4    |Partly (textfields are too small to edit them)|Yes (icon are not visible in the left sidebar in landscape, the mobile navigation bar is missing in portrait mode, textfields are too small in CRUD view, input labels occluding the login field)
|iPad Pro 10.3    |Yes|No
|Galaxy Tab 4 10.4    |Yes|No


text:
// ZAP: 2011/04/08 Changed to support clearview() in HttpPanels
// ZAP: 2011/04/08 Changed to use PopupMenuResendMessage
// ZAP: 2011/07/23 Use new add alert popup
// ZAP: 2011/09/06 Fix alert save plus concurrent mod exceptions
// ZAP: 2011/10/23 Fix add note and manage tags dialogs
// ZAP: 2011/11/20 Set order
// ZAP: 2011/12/21 Added 'show in history' popup
// ZAP: 2012/02/18 Rationalised session handling
// ZAP: 2012/03/03 Moved popups to stdmenus extension
// ZAP: 2012/03/15 Changed the method getResendDialog to pass the configuration key
// to the ManualRequestEditorDialog.
// ZAP: 2012/03/17 Issue 282 Added getAuthor()
// ZAP: 2012/04/24 Added type arguments to generic types, removed unnecessary
// cast and added @Override annotation to all appropriate methods.
// ZAP: 2012/04/28 Added log of exception.
// ZAP: 2012/05/31 Issue 308 NPE in sessionChangedEventHandler in daemon mode
// ZAP: 2012/07/02 Added the method showAlertAddDialog(HttpMessage, int).
// ZAP: 2012/07/29 Issue 43: added sessionScopeChanged event and removed access to some UI elements
// ZAP: 2012/08/01 Issue 332: added support for Modes
// ZAP: 2012/10/08 Issue 391: Performance improvements
// ZAP: 2013/03/03 Issue 546: Remove all template Javadoc comments
// ZAP: 2013/03/03 Issue 547: Deprecate unused classes and methods
// ZAP: 2013/04/14 Issue 588: ExtensionHistory.historyIdToRef should be cleared when changing
// session
// ZAP: 2013/04/14 Issue 598: Replace/update "old" pop up menu items
// ZAP: 2013/07/14 Issue 725: Clear alert's panel fields
// ZAP: 2013/07/23 Issue 738: Options to hide tabs
// ZAP: 2013/08/07 Also show Authentication messages
// ZAP: 2013/11/16 Issue 869: Differentiate proxied requests from (ZAP) user requests
// ZAP: 2013/12/02 Issue 915: Dynamically filter history based on selection in the sites window
// ZAP: 2014/03/23 Issue 503: Change the footer tabs to display the data
// with tables instead of lists
// ZAP: 2014/03/23 Issue 999: History loaded in wrong order
// ZAP: 2014/04/10 Remove cached history reference when a history reference is removed
// ZAP: 2014/04/10 Issue 1042: Having significant issues opening a previous session
// ZAP: 2014/05/20 Issue 1206: "History" tab is not cleared when a new session is created
// through the API with ZAP in GUI mode
// ZAP: 2014/12/12 Issue 1449: Added help button
// ZAP: 2015/02/09 Issue 1525: Introduce a database interface layer to allow for alternative
// implementations
// ZAP: 2015/03/03 Added delete(href) method to ensure local map updated
// ZAP: 2015/04/02 Issue 321: Support multiple databases and Issue 1582: Low memory option
// ZAP: 2015/07/16 Issue 1617: ZAP 2.4.0 throws HeadlessExceptions when running in daemon mode on
// headless machine
// ZAP: 2015/09/16 Issue 1890: ZAP can't completely scan OWASP Benchmark
// ZAP: 2016/01/26 Fixed findbugs warning
// ZAP: 2016/04/12 Listen to alert events to update the table model entries
// ZAP: 2016/04/14 Use View to display the HTTP messages
// ZAP: 2016/04/05 Issue 2458: Fix xlint warning messages
// ZAP: 2016/05/20 Moved purge method to here from PopupMenuPurgeSites
// ZAP: 2016/05/30 Issue 2494: ZAP Proxy is not showing the HTTP CONNECT Request in history tab
// ZAP: 2016/06/20 Removed unnecessary/unused constructor
// ZAP: 2016/06/21 Prevent deadlock between EDT and threads adding messages to the History tab
// ZAP: 2017/01/30 Use HistoryTableModel.
// ZAP: 2017/03/02 Issue 1634 Improve URL export.
// ZAP: 2017/03/28 Issue 3253 Allow URLs to be exported per context.
// ZAP: 2017/04/07 Added getUIName()
// ZAP: 2017/05/01 Issue 3446 - Add ability to export a Site Map via Context Menu.
// ZAP: 2017/05/02 Move alert related code to ExtensionAlert.
// ZAP: 2017/05/03 Register and process events from HistoryReference.
// ZPA: 2017/06/05 Sync HistoryReference cache.
// ZAP: 2017/06/13 Handle notification of notes set and deprecate/remove code no longer needed.
// ZAP: 2017/10/20 Move methods to delete history entries (Issue 3626).
// ZAP: 2017/11/06 Added (un)registerProxy (Issue 3983)
// ZAP: 2017/11/16 Update the table on sessionChanged (Issue 3207).
// ZAP: 2017/11/22 Delete just the history references selected (Issue 4065).
// ZAP: 2018/01/29 Add getter to expose historyReferencesTable of History tab (Issue 4000).
// ZAP: 2018/02/14 Remove unnecessary boxing / unboxing
// ZAP: 2018/03/12 Use the same help page in request editors.
// ZAP: 2019/06/01 Normalise line endings.
// ZAP: 2019/06/05 Normalise format/style.
// ZAP: 2019/09/30 Use hasView().
// ZAP: 2020/01/02 Do not display messages being deleted.
package org.parosproxy.paros.extension.history;

import java.awt.EventQueue;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import org.apache.commons.collections.map.ReferenceMap;
import org.apache.commons.httpclient.URIException;
import org.apache.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.control.Control;
import org.parosproxy.paros.control.Control.Mode;
import org.parosproxy.paros.core.proxy.ProxyServer;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.db.DatabaseException;
import org.parosproxy.paros.extension.ExtensionAdaptor;
import org.parosproxy.paros.extension.ExtensionHook;
import org.parosproxy.paros.extension.ExtensionHookView;
import org.parosproxy.paros.extension.OptionsChangedListener;
import org.parosproxy.paros.extension.SessionChangedListener;
import org.parosproxy.paros.extension.manualrequest.ManualRequestEditorDialog;
import org.parosproxy.paros.extension.manualrequest.http.impl.ManualHttpRequestEditorDialog;
import org.parosproxy.paros.model.HistoryReference;
import org.parosproxy.paros.model.HistoryReferenceEventPublisher;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.model.Session;
import org.parosproxy.paros.model.SiteMap;
import org.parosproxy.paros.model.SiteNode;
import org.parosproxy.paros.network.HttpMalformedHeaderException;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.view.View;
import org.zaproxy.zap.ZAP;
import org.zaproxy.zap.eventBus.Event;
import org.zaproxy.zap.eventBus.EventConsumer;
import org.zaproxy.zap.extension.alert.AlertEventPublisher;
import org.zaproxy.zap.extension.alert.ExtensionAlert;
import org.zaproxy.zap.extension.help.ExtensionHelp;
import org.zaproxy.zap.extension.history.HistoryFilterPlusDialog;
import org.zaproxy.zap.extension.history.ManageTagsDialog;
import org.zaproxy.zap.extension.history.NotesAddDialog;
import org.zaproxy.zap.extension.history.PopupMenuExportContextURLs;
import org.zaproxy.zap.extension.history.PopupMenuExportSelectedURLs;
import org.zaproxy.zap.extension.history.PopupMenuExportURLs;
import org.zaproxy.zap.extension.history.PopupMenuNote;
import org.zaproxy.zap.extension.history.PopupMenuPurgeHistory;
import org.zaproxy.zap.extension.history.PopupMenuTag;
import org.zaproxy.zap.view.table.HistoryReferencesTable;

public class ExtensionHistory extends ExtensionAdaptor implements SessionChangedListener {

    public static final String NAME = "ExtensionHistory";

    private static final HistoryTableModel EMPTY_MODEL = new HistoryTableModel();

    private LogPanel logPanel = null; //  @jve:decl-index=0:visual-constraint="161,134"
    private ProxyListenerLog proxyListener = null;
    private HistoryTableModel historyTableModel;

    // ZAP: added filter plus dialog
    private HistoryFilterPlusDialog filterPlusDialog = null;

    private PopupMenuPurgeHistory popupMenuPurgeHistory = null;
    private ManualRequestEditorDialog resendDialog = null;

    private PopupMenuExportMessage popupMenuExportMessage2 = null;
    private PopupMenuExportResponse popupMenuExportResponse2 = null;
    private PopupMenuTag popupMenuTag = null;
    // ZAP: Added Export URLs
    private PopupMenuExportURLs popupMenuExportURLs = null;
    private PopupMenuExportSelectedURLs popupMenuExportSelectedURLs = null;
    private PopupMenuExportContextURLs popupMenuExportContextURLs = null;
    // ZAP: Added history notes
    private PopupMenuNote popupMenuNote = null;
    private NotesAddDialog dialogNotesAdd = null;
    private ManageTagsDialog manageTags = null;

    private boolean showJustInScope = false;
    private boolean linkWithSitesTree;
    private String linkWithSitesTreeBaseUri;

    // Used to cache hrefs not added into the historyList
    @SuppressWarnings("unchecked")
    private Map<Integer, HistoryReference> historyIdToRef =
            Collections.synchronizedMap(new ReferenceMap());

    /**
     * Flag that indicates whether or not the session is changing. To prevent updating the table
     * more than once when opening a session.
     *
     * @see #sessionAboutToChange(Session)
     * @see #sessionScopeChanged(Session)
     * @see #sessionChanged(Session)
     */
    private boolean sessionChanging;

    private Logger logger = Logger.getLogger(ExtensionHistory.class);

    public ExtensionHistory() {
        super(NAME);
        this.setOrder(16);
    }

    @Override
    public String getUIName() {
        return Constant.messages.getString("history.name");
    }

    /**
     * This method initializes logPanel
     *
     * @return org.parosproxy.paros.extension.history.LogPanel
     */
    private LogPanel getLogPanel() {
        if (logPanel == null) {
            logPanel = new LogPanel(getView());
            logPanel.setName(Constant.messages.getString("history.panel.title")); // ZAP: i18n
            // ZAP: Added History (calendar) icon
            logPanel.setIcon(
                    new ImageIcon(
                            ExtensionHistory.class.getResource(
                                    "/resource/icon/16/025.png"))); // 'calendar' icon
            // Dont allow this tab to be hidden
            logPanel.setHideable(false);

            logPanel.setExtension(this);
            logPanel.setModel(historyTableModel);
        }
        return logPanel;
    }

    /** @deprecated (2.6.0) No longer used/needed. */
    @Deprecated
    public void clearLogPanelDisplayQueue() {}

    public HistoryReference getSelectedHistoryReference() {
        return getLogPanel().getSelectedHistoryReference();
    }

    public List<HistoryReference> getSelectedHistoryReferences() {
        return getLogPanel().getSelectedHistoryReferences();
    }

    @Override
    public void init() {
        super.init();

        historyTableModel = new HistoryTableModel();
        EventConsumerImpl eventConsumerImpl = new EventConsumerImpl();
        ZAP.getEventBus()
                .registerConsumer(
                        eventConsumerImpl, AlertEventPublisher.getPublisher().getPublisherName());
        ZAP.getEventBus()
                .registerConsumer(
                        eventConsumerImpl,
                        HistoryReferenceEventPublisher.getPublisher().getPublisherName());
    }

    @SuppressWarnings("deprecation")
    @Override
    public void hook(ExtensionHook extensionHook) {
        super.hook(extensionHook);
        extensionHook.addSessionListener(this);
        extensionHook.addProxyListener(getProxyListenerLog());
        extensionHook.addConnectionRequestProxyListener(getProxyListenerLog());

        if (hasView()) {
            ExtensionHookView pv = extensionHook.getHookView();
            pv.addStatusPanel(getLogPanel());
            extensionHook.addOptionsChangedListener((OptionsChangedListener) getResendDialog());

            extensionHook.getHookMenu().addPopupMenuItem(getPopupMenuTag());
            // ZAP: Added history notes
            extensionHook.getHookMenu().addPopupMenuItem(getPopupMenuNote());

            //	        extensionHook.getHookMenu().addPopupMenuItem(getPopupMenuExportMessage());
            //          extensionHook.getHookMenu().addPopupMenuItem(getPopupMenuExportResponse());

            extensionHook.getHookMenu().addPopupMenuItem(getPopupMenuPurgeHistory());

            // same as PopupMenuExport but for File menu
            // ZAP: Move 'export' menu items to Report menu
            extensionHook.getHookMenu().addReportMenuItem(getPopupMenuExportMessage2());
            extensionHook.getHookMenu().addReportMenuItem(getPopupMenuExportResponse2());
            extensionHook
                    .getHookMenu()
                    .addReportMenuItem(extensionHook.getHookMenu().getMenuSeparator());
            extensionHook.getHookMenu().addReportMenuItem(getPopupMenuExportURLs());
            extensionHook.getHookMenu().addReportMenuItem(getPopupMenuExportSelectedURLs());
            extensionHook.getHookMenu().addReportMenuItem(getPopupMenuExportContextURLs());
            extensionHook
                    .getHookMenu()
                    .addReportMenuItem(extensionHook.getHookMenu().getMenuSeparator());

            extensionHook.getHookMenu().addPopupMenuItem(createPopupMenuExportURLs());
            extensionHook.getHookMenu().addPopupMenuItem(createPopupMenuExportSelectedURLs());

            ExtensionHelp.enableHelpKey(this.getLogPanel(), "ui.tabs.history");
        }
    }

    @Override
    public void sessionChanged(final Session session) {
        sessionChanging = false;
        sessionChanged();
    }

    private ProxyListenerLog getProxyListenerLog() {
        if (proxyListener == null) {
            proxyListener = new ProxyListenerLog(getModel(), getView(), this);
        }
        return proxyListener;
    }

    public void registerProxy(ProxyServer ps) {
        ps.addProxyListener(this.getProxyListenerLog());
    }

    public void unregisterProxy(ProxyServer ps) {
        ps.removeProxyListener(this.getProxyListenerLog());
    }

    public void removeFromHistoryList(final HistoryReference href) {
        if (!hasView() || EventQueue.isDispatchThread()) {
            if (hasView()) {
                logPanel.setDisplaySelectedMessage(false);
            }
            this.historyTableModel.removeEntry(href.getHistoryId());
            if (hasView()) {
                logPanel.setDisplaySelectedMessage(true);
            }
            historyIdToRef.remove(href.getHistoryId());
        } else {
            EventQueue.invokeLater(
                    new Runnable() {

                        @Override
                        public void run() {
                            removeFromHistoryList(href);
                        }
                    });
        }
    }

    public void notifyHistoryItemChanged(HistoryReference href) {
        notifyHistoryItemChanged(href.getHistoryId());
    }

    private void notifyHistoryItemChanged(final int historyId) {
        if (!hasView() || EventQueue.isDispatchThread()) {
            this.historyTableModel.refreshEntryRow(historyId);
        } else {
            EventQueue.invokeLater(
                    new Runnable() {

                        @Override
                        public void run() {
                            notifyHistoryItemChanged(historyId);
                        }
                    });
        }
    }

    private void notifyHistoryItemsChanged() {
        if (!hasView() || EventQueue.isDispatchThread()) {
            this.historyTableModel.refreshEntryRows();
        } else {
            EventQueue.invokeLater(
                    new Runnable() {

                        @Override
                        public void run() {
                            notifyHistoryItemsChanged();
                        }
                    });
        }
    }

    public void delete(HistoryReference href) {
        if (href != null) {
            this.historyIdToRef.remove(href.getHistoryId());
            href.delete();
        }
    }

    public HistoryReference getHistoryReference(int historyId) {
        HistoryReference href = historyTableModel.getHistoryReference(historyId);
        if (href != null) {
            return href;
        }
        href = historyIdToRef.get(historyId);
        if (href == null) {
            try {
                href = new HistoryReference(historyId);
                if (href.getHistoryType() != HistoryReference.TYPE_SCANNER_TEMPORARY) {
                    addToMap(href);
                }
            } catch (Exception e) {
                return null;
            }
        }
        return href;
    }

    public int getLastHistoryId() {
        return Model.getSingleton().getDb().getTableHistory().lastIndex();
    }

    public void addHistory(HttpMessage msg, int type) {
        try {
            this.addHistory(new HistoryReference(Model.getSingleton().getSession(), type, msg));
        } catch (final Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    private void addToMap(HistoryReference historyRef) {
        historyIdToRef.put(historyRef.getHistoryId(), historyRef);
    }

    public void addHistory(HistoryReference historyRef) {
        if (Constant.isLowMemoryOptionSet()) {
            return;
        }
        try {
            synchronized (historyTableModel) {
                if (isHistoryTypeToShow(historyRef.getHistoryType())) {
                    final String uri = historyRef.getURI().toString();
                    if (this.showJustInScope && !getModel().getSession().isInScope(uri)) {
                        // Not in scope
                        addToMap(historyRef);
                        return;
                    } else if (linkWithSitesTree
                            && linkWithSitesTreeBaseUri != null
                            && !uri.startsWith(linkWithSitesTreeBaseUri)) {
                        // Not under the selected node
                        addToMap(historyRef);
                        return;
                    }
                    if (hasView()) {
                        // Dont do this in daemon mode
                        HistoryFilterPlusDialog dialog = getFilterPlusDialog();
                        HistoryFilter historyFilter = dialog.getFilter();
                        if (historyFilter != null && !historyFilter.matches(historyRef)) {
                            // Not in filter
                            addToMap(historyRef);
                            return;
                        }

                        addHistoryInEventQueue(historyRef);
                    }
                }
            }
        } catch (final Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * Tells whether or not the messages with the given history type should be shown in the History
     * tab.
     *
     * @param historyType the history type that will be checked
     * @return {@code true} if it should be shown, {@code false} otherwise
     */
    private static boolean isHistoryTypeToShow(int historyType) {
        return historyType == HistoryReference.TYPE_PROXIED
                || historyType == HistoryReference.TYPE_ZAP_USER
                || historyType == HistoryReference.TYPE_AUTHENTICATION
                || historyType == HistoryReference.TYPE_PROXY_CONNECT;
    }

    private void addHistoryInEventQueue(final HistoryReference ref) {
        if (!hasView() || EventQueue.isDispatchThread()) {
            historyTableModel.addHistoryReference(ref);
        } else {
            EventQueue.invokeLater(
                    new Runnable() {
                        @Override
                        public void run() {
                            addHistoryInEventQueue(ref);
                        }
                    });
        }
    }

    private void searchHistory(HistoryFilter historyFilter) {
        Session session = getModel().getSession();

        synchronized (historyTableModel) {
            try {
                // ZAP: Added type argument.
                List<Integer> list =
                        getModel()
                                .getDb()
                                .getTableHistory()
                                .getHistoryIdsOfHistType(
                                        session.getSessionId(),
                                        HistoryReference.TYPE_PROXIED,
                                        HistoryReference.TYPE_ZAP_USER,
                                        HistoryReference.TYPE_PROXY_CONNECT);

                buildHistory(list, historyFilter);
            } catch (DatabaseException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    private void buildHistory(List<Integer> dbList, HistoryFilter historyFilter) {
        HistoryReference historyRef = null;
        synchronized (historyTableModel) {
            if (hasView()) {
                getLogPanel().setModel(EMPTY_MODEL);
            }
            historyTableModel.clear();

            for (int i = 0; i < dbList.size(); i++) {
                int historyId = dbList.get(i);

                try {
                    SiteNode sn = getModel().getSession().getSiteTree().getSiteNode(historyId);
                    if (sn != null
                            && sn.getHistoryReference() != null
                            && sn.getHistoryReference().getHistoryId() == historyId) {
                        historyRef = sn.getHistoryReference();
                    } else {
                        historyRef = getHistoryReference(historyId);
                        if (sn != null) {
                            sn.setHistoryReference(historyRef);
                        }
                    }
                    final String uri = historyRef.getURI().toString();
                    if (this.showJustInScope && !getModel().getSession().isInScope(uri)) {
                        // Not in scope
                        continue;
                    } else if (linkWithSitesTree
                            && linkWithSitesTreeBaseUri != null
                            && !uri.startsWith(linkWithSitesTreeBaseUri)) {
                        // Not under the selected node
                        continue;
                    }
                    if (historyFilter != null && !historyFilter.matches(historyRef)) {
                        // Not in filter
                        continue;
                    }
                    historyRef.loadAlerts();
                    historyTableModel.addHistoryReference(historyRef);

                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (hasView()) {
                getLogPanel().setModel(historyTableModel);
            }
        }
    }

    private HistoryFilterPlusDialog getFilterPlusDialog() {
        if (filterPlusDialog == null) {
            filterPlusDialog = new HistoryFilterPlusDialog(getView().getMainFrame(), true);
        }
        return filterPlusDialog;
    }

    protected int showFilterPlusDialog() {
        HistoryFilterPlusDialog dialog = getFilterPlusDialog();
        dialog.setModal(true);
        try {
            dialog.setAllTags(getModel().getDb().getTableTag().getAllTags());
        } catch (DatabaseException e) {
            logger.error(e.getMessage(), e);
        }

        int exit = dialog.showDialog();
        int result = 0; // cancel, state unchanged
        HistoryFilter historyFilter = dialog.getFilter();
        if (exit == JOptionPane.OK_OPTION) {
            searchHistory(historyFilter);
            logPanel.setFilterStatus(historyFilter);
            result = 1; // applied

        } else if (exit == JOptionPane.NO_OPTION) {
            searchHistory(historyFilter);
            logPanel.setFilterStatus(historyFilter);
            result = -1; // reset
        }

        return result;
    }

    private PopupMenuPurgeHistory getPopupMenuPurgeHistory() {
        if (popupMenuPurgeHistory == null) {
            popupMenuPurgeHistory = new PopupMenuPurgeHistory(this);
        }
        return popupMenuPurgeHistory;
    }
    /**
     * This method initializes resendDialog
     *
     * @return org.parosproxy.paros.extension.history.ResendDialog
     */
    public ManualRequestEditorDialog getResendDialog() {
        if (resendDialog == null) {
            resendDialog = new ManualHttpRequestEditorDialog(true, "resend", "ui.dialogs.manreq");
            resendDialog.setTitle(Constant.messages.getString("manReq.dialog.title")); // ZAP: i18n
        }
        return resendDialog;
    }

    /**
     * This method initializes popupMenuExport1
     *
     * @return org.parosproxy.paros.extension.history.PopupMenuExport
     */
    private PopupMenuExportMessage getPopupMenuExportMessage2() {
        if (popupMenuExportMessage2 == null) {
            popupMenuExportMessage2 = new PopupMenuExportMessage();
            popupMenuExportMessage2.setExtension(this);
        }
        return popupMenuExportMessage2;
    }

    /**
     * This method initializes popupMenuExportResponse2
     *
     * @return org.parosproxy.paros.extension.history.PopupMenuExportResponse
     */
    private PopupMenuExportResponse getPopupMenuExportResponse2() {
        if (popupMenuExportResponse2 == null) {
            popupMenuExportResponse2 = new PopupMenuExportResponse();
            popupMenuExportResponse2.setExtension(this);
        }
        return popupMenuExportResponse2;
    }

    private PopupMenuTag getPopupMenuTag() {
        if (popupMenuTag == null) {
            popupMenuTag = new PopupMenuTag(this);
        }
        return popupMenuTag;
    }

    private PopupMenuNote getPopupMenuNote() {
        if (popupMenuNote == null) {
            popupMenuNote = new PopupMenuNote(this);
        }
        return popupMenuNote;
    }

    private void populateNotesAddDialogAndSetVisible(HistoryReference ref, String note) {
        dialogNotesAdd.setNote(note);
        dialogNotesAdd.setHistoryRef(ref);
        dialogNotesAdd.setVisible(true);
    }

    public void showNotesAddDialog(HistoryReference ref, String note) {
        if (dialogNotesAdd == null) {
            dialogNotesAdd = new NotesAddDialog(getView().getMainFrame(), false);
            populateNotesAddDialogAndSetVisible(ref, note);
        } else if (!dialogNotesAdd.isVisible()) {
            populateNotesAddDialogAndSetVisible(ref, note);
        }
    }

    /** @deprecated (2.7.0) No longer used/needed. */
    @Deprecated
    public void hideNotesAddDialog() {}

    /**
     * @deprecated (2.7.0) Use {@link ExtensionAlert#showAlertAddDialog(HistoryReference)} instead.
     * @param ref the {@code HistoryReference} that will have the new alert, if created.
     */
    @Deprecated
    public void showAlertAddDialog(HistoryReference ref) {
        ExtensionAlert extAlert =
                Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.class);
        if (extAlert == null) {
            return;
        }
        extAlert.showAlertAddDialog(ref);
    }

    /**
     * Sets the {@code HttpMessage} and the history type of the {@code HistoryReference} that will
     * be created if the user creates the alert. The current session will be used to create the
     * {@code HistoryReference}. The alert created will be added to the newly created {@code
     * HistoryReference}.
     *
     * <p>Should be used when the alert is added to a temporary {@code HistoryReference} as the
     * temporary {@code HistoryReference}s are deleted when the session is closed.
     *
     * @deprecated (2.7.0) Use {@link ExtensionAlert#showAlertAddDialog(HttpMessage, int)} instead.
     * @param httpMessage the {@code HttpMessage} that will be used to create the {@code
     *     HistoryReference}, must not be {@code null}
     * @param historyType the type of the history reference that will be used to create the {@code
     *     HistoryReference}
     * @see Model#getSession()
     * @see HistoryReference#HistoryReference(org.parosproxy.paros.model.Session, int, HttpMessage)
     */
    @Deprecated
    public void showAlertAddDialog(HttpMessage httpMessage, int historyType) {
        ExtensionAlert extAlert =
                Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.class);
        if (extAlert == null) {
            return;
        }
        extAlert.showAlertAddDialog(httpMessage, historyType);
    }

    /**
     * @deprecated (2.7.0) Use {@link ExtensionAlert#showAlertEditDialog(Alert)} instead.
     * @param alert the alert to edit
     */
    @Deprecated
    public void showAlertAddDialog(Alert alert) {
        ExtensionAlert extAlert =
                Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.class);
        if (extAlert == null) {
            return;
        }
        extAlert.showAlertEditDialog(alert);
    }

    private void populateManageTagsDialogAndSetVisible(HistoryReference ref, List<String> tags) {
        try {
            manageTags.setAllTags(getModel().getDb().getTableTag().getAllTags());
        } catch (DatabaseException e) {
            logger.error(e.getMessage(), e);
        }
        manageTags.setTags(tags);
        manageTags.setHistoryRef(ref);
        manageTags.setVisible(true);
    }

    public void showManageTagsDialog(HistoryReference ref, List<String> tags) {
        if (manageTags == null) {
            manageTags = new ManageTagsDialog(getView().getMainFrame(), false);
            populateManageTagsDialogAndSetVisible(ref, tags);
        } else if (!manageTags.isVisible()) {
            populateManageTagsDialogAndSetVisible(ref, tags);
        }
    }

    private PopupMenuExportURLs getPopupMenuExportURLs() {
        if (popupMenuExportURLs == null) {
            popupMenuExportURLs = createPopupMenuExportURLs();
        }
        return popupMenuExportURLs;
    }

    private PopupMenuExportURLs createPopupMenuExportURLs() {
        return new PopupMenuExportURLs(Constant.messages.getString("exportUrls.popup"), this);
    }

    private PopupMenuExportSelectedURLs getPopupMenuExportSelectedURLs() {
        if (popupMenuExportSelectedURLs == null) {
            popupMenuExportSelectedURLs = createPopupMenuExportSelectedURLs();
        }
        return popupMenuExportSelectedURLs;
    }

    private PopupMenuExportSelectedURLs createPopupMenuExportSelectedURLs() {
        return new PopupMenuExportSelectedURLs(
                Constant.messages.getString("exportUrls.popup.selected"), this);
    }

    private PopupMenuExportContextURLs getPopupMenuExportContextURLs() {
        if (popupMenuExportContextURLs == null) {
            popupMenuExportContextURLs =
                    new PopupMenuExportContextURLs(
                            Constant.messages.getString("context.export.urls.menu"), this);
        }
        return popupMenuExportContextURLs;
    }

    public void showInHistory(HistoryReference href) {
        this.getLogPanel().display(href);
        this.getLogPanel().setTabFocus();
    }

    @Override
    public void sessionAboutToChange(final Session session) {
        sessionChanging = true;

        if (!hasView() || EventQueue.isDispatchThread()) {
            historyTableModel.clear();
            historyIdToRef.clear();

            if (hasView()) {
                getView().displayMessage(null);
            }
        } else {
            try {
                EventQueue.invokeAndWait(
                        new Runnable() {
                            @Override
                            public void run() {
                                sessionAboutToChange(session);
                            }
                        });
            } catch (Exception e) {
                // ZAP: Added logging.
                logger.error(e.getMessage(), e);
            }
        }
    }

    @Override
    public String getAuthor() {
        return Constant.PAROS_TEAM;
    }

    public boolean isShowJustInScope() {
        return showJustInScope;
    }

    public void setShowJustInScope(boolean showJustInScope) {
        this.showJustInScope = showJustInScope;
        if (showJustInScope) {
            linkWithSitesTree = false;
        }
        // Refresh with the next option
        searchHistory(getFilterPlusDialog().getFilter());
    }

    public void purge(SiteMap map, SiteNode node) {
        SiteNode child = null;
        synchronized (map) {
            while (node.getChildCount() > 0) {
                try {
                    child = (SiteNode) node.getChildAt(0);
                    purge(map, child);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }

            if (node.isRoot()) {
                return;
            }

            // delete reference in node
            removeFromHistoryList(node.getHistoryReference());

            ExtensionAlert extAlert =
                    Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.class);

            if (node.getHistoryReference() != null) {
                deleteAlertsFromExtensionAlert(extAlert, node.getHistoryReference());
                node.getHistoryReference().delete();
                map.removeHistoryReference(node.getHistoryReference().getHistoryId());
            }

            // delete past reference in node
            while (node.getPastHistoryReference().size() > 0) {
                HistoryReference ref = node.getPastHistoryReference().get(0);
                deleteAlertsFromExtensionAlert(extAlert, ref);
                removeFromHistoryList(ref);
                delete(ref);
                node.getPastHistoryReference().remove(0);
                map.removeHistoryReference(ref.getHistoryId());
            }

            map.removeNodeFromParent(node);
        }
    }

    private static void deleteAlertsFromExtensionAlert(
            ExtensionAlert extAlert, HistoryReference historyReference) {
        if (extAlert == null) {
            return;
        }

        extAlert.deleteHistoryReferenceAlerts(historyReference);
    }

    void setLinkWithSitesTree(boolean linkWithSitesTree, String baseUri) {
        this.linkWithSitesTree = linkWithSitesTree;
        this.linkWithSitesTreeBaseUri = baseUri;
        if (linkWithSitesTree) {
            this.showJustInScope = false;
        }
        searchHistory(getFilterPlusDialog().getFilter());
    }

    void updateLinkWithSitesTreeBaseUri(String baseUri) {
        this.linkWithSitesTreeBaseUri = baseUri;
        searchHistory(getFilterPlusDialog().getFilter());
    }

    @Override
    public void sessionScopeChanged(Session session) {
        if (sessionChanging) {
            return;
        }
        sessionChanged();
    }

    private void sessionChanged() {
        if (hasView()) {
            searchHistory(getFilterPlusDialog().getFilter());
        } else {
            searchHistory(null);
        }
    }

    @Override
    public void sessionModeChanged(Mode mode) {
        // Ignore
    }

    @Override
    public boolean supportsLowMemory() {
        return true;
    }

    /** Part of the core set of features that should be supported by all db types */
    @Override
    public boolean supportsDb(String type) {
        return true;
    }

    /** @since 2.8.0 */
    public HistoryReferencesTable getHistoryReferencesTable() {
        return logPanel.getHistoryReferenceTable();
    }

    private class EventConsumerImpl implements EventConsumer {

        @Override
        public void eventReceived(Event event) {
            switch (event.getEventType()) {
                case HistoryReferenceEventPublisher.EVENT_NOTE_SET:
                case HistoryReferenceEventPublisher.EVENT_TAG_ADDED:
                case HistoryReferenceEventPublisher.EVENT_TAG_REMOVED:
                case HistoryReferenceEventPublisher.EVENT_TAGS_SET:
                    notifyHistoryItemChanged(
                            Integer.valueOf(
                                    event.getParameters()
                                            .get(
                                                    HistoryReferenceEventPublisher
                                                            .FIELD_HISTORY_REFERENCE_ID)));
                    break;
                case AlertEventPublisher.ALERT_ADDED_EVENT:
                case AlertEventPublisher.ALERT_CHANGED_EVENT:
                case AlertEventPublisher.ALERT_REMOVED_EVENT:
                    notifyHistoryItemChanged(
                            Integer.valueOf(
                                    event.getParameters()
                                            .get(AlertEventPublisher.HISTORY_REFERENCE_ID)));
                    break;
                case AlertEventPublisher.ALL_ALERTS_REMOVED_EVENT:
                    notifyHistoryItemsChanged();
                    break;
                default:
            }
        }
    }

    /**
     * Deletes the given history references from the {@link LogPanel History tab} and the session
     * (database), along with the corresponding {@link SiteNode}s and {@link Alert}s.
     *
     * @param hrefs the history entries to delete.
     * @see View#getDefaultDeleteKeyStroke()
     * @since 2.7.0
     */
    public void purgeHistory(List<HistoryReference> hrefs) {
        if (hasView() && hrefs.size() > 1) {
            int result =
                    getView()
                            .showConfirmDialog(
                                    Constant.messages.getString("history.purge.warning"));
            if (result != JOptionPane.YES_OPTION) {
                return;
            }
        }
        synchronized (this) {
            for (HistoryReference href : hrefs) {
                purgeHistory(href);
            }
        }
    }

    private void purgeHistory(HistoryReference href) {
        if (href == null) {
            return;
        }

        removeFromHistoryList(href);

        ExtensionAlert extAlert =
                Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.class);

        if (extAlert != null) {
            extAlert.deleteHistoryReferenceAlerts(href);
        }

        SiteNode node = href.getSiteNode();
        if (node != null) {
            SiteMap map = Model.getSingleton().getSession().getSiteTree();
            if (node.getHistoryReference() != href) {
                node.getPastHistoryReference().remove(href);
            } else if (!node.getPastHistoryReference().isEmpty()) {
                node.setHistoryReference(node.getPastHistoryReference().remove(0));
                node.getPastHistoryReference().remove(href);
            } else {
                if (node.isLeaf()) {
                    SiteNode parent = node.getParent();
                    map.removeNodeFromParent(node);
                    purgeTemporaryParents(map, parent);
                } else {
                    try {
                        node.setHistoryReference(
                                map.createReference(node, href, href.getHttpMessage()));
                    } catch (URIException
                            | HttpMalformedHeaderException
                            | NullPointerException
                            | DatabaseException e) {
                        logger.error("Failed to create temporary node:", e);
                    }
                }
            }
            map.removeHistoryReference(href.getHistoryId());
        }

        delete(href);
    }

    private void purgeTemporaryParents(SiteMap map, SiteNode node) {
        if (node == null
                || node.isRoot()
                || !node.isLeaf()
                || node.getHistoryReference().getHistoryType() != HistoryReference.TYPE_TEMPORARY) {
            return;
        }

        SiteNode parent = node.getParent();
        purge(map, node);
        purgeTemporaryParents(map, parent);
    }
}


text:
set(PL_PROJECT_NAME "PixelLight")

set(PL_PROJECT_VERSION_MAJOR    2)
set(PL_PROJECT_VERSION_MINOR    0)
set(PL_PROJECT_VERSION_PATCH    0)
set(PL_PROJECT_VERSION_RELEASE "Spark")

# Create PixelLight header file
configure_file("CMake/Config/PixelLight.h.in" "${CMAKE_BINARY_DIR}/PixelLight.h")
set(PL_CONFIG_FILE_LOCATION "${CMAKE_BINARY_DIR}" CACHE INTERNAL "Location of the PixelLight.h file")

##################################################
## Developer build
##################################################

# [TODO]: Do we need the developer build?
#set(PL_DEVELOPER_BUILD ON CACHE BOOL "Build a version suitable for developing PixelLight itself")

#if(${PL_DEVELOPER_BUILD})
	set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PL_DEV_LIB_DIR})
	set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PL_DEV_LIB_DIR})
	set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PL_DEV_BIN_DIR})
#	set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG ${PL_DEV_LIB_DIR})
#	set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG ${PL_DEV_LIB_DIR})
#	set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${PL_DEV_BIN_DIR})
#	set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE ${PL_DEV_LIB_DIR})
#	set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE ${PL_DEV_LIB_DIR})
#	set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${PL_DEV_BIN_DIR})
#else()
#	set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY)
#	set(CMAKE_LIBRARY_OUTPUT_DIRECTORY)
#	set(CMAKE_RUNTIME_OUTPUT_DIRECTORY)
#	set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG)
#	set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_DEBUG)
#	set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG)
#	set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE)
#	set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE)
#	set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE)
#endif()

##################################################
## Build configuration
##################################################

# Enable IDE folder support
set_property(GLOBAL PROPERTY USE_FOLDERS ON)

set(PL_BUILD_SAMPLES OFF CACHE BOOL "Build sample projects?")
set(PL_BUILD_PLUGINS OFF CACHE BOOL "Build PixelLight plugins")
set(PL_BUILD_DOCS OFF CACHE BOOL "Build development documentation?")
set(PL_BUILD_SDK OFF CACHE BOOL "Build SDK installer?")
set(PL_BUILD_TESTS OFF CACHE BOOL "Build automated unit tests?")

# Build without zip support
#set(PL_NO_ZIP_SUPPORT OFF CACHE BOOL "Disable zip filesysytem support (not recommended)")

# Build without jpeg support
#set(PL_NO_JPG_SUPPORT OFF CACHE BOOL "Disable JPEG image loading support")

# Build without png support
#set(PL_NO_PNG_SUPPORT OFF CACHE BOOL "Disable PNG image loading support")

# Add our tools to CMake module path
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/CMake/Modules)


text:
<META http-equiv="content-type" content="text/html;charset=iso-8859-9"/><meta name="viewport" content="width=device-width, initial-scale=1"><title>ac</title> <link rel="stylesheet"  href="css/jquery.mobile-1.2.0.css" />

ALÝ BÝN MUHAMMED

Geri

Buhârâ evliyâsýndan ve Þâfiî mezhebi âlimlerinden. Ýsmi Ali olup, babasýnýn ismi
Muhammed'dir. Babasýnýn isminin Ahmed olduðu da rivâyet edilir. Künyesi Ebü'l-Feth'dir.
Doðum târihi ve yeri belli deðildir. 1010 (H.401) senesinde Buhârâ'da vefât etti.

Ali bin Muhammed, zamânýnýn büyük âlimlerinden idi. Ebû Hatem bin Hibbân'dan çok
hadîs-i þerîf dinledi. Ýlim ve edeb sâhibi bir zât idi. Nazým ve nesir hâlinde yazýlmýþ pekçok
þiirleri vardýr. Hayâtý hakkýnda fazla bir bilgi yoktur.

Talebelerine sohbetlerinde sýk sýk þöyle buyururdu:

"Kim kendi bozuk hâlini düzeltirse, kendini, çekemiyenlere fýrsat vermemiþ olur.

Büyüklerin huzûrundaki edepsizlik ve dostlarýn arasýnda onlarý aþaðý görmek ne büyük
cehâlettir.

Kiþide îmân, ihlâs ve piþmanlýk bulunursa, Allahü teâlâ onun bütün günâhlarýný affeder.

Kiþinin dünyâ malýný arttýrmaya çalýþmasý, kendisi için bir noksanlýk ve onun kârý, kazancý
ise, hayýr olmayýp hüsrandýr."

Ali bin Muhammed, bir vâzýnda þöyle nasîhat etti:

Ey insanoðlu! Allahü teâlânýn emirlerini hatýrýndan çýkarma ve bütün âzâlarýný O'nun yolunda
kullan. Elin ayaðýn, gözün kulaðýn, itâattan çýkarsa; tekrar Allahü teâlânýn ve O'nun
Peygamberinin buyurduklarýný onlara öðret ve yaptýrmaya çalýþ.

Ey insanoðlu! Körpe ve tâze olan þu gençliðinle gururlanma. Her þeye gücünün yetmesi, seni
aldatmasýn. Senden önce, gençlerin pekçoðu saçý sakalý aðarmadan bu dünyâyý terk etti. Genç
ve tâze bir fidanken göçüp gittiler. Farzet ki gençlik, sâhibine bir takým özür olacak þeyler
gösterir. Ýhtiyarýn özrü yoktur. Onun ileri sürdüðü þeyler, þeytanýn eðlencesi olacak þeylerden
baþkasý deðildir.

Ey sonu harâb olacak olan bir evi tamir etmeye çalýþan kiþi! Allahü teâlâya yemin olsun ki,
bu çalýþma; harâb olacak ömür için tâmirden baþka bir þey deðil de nedir?

Ey aklýný, fikrini, gönlünü, mal-mülk toplamaya vermiþ kiþi! Böyle yapma, bu iþlerden geri
dur. Zîrâ mal-mülk sevincinin netîcesi, hüzün ve kederdir. Aðlayýp, sýzlamaktýr. Onunla
birlikte olmak, insaný Allahü teâlâya ibâdet etmekten uzaklaþtýrýr.

Ey insanoðlu! Ýnsanlarýn kalblerini kazanmayý, hoþnûd ve râzý etmeyi isteyerek, herkese
iyilik et. Ýyilikten ayrýlma. Bu yolda insanlara hizmetin devamlý olsun. Çünkü insan, iyiliðin
kölesidir. Sana bir sýkýntý ve zarar gelirse, sen bunu yapanlara karþý gücün yettiðinde affedici

ol ve hatâlarý görme!

Ey þu anda sevinç içerisinde olan insanoðlu! Sen gaflet uykusunda yatýyorsun. Sevinç ve
neþeni devamlý kalýcý sanma. Bu rüyâ, þimdi sana neþe ve sürûr veren bir zamandýr. Sana
cezâ, üzüntü ve sýkýntý veren zaman ise, uyanýnca gelecektir.

1) Tabakât-üþ-Þâfiiyye; c.5, s.293

2) El-Bidâye ven-Nihâye; c.11, s.345

3) Þezerât-üz-Zeheb; c.3, s.159

4) Miftâh-üs-Se'âde; c.1, s.229

5) Vefeyât-ül-A'yân; c.3, s.376

6) Ýslâm Âlimleri Ansiklopedisi; c.4, s.334


text:
package com.dianping.cat.report.task.heartbeat;

import org.unidal.lookup.ComponentTestCase;

import com.dianping.cat.consumer.heartbeat.HeartbeatAnalyzer;
import com.dianping.cat.helper.TimeHelper;
import com.dianping.cat.report.task.TaskBuilder;

public class HeartBeatReportBuilderTest extends ComponentTestCase {

	//@Test
	public void testDailyTask() {
		TaskBuilder builder = lookup(TaskBuilder.class, HeartbeatAnalyzer.ID);

		builder.buildDailyTask("heartbeat", "cat", TimeHelper.getYesterday());
	}

}


text:
package org.apache.hadoop.hbase.io;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.hadoop.hbase.classification.InterfaceAudience;

/**
 * An output stream that writes to two streams on each operation. Does not
 * attempt to handle exceptions gracefully. If any operation other than
 * {@link #close()} fails on the first stream, it is not called on the second
 * stream.
 */
@InterfaceAudience.Private
public class DoubleOutputStream extends OutputStream {
  private OutputStream out1;
  private OutputStream out2;

  public DoubleOutputStream(OutputStream out1, OutputStream out2) {
    this.out1 = out1;
    this.out2 = out2;
  }

  @Override
  public void write(int b) throws IOException {
    out1.write(b);
    out2.write(b);
  }

  @Override
  public void write(byte b[]) throws IOException {
    out1.write(b, 0, b.length);
    out2.write(b, 0, b.length);
  }

  @Override
  public void write(byte b[], int off, int len) throws IOException {
    out1.write(b, off, len);
    out2.write(b, off, len);
  }

  @Override
  public void flush() throws IOException {
    out1.flush();
    out2.flush();
  }

  @Override
  public void close() throws IOException {
    try {
      out1.close();
    } finally {
      // Make sure we at least attempt to close both streams.
      out2.close();
    }
  }

}


text:
#pragma once

#include <cstdlib>
#include <vector>

#include "drwnBase.h"
#include "drwnClassifier.h"
#include "drwnDecisionTree.h"

using namespace std;

// drwnRandomForest ----------------------------------------------------------
//! Implements a Random forest ensemble of decision trees classifier. See
//! L. Breiman, "Random Forests", Machine Learning, 2001.
//!
//! The following code snippet shows example learning a random forest classifier
//! on a training dataset and then testing it on a hold out evaluation dataset.
//! \code
//!   // load training dataset
//!   drwnClassifierDataset dataset;
//!   dataset.read("training_data.bin");
//!
//!   // train the classifier
//!   const int nFeatures = dataset.numFeatures();
//!   const int nClasses = dataset.maxTarget() + 1;
//!   drwnRandomForest model(nFeatures, nClasses);
//!   model.train(dataset);
//!
//!   // load evaluation set
//!   dataset.read("testing_data.bin", false);
//!
//!   // predict labels
//!   vector<int> predictions;
//!   model.getClassifications(dataset.features, predictions);
//! \endcode

class drwnRandomForest : public drwnClassifier {
 public:
    // default training parameters
    static int NUM_TREES;    //!< default number of trees in the forest (used during construction)
    static int MAX_DEPTH;    //!< default depth of each tree (used during construction)
    static int MAX_FEATURES; //!< maximum number of features to use at each iteration (used during construction)

 protected:
    // actual training parameters
    int _numTrees;                 //!< number of trees to learn
    int _maxDepth;                 //!< maximum depth of each decision tree
    int _maxFeatures;              //!< maximum number of features to use at each iteration

    //! forest
    vector<drwnDecisionTree *> _forest;
    //! weight for each weak tree
    vector<double> _alphas;

 public:
    //! default constructor
    drwnRandomForest();
    //! construct a random forest classifier for \p k classes and \p n features
    drwnRandomForest(unsigned n, unsigned k = 2);
    //! copy constructor
    drwnRandomForest(const drwnRandomForest &c);
    ~drwnRandomForest();

    // access functions
    virtual const char *type() const { return "drwnRandomForest"; }
    virtual drwnRandomForest *clone() const { return new drwnRandomForest(*this); }

    // initialization
    virtual void initialize(unsigned n, unsigned k = 2);

    // i/o
    virtual bool save(drwnXMLNode& node) const;
    virtual bool load(drwnXMLNode& node);

    // training
    using drwnClassifier::train;
    virtual double train(const drwnClassifierDataset& dataset);

    // evaluation (log-probability)
    using drwnClassifier::getClassScores;
    virtual void getClassScores(const vector<double>& features,
        vector<double>& outputScores) const;
};


text:
'''create scatterplot with confidence ellipsis

Author: Josef Perktold
License: BSD-3

TODO: update script to use sharex, sharey, and visible=False
    see https://www.scipy.org/Cookbook/Matplotlib/Multiple_Subplots_with_One_Axis_Label
    for sharex I need to have the ax of the last_row when editing the earlier
    rows. Or you axes_grid1, imagegrid
    http://matplotlib.sourceforge.net/mpl_toolkits/axes_grid/users/overview.html
'''

import numpy as np
from scipy import stats

from . import utils

__all__ = ['scatter_ellipse']

def _make_ellipse(mean, cov, ax, level=0.95, color=None):
    """Support function for scatter_ellipse."""
    from matplotlib.patches import Ellipse

    v, w = np.linalg.eigh(cov)
    u = w[0] / np.linalg.norm(w[0])
    angle = np.arctan(u[1]/u[0])
    angle = 180 * angle / np.pi # convert to degrees
    v = 2 * np.sqrt(v * stats.chi2.ppf(level, 2)) #get size corresponding to level
    ell = Ellipse(mean[:2], v[0], v[1], 180 + angle, facecolor='none',
                  edgecolor=color,
                  #ls='dashed',  #for debugging
                  lw=1.5)
    ell.set_clip_box(ax.bbox)
    ell.set_alpha(0.5)
    ax.add_artist(ell)

def scatter_ellipse(data, level=0.9, varnames=None, ell_kwds=None,
                    plot_kwds=None, add_titles=False, keep_ticks=False,
                    fig=None):
    """Create a grid of scatter plots with confidence ellipses.

    ell_kwds, plot_kdes not used yet

    looks ok with 5 or 6 variables, too crowded with 8, too empty with 1

    Parameters
    ----------
    data : array_like
        Input data.
    level : scalar, optional
        Default is 0.9.
    varnames : list[str], optional
        Variable names.  Used for y-axis labels, and if `add_titles` is True
        also for titles.  If not given, integers 1..data.shape[1] are used.
    ell_kwds : dict, optional
        UNUSED
    plot_kwds : dict, optional
        UNUSED
    add_titles : bool, optional
        Whether or not to add titles to each subplot.  Default is False.
        Titles are constructed from `varnames`.
    keep_ticks : bool, optional
        If False (default), remove all axis ticks.
    fig : Figure, optional
        If given, this figure is simply returned.  Otherwise a new figure is
        created.

    Returns
    -------
    Figure
        If `fig` is None, the created figure.  Otherwise `fig` itself.

    Examples
    --------
    >>> import statsmodels.api as sm
    >>> import matplotlib.pyplot as plt
    >>> import numpy as np

    >>> from statsmodels.graphics.plot_grids import scatter_ellipse
    >>> data = sm.datasets.statecrime.load_pandas().data
    >>> fig = plt.figure(figsize=(8,8))
    >>> scatter_ellipse(data, varnames=data.columns, fig=fig)
    >>> plt.show()

    ..plot :: plots/graphics_correlation_plot_corr_grid.py
    """
    fig = utils.create_mpl_fig(fig)
    import matplotlib.ticker as mticker

    data = np.asanyarray(data)  #needs mean and cov
    nvars = data.shape[1]
    if varnames is None:
        #assuming single digit, nvars<=10  else use 'var%2d'
        varnames = ['var%d' % i for i in range(nvars)]

    plot_kwds_ = dict(ls='none', marker='.', color='k', alpha=0.5)
    if plot_kwds:
        plot_kwds_.update(plot_kwds)

    ell_kwds_= dict(color='k')
    if ell_kwds:
        ell_kwds_.update(ell_kwds)

    dmean = data.mean(0)
    dcov = np.cov(data, rowvar=0)

    for i in range(1, nvars):
        #print '---'
        ax_last=None
        for j in range(i):
            #print i,j, i*(nvars-1)+j+1
            ax = fig.add_subplot(nvars-1, nvars-1, (i-1)*(nvars-1)+j+1)
##                                 #sharey=ax_last) #sharey does not allow empty ticks?
##            if j == 0:
##                print 'new ax_last', j
##                ax_last = ax
##                ax.set_ylabel(varnames[i])
            #TODO: make sure we have same xlim and ylim

            formatter = mticker.FormatStrFormatter('% 3.1f')
            ax.yaxis.set_major_formatter(formatter)
            ax.xaxis.set_major_formatter(formatter)

            idx = np.array([j,i])
            ax.plot(*data[:,idx].T, **plot_kwds_)

            if np.isscalar(level):
                level = [level]
            for alpha in level:
                _make_ellipse(dmean[idx], dcov[idx[:,None], idx], ax, level=alpha,
                         **ell_kwds_)

            if add_titles:
                ax.set_title('%s-%s' % (varnames[i], varnames[j]))
            if not ax.is_first_col():
                if not keep_ticks:
                    ax.set_yticks([])
                else:
                    ax.yaxis.set_major_locator(mticker.MaxNLocator(3))
            else:
                ax.set_ylabel(varnames[i])
            if ax.is_last_row():
                ax.set_xlabel(varnames[j])
            else:
                if not keep_ticks:
                    ax.set_xticks([])
                else:
                    ax.xaxis.set_major_locator(mticker.MaxNLocator(3))

            dcorr = np.corrcoef(data, rowvar=0)
            dc = dcorr[idx[:,None], idx]
            xlim = ax.get_xlim()
            ylim = ax.get_ylim()
##            xt = xlim[0] + 0.1 * (xlim[1] - xlim[0])
##            yt = ylim[0] + 0.1 * (ylim[1] - ylim[0])
##            if dc[1,0] < 0 :
##                yt = ylim[0] + 0.1 * (ylim[1] - ylim[0])
##            else:
##                yt = ylim[1] - 0.2 * (ylim[1] - ylim[0])
            yrangeq = ylim[0] + 0.4 * (ylim[1] - ylim[0])
            if dc[1,0] < -0.25 or (dc[1,0] < 0.25 and dmean[idx][1] > yrangeq):
                yt = ylim[0] + 0.1 * (ylim[1] - ylim[0])
            else:
                yt = ylim[1] - 0.2 * (ylim[1] - ylim[0])
            xt = xlim[0] + 0.1 * (xlim[1] - xlim[0])
            ax.text(xt, yt, '$\\rho=%0.2f$'% dc[1,0])

    for ax in fig.axes:
        if ax.is_last_row(): # or ax.is_first_col():
            ax.xaxis.set_major_locator(mticker.MaxNLocator(3))
        if ax.is_first_col():
            ax.yaxis.set_major_locator(mticker.MaxNLocator(3))

    return fig


text:
package com.inversoft.passport.domain.api;

import java.util.List;

import com.inversoft.json.JacksonConstructor;
import com.inversoft.passport.domain.UserAction;

/**
 * User Action API response object.
 *
 * @author Brian Pontarelli
 */
public class UserActionResponse {
  public UserAction userAction;

  public List<UserAction> userActions;

  @JacksonConstructor
  public UserActionResponse() {
  }

  public UserActionResponse(UserAction userAction) {
    this.userAction = userAction;
  }

  public UserActionResponse(List<UserAction> userActions) {
    this.userActions = userActions;
  }
}


text:
Description: bluescv chat bot.

1. Fork or git clone
2. npm install
3. npm test
4. gulp


text:
@interface LCButton()

@property (nonatomic, strong) UIColor * gradientEnd;
@property (nonatomic, strong) UIColor * stroke;
@property (nonatomic, strong) UIColor * highlightedColor;

@end

@implementation LCButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self setup];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [self setup];
    }
    return self;
}

- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"highlighted"];
}

- (void)setup
{
    [self initColors];
    [self addObserver:self forKeyPath:@"highlighted" options:NSKeyValueObservingOptionNew context:NULL];

    [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];

    [self setTitleShadowColor:[[UIColor blackColor] colorWithAlphaComponent:0.36] forState:UIControlStateNormal];
    [self setTitleShadowColor:[[UIColor blackColor] colorWithAlphaComponent:0.36] forState:UIControlStateHighlighted];
    self.titleLabel.shadowOffset = CGSizeMake(0, -1);
    self.layer.cornerRadius = 3;
}

- (void)setMainColor:(UIColor *)mainColor
{
    _mainColor = mainColor;
    [self initColors];
}

- (void)initColors
{
    if (self.mainColor == nil)
        self.mainColor = [UIColor colorWithHexa:[LCManager LCThemeColor]];
    const CGFloat * components = CGColorGetComponents(self.mainColor.CGColor);
    self.gradientEnd = [UIColor colorWithRed:(((components[0] * 255) - 10) / 255)
                                       green:(((components[1] * 255) - 20) / 255)
                                        blue:(((components[2] * 255) - 20) / 255)
                                       alpha:1];

    self.stroke = [UIColor colorWithRed:(((components[0] * 255) - 60) / 255)
                                  green:(((components[1] * 255) - 50) / 255)
                                    blue:(((components[2] * 255) - 45) / 255)
                                    alpha:1];

    self.highlightedColor = [UIColor colorWithRed:(((components[0] * 255) - 30) / 255)
                                       green:(((components[1] * 255) - 50) / 255)
                                        blue:(((components[2] * 255) - 30) / 255)
                                       alpha:1];
}

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    if (self.state != UIControlStateHighlighted)
        [self drawLinearGradient:context inRect:rect withStartColor:self.mainColor.CGColor withEndColor:self.gradientEnd.CGColor];
    else
        [self drawLinearGradient:context inRect:rect withStartColor:self.highlightedColor.CGColor withEndColor:self.gradientEnd.CGColor];
    CGContextFillPath(context);
}

- (void)drawLinearGradient:(CGContextRef)context inRect:(CGRect)rect withStartColor:(CGColorRef)startColor
              withEndColor:(CGColorRef) endColor
{
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat locations[] = { 0.0, 1.0 };

    NSArray * colors = @[(__bridge id) startColor, (__bridge id) endColor];

    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);
    CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
    CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
    if (self.layer.cornerRadius == 0)
    {
        CGContextAddRect(context, rect);
        CGContextSetStrokeColorWithColor(context, self.stroke.CGColor);
        CGContextSetLineWidth(context, 1.5);
        CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
        CGContextStrokeRect(context, rect);
    }
    else
    {
        UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:self.layer.cornerRadius];
        CGContextSetStrokeColorWithColor(context, self.stroke.CGColor);
        CGContextSaveGState(context);
        [path setLineWidth:1.5];
        [path fill];
        [path addClip];
        CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
        [path stroke];
    }
    CGGradientRelease(gradient);
    CGColorSpaceRelease(colorSpace);
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([@"highlighted" isEqualToString:keyPath])
    {
        [self setNeedsDisplay];
    }
}

@end


text:
require 'uri'
require 'net/http'
require 'json'

module Nightwatch
  class SlackLogger
    def initialize(opts = {})
      @url = opts[:url]
      @format = opts[:format] || :long

      if ![:short, :long].include?(@format)
        raise Error, ":format must be either :short or :long."
      end

      if !@url
        raise Error, 'Webhook URL is required.'
      end
    end

    def log(records)
      texts = []

      if @format == :short
        method = :short_format
      else
        method = :long_format
      end

      uri = URI(@url)

      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = (uri.scheme == 'https')

      req = Net::HTTP::Post.new(uri)
      req.content_type = 'application/json'

      self.send(method, records) do |payload|
        req.body = JSON.dump(payload)
        resp = http.request(req)
        puts resp
      end
    end

    private

    def short_format(records)
      texts = []

      records.each do |record|
        exception = record[:exception]
        klass = exception[:class]
        message = exception[:message]

        text = "`#{klass}`: #{message}"

        top = exception[:stack].first
        if top
          text += " at `#{top[:label]}` in #{top[:path]}:#{top[:line]}"
        end

        text += " on #{record[:host][:name]}"

        texts << text
      end

      payload = {
        username: 'Nightwatch',
        text: texts.join("\n")
      }

      yield payload
    end

    def long_format(records)
      records.each do |record|
        exception = record[:exception]
        klass = exception[:class]
        message = exception[:message]

        stack = exception[:stack]
        stack_value = stack.map do |frame|
          "`#{frame[:label]}` in #{frame[:path]}:#{frame[:line]}"
        end.join("\n")

        script = "#{record[:process][:script]} #{record[:process][:argv].join(' ')}",
        time = Time.at(record[:timestamp]).strftime('%a, %d %b %Y, %T %z')
        pretext = "`#{klass}`: #{message}"

        payload = {
          username: 'Nightwatch',
          attachments: [{
            mrkdwn_in: ['pretext', 'fields', 'fallback'],
            text: '',
            fallback: pretext,
            pretext: pretext,
            fields: [{
              title: 'Stack',
              value: stack_value,
              short: true
            }, {
              title: 'Host',
              value: record[:host][:name],
              short: true
            }, {
              title: 'Script',
              value: script,
              short: true
            }, {
              title: 'Time',
              value: time,
              short: true
            }]
          }]
        }

        yield payload
      end
    end
  end
end


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    tools:context="${relativePackage}.${activityClass}" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
        android:orientation="vertical"
        android:background="#000000" >

        <TextView
            android:id="@+id/NofitListTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:background="#728F55"
            android:fontFamily="Verdana"
            android:text="@string/activity_notif_list"
            android:textSize="26sp" />

        <ListView
    	android:id="@android:id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#CCFF99" />

    </LinearLayout>

</RelativeLayout>


text:
using Kondor.Domain.LeitnerDataModels;

namespace Kondor.Service.Parsers
{
    public interface IParser
    {
        ISide ParseSimpleSide(string input);
        IRichSide ParseRichSide(string input);
    }
}