text:
var Child_process = require("child_process");
var Fs = require("fs");
var Events = require("events")
var Util = require("./util");
var Ssh = require("./ssh");
var Socket = require("net").Socket;
var Tty = require("tty");

/**
 * @class Sftp object
 * @extends events.EventEmitter
 *
 * @property {Number} state        state the Sftp instance is in
 * @property {String} activeBuffer buffer that contains the output of the active Sftp command
 * @property {Object} callbacks    hashmap that contains callbacks for all Sftp commands
 * @property {Array}  queue        simple FIFO queue for commands to hold until (re)connection
 * @property {Object} cmdOptions   list of options per Sftp command, fetched from the output of the help command
 *
 * @param {Object}   options                    that contain all the info required
 *                                              to setup a connection
 *                                              to a remote server. Structure:
 * @param {String}   options.username           Username on remote host.
 * @param {String}   [options.password]         Password on remote host, not required if private key is provided.
 * @param {String}   [options.privateKey]       Private key for username, not required if password is provided.
 * @param {String}   [options.host="localhost"] Hostname or IP to connect to. Default: 'localhost'
 * @param {Number}   [options.port=22]          SSH Port number. Default: 22
 * @param {Number}   [options.timeout=10000]    Inactivity timeout in milliseconds. Default: 10000ms
 * @param {Boolean}  [options.autoconnect=true] Connect on instantiation. Default: true
 * @param {String}   [options.exec]             Command to be executed right after a connection is established.
 * @param {Function} [cbconnect]                callback to invoke right after a connection is established.
 * @type  {Sftp}
 */
function Sftp(options, cbconnect) {
    Events.EventEmitter.call(this);

    this.options = Util.extend({
        host: "localhost",
        port: 22,
        timeout: 10000,
        autoconnect: true
    }, options || {});

    // initialize state variables
    this.state           = 0;
    this.activeCmdBuffer = "";
    this.callbacks       = {};
    this.queue           = [];
    this.cmdOptions      = {
        ls: []
    };

    var o     = this.options,
        _self = this;
    // plaintext private key needs to be written to file first
    if (o.privateKey && o.privateKey.indexOf("BEGIN RSA PRIVATE KEY") >= 0) {
        var _self = this;
        Ssh.writeKeyFile(o.privateKey, function(err, file) {
            if (err)
                return cbconnect(err);
            o.privateKey = file;
            _self.$privateKeyTemp = file;
            afterInit();
        });
    }
    else
        afterInit();

    function afterInit() {
        _self.state = Sftp.STATE_DISCONNECTED;
        _self.emit("ready");
        cbconnect = cbconnect || o.callback || K;

        if (o.exec) {
            var args = o.exec.split(" "),
                func = parts.shift(),
                cb   = o.callback || cbconnect;
            if (!_self[func])
                return cb("Unsupported method '" + func + "' specified in the exec option");
            _self.connect(cbconnect);
            args.push(cb);
            _self[func].apply(_self, args);
        }
        else if (_self.queue.length) {
            _self.connect(cbconnect);
            _self.exec.apply(_self, _self.queue.shift());
        }
        else if (o.autoconnect) {
            _self.connect(cbconnect);
        }
    }
}

/**
 * @constant
 */
Sftp.STATE_CONNECTED    = 0x0001;
/**
 * @constant
 */
Sftp.STATE_CONNECTING   = 0x0002;
/**
 * @constant
 */
Sftp.STATE_DISCONNECTED = 0x0004;

/**
 * @name Sftp.connect
 * @event
 */

/**
 * @name Sftp.disconnect
 * @event
 */

/**
 * @name Sftp.ready
 * @event
 */

/**
 * @name Sftp.data
 * @event
 * @param {String} e chunk of data that comes in while executing an Sftp command
 */

require("util").inherits(Sftp, Events.EventEmitter);

/** @lends Sftp */
(function() {
    this.activeCmd       = null;
    this.activeCmdBuffer = null;
    this.callbacks       = null;
    this.queue           = null;
    this.cmdOptions      = null;

    var K = function() {};

    /**
     * Setup an Sftp connection to a remote host
     *
     * @param {Function} cbconnect callback to invoke right after a connection is established.
     * @type  {void}
     */
    this.connect = function(cbconnect) {
        if (!(this.state & Sftp.STATE_DISCONNECTED)) {
            if (cbconnect) {
                cbconnect(this.state & Sftp.STATE_CONNECTED
                    ? null
                    : this.state & Sftp.STATE_CONNECTING
                        ? "SFTP Error: already connecting to a host, please be patient"
                        : "SFTP Error: invalid state."
                );
            }
            return;
        }

        this.state = Sftp.STATE_CONNECTING;

        var o     = this.options,
            args  = ["-o", "Port=" + o.port],
            _self = this;
        if (o.privateKey)
            args = args.concat(Ssh.buildArgs(o.privateKey));
        args.push(
            // first we push the correct hostname (appended with the path, if supplied)
            (o.username ? o.username + "@" : "") + o.host + (o.home ? ":" + o.home : "")
        );
        // push the connection string as argument:
        console.log("launching: sftp " + args.join(" "));
        var ps = Tty.open("sftp", args);
        this.socket = ps[0];
        this.child = ps[1];

        this.socket.on("data", function(data) {
            if (_self.state & Sftp.STATE_DISCONNECTED)
                _self.socket.destroy();
            parseReply.call(_self, data.toString(), 1);
        });

        this.child.on("exit", function(code) {
            _self.emit("disconnect", code);
            _self.socket.flush();
            _self.state = Sftp.STATE_DISCONNECTED;
            if (_self.$privateKeyTemp)
                Fs.unlink(_self.$privateKeyTemp);
        });

        this.callbacks["connect"] = function() {
            _self.state = Sftp.STATE_CONNECTED;

            send.call(_self, "help", "help", function(lines) {
                registerFeatures.call(_self, lines);
                _self.emit("connect");
                cbconnect && cbconnect();

                if (_self.queue.length)
                    _self.exec.apply(_self, _self.queue.shift());
            }, K);
        };
    };

    /**
     * Parse the output of a 'help' or '?' command and fetch the command options
     * that are supported by the remote server.
     * The supported options are cached and used by functions like ls()
     *
     * @param {Array} lines Array of lines that contain strings of terminal output
     * @type  {void}
     * @private
     */
    function registerFeatures(lines) {
        lines = lines.slice(lines.indexOf("Available commands:") + 1);
        var _self = this;
        lines.forEach(function(line) {
            // parse the help output for a command
            var m = line.match(/^([^\t]*)[\s]{2,}([^\t]+)$/);
            if (!m || m.length != 3)
                return;
            // remove the unnecessary trailing spaces
            m[1] = m[1].replace(/[\s]+$/, "");
            if (!m[1])
                return;
            // parse the command structure to fetch the command options.
            // the regex is more generic then it must be, because I might use it
            // for something else later...
            m = m[1].match(/([^\s]*)(?:[\s]+)?([^\s]*)?(?:[\s]+)?([^\s]*)?(?:[\s]+)?([^\s]*)?/);
            if (m[2] && m[2].substr(0, 2) == "[-")
                _self.cmdOptions[m[1]] = m[2].substr(2, m[2].length - 3).split("");
        });
    }

    /**
     * Destroy an existing connection to remote host
     *
     * @param {Function} cbdisconn callback to invoke right after the client disconnected
     * @type  {void}
     */
    this.disconnect = function(cbdisconn) {
        if (this.state & Sftp.STATE_DISCONNECTED)
            return cbdisconn();
        var _self = this;
        this.exec("bye", "bye", function(lines) {
            _self.state = Sftp.STATE_DISCONNECTED;
            _self.emit("disconnect");
            _self.child && _self.child.kill && _self.child.kill();
            _self.child = null;
            _self.socket && _self.socket.destroy();
            if (_self.$privateKeyTemp)
                Fs.unlink(_self.$privateKeyTemp, cbdisconn);
            else
                cbdisconn();
        });
    };

    /**
     * Change directory
     *
     * @param {String}   path
     * @param {Function} cbcd
     * @type  {void}
     */
    this.cd = function(path, cbcd) {
        this.exec("cd", "cd " + (path || ""), function(lines) {
            cbcd(isError(lines));
        });
    };

    /**
     * Asynchronous chmod(2). No arguments other than a possible exception are
     * given to the completion callback.
     *
     * @param {String}       path
     * @param {String,octal} mode
     * @param {Function}     callback
     * @type  {void}
     */
    this.chmod = function(path, mode, callback) {
        if (typeof mode == "number")
            mode = mode.toString(8);
        this.exec("chmod", "chmod " + mode + " " + (path || ""), function(lines) {
            callback(isError(lines));
        });
    };

    /**
     * Asynchronous chown(2). No arguments other than a possible exception are
     * given to the completion callback.
     *
     * @param {String}   path
     * @param {String}   own
     * @param {Function} callback
     * @type  {void}
     */
    this.chown = function(path, own, cbchgrp) {
        this.exec("chown", "chown " + own + " " + (path || ""), function(lines) {
            cbchown(isError(lines));
        });
    };

    /**
     * Asynchronous symlink(2). No arguments other than a possible exception are
     * given to the completion callback.
     *
     * @param {String}   linkdata
     * @param {String}   path
     * @param {Function} callback
     * @type  {void}
     */
    this.symlink = function(linkdata, path, callback) {
        this.exec("ln", "ln " + linkdata + " " + path, function(lines) {
            callback(isError(lines));
        });
    };

    /**
     * Asynchronous mkdir(2). No arguments other than a possible exception are
     * given to the completion callback.
     *
     * @param {String}       path
     * @param {String,octal} mode
     * @param {Function}     callback
     * @type  {void}
     */
    this.mkdir = function(path, mode, callback) {
        if (!path)
            return callback("Invalid path.");
        var _self = this;
        this.exec("mkdir", "mkdir " + path, function(lines) {
            var err = isError(lines);
            if (err)
                return callback(err);
            _self.chmod(path, mode || 0755, cbmkdir);
        });
    };

    /**
     * Asynchronous pwd(1). The callback gets two arguments (err, path)
     *
     * @param {Function} callback
     * @type  {void}
     */
    this.pwd = function(callback) {
        this.exec("pwd", "pwd", function(lines) {
            // getting back on stdin:
            // sftp> pwd
            // Remote working directory: /home/cloud9
            callback(null, lines.join("").replace(/[^:]+:[\s]*([^\n\r\t]+)/g, "$1"));
        });
    };

    /**
     * Small and simple routine to transform a collection of output strings into
     * an object of property for each filesystem node.
     *
     * @param {Array} lines
     * @type  {Object}
     * @private
     */
    function parseListing(lines) {
        var res = [];
        lines.forEach(function(line) {
            if (!line || /\/[\.]{1,2}$/.test(line))
                return;
            var m = line.match(/^[\s]*([drwx-]+)[\s]*([\d]+)[\s]*([\d]+)[\s]*([\d]+)[\s]*([\d]+)[\s]*([\w\s\d]*)([\d]{2}\:[\d]{2})[\s]*(.*)$/);
            if (!m)
                return;
            res.push({
                perms: m[1],
                uid: parseInt(m[3]),
                gid: parseInt(m[4]),
                size: parseInt(m[5]),
                date: m[6],
                time: m[7],
                path: m[8]
            });
        });
        return res;
    }

    /**
     * Execute the 'ls' command, which is used for {@link Sftp#readdir}, {@link Sftp#stat},
     * {@link Sftp#fstat} and {@link Sftp#lstat} respectively. For {@link Sftp#stat}
     * and its siblings, using 'ls' is the only way to retrieve a filesystem node's
     * stats.
     * Important: 'ls' output results are cached for 10 seconds, to improve performance.
     *
     * @param {String}   path
     * @param {Function} cbls
     * @type  {void}
     * @private
     */
    function ls(path, cbls) {
        if (!this.$lsCache)
            this.$lsCache = {};
        var cache = this.$lsCache[path],
            now   = Date.now(),
            _self = this;
        if (cache) {
            if (cache.expires >= now)
                return cbls(null, cache.result);
            else
                delete this.$lsCache[path];
        }

        var cmd = "ls -l";
        if (this.cmdOptions["ls"].indexOf("a") > -1)
            cmd += "a";
        if (this.cmdOptions["ls"].indexOf("n") > -1)
            cmd += "n";
        this.exec("ls", cmd + " " + (path || ""), function(lines) {
            var err = isError(lines),
                res = parseListing(lines);
            if (!err) {
                _self.$lsCache[path] = {
                    expires: now + 10000,
                    result: res
                };
            }
            cbls(err, res);
        });
    }

    /**
     * Asynchronous readdir(3). Reads the contents of a directory. The callback
     * gets two arguments (err, files) where files is an array of the names of
     * the files in the directory excluding '.' and '..'.
     *
     * @param {String}   path
     * @param {Function} callback
     * @type  {void}
     */
    this.readdir = function(path, callback) {
        ls.call(this, path, function(err, listing) {
            if (err)
                return callback(err);

            callback(null, listing.map(function(item) {
                var p = item.path;
                return p.substr(p.lastIndexOf("/") + 1);
            }));
        });
    };

    /**
     * Asynchronously reads the entire contents of a file.
     * The callback is passed two arguments (err, data), where data is the contents
     * of the file.
     * If no encoding is specified, then the raw buffer is returned.
     * Example:
     * <pre class="code">
     * sftp.readFile("/etc/passwd", function(err, data) {
     *     if (err)
     *         throw err;
     *     console.log(data);
     * });
     * </pre>
     *
     * @param {String}   filename
     * @param {String}   encoding
     * @param {Function} callback
     * @type  {void}
     */
    this.readFile = function(filename, encoding, callback) {
        var temp = Util.DEFAULT_TMPDIR + "/" + Util.uuid();

        this.exec("readFile", "get " + filename + " " + temp, function(lines) {
            var err = isError(lines);
            if (err)
                return callback(err);
            Fs.readFile(temp, encoding, function(err, data) {
                if (err)
                    return callback(err);
                Fs.unlink(temp, function() {
                    // error? we don't care here...
                    callback(null, data);
                });
            });
        });
    };

    /**
     * Asynchronous rename(2). No arguments other than a possible exception are
     * given to the completion callback.
     *
     * @param {String}   path1
     * @param {String}   path2
     * @param {Function} callback
     * @type  {void}
     */
    this.rename = function(path1, path2, callback) {
        this.exec("rename", "rename " + path1 + " " + (path2 || path1), function(lines) {
            callback(isError(lines));
        });
    };

    /**
     * Asynchronous rmdir(2). No arguments other than a possible exception are
     * given to the completion callback.
     *
     * @param {String}   path
     * @param {Function} callback
     * @type {void}
     */
    this.rmdir = function(path, callback) {
        this.exec("rmdir", "rmdir " + path, function(lines) {
            callback(isError(lines));
        });
    };

    /**
     * Helper function to get an octal representation from terminal output in a
     * human readable form.
     * Example: 'drwxr-xr-x' --> '755' or '-rw-rw-r--' --> '664'
     *
     * @param {String} rwx
     * @type  {String}
     * @private
     */
    function getOct(rwx) {
        var oct = "";
        for (var c, o = 0, i = 0, l = rwx.length; i < l; ++i) {
            c = rwx.charAt(i);
            if (i % 3 === 0) {
                oct += "" + o;
                o = 0;
            }
            c = rwx.charAt(i + 1);
            o += c == "r" ? 4 : c == "w" ? 2 : c == "x" ? 1 : 0;
        }
        return oct;
    }

    /**
     * Sftp specific Stat object
     * @class Objects returned from sftp.stat() and sftp.lstat() are of this type.
     *
     * @property {Number} uid
     * @property {Number} gid
     * @property {String} mtime
     * @property {Number} size
     * @property {String} mode
     */
    var Stat = Sftp.Stat = function(struct) {
        this.uid   = struct.uid;
        this.gid   = struct.gid;
        this.mtime = struct.date + struct.time;
        this.size  = struct.size;
        this.mode  = parseInt(getOct(struct.perms), 10);

        /**
         * @type {Boolean}
         */
        this.isFile = function() {
            return struct.perms.charAt(0) == "-";
        };
        /**
         * @type {Boolean}
         */
        this.isDirectory = function() {
            return struct.perms.charAt(0) == "d";
        };
        /**
         * @type {Boolean}
         */
        this.isBlockDevice = function() {
            return struct.perms.charAt(0) == "b";
        };
        /**
         * @type {Boolean}
         */
        this.isCharacterDevice = function() {
            return struct.perms.charAt(0) == "c";
        };
        /**
         * @type {Boolean}
         */
        this.isSymbolicLink = function() {
            return struct.perms.charAt(0) == "l";
        };
        /**
         * @type {Boolean}
         */
        this.isFIFO = function() {
            return struct.perms.charAt(0) == "p";
        };
        /**
         * @type {Boolean}
         */
        this.isSocket = function() {
            return struct.perms.charAt(0) == "s";
        };
    };

    /**
     * Alias of {@link Sftp#stat}
     * @function
     */
    this.fstat =
    /**
     * Alias of {@link Sftp#stat}
     * @function
     */
    this.lstat = this.stat;
    /**
     * Asynchronous lstat(2). The callback gets two arguments (err, stats) where
     * stats is a sftp.Stats object. lstat() is identical to stat(), except that if
     * path is a symbolic link, then the link itself is stat-ed, not the file that
     * it refers to.
     *
     * @param {String}   path
     * @param {Function} callback
     * @type  {void}
     */
    this.stat  = function(path, callback) {
        var _self = this,
            parts = path.split("/"),
            node  = parts.pop(),
            root  = parts.join("/");
        if (root.charAt(0) != "/") {
            this.pwd(function(err, pwd) {
                if (err)
                    return callback(err);
                pwd = pwd.replace(/[\/]+$/, "");
                root = pwd + "/" + root.replace(/^[\/]+/, "");
                afterPwd();
            });
        }
        else
            afterPwd();

        function afterPwd() {
            ls.call(_self, root, function(err, list) {
                list = list.filter(function(item) {
                    return item.path.split("/").pop() === node;
                });
                if (list.length === 0)
                    return callback("Couldn't stat remote file: No such file or directory");
                return callback(null, new Stat(list[0]));
            });
        }
    };

    /**
     * Asynchronous unlink(2). No arguments other than a possible exception are
     * given to the completion callback.
     *
     * @param {String}   path
     * @param {Function} callback
     * @type  {void}
     */
    this.unlink = function(path, callback) {
        this.exec("unlink", "rm " + path, function(lines) {
            callback(isError(lines));
        });
    };

    /**
     * Asynchronously writes data to a file. data can be a string or a buffer.
     * Example:
     * <pre class="code">
     * sftp.writeFile("message.txt", "Hello Node", function(err) {
     *     if (err)
     *         throw err;
     *     console.log("It's saved!");
     * });
     * </pre>
     *
     * @param {String}        filename
     * @param {String,Buffer} data
     * @param {String}        encoding
     * @param {Function}      callback
     * @type  {void}
     */
    this.writeFile = function(filename, data, encoding, callback) {
        encoding  = encoding || "utf8";
        var temp  = Util.DEFAULT_TMPDIR + "/" + Util.uuid(),
            _self = this;

        Fs.writeFile(temp, data, encoding, function(err) {
            if (err)
                return callback(err);

            _self.exec("writeFile", "put " + temp + " " + filename, function(lines) {
                Fs.unlink(temp, function() {
                    var err = isError(lines);
                    if (err)
                        return callback(err);
                    callback();
                });
            });
        });
    };

    /**
     * Prepare an Sftp command to be sent to the remote host
     *
     * @param {String}   type
     * @param {String}   cmd
     * @param {Function} cbexec
     * @param {Function} cbprogress
     * @type  {void}
     */
    this.exec = function(type, cmd, cbexec, cbprogress) {
        var conn = this.state & Sftp.STATE_CONNECTED;
        if (this.activeCmd || !conn) {
            if (!conn)
                this.connect();
            return this.queue.push([type, cmd, cbprogress, cbexec]);
        }

        send.call(this, type, cmd, cbexec, cbprogress || K);
    };

    /**
     * Send an Sftp command to the remote host, i.e. write it to the CLI stream
     *
     * @param {String}   type
     * @param {String}   cmd
     * @param {Function} cbsend
     * @param {Function} cbprogress
     * @type  {void}
     * @private
     */
    function send(type, cmd, cbsend, cbprogress) {
        this.activeCmd = type;
        this.activeCmdBuffer = "";
        if (cbprogress && cbsend) {
            this.callbacks[type] = cbsend;
            this.callbacks[type + "_progress"] = cbprogress;
        }
        this.socket.write(new Buffer(cmd + "\r\n"));
        this.socket.resume();
    }

    /**
     * Parse the STDOUT of the sftp child process, collect the lines of data for
     * the active command and detect if the active command has finished executing.
     * If the active command is done, respective callbacks are called.
     *
     * @param {String} data
     * @type  {void}
     * @private
     */
    function parseReply(data) {
        // console.log("data: ", data, data.split("\n").length + " parts");
        this.emit("data", data);
        if (!this.activeCmd && !(this.state & Sftp.STATE_CONNECTING))
            return;
        var cbdone, cbprogress;
        if (data.indexOf("sftp>") > -1 || (this.activeCmd == "bye" && data.indexOf("bye") > -1)) {
            if (this.state & Sftp.STATE_CONNECTING && this.callbacks["connect"]) {
                this.callbacks["connect"]();
                delete this.callbacks["connect"];
            }
            // check if a command has finished executing:
            else if (cbdone = this.callbacks[this.activeCmd]) {
                delete this.callbacks[this.activeCmd];
                delete this.callbacks[this.activeCmd + "_progress"];
                this.activeCmd = null;
                cbdone((this.activeCmdBuffer + data).split(/[\n\r]+/).filter(function(line) {
                    return line.indexOf("sftp>") === -1;
                }));
                this.activeCmdBuffer = "";
            }
            if (!this.activeCmd && this.queue.length && this.state & Sftp.STATE_CONNECTED)
                this.exec.apply(this, this.queue.shift());
        }
        else if (cbprogress = this.callbacks[this.activeCmd + "_progress"]) {
            this.activeCmdBuffer += data;
            cbprogress(data);
        }
    }

    /**
     * Detect an error reply from a collection of output lines.
     *
     * @param {Array} lines
     * @private
     */
    function isError(lines) {
        var err = null;
        lines.forEach(function(line) {
            if (line.indexOf("No such file or directory") > -1)
                err = line;
        });
        return err;
    }
}).call(Sftp.prototype);

module.exports = Sftp;


text:
require 'rest-client'
require 'active_support'
require 'active_support/core_ext'
require 'yaml'
require 'active_record'
require 'activerecord-import'

$conf = YAML::load_file("./secret.yml")
ActiveRecord::Base.establish_connection($conf["mysql"])
class YahooTickets < ActiveRecord::Base
end

class MarketCrawler
  def initialize(query)
    @query = query
    @url = "http://auctions.yahooapis.jp/AuctionWebService/V2/search"
    @params = {appid: $conf["yahoo"]["appid"], category: $conf["yahoo"]["category"], query: query}
  end

  def get_all_items
    res = get_items()
    item_list = [res["Result"]["Item"]]
    page = 1
    while res["firstResultPosition"].to_i <= res["totalResultsAvailable"].to_i do
      res = get_items(page += 1)
      item_list << res["Result"]["Item"]
    end
    item_list.flatten.compact
  end

  def get_items(page=1)
    @params[:page] = page
    response = RestClient.get(@url, {params: @params})
    response = Hash.from_xml(response)
    response = response["ResultSet"]
  end

  def clean_title(title)
    title.gsub(@query, "").gsub(/^\s+/,"")
  end

  def upsert(item={})
    YahooTickets.new(
      id: item[:id],
      query: @query,
      title: item[:title],
      current_price: item[:current_price],
      bids: item[:bids],
      bid_or_buy: item[:bid_or_buy],
      created_at: DateTime.now
    )
  end

  def bulk_upsert(items_h=[{}])
    items = items_h.map{|item|
      YahooTickets.new(
        id: item[:id],
        query: item[:query],
        title: item[:title],
        current_price: item[:current_price],
        bids: item[:bids],
        bid_or_buy: item[:bid_or_buy],
        created_at: item[:created_at]
      )
    }
    YahooTickets.import items.to_a, on_duplicate_key_update: [:title, :current_price, :bids, :bid_or_buy], validate: false
  end

  def write_on_file
    #output_name = Time.now.strftime("%Y%m%d%H%M%S")[2..-1]
    #open(output_name, "w") do |f|
     # puts %w(id query title current_price bids bid_or_buy).join("\t")
     # get_all_items.each do |row|
     #   puts [row["AuctionID"], @query, clean_title(row["Title"]), row["CurrentPrice"], row["Bids"], row["BidOrBuy"]].join("\t")
     # end
  end

  def main
    items = get_all_items.map{|row| {id:row["AuctionID"], query: @query, title:clean_title(row["Title"]), current_price:row["CurrentPrice"], bids: row["Bids"], bid_or_buy:row["BidOrBuy"]}}
    bulk_upsert(items)
    p "success!!"
  end
end

mc = MarketCrawler.new($conf["query"])
mc.main

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://drone.io/github.com/gvmtool/gvm/status.png)](https://drone.io/github.com/gvmtool/gvm/latest)
[![Stories in Ready](https://badge.waffle.io/gvmtool/gvm-cli.png?label=ready&title=Ready)](https://waffle.io/gvmtool/gvm-cli)

GVM is a tool for managing parallel Versions of multiple Software Development Kits on any Unix based system. It provides a convenient command line interface for installing, switching, removing and listing Candidates.

See documentation on the [GVM Project Page](http://gvmtool.net).

Please report any bugs and feature request on the [GitHub Issue Tracker](https://github.com/gvmtool/gvm/issues).

Questions and discussions at the [Nabble Forum](http://forum.gvmtool.net).

## Installation

Open your favourite terminal and enter the following:

    $ curl -s api.gvmtool.net | bash

If the environment needs tweaking for GVM to be installed, the installer will prompt you accordingly and ask you to restart.

## Running the Cucumber Features

All GVM's BDD tests are written in Cucumber and can be found under `src/test/cucumber/gvm`.
These can be run with Gradle by running the following command:

    $ ./gradlew

__Please ensure that the JAVA_HOME environment variable set to JDK 1.7 on your system!__

Mac users can add the following line to their `~/.bash_profile` file to set this variable:

	export JAVA_HOME=$(/usr/libexec/java_home -v1.7)

### Using Docker for tests

You can run the tests in the docker container guaranteeing a clean test environment.

    $ docker build -t gvm-cli/testing .
    $ docker run --rm gvm-cli/testing

By running the following command, you don't need to wait for downloading Gradle wrapper and other dependencies. The test reports can be found under the local `build` directory.

    $ docker run --rm -v $PWD:/usr/src/app -v $HOME/.gradle:/root/.gradle gvm-cli/testing

## Running the Server Locally

It is useful to run the server locally for development purposes. Working installations of MongoDB and vert.x are required to get going. GVM can be used to install vert.x, otherwise install it manually as described on the [install page](http://vertx.io/install.html).

	$ gvm install vertx

Next, install MongoDB as described [here](http://www.mongodb.org/downloads). After installing, the database needs to be primed with some data. The following lines may be run with `mongod` running as a separate process.

	$ cd /path/to/gvm
	$ mongo gvm
	> db.candidates.insert({candidate:"groovy", default:"2.0.6"})
	> db.versions.insert({candidate:"groovy", version:"2.0.5", url:"http://dist.groovy.codehaus.org/distributions/groovy-binary-2.0.5.zip"})
	> db.versions.insert({candidate:"groovy", version:"2.0.6", url:"http://dist.groovy.codehaus.org/distributions/groovy-binary-2.0.6.zip"})

This will:

*   create a new `gvm` database
*   the Groovy candidate in the `candidates` collection (defaulting to version 2.0.6)
*   new versions 2.0.5 and 2.0.6 in the `versions` collection.

Add any other candidates that you might require.

Next, prepare the local GVM environment by building and starting the server.

	$ ./gradlew
	$ contrib/run.sh

This will start the server on localhost:8080

### Customizing the Database Location

The database may be configured using environment variables. If non are found, it will assume sensible defaults for a local mongodb installation. The follow environment variables can be specified:

    GVM_DB_ADDRESS="mongo-persistor"
    GVM_DB_HOST="xxx.mongohq.com"
    GVM_DB_PORT="1234"
    GVM_DB_NAME="gvm"
    GVM_DB_PASSWORD="mypassword"
    GVM_DB_USERNAME="myusername"

### Local Installation

To install GVM locally running against your local server, run the following commands:

	$ ./gradlew install
	$ source ~/.gvm/bin/gvm-init.sh


text:
#include "base/polygraph.h"

#include "xstd/h/iostream.h"
#include "xstd/h/sstream.h"
#include <fstream>
#include "xstd/h/iomanip.h"

#include "xstd/gadgets.h"
#include "base/CmdLine.h"
#include "base/opts.h"
#include "base/polyOpts.h"
#include "pgl/PglArraySym.h"
#include "pgl/PglNetAddrSym.h"
#include "pgl/PglNetAddrRange.h"
#include "pgl/PglNetAddrRangeSym.h"
#include "pgl/AddrMapSym.h"
#include "pgl/PglPp.h"
#include "pgl/PglStaticSemx.h"

class MyOpts: public OptGrp {
	public:
		MyOpts():
			theHelpOpt(this,    "help",          "list of options"),
			theVersOpt(this,    "version",       "package version info"),
			theCfgName(this,    "config <filename>",  "PGL configuration"),
			theCfgDirs(this,    "cfg_dirs <dirs>",  "directories for PGL #includes"),
			theZoneName(this,   "zone <str>",    "zone name"),
			theAddrStr(this,    "addresses <str>","IP addresses"),
			theNameStr(this,    "names <str>",   "domain names")
			{}

		virtual bool validate() const;

		//virtual ostream &printAnonym(ostream &os) const;
		//virtual bool parseAnonym(const Array<const char *> &opts);
		//virtual bool canParseAnonym() const { return true; }

	public:
		HelpOpt theHelpOpt;
		VersionOpt theVersOpt;
		StrOpt theCfgName;
		StrArrOpt theCfgDirs;
		StrOpt theZoneName;
		StrOpt theAddrStr;
		StrOpt theNameStr;
};

static String TheZoneName;
static String TheZoneOrRoot;
static String TheNameServerName;
static String TheNameServerIp;
static ArraySym TheAddrs("addr");
static ArraySym TheNames("addr");
static MyOpts TheOpts;

/* MyOpt */

bool MyOpts::validate() const {
	if (theCfgName) {
		if (theZoneName)
			cerr << "--config is mutually exclusive with --zone" << endl;
		else
		if (theAddrStr || theNameStr)
			cerr << "--config is mutually exclusive with --addresses and --names" << endl;
		else
			return true;
	} else {
		if (!theZoneName)
			cerr << "must specify the zone name" << endl;
		else
		if (!theAddrStr || !theNameStr)
			cerr << "must specify addresses and domain names" << endl;
		else
			return true;
	}
	return false;
}

static
void configureLogs(int prec) {
	configureStream(cout, prec);
	configureStream(cerr, prec);
	configureStream(clog, prec);
}

static
void configureViaPgl() {
	TheOpts.theCfgDirs.copy(PglPp::TheDirs);
	PglStaticSemx::Interpret(TheOpts.theCfgName);

	if (PglStaticSemx::TheAddrMapsToUse.count() != 1) {
		cerr << TheOpts.theCfgName << ": must use() exactly one address map" <<
			", but " << PglStaticSemx::TheAddrMapsToUse.count() << " maps " <<
			"were used" << endl << xexit;
	}

	const AddrMapSym *ams = PglStaticSemx::TheAddrMapsToUse.last();

	TheZoneName = ams->zone();
	TheAddrs.append(*ams->addressesSym());
	TheNames.append(*ams->namesSym());

	if (!TheZoneName) {
		cerr << ams->loc() << "address map must specify zone name"
			<< endl << xexit;
	}
	if (!TheAddrs.count()) {
		cerr << ams->loc() << "address map must specify at least one IP addresses"
			<< endl << xexit;
	}
	if (!TheNames.count()) {
		cerr << ams->loc() << "address map must specify at least one domain name"
			<< endl << xexit;
	}
}

static
void configureViaCmdLine() {
	PglNetAddrRange addrs;
	PglNetAddrRange names;

	if (!addrs.parse(TheOpts.theAddrStr))
		cerr << here << "malformed address range: `" <<  TheOpts.theAddrStr << "'" << endl << xexit;

	if (!names.parse(TheOpts.theNameStr))
		cerr << here << "malformed name range: `" <<  TheOpts.theNameStr << "'" << endl << xexit;

	NetAddrRangeSym as;
	as.range(new PglNetAddrRange(addrs));
	TheAddrs.add(as);

	NetAddrRangeSym ns;
	ns.range(new PglNetAddrRange(names));
	TheNames.add(ns);

	TheZoneName = TheOpts.theZoneName;

	if (!TheZoneName)
		cerr << "missing zone name (use --zone option)" << endl << xexit;
}

static
void configure() {
	configureLogs(2);

	if (TheOpts.theCfgName)
		configureViaPgl();
	else
		configureViaCmdLine();

	TheZoneOrRoot = TheZoneName == "." ? "root" : TheZoneName;
	TheNameServerName = "ns." + TheZoneOrRoot + ".";
	// XXX: extract addresses from Robot.dns_resolver if possible
	TheNameServerIp = "172.16.101.100";

	if (TheAddrs.count() > TheNames.count()) {
		cerr << here << "warning: the number of IP addresses (" <<
			TheAddrs.count() << ") exceeds the number of domain names (" <<
			TheNames.count() << "); ignoring extra IPs" << endl;
	}
}

static
void printSoa(ostream &os) {
	const String serialNo = "200412021"; // XXX;

	os << "$TTL 3600" << endl << endl;

	os << "@ IN SOA "
		<< TheNameServerName
		<< " dnsmaster." << TheZoneOrRoot << '.' // person responsible
		<< " (" << endl
		<< "\t " << serialNo << "; Serial" << endl
		<< "\t 10800   ; Refresh" << endl
		<< "\t 1801    ; Retry" << endl
		<< "\t 3600000 ; Expire" << endl
		<< "\t 259200  ; Minimum" << endl
		<< ")" << endl
		<< endl;

	// NS record
	os << "\tIN\tNS\t" << TheNameServerName << endl;
	os << endl;

}

static
String reverseAddr(const NetAddr &addr, int octets) {
	ostringstream os;
	for (int i = 0; i<octets; ++i) {
		if (i)
			os << '.';
		os << addr.roctet(i);
	}
	os << ends;
	return os.str().c_str();
}

static
String reverseAddr(const NetAddr &addr) {
	return reverseAddr(addr, addr.addrN().len());
}

static
String reverseName(const NetAddr &addr) {
	if (!addr.isDynamicName())
		return addr.addrA();

	return "w000000" + addr.addrA();
}

static
String forwardName(const NetAddr &addr) {
	if (TheZoneName == ".")
		return addr.addrA();

	const String &name = addr.addrA();
	if (const char *zone = name.str(TheZoneName)) {
		const int end = zone - name.cstr() - 1; // position of the dot
		if (TheZoneName == zone && end >= 0 && name[end] == '.') {
			return (addr.isDynamicName() ? "*" : "") + addr.addrA()(0, end);
		}
	}

	cerr << here << "warning: " << name << " does not end with zone suffix ("
		<< TheZoneName << "), but probably should" << endl;

	return name;
}

static
String addressType(const InAddress &ina) {
	static const String A = "A";
	static const String AAAA = "AAAA";
	if (AF_INET6 == ina.family())
		return AAAA;
	return A;
}

static
String reverseZone(const InAddress &ina) {
	static const String INADDRARPA = "IN-ADDR.ARPA";
	static const String IP6INT = "IP6.INT";
	if (AF_INET6 == ina.family())
		return IP6INT;
	return INADDRARPA;
}

int main(int argc, char *argv[]) {

	CmdLine cmd;
	cmd.configure(Array<OptGrp*>() << &TheOpts);
	if (!cmd.parse(argc, argv) || !TheOpts.validate())
		return -1;

	configure();

	const String dirFname(TheZoneOrRoot);
	const String revFname(TheZoneOrRoot + ".rev");
	ofstream direct(dirFname.cstr());
	ofstream reverse(revFname.cstr());

	NetAddr commonAddr;
	const String commonName = TheZoneName;

	// SOA records
	printSoa(direct);
	printSoa(reverse);

	// nameserver IP (only goes in to direct zone)
	direct << TheNameServerName << "\tIN\tA\t" << TheNameServerIp << endl;
	direct << endl;

	// A and PTR records
	for (int n = 0, a = 0; n < TheNames.count(); ++n, ++a) {
		if (a == TheAddrs.count())
			a = 0;
		const NetAddrSym &as = (NetAddrSym&)TheAddrs.item(a)->cast("addr");
		const NetAddrSym &ns = (NetAddrSym&)TheNames.item(n)->cast("addr");
		const NetAddr addr(as.val().addrN(), -1); // remove port number
		const NetAddr name(ns.val().addrA(), -1); // remove port number

		if (!n)
			commonAddr = addr;

		const char *pfx = "";
		if (name.addrA().chr('_')) {
			pfx = ";"; // comment
			cerr << here << "error: skipping invalid name '" << name << "' " <<
				"because underscores are not allowed in DNS" << endl;
		}

		direct << pfx
			<< forwardName(name)
			<< "\t\tIN\t"
			<< addressType(as.val().addrN())
			<< "\t"
			<< as.val().addrN().rawImage()
			<< endl;

		reverse << pfx
			<< reverseAddr(addr)
			<< "." << reverseZone(addr.addrN()) << "."
			<< "\t\tIN\tPTR\t" << reverseName(name) << '.'  << endl;
	}

	cout << "# BIND configuration for named.conf is below " << endl
		<< "# zone files are " << revFname << " and " << dirFname << endl
		<< endl;

	cout << "options {" << endl
		<< "\tdirectory \"/etc/namedb\";" << endl
		<< "\trecursion no;" << endl
		<< "};" << endl
		<< endl;

	cout << "zone \""
		// Just put the reverse zone name in the config file, without
		// and leading octets.
		// << reverseAddr(commonAddr, 2) << "."
		<< reverseZone(commonAddr.addrN()) << "\" {" << endl
		<< "\ttype master;" << endl
		<< "\tfile \"" << revFname << "\";" << endl
		<< "};" << endl
		<< endl;

	cout << "zone \"" << commonName << "\" {" << endl
		<< "\ttype master;" << endl
		<< "\tfile \"" << dirFname << "\";" << endl
		<< "};" << endl
		<< endl;

	return 0;
}


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "fuchsia/engine/browser/web_engine_browser_context.h"

#include <lib/fdio/namespace.h>
#include <memory>
#include <utility>

#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/fuchsia/fuchsia_logging.h"
#include "base/path_service.h"
#include "base/threading/thread_restrictions.h"
#include "components/client_hints/browser/in_memory_client_hints_controller_delegate.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "components/keyed_service/core/simple_key_map.h"
#include "components/profile_metrics/browser_profile_type.h"
#include "components/site_isolation/site_isolation_policy.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/client_hints_controller_delegate.h"
#include "content/public/browser/resource_context.h"
#include "fuchsia/engine/browser/web_engine_net_log_observer.h"
#include "fuchsia/engine/switches.h"
#include "media/capabilities/in_memory_video_decode_stats_db_impl.h"
#include "media/mojo/services/video_decode_perf_history.h"
#include "services/network/public/cpp/network_switches.h"

namespace {

std::unique_ptr<WebEngineNetLogObserver> CreateNetLogObserver() {
  std::unique_ptr<WebEngineNetLogObserver> result;

  const base::CommandLine* command_line =
      base::CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(network::switches::kLogNetLog)) {
    base::FilePath log_path =
        command_line->GetSwitchValuePath(network::switches::kLogNetLog);
    result = std::make_unique<WebEngineNetLogObserver>(log_path);
  }

  return result;
}

}  // namespace

class WebEngineBrowserContext::ResourceContext
    : public content::ResourceContext {
 public:
  ResourceContext() = default;

  ResourceContext(const ResourceContext&) = delete;
  ResourceContext& operator=(const ResourceContext&) = delete;

  ~ResourceContext() override = default;
};

// static
std::unique_ptr<WebEngineBrowserContext>
WebEngineBrowserContext::CreatePersistent(
    base::FilePath data_directory,
    network::NetworkQualityTracker* network_quality_tracker) {
  return base::WrapUnique(new WebEngineBrowserContext(std::move(data_directory),
                                                      network_quality_tracker));
}

// static
std::unique_ptr<WebEngineBrowserContext>
WebEngineBrowserContext::CreateIncognito(
    network::NetworkQualityTracker* network_quality_tracker) {
  return base::WrapUnique(
      new WebEngineBrowserContext({}, network_quality_tracker));
}

WebEngineBrowserContext::~WebEngineBrowserContext() {
  SimpleKeyMap::GetInstance()->Dissociate(this);
  NotifyWillBeDestroyed();

  if (resource_context_) {
    content::GetIOThreadTaskRunner({})->DeleteSoon(
        FROM_HERE, std::move(resource_context_));
  }

  BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
      this);

  ShutdownStoragePartitions();
}

std::unique_ptr<content::ZoomLevelDelegate>
WebEngineBrowserContext::CreateZoomLevelDelegate(
    const base::FilePath& partition_path) {
  return nullptr;
}

base::FilePath WebEngineBrowserContext::GetPath() {
  return data_dir_path_;
}

bool WebEngineBrowserContext::IsOffTheRecord() {
  return data_dir_path_.empty();
}

content::ResourceContext* WebEngineBrowserContext::GetResourceContext() {
  return resource_context_.get();
}

content::DownloadManagerDelegate*
WebEngineBrowserContext::GetDownloadManagerDelegate() {
  NOTIMPLEMENTED();
  return nullptr;
}

content::BrowserPluginGuestManager* WebEngineBrowserContext::GetGuestManager() {
  return nullptr;
}

storage::SpecialStoragePolicy*
WebEngineBrowserContext::GetSpecialStoragePolicy() {
  return nullptr;
}

content::PlatformNotificationService*
WebEngineBrowserContext::GetPlatformNotificationService() {
  return nullptr;
}

content::PushMessagingService*
WebEngineBrowserContext::GetPushMessagingService() {
  return nullptr;
}

content::StorageNotificationService*
WebEngineBrowserContext::GetStorageNotificationService() {
  return nullptr;
}

content::SSLHostStateDelegate*
WebEngineBrowserContext::GetSSLHostStateDelegate() {
  return nullptr;
}

content::PermissionControllerDelegate*
WebEngineBrowserContext::GetPermissionControllerDelegate() {
  return &permission_delegate_;
}

content::ClientHintsControllerDelegate*
WebEngineBrowserContext::GetClientHintsControllerDelegate() {
  return &client_hints_delegate_;
}

content::BackgroundFetchDelegate*
WebEngineBrowserContext::GetBackgroundFetchDelegate() {
  return nullptr;
}

content::BackgroundSyncController*
WebEngineBrowserContext::GetBackgroundSyncController() {
  return nullptr;
}

content::BrowsingDataRemoverDelegate*
WebEngineBrowserContext::GetBrowsingDataRemoverDelegate() {
  return nullptr;
}

std::unique_ptr<media::VideoDecodePerfHistory>
WebEngineBrowserContext::CreateVideoDecodePerfHistory() {
  if (!IsOffTheRecord()) {
    // Delegate to the base class for stateful VideoDecodePerfHistory DB
    // creation.
    return BrowserContext::CreateVideoDecodePerfHistory();
  }

  // Return in-memory VideoDecodePerfHistory.
  return std::make_unique<media::VideoDecodePerfHistory>(
      std::make_unique<media::InMemoryVideoDecodeStatsDBImpl>(
          nullptr /* seed_db_provider */),
      media::learning::FeatureProviderFactoryCB());
}

base::RepeatingCallback<bool(const GURL&)> IsJavaScriptAllowedCallback() {
  // WebEngine does not provide a way to disable JavaScript.
  return base::BindRepeating([](const GURL&) { return true; });
}

base::RepeatingCallback<bool(const GURL&)>
AreThirdPartyCookiesBlockedCallback() {
  // WebEngine does not provide a way to block third-party cookies.
  return base::BindRepeating([](const GURL&) { return false; });
}

WebEngineBrowserContext::WebEngineBrowserContext(
    base::FilePath data_directory,
    network::NetworkQualityTracker* network_quality_tracker)
    : data_dir_path_(std::move(data_directory)),
      net_log_observer_(CreateNetLogObserver()),
      simple_factory_key_(GetPath(), IsOffTheRecord()),
      resource_context_(std::make_unique<ResourceContext>()),
      client_hints_delegate_(network_quality_tracker,
                             IsJavaScriptAllowedCallback(),
                             AreThirdPartyCookiesBlockedCallback(),
                             embedder_support::GetUserAgentMetadata()) {
  SimpleKeyMap::GetInstance()->Associate(this, &simple_factory_key_);

  profile_metrics::SetBrowserProfileType(
      this, IsOffTheRecord() ? profile_metrics::BrowserProfileType::kIncognito
                             : profile_metrics::BrowserProfileType::kRegular);

  // TODO(crbug.com/1181156): Should apply any persisted isolated origins here.
  // However, since WebEngine does not persist any, that would currently be a
  // no-op.
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2016 The Chromium Authors. All rights reserved.
     Use of this source code is governed by a BSD-style license that can be
     found in the LICENSE file. -->

<shortcuts xmlns:android="http://schemas.android.com/apk/res/android" >
    <shortcut
        android:shortcutId="new-tab-shortcut"
        android:icon="@drawable/shortcut_newtab"
        android:shortcutShortLabel="@string/menu_new_tab" >
        <intent
            android:action="chromium.shortcut.action.OPEN_NEW_TAB"
            android:targetPackage="{{manifest_package}}"
            android:targetClass="org.chromium.chrome.browser.LauncherShortcutActivity" >
        </intent>
    </shortcut>

    <shortcut
        android:shortcutId="new-incognito-tab-shortcut"
        android:enabled="false"
        android:icon="@drawable/shortcut_incognito"
        android:shortcutShortLabel="@string/accessibility_tabstrip_incognito_identifier"
        android:shortcutLongLabel="@string/menu_new_incognito_tab"
        android:shortcutDisabledMessage="@string/disabled_incognito_launcher_shortcut_message" >
        <intent
            android:action="chromium.shortcut.action.OPEN_NEW_INCOGNITO_TAB"
            android:targetPackage="{{manifest_package}}"
            android:targetClass="org.chromium.chrome.browser.LauncherShortcutActivity" >
        </intent>
    </shortcut>
</shortcuts>


text:
#ifndef QCONTINUINGANIMATIONGROUPJOB_P_H
#define QCONTINUINGANIMATIONGROUPJOB_P_H

#include "private/qanimationgroupjob_p.h"

QT_BEGIN_NAMESPACE

class Q_QML_PRIVATE_EXPORT QContinuingAnimationGroupJob : public QAnimationGroupJob
{
    Q_DISABLE_COPY(QContinuingAnimationGroupJob)
public:
    QContinuingAnimationGroupJob();
    ~QContinuingAnimationGroupJob();

    int duration() const { return -1; }

protected:
    void updateCurrentTime(int currentTime);
    void updateState(QAbstractAnimationJob::State newState, QAbstractAnimationJob::State oldState);
    void updateDirection(QAbstractAnimationJob::Direction direction);
    void uncontrolledAnimationFinished(QAbstractAnimationJob *animation);
    void debugAnimation(QDebug d) const;
};

QT_END_NAMESPACE

#endif // QCONTINUINGANIMATIONGROUPJOB_P_H


text:
package com.ibm.watson.discovery.v1.model;

import com.google.gson.annotations.SerializedName;
import com.ibm.cloud.sdk.core.service.model.GenericModel;
import java.util.List;

/** Training query details. */
public class TrainingQuery extends GenericModel {

  @SerializedName("query_id")
  protected String queryId;

  @SerializedName("natural_language_query")
  protected String naturalLanguageQuery;

  protected String filter;
  protected List<TrainingExample> examples;

  /**
   * Gets the queryId.
   *
   *
The query ID associated with the training query.
   *
   * @return the queryId
   */
  public String getQueryId() {
    return queryId;
  }

  /**
   * Gets the naturalLanguageQuery.
   *
   *
The natural text query for the training query.
   *
   * @return the naturalLanguageQuery
   */
  public String getNaturalLanguageQuery() {
    return naturalLanguageQuery;
  }

  /**
   * Gets the filter.
   *
   *
The filter used on the collection before the **natural_language_query** is applied.
   *
   * @return the filter
   */
  public String getFilter() {
    return filter;
  }

  /**
   * Gets the examples.
   *
   *
Array of training examples.
   *
   * @return the examples
   */
  public List<TrainingExample> getExamples() {
    return examples;
  }
}


text:
namespace camera_windows {
using ::testing::_;
using ::testing::Eq;
using ::testing::NiceMock;
using ::testing::Pointee;
using ::testing::Return;

namespace test {

TEST(Camera, InitCameraCreatesCaptureController) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockCaptureControllerFactory> capture_controller_factory =
      std::make_unique<MockCaptureControllerFactory>();

  EXPECT_CALL(*capture_controller_factory, CreateCaptureController)
      .Times(1)
      .WillOnce([]() {
        std::unique_ptr<NiceMock<MockCaptureController>> capture_controller =
            std::make_unique<NiceMock<MockCaptureController>>();

        EXPECT_CALL(*capture_controller, InitCaptureDevice)
            .Times(1)
            .WillOnce(Return(true));

        return capture_controller;
      });

  EXPECT_TRUE(camera->GetCaptureController() == nullptr);

  // Init camera with mock capture controller factory
  bool result =
      camera->InitCamera(std::move(capture_controller_factory),
                         std::make_unique<MockTextureRegistrar>().get(),
                         std::make_unique<MockBinaryMessenger>().get(), false,
                         ResolutionPreset::kAuto);
  EXPECT_TRUE(result);
  EXPECT_TRUE(camera->GetCaptureController() != nullptr);
}

TEST(Camera, InitCameraReportsFailure) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockCaptureControllerFactory> capture_controller_factory =
      std::make_unique<MockCaptureControllerFactory>();

  EXPECT_CALL(*capture_controller_factory, CreateCaptureController)
      .Times(1)
      .WillOnce([]() {
        std::unique_ptr<NiceMock<MockCaptureController>> capture_controller =
            std::make_unique<NiceMock<MockCaptureController>>();

        EXPECT_CALL(*capture_controller, InitCaptureDevice)
            .Times(1)
            .WillOnce(Return(false));

        return capture_controller;
      });

  EXPECT_TRUE(camera->GetCaptureController() == nullptr);

  // Init camera with mock capture controller factory
  bool result =
      camera->InitCamera(std::move(capture_controller_factory),
                         std::make_unique<MockTextureRegistrar>().get(),
                         std::make_unique<MockBinaryMessenger>().get(), false,
                         ResolutionPreset::kAuto);
  EXPECT_FALSE(result);
  EXPECT_TRUE(camera->GetCaptureController() != nullptr);
}

TEST(Camera, AddPendingResultReturnsErrorForDuplicates) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> first_pending_result =
      std::make_unique<MockMethodResult>();
  std::unique_ptr<MockMethodResult> second_pending_result =
      std::make_unique<MockMethodResult>();

  EXPECT_CALL(*first_pending_result, ErrorInternal).Times(0);
  EXPECT_CALL(*first_pending_result, SuccessInternal);
  EXPECT_CALL(*second_pending_result, ErrorInternal).Times(1);

  camera->AddPendingResult(PendingResultType::kCreateCamera,
                           std::move(first_pending_result));

  // This should fail
  camera->AddPendingResult(PendingResultType::kCreateCamera,
                           std::move(second_pending_result));

  // Mark pending result as succeeded
  camera->OnCreateCaptureEngineSucceeded(0);
}

TEST(Camera, OnCreateCaptureEngineSucceededReturnsCameraId) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const int64_t texture_id = 12345;

  EXPECT_CALL(*result, ErrorInternal).Times(0);
  EXPECT_CALL(
      *result,
      SuccessInternal(Pointee(EncodableValue(EncodableMap(
          {{EncodableValue("cameraId"), EncodableValue(texture_id)}})))));

  camera->AddPendingResult(PendingResultType::kCreateCamera, std::move(result));

  camera->OnCreateCaptureEngineSucceeded(texture_id);
}

TEST(Camera, CreateCaptureEngineReportsError) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const std::string error_text = "error_text";

  EXPECT_CALL(*result, SuccessInternal).Times(0);
  EXPECT_CALL(*result, ErrorInternal(Eq("camera_error"), Eq(error_text), _));

  camera->AddPendingResult(PendingResultType::kCreateCamera, std::move(result));

  camera->OnCreateCaptureEngineFailed(CameraResult::kError, error_text);
}

TEST(Camera, CreateCaptureEngineReportsAccessDenied) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const std::string error_text = "error_text";

  EXPECT_CALL(*result, SuccessInternal).Times(0);
  EXPECT_CALL(*result,
              ErrorInternal(Eq("CameraAccessDenied"), Eq(error_text), _));

  camera->AddPendingResult(PendingResultType::kCreateCamera, std::move(result));

  camera->OnCreateCaptureEngineFailed(CameraResult::kAccessDenied, error_text);
}

TEST(Camera, OnStartPreviewSucceededReturnsFrameSize) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const int32_t width = 123;
  const int32_t height = 456;

  EXPECT_CALL(*result, ErrorInternal).Times(0);
  EXPECT_CALL(
      *result,
      SuccessInternal(Pointee(EncodableValue(EncodableMap({
          {EncodableValue("previewWidth"), EncodableValue((float)width)},
          {EncodableValue("previewHeight"), EncodableValue((float)height)},
      })))));

  camera->AddPendingResult(PendingResultType::kInitialize, std::move(result));

  camera->OnStartPreviewSucceeded(width, height);
}

TEST(Camera, StartPreviewReportsError) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const std::string error_text = "error_text";

  EXPECT_CALL(*result, SuccessInternal).Times(0);
  EXPECT_CALL(*result, ErrorInternal(Eq("camera_error"), Eq(error_text), _));

  camera->AddPendingResult(PendingResultType::kInitialize, std::move(result));

  camera->OnStartPreviewFailed(CameraResult::kError, error_text);
}

TEST(Camera, StartPreviewReportsAccessDenied) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const std::string error_text = "error_text";

  EXPECT_CALL(*result, SuccessInternal).Times(0);
  EXPECT_CALL(*result,
              ErrorInternal(Eq("CameraAccessDenied"), Eq(error_text), _));

  camera->AddPendingResult(PendingResultType::kInitialize, std::move(result));

  camera->OnStartPreviewFailed(CameraResult::kAccessDenied, error_text);
}

TEST(Camera, OnPausePreviewSucceededReturnsSuccess) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  EXPECT_CALL(*result, ErrorInternal).Times(0);
  EXPECT_CALL(*result, SuccessInternal(nullptr));

  camera->AddPendingResult(PendingResultType::kPausePreview, std::move(result));

  camera->OnPausePreviewSucceeded();
}

TEST(Camera, PausePreviewReportsError) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const std::string error_text = "error_text";

  EXPECT_CALL(*result, SuccessInternal).Times(0);
  EXPECT_CALL(*result, ErrorInternal(Eq("camera_error"), Eq(error_text), _));

  camera->AddPendingResult(PendingResultType::kPausePreview, std::move(result));

  camera->OnPausePreviewFailed(CameraResult::kError, error_text);
}

TEST(Camera, PausePreviewReportsAccessDenied) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const std::string error_text = "error_text";

  EXPECT_CALL(*result, SuccessInternal).Times(0);
  EXPECT_CALL(*result,
              ErrorInternal(Eq("CameraAccessDenied"), Eq(error_text), _));

  camera->AddPendingResult(PendingResultType::kPausePreview, std::move(result));

  camera->OnPausePreviewFailed(CameraResult::kAccessDenied, error_text);
}

TEST(Camera, OnResumePreviewSucceededReturnsSuccess) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  EXPECT_CALL(*result, ErrorInternal).Times(0);
  EXPECT_CALL(*result, SuccessInternal(nullptr));

  camera->AddPendingResult(PendingResultType::kResumePreview,
                           std::move(result));

  camera->OnResumePreviewSucceeded();
}

TEST(Camera, ResumePreviewReportsError) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const std::string error_text = "error_text";

  EXPECT_CALL(*result, SuccessInternal).Times(0);
  EXPECT_CALL(*result, ErrorInternal(Eq("camera_error"), Eq(error_text), _));

  camera->AddPendingResult(PendingResultType::kResumePreview,
                           std::move(result));

  camera->OnResumePreviewFailed(CameraResult::kError, error_text);
}

TEST(Camera, OnResumePreviewPermissionFailureReturnsError) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const std::string error_text = "error_text";

  EXPECT_CALL(*result, SuccessInternal).Times(0);
  EXPECT_CALL(*result,
              ErrorInternal(Eq("CameraAccessDenied"), Eq(error_text), _));

  camera->AddPendingResult(PendingResultType::kResumePreview,
                           std::move(result));

  camera->OnResumePreviewFailed(CameraResult::kAccessDenied, error_text);
}

TEST(Camera, OnStartRecordSucceededReturnsSuccess) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  EXPECT_CALL(*result, ErrorInternal).Times(0);
  EXPECT_CALL(*result, SuccessInternal(nullptr));

  camera->AddPendingResult(PendingResultType::kStartRecord, std::move(result));

  camera->OnStartRecordSucceeded();
}

TEST(Camera, StartRecordReportsError) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const std::string error_text = "error_text";

  EXPECT_CALL(*result, SuccessInternal).Times(0);
  EXPECT_CALL(*result, ErrorInternal(Eq("camera_error"), Eq(error_text), _));

  camera->AddPendingResult(PendingResultType::kStartRecord, std::move(result));

  camera->OnStartRecordFailed(CameraResult::kError, error_text);
}

TEST(Camera, StartRecordReportsAccessDenied) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const std::string error_text = "error_text";

  EXPECT_CALL(*result, SuccessInternal).Times(0);
  EXPECT_CALL(*result,
              ErrorInternal(Eq("CameraAccessDenied"), Eq(error_text), _));

  camera->AddPendingResult(PendingResultType::kStartRecord, std::move(result));

  camera->OnStartRecordFailed(CameraResult::kAccessDenied, error_text);
}

TEST(Camera, OnStopRecordSucceededReturnsSuccess) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const std::string file_path = "C:\temp\filename.mp4";

  EXPECT_CALL(*result, ErrorInternal).Times(0);
  EXPECT_CALL(*result, SuccessInternal(Pointee(EncodableValue(file_path))));

  camera->AddPendingResult(PendingResultType::kStopRecord, std::move(result));

  camera->OnStopRecordSucceeded(file_path);
}

TEST(Camera, StopRecordReportsError) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const std::string error_text = "error_text";

  EXPECT_CALL(*result, SuccessInternal).Times(0);
  EXPECT_CALL(*result, ErrorInternal(Eq("camera_error"), Eq(error_text), _));

  camera->AddPendingResult(PendingResultType::kStopRecord, std::move(result));

  camera->OnStopRecordFailed(CameraResult::kError, error_text);
}

TEST(Camera, StopRecordReportsAccessDenied) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const std::string error_text = "error_text";

  EXPECT_CALL(*result, SuccessInternal).Times(0);
  EXPECT_CALL(*result,
              ErrorInternal(Eq("CameraAccessDenied"), Eq(error_text), _));

  camera->AddPendingResult(PendingResultType::kStopRecord, std::move(result));

  camera->OnStopRecordFailed(CameraResult::kAccessDenied, error_text);
}

TEST(Camera, OnTakePictureSucceededReturnsSuccess) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const std::string file_path = "C:\\temp\\filename.jpeg";

  EXPECT_CALL(*result, ErrorInternal).Times(0);
  EXPECT_CALL(*result, SuccessInternal(Pointee(EncodableValue(file_path))));

  camera->AddPendingResult(PendingResultType::kTakePicture, std::move(result));

  camera->OnTakePictureSucceeded(file_path);
}

TEST(Camera, TakePictureReportsError) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const std::string error_text = "error_text";

  EXPECT_CALL(*result, SuccessInternal).Times(0);
  EXPECT_CALL(*result, ErrorInternal(Eq("camera_error"), Eq(error_text), _));

  camera->AddPendingResult(PendingResultType::kTakePicture, std::move(result));

  camera->OnTakePictureFailed(CameraResult::kError, error_text);
}

TEST(Camera, TakePictureReportsAccessDenied) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockMethodResult> result =
      std::make_unique<MockMethodResult>();

  const std::string error_text = "error_text";

  EXPECT_CALL(*result, SuccessInternal).Times(0);
  EXPECT_CALL(*result,
              ErrorInternal(Eq("CameraAccessDenied"), Eq(error_text), _));

  camera->AddPendingResult(PendingResultType::kTakePicture, std::move(result));

  camera->OnTakePictureFailed(CameraResult::kAccessDenied, error_text);
}

TEST(Camera, OnVideoRecordSucceededInvokesCameraChannelEvent) {
  std::unique_ptr<CameraImpl> camera =
      std::make_unique<CameraImpl>(MOCK_DEVICE_ID);
  std::unique_ptr<MockCaptureControllerFactory> capture_controller_factory =
      std::make_unique<MockCaptureControllerFactory>();

  std::unique_ptr<MockBinaryMessenger> binary_messenger =
      std::make_unique<MockBinaryMessenger>();

  const std::string file_path = "C:\\temp\\filename.mp4";
  const int64_t camera_id = 12345;
  std::string camera_channel =
      std::string("plugins.flutter.io/camera_windows/camera") +
      std::to_string(camera_id);
  const int64_t video_duration = 1000000;

  EXPECT_CALL(*capture_controller_factory, CreateCaptureController)
      .Times(1)
      .WillOnce(
          []() { return std::make_unique<NiceMock<MockCaptureController>>(); });

  // TODO: test binary content.
  // First time is video record success message,
  // and second is camera closing message.
  EXPECT_CALL(*binary_messenger, Send(Eq(camera_channel), _, _, _)).Times(2);

  // Init camera with mock capture controller factory
  camera->InitCamera(std::move(capture_controller_factory),
                     std::make_unique<MockTextureRegistrar>().get(),
                     binary_messenger.get(), false, ResolutionPreset::kAuto);

  // Pass camera id for camera
  camera->OnCreateCaptureEngineSucceeded(camera_id);

  camera->OnVideoRecordSucceeded(file_path, video_duration);

  // Dispose camera before message channel.
  camera = nullptr;
}

}  // namespace test
}  // namespace camera_windows


text:
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE DataKinds #-}

module Bug where

pattern PATTERN = ()

wrongLift :: PATTERN
wrongLift = undefined


text:
<?php

namespace Brickoo\Component\Storage\Messaging\Message;

use Brickoo\Component\Storage\Messaging\Messages;

/**
 * RetrieveByCallbackMessage
 *
 * Implements a message for retrieving cached data
 * using a callback as fresh fallback loader.
 * @author Celestino Diaz <celestino.diaz@gmx.de>
 */
class RetrieveByCallbackMessage extends StorageMessage {

    /**
     * @param string $identifier the cache unique identifier
     * @param callable $callback the callback for fresh loading
     * @param array $callbackArguments the callback arguments
     * @param integer $cacheLifetime the max. cache lifetime for the fresh loaded content
     */
    public function __construct($identifier, callable $callback, array $callbackArguments = [], $cacheLifetime = 0) {
        parent::__construct(Messages::CALLBACK);
        $this->setIdentifier($identifier)
            ->setLifetime($cacheLifetime)
            ->setCallback($callback)
            ->setCallbackArguments($callbackArguments);
    }

}


text:
require "spec_helper"

# We need to require AMQ-Protocol manually.
# In the library this is required in the file
# amq/client.rb, but this is a unit test and
# we don't want to mess around with unecessary
# dependencies.
require "amq/protocol/client"
require "amq/protocol/frame"

# We have to use Kernel#load so extensions to the
# Logging module from client.rb will be overridden.
load "amq/client/framing/string/frame.rb"

describe AMQ::Client::Framing::String do
  subject do
    AMQ::Client::Framing::String::Frame
  end

  # Created by:
  # frame = AMQ::Protocol::Queue::Declare.encode(1, "tasks", false, false, false, false, {})
  # frame.encode
  # frame.payload
  before do
    data = ["\x01\x00\x00\x00\x00\x00\b"]
    data << "\x00\n\x00(\x01/\x00\x00"
    data << "\xCE"
    @string = data.join

    subject.stub(:decode_header).with(data.first).and_return([1, 0, data[1].bytesize])
  end

  it "should be able to decode frame type" do
    subject.decode(@string).should be_kind_of(AMQ::Protocol::MethodFrame)
  end

  it "should be able to decode channel" do
    subject.decode(@string).channel.should eql(0)
  end

  it "should be able to decode payload" do
    subject.decode(@string).payload.should eql("\x00\n\x00(\x01/\x00\x00")
  end

  it "should raise an error if the frame length is miscalculated" do
    data = @string[0..-2] + "too long" + "\xCE"
    string   = String.new(data)
    lambda { subject.decode(string) }.should raise_error(AMQ::Client::BadLengthError)
  end

  it "should raise an error if the frame doesn't end with FINAL_OCTET" do
    string = @string[0..-2] + "x"
    lambda { subject.decode(string) }.should raise_error(AMQ::Client::NoFinalOctetError)
  end
end


text:
package org.xbib.io.compress.xz.lz;

public final class Matches {
    public final int[] len;
    public final int[] dist;
    public int count = 0;

    Matches(int countMax) {
        len = new int[countMax];
        dist = new int[countMax];
    }
}


text:
package org.activiti.designer.validation.bpmn20.validation.worker;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.eclipse.emf.ecore.EObject;
import org.eclipse.graphiti.mm.pictograms.Diagram;

/**
 *
 * Interface for validation workers.
 *
 * @author Tiese Barrell
 * @since 5.6
 * @version 1
 */
public interface ProcessValidationWorker {

  Collection<ProcessValidationWorkerMarker> validate(Diagram diagram, Map<String, List<EObject>> processNodes);

}


text:
import os
import socket
import copy
import sys
import traceback
import uuid

# Centos-7 doesn't include the svg mime type
# /usr/lib64/python/mimetypes.py
import mimetypes

# Django Split Settings
from split_settings.tools import optional, include

# Load default settings.
from .defaults import *  # NOQA

if "pytest" in sys.modules:
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            'LOCATION': 'unique-{}'.format(str(uuid.uuid4())),
        },
    }

# awx-manage shell_plus --notebook
NOTEBOOK_ARGUMENTS = [
    '--NotebookApp.token=',
    '--ip', '0.0.0.0',
    '--port', '8888',
    '--allow-root',
    '--no-browser',
]

# print SQL queries in shell_plus
SHELL_PLUS_PRINT_SQL = False

# show colored logs in the dev environment
# to disable this, set `COLOR_LOGS = False` in awx/settings/local_settings.py
LOGGING['handlers']['console']['()'] = 'awx.main.utils.handlers.ColorHandler'  # noqa
# task system does not propagate to AWX, so color log these too
LOGGING['handlers']['task_system'] = LOGGING['handlers']['console'].copy()  # noqa
COLOR_LOGS = True

# Pipe management playbook output to console
LOGGING['loggers']['awx.isolated.manager.playbooks']['propagate'] = True  # noqa

# celery is annoyingly loud when docker containers start
LOGGING['loggers'].pop('celery', None)  # noqa

ALLOWED_HOSTS = ['*']

mimetypes.add_type("image/svg+xml", ".svg", True)
mimetypes.add_type("image/svg+xml", ".svgz", True)

# Disallow sending session cookies over insecure connections
SESSION_COOKIE_SECURE = False

# Disallow sending csrf cookies over insecure connections
CSRF_COOKIE_SECURE = False

# Override django.template.loaders.cached.Loader in defaults.py
template = next((tpl_backend for tpl_backend in TEMPLATES if tpl_backend['NAME'] == 'default'), None) # noqa
template['OPTIONS']['loaders'] = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

CALLBACK_QUEUE = "callback_tasks"

# Enable dynamically pulling roles from a requirement.yml file
# when updating SCM projects
# Note: This setting may be overridden by database settings.
AWX_ROLES_ENABLED = True

# Enable PROOT for tower-qa integration tests.
# Note: This setting may be overridden by database settings.
AWX_PROOT_ENABLED = True

AWX_ISOLATED_USERNAME = 'root'
AWX_ISOLATED_CHECK_INTERVAL = 1
AWX_ISOLATED_PERIODIC_CHECK = 30

# Disable Pendo on the UI for development/test.
# Note: This setting may be overridden by database settings.
PENDO_TRACKING_STATE = "off"
INSIGHTS_TRACKING_STATE = False

# Use Django-Jenkins if installed. Only run tests for awx.main app.
try:
    import django_jenkins
    INSTALLED_APPS += [django_jenkins.__name__,] # noqa
    PROJECT_APPS = ('awx.main.tests', 'awx.api.tests',)
except ImportError:
    pass

if 'django_jenkins' in INSTALLED_APPS:
    JENKINS_TASKS = (
        # 'django_jenkins.tasks.run_pylint',
        # 'django_jenkins.tasks.run_flake8',
        # The following are not needed when including run_flake8
        # 'django_jenkins.tasks.run_pep8',
        # 'django_jenkins.tasks.run_pyflakes',
        # The following are handled by various grunt tasks and no longer required
        # 'django_jenkins.tasks.run_jshint',
        # 'django_jenkins.tasks.run_csslint',
    )
    PEP8_RCFILE = "setup.cfg"
    PYLINT_RCFILE = ".pylintrc"

# debug toolbar and swagger assume that requirements/requirements_dev.txt are installed

INSTALLED_APPS += [   # NOQA
    'rest_framework_swagger',
    'debug_toolbar',
]

MIDDLEWARE = [
    'debug_toolbar.middleware.DebugToolbarMiddleware',
] + MIDDLEWARE  # NOQA

DEBUG_TOOLBAR_CONFIG = {
    'ENABLE_STACKTRACES' : True,
}

# Configure a default UUID for development only.
SYSTEM_UUID = '00000000-0000-0000-0000-000000000000'
INSTALL_UUID = '00000000-0000-0000-0000-000000000000'

# Store a snapshot of default settings at this point before loading any
# customizable config files.
DEFAULTS_SNAPSHOT = {}
this_module = sys.modules[__name__]
for setting in dir(this_module):
    if setting == setting.upper():
        DEFAULTS_SNAPSHOT[setting] = copy.deepcopy(getattr(this_module, setting))

# If there is an `/etc/tower/settings.py`, include it.
# If there is a `/etc/tower/conf.d/*.py`, include them.
include(optional('/etc/tower/settings.py'), scope=locals())
include(optional('/etc/tower/conf.d/*.py'), scope=locals())

# Installed differently in Dockerfile compared to production versions
AWX_ANSIBLE_COLLECTIONS_PATHS = '/vendor/awx_ansible_collections'

BASE_VENV_PATH = "/venv/"
ANSIBLE_VENV_PATH = os.path.join(BASE_VENV_PATH, "ansible")
AWX_VENV_PATH = os.path.join(BASE_VENV_PATH, "awx")

# If any local_*.py files are present in awx/settings/, use them to override
# default settings for development.  If not present, we can still run using
# only the defaults.
try:
    include(optional('local_*.py'), scope=locals())
except ImportError:
    traceback.print_exc()
    sys.exit(1)

CELERYBEAT_SCHEDULE.update({  # noqa
    'isolated_heartbeat': {
        'task': 'awx.main.tasks.awx_isolated_heartbeat',
        'schedule': timedelta(seconds=AWX_ISOLATED_PERIODIC_CHECK),  # noqa
        'options': {'expires': AWX_ISOLATED_PERIODIC_CHECK * 2},  # noqa
    }
})

CLUSTER_HOST_ID = socket.gethostname()

if 'Docker Desktop' in os.getenv('OS', ''):
    os.environ['SDB_NOTIFY_HOST'] = 'docker.for.mac.host.internal'
else:
    try:
        os.environ['SDB_NOTIFY_HOST'] = os.popen('ip route').read().split(' ')[2]
    except Exception:
        pass

AWX_CALLBACK_PROFILE = True


text:
package org.pmg.jms.gensudoku.director;

import org.pmg.jms.gensudoku.genprofile.*;
import java.util.ArrayList;

/**
 *
 * @author peter
 */
public class UnitMarshal {

    private final Profile profile;
    private final ArrayList<String> iterations = new ArrayList<>();
    protected String resolved = "";

    public UnitMarshal(String unitId) {

        profile = getUnitProfile(unitId);
    }

    public void addSnapshot() {

        iterations.add(0,resolved);
    }

    public void addSolvent(String solvent) {

        resolved += solvent;
    }

    public boolean contains(String solvent) {

        return resolved.contains(solvent);
    }

    public String[] getAllPeers(String key) {

        return profile.getAllPeers(key);
    }

    public String getResolved() {

        return resolved;
    }

    public void reset() {

        resolved = "";
        iterations.clear();
    }

    public void rollback(int retroIndex) {

        while (retroIndex > 0) {
            iterations.remove(0);
            retroIndex--;
        }
        resolved = iterations.get(0);
    }

    private static Profile getUnitProfile(String unitId) {

        switch (unitId) {
            case "ROWA" : return new ProfileRowA();
            case "ROWB" : return new ProfileRowB();
            case "ROWC" : return new ProfileRowC();
            case "ROWD" : return new ProfileRowD();
            case "ROWE" : return new ProfileRowE();
            case "ROWF" : return new ProfileRowF();
            case "ROWG" : return new ProfileRowG();
            case "ROWH" : return new ProfileRowH();
            case "ROWI" : return new ProfileRowI();
            case "COL1" : return new ProfileCol1();
            case "COL2" : return new ProfileCol2();
            case "COL3" : return new ProfileCol3();
            case "COL4" : return new ProfileCol4();
            case "COL5" : return new ProfileCol5();
            case "COL6" : return new ProfileCol6();
            case "COL7" : return new ProfileCol7();
            case "COL8" : return new ProfileCol8();
            case "COL9" : return new ProfileCol9();
            case "SQUA1" : return new ProfileSquA1();
            case "SQUA2" : return new ProfileSquA2();
            case "SQUA3" : return new ProfileSquA3();
            case "SQUB1" : return new ProfileSquB1();
            case "SQUB2" : return new ProfileSquB2();
            case "SQUB3" : return new ProfileSquB3();
            case "SQUC1" : return new ProfileSquC1();
            case "SQUC2" : return new ProfileSquC2();
            case "SQUC3" : return new ProfileSquC3();
        }
        return null;
    }

}


text:
namespace Orc.DependencyGraph.GraphD
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;

    [DebuggerDisplay("{Value.ToString()}: [{(this as IInternalNode<T>).PrintImmediatePrecedents}]")]
    internal class InternalNode<T>
        : IInternalNode<T> where T : IEquatable<T>
    {
        internal InternalNode(T publicNode, Graph<T> graph)
        {
            this.Edges = new List<InternalNode<T>>();
            this.Parents = new List<InternalNode<T>>();

            this.Value = publicNode;
            this._graph = graph;
        }

        public List<InternalNode<T>> Edges { get; private set; }
        public List<InternalNode<T>> Parents { get; private set; }
        IEnumerable<IInternalNode<T>> IInternalNode<T>.Edges { get { return this.Edges; } }
        IEnumerable<IInternalNode<T>> IInternalNode<T>.Parents { get { return this.Parents; } }

        public T Value { get; internal set; }

        public IGraph<T> Graph
        {
            get { return this._graph; }
        }

        public int Level
        {
            get { return this._graph.ReferencePoint + this.ReferenceRelativeLevel; }
        }

        private readonly Graph<T> _graph;

        public int ReferenceRelativeLevel { get; set; }

        public IOrderedEnumerable<INode<T>> GetNeighbours(int relativeLevelFrom, int relativeLevelTo)
        {
            return new OrderedEnumerable<INode<T>>(() => this.GetNeighboursInternal(relativeLevelFrom, relativeLevelTo));
        }
        private IEnumerable<INode<T>> GetNeighboursInternal(int relativeLevelFrom, int relativeLevelTo)
        {
            if (relativeLevelFrom < 0 && relativeLevelTo < 0)
                return this._graph.GetPrecedents(this, (_ => _ != this && _.Level >= this.Level + relativeLevelFrom && _.Level <= this.Level + relativeLevelTo)).OrderBy(_ => _.Level);
            else if (relativeLevelFrom > 0 && relativeLevelTo > 0)
            {
                return this._graph.GetDescendants(this, (_ => _ != this && _.Level >= this.Level + relativeLevelFrom && _.Level <= this.Level + relativeLevelTo)).OrderBy(_ => _.Level);
            }
            else
            {
                var precedents = this._graph.GetPrecedents(this, (_ => _ != this && _.Level >= this.Level + relativeLevelFrom && _.Level <= this.Level + relativeLevelTo));
                var descendants = this._graph.GetDescendants(this, (_ => _ != this && _.Level >= this.Level + relativeLevelFrom && _.Level <= this.Level + relativeLevelTo));

                return precedents.Union(descendants).OrderBy(_ => _.Level);
            }
        }

        public IOrderedEnumerable<INode<T>> Precedents
        {
            get
            {
                return new OrderedEnumerable<INode<T>>(
                    () => this._graph.GetPrecedents(this, (_ => _.Level < this.Level)).OrderBy(_ => _.Level));
            }
        }

        public IOrderedEnumerable<INode<T>> Descendants
        {
            get
            {
                return new OrderedEnumerable<INode<T>>(() => this._graph.GetDescendants(this, (_ => _.Level > this.Level)).OrderBy(_ => _.Level));
            }
        }

        public IOrderedEnumerable<INode<T>> ImmediatePrecedents
        {
            get
            {
                return new OrderedEnumerable<INode<T>>(() => this.Parents.OrderBy(x => x.Level));
            }
        }

        public IOrderedEnumerable<INode<T>> ImmediateDescendants
        {
            get
            {
                return new OrderedEnumerable<INode<T>>(() => this.Edges.OrderBy(x => x.Level));
            }
        }

        public IOrderedEnumerable<INode<T>> TerminatingPrecedents
        {
            get
            {
                return new OrderedEnumerable<INode<T>>(() => this._graph.GetPrecedents(this, (_ => _.Level < this.Level && !_.Parents.Any())).OrderBy(_ => _.Level));
            }
        }

        public IOrderedEnumerable<INode<T>> TerminatingDescendants
        {
            get
            {
                return new OrderedEnumerable<INode<T>>(() => this._graph.GetDescendants(this, (_ => _.Level > this.Level && !_.Edges.Any())).OrderBy(_ => _.Level));
            }
        }

        string IInternalNode<T>.PrintImmediatePrecedents
        {
            get
            {
                if (!this.Edges.Any()) return string.Empty;
                var sb = new StringBuilder();
                foreach (var immediatePrecedents in this.Edges)
                {
                    sb.Append(immediatePrecedents.Value);
                    sb.Append(", ");
                }
                return sb.Remove(sb.Length-2,2).ToString();
            }
        }
    }
}


text:
from survey.features.page_objects.base import PageObject
from nose.tools import assert_equals

class AddLocationHierarchyPage(PageObject):
    def __init__(self, browser):
        super(AddLocationHierarchyPage, self).__init__(browser)
        self.url = '/locations/hierarchy/add/'

    def see_field_details(self, level, form, status=True):
        assert_equals(status, self.browser.is_text_present(level))
        status = 1 if status else 0
        for field in ['levels', 'required', 'has_code', 'code']:
            assert_equals(status, len(self.browser.find_by_name(form + '-levels')))

    def submit(self):
        self.browser.find_by_name('save_button').first.click()


text:
package parser

import (
	"bytes"
	"fmt"
)

const (
	astInt      = "INT"
	astInteger  = "INTEGER"
	astSmallInt = "SMALLINT"
	astBigInt   = "BIGINT"
	astReal     = "REAL"
	astDouble   = "DOUBLE PRECISION"
	astFloat    = "FLOAT"
	astDecimal  = "DECIMAL"
	astNumeric  = "NUMERIC"
)

// ColumnType represents a type in a column definition.
type ColumnType interface {
	fmt.Stringer
	columnType()
}

func (*BoolType) columnType()      {}
func (*IntType) columnType()       {}
func (*FloatType) columnType()     {}
func (*DecimalType) columnType()   {}
func (*DateType) columnType()      {}
func (*TimestampType) columnType() {}
func (*StringType) columnType()    {}
func (*BytesType) columnType()     {}

// BoolType represents a BOOLEAN type.
type BoolType struct {
	Name string
}

func (node *BoolType) String() string {
	return node.Name
}

// IntType represents an INT, INTEGER, SMALLINT or BIGINT type.
type IntType struct {
	Name string
	N    int
}

func (node *IntType) String() string {
	var buf bytes.Buffer
	_, _ = buf.WriteString(node.Name)
	if node.N > 0 {
		fmt.Fprintf(&buf, "(%d)", node.N)
	}
	return buf.String()
}

// FloatType represents a REAL, DOUBLE or FLOAT type.
type FloatType struct {
	Name string
	Prec int
}

func (node *FloatType) String() string {
	var buf bytes.Buffer
	_, _ = buf.WriteString(node.Name)
	if node.Prec > 0 {
		fmt.Fprintf(&buf, "(%d)", node.Prec)
	}
	return buf.String()
}

// DecimalType represents a DECIMAL or NUMERIC type.
type DecimalType struct {
	Name  string
	Prec  int
	Scale int
}

func (node *DecimalType) String() string {
	var buf bytes.Buffer
	_, _ = buf.WriteString(node.Name)
	if node.Prec > 0 {
		fmt.Fprintf(&buf, "(%d", node.Prec)
		if node.Scale > 0 {
			fmt.Fprintf(&buf, ",%d", node.Scale)
		}
		_, _ = buf.WriteString(")")
	}
	return buf.String()
}

// DateType represents a DATE type.
type DateType struct {
	Name string
}

func (node *DateType) String() string {
	return node.Name
}

// TimestampType represents a TIMESTAMP type.
type TimestampType struct {
}

func (node *TimestampType) String() string {
	return "TIMESTAMP"
}

// StringType represents a STRING, CHAR or VARCHAR type.
type StringType struct {
	Name string
	N    int
}

func (node *StringType) String() string {
	var buf bytes.Buffer
	_, _ = buf.WriteString(node.Name)
	if node.N > 0 {
		fmt.Fprintf(&buf, "(%d)", node.N)
	}
	return buf.String()
}

// BytesType represents a BYTES or BLOB type.
type BytesType struct {
	Name string
}

func (node *BytesType) String() string {
	return node.Name
}


text:
{%- unless page.layout == 'collection' -%}
  <time class="entry-date dt-published" datetime="{{ entry.date | date_to_xmlschema }}">
    {%- assign date_format = site.date_format | default: "%B %-d, %Y" -%}
    {{ entry.date | date: date_format }}
  </time>
{%- endunless -%}


text:
namespace algorithms {
	class DoublePointAlgorithm : public Algorithm {
	public:
		Matrix getMatrix() {
			return Matrix(1.0f);
		}
	};
}

#endif // ~__RED_DOUBLE_POINT_ALGORITHM__


text:
<?php
/**
 * Created by EdwardData
 * BlackCube Technologies
 * Date: 3/10/15
 * Time: 11:28 AM
 *
 */

namespace Bitxone\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * ShippingCodes
 *
 * @ORM\Table(name="shipping_codes")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks()
 */

class ShippingCodes
{
	/**
	* @var integer
	*
	* @ORM\Column(name="id", type="integer", nullable=false)
	* @ORM\Id
	* @ORM\GeneratedValue(strategy="IDENTITY")
	*/
	private $id;

	/**
	* @var string
	*
	* @ORM\Column(name="guid", type="string", length=255, nullable=false)
	*/
	private $guid;

	/**
	 * @var integer
	 *
	 * @ORM\ManyToOne(targetEntity="Bitxone\MainBundle\Entity\Retailers", inversedBy="shippingCodes", cascade={"persist"})
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="retailer_id", referencedColumnName="id", nullable=false)
     * })
	 *
	*/
	private $retailerId;

	/**
	* @var string
	*
	* @ORM\Column(name="chub_code", type="string", length=255, nullable=false)
	*/
	private $chubCode;

	/**
	* @var string
	*
	* @ORM\Column(name="erp_ship_code", type="string", length=255, nullable=false)
	*/
	private $erpShipCode;

	/**
	* @var \DateTime
	*
	* @ORM\Column(name="created_at", type="datetime", nullable=true)
	*/
	private $createdAt;

	/**
	* @var \DateTime
	*
	* @ORM\Column(name="updated_at", type="datetime", nullable=true)
	*/
	private $updatedAt;

	/**
	 * @return int
	 */
	public function getId()
	{
		return $this->id;
	}

	/**
	 * @param int $id
	 */
	public function setId( $id )
	{
		$this->id = $id;
	}

	/**
	 * @return string
	 */
	public function getGuid()
	{
		return $this->guid;
	}

	/**
	 * @param string $guid
	 */
	public function setGuid( $guid )
	{
		$this->guid = $guid;
	}

	/**
	 * @return int
	 */
	public function getRetailerId()
	{
		return $this->retailerId;
	}

	/**
	 * @param int $retailerId
	 */
	public function setRetailerId( $retailerId )
	{
		$this->retailerId = $retailerId;
	}

	/**
	 * @return string
	 */
	public function getChubCode()
	{
		return $this->chubCode;
	}

	/**
	 * @param string $chubCode
	 */
	public function setChubCode( $chubCode )
	{
		$this->chubCode = $chubCode;
	}

	/**
	 * @return string
	 */
	public function getErpShipCode()
	{
		return $this->erpShipCode;
	}

	/**
	 * @param string $erpShipCode
	 */
	public function setErpShipCode( $erpShipCode )
	{
		$this->erpShipCode = $erpShipCode;
	}

	/**
	 * @return \DateTime
	 */
	public function getCreatedAt()
	{
		return $this->createdAt;
	}

	/**
	 * @param \DateTime $createdAt
	 */
	public function setCreatedAt( $createdAt )
	{
		$this->createdAt = $createdAt;
	}

	/**
	 * @return \DateTime
	 */
	public function getUpdatedAt()
	{
		return $this->updatedAt;
	}

	/**
	 * @param \DateTime $updatedAt
	 */
	public function setUpdatedAt( $updatedAt )
	{
		$this->updatedAt = $updatedAt;
	}

	/**
	* @ORM\PrePersist
	*/
	public function setPrePersistGuid()
	{
		$this->setGuid( \uuid_create() );
	}

	/**
	* @ORM\PrePersist
	*/
	public function setPrePersistCreatedAt()
	{
		$this->setCreatedAt(new \DateTime());
	}

	/**
	* @ORM\PreUpdate
	*/
	public function setPreUpdateUpdatedAt()
	{
		$this->setUpdatedAt(new \DateTime());
	}

	public function __toString()
	{
		return $this->getErpShipCode();
	}

}


text:
// Copyright 2018 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
* @fileoverview Unit tests for ConceptCardObjectFactory.
*/

describe('Concept card object factory', function() {
  beforeEach(module('oppia'));

  describe('ConceptCardObjectFactory', function() {
    var ConceptCardObjectFactory;
    var conceptCardDict = {
      explanation: 'test explanation',
      worked_examples: ['worked example 1', 'worked example 2']
    };
    beforeEach(inject(function($injector) {
      ConceptCardObjectFactory = $injector.get('ConceptCardObjectFactory');
    }));

    it('should create a new concept card from a backend dictionary',
      function() {
        var conceptCard =
          ConceptCardObjectFactory.createFromBackendDict(conceptCardDict);
        expect(conceptCard.getExplanation()).toEqual('test explanation');
        expect(conceptCard.getWorkedExamples()).toEqual(
          ['worked example 1', 'worked example 2']);
      });

    it('should convert to a backend dictionary', function() {
      var conceptCard =
        ConceptCardObjectFactory.createFromBackendDict(conceptCardDict);
      expect(conceptCard.toBackendDict()).toEqual(conceptCardDict);
    });

    it('should create an interstitial concept card', function() {
      var conceptCard =
        ConceptCardObjectFactory.createInterstitialConceptCard();
      expect(conceptCard.getExplanation()).toEqual(
        'Loading review material');
      expect(conceptCard.getWorkedExamples()).toEqual([]);
    });
  });
});


text:
@interface SecEvent : UIViewController <UITextFieldDelegate, UITextViewDelegate>
@property (nonatomic) NSInteger *NumThing;    //Keeping the index of the event
@property (strong, nonatomic) NSString *PushName;   //key for notification

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>src/away/textures/MipmapGenerator.ts</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for: 0.1.0

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

away.events.AssetEvent

away.events.Event

away.events.EventDispatcher

away.events.HTTPStatusEvent

away.events

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

File: src/away/textures/MipmapGenerator.ts

///<reference path="../_definitions.ts"/>

module away.textures
{
	//import flash.display.*;
	//import flash.display3D.textures.CubeTexture;
	//import flash.display3D.textures.Texture;
	//import flash.display3D.textures.TextureBase;
	//import flash.geom.*;

	/**
	 * MipmapGenerator is a helper class that uploads BitmapData to a Texture including mipmap levels.
	 */
	export class MipmapGenerator
	{
		private static _matrix:away.geom.Matrix = new away.geom.Matrix();
		private static _rect:away.geom.Rectangle = new away.geom.Rectangle();
		private static _source:away.display.BitmapData;//= new away.display.BitmapData();

		/**
		 * Uploads a BitmapData with mip maps to a target Texture object.
		 * @param source
		 * @param target The target Texture to upload to.
		 * @param mipmap An optional mip map holder to avoids creating new instances for fe animated materials.
		 * @param alpha Indicate whether or not the uploaded bitmapData is transparent.
		 */
		public static generateHTMLImageElementMipMaps(source:HTMLImageElement, target:away.displayGL.TextureBase, mipmap:away.display.BitmapData = null, alpha:boolean = false, side:number = -1)
		{

			MipmapGenerator._rect.width = source.width;
			MipmapGenerator._rect.height = source.height;

			MipmapGenerator._source = new away.display.BitmapData(source.width, source.height, alpha);
			MipmapGenerator._source.drawImage(source, MipmapGenerator._rect, MipmapGenerator._rect);

			MipmapGenerator.generateMipMaps(MipmapGenerator._source, target, mipmap);

			MipmapGenerator._source.dispose();
			MipmapGenerator._source = null;

		}

		/**
		 * Uploads a BitmapData with mip maps to a target Texture object.
		 * @param source The source BitmapData to upload.
		 * @param target The target Texture to upload to.
		 * @param mipmap An optional mip map holder to avoids creating new instances for fe animated materials.
		 * @param alpha Indicate whether or not the uploaded bitmapData is transparent.
		 */
		public static generateMipMaps(source:away.display.BitmapData, target:away.displayGL.TextureBase, mipmap:away.display.BitmapData = null, alpha:boolean = false, side:number = -1)
		{
			var w:number = source.width;
			var h:number = source.height;
			var regen:boolean = mipmap != null;
			var i:number;

			if (!mipmap) {

				mipmap = new away.display.BitmapData(w, h, alpha);

			}

			MipmapGenerator._rect.width = w;
			MipmapGenerator._rect.height = h;

			var tx:away.displayGL.Texture;

			while (w >= 1 || h >= 1) {

				if (alpha) {

					mipmap.fillRect(MipmapGenerator._rect, 0);

				}

				MipmapGenerator._matrix.a = MipmapGenerator._rect.width/source.width;
				MipmapGenerator._matrix.d = MipmapGenerator._rect.height/source.height;

				mipmap.width = MipmapGenerator._rect.width;
				mipmap.height = MipmapGenerator._rect.height;
				mipmap.copyPixels(source, source.rect, MipmapGenerator._rect);

				//console.log( target instanceof away.display3D.Texture , mipmap.width , mipmap.height );

				if (target instanceof away.displayGL.Texture) {
					tx = <away.displayGL.Texture> target;
					tx.uploadFromBitmapData(mipmap, i++);
				} else {
					away.Debug.throwPIR('MipMapGenerator', 'generateMipMaps', 'Dependency: CubeTexture');
					// TODO: implement cube texture upload;
					//CubeTexture(target).uploadFromBitmapData(mipmap, side, i++);
				}

				w >>= 1;
				h >>= 1;

				MipmapGenerator._rect.width = w > 1? w : 1;
				MipmapGenerator._rect.height = h > 1? h : 1;
			}

			if (!regen) {

				mipmap.dispose();

			}

		}
	}
}


text:
module utills {
	/**
	 *
	 * @author
	 *
	 */
	export class AdBanner extends egret.Sprite{
    	private banner:egret.Bitmap;
		public constructor() {
    		super()
            this.addEventListener(egret.Event.ADDED_TO_STAGE,this.onAddToStage,this);
		}
		private onAddToStage(){
		    this.banner = new egret.Bitmap();
            this.banner.texture = RES.getRes('banner_png');
            this.banner.height = 80;
            this.banner.width = 640;
            this.addChild(this.banner);
		}
	}
}


text:
package app2;

import leap.core.annotation.Inject;
import leap.web.App;
import leap.web.json.JsonConfigurator;

public class Global extends App {

	protected @Inject JsonConfigurator jc;

	@Override
    protected void init() throws Throwable {
		jc.setDefaultSerializationIgnoreNull(true);
	}

}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>triangulate</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

Module triangulate

Classes

    Triangulation

Variables

    set

[hide private]