text:
// Declarations for 2D FFT routines in third_party/fft2d/fft2d.

#ifndef FFT2D_FFT_H__
#define FFT2D_FFT_H__

#ifdef __cplusplus
extern "C" {
#endif

extern void cdft2d(int, int, int, double**, double*, int*, double*);
extern void rdft2d(int, int, int, double**, double*, int*, double*);
extern void ddct2d(int, int, int, double**, double*, int*, double*);
extern void ddst2d(int, int, int, double**, double*, int*, double*);
extern void ddct8x8s(int isgn, double** a);
extern void ddct16x16s(int isgn, double** a);

#ifdef __cplusplus
}
#endif

#endif  // FFT2D_FFT_H__

redpajama_set_name: RedPajamaGithub


text:
var path = require('path'),
    demoPath = path.join(__dirname, 'demo'),
    wwwPath = path.join(__dirname, 'www'),
    docsPath = path.join(__dirname, 'docs'),
    pkg = require('./package.json'),
    HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: path.join(demoPath, 'index.js'),
    output: {
        path: wwwPath,
        filename: 'demo.js'
    },
    module: {
        loaders: [{
            test: /[\/]angular\.js$/,
            loader: 'expose?angular!exports?window.angular'
        }, {
            test: /\.json$/,
            loader: "json"
        }, {
            test: /\.css$/,
            loader: "style!css"
        }, {
            test: [/ionicons\.svg/, /ionicons\.eot/, /ionicons\.ttf/, /ionicons\.woff/],
            loader: 'file?name=fonts/[name].[ext]'
        }, {
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            loader: "ng-annotate?add=true!babel"
        }]
    },
    plugins: [new HtmlWebpackPlugin({
        filename: 'index.html',
        pkg: pkg,
        template: path.join(demoPath, 'index.html')
    })]
};


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/dlg_action_margin"
    android:paddingLeft="@dimen/dlg_action_margin"
    android:paddingRight="@dimen/dlg_action_margin"
    android:paddingBottom="@dimen/dlg_bottom_margin">

    <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/dlg_content_margin"
        android:paddingRight="@dimen/dlg_content_margin"
        android:paddingLeft="@dimen/dlg_content_margin"
        android:paddingBottom="@dimen/dlg_action_margin"
        android:layout_alignParentTop="true"
        android:orientation="vertical">

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            style="@style/DialogTitle"
            android:text="@string/copy_pwd"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            android:text="@string/warning_copy"
            android:textAppearance="@style/TextAppearance.AppCompat.Body1"/>

        <CheckBox android:id="@+id/checkbox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            android:text="@string/remember_choice"/>

    </LinearLayout>

    <Button android:id="@+id/ok"
        style="@style/Button.Flat.Accent"
        android:layout_width="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_below="@id/container"
        android:text="@android:string/ok"
        android:layout_height="wrap_content" />

    <Button android:id="@+id/cancel"
        style="@style/Button.Flat.Accent"
        android:layout_width="wrap_content"
        android:layout_below="@id/container"
        android:layout_toLeftOf="@id/ok"
        android:text="@android:string/cancel"
        android:layout_height="wrap_content" />

</RelativeLayout>


text:
"use strict";

exports.stringify = stringify;

var defaults = {
    maxLength: 200,
    doubleSpaceDepth: 1,
    spaceBeforeColon: false,
    spaceAfterColon: true,
    spaceAfterComma: true,
    spaceInsideBraces: true,
    spaceInsideBrackets: true,
    sameLineBraces: false,
    sameLineBrackets: false,
    typeOrder: {
        boolean: 1,
        number: 2,
        string: 3,
        default: 99,
    }
};

function stringify(obj, opts, depth) {
    var str, indent, type = typeof obj;

    if (typeof depth !== 'number') { depth = 1; };
    if (typeof opts !== 'object') { opts = {}; }
    Object.keys(defaults).forEach(function(key){
        if (!opts.hasOwnProperty(key)) {
            opts[key] = defaults[key];
        }
    });

    switch(type){
        case "object":
            indent = Array(depth).join('\t');

            if (obj === null) {
                str = "null";
            } else if (Array.isArray(obj)) {
                str = '[' + (opts.spaceInsideBrackets?' ':'') + '\n';
                str += Object.keys(obj)
                    .map(function(key, i, arr){ return (depth <= opts.doubleSpaceDepth && i?'\n':'') + '\t' + indent + stringify(obj[key], opts, depth+1); })
                    .join(',' + (opts.spaceAfterComma?' ':'') + '\n');
                str += (opts.spaceInsideBrackets?' ':'') + '\n' + indent + ']';
                if (opts.sameLineBrackets) { str = str.replace(/\n\t*\[/g,'['); }
            } else {
                str = '{' + (opts.spaceInsideBraces?' ':'') + '\n';
                str += Object.keys(obj)
                    .sort(function(a,b){ var sa=opts.typeOrder[typeof obj[a]]||opts.typeOrder.default, sb=opts.typeOrder[typeof obj[b]]||opts.typeOrder.default; return ((sa !== sb)?(sa - sb):(a>b?1:-1)); })
                    .map(function(key, i, arr){ return (depth <= opts.doubleSpaceDepth && i?'\n':'') + '\t' + indent + JSON.stringify(key) + (opts.spaceBeforeColon?' ':'') + ':' + (opts.spaceAfterColon?' ':'') + stringify(obj[key], opts, depth+1); })
                    .join(',' + (opts.spaceAfterComma?' ':'') + '\n');
                str += (opts.spaceInsideBraces?' ':'') + '\n' + indent + '}';
                if (opts.sameLineBraces) { str = str.replace(/\n\t*\{/g,'{'); }
            }

            if (str.length < opts.maxLength) { str = str.replace(/\n\t*/g,''); } // collapse short JSON sections
            if (/ \n/.test(str)) { str = str.replace(/ \n/g,'\n'); } // remove extraneous spaces
            if (/^{ +}/.test(str)) { str = str.replace(/^{ +}/,'{}'); } // collapse empty braces
            if (/^\[ +\]/.test(str)) { str = str.replace(/^\[ +\]/,'[]'); } // collapse empty brackets

            return str;

        default:
            str = JSON.stringify(obj);
  }

  return str;
}


text:
var bespin = require('bespin');
var console = require('bespin:console').console;
var Promise = require('bespin:promise').Promise;
var catalog = require('bespin:plugins').catalog;

var util = require('bespin:util/util');
var cookie = require('bespin:util/cookie');

exports.createServer = function(base_url) {
    exports.server = new exports.BespinServer(base_url);

    // start polling
    exports.server._poll();

    return exports.server;
};

exports.BespinServer = function(base_url) {
    this.base_url = base_url || '';
};

/**
 * The Server object implements the Bespin Server API (See
 * https://wiki.mozilla.org/BespinServerAPI) giving the client access to the
 * backend store. The FileSystem object uses this to talk back.
 */
exports.BespinServer.prototype = {
    // Stores the outstanding asynchronous tasks that we've submitted
    _jobs: {},

    _jobsCount: 0,

    // interval parameters
    _interval: {
        lo:   200,  // the lowest interval in ms
        hi:   5000, // the highest interval in ms
        step: 100,  // the change step in ms
        threshold: 3,    // number of response items
        current:   5000, // the current interval in ms
        handle:    null
    },

    /**
     * This is a nasty hack to call callback like onSuccess and if there is some
     * syntax problem to do something other than swallow the error
     */
    _callCallback: function(options, functionName, args) {
        if (util.isFunction(options[functionName])) {
            try {
                options[functionName].apply(null, args);
                return true;
            } catch (ex) {
                console.group('Error calling options.' + functionName + ' from server.request');
                console.log(options);
                console.log(options[functionName].toString());
                console.error(ex);
                console.trace();
                console.groupEnd();

                // If got an exception on success it's really a failure
                if (functionName == 'onSuccess' && util.isFunction(options.onFailure)) {
                    try {
                        options.onFailure({ responseText: ex.toString() });
                    } catch (ex2) {
                        console.group('Error calling options.onFailure from server.request');
                        console.error(ex2);
                        console.trace();
                        console.groupEnd();
                    }
                }
            }
        }

        return false;
    },

    /**
     * The core way to access the backend system.
     * Similar to the Prototype Ajax.Request wrapper
     * @param method is the HTTP method (GET|POST|PUT|DELETE)
     * @param url is the sub url to hit (after the base url)
     * @param payload is what to send up for POST requests
     * @param options is how you pass in various callbacks.
     *   options['evalJSON'] = true or false to auto eval
     *   options['onSuccess'] = the main success callback
     *   options['onFailure'] = call for general failures
     *   options['on' + STATUS CODE] = call for specific failures
     *   options['log'] = just log the following
     */
    request: function(method, url, payload, options) {
        var server = this;
        var xhr = new XMLHttpRequest();
        options = options || {};

        var pr = null;
        if (!options.onSuccess) {
            pr = new Promise();
        }

        var onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status && xhr.status !== 0 && (xhr.status >= 200 && xhr.status < 300)) {
                    var response = xhr.responseText;

                    if (options.evalJSON && response) {
                        try {
                            response = JSON.parse(response);
                        } catch (syntaxException) {
                            console.log('Couldn\'t eval the JSON: ' + response + ' (SyntaxError: ' + syntaxException + ')');
                        }
                    }

                    if (pr) {
                        pr.resolve(response);
                    } else {
                        var handled = server._callCallback(options, 'onSuccess', [ response, xhr ]);

                        if (!handled && options.log) {
                            console.log(options.log);
                        }
                    }
                } else {
                    if (pr) {
                        var error = new Error(xhr.responseText + ' (Status ' + xhr.status + ")");
                        error.xhr = xhr;
                        pr.reject(error);
                    } else {
                        handled = server._callCallback(options, 'on' + xhr.status, [ xhr ]);
                        if (!handled) {
                            server._callCallback(options, 'onFailure', [ xhr ]);
                        }
                    }
                }
            }
        };

        xhr.onreadystatechange = onreadystatechange;
        xhr.open(method, this.base_url + url, true); // url must have leading /

        this.protectXhrAgainstCsrf(xhr);

        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        if (options.headers) {
            for (var key in options.headers) {
                if (options.headers.hasOwnProperty(key)) {
                    xhr.setRequestHeader(key, options.headers[key]);
                }
            }
        }

        xhr.send(payload);
        return pr;
    },

    /**
     * There are 2 ways of doing CSRF protection, to get the token using
     * getAntiCsrfToken() and setting it into the request using the correct
     * header, or by just calling this function
     */
    protectXhrAgainstCsrf: function(xhr) {
        xhr.setRequestHeader('X-Domain-Token', this.getAntiCsrfToken());
    },

    /**
     * Provide the Anti CSRF token to anyone wanting to do XHR requests.
     * See also, the comments against protectXhrAgainstCsrf
     * @see protectXhrAgainstCsrf()
     */
    getAntiCsrfToken: function() {
        var token = cookie.get('Domain-Token');
        if (!token) {
            token = util.randomPassword();
            cookie.set('Domain-Token', token);
        }
        return token;
    },

    /**
     * As request() except that the response is fetched without a connection,
     * instead using the /messages URL
     */
    requestDisconnected: function(method, url, payload, options) {
        options = options || {};
        options.evalJSON = true;
        // The response that we get from the server isn't a 'done it' response
        // any more - it's just a 'working on it' response.
        options.originalOnSuccess = options.onSuccess;

        var pr = new Promise();
        options.promise = pr;

        var self = this;

        this.request(method, url, payload, options).then(function(response, xhr) {
            if (response.jobid == null) {
                console.error('Missing jobid', response);
                var error = new Error('Server returned ' + xhr.status);
                error.xhr = xhr;
                pr.reject(error);
                return;
            }

            if (response.taskname) {
                console.log('Server is running : ' + response.taskname);
            }

            self._jobs[response.jobid] = {
                jobid: response.jobid,
                options: options
            };
            self._jobsCount++;
            //self._checkPolling();
        });

        return pr;
    },

    /**
     * Do we need to set off another poll?
     */
    /*
    _checkPolling: function() {
        if (this._jobsCount == 0) {
            return;
        }
        if (this._timeout != null) {
            return;
        }

        this._poll();
    },
    */

    _processResponse: function(message) {
        if (!('jobid' in message)) {
            if ('msgtargetid' in message) {
                var target = catalog.getExtensionByKey(
                                'msgtargetid', message.msgtargetid);
                if (target) {
                    target.load(function (f) {
                        f(message);
                    });
                } else {
                    console.log('UNPROCESSED MSG FROM ' + message.from +
                        ' FOR ' + message.msgtargetid + ': ' + message.text);
                }
            } else {
                console.warn('Missing jobid in message', message);
            }
            return;
        }

        var job = this._jobs[message.jobid];
        if (!job) {
            console.debug('job unknown. page reload?', message, this);
            return;
        }

        // TODO: Errors come through with message.error=true, but we're not
        // currently doing anything with that. It's complicated by the
        // need for a partial error system, and the question about how we
        // treat messages that errored half way through
        if (message.asyncDone) {
            if (Array.isArray(job.partials)) {
                // We're done, and we've got outstanding messages
                // that we need to pass on. We aggregate the
                // messages and call originalOnSuccess
                job.partials.push(message.output);
                job.options.promise.resolve(job.partials.join('<br/>'));
            } else {
                // We're done, and all we have is what we've just
                // been sent, so just call originalOnSuccess
                job.options.promise.resolve(message.output);
            }
        }
        else {
            if (util.isFunction(job.options.onPartial)) {
                // In progress, and we have somewhere to send the
                // messages that we've just been sent
                job.options.onPartial(message.output);
            } else {
                if (util.none(job.partials)) {
                    job.partials = [];
                }

                // In progress, and no-where to send the messages,
                // so we store them for onSuccess when we're done
                job.partials.push(message.output);
            }
        }

        if (message.asyncDone) {
            if (this._jobsCount > 0) {
                this._jobsCount--;
            }
            delete this._jobs[message.jobid];
        }
    },

    /**
     * Starts up message retrieve for this user.
     */
    _poll: function(payload) {
        if (payload) {
            this._doPoll(payload);
            return;
        }
        // ask mobwrite
        var mobwriteInstance = catalog.getExtensions('mobwriteinstance');
        if (mobwriteInstance && mobwriteInstance.length) {
            // always use the first instance
            var self = this;
            mobwriteInstance[0].load(function (mobwrite) {
                self._doPoll(mobwrite.collect());
            });
            return;
        }
        // the default
        this._doPoll(null);
    },

    /**
     * Starts I/O for the message retrieval.
     */
    _doPoll: function(mobwritePayload) {
        /*
        if (mobwritePayload) {
            console.log('FROM mobwrite:\n' + mobwritePayload);
        }
        */
        var self = this;
        this.request('POST', '/messages/', mobwritePayload, {
            evalJSON: true
        }).then(function(messages) {
                var interval = self._interval;
                // kill the current timeout
                if (interval.handle) {
                    clearTimeout(interval.handle);
                    interval.handle = null;
                }

                // process all messagesf
                for (var i = 0; i < messages.length; i++) {
                    self._processResponse(messages[i]);
                }

                // schedule next poll, if not scheduled yet
                if (!interval.handle) {
                    self._schedulePoll(messages.length);
                }
            },
            function(message) {
                self._processResponse(message);
                self._schedulePoll(0);
            }
        );
    },

    /**
     * Schedules the next poll.
     */
    _schedulePoll: function(n) {
        var self = this;
        var interval = this._interval;
        var current  = interval.current;
        // kill the current timeout
        if (interval.handle) {
            clearTimeout(interval.handle);
            interval.handle = null;
        }
        // do we need to update the polling interval?
        if (n <= 1) {
            // we got nothing: poll less frequently
            current += interval.step;
        } else if (n >= interval.threshold) {
            // we got a lot: poll more frequently
            current = current / n * interval.threshold;
        }
        // clip new interval, and make sure that number of ms is whole
        current = Math.min(interval.hi, Math.max(interval.lo, Math.ceil(current)));
        // save new polling interval
        interval.current = current;
        // schedule the next poll
        interval.handle = setTimeout(function() {
            self._poll();
        }, current);
    },

    /**
     * Schedule the next poll.
     */
    schedulePoll: function (ms, payload) {
        var self = this;
        var interval = this._interval;
        if (typeof ms == 'number' && (!interval.handle || ms < interval.current)) {
            // kill the current timeout
            if (interval.handle) {
                clearTimeout(interval.handle);
                interval.handle = null;
            }
            // save new polling interval
            interval.current = Math.max(ms, 0);
            // schedule the next poll
            interval.handle = setTimeout(function() {
                self._poll(payload);
            }, ms);
        }
    }
};


text:
package TAPL2.FullEquiRec

import TAPL2.Lib._
import TAPL2.FullSimple.FullSimple

case class TyVar(i: String) extends Ty

case class TyRecord(els: List[(String, Ty)]) extends Ty

case class TyArr(t1: Ty, t2: Ty) extends Ty

case object TyNat extends Ty

case class TyVariant(els: List[(String, Ty)]) extends Ty

case object TyBool extends Ty

case object TyString extends Ty

case object TyFloat extends Ty

case object TyUnit extends Ty

case class TyRec(id: String, ty: Ty) extends Ty

case object TmTrue extends Term

case object TmFalse extends Term

case class TmIf(cond: Term, t1: Term, t2: Term) extends Term

case class TmVar(i: String) extends Term

case class TmString(s: String) extends Term

case class TmAscribe(t: Term, ty: Ty) extends Term

case class TmRecord(fields: List[(String, Term)]) extends Term

case class TmProj(t: Term, proj: String) extends Term

case class TmAbs(v: String, ty: Ty, t: Term) extends Term

case class TmApp(t1: Term, t2: Term) extends Term

case object TmZero extends Term

case class TmSucc(t: Term) extends Term

case class TmPred(t: Term) extends Term

case class TmIsZero(t: Term) extends Term

case class TmInert(ty: Ty) extends Term

case class TmCase(sel: Term, branches: List[(String, String, Term)]) extends Term

case class TmTag(tag: String, t: Term, ty: Ty) extends Term

case class TmLet(l: String, t1: Term, t2: Term) extends Term

case object TmUnit extends Term

case class TmFix(t: Term) extends Term

object RecType {

  trait Parser extends TParser {
    lexical.reserved += "Rec"
    lexical.delimiters += "."

    val pRecTypeT: PackratParser[Ty] = "Rec" ~> ucid ~ ("." ~> pT) ^^ { case x ~ ty => TyRec(x, ty) }
  }

}

object FullEquiRec {

  trait Parser extends FullSimple.Parser with RecType.Parser {

    val pFullEquiRecE: PackratParser[Term] = pFullSimpleE
    val pFullEquiRecT: PackratParser[Ty] = pFullSimpleT ||| pRecTypeT

    override val pE: PackratParser[Term] = pFullEquiRecE
    override val pT: PackratParser[Ty] = pFullEquiRecT
  }

}

object TestFullEquiRec {

  def parseAndPrint(inp: String): Unit = {
    val p = new FullEquiRec.Parser {}
    println(parse(p.pE)(inp))
  }

}


text:
<?php

namespace Laminas\Db\Sql\Ddl\Column;

use Laminas\Db\Sql\Ddl\Constraint\ConstraintInterface;

use function array_merge;

class Column implements ColumnInterface
{
    /** @var null|string|int */
    protected $default;

    /** @var bool */
    protected $isNullable = false;

    /** @var string */
    protected $name = '';

    /** @var array */
    protected $options = [];

    /** @var ConstraintInterface[] */
    protected $constraints = [];

    /** @var string */
    protected $specification = '%s %s';

    /** @var string */
    protected $type = 'INTEGER';

    /**
     * @param null|string $name
     * @param bool        $nullable
     * @param mixed|null  $default
     * @param mixed[]     $options
     */
    public function __construct($name = null, $nullable = false, $default = null, array $options = [])
    {
        $this->setName($name);
        $this->setNullable($nullable);
        $this->setDefault($default);
        $this->setOptions($options);
    }

    /**
     * @param  string $name
     * @return self Provides a fluent interface
     */
    public function setName($name)
    {
        $this->name = (string) $name;
        return $this;
    }

    /**
     * @return null|string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param  bool $nullable
     * @return self Provides a fluent interface
     */
    public function setNullable($nullable)
    {
        $this->isNullable = (bool) $nullable;
        return $this;
    }

    /**
     * @return bool
     */
    public function isNullable()
    {
        return $this->isNullable;
    }

    /**
     * @param  null|string|int $default
     * @return self Provides a fluent interface
     */
    public function setDefault($default)
    {
        $this->default = $default;
        return $this;
    }

    /**
     * @return null|string|int
     */
    public function getDefault()
    {
        return $this->default;
    }

    /**
     * @param  array $options
     * @return self Provides a fluent interface
     */
    public function setOptions(array $options)
    {
        $this->options = $options;
        return $this;
    }

    /**
     * @param  string $name
     * @param  string $value
     * @return self Provides a fluent interface
     */
    public function setOption($name, $value)
    {
        $this->options[$name] = $value;
        return $this;
    }

    /**
     * @return array
     */
    public function getOptions()
    {
        return $this->options;
    }

    /**
     * @return self Provides a fluent interface
     */
    public function addConstraint(ConstraintInterface $constraint)
    {
        $this->constraints[] = $constraint;

        return $this;
    }

    /**
     * @return array
     */
    public function getExpressionData()
    {
        $spec = $this->specification;

        $params   = [];
        $params[] = $this->name;
        $params[] = $this->type;

        $types = [self::TYPE_IDENTIFIER, self::TYPE_LITERAL];

        if (! $this->isNullable) {
            $spec .= ' NOT NULL';
        }

        if ($this->default !== null) {
            $spec    .= ' DEFAULT %s';
            $params[] = $this->default;
            $types[]  = self::TYPE_VALUE;
        }

        $data = [
            [
                $spec,
                $params,
                $types,
            ],
        ];

        foreach ($this->constraints as $constraint) {
            $data[] = ' ';
            $data   = array_merge($data, $constraint->getExpressionData());
        }

        return $data;
    }
}


text:
import THREE = require('three');

import Scene = THREE.Scene;
import WebGLRenderTarget = THREE.WebGLRenderTarget;
import Camera = THREE.Camera;
import PerspectiveCamera = THREE.PerspectiveCamera;
import Renderer = THREE.Renderer;
import WebGLRenderer = THREE.WebGLRenderer;
import View = require("./view");
import ShaderData = require("../data/shader_data");
/**
 * Created by kevin.mayo on 2/13/2017.
 */

class RenderView extends View {

  renderBuffer: WebGLRenderTarget;
  renderScene: Scene;
  camera: Camera;
  canvas: HTMLCanvasElement;
  shaderData: ShaderData;
  loaded: boolean = false;
  renderer: WebGLRenderer;

  scene: Scene;

  constructor() {
    super();

    this.camera = new PerspectiveCamera(70, window.innerWidth, window.innerHeight);

    this.renderBuffer = new WebGLRenderTarget(200, 200, {
      minFilter: THREE.LinearFilter,
      magFilter: THREE.NearestFilter,
      format: THREE.RGBFormat
    });
    this.renderScene = new Scene();

  }

  onResize(width: number, height: number): void {
    super.onResize(width, height);

    this.renderer.setPixelRatio(window.devicePixelRatio);
    this.renderer.setSize(width, height);

  }

  draw(time: number): void {
    super.draw(time);

    this.renderer.clear();
    this.renderer.render(this.renderScene, this.camera, this.renderBuffer, true);

    this.renderer.render(this.scene, this.camera);
  }
}

export = RenderView;


text:
Change Log
===

v3.0.0
---
* **BREAKING CHANGES**
  * [enhancement] Upgraded to tslint@5

v2.1.0
---
* [new-fixer] `jasmine-no-lambda-expression-callbacks`
* [new-fixer] `import-barrels`
* [new-rule-option] `fixWithExplicitBarrelImport` added to `import-barrels`
* [enhancement] Added preliminary checks for `jasmine-no-lambda-expression-callbacks` rule to skip walking file if there are no jasmine
top-level statements.

v2.0.0
---
* **BREAKING CHANGES**
  * [enhancement] Upgraded to tslint@4

v1.0.0
---
* [new-rule] `import-barrels` rule added
* [new-rule] `jasmine-no-lambda-expression-callbacks` rule added


text:
package com.linecorp.armeria.server.logging.structured;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;

import com.linecorp.armeria.common.RequestContext;
import com.linecorp.armeria.common.logging.RequestLog;
import com.linecorp.armeria.common.util.TextFormatter;

/**
 * A representation and constructor of a service log which holds only very common fields that are protocol
 * agnostic.
 */
public abstract class StructuredLog {
    private final long timestampMillis;
    private final long responseTimeNanos;
    private final long requestSize;
    private final long responseSize;

    /**
     * Creates a new instance.
     */
    protected StructuredLog(long timestampMillis, long responseTimeNanos, long requestSize, long responseSize) {
        this.timestampMillis = timestampMillis;
        this.responseTimeNanos = responseTimeNanos;
        this.requestSize = requestSize;
        this.responseSize = responseSize;
    }

    /**
     * Constructs {@link StructuredLog} from {@link RequestContext} and {@link RequestLog}.
     * Can be used as {@link StructuredLogBuilder}.
     */
    protected StructuredLog(RequestLog reqLog) {
        timestampMillis = reqLog.requestStartTimeMillis();
        responseTimeNanos = reqLog.totalDurationNanos();

        requestSize = reqLog.requestLength();
        responseSize = reqLog.responseLength();
    }

    /**
     * Returns the timestamp in ms of the time that the request has been received.
     *
     * @return timestamp in ms of the time the request received
     */
    @JsonProperty
    public long timestampMillis() {
        return timestampMillis;
    }

    /**
     * Returns the duration in ms of the time that is taken to process the request.
     *
     * @return duration in ns that was taken to process the request
     */
    @JsonProperty
    public long responseTimeNanos() {
        return responseTimeNanos;
    }

    /**
     * Returns the size of request payload.
     *
     * @return size of the request payload in bytes
     */
    @JsonProperty
    public long requestSize() {
        return requestSize;
    }

    /**
     * Returns the size of response payload.
     *
     * @return size of the response payload in bytes
     */
    @JsonProperty
    public long responseSize() {
        return responseSize;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                          .add("timestamp", TextFormatter.epoch(timestampMillis))
                          .add("responseTime", TextFormatter.elapsed(responseTimeNanos))
                          .add("requestSize", TextFormatter.size(requestSize))
                          .add("responseSize", TextFormatter.size(responseSize))
                          .toString();
    }
}


text:
<?php

namespace casamunoz\empresaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Factura
 *
 * @ORM\Table(name="factura", indexes={@ORM\Index(name="IDX_F9EBA0097A663008", columns={"emp_id"}), @ORM\Index(name="IDX_F9EBA009476C47F6", columns={"tip_id"})})
 * @ORM\Entity
 */
class Factura
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="factura_id_seq", allocationSize=1, initialValue=1)
     */
    private $id;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="fecha_factura", type="date", nullable=false)
     */
    private $fechaFactura;

    /**
     * @var string
     *
     * @ORM\Column(name="monto_total", type="decimal", precision=8, scale=2, nullable=false)
     */
    private $montoTotal;

    /**
     * @var \Empleado
     *
     * @ORM\ManyToOne(targetEntity="Empleado")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="emp_id", referencedColumnName="id")
     * })
     */
    private $emp;

    /**
     * @var \TipoPago
     *
     * @ORM\ManyToOne(targetEntity="TipoPago")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="tip_id", referencedColumnName="id")
     * })
     */
    private $tip;

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

    /**
     * Set fechaFactura
     *
     * @param \DateTime $fechaFactura
     * @return Factura
     */
    public function setFechaFactura($fechaFactura)
    {
        $this->fechaFactura = $fechaFactura;

        return $this;
    }

    /**
     * Get fechaFactura
     *
     * @return \DateTime
     */
    public function getFechaFactura()
    {
        return $this->fechaFactura;
    }

    /**
     * Set montoTotal
     *
     * @param string $montoTotal
     * @return Factura
     */
    public function setMontoTotal($montoTotal)
    {
        $this->montoTotal = $montoTotal;

        return $this;
    }

    /**
     * Get montoTotal
     *
     * @return string
     */
    public function getMontoTotal()
    {
        return $this->montoTotal;
    }

    /**
     * Set emp
     *
     * @param \casamunoz\empresaBundle\Entity\Empleado $emp
     * @return Factura
     */
    public function setEmp(\casamunoz\empresaBundle\Entity\Empleado $emp = null)
    {
        $this->emp = $emp;

        return $this;
    }

    /**
     * Get emp
     *
     * @return \casamunoz\empresaBundle\Entity\Empleado
     */
    public function getEmp()
    {
        return $this->emp;
    }

    /**
     * Set tip
     *
     * @param \casamunoz\empresaBundle\Entity\TipoPago $tip
     * @return Factura
     */
    public function setTip(\casamunoz\empresaBundle\Entity\TipoPago $tip = null)
    {
        $this->tip = $tip;

        return $this;
    }

    /**
     * Get tip
     *
     * @return \casamunoz\empresaBundle\Entity\TipoPago
     */
    public function getTip()
    {
        return $this->tip;
    }
}


text:
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace dwCheckApi.Entities
{
    public class Character : BaseAuditClass
    {
        public int CharacterId { get; set; }
        public string CharacterName { get; set; }
        public virtual ICollection<BookCharacter> BookCharacter { get; set; } = new Collection<BookCharacter>();
    }
}


text:
package pl.touk.sputnik.processor.sonar;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import pl.touk.sputnik.review.ReviewResult;
import pl.touk.sputnik.review.Severity;
import pl.touk.sputnik.review.Violation;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;

/**
 * Parses a json file produced by a run of Sonar.
 */
@Slf4j
@AllArgsConstructor
class SonarResultParser {

    private final File resultFile;

    /**
     * A component in the result file is identified by a key.
     * It may reference another component by its key (called moduleKey).
     */
    @AllArgsConstructor
    private static class Component {
        public String path;
        public String moduleKey;
    }

    /**
     * Parses the file and returns all the issues as a ReviewResult.
     */
    public ReviewResult parseResults() throws IOException {
        ReviewResult result = new ReviewResult();
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(new FileReader(resultFile));
        JsonNode issues = rootNode.path("issues");
        Iterator<JsonNode> issuesIterator = issues.iterator();
        Map<String, Component> components = getComponents(rootNode.path("components"));

        while (issuesIterator.hasNext()) {
            JsonNode issue = issuesIterator.next();
            boolean isNew = issue.path("isNew").asBoolean();
            if (!isNew) {
                log.debug("Skipping already indexed issue: {}", issue.toString());
                continue;
            }
            JsonNode lineNode = issue.path("line");
            if (lineNode.isMissingNode()) {
                log.debug("Skipping an issue with no line information: {}", issue.toString());
                continue;
            }
            int line = lineNode.asInt();
            String message = issue.path("message").asText();
            String file = getIssueFilePath(issue.path("component").asText(), components);
            String severity = issue.path("severity").asText();
            String rule = issue.path("rule").asText();
            result.add(new Violation(file, line, String.format("%s (Rule: %s)", message, rule), getSeverity(severity)));
        }
        return result;
    }

    /**
     * Converts a Sonar severity to a Sputnik severity.
     * @param severityName severity to convert.
     */
    static Severity getSeverity(String severityName) {
        switch (severityName) {
        case "BLOCKER":
        case "CRITICAL":
        case "MAJOR":
            return Severity.ERROR;
        case "MINOR":
            return Severity.WARNING;
        case "INFO":
            return Severity.INFO;
        default:
          log.warn("Unknown severity: " + severityName);
        }
        return Severity.WARNING;
    }

    /**
     * Extracts all the components from the json data.
     */
    private Map<String, Component> getComponents(JsonNode componentsNode) {
        Iterator<JsonNode> it = componentsNode.iterator();
        Map<String, Component> components = Maps.newHashMap();

        while(it.hasNext()){
            JsonNode componentNode = it.next();
            JsonNode pathNode = componentNode.path("path");
            JsonNode moduleNode = componentNode.path("moduleKey");
            components.put(componentNode.path("key").asText(),
                    new Component(pathNode.asText(), moduleNode.isMissingNode()?null:moduleNode.asText()));
        }

        return components;
    }

    /**
     * Returns the path of the file linked to an issue created by Sonar.
     * The path is relative to the folder where Sonar has been run.
     *
     * @param issueComponent "component" field in an issue.
     * @param components information about all components.
     */
    private String getIssueFilePath(String issueComponent, Map<String, Component> components) {
        Component comp = components.get(issueComponent);
        String file = comp.path;
        if (!Strings.isNullOrEmpty(comp.moduleKey)) {
            String theKey = comp.moduleKey;
            while (!theKey.isEmpty()) {
                Component theChildComp = components.get(theKey);

                int p = theKey.lastIndexOf(":");
                if (p > 0) {
                    theKey = theKey.substring(0, p);
                } else {
                    theKey = "";
                }

                if (theChildComp != null && !Strings.isNullOrEmpty(theChildComp.path)) {
                    file = theChildComp.path + '/' + file;
                }
            }
        }
        return file;
    }
}


text:
bool pointer_null_size_zero_function_called = false;
bool pointer_null_size_max_function_called = false;
bool pointer_null_size_valid_function_called = false;
bool pointer_valid_size_zero_function_called = false;
bool pointer_valid_size_max_function_called = false;
bool pointer_valid_size_valid_function_called = false;

static void pointer_null_size_zero_function(int value)
{
    if (value == EXIT_FAILURE)
    {
        pointer_null_size_zero_function_called = true;
    }
}

static void pointer_null_size_max_function(int value)
{
    if (value == EXIT_FAILURE)
    {
        pointer_null_size_max_function_called = true;
    }
}

static void pointer_null_size_valid_function(int value)
{
    if (value == EXIT_FAILURE)
    {
        pointer_null_size_valid_function_called = true;
    }
}

static void pointer_valid_size_zero_function(int value)
{
    if (value == EXIT_FAILURE)
    {
        pointer_valid_size_zero_function_called = true;
    }
}

static void pointer_valid_size_max_function(int value)
{
    if (value == EXIT_FAILURE)
    {
        pointer_valid_size_max_function_called = true;
    }
}

static void pointer_valid_size_valid_function(int value)
{
    if (value == EXIT_FAILURE)
    {
        pointer_valid_size_valid_function_called = true;
    }
}

Test(el_custom_realloc, pointer_null_size_zero_triggers_function)
{
    void *pointer = NULL;
    el_handlers handlers = el_default_handlers();
    handlers.error_function = pointer_null_size_zero_function;

    cr_assert_not(pointer_null_size_zero_function_called);
    pointer = el_custom_realloc(pointer, 0, handlers);
    cr_assert(pointer_null_size_zero_function_called);

    el_free(pointer);
}

Test(el_custom_realloc, pointer_null_size_max_triggers_function)
{
    void *pointer = NULL;
    el_handlers handlers = el_default_handlers();
    handlers.error_function = pointer_null_size_max_function;

    cr_assert_not(pointer_null_size_max_function_called);
    pointer = el_custom_realloc(pointer, SIZE_MAX, handlers);
    cr_assert(pointer_null_size_max_function_called);

    el_free(pointer);
}

Test(el_custom_realloc, pointer_null_size_valid_not_triggers_function)
{
    void *pointer = NULL;
    el_handlers handlers = el_default_handlers();
    handlers.error_function = pointer_null_size_valid_function;

    cr_assert_not(pointer_null_size_valid_function_called);
    pointer = el_custom_realloc(pointer, 100, handlers);
    cr_assert_not(pointer_null_size_valid_function_called);

    el_free(pointer);
}

Test(el_custom_realloc, pointer_valid_size_zero_triggers_function)
{
    void *pointer = el_malloc(10);
    el_handlers handlers = el_default_handlers();
    handlers.error_function = pointer_valid_size_zero_function;

    cr_assert_not(pointer_valid_size_zero_function_called);
    pointer = el_custom_realloc(pointer, 0, handlers);
    cr_assert(pointer_valid_size_zero_function_called);

    el_free(pointer);
}

Test(el_custom_realloc, pointer_valid_size_max_triggers_function)
{
    void *pointer = el_malloc(10);
    el_handlers handlers = el_default_handlers();
    handlers.error_function = pointer_valid_size_max_function;

    cr_assert_not(pointer_valid_size_max_function_called);
    pointer = el_custom_realloc(pointer, SIZE_MAX, handlers);
    cr_assert(pointer_valid_size_max_function_called);

    el_free(pointer);
}

Test(el_custom_realloc, pointer_valid_size_valid_not_triggers_function)
{
    void *pointer = el_malloc(10);
    el_handlers handlers = el_default_handlers();
    handlers.error_function = pointer_valid_size_valid_function;

    cr_assert_not(pointer_valid_size_valid_function_called);
    pointer = el_custom_realloc(pointer, 100, handlers);
    cr_assert_not(pointer_valid_size_valid_function_called);

    el_free(pointer);
}

Test(el_custom_realloc, handlers_out_stream_null)
{
    void *pointer = el_malloc(10);
    el_handlers handlers = el_default_handlers();
    handlers.out_stream = NULL;

    pointer = el_custom_realloc(pointer, 100, handlers);
    el_free(pointer);
}

Test(el_custom_realloc, handlers_error_stream_null)
{
    void *pointer = el_malloc(10);
    el_handlers handlers = el_default_handlers();
    handlers.error_stream = NULL;

    pointer = el_custom_realloc(pointer, 100, handlers);
    el_free(pointer);
}

Test(el_custom_realloc, handlers_error_function_null)
{
    void *pointer = el_malloc(10);
    el_handlers handlers = el_default_handlers();
    handlers.error_function = NULL;

    pointer = el_custom_realloc(pointer, 100, handlers);
    el_free(pointer);
}

Test(el_custom_realloc, handlers_all_null)
{
    void *pointer = el_malloc(10);
    pointer = el_custom_realloc(pointer, 100, el_null_handlers());
    el_free(pointer);
}


text:
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  validates_presence_of :email, :name, :password, on: :create
  validates :email, uniqueness: true
end


text:
const assert = require('assert')

describe('env', () => {
  it('ensure env is test', async () => {
    assert.equal(process.env.NODE_ENV, 'test', 'the env is set to test')
  })
})


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Threading;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
    internal sealed class VSTypeScriptGoToSymbolContext
    {
        internal DefinitionItem? DefinitionItem;

        internal VSTypeScriptGoToSymbolContext(Document document, int position, CancellationToken cancellationToken)
        {
            Document = document;
            Position = position;
            CancellationToken = cancellationToken;
        }

        public Document Document { get; }
        public int Position { get; }
        public CancellationToken CancellationToken { get; }

        public TextSpan Span { get; set; }

        public void AddItem(string key, VSTypeScriptDefinitionItem item)
        {
            _ = key;
            this.DefinitionItem = item.UnderlyingObject;
        }
    }
}


text:
layout: page
title: Scholar Sky Group Dinner
date: 2016-05-24
author: Doris Stout
tags: weekly links, java
status: published
summary: Proin vel leo leo. Morbi ut aliquam ipsum, ac pretium.
banner: images/banner/people.jpg
booking:
  startDate: 02/13/2016
  endDate: 02/18/2016
  ctyhocn: STLFVHX
  groupCode: SSGD
published: true
---
Aenean faucibus, nibh nec dictum elementum, sapien magna suscipit diam, ut molestie eros mauris nec ipsum. In in tortor dictum, cursus magna at, iaculis urna. Maecenas ornare justo erat, eu eleifend nulla viverra quis. Duis viverra commodo tempus. Proin volutpat pellentesque dolor vel mattis. Nulla purus ante, lacinia vel diam at, dapibus scelerisque elit. In feugiat fringilla rutrum. Vivamus erat quam, gravida ac ligula ut, vestibulum vulputate nisl. Nullam vel urna felis. Nulla ut quam eu nunc gravida posuere in id nibh. Maecenas eget libero justo. Nam a justo diam. Nam mollis varius dapibus.

* Ut ac metus interdum, tempor nisl eu, cursus arcu
* Vestibulum posuere dui eget libero luctus, tempus vulputate purus aliquet
* Aliquam varius massa id libero sodales laoreet
* Suspendisse aliquet nulla a elementum placerat
* Vivamus commodo purus eu leo maximus mattis.

Nulla posuere volutpat tincidunt. Morbi tellus ante, maximus vitae porta vel, eleifend ac mi. Donec congue sodales auctor. Cras gravida eget leo non pulvinar. Ut erat velit, finibus eget tortor et, pulvinar vehicula risus. Morbi imperdiet venenatis urna eu iaculis. Cras eu finibus nisi. In nec volutpat odio. Vivamus fermentum ac sapien non iaculis.


text:
import { Color } from './../math/Color';
import { Object3D } from './../core/Object3D';
import { DirectionalLightShadow } from './DirectionalLightShadow';
import { Light } from './Light';

/**
 * Affects objects using MeshLambertMaterial or MeshPhongMaterial.
 *
 * @example
 * // White directional light at half intensity shining from the top.
 * var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
 * directionalLight.position.set( 0, 1, 0 );
 * scene.add( directionalLight );
 *
 * @see src/lights/DirectionalLight.js
 */
export class DirectionalLight extends Light {

	constructor( color?: Color | string | number, intensity?: number );

	/**
	 * Target used for shadow camera orientation.
	 */
	target: Object3D;

	/**
	 * Light's intensity.
	 * Default — 1.0.
	 */
	intensity: number;

	shadow: DirectionalLightShadow;

}


text:
package org.spongepowered.api.world.gen.populator;

import org.spongepowered.api.Sponge;
import org.spongepowered.api.data.manipulator.mutable.MobSpawnerData;
import org.spongepowered.api.entity.EntityArchetype;
import org.spongepowered.api.item.inventory.ItemStackSnapshot;
import org.spongepowered.api.util.ResettableBuilder;
import org.spongepowered.api.util.weighted.LootTable;
import org.spongepowered.api.util.weighted.VariableAmount;
import org.spongepowered.api.util.weighted.WeightedTable;
import org.spongepowered.api.world.gen.Populator;

import java.util.Optional;

import javax.annotation.Nullable;

/**
 * Represents a {@link Populator} which places 'Dungeon's randomly underground. Each dungeon has
 * some associated MobSpawnerData, and data regarding the contents of any chests
 * generated within the dungeon.
 */
public interface Dungeon extends Populator {

    /**
     * Creates a new {@link Builder} to build a {@link Dungeon} populator.
     *
     * @return The new builder
     */
    static Builder builder() {
        return Sponge.getRegistry().createBuilder(Builder.class);
    }

    /**
     * Gets the number of attempts at randomly spawning a generator per chunk.
     *
     * @return The number of attempts
     */
    VariableAmount getAttemptsPerChunk();

    /**
     * Sets the number of attempts at randomly spawning a generator per chunk.
     *
     * @param attempts The new number of attempts
     */
    void setAttemptsPerChunk(VariableAmount attempts);

    /**
     * Sets the number of attempts at randomly spawning a generator per chunk.
     *
     * @param attempts The new number of attempts
     */
    default void setAttemptsPerChunk(int attempts) {
        setAttemptsPerChunk(VariableAmount.fixed(attempts));
    }

    /**
     *
Gets the {@link MobSpawnerData} which represents the MobSpawner which
     * will be created within the dungeon.

     *
     *
Note:  Only one of choices or mob spawner data
     * will be present.

     *
     * @return The mob spawner data, if present
     */
    Optional<MobSpawnerData> getMobSpawnerData();

    /**
     *
Sets {@link MobSpawnerData} which will be used to create the spawner
     * within the dungeon.

     *
     *
Note:  Only one of choices or mob spawner data
     * will be present.

     * @param data MobSpawnerData to use
     */
    void setMobSpawnerData(MobSpawnerData data);

    /**
     *
Gets a weighted collection of possible
     * {@link EntityArchetype}s that could be spawned. One type is chosen when
     * creating the dungeon, for more complex spawners see
     * {@link #getMobSpawnerData()}.

     *
     *
Note:  Only one of choices or mob spawner data
     * will be present.

     *
     * @return Weighted table of possible types, if present
     */
    Optional<WeightedTable<EntityArchetype>> getChoices();

    /**
     *
Sets the possible {@link EntityArchetype}s that could be spawned.
     * One type is chosen when creating the dungeon, for more complex
     * spawners see {@link #setMobSpawnerData(MobSpawnerData)}

     *
     *
Note:  Only one of choices or mob spawner data
     * will be present.

     *
     * @param choices Weighted table of possible types
     */
    void setChoices(WeightedTable<EntityArchetype> choices);

    /**
     * Gets a mutable weighted collection of possible contents of the chests.
     * Items will be randomly selected from this list based on weight in order
     * to calculate the contents of chests placed within the dungeon.
     *
     * @return The contents list
     */
    LootTable<ItemStackSnapshot> getPossibleContents();

    /**
     * A builder for constructing {@link Dungeon} populators.
     */
    interface Builder extends ResettableBuilder<Dungeon, Builder> {

        /**
         * Sets the number of attempts at randomly spawning a generator per
         * chunk.
         *
         * @param attempts The new number of attempts
         * @return This builder, for chaining
         */
        Builder attempts(VariableAmount attempts);

        /**
         * Sets the number of attempts at randomly spawning a generator per
         * chunk.
         *
         * @param attempts The new number of attempts
         * @return This builder, for chaining
         */
        default Builder attempts(int attempts) {
            return attempts(VariableAmount.fixed(attempts));
        }

        /**
         *
Sets {@link MobSpawnerData} that will be used to create the spawner
         * within the dungeon.

         *
         *
Note:  Only one of choices or mob spawner data
         * will be present.

         * @param data MobSpawnerData to use
         * @return This builder, for chaining
         */
        Builder mobSpawnerData(MobSpawnerData data);

        /**
         *
Sets the possible {@link EntityArchetype}s that could be spawned.
         * One type is chosen when creating the dungeon, for more complex
         * spawners see {@link #mobSpawnerData(MobSpawnerData)}}

         *
         *
To use the default set of choices, pass null instead
         * of a table.

         *
         *
Note:  Only one of choices or mob spawner data
         * will be present.

         *
         * @param choices Weighted table of possible types
         * @return This builder, for chaining
         */
        Builder choices(@Nullable WeightedTable<EntityArchetype> choices);

        /**
         * Defines a {@link LootTable} of {@link ItemStackSnapshot}s from which
         * items will be randomly selected based on weight in order to calculate
         * the contents of chests placed within the dungeon.
         *
         * @param items The possible items
         * @return This builder, for chaining
         */
        Builder possibleItems(LootTable<ItemStackSnapshot> items);

        /**
         * Builds a new instance of a {@link Dungeon} populator with the
         * settings set within the builder.
         *
         * @return A new instance of the populator
         * @throws IllegalStateException If there are any settings left unset
         *         which do not have default values
         */
        Dungeon build() throws IllegalStateException;

    }
}


text:
Sign up

		<form name="userForm" data-ng-submit="signup()" class="signin form-horizontal" novalidate autocomplete="off">
			<fieldset>

					Username
					<input type="text" id="username" name="username" class="form-control" data-ng-model="credentials.username" placeholder="Username">

					Password
					<input type="password" id="password" name="password" class="form-control" data-ng-model="credentials.password" placeholder="Password">

                    Retype Password
                    <input type="password" id="passwordCtrl" name="passwordCtrl" class="form-control" data-ng-model="credentials.passwordCtrl" placeholder="Retype Password">

					<button type="submit" class="btn btn-large btn-primary">Sign up</button>  or
					Sign in

			</fieldset>
		</form>


text:
package org.apache.flink.table.types.inference;

import org.apache.flink.annotation.Internal;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.inference.strategies.CommonTypeStrategy;
import org.apache.flink.table.types.inference.strategies.ExplicitTypeStrategy;
import org.apache.flink.table.types.inference.strategies.FirstTypeStrategy;
import org.apache.flink.table.types.inference.strategies.MappingTypeStrategy;
import org.apache.flink.table.types.inference.strategies.MatchFamilyTypeStrategy;
import org.apache.flink.table.types.inference.strategies.MissingTypeStrategy;
import org.apache.flink.table.types.inference.strategies.NullableTypeStrategy;
import org.apache.flink.table.types.inference.strategies.UseArgumentTypeStrategy;
import org.apache.flink.table.types.inference.strategies.VaryingStringTypeStrategy;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.LogicalTypeFamily;
import org.apache.flink.table.types.logical.LogicalTypeRoot;

import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;

import static org.apache.flink.table.types.utils.TypeConversions.fromLogicalToDataType;

/**
 * Strategies for inferring an output or accumulator data type of a function call.
 *
 * @see TypeStrategy
 */
@Internal
public final class TypeStrategies {

    /** Placeholder for a missing type strategy. */
    public static final TypeStrategy MISSING = new MissingTypeStrategy();

    /** Type strategy that returns a common, least restrictive type of all arguments. */
    public static final TypeStrategy COMMON = new CommonTypeStrategy();

    /** Type strategy that returns a fixed {@link DataType}. */
    public static TypeStrategy explicit(DataType dataType) {
        return new ExplicitTypeStrategy(dataType);
    }

    /** Type strategy that returns the n-th input argument. */
    public static TypeStrategy argument(int pos) {
        return new UseArgumentTypeStrategy(pos);
    }

    /** Type strategy that returns the first type that could be inferred. */
    public static TypeStrategy first(TypeStrategy... strategies) {
        return new FirstTypeStrategy(Arrays.asList(strategies));
    }

    /** Type strategy that returns the given argument if it is of the same logical type family. */
    public static TypeStrategy matchFamily(int argumentPos, LogicalTypeFamily family) {
        return new MatchFamilyTypeStrategy(argumentPos, family);
    }

    /**
     * Type strategy that maps an {@link InputTypeStrategy} to a {@link TypeStrategy} if the input
     * strategy infers identical types.
     */
    public static TypeStrategy mapping(Map<InputTypeStrategy, TypeStrategy> mappings) {
        return new MappingTypeStrategy(mappings);
    }

    /**
     * A type strategy that can be used to make a result type nullable if any of the selected input
     * arguments is nullable. Otherwise the type will be not null.
     */
    public static TypeStrategy nullable(
            ConstantArgumentCount includedArgs, TypeStrategy initialStrategy) {
        return new NullableTypeStrategy(includedArgs, initialStrategy);
    }

    /**
     * A type strategy that can be used to make a result type nullable if any of the input arguments
     * is nullable. Otherwise the type will be not null.
     */
    public static TypeStrategy nullable(TypeStrategy initialStrategy) {
        return nullable(ConstantArgumentCount.any(), initialStrategy);
    }

    /**
     * A type strategy that ensures that the result type is either {@link LogicalTypeRoot#VARCHAR}
     * or {@link LogicalTypeRoot#VARBINARY} from their corresponding non-varying roots.
     */
    public static TypeStrategy varyingString(TypeStrategy initialStrategy) {
        return new VaryingStringTypeStrategy(initialStrategy);
    }

    /**
     * Type strategy specific for aggregations that partially produce different nullability
     * depending whether the result is grouped or not.
     */
    public static TypeStrategy aggArg0(
            Function<LogicalType, LogicalType> aggType, boolean nullableIfGroupingEmpty) {
        return callContext -> {
            final DataType argDataType = callContext.getArgumentDataTypes().get(0);
            final LogicalType argType = argDataType.getLogicalType();
            LogicalType result = aggType.apply(argType);
            if (nullableIfGroupingEmpty && !callContext.isGroupedAggregation()) {
                // null only if condition is met, otherwise arguments nullability
                result = result.copy(true);
            } else if (!nullableIfGroupingEmpty) {
                // never null
                result = result.copy(false);
            }
            return Optional.of(fromLogicalToDataType(result));
        };
    }

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

    @SuppressWarnings("BooleanMethodIsAlwaysInverted")
    private TypeStrategies() {
        // no instantiation
    }
}


text:
            <form form ng-controller="AnswerController" ng-submit="upVote(answer)">

                    <button type="submit" class="btn btn-default">

                    </button>

            </form>

                    {{answer.vote}}

            <form form ng-controller="AnswerController" ng-submit="downVote(answer)">

                    <button type="submit" class="btn btn-default">

                    </button>

            </form>

            <form ng-controller="AnswerController" ng-submit="updateAnswer(answer)">
                <textArea type=text ng-model="answer.text" class="big-textarea editable_display editable_display_no_border answer_edition" name="text" readonly="readonly" >
                    {{answer.text}}
                </textArea>
                <button type="submit" class="btn_to_display answer_edition hidden" name="editAnwser">
                     {{ 'ANSWER.SEND' | translate}}
                </button>
            </form>

        {{answer.user.username}}
        {{answer.user.reputation}}

        {{ 'CREATED' | translate }} {{ answer.created | date:"dd-MM-yyyy HH:mm:ss" }}

            {{ 'EDITED' | translate }} {{ answer.edited | date:"dd-MM-yyyy HH:mm:ss" }}

                    <comment comment="comment"></comment>

        <form ng-controller="CommentController" ng-submit="createComment(comment,answer.id,null)" autocomplete="off">

                <textarea type=text ng-model="comment.text" class="big-textarea add-comment" rows="10" autocomplete="off"
                            placeholder="Add a new comment..."></textarea>

                <button type="submit" class="btn btn-success add-comment">

                </button>

        </form>

                {{ 'ANSWER.EDITANSWER' | translate}}

            <button ng-controller="AnswerController" ng-click="deleteAnswer(answer)" class="btn btn-danger">

        </button>


text:
//
//  QQTabbarViewController.m
//  tabbarTest
//
//  Created by Maybe on 2017/12/21.
//  Copyright © 2017年 JJBangKeJi. All rights reserved.
//

#import "QQTabBarController.h"
#import "DefaultAnimation.h"
#import "MCFactory.h"
#import "MCTabBarItem.h"
#import "UITabBar+MCBigItem.h"
#import "QYTabBar.h"
#define kwidth          [UIScreen mainScreen].bounds.size.width
static const NSInteger ButtonTag = 100;

static const NSInteger tabbarHeight = 80;//自定义TabBar的高度
@interface QQTabBarController ()
@property (nonatomic,strong) MCTabBarItem *lastItem;
@property (nonatomic,strong) NSArray *itemsArray;
@property (nonatomic , strong) QYTabBar *tab;

@end

@implementation QQTabBarController
- (instancetype)init
{
    if (self = [super init]) {

    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];

}
- (instancetype)initTabWithItems:(NSArray<MCTabBarItem *> *)items navClass:(Class)navClass;
{
    if (self = [super init]) {
        //去除tab的横线
//        [self.tabBar setBackgroundImage:[UIImage new]];
//        [self.tabBar setShadowImage:[UIImage new]];
        self.tab = [[QYTabBar alloc]init];
        self.tab.frame = self.tabBar.bounds;
        // UITabBarController子类
        [self setValue: self.tab forKey:@"tabBar"];
        self.itemsArray = items;
        [self initVC:items navClass:navClass];
        [self createVc:items];
    }
    return self;
}
/**
 改变tabbar的高度
 */
//- (void)viewWillLayoutSubviews{
    //这里设置高度  默认就是系统的高度
//    CGRect tabFrame = self.tabBar.frame;
//    tabFrame.size.height = tabbarHeight;
//    tabFrame.origin.y = self.view.frame.size.height - tabbarHeight;
//    self.tabBar.frame = tabFrame;
//}
- (void)initVC:(NSArray<MCTabBarItem *> *)items navClass:(Class)navClass{
    NSMutableArray *vcs = [NSMutableArray array];
    for (MCTabBarItem *item in items) {
        if (item.vc) {
            UINavigationController *nav = (UINavigationController *) [[navClass alloc] initWithRootViewController:item.vc];
            item.vc.navigationItem.title = item.text;
            [vcs addObject:nav];
        }
    }

    self.viewControllers = vcs;
}
- (void)createVc:(NSArray<MCTabBarItem *> *)items
{
    float TabWidth = kwidth/items.count;
    NSInteger index = 0;
    for (int i=0; i<items.count; i++) {
        MCTabBarItem *item = items[i];
        if (item.isBigItem && !self.tabBar.BigButton) {
            self.tabBar.BigButton = item;
            CGFloat offset = 0;
            if (item.offset && item.offset<0) {
                offset = item.offset;
            }else{
                offset = -20;
            }
            item.frame = CGRectMake(i*TabWidth, offset, item.bigItemSize.width, item.bigItemSize.height);
            item.centerX = self.tabBar.centerX;
            [item setBackgroundImage:item.defaultImg forState:UIControlStateNormal];
            [item setBackgroundImage:item.selectedImg forState:UIControlStateSelected];
        }else{
            item.frame = CGRectMake(i*TabWidth, 0, TabWidth, self.tabBar.frame.size.height);
            [item setImage:item.defaultImg forState:UIControlStateNormal];
            [item setImage:item.selectedImg forState:UIControlStateSelected];
            [item setTitle:item.text forState:UIControlStateNormal];
        }
        if (item.vc) {
            item.tag = ButtonTag + index;
            index +=1;
        }
        item.titleLabel.textAlignment = NSTextAlignmentCenter;
        if (i == 0) {
            item.selected  = YES;
            self.lastItem = item;
        }
        [item addTarget:self action:@selector(selectedTab:)forControlEvents:UIControlEventTouchUpInside];
        [self.tabBar addSubview:item];
    }
}
- (void)setDefaultColor:(UIColor *)defaultColor
{
    _defaultColor = defaultColor;
    [self.itemsArray enumerateObjectsUsingBlock:^(MCTabBarItem * item, NSUInteger idx, BOOL * _Nonnull stop) {
        [item setTitleColor:defaultColor forState:UIControlStateNormal];
    }];
}
- (void)setSelectedColor:(UIColor *)selectedColor
{
    _selectedColor = selectedColor;
    [self.itemsArray enumerateObjectsUsingBlock:^(MCTabBarItem * item, NSUInteger idx, BOOL * _Nonnull stop) {
        [item setTitleColor:selectedColor forState:UIControlStateSelected];
    }];
}
- (void)setFont:(UIFont *)font
{
    _font = font;
    [self.itemsArray enumerateObjectsUsingBlock:^(MCTabBarItem * item, NSUInteger idx, BOOL * _Nonnull stop) {
        item.titleLabel.font = font;
    }];
}

- (void)selectedTab:(MCTabBarItem *)item
{
    if (!item.tag) {
        if ([self.customDelegate respondsToSelector:@selector(clickBigItem)]) {
            [self.customDelegate clickBigItem];
        }
        return;
    }
    if (self.lastItem) {
        self.lastItem.selected = NO;
    }
    self.selectedIndex = item.tag - ButtonTag;
    item.selected = YES;
    self.lastItem = item;
    if ([self.customDelegate respondsToSelector:@selector(QQTabBarController:didSelectdIndex:)]) {
        [self.customDelegate QQTabBarController:self didSelectdIndex:self.selectedIndex];
    }
}
//设置选中的下标
- (void)setTabIndex:(NSInteger)index
{
    MCTabBarItem *item = [self.tabBar viewWithTag:index + ButtonTag];
    [self selectedTab:item];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end


text:
\defgroup mrpt_core_exception_grp Nested exceptions helpers
\ingroup mrpt_core_grp

See: \ref core_exceptions_example/test.cpp
\snippet core_exceptions_example/test.cpp example-nested-exceptions
Output:
\include core_exceptions_example/console.out


text:
[Home](./index.md) > [puppeteer](./puppeteer.md) > [Page](./puppeteer.page.md) > [title](./puppeteer.page.title.md)

## Page.title() method

Signature:

```typescript
title(): Promise<string>;
```
Returns:

Promise<string>


text:
static void *ARProgressContext = &ARProgressContext;

@interface ARInternalMobileWebViewController () <WKNavigationDelegate>
@property (nonatomic, assign) BOOL loaded;
@property (nonatomic, strong) ARInternalShareValidator *shareValidator;
@end

@implementation ARInternalMobileWebViewController

- (instancetype)initWithURL:(NSURL *)url
{
    NSString *urlString = url.absoluteString;
    NSString *urlHost = url.host;
    NSString *urlScheme = url.scheme;

    NSURL *correctBaseUrl = [ARRouter baseWebURL];
    NSString *correctHost = correctBaseUrl.host;
    NSString *correctScheme = correctBaseUrl.scheme;

    if ([[ARRouter artsyHosts] containsObject:urlHost]) {
        NSMutableString *mutableUrlString = [urlString mutableCopy];
        if (![urlScheme isEqualToString:correctScheme]) {
            [mutableUrlString replaceOccurrencesOfString:urlScheme withString:correctScheme options:NSCaseInsensitiveSearch range:NSMakeRange(0, mutableUrlString.length)];
        }
        if (![url.host isEqualToString:correctBaseUrl.host]) {
            [mutableUrlString replaceOccurrencesOfString:urlHost withString:correctHost options:NSCaseInsensitiveSearch range:NSMakeRange(0, mutableUrlString.length)];
        }
        url = [NSURL URLWithString:mutableUrlString];
    } else if (!urlHost) {
        url = [NSURL URLWithString:urlString relativeToURL:correctBaseUrl];
    }

    if (![urlString isEqualToString:url.absoluteString]) {
        NSLog(@"Rewriting %@ as %@", urlString, url.absoluteString);
    }

    self = [super initWithURL:url];
    if (!self) {
        return nil;
    }

    _shareValidator = [[ARInternalShareValidator alloc] init];

    ARActionLog(@"InternalWebVC init with URL %@", url);
    return self;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.webView stopLoading];
}

- (void)loadURL:(NSURL *)URL
{
    self.loaded = NO;
    [self showLoading];
    [super loadURL:URL];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self showLoading];

    // KVO on progress for when we can show the page
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew & NSKeyValueObservingOptionOld context:ARProgressContext];

    if ([AROptions boolForOption:AROptionsShowMartsyOnScreen]) {
        [self displayDebugMartsyIndicator];
    }
}

- (void)displayDebugMartsyIndicator {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 25, 30, 10, 10)]; // nice and oldschool
    view.layer.cornerRadius = 5;
    view.layer.masksToBounds = YES;
    view.backgroundColor = [UIColor redColor];
    [self.view insertSubview:view aboveSubview:self.webView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!self.loaded) {
        [self.webView loadRequest:[self requestWithURL:self.currentURL]];
    }
}

- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress" context:ARProgressContext];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    // Check if the view has reached the DOMContentLoaded stage.
    if (context == ARProgressContext && [keyPath isEqualToString:@"estimatedProgress"]) {
        [self.webView evaluateJavaScript:@"document.readyState == \"interactive\"" completionHandler:^(id response, NSError *error) {
            if ([response boolValue]) {
                [self hideLoading];
            }
        }];
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)showLoading
{
    [self ar_presentIndeterminateLoadingIndicatorAnimated:YES];
}

- (void)hideLoading
{
    [self ar_removeIndeterminateLoadingIndicatorAnimated:YES];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;
{
    /// If we do this initially there's a chance of seeing a black screen
    /// instead of our default white
    self.webView.scrollView.backgroundColor = [UIColor whiteColor];

    self.loaded = YES;

    // There are certain edge-cases, not fully known atm, that make it so that the DOMContentLoaded hook isn't
    // triggered. Therefore, hide the loading view here for good measure.
    [self hideLoading];
}

// Load a new internal web VC for each link we can do

- (WKNavigationActionPolicy)shouldLoadNavigationAction:(WKNavigationAction *)navigationAction;
{
    NSURL *URL = navigationAction.request.URL;

    // If we really have to hijack regardless do it first.
    // This is to take into account AJAX requests which are not
    // strictly classed as a WKNavigationTypeLinkActivated
    // as the user may not have _directly_ loaded it

    if (navigationAction.navigationType == WKNavigationTypeLinkActivated) {
        if ([self.shareValidator isSocialSharingURL:URL]) {
            ARWindow *window = ARAppDelegate.sharedInstance.window;
            CGPoint lastTouchPointInView = [window convertPoint:window.lastTouchPoint toView:self.view];
            CGRect position = (CGRect){.origin = lastTouchPointInView, .size = CGSizeZero};
            [self.shareValidator shareURL:URL inView:self.view frame:position];

            ARActionLog(@"Artsy URL: Denied - %@ - %@", URL, @(navigationAction.navigationType));
            return WKNavigationActionPolicyCancel;

        } else {
            // TODO: this opens a new web view for every navigation action. Let's switch to react-native web views and fix that
            [[AREmission sharedInstance] navigate:[URL absoluteString]];

            ARActionLog(@"Artsy URL: Denied - %@ - %@", URL, @(navigationAction.navigationType));
            return WKNavigationActionPolicyCancel;
        }
    }

    ARActionLog(@"Artsy URL: Allowed - %@ - %@", URL, @(navigationAction.navigationType));
    return WKNavigationActionPolicyAllow;
}

// A full reload, not just a webView.reload, which only refreshes the view without re-requesting data.

- (NSURLRequest *)requestWithURL:(NSURL *)URL
{
    return [ARRouter requestForURL:URL];
}

@end


text:
// Licensed under Apache License version 2.0
package javax.jmdns.impl.tasks.resolver;

import java.io.IOException;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jmdns.impl.DNSOutgoing;
import javax.jmdns.impl.JmDNSImpl;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.tasks.DNSTask;

/**
 * This is the root class for all resolver tasks.
 *
 * @author Pierre Frisch
 */
public abstract class DNSResolverTask extends DNSTask {
	private static Logger logger = Logger.getLogger(DNSResolverTask.class
			.getName());

	/**
	 * Counts the number of queries being sent.
	 */
	protected int _count = 0;

	/**
	 * @param jmDNSImpl
	 */
	public DNSResolverTask(JmDNSImpl jmDNSImpl) {
		super(jmDNSImpl);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return super.toString() + " count: " + _count;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see javax.jmdns.impl.tasks.DNSTask#start(java.util.Timer)
	 */
	@Override
	public void start(Timer timer) {
		if (!this.getDns().isCanceling() && !this.getDns().isCanceled()) {
			timer.schedule(this, DNSConstants.QUERY_WAIT_INTERVAL,
					DNSConstants.QUERY_WAIT_INTERVAL);
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.util.TimerTask#run()
	 */
	@Override
	public void run() {
		try {
			if (this.getDns().isCanceling() || this.getDns().isCanceled()) {
				this.cancel();
			} else {
				if (_count++ < 3) {
					if (logger.isLoggable(Level.FINER)) {
						logger.finer(this.getName() + ".run() JmDNS "
								+ this.description());
					}
					DNSOutgoing out = new DNSOutgoing(
							DNSConstants.FLAGS_QR_QUERY);
					out = this.addQuestions(out);
					if (this.getDns().isAnnounced()) {
						out = this.addAnswers(out);
					}
					if (!out.isEmpty()) {
						this.getDns().send(out);
					}
				} else {
					// After three queries, we can quit.
					this.cancel();
				}
			}
		} catch (Throwable e) {
			logger.log(Level.WARNING, this.getName() + ".run() exception ", e);
			this.getDns().recover();
		}
	}

	/**
	 * Overridden by subclasses to add questions to the message.

	 * Note: Because of message size limitation the returned message may
	 * be different than the message parameter.
	 *
	 * @param out
	 *            outgoing message
	 * @return the outgoing message.
	 * @exception IOException
	 */
	protected abstract DNSOutgoing addQuestions(DNSOutgoing out)
			throws IOException;

	/**
	 * Overridden by subclasses to add questions to the message.

	 * Note: Because of message size limitation the returned message may
	 * be different than the message parameter.
	 *
	 * @param out
	 *            outgoing message
	 * @return the outgoing message.
	 * @exception IOException
	 */
	protected abstract DNSOutgoing addAnswers(DNSOutgoing out)
			throws IOException;

	/**
	 * Returns a description of the resolver for debugging
	 *
	 * @return resolver description
	 */
	protected abstract String description();

}


text:
namespace web_intents {

#define NATIVE_SCHEME "chrome-intents-native"

const char kChromeNativeSerivceScheme[] = NATIVE_SCHEME;
const char kNativeFilePickerUrl[] = NATIVE_SCHEME "://file-picker";

NativeServiceRegistry::NativeServiceRegistry() {}

void NativeServiceRegistry::GetSupportedServices(
    const string16& action,
    IntentServiceList* services) {
  if (!CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kWebIntentsNativeServicesEnabled))
    return;

#if !defined(ANDROID)
  if (EqualsASCII(action, web_intents::kActionPick)) {
    // File picker registrations.
    webkit_glue::WebIntentServiceData service(
        ASCIIToUTF16(kActionPick),
        ASCIIToUTF16("*/*"),  // handle any MIME-type
        string16(),
        GURL(web_intents::kNativeFilePickerUrl),
        FilePickerFactory::GetServiceTitle());
    service.disposition = webkit_glue::WebIntentServiceData::DISPOSITION_NATIVE;

    services->push_back(service);
  }
#endif
}

NativeServiceFactory::NativeServiceFactory() {}

IntentServiceHost* NativeServiceFactory::CreateServiceInstance(
    const GURL& service_url,
    const webkit_glue::WebIntentData& intent,
    content::WebContents* web_contents) {

#if !defined(ANDROID)
  if (service_url.spec() == kNativeFilePickerUrl) {
    return FilePickerFactory::CreateServiceInstance(intent, web_contents);
  }
#endif

  return NULL;  // couldn't create instance
}

}  // namespace web_intents


text:
hqDefine('hqadmin/js/hqadmin_base_report', [
    'jquery',
    'hqwebapp/js/initial_page_data',
    'reports/js/config.dataTables.bootstrap',
], function (
    $,
    initialPageData,
    datatablesConfig
) {
    $(function () {
        var aoColumns = initialPageData.get('aoColumns');
        if (aoColumns) {
            var reportTables = datatablesConfig.HQReportDataTables({
                aoColumns: aoColumns,
            });
            reportTables.render();
        }
    });
});


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 sw=2 et tw=78: */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

/* the caret is the text cursor used, e.g., when editing */

#ifndef nsCaret_h__
#define nsCaret_h__

#include "nsCoord.h"
#include "nsISelectionListener.h"
#include "nsITimer.h"
#include "nsWeakPtr.h"
#include "nsFrameSelection.h"

class nsRenderingContext;
class nsDisplayListBuilder;

//-----------------------------------------------------------------------------
class nsCaret : public nsISelectionListener
{
  public:

                  nsCaret();
    virtual       ~nsCaret();

    enum EViewCoordinates {
      eTopLevelWindowCoordinates,
      eRenderingViewCoordinates,
      eClosestViewCoordinates
    };

  public:

    NS_DECL_ISUPPORTS

    nsresult    Init(nsIPresShell *inPresShell);
    void    Terminate();

    nsISelection*    GetCaretDOMSelection();
    nsresult    SetCaretDOMSelection(nsISelection *inDOMSel);

    /** GetCaretVisible will get the visibility of the caret
     *  This function is virtual so that it can be used by nsCaretAccessible
     *  without linking
     *  @param inMakeVisible true it is shown, false it is hidden
     *  @return false if and only if inMakeVisible is null, otherwise true
     */
    virtual nsresult    GetCaretVisible(bool *outMakeVisible);

    /** SetCaretVisible will set the visibility of the caret
     *  @param inMakeVisible true to show the caret, false to hide it
     */
    void    SetCaretVisible(bool intMakeVisible);

    /** SetCaretReadOnly set the appearance of the caret
     *  @param inMakeReadonly true to show the caret in a 'read only' state,
     *	    false to show the caret in normal, editing state
     */
    void    SetCaretReadOnly(bool inMakeReadonly);

    /** GetCaretReadOnly get the appearance of the caret
     *	@return true if the caret is in 'read only' state, otherwise,
     *	    returns false
     */
    bool GetCaretReadOnly()
    {
      return mReadOnly;
    }

    /**
     * Gets the position and size of the caret that would be drawn for
     * the focus node/offset of aSelection (assuming it would be drawn,
     * i.e., disregarding blink status). The geometry is stored in aRect,
     * and we return the frame aRect is relative to.
     * @param aRect must be non-null
     * @param aBidiIndicatorSize if non-null, set to the bidi indicator size.
     */
    virtual nsIFrame* GetGeometry(nsISelection* aSelection,
                                  nsRect* aRect,
                                  nscoord* aBidiIndicatorSize = nsnull);

    /** EraseCaret
     *  this will erase the caret if its drawn and reset drawn status
     */
    void    EraseCaret();

    void    SetVisibilityDuringSelection(bool aVisibility);

    /** DrawAtPosition
     *
     *  Draw the caret explicitly, at the specified node and offset.
     *  To avoid drawing glitches, you should call EraseCaret()
     *  after each call to DrawAtPosition().
     *
     *  Note: This call breaks the caret's ability to blink at all.
     **/
    nsresult    DrawAtPosition(nsIDOMNode* aNode, PRInt32 aOffset);

    /** GetCaretFrame
     *  Get the current frame that the caret should be drawn in. If the caret is
     *  not currently visible (i.e., it is between blinks), then this will
     *  return null.
     *
     *  @param aOffset is result of the caret offset in the content.
     */
    nsIFrame*     GetCaretFrame(PRInt32 *aOffset = nsnull);

    /** GetCaretRect
     *  Get the current caret rect. Only call this when GetCaretFrame returns
     *  non-null.
     */
    nsRect        GetCaretRect()
    {
      nsRect r;
      r.UnionRect(mCaretRect, GetHookRect());
      return r;
    }

    /** InvalidateOutsideCaret
     *  Invalidate the area that the caret currently occupies if the caret is
     *  outside of its frame's overflow area. This is used when the content that
     *  the caret is currently drawn is is being deleted or reflowed.
     */
    void      InvalidateOutsideCaret();

    /** UpdateCaretPosition
     *  Update the caret's current frame and rect, but don't draw yet. This is
     *  useful for flickerless moving of the caret (e.g., when the frame the
     *  caret is in reflows and is moved).
     */
    void      UpdateCaretPosition();

    /** PaintCaret
     *  Actually paint the caret onto the given rendering context.
     */
    void      PaintCaret(nsDisplayListBuilder *aBuilder,
                         nsRenderingContext *aCtx,
                         nsIFrame *aForFrame,
                         const nsPoint &aOffset);
    /**
     * Sets whether the caret should only be visible in nodes that are not
     * user-modify: read-only, or whether it should be visible in all nodes.
     *
     * @param aIgnoreUserModify true to have the cursor visible in all nodes,
     *                          false to have it visible in all nodes except
     *                          those with user-modify: read-only
     */

    void SetIgnoreUserModify(bool aIgnoreUserModify);

    //nsISelectionListener interface
    NS_DECL_NSISELECTIONLISTENER

    static void   CaretBlinkCallback(nsITimer *aTimer, void *aClosure);

    nsresult      GetCaretFrameForNodeOffset(nsIContent* aContentNode,
                                             PRInt32 aOffset,
                                             nsFrameSelection::HINT aFrameHint,
                                             PRUint8 aBidiLevel,
                                             nsIFrame** aReturnFrame,
                                             PRInt32* aReturnOffset);

    NS_IMETHOD CheckCaretDrawingState();

protected:

    void          KillTimer();
    nsresult      PrimeTimer();

    void          StartBlinking();
    void          StopBlinking();

    // If the nearest block has a potential 'text-overflow' marker then
    // invalidate it.
    void          InvalidateTextOverflowBlock();

    bool          DrawAtPositionWithHint(nsIDOMNode* aNode,
                                         PRInt32 aOffset,
                                         nsFrameSelection::HINT aFrameHint,
                                         PRUint8 aBidiLevel,
                                         bool aInvalidate);

    struct Metrics {
      nscoord mBidiIndicatorSize; // width and height of bidi indicator
      nscoord mCaretWidth;        // full caret width including bidi indicator
    };
    Metrics ComputeMetrics(nsIFrame* aFrame, PRInt32 aOffset, nscoord aCaretHeight);
    nsresult GetGeometryForFrame(nsIFrame* aFrame,
                                 PRInt32   aFrameOffset,
                                 nsRect*   aRect,
                                 nscoord*  aBidiIndicatorSize);

    // Returns true if the caret should be drawn. When |mDrawn| is true,
    // this returns true, so that we erase the drawn caret. If |aIgnoreDrawnState|
    // is true, we don't take into account whether the caret is currently
    // drawn or not. This can be used to determine if the caret is drawn when
    // it shouldn't be.
    bool          MustDrawCaret(bool aIgnoreDrawnState);

    void          DrawCaret(bool aInvalidate);
    void          DrawCaretAfterBriefDelay();
    bool          UpdateCaretRects(nsIFrame* aFrame, PRInt32 aFrameOffset);
    static void   InvalidateRects(const nsRect &aRect, const nsRect &aHook,
                                  nsIFrame *aFrame);
    nsRect        GetHookRect()
    {
#ifdef IBMBIDI
      return mHookRect;
#else
      return nsRect();
#endif
    }
    void          ToggleDrawnStatus() { mDrawn = !mDrawn; }

    already_AddRefed<nsFrameSelection> GetFrameSelection();

    // Returns true if we should not draw the caret because of XUL menu popups.
    // The caret should be hidden if:
    // 1. An open popup contains the caret, but a menu popup exists before the
    //    caret-owning popup in the popup list (i.e. a menu is in front of the
    //    popup with the caret). If the menu itself contains the caret we don't
    //    hide it.
    // 2. A menu popup is open, but there is no caret present in any popup.
    // 3. The caret selection is empty.
    bool IsMenuPopupHidingCaret();

protected:

    nsWeakPtr             mPresShell;
    nsWeakPtr             mDomSelectionWeak;

    nsCOMPtr<nsITimer>    mBlinkTimer;

    // XXX these fields should go away and the values be acquired as needed,
    // probably by ComputeMetrics.
    PRUint32              mBlinkRate;         // time for one cyle (on then off), in milliseconds
    nscoord               mCaretWidthCSSPx;   // caret width in CSS pixels
    float                 mCaretAspectRatio;  // caret width/height aspect ratio

    bool                  mVisible;           // is the caret blinking

    bool                  mDrawn;             // Denotes when the caret is physically drawn on the screen.
    bool                  mPendingDraw;       // True when the last on-state draw was suppressed.

    bool                  mReadOnly;          // it the caret in readonly state (draws differently)
    bool                  mShowDuringSelection; // show when text is selected

    bool                  mIgnoreUserModify;

#ifdef IBMBIDI
    bool                  mKeyboardRTL;       // is the keyboard language right-to-left
    bool                  mBidiUI;            // is bidi UI turned on
    nsRect                mHookRect;          // directional hook on the caret
    PRUint8               mLastBidiLevel;     // saved bidi level of the last draw request, to use when we erase
#endif
    nsRect                mCaretRect;         // the last caret rect, in the coodinates of the last frame.

    nsCOMPtr<nsIContent>  mLastContent;       // store the content the caret was last requested to be drawn
                                              // in (by DrawAtPosition()/DrawCaret()),
                                              // note that this can be different than where it was
                                              // actually drawn (anon <BR> in text control)
    PRInt32               mLastContentOffset; // the offset for the last request

    nsFrameSelection::HINT mLastHint;        // the hint associated with the last request, see also
                                              // mLastBidiLevel below

};

// handy stack-based class for temporarily disabling the caret

class StCaretHider
{
public:
               StCaretHider(nsCaret* aSelCon)
               : mWasVisible(false), mCaret(aSelCon)
               {
                 if (mCaret)
                 {
                   mCaret->GetCaretVisible(&mWasVisible);
                   if (mWasVisible)
                     mCaret->SetCaretVisible(false);
                 }
               }

               ~StCaretHider()
               {
                 if (mCaret && mWasVisible)
                   mCaret->SetCaretVisible(true);
                 // nsCOMPtr releases mPresShell
               }

protected:

    bool                    mWasVisible;
    nsCOMPtr<nsCaret>  mCaret;
};

#endif //nsCaret_h__


text:
var fs = require('fs'),
  mapnik = require('mapnik'),
  mercator = new(require('sphericalmercator'))(),
  sm = require('sphericalmercator'),
  nfs = require('node-fs'),
  sm = require('sphericalmercator');

var Thumbnail = function( koop ){

  // Primary entry point for thumbnail generation
  // should be relatively stupid about where to write file, but should check for cached images
  // @param json GeoJSON for rendering to image
  // @param extent bounding box for image
  this.generate = function( json, key, options, callback ) {
    var self = this;
    var dir = koop.files.localDir + 'thumbs/' + key;
    // make sure dir exists
    nfs.mkdir( dir, '0777', true, function(err){
      var jsonFile = koop.files.localDir + options.f_base + '.json';
      if (!fs.existsSync( jsonFile )){
        fs.writeFile( jsonFile, JSON.stringify( json ), function(err){
          self.render(json, jsonFile, options, callback);
        });
      } else {
        self.render(json, jsonFile, options, callback);
      }
    });

  };

  // actually renders and returns the saved file
  this.render = function( json, jsonFile, options, callback ){

    var png = jsonFile.replace('json', 'png');

    var map = new mapnik.Map( options.width, options.height );
    map.loadSync(__dirname + '/../templates/renderers/style.xml');

    var layer = new mapnik.Layer('layer1');
    layer.srs = '+init=epsg:4326';
    layer.datasource = new mapnik.Datasource( { type: 'geojson', file: jsonFile } );

    // add styles
    layer.styles = [json.features[0].geometry.type.toLowerCase()];

    map.add_layer(layer);

    var image = new mapnik.Image( options.width, options.height );

    // project extent
    //if (!options.extent){
    //  options.extent = Extent.bounds( json.features );
    //}
    //var buff = 0;
    //var merc = new sm( { size:options.width } ),
    //  mins = merc.forward( [options.extent.xmin-buff, options.extent.ymin-buff] ),
    //  maxs = merc.forward( [options.extent.xmax+buff, options.extent.ymax+buff] );
    //map.extent = [ mins[0], mins[1], maxs[0], maxs[1] ];

    // instead of setting extent we can have mapnik zoom to all features
    map.zoomAll();

    map.render( image, {}, function( err, im ) {
      if (err) {
        callback( err, null );
      } else {
        im.encode( 'png', function( err, buffer ) {
          fs.write( png, buffer, function( err ) {
            callback( null, png );
          });
        });
      }
    });

  };

  return this;
};

module.exports = Thumbnail;


text:
#ifndef WEBRTC_BASE_ASYNCRESOLVERINTERFACE_H_
#define WEBRTC_BASE_ASYNCRESOLVERINTERFACE_H_

#include "webrtc/base/sigslot.h"
#include "webrtc/base/socketaddress.h"

namespace rtc {

// This interface defines the methods to resolve the address asynchronously.
class AsyncResolverInterface {
 public:
  AsyncResolverInterface();
  virtual ~AsyncResolverInterface();

  // Start address resolve process.
  virtual void Start(const SocketAddress& addr) = 0;
  // Returns top most resolved address of |family|
  virtual bool GetResolvedAddress(int family, SocketAddress* addr) const = 0;
  // Returns error from resolver.
  virtual int GetError() const = 0;
  // Delete the resolver.
  virtual void Destroy(bool wait) = 0;
  // Returns top most resolved IPv4 address if address is resolved successfully.
  // Otherwise returns address set in SetAddress.
  SocketAddress address() const {
    SocketAddress addr;
    GetResolvedAddress(AF_INET, &addr);
    return addr;
  }

  // This signal is fired when address resolve process is completed.
  sigslot::signal1<AsyncResolverInterface*> SignalDone;
};

}  // namespace rtc

#endif


text:
uxrocket.handlebars
===================

Handlebars Helpers for UX Rocket templates


text:
<?php

namespace KWedrowicz\JobCommunication\Message;

use KWedrowicz\JobCommunication\Params\UserParams;

class InsertUserDocument extends CommandMessage
{
    public function __construct(UserParams $params)
    {
        $this->params = $params;
        parent::__construct();
    }

    public function getName(): string
    {
        return MessageType::INSERT_USER_DOCUMENT;
    }

    public function getChannel(): string
    {
        return MessageChannel::DOCUMENT;
    }
}


text:
package com.lenox.beyondj.action.converter;

import net.sourceforge.stripes.validation.DateTypeConverter;
import net.sourceforge.stripes.validation.TypeConverter;
import net.sourceforge.stripes.validation.ValidationError;
import org.joda.time.DateTime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
/**
 * @author nickk
 */
public class JodaDateConverter implements TypeConverter<DateTime> {

	private static final String FORMAT = "yyyy-MM-dd";
	DateTypeConverter dateTypeConverter = new DateTypeConverter();

	public void setLocale(Locale locale) {
		dateTypeConverter.setLocale(locale);
	}

	public DateTime convert(String input,
			Class<? extends DateTime> targetClass,
			Collection<ValidationError> errors) {
		DateTime dateTime = null;
		SimpleDateFormat fmt = new SimpleDateFormat(FORMAT);

		try {
			Date dt = fmt.parse(input);
			dateTime = new DateTime(dt);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return dateTime;
	}
}


text: rosparam load `rospack find itomp_cio_planner`/config/params.yaml itomp_planner