text:
use super::{
    super::{
        common::{get_metric, GetMetricResult},
        types::{MetricsEvaluatorError, MetricsEvaluatorInput},
    },
    CATEGORY,
};
use crate::{
    configuration::EvaluatorArgs,
    evaluator::{EvaluationResult, Evaluator},
    evaluators::EvaluatorType,
};
use anyhow::Result;
use clap::Parser;
use log::debug;
use poem_openapi::Object as PoemObject;
use prometheus_parse::Scrape as PrometheusScrape;
use serde::{Deserialize, Serialize};

// TODO: When we have it, switch to using a crate that unifies metric names.
// As it is now, this metric name could change and we'd never catch it here
// at compile time.
const METRIC: &str = "aptos_consensus_timeout_count";

#[derive(Clone, Debug, Deserialize, Parser, PoemObject, Serialize)]
pub struct ConsensusTimeoutsEvaluatorArgs {
    /// The amount by which timeouts are allowed to increase between each
    /// round of metrics collection.
    #[clap(long, default_value_t = 0)]
    pub allowed_consensus_timeouts: u64,
}

#[allow(dead_code)]
#[derive(Debug)]
pub struct ConsensusTimeoutsEvaluator {
    args: ConsensusTimeoutsEvaluatorArgs,
}

impl ConsensusTimeoutsEvaluator {
    pub fn new(args: ConsensusTimeoutsEvaluatorArgs) -> Self {
        Self { args }
    }

    fn get_consensus_timeouts(
        &self,
        metrics: &PrometheusScrape,
        metrics_round: &str,
    ) -> GetMetricResult {
        let evaluation_on_missing_fn = || {
            self.build_evaluation_result(
                "Consensus timeouts metric missing".to_string(),
                0,
                format!(
                    "The {} set of metrics from the target node is missing the metric: {}",
                    metrics_round, METRIC
                ),
            )
        };
        get_metric(metrics, METRIC, None, evaluation_on_missing_fn)
    }

    #[allow(clippy::comparison_chain)]
    fn build_evaluation(
        &self,
        previous_timeouts_count: u64,
        latest_timeouts_count: u64,
    ) -> EvaluationResult {
        if latest_timeouts_count > previous_timeouts_count + self.args.allowed_consensus_timeouts {
            self.build_evaluation_result(
                "Consensus timeouts metric increased".to_string(),
                50,
                format!(
                    "The consensus timeouts count increased from {} to {} between metrics rounds more than the allowed amount ({})",
                    previous_timeouts_count, latest_timeouts_count, self.args.allowed_consensus_timeouts
                ),
            )
        } else {
            self.build_evaluation_result(
                "Consensus timeouts metric okay".to_string(),
                100,
                format!(
                    "The consensus timeouts count was {} in the first round and {} in the second round of metrics collection, which is within tolerance of the allowed increase ({})",
                    previous_timeouts_count, latest_timeouts_count, self.args.allowed_consensus_timeouts
                ),
            )
        }
    }
}

#[async_trait::async_trait]
impl Evaluator for ConsensusTimeoutsEvaluator {
    type Input = MetricsEvaluatorInput;
    type Error = MetricsEvaluatorError;

    /// Assert that the consensus timeouts are not increasing too much.
    async fn evaluate(&self, input: &Self::Input) -> Result<Vec<EvaluationResult>, Self::Error> {
        let mut evaluation_results = vec![];

        let previous_timeouts_count = self
            .get_consensus_timeouts(&input.previous_target_metrics, "first")
            .unwrap(&mut evaluation_results);

        let latest_timeouts_count = self
            .get_consensus_timeouts(&input.latest_target_metrics, "second")
            .unwrap(&mut evaluation_results);

        match (previous_timeouts_count, latest_timeouts_count) {
            (Some(previous), Some(latest)) => {
                evaluation_results.push(self.build_evaluation(previous, latest));
            }
            _ => {
                debug!(
                    "Not evaluating timeouts count because we're missing metrics from the target"
                );
            }
        };

        Ok(evaluation_results)
    }

    fn get_category_name() -> String {
        CATEGORY.to_string()
    }

    fn get_evaluator_name() -> String {
        "timeouts".to_string()
    }

    fn from_evaluator_args(evaluator_args: &EvaluatorArgs) -> Result<Self> {
        Ok(Self::new(evaluator_args.consensus_timeouts_args.clone()))
    }

    fn evaluator_type_from_evaluator_args(evaluator_args: &EvaluatorArgs) -> Result<EvaluatorType> {
        Ok(EvaluatorType::Metrics(Box::new(Self::from_evaluator_args(
            evaluator_args,
        )?)))
    }
}


text:
import sys

def fizz_buzz(ceiling):
    """Display numbers, replacing evenly-divisible numbers with fuzz/buzz.

    Starting with 1, show numbers up to and including the ceiling value. If the
    number is evenly divisible by 3, display "Fizz"; "Buzz" when evenly
    divisible by 5. When by both, display "FizzBuzz".

    Accepts:
        ceiling: int, Finally number to consider for display
    """
    # From 1 to the ceiling (+1 to include the ceiling number)
    for number in range(1, ceiling + 1):
        if number % 5 == 0 and number % 3 == 0:
            # If evenly divisible by both
            # the elif and else will not get considered when this is true
            sys.stdout.write("FizzBuzz ")
        elif number % 5 == 0:
            sys.stdout.write("Buzz ")
        elif number % 3 == 0:
            sys.stdout.write("Fizz ")
        else:
            sys.stdout.write('{} '.format(number))
    sys.stdout.flush()

def fizz_buzz2(ceiling):
    print ' '.join(
        'Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or str(i)
        for i in  range(1, ceiling + 1)
    )

fizz_buzz(15)
print('')
fizz_buzz2(15)

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: TDD - how is it done? Vol 2
date: 2007-04-17T11:57:00.000Z
author: Marcus Hammarberg
tags:
  - .NET
  - Agile- TDD
modified_time: 2007-04-17T12:05:01.769Z
blogger_id: tag:blogger.com,1999:blog-36533086.post-5105649867606006552
blogger_orig_url: http://www.marcusoft.net/2007/04/tdd-how-is-it-done-vol-2.html
---

When
digging around for TDD stuff i have started [a small
series](http://marcushammarberg.blogspot.com/2007/04/tdd-how-is-it-done.html)
(?) about how to actually implementing the good ideas and promises from
TDD.

Found another good article on the practicalities for Test Driven
Development. This one is about [Mock
Objects](http://msdn.microsoft.com/msdnmag/issues/04/10/NMock/).

The minute after you start to think about doing TDD through all your
code you find yourself pondering about how to test only the current
layer. For example the business layer has references to the Data Access
layer (as it often do) but i only want to test the business layer. This
is solve by Mock objects, which [the
article](http://msdn.microsoft.com/msdnmag/issues/04/10/NMock/) is
about.

Also some issues about configuration arises. Like; how can i assure that
the mocked objects are used in a test run but now in a debug run...
There are some references about that also in the article.


text:
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var fs = require("fs");
var path = require("path");
var configuration_1 = require("./configuration");
var error_1 = require("./error");
var utils_1 = require("./utils");
var moduleDirectory = path.dirname(module.filename);
var CORE_RULES_DIRECTORY = path.resolve(moduleDirectory, ".", "rules");
var cachedRules = new Map();
function loadRules(ruleOptionsList, rulesDirectories, isJs) {
    if (isJs === void 0) { isJs = false; }
    var rules = [];
    var notFoundRules = [];
    var notAllowedInJsRules = [];
    for (var _i = 0, ruleOptionsList_1 = ruleOptionsList; _i < ruleOptionsList_1.length; _i++) {
        var ruleOptions = ruleOptionsList_1[_i];
        if (ruleOptions.ruleSeverity === "off") {
            // Perf: don't bother finding the rule if it's disabled.
            continue;
        }
        var ruleName = ruleOptions.ruleName;
        var Rule = findRule(ruleName, rulesDirectories);
        if (Rule === undefined) {
            notFoundRules.push(ruleName);
        }
        else if (isJs && Rule.metadata !== undefined && Rule.metadata.typescriptOnly) {
            notAllowedInJsRules.push(ruleName);
        }
        else {
            var rule = new Rule(ruleOptions);
            if (rule.isEnabled()) {
                rules.push(rule);
            }
            if (Rule.metadata !== undefined && Rule.metadata.deprecationMessage !== undefined) {
                error_1.showWarningOnce(Rule.metadata.ruleName + " is deprecated. " + Rule.metadata.deprecationMessage);
            }
        }
    }
    if (notFoundRules.length > 0) {
        var warning = (_a = ["\n            Could not find implementations for the following rules specified in the configuration:\n                ", "\n            Try upgrading TSLint and/or ensuring that you have all necessary custom rules installed.\n            If TSLint was recently upgraded, you may have old rules configured which need to be cleaned up.\n        "], _a.raw = ["\n            Could not find implementations for the following rules specified in the configuration:\n                ", "\n            Try upgrading TSLint and/or ensuring that you have all necessary custom rules installed.\n            If TSLint was recently upgraded, you may have old rules configured which need to be cleaned up.\n        "], utils_1.dedent(_a, notFoundRules.join("\n                ")));
        error_1.showWarningOnce(warning);
    }
    if (notAllowedInJsRules.length > 0) {
        var warning = (_b = ["\n            Following rules specified in configuration couldn't be applied to .js or .jsx files:\n                ", "\n            Make sure to exclude them from \"jsRules\" section of your tslint.json.\n        "], _b.raw = ["\n            Following rules specified in configuration couldn't be applied to .js or .jsx files:\n                ", "\n            Make sure to exclude them from \"jsRules\" section of your tslint.json.\n        "], utils_1.dedent(_b, notAllowedInJsRules.join("\n                ")));
        error_1.showWarningOnce(warning);
    }
    if (rules.length === 0) {
        error_1.showWarningOnce("No valid rules have been specified");
    }
    return rules;
    var _a, _b;
}
exports.loadRules = loadRules;
function findRule(name, rulesDirectories) {
    var camelizedName = transformName(name);
    // first check for core rules
    var Rule = loadCachedRule(CORE_RULES_DIRECTORY, camelizedName);
    return Rule !== undefined ? Rule :
        // then check for rules within the first level of rulesDirectory
        utils_1.find(utils_1.arrayify(rulesDirectories), function (dir) { return loadCachedRule(dir, camelizedName, true); });
}
exports.findRule = findRule;
function transformName(name) {
    // camelize strips out leading and trailing underscores and dashes, so make sure they aren't passed to camelize
    // the regex matches the groups (leading underscores and dashes)(other characters)(trailing underscores and dashes)
    var nameMatch = name.match(/^([-_]*)(.*?)([-_]*)$/);
    if (nameMatch === null) {
        return name + "Rule";
    }
    return "" + nameMatch[1] + utils_1.camelize(nameMatch[2]) + nameMatch[3] + "Rule";
}
/**
 * @param directory - An absolute path to a directory of rules
 * @param ruleName - A name of a rule in filename format. ex) "someLintRule"
 */
function loadRule(directory, ruleName) {
    var fullPath = path.join(directory, ruleName);
    if (fs.existsSync(fullPath + ".js")) {
        var ruleModule = require(fullPath);
        if (ruleModule !== undefined) {
            return ruleModule.Rule;
        }
    }
    return "not-found";
}
function loadCachedRule(directory, ruleName, isCustomPath) {
    // use cached value if available
    var fullPath = path.join(directory, ruleName);
    var cachedRule = cachedRules.get(fullPath);
    if (cachedRule !== undefined) {
        return cachedRule === "not-found" ? undefined : cachedRule;
    }
    // get absolute path
    var absolutePath = directory;
    if (isCustomPath) {
        absolutePath = configuration_1.getRelativePath(directory);
        if (absolutePath !== undefined && !fs.existsSync(absolutePath)) {
            throw new error_1.FatalError("Could not find custom rule directory: " + directory);
        }
    }
    var Rule = absolutePath === undefined ? "not-found" : loadRule(absolutePath, ruleName);
    cachedRules.set(fullPath, Rule);
    return Rule === "not-found" ? undefined : Rule;
}


text:
<?php

namespace Geezify\Exception;

use InvalidArgumentException;

/**
 * Class NotAnIntegerArgumentException.
 *
 * @author Sam As End <4sam21{at}gmail.com>
 */
class NotAnIntegerArgumentException extends InvalidArgumentException
{
    public function __construct($argument)
    {
        parent::__construct(
            sprintf(
                'Not an integer!, %s given.',
                gettype($argument)
            )
        );
    }
}


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

namespace Sakuno.ING.Http
{
    public sealed class HttpMessage
    {
    }
}


text:
define(['build/Objects/Abstract/menu_item', 'build/Factories/resource_property_factory'], function (MenuItem, ResourceItemPropertyFactory) {

    var Resource = function (data) {

        //Call the parent constructor
        MenuItem.call(this, arguments);

        /**
         * Resource items
         * @type {Array}
         */
        this.items = [];

        /**
         * Our custom type
         * @type {string}
         */
        this.type = 'resource';

        /**
         * Target where to fetch the data from
         */
        this.target = data.target;

        /**
         * Paging options
         * @type {{}}
         */
        this.paging = {};

        /**
         * Special properties of a resource
         * @type {*|{}}
         */
        this.properties = data.properties ? ResourceItemPropertyFactory.createProperties(data.properties) : [];

        /**
         * Getter for the id
         * @returns string
         * @override
         */
        this.getId = function () {
            return this.target;
        };

        /**
         * Getter for the target
         * @returns String
         */
        this.getTarget = function () {
            return this.target;
        };

        /**
         * Get items in this resource
         * @returns {Array}
         */
        this.getItems = function () {
            return this.items;
        };

        /**
         * Get the current paging
         * @returns Object
         */
        this.getPaging = function () {
            return this.paging;
        };

        /**
         * Get the properties active on this resource
         * @returns {*|{}}
         */
        this.getProperties = function() {
            return this.properties;
        };

        /**
         * Check if certain named property is present
         * @param name
         * @return boolean
         */
        this.hasProperty = function(name) {
            return this.getProperty(name) !== false;
        };

        /**
         * Get the property
         * @param name
         * @return Property
         */
        this.getProperty = function(name) {
            for(var i in this.properties) {
                if(this.properties[i].getName() == name) {
                    return this.properties[i];
                }
            }
            return false;
        };

        /**
         * Update with new data
         * @param data
         */
        this.extend = function (data) {

            //Initialize like this otherwise we have circular dependencies
            var MenuItemFactory = require('build/Factories/menu_item_factory');

            //Create actual items
            data.items = data.items.map(function (item) {
                return MenuItemFactory.createItem(item);
            }.bind(this));

            this.items = this.items.concat(data.items);
            this.paging = data.paging;
        };

        /**
         * Set the active item in our childs
         * @param item
         */
        this.setActiveItem = function (item) {
            for (var i in this.items) {
                this.items[i].setIsActive(this.items[i].getId() == item.getId());
            }
        };

        /**
         * Update with new data
         * @param data
         */
        this.update = function (data) {
            if (data.items && (data.items.length > 0 || this.items.length == 0)) {

                //Initialize like this otherwise we have circular dependencies
                var MenuItemFactory = require('build/Factories/menu_item_factory');

                //When items are passed as data directly write them as the content
                //Since we receive a Resource object here it will always have items, so we check if it already
                //contains items, or if originally there were no items (this.items.length == 0)
                this.items = data.items.map(function (item) {
                    return MenuItemFactory.createItem(item);
                }.bind(this));
            } else if (!this.paging || !this.paging.total) {
                this.items = [];

                //Just load the original resource again
                setTimeout(function () {
                    flux.actions.updateResource(this, this.getTarget());
                }.bind(this), 1);
            } else if(this.paging.total) {
                //When we have a clue what to call to update this resource do that
                //setTimeout is to handle the "async" behavior of dispatching
                setTimeout(function () {
                    flux.actions.updateResource(this, this.paging.total);
                }.bind(this), 1);
            }
        };
    };

    // Inherit Panel
    Resource.prototype = MenuItem;

    // Fix constructor
    Resource.prototype.constructor = Resource;

    return Resource;
});


text:
/**
 * Created by pmeijer on 4/9/2014.
 */

'use strict';
if (typeof window === 'undefined') {

    // server-side setup
    var requirejs = require("../../../../../test-conf.js").requirejs;

    var chai = require('chai'),
        should = chai.should(),
        assert = chai.assert,
        expect = chai.expect;
}

describe('CoreExamplesGen', function () {
    var plugin,
        core,
        meta,
        mParent,
        orgNode,
        refNode,
        port1,
        port2,
        port3,
        conn11,
        conn21,
        conn33,
        parentExample,
        connectionExample,
        referenceExample,
        m1,
        modelsNode,
        Logger;

    before(function (done) { requirejs(
        ['plugin/CoreExamples/CoreExamples/CoreExamples', 'mocks/LoggerMock', 'models/TestCore/modelExample'],
        function (CoreExamples, Logger_, mockModel_) {
            var mockModel = mockModel_;
            Logger = Logger_;
            plugin = new CoreExamples();
            core = mockModel.core;
            meta = mockModel.META;
            // Parent Example
            modelsNode = mockModel.activeNode;
            parentExample = mockModel.parentExample;
            mParent = mockModel.mParent;
            // Reference Example
            referenceExample = mockModel.referenceExample;
            orgNode = mockModel.orgNode;
            refNode = mockModel.refNode;
            // Connection Example
            connectionExample = mockModel.connectionExample;
            m1 = mockModel.m1;
            port1 = mockModel.port1;
            port2 = mockModel.port2;
            port3 = mockModel.port3;
            conn11 = mockModel.conn1;
            conn21 = mockModel.conn2;
            conn33 = mockModel.conn3;
            done();
        });
    });

    it('compareParentAndChildsParent', function (done) {
        plugin.core = core;
        plugin.logger = new Logger();

        plugin.compareParentAndChildsParent(mParent, function (err) {
            expect(err).to.equal('');
            expect(plugin.logger.info_messages[0]).
                to.equal("Parent och its child's parent had the same GUID (as expected).");
            done();
        });
    });

    it('parentExample', function (done) {
        var children = [mParent];
        plugin.core = core;
        plugin.logger = new Logger();
        plugin.META = meta;
        plugin.parentExample(children, function (err) {
            expect(err).to.equal('');
            expect(plugin.logger.info_messages[0]).
                to.equal("Parent och its child's parent had the same GUID (as expected).");
            done();
        });
    });

    it('referenceExample', function (done) {
        var children = [orgNode, refNode];
        plugin.core = core;
        plugin.logger = new Logger();
        plugin.META = meta;
        plugin.referenceExample(children, function (err) {
            expect(err).to.equal('');
            expect(plugin.logger.info_messages[0]).
                to.equal("Reference and original node had the same GUID (as expected).");
            done();
        });
    });

    it('visitPorts1', function (done) {
        plugin.core = core;
        plugin.logger = new Logger();

        plugin.visitPorts(port1, function (err) {
            expect(err).to.equal('');
            expect(plugin.logger.info_messages[0]).
                to.equal('ConnectionElement connects "Port1" and "p1".');
            done();
        });
    });

    it('visitPorts3', function (done) {
        plugin.core = core;
        plugin.logger = new Logger();

        plugin.visitPorts(port3, function (err) {
            expect(err).to.equal('');
            expect(plugin.logger.info_messages[0]).
                to.equal('ConnectionElement connects "Port3" and "Port3".');
            done();
        });
    });

    it('connectionExample', function (done) {
        var children = [port1, port2, port3, conn11, conn21, conn33, m1];
        plugin.core = core;
        plugin.logger = new Logger();
        plugin.META = meta;

        plugin.connectionExample(children, function (err) {
            expect(err).to.equal('');
            expect(plugin.logger.info_messages.length).to.equal(3);
            done();
        });
    });

    it('recursiveChildrenExample1', function (done) {
        var children = [parentExample];
        plugin.core = core;
        plugin.logger = new Logger();
        plugin.META = meta;
        plugin.recursiveChildrenExample(children, function (err) {
            expect(err).to.equal('');
            expect(plugin.logger.info_messages.length).to.equal(3);
            done();
        });
    });

    it('recursiveChildrenExample2', function (done) {
        var children = [connectionExample];
        plugin.core = core;
        plugin.logger = new Logger();
        plugin.META = meta;
        plugin.recursiveChildrenExample(children, function (err) {
            expect(err).to.equal('');
            expect(plugin.logger.info_messages.length).to.equal(9);
            done();
        });
    });

    it('runExamples1', function (done) {
        plugin.core = core;
        plugin.logger = new Logger();
        plugin.META = meta;
        plugin.runExamples(connectionExample, function (err) {
            expect(err).to.equal('');
            expect(plugin.logger.info_messages.length).to.equal(5);
            done();
        });
    });

    it('runExamplesEmpty', function (done) {
        plugin.core = core;
        plugin.logger = new Logger();
        plugin.META = meta;
        plugin.runExamples(modelsNode, function (err) {
            expect(err).to.equal(null);
            expect(plugin.logger.debug_messages[0]).to.equal('Found unexpected child, Models, inside Models.');
            done();
        });
    });
});


text:
#include "catch_reporter_console.h"

#include "../internal/catch_reporter_registrars.hpp"
#include "../internal/catch_console_colour.h"
#include "../internal/catch_version.h"
#include "../internal/catch_text.h"
#include "../internal/catch_stringref.h"

#include <cfloat>
#include <cstdio>

#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
 // Note that 4062 (not all labels are handled and default is missing) is enabled
#endif

#if defined(__clang__)
#  pragma clang diagnostic push
// For simplicity, benchmarking-only helpers are always enabled
#  pragma clang diagnostic ignored "-Wunused-function"
#endif

namespace Catch {

namespace {

// Formatter impl for ConsoleReporter
class ConsoleAssertionPrinter {
public:
    ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
    ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
    ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
        : stream(_stream),
        stats(_stats),
        result(_stats.assertionResult),
        colour(Colour::None),
        message(result.getMessage()),
        messages(_stats.infoMessages),
        printInfoMessages(_printInfoMessages) {
        switch (result.getResultType()) {
        case ResultWas::Ok:
            colour = Colour::Success;
            passOrFail = "PASSED";
            //if( result.hasMessage() )
            if (_stats.infoMessages.size() == 1)
                messageLabel = "with message";
            if (_stats.infoMessages.size() > 1)
                messageLabel = "with messages";
            break;
        case ResultWas::ExpressionFailed:
            if (result.isOk()) {
                colour = Colour::Success;
                passOrFail = "FAILED - but was ok";
            } else {
                colour = Colour::Error;
                passOrFail = "FAILED";
            }
            if (_stats.infoMessages.size() == 1)
                messageLabel = "with message";
            if (_stats.infoMessages.size() > 1)
                messageLabel = "with messages";
            break;
        case ResultWas::ThrewException:
            colour = Colour::Error;
            passOrFail = "FAILED";
            messageLabel = "due to unexpected exception with ";
            if (_stats.infoMessages.size() == 1)
                messageLabel += "message";
            if (_stats.infoMessages.size() > 1)
                messageLabel += "messages";
            break;
        case ResultWas::FatalErrorCondition:
            colour = Colour::Error;
            passOrFail = "FAILED";
            messageLabel = "due to a fatal error condition";
            break;
        case ResultWas::DidntThrowException:
            colour = Colour::Error;
            passOrFail = "FAILED";
            messageLabel = "because no exception was thrown where one was expected";
            break;
        case ResultWas::Info:
            messageLabel = "info";
            break;
        case ResultWas::Warning:
            messageLabel = "warning";
            break;
        case ResultWas::ExplicitFailure:
            passOrFail = "FAILED";
            colour = Colour::Error;
            if (_stats.infoMessages.size() == 1)
                messageLabel = "explicitly with message";
            if (_stats.infoMessages.size() > 1)
                messageLabel = "explicitly with messages";
            break;
            // These cases are here to prevent compiler warnings
        case ResultWas::Unknown:
        case ResultWas::FailureBit:
        case ResultWas::Exception:
            passOrFail = "** internal error **";
            colour = Colour::Error;
            break;
        }
    }

    void print() const {
        printSourceInfo();
        if (stats.totals.assertions.total() > 0) {
            printResultType();
            printOriginalExpression();
            printReconstructedExpression();
        } else {
            stream << '\n';
        }
        printMessage();
    }

private:
    void printResultType() const {
        if (!passOrFail.empty()) {
            Colour colourGuard(colour);
            stream << passOrFail << ":\n";
        }
    }
    void printOriginalExpression() const {
        if (result.hasExpression()) {
            Colour colourGuard(Colour::OriginalExpression);
            stream << "  ";
            stream << result.getExpressionInMacro();
            stream << '\n';
        }
    }
    void printReconstructedExpression() const {
        if (result.hasExpandedExpression()) {
            stream << "with expansion:\n";
            Colour colourGuard(Colour::ReconstructedExpression);
            stream << Column(result.getExpandedExpression()).indent(2) << '\n';
        }
    }
    void printMessage() const {
        if (!messageLabel.empty())
            stream << messageLabel << ':' << '\n';
        for (auto const& msg : messages) {
            // If this assertion is a warning ignore any INFO messages
            if (printInfoMessages || msg.type != ResultWas::Info)
                stream << Column(msg.message).indent(2) << '\n';
        }
    }
    void printSourceInfo() const {
        Colour colourGuard(Colour::FileName);
        stream << result.getSourceInfo() << ": ";
    }

    std::ostream& stream;
    AssertionStats const& stats;
    AssertionResult const& result;
    Colour::Code colour;
    std::string passOrFail;
    std::string messageLabel;
    std::string message;
    std::vector<MessageInfo> messages;
    bool printInfoMessages;
};

std::size_t makeRatio(std::size_t number, std::size_t total) {
    std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
    return (ratio == 0 && number > 0) ? 1 : ratio;
}

std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
    if (i > j && i > k)
        return i;
    else if (j > k)
        return j;
    else
        return k;
}

struct ColumnInfo {
    enum Justification { Left, Right };
    std::string name;
    int width;
    Justification justification;
};
struct ColumnBreak {};
struct RowBreak {};

class Duration {
    enum class Unit {
        Auto,
        Nanoseconds,
        Microseconds,
        Milliseconds,
        Seconds,
        Minutes
    };
    static const uint64_t s_nanosecondsInAMicrosecond = 1000;
    static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
    static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
    static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;

    double m_inNanoseconds;
    Unit m_units;

public:
    explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
        : m_inNanoseconds(inNanoseconds),
        m_units(units) {
        if (m_units == Unit::Auto) {
            if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
                m_units = Unit::Nanoseconds;
            else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
                m_units = Unit::Microseconds;
            else if (m_inNanoseconds < s_nanosecondsInASecond)
                m_units = Unit::Milliseconds;
            else if (m_inNanoseconds < s_nanosecondsInAMinute)
                m_units = Unit::Seconds;
            else
                m_units = Unit::Minutes;
        }

    }

    auto value() const -> double {
        switch (m_units) {
        case Unit::Microseconds:
            return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
        case Unit::Milliseconds:
            return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
        case Unit::Seconds:
            return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
        case Unit::Minutes:
            return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
        default:
            return m_inNanoseconds;
        }
    }
    auto unitsAsString() const -> std::string {
        switch (m_units) {
        case Unit::Nanoseconds:
            return "ns";
        case Unit::Microseconds:
            return "us";
        case Unit::Milliseconds:
            return "ms";
        case Unit::Seconds:
            return "s";
        case Unit::Minutes:
            return "m";
        default:
            return "** internal error **";
        }

    }
    friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
        return os << duration.value() << ' ' << duration.unitsAsString();
    }
};
} // end anon namespace

class TablePrinter {
    std::ostream& m_os;
    std::vector<ColumnInfo> m_columnInfos;
    std::ostringstream m_oss;
    int m_currentColumn = -1;
    bool m_isOpen = false;

public:
    TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
    :   m_os( os ),
        m_columnInfos( std::move( columnInfos ) ) {}

    auto columnInfos() const -> std::vector<ColumnInfo> const& {
        return m_columnInfos;
    }

    void open() {
        if (!m_isOpen) {
            m_isOpen = true;
            *this << RowBreak();

			Columns headerCols;
			Spacer spacer(2);
			for (auto const& info : m_columnInfos) {
				headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
				headerCols += spacer;
			}
			m_os << headerCols << '\n';

            m_os << Catch::getLineOfChars<'-'>() << '\n';
        }
    }
    void close() {
        if (m_isOpen) {
            *this << RowBreak();
            m_os << std::endl;
            m_isOpen = false;
        }
    }

    template<typename T>
    friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
        tp.m_oss << value;
        return tp;
    }

    friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
        auto colStr = tp.m_oss.str();
        const auto strSize = colStr.size();
        tp.m_oss.str("");
        tp.open();
        if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
            tp.m_currentColumn = -1;
            tp.m_os << '\n';
        }
        tp.m_currentColumn++;

        auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
        auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
            ? std::string(colInfo.width - (strSize + 1), ' ')
            : std::string();
        if (colInfo.justification == ColumnInfo::Left)
            tp.m_os << colStr << padding << ' ';
        else
            tp.m_os << padding << colStr << ' ';
        return tp;
    }

    friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
        if (tp.m_currentColumn > 0) {
            tp.m_os << '\n';
            tp.m_currentColumn = -1;
        }
        return tp;
    }
};

ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
    : StreamingReporterBase(config),
    m_tablePrinter(new TablePrinter(config.stream(),
        [&config]() -> std::vector<ColumnInfo> {
        if (config.fullConfig()->benchmarkNoAnalysis())
        {
            return{
                { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
                { "     samples", 14, ColumnInfo::Right },
                { "  iterations", 14, ColumnInfo::Right },
                { "        mean", 14, ColumnInfo::Right }
            };
        }
        else
        {
            return{
                { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
                { "samples      mean       std dev", 14, ColumnInfo::Right },
                { "iterations   low mean   low std dev", 14, ColumnInfo::Right },
                { "estimated    high mean  high std dev", 14, ColumnInfo::Right }
            };
        }
    }())) {}
ConsoleReporter::~ConsoleReporter() = default;

std::string ConsoleReporter::getDescription() {
    return "Reports test results as plain lines of text";
}

void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
    stream << "No test cases matched '" << spec << '\'' << std::endl;
}

void ConsoleReporter::reportInvalidArguments(std::string const&arg){
    stream << "Invalid Filter: " << arg << std::endl;
}

void ConsoleReporter::assertionStarting(AssertionInfo const&) {}

bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
    AssertionResult const& result = _assertionStats.assertionResult;

    bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();

    // Drop out if result was successful but we're not printing them.
    if (!includeResults && result.getResultType() != ResultWas::Warning)
        return false;

    lazyPrint();

    ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
    printer.print();
    stream << std::endl;
    return true;
}

void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
    m_tablePrinter->close();
    m_headerPrinted = false;
    StreamingReporterBase::sectionStarting(_sectionInfo);
}
void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
    m_tablePrinter->close();
    if (_sectionStats.missingAssertions) {
        lazyPrint();
        Colour colour(Colour::ResultError);
        if (m_sectionStack.size() > 1)
            stream << "\nNo assertions in section";
        else
            stream << "\nNo assertions in test case";
        stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
    }
    double dur = _sectionStats.durationInSeconds;
    if (shouldShowDuration(*m_config, dur)) {
        stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << std::endl;
    }
    if (m_headerPrinted) {
        m_headerPrinted = false;
    }
    StreamingReporterBase::sectionEnded(_sectionStats);
}

#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
void ConsoleReporter::benchmarkPreparing(std::string const& name) {
	lazyPrintWithoutClosingBenchmarkTable();

	auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));

	bool firstLine = true;
	for (auto line : nameCol) {
		if (!firstLine)
			(*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
		else
			firstLine = false;

		(*m_tablePrinter) << line << ColumnBreak();
	}
}

void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
    (*m_tablePrinter) << info.samples << ColumnBreak()
        << info.iterations << ColumnBreak();
    if (!m_config->benchmarkNoAnalysis())
        (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
}
void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
    if (m_config->benchmarkNoAnalysis())
    {
        (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
    }
    else
    {
        (*m_tablePrinter) << ColumnBreak()
            << Duration(stats.mean.point.count()) << ColumnBreak()
            << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
            << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
            << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
            << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
            << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
    }
}

void ConsoleReporter::benchmarkFailed(std::string const& error) {
	Colour colour(Colour::Red);
    (*m_tablePrinter)
        << "Benchmark failed (" << error << ')'
        << ColumnBreak() << RowBreak();
}
#endif // CATCH_CONFIG_ENABLE_BENCHMARKING

void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
    m_tablePrinter->close();
    StreamingReporterBase::testCaseEnded(_testCaseStats);
    m_headerPrinted = false;
}
void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
    if (currentGroupInfo.used) {
        printSummaryDivider();
        stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
        printTotals(_testGroupStats.totals);
        stream << '\n' << std::endl;
    }
    StreamingReporterBase::testGroupEnded(_testGroupStats);
}
void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
    printTotalsDivider(_testRunStats.totals);
    printTotals(_testRunStats.totals);
    stream << std::endl;
    StreamingReporterBase::testRunEnded(_testRunStats);
}
void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
    StreamingReporterBase::testRunStarting(_testInfo);
    printTestFilters();
}

void ConsoleReporter::lazyPrint() {

    m_tablePrinter->close();
    lazyPrintWithoutClosingBenchmarkTable();
}

void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {

    if (!currentTestRunInfo.used)
        lazyPrintRunInfo();
    if (!currentGroupInfo.used)
        lazyPrintGroupInfo();

    if (!m_headerPrinted) {
        printTestCaseAndSectionHeader();
        m_headerPrinted = true;
    }
}
void ConsoleReporter::lazyPrintRunInfo() {
    stream << '\n' << getLineOfChars<'~'>() << '\n';
    Colour colour(Colour::SecondaryText);
    stream << currentTestRunInfo->name
        << " is a Catch v" << libraryVersion() << " host application.\n"
        << "Run with -? for options\n\n";

    if (m_config->rngSeed() != 0)
        stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";

    currentTestRunInfo.used = true;
}
void ConsoleReporter::lazyPrintGroupInfo() {
    if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
        printClosedHeader("Group: " + currentGroupInfo->name);
        currentGroupInfo.used = true;
    }
}
void ConsoleReporter::printTestCaseAndSectionHeader() {
    assert(!m_sectionStack.empty());
    printOpenHeader(currentTestCaseInfo->name);

    if (m_sectionStack.size() > 1) {
        Colour colourGuard(Colour::Headers);

        auto
            it = m_sectionStack.begin() + 1, // Skip first section (test case)
            itEnd = m_sectionStack.end();
        for (; it != itEnd; ++it)
            printHeaderString(it->name, 2);
    }

    SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;

    stream << getLineOfChars<'-'>() << '\n';
    Colour colourGuard(Colour::FileName);
    stream << lineInfo << '\n';
    stream << getLineOfChars<'.'>() << '\n' << std::endl;
}

void ConsoleReporter::printClosedHeader(std::string const& _name) {
    printOpenHeader(_name);
    stream << getLineOfChars<'.'>() << '\n';
}
void ConsoleReporter::printOpenHeader(std::string const& _name) {
    stream << getLineOfChars<'-'>() << '\n';
    {
        Colour colourGuard(Colour::Headers);
        printHeaderString(_name);
    }
}

// if string has a : in first line will set indent to follow it on
// subsequent lines
void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
    std::size_t i = _string.find(": ");
    if (i != std::string::npos)
        i += 2;
    else
        i = 0;
    stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
}

struct SummaryColumn {

    SummaryColumn( std::string _label, Colour::Code _colour )
    :   label( std::move( _label ) ),
        colour( _colour ) {}
    SummaryColumn addRow( std::size_t count ) {
        ReusableStringStream rss;
        rss << count;
        std::string row = rss.str();
        for (auto& oldRow : rows) {
            while (oldRow.size() < row.size())
                oldRow = ' ' + oldRow;
            while (oldRow.size() > row.size())
                row = ' ' + row;
        }
        rows.push_back(row);
        return *this;
    }

    std::string label;
    Colour::Code colour;
    std::vector<std::string> rows;

};

void ConsoleReporter::printTotals( Totals const& totals ) {
    if (totals.testCases.total() == 0) {
        stream << Colour(Colour::Warning) << "No tests ran\n";
    } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
        stream << Colour(Colour::ResultSuccess) << "All tests passed";
        stream << " ("
            << pluralise(totals.assertions.passed, "assertion") << " in "
            << pluralise(totals.testCases.passed, "test case") << ')'
            << '\n';
    } else {

        std::vector<SummaryColumn> columns;
        columns.push_back(SummaryColumn("", Colour::None)
                          .addRow(totals.testCases.total())
                          .addRow(totals.assertions.total()));
        columns.push_back(SummaryColumn("passed", Colour::Success)
                          .addRow(totals.testCases.passed)
                          .addRow(totals.assertions.passed));
        columns.push_back(SummaryColumn("failed", Colour::ResultError)
                          .addRow(totals.testCases.failed)
                          .addRow(totals.assertions.failed));
        columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
                          .addRow(totals.testCases.failedButOk)
                          .addRow(totals.assertions.failedButOk));

        printSummaryRow("test cases", columns, 0);
        printSummaryRow("assertions", columns, 1);
    }
}
void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
    for (auto col : cols) {
        std::string value = col.rows[row];
        if (col.label.empty()) {
            stream << label << ": ";
            if (value != "0")
                stream << value;
            else
                stream << Colour(Colour::Warning) << "- none -";
        } else if (value != "0") {
            stream << Colour(Colour::LightGrey) << " | ";
            stream << Colour(col.colour)
                << value << ' ' << col.label;
        }
    }
    stream << '\n';
}

void ConsoleReporter::printTotalsDivider(Totals const& totals) {
    if (totals.testCases.total() > 0) {
        std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
        std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
        std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
        while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
            findMax(failedRatio, failedButOkRatio, passedRatio)++;
        while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
            findMax(failedRatio, failedButOkRatio, passedRatio)--;

        stream << Colour(Colour::Error) << std::string(failedRatio, '=');
        stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
        if (totals.testCases.allPassed())
            stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
        else
            stream << Colour(Colour::Success) << std::string(passedRatio, '=');
    } else {
        stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
    }
    stream << '\n';
}
void ConsoleReporter::printSummaryDivider() {
    stream << getLineOfChars<'-'>() << '\n';
}

void ConsoleReporter::printTestFilters() {
    if (m_config->testSpec().hasFilters()) {
        Colour guard(Colour::BrightYellow);
        stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n';
    }
}

CATCH_REGISTER_REPORTER("console", ConsoleReporter)

} // end namespace Catch

#if defined(_MSC_VER)
#pragma warning(pop)
#endif

#if defined(__clang__)
#  pragma clang diagnostic pop
#endif


text:
package at.linuxtage.companion.fragments;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.paging.PagedList;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import at.linuxtage.companion.R;
import at.linuxtage.companion.adapters.EventsAdapter;
import at.linuxtage.companion.model.StatusEvent;
import at.linuxtage.companion.viewmodels.ExternalBookmarksViewModel;

public class ExternalBookmarksListFragment extends RecyclerViewFragment implements Observer<PagedList<StatusEvent>> {

	private static final String ARG_BOOKMARK_IDS = "bookmark_ids";

	private EventsAdapter adapter;

	public static ExternalBookmarksListFragment newInstance(@NonNull long[] bookmarkIds) {
		ExternalBookmarksListFragment f = new ExternalBookmarksListFragment();
		Bundle args = new Bundle();
		args.putLongArray(ARG_BOOKMARK_IDS, bookmarkIds);
		f.setArguments(args);
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		adapter = new EventsAdapter(getContext(), this);
	}

	@Override
	protected void onRecyclerViewCreated(RecyclerView recyclerView, Bundle savedInstanceState) {
		recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
		recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL));
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		setAdapter(adapter);
		setEmptyText(getString(R.string.no_bookmark));
		setProgressBarVisible(true);

		long[] bookmarkIds = getArguments().getLongArray(ARG_BOOKMARK_IDS);
		final ExternalBookmarksViewModel viewModel = ViewModelProviders.of(this).get(ExternalBookmarksViewModel.class);
		viewModel.setBookmarkIds(bookmarkIds);
		viewModel.getBookmarks().observe(getViewLifecycleOwner(), this);
	}

	@Override
	public void onChanged(PagedList<StatusEvent> bookmarks) {
		adapter.submitList(bookmarks);
		setProgressBarVisible(false);
	}
}


text:
define(["jquery", "jquery_ui", "underscore", "backbone", "marionette", "ux",
    "jquery_orgchart"
], function ($, jquery_ui, _, Backbone, Marionette, ux) {

// require("jquery-bridget/jquery.bridget")
//    $.bridget( 'masonry', masonry );

    var idAttribute = ux.idAttribute || "id";
    var typeAttribute = ux.typeAttribute || "widget";
    var labelAttribute = ux.labelAttribute || "label";
    var commentAttribute = ux.commentAttribute || "comment"
    var DEBUG = true //&& ux.DEBUG;

	ux.view.OrgChart = ux.view["meta4:ux:OrgChart"] = function(options) {
		options = ux.checkOptions(options);

		/** OrgBranch **/
		var OrgBranch = Backbone.Marionette.CompositeView.extend({
            childView: OrgBranch,  tagName: "li", childViewContainer: "ul",
            isSortable: true, isSelectable: true, isHideable: false, isHoverPanel: true,
			events: {
				"click [about]": "doEventSelect"
			},
			template: "
{{label}}

",
			initialize: function(_options) {
//DEBUG && console.debug("Init OrgBranch", this, _options)
				ux.initialize(this, _options);
			},
			childViewOptions: function(_model) {
			    var childOptions = _.extend({ model: _model }, this.options.child );
//DEBUG && console.debug("getBranchOptions: %o %o", this, childOptions)
			    return childOptions
			},
			getChildView: function(_model) {
//console.debug("getBranchChild: %o %o -> %o %o",this, arguments, this.childView, OrgChart)
                return OrgBranch
			}
		})

		var OrgChart = Backbone.Marionette.CompositeView.extend({
		    isCommon: true, isHoverPanel: true,
			childView: OrgBranch,
			tagName: "div",
			template: "

{{label}}

",
			className: "ux-org-chart", childViewContainer: ".org_root li ul",
			events: {
			  'click [about]': 'doEventSelect'
			},
			initialize: function(_options) {
				ux.initialize(this, _options);
			},
			childViewOptions: function(_model) {
			    var childOptions = _.extend({ model: _model }, this.options.child );
//DEBUG && console.debug("getRootOptions: %o %o", this, childOptions)
			    return childOptions
			},
			onShow: function() {
			    var $container = $(".orgchart_container", this.$el)
			    var $root = $(".org_root",this.$el)
console.debug("OrgChart: %o", $root)
				var options = _.extend({
				   stack: true, interactive: true, depth: 2, showLevels: 2,
				   copyClasses: true,
				   copyData: true, copyStyles: true, copyTitle: true,
				container: $container
				}, this.options.options)

			    $root.orgChart(options)
			}
		})

		return OrgChart
	}
    return ux;
 })


text:
cask "thunder" do
  version "5.0.2.65551"
  sha256 "7424c02088ca9f09e69acf276305f7f2007b9f5b3500ae4d4c5feadf01183047"

  url "https://down.sandai.net/mac/thunder_#{version}.dmg",
      verified: "down.sandai.net/mac/"
  name "Thunder"
  name "迅雷"
  desc "VPN and WiFi proxy"
  homepage "https://www.xunlei.com/"

  livecheck do
    url "https://dl.xunlei.com"
    regex(/thunder[._-](\d+(?:\.\d+)+)\.dmg/i)
  end

  auto_updates true
  depends_on macos: ">= :high_sierra"

  app "Thunder.app"

  zap trash: [
    "~/Library/Application Support/Thunder",
    "~/Library/Caches/com.xunlei.Thunder",
    "~/Library/Caches/com.xunlei.XLPlayer",
    "~/Library/Cookies/com.xunlei.Thunder.binarycookies",
    "~/Library/Preferences/com.xunlei.Thunder.loginSDK.plist",
    "~/Library/Preferences/com.xunlei.Thunder.plist",
    "~/Library/Preferences/com.xunlei.XLPlayer.plist",
    "~/Library/Saved Application State/com.xunlei.Thunder.savedState",
    "~/Library/Saved Application State/com.xunlei.XLPlayer.savedState",
    "~/Library/WebKit/com.xunlei.Thunder",
  ]
end


text:
CEvent::CEvent() {
}

CEvent::~CEvent() {
    // Do nothing
}

// Handle events
void CEvent::OnEvent(SDL_Event* Event) {

    // Switch on event type
    switch(Event->type) {

        // If event is an active event
        case SDL_ACTIVEEVENT: {
            // Switch on event active state
            switch(Event->active.state) {

                // If event is mouse focus
                case SDL_APPMOUSEFOCUS: {

                    // Do OnMouseFocus if we gained mouse focus
                    if ( Event->active.gain ) {
                        OnMouseFocus();

                    // Otherwise do this event
                    } else {
                        OnMouseBlur();
                    }

                    break;
                }

                // If App gained focus
                case SDL_APPINPUTFOCUS: {

                    // Do OnInputFocus if we gained focus
                    if ( Event->active.gain ) {
                        OnInputFocus();

                    // Otherwise do OnInputBlur
                    } else {
                        OnInputBlur();
                    }

                    break;
                }

                // If the App just became active or not
                case SDL_APPACTIVE:    {

                    // Do OnRestore if we were restored.
                    if ( Event->active.gain ) {
                        OnRestore();

                    // Otherwise do OnMinimize if we were minimized.
                    } else {
                        OnMinimize();
                    }

                    break;
                }
            }
            break;
        }

        // If a key was pressed, do the appropriate thing.
        case SDL_KEYDOWN: {

            // Call OnKeyDown with the keysym, the mod, and the unicode value
            OnKeyDown(Event->key.keysym.sym, Event->key.keysym.mod,
                      Event->key.keysym.unicode);
            break;
        }

        // Same for key unpress
        case SDL_KEYUP: {
            OnKeyUp(Event->key.keysym.sym, Event->key.keysym.mod,
                    Event->key.keysym.unicode);
            break;
        }

        // Handle mouse motion
        case SDL_MOUSEMOTION: {

            // Pass through motion and whether or not buttons are clicked
            OnMouseMove(Event->motion.x, Event->motion.y,
                        Event->motion.xrel,Event->motion.yrel,
                        (Event->motion.state & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0,
                        (Event->motion.state & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0,
                        (Event->motion.state & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0);
            break;
        }

        // Handle mouse button presses
        case SDL_MOUSEBUTTONDOWN: {

            // Switch on which button was pressed
            switch(Event->button.button) {

                // Do left things if left button was pressed
                case SDL_BUTTON_LEFT: {
                    OnLButtonDown(Event->button.x,Event->button.y);
                    break;
                }

                // Do right things if right button was pressed
                case SDL_BUTTON_RIGHT: {
                    OnRButtonDown(Event->button.x,Event->button.y);
                    break;
                }

                // Middle things
                case SDL_BUTTON_MIDDLE: {
                    OnMButtonDown(Event->button.x,Event->button.y);
                    break;
                }
            }
            break;
        }

        // Do the same thing for right button presses
        case SDL_MOUSEBUTTONUP:    {
            switch(Event->button.button) {
                case SDL_BUTTON_LEFT: {
                    OnLButtonUp(Event->button.x,Event->button.y);
                    break;
                }
                case SDL_BUTTON_RIGHT: {
                    OnRButtonUp(Event->button.x,Event->button.y);
                    break;
                }
                case SDL_BUTTON_MIDDLE: {
                    OnMButtonUp(Event->button.x,Event->button.y);
                    break;
                }
            }
            break;
        }

        // Handle joystick axis motion
        case SDL_JOYAXISMOTION: {
            OnJoyAxis(Event->jaxis.which, Event->jaxis.axis, Event->jaxis.value);
            break;
        }

        // Handle joystick ball motion
        case SDL_JOYBALLMOTION: {
            OnJoyBall(Event->jball.which, Event->jball.ball,
                      Event->jball.xrel,Event->jball.yrel);
            break;
        }

        // Handle joystick hat motion
        case SDL_JOYHATMOTION: {
            OnJoyHat(Event->jhat.which,Event->jhat.hat,Event->jhat.value);
            break;
        }

        // Handle joystick button press
        case SDL_JOYBUTTONDOWN: {
            OnJoyButtonDown(Event->jbutton.which,Event->jbutton.button);
            break;
        }

        // Handle joystick button unpress
        case SDL_JOYBUTTONUP: {
            OnJoyButtonUp(Event->jbutton.which,Event->jbutton.button);
            break;
        }

        // Handle quitting
        case SDL_QUIT: {
            OnExit();
            break;
        }

        // Handle window manager event?
        case SDL_SYSWMEVENT: {
            //Ignore
            break;
        }

        // Handle resize events
        case SDL_VIDEORESIZE: {
            OnResize(Event->resize.w,Event->resize.h);
            break;
        }

        // Handle expose events.
        case SDL_VIDEOEXPOSE: {
            OnExpose();
            break;
        }

        // Handle anything else
        default: {
            OnUser(Event->user.type, Event->user.code,
                   Event->user.data1,Event->user.data2);
            break;
        }
    }
}

// What to do on input focus.
void CEvent::OnInputFocus() {
    //Pure virtual, do nothing
}

// What to do on input blur
void CEvent::OnInputBlur() {
    //Pure virtual, do nothing
}

// What to do on keypress
void CEvent::OnKeyDown(SDLKey, SDLMod, Uint16) {
    //Pure virtual, do nothing
}

// What to do on key unpress
void CEvent::OnKeyUp(SDLKey, SDLMod, Uint16) {
    //Pure virtual, do nothing
}

// What to do on mouse focus
void CEvent::OnMouseFocus() {
    //Pure virtual, do nothing
}

// What to do on mouse blur
void CEvent::OnMouseBlur() {
    //Pure virtual, do nothing
}

// What to do on mouse movement
void CEvent::OnMouseMove(int, int, int, int,
                         bool, bool, bool) {
    //Pure virtual, do nothing
}

// Mouse wheel movement
void CEvent::OnMouseWheel(bool, bool) {
    //Pure virtual, do nothing
}

// L button press
void CEvent::OnLButtonDown(int, int) {
    //Pure virtual, do nothing
}

// L button unpress
void CEvent::OnLButtonUp(int, int) {
    //Pure virtual, do nothing
}

// R Button press
void CEvent::OnRButtonDown(int, int) {
    //Pure virtual, do nothing
}

// R Button unpress
void CEvent::OnRButtonUp(int, int) {
    //Pure virtual, do nothing
}

// M Button press
void CEvent::OnMButtonDown(int, int) {
    //Pure virtual, do nothing
}

// M Button unpress
void CEvent::OnMButtonUp(int, int) {
    //Pure virtual, do nothing
}

// Joystick axis movement
void CEvent::OnJoyAxis(Uint8, Uint8, Sint16) {
    //Pure virtual, do nothing
}

// Handle joystick button press
void CEvent::OnJoyButtonDown(Uint8, Uint8) {
    //Pure virtual, do nothing
}

// Handle joystick button unpress
void CEvent::OnJoyButtonUp(Uint8, Uint8) {
    //Pure virtual, do nothing
}

// Handle joystick hat press
void CEvent::OnJoyHat(Uint8, Uint8, Uint8) {
    //Pure virtual, do nothing
}

// Handle joystick ball movement
void CEvent::OnJoyBall(Uint8, Uint8, Sint16, Sint16) {
    //Pure virtual, do nothing
}

// Handle minimize
void CEvent::OnMinimize() {
    //Pure virtual, do nothing
}

// Handle restore
void CEvent::OnRestore() {
    //Pure virtual, do nothing
}

// Handle resize
void CEvent::OnResize(int, int) {
    //Pure virtual, do nothing
}

// Handle expose
void CEvent::OnExpose() {
    //Pure virtual, do nothing
}

// Handle exit
void CEvent::OnExit() {
    //Pure virtual, do nothing
}

// Handle other stuff
void CEvent::OnUser(Uint8, int, void*, void*) {
    //Pure virtual, do nothing
}


text:
static NSString * const kFBClusteringManagerLockName = @"co.infinum.clusteringLock";

#pragma mark - Utility functions

NSInteger FBZoomScaleToZoomLevel(MKZoomScale scale)
{
    double totalTilesAtMaxZoom = MKMapSizeWorld.width / 256.0;
    NSInteger zoomLevelAtMaxZoom = log2(totalTilesAtMaxZoom);
    NSInteger zoomLevel = MAX(0, zoomLevelAtMaxZoom + floor(log2f(scale) + 0.5));

    return zoomLevel;
}

CGFloat FBCellSizeForZoomScale(MKZoomScale zoomScale)
{
    NSInteger zoomLevel = FBZoomScaleToZoomLevel(zoomScale);

    switch (zoomLevel) {
        case 13:
        case 14:
        case 15:
            return 64;
        case 16:
        case 17:
        case 18:
            return 32;
        case 19:
            return 16;

        default:
            return 88;
    }
}

#pragma mark - FBClusteringManager

@interface FBClusteringManager ()

@property (nonatomic, strong) FBQuadTree *tree;
@property (nonatomic, strong) NSRecursiveLock *lock;

@end

@implementation FBClusteringManager

- (id)init
{
    return [self initWithAnnotations:nil];
}

- (id)initWithAnnotations:(NSArray *)annotations
{
    self = [super init];
    if (self) {
        _lock = [NSRecursiveLock new];
        [self addAnnotations:annotations];
    }
    return self;
}

- (void)setAnnotations:(NSArray *)annotations
{
    self.tree = nil;
    [self addAnnotations:annotations];
}

- (void)addAnnotations:(NSArray *)annotations
{
    if (!self.tree) {
        self.tree = [[FBQuadTree alloc] init];
    }

    [self.lock lock];
    for (id<MKAnnotation> annotation in annotations) {
        [self.tree insertAnnotation:annotation];
    }
    [self.lock unlock];
}

- (NSArray *)clusteredAnnotationsWithinMapRect:(MKMapRect)rect withZoomScale:(double)zoomScale
{
    return [self clusteredAnnotationsWithinMapRect:rect withZoomScale:zoomScale withFilter:nil];
}

- (NSArray *)clusteredAnnotationsWithinMapRect:(MKMapRect)rect withZoomScale:(double)zoomScale withFilter:(BOOL (^)(id<MKAnnotation>)) filter
{
    double cellSize = FBCellSizeForZoomScale(zoomScale);
    if ([self.delegate respondsToSelector:@selector(cellSizeFactorForCoordinator:)]) {
        cellSize *= [self.delegate cellSizeFactorForCoordinator:self];
    }
    double scaleFactor = zoomScale / cellSize;

    NSInteger minX = floor(MKMapRectGetMinX(rect) * scaleFactor);
    NSInteger maxX = floor(MKMapRectGetMaxX(rect) * scaleFactor);
    NSInteger minY = floor(MKMapRectGetMinY(rect) * scaleFactor);
    NSInteger maxY = floor(MKMapRectGetMaxY(rect) * scaleFactor);

    NSMutableArray *clusteredAnnotations = [[NSMutableArray alloc] init];

    [self.lock lock];
    for (NSInteger x = minX; x <= maxX; x++) {
        for (NSInteger y = minY; y <= maxY; y++) {
            MKMapRect mapRect = MKMapRectMake(x/scaleFactor, y/scaleFactor, 1.0/scaleFactor, 1.0/scaleFactor);
            FBBoundingBox mapBox = FBBoundingBoxForMapRect(mapRect);

            __block double totalLatitude = 0;
            __block double totalLongitude = 0;

            NSMutableArray *annotations = [[NSMutableArray alloc] init];

            [self.tree enumerateAnnotationsInBox:mapBox usingBlock:^(id<MKAnnotation> obj) {

                if(!filter || (filter(obj) == TRUE))
                {
                    totalLatitude += [obj coordinate].latitude;
                    totalLongitude += [obj coordinate].longitude;
                    [annotations addObject:obj];
                }
            }];

            NSInteger count = [annotations count];
            if (count == 1) {
                [clusteredAnnotations addObjectsFromArray:annotations];
            }

            if (count > 1) {
                CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(totalLatitude/count, totalLongitude/count);
                FBAnnotationCluster *cluster = [[FBAnnotationCluster alloc] init];
                cluster.coordinate = coordinate;
                cluster.annotations = annotations;
                [clusteredAnnotations addObject:cluster];
            }
        }
    }
    [self.lock unlock];

    return [NSArray arrayWithArray:clusteredAnnotations];
}

- (NSArray *)allAnnotations
{
    NSMutableArray *annotations = [[NSMutableArray alloc] init];

    [self.lock lock];
    [self.tree enumerateAnnotationsUsingBlock:^(id<MKAnnotation> obj) {
        [annotations addObject:obj];
    }];
    [self.lock unlock];

    return annotations;
}

- (void)displayAnnotations:(NSArray *)annotations onMapView:(MKMapView *)mapView
{
    NSMutableSet *before = [NSMutableSet setWithArray:mapView.annotations];
    [before removeObject:[mapView userLocation]];
    NSSet *after = [NSSet setWithArray:annotations];

    NSMutableSet *toKeep = [NSMutableSet setWithSet:before];
    [toKeep intersectSet:after];

    NSMutableSet *toAdd = [NSMutableSet setWithSet:after];
    [toAdd minusSet:toKeep];

    NSMutableSet *toRemove = [NSMutableSet setWithSet:before];
    [toRemove minusSet:after];

    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [mapView addAnnotations:[toAdd allObjects]];
        [mapView removeAnnotations:[toRemove allObjects]];
    }];
}

@end


text:
namespace Neat.WindowsPhone7.Service.Rest.Client.Proxy.Interface
{
    public interface IHttpWebProxy
    {
        /// <summary>
        /// Send the httpWebProxyRequest to the remote server asynchronously and specify a Response callback
        /// </summary>
        /// <param name="httpWebRequestParameters"> </param>
        void BeginRequest(HttpWebRequestParameters httpWebRequestParameters);
    }
}


text:
namespace Zenith.Core.Models.DeepSpaceNetwork
{
    public class MeasuredValue<T> where T : struct
    {
        T Value { get; set; }
        string Units { get; set; }
    }
}


text:
module RubyCritic
  module SourceControlSystem
    class Mercurial < Base
      register_system

      def self.supported?
        `hg verify 2>&1` && $CHILD_STATUS.success?
      end

      def self.to_s
        'Mercurial'
      end

      def revisions_count(path)
        `hg log #{path.shellescape} --template '1'`.size
      end

      def date_of_last_commit(path)
        `hg log #{path.shellescape} --template '{date|isodate}' --limit 1`.chomp
      end

      def revision?
        false
      end
    end
  end
end


text:
using System;
using NUnit.Framework;

namespace GeneticSharp.Extensions.UnitTests.Checkers
{
    [TestFixture]
    [Category("Extensions")]
    public class CheckersMoveTest
    {
        [Test]
        public void Constructor_NullPiece_Exception()
        {
            var actual = Assert.Catch<ArgumentNullException>(() =>
            {
                new CheckersMove(null, new CheckersSquare(0, 0));
            });

            Assert.AreEqual("piece", actual.ParamName);
        }

        [Test]
        public void Constructor_PieceWithoutCurrentSquare_Exception()
        {
            Assert.Catch<ArgumentException>(() =>
            {
                new CheckersMove(new CheckersPiece(CheckersPlayer.PlayerOne), null);
            }, "A piece for a move should have a current square defined.");

        }

        [Test]
        public void Constructor_ToSquareNull_Exception()
        {
            var actual = Assert.Catch<ArgumentNullException>(() =>
            {
                new CheckersMove(new CheckersPiece(CheckersPlayer.PlayerOne) { CurrentSquare = new CheckersSquare(0, 1) }, null);
            });

            Assert.AreEqual("toSquare", actual.ParamName);
        }
    }
}


text:
// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
/*

    This is an example illustrating the use of the gui api from the dlib C++ Library.

    This is a pretty simple example.  It makes a window with a user
    defined widget (a draggable colored box) and a button.  You can drag the
    box around or click the button which increments a counter.
*/

#include <dlib/gui_widgets.h>
#include <sstream>
#include <string>

using namespace std;
using namespace dlib;

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

class color_box : public draggable
{
    /*
        Here I am defining a custom drawable widget that is a colored box that
        you can drag around on the screen.  draggable is a special kind of drawable
        object that, as the name implies, is draggable by the user via the mouse.
        To make my color_box draggable all I need to do is inherit from draggable.
    */
    unsigned char red, green,blue;

public:
    color_box (
        drawable_window& w,
        rectangle area,
        unsigned char red_,
        unsigned char green_,
        unsigned char blue_
    ) :
        draggable(w),
        red(red_),
        green(green_),
        blue(blue_)
    {
        rect = area;
        set_draggable_area(rectangle(10,10,400,400));

        // Whenever you make your own drawable widget (or inherit from any drawable widget
        // or interface such as draggable) you have to remember to call this function to
        // enable the events.  The idea here is that you can perform whatever setup you
        // need to do to get your object into a valid state without needing to worry about
        // event handlers triggering before you are ready.
        enable_events();
    }

    ~color_box (
    )
    {
        // Disable all further events for this drawable object.  We have to do this
        // because we don't want any events (like draw()) coming to this object while or
        // after it has been destructed.
        disable_events();

        // Tell the parent window to redraw its area that previously contained this
        // drawable object.
        parent.invalidate_rectangle(rect);
    }

private:

    void draw (
        const canvas& c
    ) const
    {
        // The canvas is an object that represents a part of the parent window
        // that needs to be redrawn.

        // The first thing I usually do is check if the draw call is for part
        // of the window that overlaps with my widget.  We don't have to do this
        // but it is usually good to do as a speed hack.  Also, the reason
        // I don't have it set to only give you draw calls when it does indeed
        // overlap is because you might want to do some drawing outside of your
        // widget's rectangle.  But usually you don't want to do that :)
        rectangle area = c.intersect(rect);
        if (area.is_empty() == true)
            return;

        // This simple widget is just going to draw a box on the screen.
        fill_rect(c,rect,rgb_pixel(red,green,blue));
    }
};

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

class win : public drawable_window
{
    /*
        Here I am going to define our window.  In general, you can define as
        many window types as you like and make as many instances of them as you want.
        In this example I am only making one though.
    */
public:
    win(
    ) : // All widgets take their parent window as an argument to their constructor.
        c(*this),
        b(*this),
        cb(*this,rectangle(100,100,200,200),0,0,255), // the color_box will be blue and 101 pixels wide and tall
        mbar(*this)
    {
        // tell our button to put itself at the position (10,60).
        b.set_pos(10,60);
        b.set_name("button");

        // lets put the label 5 pixels below the button
        c.set_pos(b.left(),b.bottom()+5);

        // set which function should get called when the button gets clicked.  In this case we want
        // the on_button_clicked member to be called on *this.
        b.set_click_handler(*this,&win::on_button_clicked);
        // Alternatively, if you have a compiler which supports the lambda functions from the
        // new C++ standard then you can use a lambda function instead of telling the click
        // handler to call one of the member functions.  So for example, you could do this
        // instead (uncomment the code if you have C++0x support):
        /*
        b.set_click_handler([&](){
                ++counter;
                ostringstream sout;
                sout << "Counter: " << counter;
                c.set_text(sout.str());
                });
        */
        // In general, all the functions which register events can take either member
        // functions or lambda functions.

        // Lets also make a simple menu bar.
        // First we say how many menus we want in our menu bar.  In this example we only want 1.
        mbar.set_number_of_menus(1);
        // Now we set the name of our menu.  The 'M' means that the M in Menu will be underlined
        // and the user will be able to select it by hitting alt+M
        mbar.set_menu_name(0,"Menu",'M');

        // Now we add some items to the menu.  Note that items in a menu are listed in the
        // order in which they were added.

        // First lets make a menu item that does the same thing as our button does when it is clicked.
        // Again, the 'C' means the C in Click is underlined in the menu.
        mbar.menu(0).add_menu_item(menu_item_text("Click Button!",*this,&win::on_button_clicked,'C'));
        // lets add a separator (i.e. a horizontal separating line) to the menu
        mbar.menu(0).add_menu_item(menu_item_separator());
        // Now lets make a menu item that calls show_about when the user selects it.
        mbar.menu(0).add_menu_item(menu_item_text("About",*this,&win::show_about,'A'));

        // set the size of this window
        set_size(430,380);

        counter = 0;

        set_title("dlib gui example");
        show();
    }

    ~win(
    )
    {
        // You should always call close_window() in the destructor of window
        // objects to ensure that no events will be sent to this window while
        // it is being destructed.
        close_window();
    }

private:

    void on_button_clicked (
    )
    {
        // when someone clicks our button it will increment the counter and
        // display it in our label c.
        ++counter;
        ostringstream sout;
        sout << "counter: " << counter;
        c.set_text(sout.str());
    }

    void show_about(
    )
    {
        message_box("About","This is a dlib gui example program");
    }

    unsigned long counter;
    label c;
    button b;
    color_box cb;
    menu_bar mbar;
};

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

int main()
{
    // create our window
    win my_window;

    // wait until the user closes this window before we let the program
    // terminate.
    my_window.wait_until_closed();

    return 0;
}

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

// Normally, if you built this application on MS Windows in Visual Studio you
// would see a black console window pop up when you ran it.  The following
// #pragma directives tell Visual Studio to not include a console window along
// with your application.  However, if you prefer to have the console pop up as
// well then simply remove these #pragma statements.
#ifdef _MSC_VER
#   pragma comment( linker, "/entry:mainCRTStartup" )
#   pragma comment( linker, "/SUBSYSTEM:WINDOWS" )
#endif

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


text:
namespace lldb_private {
namespace process_gdb_remote {

void GDBRemoteTest::SetUpTestCase() {
#if defined(_MSC_VER)
  WSADATA data;
  ::WSAStartup(MAKEWORD(2, 2), &data);
#endif
}

void GDBRemoteTest::TearDownTestCase() {
#if defined(_MSC_VER)
  ::WSACleanup();
#endif
}

llvm::Error GDBRemoteTest::Connect(GDBRemoteCommunication &client,
                                   GDBRemoteCommunication &server) {
  bool child_processes_inherit = false;
  TCPSocket listen_socket(true, child_processes_inherit);
  if (llvm::Error error = listen_socket.Listen("127.0.0.1:0", 5).ToError())
    return error;

  Socket *accept_socket;
  std::future<Status> accept_status = std::async(
      std::launch::async, [&] { return listen_socket.Accept(accept_socket); });

  llvm::SmallString<32> remote_addr;
  llvm::raw_svector_ostream(remote_addr)
      << "connect://localhost:" << listen_socket.GetLocalPortNumber();

  std::unique_ptr<ConnectionFileDescriptor> conn_up(
      new ConnectionFileDescriptor());
  if (conn_up->Connect(remote_addr, nullptr) != lldb::eConnectionStatusSuccess)
    return llvm::make_error<llvm::StringError>("Unable to connect",
                                               llvm::inconvertibleErrorCode());

  client.SetConnection(conn_up.release());
  if (llvm::Error error = accept_status.get().ToError())
    return error;

  server.SetConnection(new ConnectionFileDescriptor(accept_socket));
  return llvm::Error::success();
}

} // namespace process_gdb_remote
} // namespace lldb_private


text:
  #define BLUEFRUIT_HWSERIAL_NAME      Serial1
#endif

// SHARED UART SETTINGS
// ----------------------------------------------------------------------------------------------
// The following sets the optional Mode pin, its recommended but not required
// ----------------------------------------------------------------------------------------------
#define BLUEFRUIT_UART_MODE_PIN        -1    // Set to -1 if unused

// HARDWARE SPI SETTINGS
// ----------------------------------------------------------------------------------------------
// The following macros declare the pins to use for HW SPI communication.
// SCK, MISO and MOSI should be connected to the HW SPI pins on the Uno, etc.
// This should be used with nRF51822 based Bluefruit LE modules that use SPI.
// ----------------------------------------------------------------------------------------------
#define BLUEFRUIT_SPI_CS               8
#define BLUEFRUIT_SPI_IRQ              7
#define BLUEFRUIT_SPI_RST              6    // Optional but recommended, set to -1 if unused

extern unsigned int getBatteryVoltage();
extern unsigned char chargeLookup(const unsigned int * mv_curve, const unsigned char * charge_curve, unsigned int mv_in);

#endif


text:
package org.codehaus.griffon.runtime.datasource;

import griffon.annotations.inject.DependsOn;
import griffon.core.Configuration;
import griffon.core.addon.GriffonAddon;
import griffon.core.injection.Module;
import griffon.plugins.datasource.DataSourceFactory;
import griffon.plugins.datasource.DataSourceHandler;
import griffon.plugins.datasource.DataSourceStorage;
import org.codehaus.griffon.runtime.core.injection.AbstractModule;
import org.codehaus.griffon.runtime.util.ResourceBundleProvider;
import org.kordamp.jipsy.annotations.ServiceProviderFor;

import javax.inject.Named;
import java.util.ResourceBundle;

import static griffon.util.AnnotationUtils.named;

/**
 * @author Andres Almiray
 */
@Named("datasource")
@DependsOn("monitor")
@ServiceProviderFor(Module.class)
public class DataSourceModule extends AbstractModule {
    @Override
    protected void doConfigure() {
        // tag::bindings[]
        bind(ResourceBundle.class)
            .withClassifier(named("datasource"))
            .toProvider(new ResourceBundleProvider("DataSource"))
            .asSingleton();

        bind(Configuration.class)
            .withClassifier(named("datasource"))
            .to(DefaultDataSourceConfiguration.class)
            .asSingleton();

        bind(DataSourceStorage.class)
            .to(DefaultDataSourceStorage.class)
            .asSingleton();

        bind(DataSourceFactory.class)
            .to(DefaultDataSourceFactory.class)
            .asSingleton();

        bind(DataSourceHandler.class)
            .to(DefaultDataSourceHandler.class)
            .asSingleton();

        bind(GriffonAddon.class)
            .to(DataSourceAddon.class)
            .asSingleton();
        // end::bindings[]
    }
}


text:
const { CHANNEL_TYPES } = require("../constants");

module.exports = function(irc, ircConfig, io) {
	const addAndJoinChannel = function(serverName, name, data, callback) {
		ircConfig.addChannelToIrcConfig(
			serverName, name, CHANNEL_TYPES.PUBLIC, data,
			(err) => {
				joinIrcChannel(serverName, name);
				if (io) {
					io.emitIrcConfig();
				}
				if (typeof callback === "function") {
					callback(err);
				}
			}
		);
	};

	const connectUnconnectedIrcs = function() {
		irc.connectUnconnectedClients();
	};

	const loadAndConnectUnconnectedIrcs = function(callback) {
		ircConfig.loadAndEmitIrcConfig(() => {
			connectUnconnectedIrcs();

			if (typeof callback === "function") {
				callback();
			}
		});
	};

	const reconnectIrcServer = function(serverName) {
		irc.reconnectServer(serverName);
	};

	const disconnectIrcServer = function(serverName) {
		irc.disconnectServer(serverName);
	};

	const disconnectAndRemoveIrcServer = function(serverName) {
		irc.removeServer(serverName);
	};

	const joinIrcChannel = function(serverName, channelName) {
		irc.joinChannel(serverName, channelName);
	};

	const partIrcChannel = function(serverName, channelName) {
		irc.partChannel(serverName, channelName);
	};

	const sendOutgoingMessage = function(channel, message, messageToken) {
		irc.sendOutgoingMessage(channel, message, messageToken);
	};

	const currentIrcClients = function() {
		return irc.clients();
	};

	const getIrcChannelNameFromUri = function(channelUri) {
		return irc.getIrcChannelNameFromUri(channelUri);
	};

	return {
		addAndJoinChannel,
		connectUnconnectedIrcs,
		currentIrcClients,
		disconnectAndRemoveIrcServer,
		disconnectIrcServer,
		getIrcChannelNameFromUri,
		joinIrcChannel,
		loadAndConnectUnconnectedIrcs,
		partIrcChannel,
		reconnectIrcServer,
		sendOutgoingMessage
	};
};


text:
from __future__ import absolute_import

from rest_framework.response import Response

from sentry.api.bases import (
    OrganizationEndpoint,
    SentryAppBaseEndpoint,
    add_integration_platform_metric_tag,
)
from sentry.api.paginator import OffsetPaginator
from sentry.api.serializers import serialize
from sentry.coreapi import APIError
from sentry.mediators import sentry_app_components
from sentry.models import Project, SentryAppComponent

class SentryAppComponentsEndpoint(SentryAppBaseEndpoint):
    def get(self, request, sentry_app):
        return self.paginate(
            request=request,
            queryset=sentry_app.components.all(),
            paginator_cls=OffsetPaginator,
            on_results=lambda x: serialize(x, request.user),
        )

class OrganizationSentryAppComponentsEndpoint(OrganizationEndpoint):
    @add_integration_platform_metric_tag
    def get(self, request, organization):
        try:
            project = Project.objects.get(
                id=request.GET["projectId"], organization_id=organization.id
            )
        except Project.DoesNotExist:
            return Response([], status=404)

        components = []

        for install in organization.sentry_app_installations.all():
            _components = SentryAppComponent.objects.filter(sentry_app_id=install.sentry_app_id)

            if "filter" in request.GET:
                _components = _components.filter(type=request.GET["filter"])

            for component in _components:
                try:
                    sentry_app_components.Preparer.run(
                        component=component, install=install, project=project
                    )
                    components.append(component)
                except APIError:
                    continue

        return self.paginate(
            request=request,
            queryset=components,
            paginator_cls=OffsetPaginator,
            on_results=lambda x: serialize(x, request.user),
        )


text:
require "integration/factories/collection_factory"

class InstanceTemplateFactory < CollectionFactory
  def initialize(example)
    super(Fog::Compute[:google].instance_templates, example)
  end

  def params
    {
      :name => resource_name,
      # TODO: Properties config is convoluted, needs to be refactored
      :properties => {
          :machine_type => TEST_MACHINE_TYPE,
          :disks => [{
                         :boot => true,
                         :auto_delete => true,
                         :initialize_params =>
                          { :source_image => "projects/ubuntu-os-cloud/global/images/ubuntu-1804-bionic-v20180522" }
                     }],
          :network_interfaces => [{ :network => "global/networks/default" }]
      }
    }
  end
end


text:
package org.wso2.carbon.uuf.spi.auth;

public interface User {

    String getUsername();

    boolean hasPermission(String resourceUri, String action);

}


text:
{{{
  "title": "Object Storage Regions and Service Points",
  "date": "07-05-2016",
  "author": "Daniel Stephan",
  "attachments": [],
  "contentIsHTML": false
}}}

### Description
The CenturyLink Cloud Object Storage service is available in multiple regions. A region consists of two data centers, a primary and a secondary. You can only read and write to the primary. You cannot directly interact with the secondary. Under certain circumstances, the service promotes the secondary to primary. Once you create a bucket in a specific region, you need to use the appropriate service point to interact with that bucket.

Here is a list of the different regions, the individual data centers that comprise the region, and the region service points.

### Service Points
|Region|Primary Data Center|Secondary Data Center|Service Point|
|---|---|---|---:|
|Canada|CA1|CA3|canada.os.ctl.io|
|US-East|VA1|NY1|useast.os.ctl.io|


text:
namespace chromeos {

// Representation independent class that controls screen showing warning about
// malformed HWID to users.
class WrongHWIDScreen : public BaseScreen,
                        public WrongHWIDScreenActor::Delegate {
 public:
  WrongHWIDScreen(BaseScreenDelegate* base_screen_delegate,
                  WrongHWIDScreenActor* actor);
  virtual ~WrongHWIDScreen();

  // BaseScreen implementation:
  virtual void PrepareToShow() override;
  virtual void Show() override;
  virtual void Hide() override;
  virtual std::string GetName() const override;

  // WrongHWIDScreenActor::Delegate implementation:
  virtual void OnExit() override;
  virtual void OnActorDestroyed(WrongHWIDScreenActor* actor) override;

 private:
  WrongHWIDScreenActor* actor_;

  DISALLOW_COPY_AND_ASSIGN(WrongHWIDScreen);
};

}  // namespace chromeos

#endif  // CHROME_BROWSER_CHROMEOS_LOGIN_SCREENS_WRONG_HWID_SCREEN_H_