text:
<?php

require_once('src/lightncandy.php');
require_once('tests/helpers_for_test.php');

$tmpdir = sys_get_temp_dir();
$errlog_fn = tempnam($tmpdir, 'terr_');

function start_catch_error_log() {
    global $errlog_fn;
    date_default_timezone_set('GMT');
    if (file_exists($errlog_fn)) {
        unlink($errlog_fn);
    }
    return ini_set('error_log', $errlog_fn);
}

function stop_catch_error_log() {
    global $errlog_fn;
    ini_restore('error_log');
    if (!file_exists($errlog_fn)) {
        return null;
    }
    return array_map(function ($l) {
        $l = rtrim($l);
        preg_match('/GMT\] (.+)/', $l, $m);
        return isset($m[1]) ? $m[1] : $l;
    }, file($errlog_fn));
}

class errorTest extends PHPUnit_Framework_TestCase
{
    public function testException()
    {
        $this->setExpectedException('Exception', 'Bad token {{{foo}} ! Do you mean {{foo}} or {{{foo}}}?');
        $php = LightnCandy::compile('{{{foo}}', Array('flags' => LightnCandy::FLAG_ERROR_EXCEPTION));
    }

    public function testErrorLog()
    {
        start_catch_error_log();
        $php = LightnCandy::compile('{{{foo}}', Array('flags' => LightnCandy::FLAG_ERROR_LOG));
        $e = stop_catch_error_log();
        if ($e) {
            $this->assertEquals(Array('Bad token {{{foo}} ! Do you mean {{foo}} or {{{foo}}}?'), $e);
        } else {
            $this->markTestIncomplete('skip HHVM');
        }
    }

    /**
     * @dataProvider renderErrorProvider
     */
    public function testRenderingException($test)
    {
        $this->setExpectedException('Exception', $test['expected']);
        $php = LightnCandy::compile($test['template'], $test['options']);
        $renderer = LightnCandy::prepare($php);
        $renderer(null, LCRun3::DEBUG_ERROR_EXCEPTION);
    }

    /**
     * @dataProvider renderErrorProvider
     */
    public function testRenderingErrorLog($test)
    {
        start_catch_error_log();
        $php = LightnCandy::compile($test['template'], $test['options']);
        $renderer = LightnCandy::prepare($php);
        $renderer(null, LCRun3::DEBUG_ERROR_LOG);
        $e = stop_catch_error_log();
        if ($e) {
            $this->assertEquals(Array($test['expected']), $e);
        } else {
            $this->markTestIncomplete('skip HHVM');
        }
    }

    public function renderErrorProvider()
    {
        $errorCases = Array(
             Array(
                 'template' => '{{{foo}}}',
                 'expected' => 'LCRun3: [foo] is not exist',
             ),
             Array(
                 'template' => '{{foo}}',
                 'options' => Array(
                     'hbhelpers' => Array(
                         'foo' => function () {
                             return 1/0;
                         }
                     ),
                 ),
                 'expected' => 'LCRun3: call custom helper \'foo\' error: Division by zero',
             ),
        );

        return array_map(function($i) {
            if (!isset($i['options'])) {
                $i['options'] = Array('flags' => LightnCandy::FLAG_RENDER_DEBUG);
            }
            if (!isset($i['options']['flags'])) {
                $i['options']['flags'] = LightnCandy::FLAG_RENDER_DEBUG;
            }
            return Array($i);
        }, $errorCases);
    }

    /**
     * @dataProvider errorProvider
     */
    public function testErrors($test)
    {
        global $tmpdir;

        $php = LightnCandy::compile($test['template'], $test['options']);
        $context = LightnCandy::getContext();

        // This case should be compiled without error
        if (!isset($test['expected'])) {
            return;
        }

        $this->assertEquals($test['expected'], $context['error'], "Code: $php");
    }

    public function errorProvider()
    {
        $errorCases = Array(
            Array(
                'template' => '{{testerr1}}}',
                'expected' => 'Bad token {{testerr1}}} ! Do you mean {{testerr1}} or {{{testerr1}}}?',
            ),
            Array(
                'template' => '{{{testerr2}}',
                'expected' => 'Bad token {{{testerr2}} ! Do you mean {{testerr2}} or {{{testerr2}}}?',
            ),
            Array(
                'template' => '{{{#testerr3}}}',
                'expected' => 'Bad token {{{#testerr3}}} ! Do you mean {{#testerr3}} ?',
            ),
            Array(
                'template' => '{{{!testerr4}}}',
                'expected' => 'Bad token {{{!testerr4}}} ! Do you mean {{!testerr4}} ?',
            ),
            Array(
                'template' => '{{{^testerr5}}}',
                'expected' => 'Bad token {{{^testerr5}}} ! Do you mean {{^testerr5}} ?',
            ),
            Array(
                'template' => '{{{/testerr6}}}',
                'expected' => 'Bad token {{{/testerr6}}} ! Do you mean {{/testerr6}} ?',
            ),
            Array(
                'template' => '{{win[ner.test1}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming in {{win[ner.test1}}',
            ),
            Array(
                'template' => '{{win]ner.test2}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming as \'win]ner.test2\' in {{win]ner.test2}} !',
            ),
            Array(
                'template' => '{{wi[n]ner.test3}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming as \'wi[n]ner.test3\' in {{wi[n]ner.test3}} !',
            ),
            Array(
                'template' => '{{winner].[test4]}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming as \'winner].[test4]\' in {{winner].[test4]}} !',
            ),
            Array(
                'template' => '{{winner[.test5]}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming as \'winner[.test5]\' in {{winner[.test5]}} !',
            ),
            Array(
                'template' => '{{winner.[.test6]}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
            ),
            Array(
                'template' => '{{winner.[#te.st7]}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
            ),
            Array(
                'template' => '{{test8}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
            ),
            Array(
                'template' => '{{test9]}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming as \'test9]\' in {{test9]}} !',
            ),
            Array(
                'template' => '{{testA[}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming in {{testA[}}',
            ),
            Array(
                'template' => '{{[testB}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming in {{[testB}}',
            ),
            Array(
                'template' => '{{]testC}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming as \']testC\' in {{]testC}} !',
            ),
            Array(
                'template' => '{{[testD]}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
            ),
            Array(
                'template' => '{{te]stE}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming as \'te]stE\' in {{te]stE}} !',
            ),
            Array(
                'template' => '{{tee[stF}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming in {{tee[stF}}',
            ),
            Array(
                'template' => '{{te.e[stG}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming in {{te.e[stG}}',
            ),
            Array(
                'template' => '{{te.e]stH}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming as \'te.e]stH\' in {{te.e]stH}} !',
            ),
            Array(
                'template' => '{{te.e[st.endI}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming in {{te.e[st.endI}}',
            ),
            Array(
                'template' => '{{te.e]st.endJ}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming as \'te.e]st.endJ\' in {{te.e]st.endJ}} !',
            ),
            Array(
                'template' => '{{te.[est].endK}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
            ),
            Array(
                'template' => '{{te.t[est].endL}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming as \'te.t[est].endL\' in {{te.t[est].endL}} !',
            ),
            Array(
                'template' => '{{te.t[est]o.endM}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming as \'te.t[est]o.endM\' in {{te.t[est]o.endM}} !',
            ),
            Array(
                'template' => '{{te.[est]o.endN}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
                'expected' => 'Wrong variable naming as \'te.[est]o.endN\' in {{te.[est]o.endN}} !',
            ),
            Array(
                'template' => '{{te.[e.st].endO}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
            ),
            Array(
                'template' => '{{te.[e.s[t].endP}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
            ),
            Array(
                'template' => '{{te.[e[s.t].endQ}}',
                'options' => Array('flags' => LightnCandy::FLAG_ADVARNAME),
            ),
            Array(
                'template' => '{{helper}}',
                'options' => Array('helpers' => Array(
                    'helper' => Array('bad input'),
                )),
                'expected' => 'I found an array in helpers with key as helper, please fix it.',
            ),
            Array(
                'template' => '<ul>{{#each item}}<li>{{name}}</li>',
                'expected' => 'Unclosed token {{{#each item}}} !!',
            ),
            Array(
                'template' => 'issue63: {{test_join}} Test! {{this}} {{/test_join}}',
                'expected' => 'Unexpect token: {{/test_join}} !',
            ),
            Array(
                'template' => '{{#if a}}TEST{{/with}}',
                'options' => Array('flags' => LightnCandy::FLAG_WITH),
                'expected' => 'Unexpect token: {{/with}} !',
            ),
            Array(
                'template' => '{{#foo}}error{{/bar}}',
                'expected' => 'Unexpect token {{/bar}} ! Previous token {{#[foo]}} is not closed',
            ),
            Array(
                'template' => '{{../foo}}',
                'expected' => 'Do not support {{../var}}, you should do compile with LightnCandy::FLAG_PARENT flag',
            ),
            Array(
                'template' => '{{..}}',
                'expected' => 'Do not support {{../var}}, you should do compile with LightnCandy::FLAG_PARENT flag',
            ),
            Array(
                'template' => '{{test_join [a]=b}}',
                'options' => Array(
                    'flags' => LightnCandy::FLAG_NAMEDARG,
                    'helpers' => Array('test_join')
                ),
                'expected' => "Wrong argument name as '[a]' in {{test_join [a]=b}} ! You should fix your template or compile with LightnCandy::FLAG_ADVARNAME flag.",
            ),
            Array(
                'template' => '{{a=b}}',
                'options' => Array('flags' => LightnCandy::FLAG_NAMEDARG),
                'expected' => 'Do not support name=value in {{a=b}}, you should use it after a custom helper.',
            ),
            Array(
                'template' => '{{test a=b}}',
                'options' => Array('flags' => LightnCandy::FLAG_NAMEDARG),
                'expected' => 'Do not support name=value in {{test a=b}}, maybe you missing the custom helper?',
            ),
            Array(
                'template' => '{{#test a=b}}YA~{{/test}}',
                'options' => Array('flags' => LightnCandy::FLAG_NAMEDARG),
                'expected' => 'Do not support name=value in {{#test a=b}}, maybe you missing the block custom helper?',
            ),
            Array(
                'template' => '{{#foo}}1{{^}}2{{/foo}}',
                'expected' => 'Do not support {{^}}, you should do compile with LightnCandy::FLAG_ELSE flag',
            ),
            Array(
                'template' => '{{#with a}OK!{{/with}}',
                'options' => Array('flags' => LightnCandy::FLAG_WITH),
                'expected' => 'Unclosed token {{{#with a}OK!{{/with}}} !!',
            ),
            Array(
                'template' => '{{#each a}OK!{{/each}}',
                'expected' => 'Unclosed token {{{#each a}OK!{{/each}}} !!',
            ),
            Array(
                'template' => '{{#with items}}OK!{{/with}}',
                'options' => Array('flags' => LightnCandy::FLAG_WITH),
            ),
            Array(
                'template' => '{{#with}}OK!{{/with}}',
                'options' => Array('flags' => LightnCandy::FLAG_WITH),
                'expected' => 'No argument after {{#with}} !',
            ),
            Array(
                'template' => '{{>not_found}}',
                'expected' => "Can not find partial file for 'not_found', you should set correct basedir and fileext in options",
            ),
            Array(
                'template' => '{{>tests/test1 foo}}',
                'options' => Array('basedir' => '.'),
                'expected' => 'Do not support {{>tests/test1 [foo]}}, you should do compile with LightnCandy::FLAG_RUNTIMEPARTIAL flag',
            ),
            Array(
                'template' => '{{#with foo}}ABC{{/with}}',
                'expected' => 'Do not support {{#with var}}, you should do compile with LightnCandy::FLAG_WITH flag',
            ),
            Array(
                'template' => '{{abc}}',
                'options' => Array('helpers' => Array('abc')),
                'expected' => 'Can not find custom helper function defination abc() !',
            ),
            Array(
                'template' => '{{=~= =~=}}',
                'expected' => "Can not set delimiter contains '=' , you try to set delimiter as '~=' and '=~'.",
            ),
            Array(
                'template' => '{{>recursive}}',
                'options' => Array('basedir' => 'tests', 'flags' => LightnCandy::FLAG_WITH),
                'expected' => Array(
                    'I found recursive partial includes as the path: recursive -> recursive! You should fix your template or compile with LightnCandy::FLAG_RUNTIMEPARTIAL flag.',
                    "Skip rendering partial 'recursive' again due to recursive detected",
                )
            ),
            Array(
                'template' => '{{test_join (foo bar)}}',
                'options' => Array(
                    'flags' => LightnCandy::FLAG_ADVARNAME,
                    'helpers' => Array('test_join'),
                ),
                'expected' => "Can not find custom helper function defination foo() !",
            ),
            Array(
                'template' => '{{1 + 2}}',
                'options' => Array(
                    'flags' => LightnCandy::FLAG_HANDLEBARSJS,
                    'helpers' => Array('test_join'),
                ),
                'expected' => "Wrong variable naming as '+' in {{1 + 2}} ! You should wrap ! \" # % & ' * + , ; < = > { | } ~ into [ ]",
            ),
            Array(
                'template' => '{{> (foo) bar}}',
                'options' => Array(
                    'flags' => LightnCandy::FLAG_HANDLEBARSJS,
                    'basedir' => '.',
                ),
                'expected' => Array(
                    "Can not find custom helper function defination foo() !",
                    "You use dynamic partial name as '(foo)', this only works with option FLAG_RUNTIMEPARTIAL enabled",
                )
            ),
            Array(
                'template' => '{{{{#foo}}}',
                'options' => Array(
                    'flags' => LightnCandy::FLAG_HANDLEBARSJS,
                ),
                'expected' => Array(
                    'Bad token {{{{#foo}}} ! Do you mean {{{{#foo}}}} ?',
                    'Wrong raw block begin with {{{{#foo}}} ! Remove "#" to fix this issue.',
                    'Unclosed token {{{#foo}}} !!',
                )
            ),
            Array(
                'template' => '{{{{foo}}}} {{ {{{{/bar}}}}',
                'options' => Array(
                    'flags' => LightnCandy::FLAG_HANDLEBARSJS,
                ),
                'expected' => Array(
                    'Unexpect token {{/bar}} ! Previous token {{#[foo]}} is not closed',
                )
            ),
            Array(
                'template' => '{{{{foo}}}} {{ {{{{#foo}}}}',
                'options' => Array(
                    'flags' => LightnCandy::FLAG_HANDLEBARSJS,
                ),
                'expected' => Array(
                    'Wrong raw block end with {{{{#foo}}}} ! Replace "#" with "/" will fix this issue.',
                    'Unclosed token {{{#foo}}} !!',
                )
            ),
        );

        return array_map(function($i) {
            if (!isset($i['options'])) {
                $i['options'] = Array('flags' => 0);
            }
            if (!isset($i['options']['flags'])) {
                $i['options']['flags'] = 0;
            }
            if (isset($i['expected']) && !is_array($i['expected'])) {
                $i['expected'] = Array($i['expected']);
            }
            return Array($i);
        }, $errorCases);
    }
}

?>


text:
'use strict';

const common = require('../common');
const http = require('http');
const assert = require('assert');
const { Writable } = require('stream');
const Countdown = require('../common/countdown');

const N = 2;
let abortRequest = true;

const server = http.Server(common.mustCall((req, res) => {
  const headers = { 'Content-Type': 'text/plain' };
  headers['Content-Length'] = 50;
  const socket = res.socket;
  res.writeHead(200, headers);
  res.write('aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd');
  if (abortRequest) {
    process.nextTick(() => socket.destroy());
  } else {
    process.nextTick(() => res.end('eeeeeeeeee'));
  }
}, N));

server.listen(0, common.mustCall(() => {
  download();
}));

const finishCountdown = new Countdown(N, common.mustCall(() => {
  server.close();
}));
const reqCountdown = new Countdown(N, common.mustCall());

function download() {
  const opts = {
    port: server.address().port,
    path: '/',
  };
  const req = http.get(opts);
  req.on('error', common.mustNotCall());
  req.on('response', (res) => {
    assert.strictEqual(res.statusCode, 200);
    assert.strictEqual(res.headers.connection, 'close');
    let aborted = false;
    const writable = new Writable({
      write(chunk, encoding, callback) {
        callback();
      }
    });
    res.pipe(writable);
    const _handle = res.socket._handle;
    _handle._close = res.socket._handle.close;
    _handle.close = function(callback) {
      _handle._close();
      // Set readable to true even though request is complete
      if (res.complete) res.readable = true;
      callback();
    };
    res.on('end', common.mustCall(() => {
      reqCountdown.dec();
    }));
    res.on('aborted', () => {
      aborted = true;
    });
    res.on('error', common.mustNotCall());
    writable.on('finish', () => {
      assert.strictEqual(aborted, abortRequest);
      finishCountdown.dec();
      if (finishCountdown.remaining === 0) return;
      abortRequest = false; // Next one should be a good response
      download();
    });
  });
  req.end();
}

redpajama_set_name: RedPajamaGithub


text:
"use strict";
const AWS = require('aws-sdk'),
	nconf = require('nconf'),
	Q = require('q'),
    util = require('util'),
    crypto = require('crypto');

var ConfKeys = {
	SnsTopicArn: 'aws.sns.TopicArn'
};

var isAWSInitialized = false;
function initAWS() {
	if (!Messenger.isAWSInitialized) {
		AWS.config.loadFromPath('./aws-sdk-secrets.json');
		Messenger.isAWSInitialized = true;
	}
};

var isConfigLoaded = false;
function loadConfig() {
	if (!Messenger.isConfigLoaded) {
		nconf.argv()
			.env()
			.file({ file: 'messenger-config.json' });
		Messenger.isConfigLoaded = true;
	}
};

module.exports = new Messenger();

function createHash(message) {
    if (!(message && Array.isArray(message)))
        throw new TypeError('Invalid argument. Expected array.');
    let hash = crypto.createHash('sha256');
    message.forEach((line) => hash.update(line));
    return hash.digest('base64');
}

function Messenger() {
	if (!(this instanceof Messenger)) return new Messenger();
	initAWS();
	loadConfig();
    this.topicArn = nconf.get(ConfKeys.SnsTopicArn);
    const SECONDS = 1000;
    const MINUTES = SECONDS * 60;
    /** Delay duplicate notifications to occur no more than every N milliseconds */
    const notificationDelayMilliseconds = 90 * MINUTES;
    /** As part of delaying duplicate notifications, we track the hash of the last notification */
    this.lastNotificationHash = null;
    this.lastNotifyTime = Date.now() - notificationDelayMilliseconds; // first error will trigger a notification

	this.saveDefaultConfig = function() {
		nconf.set(ConfKeys.SnsTopicArn, 'arn:aws:sns:YOURREGION:SOMENUMBER:YOURTOPICNAME');
		nconf.save();
	};
	// Sends the specified message and returns a promise.
	this.sendSMS = function(msg) {
		var deferred = Q.defer();
		var sns = new AWS.SNS();
		var params = {
			Message: msg, /* required */
			TopicArn: this.topicArn
		};
		var request = sns.publish(params, function(err, data) {
			if (err)
				deferred.reject(new Error(err));
			else
				deferred.resolve(data);
		});
		return deferred.promise;
	};

    this.sendNotification = function (messageLines) {
        if (!(typeof messageLines === 'string' || Array.isArray(messageLines)))
            throw new TypeError('Invalid argument. Expected string or array');
        if (!Array.isArray(messageLines)) {
            messageLines = [messageLines];
        }
        var newHash = createHash(messageLines);
        var millisecondsSinceLastError = Date.now() - this.lastNotifyTime;
        util.log('%s minutes since last notification...', millisecondsSinceLastError / MINUTES);
        if (newHash != this.lastNotificationHash || millisecondsSinceLastError > notificationDelayMilliseconds) {
            messageLines.forEach( (msg) => {
                this.sendSMS(msg).then(() => {}, (err) => util.log('error sending SMS: %s', err));
            });
            this.lastNotificationHash = newHash;
            this.lastNotifyTime = Date.now();
        } else {
            util.log('Notification is a duplicate of prior. Delaying this notification for %s more minutes. NOT sending notification.', (notificationDelayMilliseconds - millisecondsSinceLastError) / MINUTES );
        }
    }
};


text:
Setup Prometheus monitoring
===========================

Prometheus_ is a widely popular tool for monitoring and alerting a wide variety of systems. Dask.distributed exposes
scheduler and worker metrics in a prometheus text based format. Metrics are available at ``http://scheduler-address:8787/metrics`` when the ``prometheus_client`` package has been installed.

.. _Prometheus: https://prometheus.io

Available metrics are as following

+---------------------------------------------+------------------------------------------------+-----------+--------+
| Metric name                                 | Description                                    | Scheduler | Worker |
+=========================+===================+================================================+===========+========+
| python_gc_objects_collected_total           | Objects collected during gc.                   |    Yes    |  Yes   |
+---------------------------------------------+------------------------------------------------+-----------+--------+
| python_gc_objects_uncollectable_total       | Uncollectable object found during GC.          |    Yes    |  Yes   |
+---------------------------------------------+------------------------------------------------+-----------+--------+
| python_gc_collections_total                 | Number of times this generation was collected. |    Yes    |  Yes   |
+---------------------------------------------+------------------------------------------------+-----------+--------+
| python_info                                 | Python platform information.                   |    Yes    |  Yes   |
+---------------------------------------------+------------------------------------------------+-----------+--------+
| dask_scheduler_workers                      | Number of workers connected.                   |    Yes    |        |
+---------------------------------------------+------------------------------------------------+-----------+--------+
| dask_scheduler_clients                      | Number of clients connected.                   |    Yes    |        |
+---------------------------------------------+------------------------------------------------+-----------+--------+
| dask_scheduler_tasks                        | Number of tasks at scheduler.                  |    Yes    |        |
+---------------------------------------------+------------------------------------------------+-----------+--------+
| dask_worker_tasks                           | Number of tasks at worker.                     |           |  Yes   |
+---------------------------------------------+------------------------------------------------+-----------+--------+
| dask_worker_connections                     | Number of task connections to other workers.   |           |  Yes   |
+---------------------------------------------+------------------------------------------------+-----------+--------+
| dask_worker_threads                         | Number of worker threads.                      |           |  Yes   |
+---------------------------------------------+------------------------------------------------+-----------+--------+
| dask_worker_latency_seconds                 | Latency of worker connection.                  |           |  Yes   |
+---------------------------------------------+------------------------------------------------+-----------+--------+
| dask_worker_tick_duration_median_seconds    | Median tick duration at worker.                |           |  Yes   |
+---------------------------------------------+------------------------------------------------+-----------+--------+
| dask_worker_task_duration_median_seconds    | Median task runtime at worker.                 |           |  Yes   |
+---------------------------------------------+------------------------------------------------+-----------+--------+
| dask_worker_transfer_bandwidth_median_bytes | Bandwidth for transfer at worker in Bytes.     |           |  Yes   |
+---------------------------------------------+------------------------------------------------+-----------+--------+


text:
window.addEventListener("DOMContentLoaded", function () {

    // warning of missing CSS Shapes support shown by default
    var warning = document.getElementById('warning');

    function support() {
        var style = window.getComputedStyle(document.body, null);
        var prefixes = ['','-webkit-'];

        //returns true if CSS Shapes Level 1 is supported, prefixed or not
        //browsers without Array.some are unlikely to support CSS Shapes anyway
        return prefixes.some(function(prefix){
          return prefix + "shape-outside" in style;
        });
    }

    if (!support()) {
        warning.className = "";
    }
}, false);


text:
package com.backend.rybakowka;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.web.bind.annotation.CrossOrigin;

@SpringBootApplication
@EnableCaching
//@CrossOrigin(origins = "http://localhost:4200")
//@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class RybakowkaApplication {

	public static void main(String[] args) {
		SpringApplication.run(RybakowkaApplication.class, args);
	}
}


text:
namespace EasyNetQ.Scheduler
{
    public class SchedulerServiceConfiguration : ConfigurationBase
    {
        public int PublishIntervalSeconds { get; set; }
        public int PurgeIntervalSeconds { get; set; }

        public static SchedulerServiceConfiguration FromConfigFile()
        {
            return new SchedulerServiceConfiguration
            {
                PublishIntervalSeconds = GetIntAppSetting("PublishIntervalSeconds"),
                PurgeIntervalSeconds = GetIntAppSetting("PurgeIntervalSeconds")
            };
        }
    }
}


text:
//
//  ChannelListViewController.m
//  DemoHaHaHa
//
//  Created by fm on 2017/7/20.
//  Copyright © 2017年 wangjiuyin. All rights reserved.
//

#import "ChannelListViewController.h"
#import "ChannellistControl.h"

@interface ChannelListViewController ()

@property (nonatomic, strong) ChannellistControl *control;

@end

@implementation ChannelListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    WS(weakSelf);
    [self.view addSubview:self.channelListView];
    [self.channelListView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    [self.control registerCell];
    [self.control loadData];
}

#pragma mark - getter & setter
- (ChannellistControl *)control
{
    if (!_control) {
        _control = [[ChannellistControl alloc] init];
        _control.vc = self;
    }
    return _control;
}

- (UITableView *)channelListView
{
    if (!_channelListView) {
        _channelListView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _channelListView.backgroundColor = [UIColor whiteColor];
        _channelListView.delegate = self.control;
        _channelListView.dataSource = self.control;
        _channelListView.showsHorizontalScrollIndicator = NO;
        _channelListView.showsVerticalScrollIndicator = NO;
        _channelListView.tableHeaderView = self.tableHeaderView;
    }
    return _channelListView;
}

- (ChannelTableHeaderView *)tableHeaderView
{
    if (!_tableHeaderView) {
        _tableHeaderView = [[ChannelTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, 60)];
        [_tableHeaderView updateContent:@"编辑我订阅的频道"];
        [_tableHeaderView addTarget:self.control action:@selector(toEditChannel) forControlEvents:UIControlEventTouchUpInside];
    }
    return _tableHeaderView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
package org.apache.geronimo.test.jsf.web;

import java.io.IOException;

import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

public class HeadingTag extends UIComponentBase {

    public HeadingTag() {
    }

    @Override
    public void encodeBegin(FacesContext context) throws IOException {
        ResponseWriter writer = context.getResponseWriter();

        String message = (String) getAttributes().get("message");
        String type = (String) getAttributes().get("type");

        writer.startElement(type, this);
        writer.writeText(message, null);
        writer.endElement(type);
    }

    @Override
    public String getFamily() {
        return "Heading";
    }

}


text:
package egovmei.apps.modules.dashboard.mapper;

import egovframework.rte.psl.dataaccess.mapper.Mapper;
import egovmei.apps.modules.dashboard.dao.DashboardDAO;

/**
 * mybatis dao
 * @author Seok Kyun. Choi. 최석균 (Syaku)
 * @site http://syaku.tistory.com
 * @since 2016. 11. 1.
 */
@Mapper
public interface DashboardEgovMapper extends DashboardDAO {
}


text:
/* eslint indent: ["off"] */
import $ from 'dom7';
import Utils from '../../utils/utils';
import Framework7Class from '../../utils/class';

class PhotoBrowser extends Framework7Class {
  constructor(app, params = {}) {
    super(params, [app]);

    const pb = this;
    pb.app = app;

    const defaults = Utils.extend({
      on: {},
    }, app.params.photoBrowser);

    // Extend defaults with modules params
    pb.useModulesParams(defaults);

    pb.params = Utils.extend(defaults, params);

    Utils.extend(pb, {
      exposed: false,
      opened: false,
      activeIndex: pb.params.swiper.initialSlide,
      url: pb.params.url,
      view: pb.params.view || app.views.main,
      swipeToClose: {
        allow: true,
        isTouched: false,
        diff: undefined,
        start: undefined,
        current: undefined,
        started: false,
        activeSlide: undefined,
        timeStart: undefined,
      },
    });

    // Install Modules
    pb.useModules();

    // Init
    pb.init();
  }
  onSlideChange(swiper) {
    const pb = this;
    pb.activeIndex = swiper.activeIndex;

    let current = swiper.activeIndex + 1;
    let total = pb.params.virtualSlides ? pb.params.photos.length : swiper.slides.length;
    if (swiper.params.loop) {
      total -= 2;
      current -= swiper.loopedSlides;
      if (current < 1) current = total + current;
      if (current > total) current -= total;
    }

    const $activeSlideEl = pb.params.virtualSlides
      ? swiper.$wrapperEl.find(`.swiper-slide[data-swiper-slide-index="${swiper.activeIndex}"]`)
      : swiper.slides.eq(swiper.activeIndex);
    const $previousSlideEl = pb.params.virtualSlides
      ? swiper.$wrapperEl.find(`.swiper-slide[data-swiper-slide-index="${swiper.previousIndex}"]`)
      : swiper.slides.eq(swiper.previousIndex);

    let $currentEl = pb.$el.find('.photo-browser-current');
    let $totalEl = pb.$el.find('.photo-browser-total');
    if (pb.params.type === 'page' && pb.params.navbar && $currentEl.length === 0 && pb.app.theme === 'ios') {
      const navbarEl = pb.app.navbar.getElByPage(pb.$el);
      if (navbarEl) {
        $currentEl = $(navbarEl).find('.photo-browser-current');
        $totalEl = $(navbarEl).find('.photo-browser-total');
      }
    }
    $currentEl.text(current);
    $totalEl.text(total);

    // Update captions
    if (pb.captions.length > 0) {
      const captionIndex = swiper.params.loop ? $activeSlideEl.attr('data-swiper-slide-index') : pb.activeIndex;
      pb.$captionsContainerEl.find('.photo-browser-caption-active').removeClass('photo-browser-caption-active');
      pb.$captionsContainerEl.find(`[data-caption-index="${captionIndex}"]`).addClass('photo-browser-caption-active');
    }

    // Stop Video
    const previousSlideVideo = $previousSlideEl.find('video');
    if (previousSlideVideo.length > 0) {
      if ('pause' in previousSlideVideo[0]) previousSlideVideo[0].pause();
    }
  }
  onTouchStart() {
    const pb = this;
    const swipeToClose = pb.swipeToClose;
    if (!swipeToClose.allow) return;
    swipeToClose.isTouched = true;
  }
  onTouchMove(e) {
    const pb = this;
    const swipeToClose = pb.swipeToClose;

    if (!swipeToClose.isTouched) return;
    if (!swipeToClose.started) {
      swipeToClose.started = true;
      swipeToClose.start = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
      if (pb.params.virtualSlides) {
        swipeToClose.activeSlide = pb.swiper.$wrapperEl.children('.swiper-slide-active');
      } else {
        swipeToClose.activeSlide = pb.swiper.slides.eq(pb.swiper.activeIndex);
      }
      swipeToClose.timeStart = Utils.now();
    }
    e.preventDefault();
    swipeToClose.current = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
    swipeToClose.diff = swipeToClose.start - swipeToClose.current;
    const opacity = 1 - (Math.abs(swipeToClose.diff) / 300);
    const color = pb.exposed || pb.params.theme === 'dark' ? 0 : 255;
    swipeToClose.activeSlide.transform(`translate3d(0,${-swipeToClose.diff}px,0)`);
    pb.swiper.$el.css('background-color', `rgba(${color}, ${color}, ${color}, ${opacity})`).transition(0);
  }
  onTouchEnd() {
    const pb = this;
    const swipeToClose = pb.swipeToClose;
    swipeToClose.isTouched = false;
    if (!swipeToClose.started) {
      swipeToClose.started = false;
      return;
    }
    swipeToClose.started = false;
    swipeToClose.allow = false;
    const diff = Math.abs(swipeToClose.diff);
    const timeDiff = (new Date()).getTime() - swipeToClose.timeStart;
    if ((timeDiff < 300 && diff > 20) || (timeDiff >= 300 && diff > 100)) {
      Utils.nextTick(() => {
        if (pb.$el) {
          if (swipeToClose.diff < 0) pb.$el.addClass('swipe-close-to-bottom');
          else pb.$el.addClass('swipe-close-to-top');
        }
        pb.emit('local::swipeToClose', pb);
        pb.close();
        swipeToClose.allow = true;
      });
      return;
    }
    if (diff !== 0) {
      swipeToClose.activeSlide.addClass('photo-browser-transitioning').transitionEnd(() => {
        swipeToClose.allow = true;
        swipeToClose.activeSlide.removeClass('photo-browser-transitioning');
      });
    } else {
      swipeToClose.allow = true;
    }
    pb.swiper.$el.transition('').css('background-color', '');
    swipeToClose.activeSlide.transform('');
  }

  // Render Functions
  renderNavbar() {
    const pb = this;
    if (pb.params.renderNavbar) return pb.params.renderNavbar.call(pb);

    let iconsColor = pb.params.iconsColor;
    if (!pb.params.iconsColor && pb.params.theme === 'dark') iconsColor = 'white';

    const backLinkText = pb.app.theme === 'ios' && pb.params.backLinkText ? pb.params.backLinkText : '';

    const isPopup = pb.params.type !== 'page';
    const navbarHtml = `

              <i class="icon icon-back ${iconsColor ? `color-${iconsColor}` : ''}">
              ${backLinkText ? `<span>${backLinkText}</span>` : ''}

            ${pb.params.navbarOfText}

    `.trim();
    return navbarHtml;
  }
  renderToolbar() {
    const pb = this;
    if (pb.params.renderToolbar) return pb.params.renderToolbar.call(pb);

    let iconsColor = pb.params.iconsColor;
    if (!pb.params.iconsColor && pb.params.theme === 'dark') iconsColor = 'white';

    const toolbarHtml = `

            <i class="icon icon-back ${iconsColor ? `color-${iconsColor}` : ''}">

            <i class="icon icon-forward ${iconsColor ? `color-${iconsColor}` : ''}">

    `.trim();
    return toolbarHtml;
  }
  renderCaption(caption, index) {
    const pb = this;
    if (pb.params.renderCaption) return pb.params.renderCaption.call(pb, caption, index);
    const captionHtml = `

        ${caption}

    `.trim();
    return captionHtml;
  }
  renderObject(photo, index) {
    const pb = this;
    if (pb.params.renderObject) return pb.params.renderObject.call(pb, photo, index);
    const objHtml = `

${photo.html ? photo.html : photo}

    `;
    return objHtml;
  }
  renderLazyPhoto(photo, index) {
    const pb = this;
    if (pb.params.renderLazyPhoto) return pb.params.renderLazyPhoto.call(pb, photo, index);
    const photoHtml = `

${pb.app.theme === 'md' ? Utils.mdPreloaderContent : ''}

    `.trim();
    return photoHtml;
  }
  renderPhoto(photo, index) {
    const pb = this;
    if (pb.params.renderPhoto) return pb.params.renderPhoto.call(pb, photo, index);
    const photoHtml = `

    `.trim();
    return photoHtml;
  }
  render() {
    const pb = this;
    if (pb.params.render) return pb.params.render.call(pb, pb.params);
    const html = `

            ${pb.params.navbar ? pb.renderNavbar() : ''}
            ${pb.params.toolbar ? pb.renderToolbar() : ''}

              ${pb.params.photos.map((photo, index) => {
                if (photo.caption) return pb.renderCaption(photo.caption, index);
                return '';
              }).join(' ')}

                ${pb.params.virtualSlides ? '' : pb.params.photos.map((photo, index) => {
                  if (photo.html || ((typeof photo === 'string' || photo instanceof String) && photo.indexOf('<') >= 0 && photo.indexOf('>') >= 0)) {
                    return pb.renderObject(photo, index);
                  } else if (pb.params.swiper.lazy === true || (pb.params.swiper.lazy && pb.params.swiper.lazy.enabled)) {
                    return pb.renderLazyPhoto(photo, index);
                  }
                  return pb.renderPhoto(photo, index);
                }).join(' ')}

    `.trim();
    return html;
  }
  renderStandalone() {
    const pb = this;
    if (pb.params.renderStandalone) return pb.params.renderStandalone.call(pb);
    const standaloneHtml = `<div class="popup photo-browser-popup photo-browser-standalone popup-tablet-fullscreen">${pb.render()}</div>`;
    return standaloneHtml;
  }
  renderPage() {
    const pb = this;
    if (pb.params.renderPage) return pb.params.renderPage.call(pb);
    const pageHtml = pb.render();

    return pageHtml;
  }
  renderPopup() {
    const pb = this;
    if (pb.params.renderPopup) return pb.params.renderPopup.call(pb);
    const popupHtml = `<div class="popup photo-browser-popup">${pb.render()}</div>`;

    return popupHtml;
  }

  // Callbacks
  onOpen(type, el) {
    const pb = this;
    const app = pb.app;
    const $el = $(el);

    $el[0].f7PhotoBrowser = pb;

    pb.$el = $el;
    pb.el = $el[0];
    pb.openedIn = type;
    pb.opened = true;

    pb.$swiperContainerEl = pb.$el.find('.photo-browser-swiper-container');
    pb.$swiperWrapperEl = pb.$el.find('.photo-browser-swiper-wrapper');
    pb.slides = pb.$el.find('.photo-browser-slide');
    pb.$captionsContainerEl = pb.$el.find('.photo-browser-captions');
    pb.captions = pb.$el.find('.photo-browser-caption');

    // Init Swiper
    const swiperParams = Utils.extend({}, pb.params.swiper, {
      initialSlide: pb.activeIndex,
      on: {
        tap(e) {
          pb.emit('local::tap', e);
        },
        click(e) {
          if (pb.params.exposition) {
            pb.expositionToggle();
          }
          pb.emit('local::click', e);
        },
        doubleTap(e) {
          pb.emit('local::doubleTap', e);
        },
        slideChange(...args) {
          const swiper = this;
          pb.onSlideChange(swiper);
          pb.emit('local::slideChange', ...args);
        },
        transitionStart(...args) {
          pb.emit('local::transitionStart', ...args);
        },
        transitionEnd(...args) {
          pb.emit('local::transitionEnd', ...args);
        },
        slideChangeStart(...args) {
          pb.emit('local::slideChangeTransitionStart', ...args);
        },
        slideChangeEnd(...args) {
          pb.emit('local::slideChangeTransitionEnd', ...args);
        },
        lazyImageLoad(...args) {
          pb.emit('local::lazyImageLoad', ...args);
        },
        lazyImageReady(...args) {
          const slideEl = args[0];
          $(slideEl).removeClass('photo-browser-slide-lazy');
          pb.emit('local::lazyImageReady', ...args);
        },
      },
    });
    if (pb.params.swipeToClose && pb.params.type !== 'page') {
      Utils.extend(swiperParams.on, {
        touchStart(e) {
          pb.onTouchStart(e);
          pb.emit('local::touchStart', e);
        },
        touchMoveOpposite(e) {
          pb.onTouchMove(e);
          pb.emit('local::touchMoveOpposite', e);
        },
        touchEnd(e) {
          pb.onTouchEnd(e);
          pb.emit('local::touchEnd', e);
        },
      });
    }
    if (pb.params.virtualSlides) {
      Utils.extend(swiperParams, {
        virtual: {
          slides: pb.params.photos,
          renderSlide(photo, index) {
            if (photo.html || ((typeof photo === 'string' || photo instanceof String) && photo.indexOf('<') >= 0 && photo.indexOf('>') >= 0)) {
              return pb.renderObject(photo, index);
            } else if (pb.params.swiper.lazy === true || (pb.params.swiper.lazy && pb.params.swiper.lazy.enabled)) {
              return pb.renderLazyPhoto(photo, index);
            }
            return pb.renderPhoto(photo, index);
          },
        },
      });
    }

    pb.swiper = app.swiper.create(pb.$swiperContainerEl, swiperParams);

    if (pb.activeIndex === 0) {
      pb.onSlideChange(pb.swiper);
    }
    if (pb.$el) {
      pb.$el.trigger('photobrowser:open');
    }
    pb.emit('local::open photoBrowserOpen', pb);
  }
  onOpened() {
    const pb = this;

    if (pb.$el) {
      pb.$el.trigger('photobrowser:opened');
    }
    pb.emit('local::opened photoBrowserOpened', pb);
  }
  onClose() {
    const pb = this;
    if (pb.destroyed) return;

    // Destroy Swiper
    if (pb.swiper && pb.swiper.destroy) {
      pb.swiper.destroy(true, false);
      pb.swiper = null;
      delete pb.swiper;
    }
    if (pb.$el) {
      pb.$el.trigger('photobrowser:close');
    }
    pb.emit('local::close photoBrowserClose', pb);
  }
  onClosed() {
    const pb = this;
    if (pb.destroyed) return;
    pb.opened = false;
    pb.$el = null;
    pb.el = null;
    delete pb.$el;
    delete pb.el;
    if (pb.$el) {
      pb.$el.trigger('photobrowser:closed');
    }
    pb.emit('local::closed photoBrowserClosed', pb);
  }

  // Open
  openPage() {
    const pb = this;
    if (pb.opened) return pb;

    const pageHtml = pb.renderPage();

    pb.view.router.navigate({
      url: pb.url,
      route: {
        content: pageHtml,
        path: pb.url,
        on: {
          pageBeforeIn(e, page) {
            pb.view.$el.addClass(`with-photo-browser-page with-photo-browser-page-${pb.params.theme}`);
            pb.onOpen('page', page.el);
          },
          pageAfterIn(e, page) {
            pb.onOpened('page', page.el);
          },
          pageBeforeOut(e, page) {
            pb.view.$el.removeClass(`with-photo-browser-page with-photo-browser-page-exposed with-photo-browser-page-${pb.params.theme}`);
            pb.onClose('page', page.el);
          },
          pageAfterOut(e, page) {
            pb.onClosed('page', page.el);
          },
        },
      },
    });
    return pb;
  }

  openStandalone() {
    const pb = this;
    if (pb.opened) return pb;

    const standaloneHtml = pb.renderStandalone();

    const popupParams = {
      backdrop: false,
      content: standaloneHtml,
      on: {
        popupOpen(popup) {
          pb.onOpen('popup', popup.el);
        },
        popupOpened(popup) {
          pb.onOpened('popup', popup.el);
        },
        popupClose(popup) {
          pb.onClose('popup', popup.el);
        },
        popupClosed(popup) {
          pb.onClosed('popup', popup.el);
        },
      },
    };

    if (pb.params.routableModals) {
      pb.view.router.navigate({
        url: pb.url,
        route: {
          path: pb.url,
          popup: popupParams,
        },
      });
    } else {
      pb.modal = pb.app.popup.create(popupParams).open();
    }
    return pb;
  }

  openPopup() {
    const pb = this;
    if (pb.opened) return pb;

    const popupHtml = pb.renderPopup();

    const popupParams = {
      content: popupHtml,
      on: {
        popupOpen(popup) {
          pb.onOpen('popup', popup.el);
        },
        popupOpened(popup) {
          pb.onOpened('popup', popup.el);
        },
        popupClose(popup) {
          pb.onClose('popup', popup.el);
        },
        popupClosed(popup) {
          pb.onClosed('popup', popup.el);
        },
      },
    };

    if (pb.params.routableModals) {
      pb.view.router.navigate({
        url: pb.url,
        route: {
          path: pb.url,
          popup: popupParams,
        },
      });
    } else {
      pb.modal = pb.app.popup.create(popupParams).open();
    }
    return pb;
  }

  // Exposition
  expositionEnable() {
    const pb = this;
    if (pb.params.type === 'page') {
      pb.view.$el.addClass('with-photo-browser-page-exposed');
    }
    if (pb.$el) pb.$el.addClass('photo-browser-exposed');
    if (pb.params.expositionHideCaptions) pb.$captionsContainerEl.addClass('photo-browser-captions-exposed');
    pb.exposed = true;
    return pb;
  }
  expositionDisable() {
    const pb = this;
    if (pb.params.type === 'page') {
      pb.view.$el.removeClass('with-photo-browser-page-exposed');
    }
    if (pb.$el) pb.$el.removeClass('photo-browser-exposed');
    if (pb.params.expositionHideCaptions) pb.$captionsContainerEl.removeClass('photo-browser-captions-exposed');
    pb.exposed = false;
    return pb;
  }
  expositionToggle() {
    const pb = this;
    if (pb.params.type === 'page') {
      pb.view.$el.toggleClass('with-photo-browser-page-exposed');
    }
    if (pb.$el) pb.$el.toggleClass('photo-browser-exposed');
    if (pb.params.expositionHideCaptions) pb.$captionsContainerEl.toggleClass('photo-browser-captions-exposed');
    pb.exposed = !pb.exposed;
    return pb;
  }
  open(index) {
    const pb = this;
    const type = pb.params.type;
    if (pb.opened) {
      if (pb.swiper && typeof index !== 'undefined') {
        pb.swiper.slideTo(parseInt(index, 10));
      }
      return pb;
    } else if (typeof index !== 'undefined') {
      pb.activeIndex = index;
    }
    if (type === 'standalone') {
      pb.openStandalone();
    }
    if (type === 'page') {
      pb.openPage();
    }
    if (type === 'popup') {
      pb.openPopup();
    }
    return pb;
  }
  close() {
    const pb = this;
    if (!pb.opened) return pb;
    if (pb.params.routableModals || pb.openedIn === 'page') {
      if (pb.view) pb.view.router.back();
    } else {
      pb.modal.once('modalClosed', () => {
        Utils.nextTick(() => {
          pb.modal.destroy();
          delete pb.modal;
        });
      });
      pb.modal.close();
    }
    return pb;
  }
  // eslint-disable-next-line
  init() {}
  destroy() {
    let pb = this;
    pb.emit('local::beforeDestroy photoBrowserBeforeDestroy', pb);
    if (pb.$el) {
      pb.$el.trigger('photobrowser:beforedestroy');
      delete pb.$el[0].f7PhotoBrowser;
    }
    Utils.deleteProps(pb);
    pb = null;
  }
}

export default PhotoBrowser;


text:
<?xml version="1.0" encoding="UTF-8"?>
<parser-result-sets>
    <parser-result sql-case-id="truncate_table">
        <tables>

        </tables>
        <tokens>

        </tokens>
    </parser-result>

    <parser-result sql-case-id="truncate_table_only">
        <tables>

        </tables>
        <tokens>

        </tokens>
    </parser-result>
</parser-result-sets>


text:
/**
  Renders a list of items, then changes them all.
**/
Perf.TemplateBindingProfiler = Perf.Benchmark.extend({
  //testCount: 40,
  name: 'Template Bindings',
  lastAge: 1,

  setup: function(){
    var people = [];

    for (var i=0; i<500; i++) {
      people.push(Em.Object.create({name: "Person " + i, age: this.nextAge()}));
    }

    var templateBindingsView = this.renderToScratch('templateBindings', {people: people});

    this.set('people', people);
    this.set('templateBindingsView', templateBindingsView);
  },

  test: function() {
    var people = this.get('people');

    for (var i=0; i<people.length; i++) {
      people[i].set('age', this.nextAge());
    }
  },

  teardown: function(){
    this.get('templateBindingsView').destroy();
  },

  nextAge: function() {
    this.incrementProperty('lastAge');
    if (this.get('lastAge') > 99) { this.set('lastAge', 1)}

    return this.get('lastAge');
  }
});


text:
package com.vaadin.addon.charts;

import java.io.Serializable;

/**
 * Listener interface for series show events
 */
public interface SeriesShowListener extends Serializable {

    /**
     * Called when a series is shown
     *
     * @param event
     *            the {@link SeriesShowEvent} containing information on the
     *            event.
     */
    public void onShow(SeriesShowEvent event);

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Angular Webpack</title>
    <base href="/">
    <link rel="stylesheet" href="dist/style.css" type="text/css">

Angular Webpack

    <ui-view></ui-view>


text:
package org.hisp.dhis.android.core.program.programindicatorengine.internal.function;

import org.hisp.dhis.android.core.parser.internal.expression.CommonExpressionVisitor;
import org.hisp.dhis.parser.expression.antlr.ExpressionParser;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class D2CeilShould {

    @Mock
    private ExpressionParser.ExprContext context;

    @Mock
    private CommonExpressionVisitor visitor;

    @Mock
    private ExpressionParser.ExprContext mockedFirstExpr;

    private D2Ceil ceil = new D2Ceil();

    @Before
    public void setUp() {
        when(context.expr(0)).thenReturn(mockedFirstExpr);
    }

    @Test
    public void evaluateMustReturnCeiledValue() {
        when(visitor.castStringVisit(mockedFirstExpr)).thenReturn("4.1");
        assertThat(ceil.evaluate(context, visitor)).isEqualTo("5");

        when(visitor.castStringVisit(mockedFirstExpr)).thenReturn("0.8");
        assertThat(ceil.evaluate(context, visitor)).isEqualTo("1");

        when(visitor.castStringVisit(mockedFirstExpr)).thenReturn("5.1");
        assertThat(ceil.evaluate(context, visitor)).isEqualTo("6");

        when(visitor.castStringVisit(mockedFirstExpr)).thenReturn("1");
        assertThat(ceil.evaluate(context, visitor)).isEqualTo("1");

        when(visitor.castStringVisit(mockedFirstExpr)).thenReturn("-9.3");
        assertThat(ceil.evaluate(context, visitor)).isEqualTo("-9");

        when(visitor.castStringVisit(mockedFirstExpr)).thenReturn("-5.9");
        assertThat(ceil.evaluate(context, visitor)).isEqualTo("-5");
    }

    @Test
    public void return_zero_when_number_is_invalid() {
        when(visitor.castStringVisit(mockedFirstExpr)).thenReturn("not a number");

        assertThat(ceil.evaluate(context, visitor)).isEqualTo("0");
    }
}


text:
<?php namespace Merchant\Repositories\Interfaces;

use Merchant\Campaign;

interface CampaignInterface
{
    /**
     * Get Campaign by id.
     *
     * @param integer $id
     *
     * @return Merchant
     */
    public function getById($id);

    /**
     * Get Campaign by attributes.
     *
     * @param array $attributes
     * @param boolean $toArray
     * @return Campaign
     */
    public function getByAttributes(array $attributes, $toArray = true);

    /**
     * Get Campaign by id and attributes.
     *
     * @param integer $id
     * @param array $attributes
     * @return Merchant
     */
    public function getByIdAndAttiributes($id, array $attributes);

    /**
     * Get all Campaign by attributes
     *
     * @param array $attributes
     * @param string $orderBy
     * @param string $sort
     * @return Campaign
     */
    public function getAllByAttributes(array $attributes, $orderBy = '', $sort = 'ASC');

    /**
     * Get all Campaign by attributes with relationships
     *
     * @param array $attributes
     * @param array $relations
     * @param string $orderBy
     * @param string $sort
     * @return Campaign
     */
    public function getAllByAttributesWithRelations(array $attributes, array $relations, $orderBy = '', $sort = 'ASC');

    /**
     * Create new campaign.
     *
     * @param array $payload
     *
     * @return Campaign
     */
    public function create($payload);

    /**
     * Update a campaign by id.
     *
     * @param integer $id
     * @param array $payload
     *
     * @return boolean
     */
    public function updateById($id, array $payload);

    /**
     * Update a campaign by attributes.
     *
     * @param array $attributes
     * @param array $payload
     *
     * @return boolean
     */
    public function updateByAttributes(array $attributes, array $payload);

    /**
     * Delete an campaign.
     *
     * @param integer $id
     * @return Campaign
     */
    public function delete($id);
}


text:
/**
 * @namespace
 */
Html = {

	templates: {

	},

	params: {
		replace: {
			"\\r\\n": "
",
			"\\n\\r": "
",
			"
\\s*
": "
",
			"
\\s*
": "
",
			"
\\s*
": "
",
			"
\\s*
": "
",
			"
\\s*
": "
"
		}
	},

	_templateNamePattern: new RegExp("^<\\!--\\s*([\\w\\-]+)\\s*-->\\s*$"),

	_dom: null,

	/**
	 * Initializes namespace
	 */
	initialize: function() {
		//eval(new ActiveXObject("Scripting.FileSystemObject").OpenTextFile(scriptRoot + "Diff\\diff_match_patch_uncompressed.js", 1).ReadAll());
		this._dom = new ActiveXObject("MSXML2.DOMDocument");
		this._dom.validateOnParse = false;
		this._dom.async = false;
		var xml = "<node></node>";
		var parsed = this._dom.loadXML(xml);
		if (!parsed)
			throw new Error("Error parsing XHTML file " + xml + ":" + this._dom.parseError.reason);
	},

	/**
	 * Loads HTML templates from specified file
	 *
	 * @param {Sys.IO.File} file File reference or path to file (string)
	 * @param {Object} context Namespace containing templates file
	 */
	loadTemplates: function(file, context) {
		if (typeof file == "string") {
			file = new Sys.IO.File(file, Sys.IO.Mode.READ, Sys.IO.Unicode.DEFAULT, context);
		}
		var templateName = null, template = "";
		while (!file.atEnd()) {
			var line = file.readLine();
			var newTemplate = Html._templateNamePattern.exec(line);
			if (newTemplate) {
				if (templateName) {
					Html.templates[templateName] = new Html.Template(templateName, template.replace(/[\r\n]+$/, "").replace(/^[\r\n]+/, ""));
				}
				templateName = newTemplate[1];
				template = "";
			}
			else {
				template = template + "\n" + line;
			}
		}
		if (templateName) {
			Html.templates[templateName] = new Html.Template(templateName, template);
		}
	},

	/**
	 * Loads XHTML templates from specified file
	 *
	 * @param {Sys.IO.File} file File reference or path to file (string)
	 * @param {Object} context Namespace containing templates file
	 * @param {Map<String, Function>} extensions
	 */
	loadXTemplates: function(file, context, extensions) {
		if (typeof file == "string") {
			file = new Sys.IO.File(file, Sys.IO.Mode.READ, Sys.IO.Unicode.DEFAULT, context);
		}
		var xml = file.readAll();
		var dom = new ActiveXObject("MSXML2.DOMDocument");
		dom.validateOnParse = false;
		dom.async = false;
		var parsed = dom.loadXML(xml);
		if (!parsed)
			throw new Error("Error parsing XHTML file " + file.getName() + ":" + dom.parseError.reason);

		var template = new Html.XTemplate("", dom, null, extensions);
		file.close();
		return template;
	}
};

Html.Template = extend(Core.Types.Named, {

	_template: null,

	/**
	 * @param {String} name
	 * @param {String} template
	 */
	create: function(name, template) {
		_super.create(name);
		this._template = template;
	},

	/**
	 * Generates output using provided parameters
	 *
	 * @param {Object} params
	 * @type {String}
	 */
	generate: function(params) {
		var generated = Core.Output.exec(this._template, params, Html.templates);
		for (var search in Html.params.replace) {
			var replace = Html.params.replace[search];
			generated = generated.replace(new RegExp(search, "g"), replace);
		}
		return generated;
	}
});

Html.XTemplate = extend(Core.Types.Named, {

	_dom: null,
	_extensions: null,
	parent: null,
	name: null,
	context: null,
	templates: null,

	/**
	 * @param {IXMLDOMElement} dom XHTML DOM element defining this template
	 * @param {Html.XTemplate} parent parent template if any
	 * @param {Map<String, Function>} extensions template extensions
	 */
	create: function(name, dom, parent, extensions) {

		this._dom = dom;
		this._extensions = extensions || {};
		this.parent = parent;
		this.name = name;

		_super.create(name);

		this.context = {
			$: (parent ? parent.context : null)
		};
		this.templates = {};

		var template = this;
		var findTemplates = function(node) {
			var children = node.childNodes;
			var templateNodes = [];
			for (var n = 0; n < children.length; n++) {
				var child = children[n];
				if (child.nodeTypeString == "element") {
					if (child.nodeName == "ea:template") {
						var attributes = template._prepareAttributes(child.attributes, "ea");
						var name = attributes.ea.name;
						var childTemplate = new Html.XTemplate(name, child, template);
						template.templates[name] = childTemplate;
						templateNodes.push(child);
					}
					else {
						findTemplates(child);
					}
				}
			}
			for (var t = 0; t < templateNodes.length; t++) {
				node.removeChild(templateNodes[t]);
			}
		};
		findTemplates(dom);
	},

	_prepareAttributes: function(attributes, tagNs) {
		var attrs = {
			ea: {}
		};
		for (var a = 0; a < attributes.length; a++) {
			var name = attributes[a].name;
			var ns = tagNs || "_default";
			var parts = name.split(":");
			if (parts.length == 2) {
				name = parts[1];
				ns = parts[0];
			}
			if (!(ns in attrs))
				attrs[ns] = {};
			attrs[ns][name] = unescape(attributes[a].value);
		}
		return attrs;
	},

	/**
	 * @param {String} name
	 * @type {Function}
	 */
	_findExtension: function(name) {
		var extension = this._extensions[name];
		if (!extension) {
			if (this.parent)
				extension = this.parent._findExtension(name);
			else
				extension = null;
		}
		return extension;
	},

	/**
	 * @param {Sting} name Template name
	 * @type {Html.XTemplate}
	 */
	findTemplate: function(name) {
		var template = this.templates[name];
		if (!template) {
			if (this.parent)
				template = this.parent.findTemplate(name);
			else
				template = null;
		}
		return template;
	},

	/**
	 * Generates output using provided parameters
	 *
	 * @param {Object} params
	 * @param {Html.IO.File} output
	 * @type {String}
	 */
	generate: function(params, output) {

		params = params || [];
		var generated = "";

		var generate = function(string, mode) {
			var isContect = (mode == Html.IO.ProcessContentMode.CONTENT);
			if (isContect) {
				if (output.processing.trimContent)
					string = string.trim();
				mode = output.processing.processContentAs;
			}
			switch (mode) {
			case Html.IO.ProcessContentMode.RAW:
				break;
			case Html.IO.ProcessContentMode.XML:
				var textNode = Html._dom.createTextNode(string);
				string = textNode.xml;
				break;
			case Html.IO.ProcessContentMode.ATTRIBUTE:
				var attribute = Html._dom.createAttribute("a");
				attribute.value = string;
				var xml = attribute.xml;
				string = xml.substring(3, xml.length - 1);
				break;
			case Html.IO.ProcessContentMode.HTML:
				var dom = new ActiveXObject("MSXML2.DOMDocument");
				dom.validateOnParse = false;
				dom.async = false;
				var xml = "" + string + "";
				var parsed = dom.loadXML(xml);
				if (!parsed)
					throw new Error("Error parsing XHTML file " + xml + ":" + dom.parseError.reason);
				var content = dom.documentElement.childNodes;
				xml = dom.documentElement.xml;
				xml = xml.substring(xml.indexOf(">") + 1, xml.lastIndexOf("<"));
				string = xml;
				break;
			default:
				throw new Error("Unsupported mode: " + mode);
			}
			if (isContect && string) {
				var filter = output.processing.filterContent;
				if (filter) {
					for (var f = 0; f < filter.length; f++)
						string = filter[f].call(string);
				}
			}
			output.writeString(string);
		};

		var template = this;
		var buildRt = function(context) {
			var rt = {};
			var ct2rt = function(ct) {
				for (var name in ct) {
					if (name != "$" && !(name in rt))
						rt[name] = ct[name];
				}
				if (ct.$ != null) {
					ct2rt(ct.$);
				}
			};
			ct2rt(context);
			return rt;
		};
		var unescape = function(text) {
			return text.replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
		};
		var processScript = function(script, context) {
			var rt = buildRt(context);
			eval("var fn = function(" + Core.Utils.getNames(rt).join(", ") + ") {return " + script + ";}");
			var result;
			try {
				result = fn.apply(null, Core.Utils.getValues(rt));
			}
			catch (error) {
				throw new Error("Evaluation error: '" + error.message + "', script: '" + script + "'");
			}
			return result;
		};
		var processText = function(text, context) {
			var s = text.indexOf("{{");
			var e = text.indexOf("}}");
			if (s != -1 && e != -1) {
				return text.substring(0, s) + processScript(text.substring(s + 2, e), context) + processText(text.substring(e + 2), context);
			}
			else {
				return text;
			}
		};
		var generateAttributes = function(attributes, ns, context) {
			for (var name in attributes) {
				var qName = (ns ? ns + ":" : "") + name;
				if (qName != "xmlns:ea") {
					var value = processText(attributes[name], context);
					generate(" " + qName + "=\"", Html.IO.ProcessContentMode.RAW);
					generate(value, Html.IO.ProcessContentMode.ATTRIBUTE);
					generate("\"", Html.IO.ProcessContentMode.RAW);
				}
			}
		};
		var SCRIPT = 0,
			IGNORE = 1,
			NAME = 2,
			TEMPLATE = 3,
			EXTENSION = 4;
		var prepareAttributes = function(attributes, tag, context, types) {
			var result = {};
			for (var name in attributes) {
				if (name in types) {
					var type = types[name];
					switch (type) {
					case IGNORE:
						break;
					case SCRIPT:
						result[name] = processScript(attributes[name], context);
						break;
					case NAME:
						result[name] = attributes[name];
						break;
					case TEMPLATE:
						var included = template.findTemplate(attributes[name]);
						if (!included)
							throw new Error("Unknown template: " + attributes[name]);
						result[name] = included;
						break;
					case EXTENSION:
						var extension = template._findExtension(attributes[name]);
						result[name] = extension;
						break;
					default:
						throw new Error("Unknown attribute type: " + type);
					}
				}
				else
					throw new Error("Unknown attribute: " + name + " for tag: " + tag);
			}
			return result;
		};
		var findContext = function(context, name) {
			if (name in context)
				return context;
			if (context.$)
				return findContext(context.$, name);
			return null;
		};
		var generateNodes = function(nodes, context, contextTag, constraints, params) {
			for (var n = 0; n < nodes.length; n++) {
				var node = nodes[n];
				generateNode(node, context, contextTag, constraints, params);
			}
		};
		var generateNode = function(node, context, contextTag, constraints, params) {
			var nodeType = node.nodeTypeString;
			switch (nodeType) {
			case "element":
				var name = node.nodeName;
				var qName = name;
				if (constraints) {
					if (constraints.allow.indexOf(qName) == -1)
						throw new Error("Tag: " + qName + " is not allowed in context of: " + contextTag);
					if (constraints.process.indexOf(qName) == -1)
						return;
				}
				var ns = "";
				var parts = name.split(":");
				if (parts.length == 2) {
					name = parts[1];
					ns = parts[0];
				}
				var attributes = template._prepareAttributes(node.attributes, ns);
				var rendered = attributes.ea.rendered;
				if (!rendered) {
					rendered = true;
				}
				else {
					rendered = processScript(rendered, context);
					if (typeof(result) == "string")
						result = (result.toLowerCase() == "true");
				}
				if (rendered) {
					var children = node.childNodes;
					if (ns == "ea") {
						switch (name) {
						case "template":
							var attrs = prepareAttributes(attributes.ea, qName, context, {
								name: IGNORE,
								rendered: IGNORE
							});
							generateNodes(children, context, qName);
							break;
						case "include":
							var attrs = prepareAttributes(attributes.ea, qName, context, {
								template: TEMPLATE,
								rendered: IGNORE
							});
							var included = attrs.template;
							var includeParams = {};
							generateNodes(children, context, qName, {allow:["ea:param"],process:["ea:param"]}, includeParams);
							output.write(included, includeParams);
							break;
						case "param":
							var attrs = prepareAttributes(attributes.ea, qName, context, {
								name: NAME,
								value: SCRIPT,
								rendered: IGNORE
							});
							if (params) {
								params[attrs.name] = attrs.value;
							}
							else {
								throw new Error("Param tag used in wrong context: " + contextTag || "root");
							}
							break;
						case "extension":
							var attrs = prepareAttributes(attributes.ea, qName, context, {
								name: EXTENSION,
								rendered: IGNORE
							});
							var extensionParams = {};
							generateNodes(children, context, qName, {allow:["ea:param"],process:["ea:param"]}, extensionParams);
							var passedParams = {};
							for (var name in extensionParams) {
								passedParams[name] = extensionParams[name];
							}
							attrs.name.call(null, output, template, extensionParams);
							for (var name in passedParams) {
								var value = extensionParams[name];
								context[name] = value;
							}
							break;
						case "var":
							var attrs = prepareAttributes(attributes.ea, qName, context, {
								name: NAME,
								value: SCRIPT,
								rendered: IGNORE
							});
							context[attrs.name] = attrs.value;
							break;
						case "for":
							context = {
								$: context
							};
							var attrs = prepareAttributes(attributes.ea, qName, context, {
								"var": NAME,
								"in": SCRIPT,
								index: NAME,
								key: NAME,
								rendered: IGNORE
							});
							var collection = attrs["in"];
							var variableName = attrs["var"];
							var indexName = attrs.index;
							var keyName = attrs.key;
							if (typeof(collection) == "object") {
								if (collection instanceof Array) {
									for (var index = 0; index < collection.length; index++) {
										if (variableName)
											context[variableName] = collection[index];
										if (indexName)
											context[indexName] = index;
										generateNodes(children, context, qName);
									}
								}
								else if (Core.Types.AbstractCollection.isInstance(collection)) {
									var index = 0;
									collection.forEach(function(element) {
										if (variableName)
											context[variableName] = element;
										if (indexName)
											context[indexName] = index;
										generateNodes(children, context, qName);
										index++;
									});
								}
								else {
									var index = 0;
									for (var key in collection) {
										if (variableName)
											context[variableName] = collection[key];
										if (indexName)
											context[indexName] = index;
										if (keyName)
											context[keyName] = key;
										generateNodes(children, context, qName);
										index++;
									}
								}
							}
							else {
								throw new Error(collection + " is not a collection: " + typeof(collection));
							}
							break;
						case "html":
							var attrs = prepareAttributes(attributes.ea, qName, context, {
								content: SCRIPT,
								rendered: IGNORE
							});
							generate(attrs.content, Html.IO.ProcessContentMode.HTML);
							break;
						case "raw":
							var attrs = prepareAttributes(attributes.ea, qName, context, {
								content: SCRIPT,
								rendered: IGNORE
							});
							generate(attrs.content, Html.IO.ProcessContentMode.RAW);
							break;
						case "tag":
							var attrs = prepareAttributes(attributes.ea, qName, context, {
								name: SCRIPT,
								rendered: IGNORE
							});
							generate("<" + attrs.name, Html.IO.ProcessContentMode.RAW);
							generateNodes(children, context, qName, {allow:["ea:attribute", "ea:content"],process:["ea:attribute"]});
							generate(">", Html.IO.ProcessContentMode.RAW);
							generateNodes(children, context, qName, {allow:["ea:attribute", "ea:content"],process:["ea:content"]});
							generate("</" + attrs.name + ">", Html.IO.ProcessContentMode.RAW);
							break;
						case "attribute":
							if (contextTag != "ea:tag")
								throw new Error("Tag: " + qName + " used in wrong context: " + contextTag || "root");
							var attrs = prepareAttributes(attributes.ea, qName, context, {
								name: SCRIPT,
								value: SCRIPT,
								rendered: IGNORE
							});
							generate(" " + attrs.name + "=\"", Html.IO.ProcessContentMode.RAW);
							generate(attrs.value, Html.IO.ProcessContentMode.ATTRIBUTE);
							generate("\"", Html.IO.ProcessContentMode.RAW);
							break;
						case "content":
							context = {
								$: context
							};
							var attrs = prepareAttributes(attributes.ea, qName, context, {
								rendered: IGNORE
							});
							generateNodes(children, context, qName);
							break;
						default:
							throw new Error("Unknown EA tag: " + name);
						}
					}
					else {
						generate("<" + qName, Html.IO.ProcessContentMode.RAW);
						for (var ns in attributes) {
							if (ns != "ea") {
								generateAttributes(attributes[ns], (ns == "_default" ? null : ns), context);
							}
						}
						if (children.length == 0 && ["br"].indexOf(qName) != -1) {
							generate("/>", Html.IO.ProcessContentMode.RAW);
						}
						else {
							generate(">", Html.IO.ProcessContentMode.RAW);
							generateNodes(children, context, qName);
							generate("</" + qName + ">", Html.IO.ProcessContentMode.RAW);
						}
					}
				}
				break;
			case "document":
				var children = node.childNodes;
				generateNodes(children, context);
				break;
			case "processinginstruction":
				if (node.nodeName == "ea") {
					var rest = node.text.replace(/\s*([a-z_][a-z0-9_\-]*)="([^"]*)\s*"/gi, function(whole, name, value) {
						switch (name) {
						case "process-content-as":
							var processContentAs = Html.IO.ProcessContentMode[value.toUpperCase()];
							if (processContentAs == null)
								throw new Error("Unsupported content processing mode: " + value.toUpperCase());
							output.processing.processContentAs = processContentAs;
							break;
						case "trim-content":
							output.processing.trimContent = (value.toLowerCase() == "true");
							break;
						case "filter-content":
							if (value) {
								value = new Function("return " + value + ";");
								if (!output.processing.filterContent)
									output.processing.filterContent = [];
								output.processing.filterContent.push(value);
							}
							else {
								output.processing.filterContent = null;
							}
							break;
						default:
							throw new Error("Unsupported processing instruction: " + name);
						}
					});
					if (rest && rest !== "undefined") // TODO: WTF with Chakra?
						throw new Error("Syntax error in processing instruction at: " + rest);
				}
				else {
					generate("<?" + node.nodeName + " " + node.text + "?>", Html.IO.ProcessContentMode.RAW);
				}
				break;
			case "documenttype":
				generate(node.xml, Html.IO.ProcessContentMode.RAW);
				break;
			case "comment":
				generate(processText(node.xml, context), Html.IO.ProcessContentMode.RAW);
				break;
			case "cdatasection":
				generate(processText(node.xml, context), Html.IO.ProcessContentMode.RAW);
				break;
			case "text":
				generate(processText(unescape(node.nodeValue), context), Html.IO.ProcessContentMode.CONTENT);
				break;
			default:
				throw new Error("Unsupported tag type: " + nodeType);
			}
		};
		var h = {};
		for (var name in params) {
			h[name] = this.context[name];
			this.context[name] = params[name];
		}
		generateNode(this._dom, this.context);
		for (var name in params) {
			this.context[name] = h[name];
		}
		return generated;
	}
});


text:
	<meta charset="utf-8">
	<meta name="author" content="GrapeSoft">
	<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,800' rel='stylesheet' type='text/css'>
	<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
	<script type="text/javascript" src="scripts/jquery-fallback.js"></script>


text:
<?php
namespace ck\RecipesBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="ck\RecipesBundle\Entity\RecipesCategoryRepository")
 * @ORM\Table(name="recipes_category")
 */
class RecipesCategory
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=150)
     */
    protected $name;

    /**
     * @ORM\ManyToMany(targetEntity="ck\RecipesBundle\Entity\Recipe", mappedBy="categories")
     */
    private $recipes;

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

    /**
     * Set name
     *
     * @param string $name
     * @return RecipesCategory
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

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

    public function __toString()
    {
        return $this->getName();
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->recipes = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add recipes
     *
     * @param \ck\RecipesBundle\Entity\Recipe $recipes
     * @return RecipesCategory
     */
    public function addRecipe(\ck\RecipesBundle\Entity\Recipe $recipes)
    {
        $this->recipes[] = $recipes;

        return $this;
    }

    /**
     * Remove recipes
     *
     * @param \ck\RecipesBundle\Entity\Recipe $recipes
     */
    public function removeRecipe(\ck\RecipesBundle\Entity\Recipe $recipes)
    {
        $this->recipes->removeElement($recipes);
    }

    /**
     * Get recipes
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getRecipes()
    {
        return $this->recipes;
    }
}


text:
package blobserver

import (
	"errors"
	"io"
	"os"

	"camlistore.org/pkg/blob"
	"camlistore.org/pkg/context"
	"camlistore.org/pkg/types"
)

// NoImplStorage is an implementation of Storage that returns a not
// implemented error for all operations.
type NoImplStorage struct{}

var _ Storage = (*NoImplStorage)(nil)

func (nis *NoImplStorage) Fetch(blob.Ref) (file types.ReadSeekCloser, size int64, err error) {
	return nil, 0, os.ErrNotExist
}

func (nis *NoImplStorage) FetchStreaming(blob.Ref) (file io.ReadCloser, size int64, err error) {
	return nil, 0, os.ErrNotExist
}

func (nis *NoImplStorage) ReceiveBlob(blob.Ref, io.Reader) (sb blob.SizedRef, err error) {
	err = errors.New("ReceiveBlob not implemented")
	return
}

func (nis *NoImplStorage) StatBlobs(dest chan<- blob.SizedRef, blobs []blob.Ref) error {
	return errors.New("Stat not implemented")
}

func (nis *NoImplStorage) EnumerateBlobs(ctx *context.Context, dest chan<- blob.SizedRef, after string, limit int) error {
	return errors.New("EnumerateBlobs not implemented")
}

func (nis *NoImplStorage) RemoveBlobs(blobs []blob.Ref) error {
	return errors.New("Remove not implemented")
}


text:
from gevent import monkey; monkey.patch_all()
import argparse
import os
import csv
import sys
import itertools
from datetime import datetime
from yaml import load
from logging.config import dictConfig
from logging import getLogger

from reports.utilities.invoices import InvoicesUtility
from reports.utilities.refunds import RefundsUtility
from reports.utilities.bids import BidsUtility, HEADERS
from reports.utilities.tenders import TendersUtility
from reports.helpers import parse_period_string
from reports.vault import Vault
from reports.utilities.send import Porter
from reports.utilities.zip import compress

SCRIPTS = [BidsUtility, InvoicesUtility, TendersUtility, RefundsUtility]
YES = ['y', 'yes', 'true', 't']
NO = ['n', 'no', 'false', 'f']
DEFAULT_KINDS = ['general', 'special', 'defense', 'other', '_kind']
DEFAULT_INCLUDE = "bids,invoices,tenders,refunds"
parser = argparse.ArgumentParser(description="Openprocurement Billing")
parser.add_argument('-c', '--config', required=True)
parser.add_argument('--brokers', dest='brokers', action="store")
parser.add_argument('--period', dest='period', action='store')
parser.add_argument('--notify', action='store', default='no')
parser.add_argument('--timestamp', action='store')
parser.add_argument('--include', action='store', default=DEFAULT_INCLUDE)
parser.add_argument('--notify-brokers', action="append")
parser.add_argument('--timezone', default='Europe/Kiev')
ARGS = parser.parse_args()

with open(ARGS.config) as _in:
    CONFIG = load(_in)

dictConfig(CONFIG)
WORKDIR = CONFIG['out']['out_dir']
INCLUDE = [op.strip() for op in ARGS.include.split(",")]
TIMESTAMP = ARGS.timestamp or datetime.now().strftime("%Y-%m-%d/%H-%M-%S-%f")

LOGGER = getLogger('BILLING')
PORTER = Porter(CONFIG, TIMESTAMP, ARGS.notify_brokers)
VAULT = Vault(CONFIG)

def upload_and_notify(files):
    ctx = PORTER.upload_files(files)
    if ARGS.notify and (ARGS.notify in YES):
        PORTER.postman.send_emails(ctx)
    return ctx

def send_emails_from_existing_files():
    ctx = PORTER.create_emails_context_from_existing_prefix()
    if ARGS.notify:
        PORTER.postman.send_emails(ctx)
    return [entry['broker'] for entry in ctx]

def generate_for_broker(broker, period, timezone='Europe/Kiev'):
    utilities = map(lambda u: u(broker, period, CONFIG, timezone),
                    SCRIPTS)
    for ut in utilities:
        if isinstance(ut, (TendersUtility, RefundsUtility)):
            ut.kinds = DEFAULT_KINDS
        ut.run()

def construct_filenames_of_generation(type, broker, period):
    start, end = period
    return "{}@{}--{}-{}.csv".format(broker, start, end, type)

def create_all_bids_csv(brokers, period):
    path = CONFIG.get('out').get('out_dir')
    files = [
        construct_filenames_of_generation('bids', broker, period)
        for broker in brokers
        if broker != 'all'
    ]
    all_file = "all@{0}--{1}-bids.csv".format(*period)
    with open(os.path.join(path, all_file), 'w') as out_stream:
        results_file = csv.writer(out_stream)
        results_file.writerow(HEADERS)
        for header, iterator in zip(
                (['after_2017-01-01'], ['after 2017-08-16']),
                (itertools.takewhile, itertools.dropwhile)
                ):
            results_file.writerow(header)
            for file in files:
                with open(os.path.join(path, file)) as broker_file:
                    reader = csv.reader(broker_file)
                    next(reader)
                    for line in iterator(
                            lambda line: line != ['after 2017-08-16'],
                            reader
                            ):
                        if line and line != header:
                            results_file.writerow(line)

def get_password_for_broker(broker):
    key = os.path.join(
            CONFIG['brokers_keys'].get('passwords_prefix')
            )
    try:
        password = VAULT.get(key, {}).get(broker)
        if not password:
            LOGGER.info("No password for broker {}".format(broker))
            password = ""
        LOGGER.info("Got password for broker {}".format(broker))
        return str(password)
    except Exception as e:
        LOGGER.fatal(
                "Vault extraction falied with error {}".format(e)
                )
        raise e

def zip_for_broker(
        broker,
        period,
        include=INCLUDE,
        ):
    start, end = period
    files = [
        construct_filenames_of_generation(type, broker, period)
        for type in include
    ]
    result_zip_name = "{}@{}--{}-{}.zip".format(
        broker, start, end, "-".join(include)
    )
    try:
        password = get_password_for_broker(broker)
        if password:
            return compress(
                files,
                CONFIG['out']['out_dir'],
                result_zip_name,
                password
            )
        return False
    except (OSError, IOError) as e:
        LOGGER.fatal(
                "Falied to create archive {} for broker {}. Error: {}".format(
                    result_zip_name, broker, e
                    )
                )
        return False

def zip_all_tenders(brokers, period):
    start, end = period
    try:
        return compress(
            [
                "{}@{}--{}-{}.csv".format(broker, start, end, type)
                for type in ['tenders', 'refunds']
                for broker in brokers
                if brokers != 'all'
            ],
            CONFIG['out']['out_dir'],
            "all@{}--{}-tenders.zip".format(start, end),
            None
        )
    except (OSError, IOError) as e:
        LOGGER.fatal("Error: {}".format(e))
        return False

def zip_all_bids(brokers, period):
    start, end = period
    files = ["all@{}--{}-bids.csv".format(start, end)]
    files.extend([
        "{}@{}--{}-invoices.csv".format(broker, start, end)
        for broker in brokers
        if broker != 'all'
    ])
    try:
        name = "all@{}--{}-bids.zip".format(start, end)
        password = get_password_for_broker('all')
        if password:
            return compress(
                files,
                CONFIG['out']['out_dir'],
                name,
                password
            )
        return False
    except (OSError, IOError) as e:
        LOGGER.fatal(
            "Falied to create archive {} for broker {}. Error: {}".format(
                name, broker, e
                )
            )
        return False

def clean_up(brokers, period):
    start, end = period
    files= [
        "{}@{}--{}-{}.csv".format(broker, start, end, op)
        for broker in brokers
        for op in INCLUDE
        ]
    files.append("all@{}--{}-bids.csv".format(start, end))
    for file in files:
        try:
            os.remove(os.path.join(WORKDIR, file))
            LOGGER.warning("Cleaned {}".format(file))
        except (OSError, IOError) as e:
            LOGGER.fatal("Error {} while removing file {}".format(e, file))

def run():
    period = parse_period_string(ARGS.period)
    if ARGS.timestamp:
        sent = send_emails_from_existing_files()
        if all(sent):
            LOGGER.warning(
                "Sent emails to {} from existing prefix {}".format(
                    sent, TIMESTAMP
                    )
                )
            sys.exit(0)
    if ARGS.brokers:
        brokers = [
            b.strip() for b in ARGS.brokers.split(',')
            if b.strip() != 'all'
        ]
    else:
        brokers = [
            item.strip() for item in CONFIG.get('brokers_emails').keys()
            if item.strip() != 'all'
        ]
    LOGGER.warning("Started generation for {} between {} and {}".format(
        brokers, period[0], period[1])
        )
    LOGGER.warning("Archive content: {}".format(INCLUDE))
    LOGGER.warning("Timestamp: {}".format(TIMESTAMP))
    results = []
    for broker in brokers:
        generate_for_broker(broker, period)
        zip_file_path = zip_for_broker(broker, period)
        if zip_file_path:
            results.append(upload_and_notify([zip_file_path]))
    create_all_bids_csv(brokers, period)

    if not ARGS.brokers or (ARGS.brokers and ('all' in ARGS.brokers)):
        all_tenders = zip_all_tenders(brokers, period)
        all_bids = zip_all_bids(brokers, period)
        results.extend(upload_and_notify([
            _file for _file in (all_bids, all_tenders)
            if _file
            ]))
    if all(results):
        clean_up(brokers, period)


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

#ifndef ImagePattern_h
#define ImagePattern_h

#include "platform/graphics/Pattern.h"

class SkImage;

namespace blink {

class Image;

class PLATFORM_EXPORT ImagePattern final : public Pattern {
public:
    static PassRefPtr<ImagePattern> create(PassRefPtr<Image>, RepeatMode);

    bool isTextureBacked() const override;

protected:
    PassRefPtr<SkShader> createShader() override;

private:
    ImagePattern(PassRefPtr<Image>, RepeatMode);

    RefPtr<SkImage> m_tileImage;
};

} // namespace blink

#endif  /* ImagePattern_h */


text:
__version__ = "2.0.1"

def detect(aBuf):
    from . import universaldetector
    u = universaldetector.UniversalDetector()
    u.reset()
    u.feed(aBuf)
    u.close()
    return u.result


text:
package net.linkedbuildingdata.rdf.modelfactory.virtuoso;

import java.util.Properties;

import net.linkedbuildingdata.rdf.modelfactory.JenaModelFactoryBase;

import org.apache.log4j.Logger;

import virtuoso.jena.driver.VirtModel;

import com.hp.hpl.jena.rdf.model.Model;

public class VirtuosoJenaModelFactory extends JenaModelFactoryBase {

	private static final Logger logger = Logger.getLogger(VirtuosoJenaModelFactory.class);

	private Model model;

	public VirtuosoJenaModelFactory(String factoryName, Properties properties) {
		super(factoryName, properties);
	}

	@Override
	public Model createModel() throws Exception {
		Model model = getModel();

		if (!model.isEmpty()) {

			logger.info(String.format("[Virt] Clearing model '%s'", getModelId()));

			model.removeAll();

			logger.info(String.format("[Virt] Clearing model '%s' compeleted", getModelId()));
		}

		return model;
	}

	@Override
	public Model getModel() throws Exception {
		if (model == null) {

			if (getModelId() == null) {
				throw new IllegalArgumentException(String.format("Argument %s is undefined", ARGUMENT_MODEL_ID));
			}

			logger.info(String.format("[Virt] Getting model '%s'", getModelId()));

			model = VirtModel.openDatabaseModel(getModelId(), getServerUrl(), getUserName(), getPassword());

			logger.info(String.format("[Virt] Getting model '%s' completed", getModelId()));

		}

		return model;
	}

	@Override
	public void release() throws Exception {
		if (model != null) {
			model.close();
			model = null;
		}
	}

}


text:
'use strict'

require('dotenv').config({ path: `${__dirname}/.env` })
require('./lib/server.js').start()


text:
package com.rocketfuel.sdbc.base.jdbc

import java.sql.{DriverPropertyInfo, Driver}
import java.util.Properties
import java.util.logging.Logger

class TestDriver extends Driver {
  override def acceptsURL(url: String): Boolean = ???

  override def jdbcCompliant(): Boolean = ???

  override def getPropertyInfo(url: String, info: Properties): Array[DriverPropertyInfo] = ???

  override def getMinorVersion: Int = ???

  override def getParentLogger: Logger = ???

  override def connect(url: String, info: Properties): java.sql.Connection = ???

  override def getMajorVersion: Int = ???
}