text:
import argparse
from unittest import mock

from blazarclient import shell
from blazarclient import tests
from blazarclient.v1.shell_commands import hosts

class CreateHostTest(tests.TestCase):

    def setUp(self):
        super(CreateHostTest, self).setUp()
        self.create_host = hosts.CreateHost(shell.BlazarShell(), mock.Mock())

    def test_args2body(self):
        args = argparse.Namespace(
            name='test-host',
            extra_capabilities=[
                'extra_key1=extra_value1',
                'extra_key2=extra_value2',
            ]
        )

        expected = {
            'name': 'test-host',
            'extra_key1': 'extra_value1',
            'extra_key2': 'extra_value2',
        }

        ret = self.create_host.args2body(args)
        self.assertDictEqual(ret, expected)

class UpdateHostTest(tests.TestCase):

    def create_update_command(self, list_value):
        mock_host_manager = mock.Mock()
        mock_host_manager.list.return_value = list_value

        mock_client = mock.Mock()
        mock_client.host = mock_host_manager

        blazar_shell = shell.BlazarShell()
        blazar_shell.client = mock_client
        return hosts.UpdateHost(blazar_shell, mock.Mock()), mock_host_manager

    def test_update_host(self):
        list_value = [
            {'id': '101', 'hypervisor_hostname': 'host-1'},
            {'id': '201', 'hypervisor_hostname': 'host-2'},
        ]
        update_host, host_manager = self.create_update_command(list_value)
        args = argparse.Namespace(
            id='101',
            extra_capabilities=[
                'key1=value1',
                'key2=value2'
            ])
        expected = {
            'values': {
                'key1': 'value1',
                'key2': 'value2'
            }
        }
        update_host.run(args)
        host_manager.update.assert_called_once_with('101', **expected)

    def test_update_host_with_name(self):
        list_value = [
            {'id': '101', 'hypervisor_hostname': 'host-1'},
            {'id': '201', 'hypervisor_hostname': 'host-2'},
        ]
        update_host, host_manager = self.create_update_command(list_value)
        args = argparse.Namespace(
            id='host-1',
            extra_capabilities=[
                'key1=value1',
                'key2=value2'
            ])
        expected = {
            'values': {
                'key1': 'value1',
                'key2': 'value2'
            }
        }
        update_host.run(args)
        host_manager.update.assert_called_once_with('101', **expected)

    def test_update_host_with_name_startwith_number(self):
        list_value = [
            {'id': '101', 'hypervisor_hostname': '1-host'},
            {'id': '201', 'hypervisor_hostname': '2-host'},
        ]
        update_host, host_manager = self.create_update_command(list_value)
        args = argparse.Namespace(
            id='1-host',
            extra_capabilities=[
                'key1=value1',
                'key2=value2'
            ])
        expected = {
            'values': {
                'key1': 'value1',
                'key2': 'value2'
            }
        }
        update_host.run(args)
        host_manager.update.assert_called_once_with('101', **expected)

class ShowHostTest(tests.TestCase):

    def create_show_command(self, list_value, get_value):
        mock_host_manager = mock.Mock()
        mock_host_manager.list.return_value = list_value
        mock_host_manager.get.return_value = get_value

        mock_client = mock.Mock()
        mock_client.host = mock_host_manager

        blazar_shell = shell.BlazarShell()
        blazar_shell.client = mock_client
        return hosts.ShowHost(blazar_shell, mock.Mock()), mock_host_manager

    def test_show_host(self):
        list_value = [
            {'id': '101', 'hypervisor_hostname': 'host-1'},
            {'id': '201', 'hypervisor_hostname': 'host-2'},
        ]
        get_value = {
            'id': '101', 'hypervisor_hostname': 'host-1'}

        show_host, host_manager = self.create_show_command(list_value,
                                                           get_value)

        args = argparse.Namespace(id='101')
        expected = [('hypervisor_hostname', 'id'), ('host-1', '101')]

        ret = show_host.get_data(args)
        self.assertEqual(ret, expected)

        host_manager.get.assert_called_once_with('101')

    def test_show_host_with_name(self):
        list_value = [
            {'id': '101', 'hypervisor_hostname': 'host-1'},
            {'id': '201', 'hypervisor_hostname': 'host-2'},
        ]
        get_value = {
            'id': '101', 'hypervisor_hostname': 'host-1'}

        show_host, host_manager = self.create_show_command(list_value,
                                                           get_value)

        args = argparse.Namespace(id='host-1')
        expected = [('hypervisor_hostname', 'id'), ('host-1', '101')]

        ret = show_host.get_data(args)
        self.assertEqual(ret, expected)

        host_manager.get.assert_called_once_with('101')

    def test_show_host_with_name_startwith_number(self):
        list_value = [
            {'id': '101', 'hypervisor_hostname': '1-host'},
            {'id': '201', 'hypervisor_hostname': '2-host'},
        ]
        get_value = {
            'id': '101', 'hypervisor_hostname': '1-host'}

        show_host, host_manager = self.create_show_command(list_value,
                                                           get_value)
        args = argparse.Namespace(id='1-host')
        expected = [('hypervisor_hostname', 'id'), ('1-host', '101')]

        ret = show_host.get_data(args)
        self.assertEqual(ret, expected)

        host_manager.get.assert_called_once_with('101')

class DeleteHostTest(tests.TestCase):

    def create_delete_command(self, list_value):
        mock_host_manager = mock.Mock()
        mock_host_manager.list.return_value = list_value

        mock_client = mock.Mock()
        mock_client.host = mock_host_manager

        blazar_shell = shell.BlazarShell()
        blazar_shell.client = mock_client
        return hosts.DeleteHost(blazar_shell, mock.Mock()), mock_host_manager

    def test_delete_host(self):
        list_value = [
            {'id': '101', 'hypervisor_hostname': 'host-1'},
            {'id': '201', 'hypervisor_hostname': 'host-2'},
        ]
        delete_host, host_manager = self.create_delete_command(list_value)

        args = argparse.Namespace(id='101')
        delete_host.run(args)

        host_manager.delete.assert_called_once_with('101')

    def test_delete_host_with_name(self):
        list_value = [
            {'id': '101', 'hypervisor_hostname': 'host-1'},
            {'id': '201', 'hypervisor_hostname': 'host-2'},
        ]
        delete_host, host_manager = self.create_delete_command(list_value)

        args = argparse.Namespace(id='host-1')
        delete_host.run(args)

        host_manager.delete.assert_called_once_with('101')

    def test_delete_host_with_name_startwith_number(self):
        list_value = [
            {'id': '101', 'hypervisor_hostname': '1-host'},
            {'id': '201', 'hypervisor_hostname': '2-host'},
        ]
        delete_host, host_manager = self.create_delete_command(list_value)

        args = argparse.Namespace(id='1-host')
        delete_host.run(args)

        host_manager.delete.assert_called_once_with('101')


text:
/**
 * @fileOverview jasmine runner in nodejs for KISSY.
 * refer: https://github.com/mhevery/jasmine-node/
 * @author yiminghe@gmail.com
 */

// global
var S = global.KISSY = require('../../' + 'build/kissy-nodejs.js');

var jasmineWrapper = require('../jasmine/jasmine');

var jasmine = jasmineWrapper.jasmine;

S.each(jasmineWrapper, function (v, k) {
    global[k] = v;
});

require('jasmine-reporters');

// ------------ configs start

var isVerbose = false;
var showColors = true;
var extentions = "js";
var match = '.';
var matchAll = false;

var junitReport = {
    report: true,
    savePath: "./reports/",
    useDotNotation: true,
    consolidate: true
};

var mods = [
    'xtemplate',
    'kison',
    'json',
    'base',
    'htmlparser',
    'event/custom'
];

// ------------ configs end

var specFolders = [];

var util,
    path = require('path');

try {
    util = require('util')
} catch (e) {
    util = require('sys')
}

for (var key in jasmine) {
    global[key] = jasmine[key];
}

S.each(mods, function (m) {
    m = m.replace(/\//g, '/sub-modules/');
    specFolders.push(m + '/tests/specs/');
});

var regExpSpec = new RegExp(match + (matchAll ? "" : "spec\\.") +
    "(" + extentions + ")$", 'i');

var cwd = process.cwd();

// in case run from idea
if (!S.endsWith(cwd, "src")) {
    cwd += '/src';
}

var exitCode, index = 0;

console.log(mods);

// KISSY.use is asynchronous even in nodejs
KISSY.use(mods, function (S) {

    var args = S.makeArray(arguments);

    var index = 0;

    function onComplete(runner) {
        var description = runner.queue.blocks[0].description;
        util.print(description + ' ↑ \n');
        util.print(new Array(20).join('-'));
        util.print('\n');
        if (runner.results().failedCount == 0) {
            exitCode = 0;
        } else {
            exitCode = 1;
            process.exit(exitCode);
        }

        process.nextTick(function () {
            // new environment
            jasmine.currentEnv_ = new jasmine.Env();
            next();
        });
    }

    function next() {

        if (index < specFolders.length) {
            var specFolder = path.resolve(cwd, specFolders[index++]);

            executeSpecsInFolder(specFolder,
                onComplete,
                isVerbose,
                showColors,
                regExpSpec,
                junitReport);
        }
    }

    next();

});

function help() {
    util.print([
        'USAGE: jasmine-node [--color|--noColor] [--verbose] [--coffee] directory'
        , ''
        , 'Options:'
        , '  --color            - use color coding for output'
        , '  --noColor          - do not use color coding for output'
        , '  -m, --match REGEXP - load only specs containing "REGEXPspec"'
        , '  --matchAll         - relax requirement of "spec" in spec file names'
        , '  --verbose          - print extra information per each test run'
        , '  --junitReport      - export tests results as junitReport xml format'
        , '  --output           - defines the output folder for junitReport files'
        , '  -h, --help         - display this help and exit'
        , ''
    ].join("\n"));

    process.exit(-1);
}

var walkdir = require('walkdir');
var fs = require('fs');

function loadSpecs(loadPath, matcher) {
    var wannaBeSpecs = walkdir.sync(loadPath),
        specs = [];

    for (var i = 0; i < wannaBeSpecs.length; i++) {
        var file = wannaBeSpecs[i];
        try {
            if (fs.statSync(file).isFile()) {
                if (!/.*node_modules.*/.test(file) &&
                    matcher.test(path.basename(file))) {
                    specs.push(file);
                }
            }
        } catch (e) {
            // nothing to do here
        }
    }

    return specs;
}

var jasmineNode = require('../jasmine/node/reporter').jasmineNode;

function executeSpecsInFolder(folder, done, isVerbose, showColors, matcher, junitReport) {
    var fileMatcher = matcher || new RegExp(".(js)$", "i"),
        jasmineEnv = jasmine.getEnv();

    var specsList = loadSpecs(folder, fileMatcher);

    if (junitReport && junitReport.report) {
        if (!path.existsSync(junitReport.savePath)) {
            util.puts('creating junit xml report save path: ' + junitReport.savePath);
            fs.mkdirSync(junitReport.savePath, "0755");
        }
        jasmineEnv.addReporter(new jasmine['JUnitXmlReporter'](junitReport.savePath,
            junitReport.consolidate,
            junitReport.useDotNotation));
    }

    if (isVerbose) {
        jasmineEnv.addReporter(new jasmineNode.TerminalVerboseReporter({
            print: util.print,
            color: showColors,
            onComplete: done
        }));
    } else {
        jasmineEnv.addReporter(new jasmineNode.TerminalReporter({
            print: util.print,
            color: showColors,
            onComplete: done
        }));
    }

    for (var i = 0, len = specsList.length; i < len; ++i) {
        var filename = specsList[i];
        require(filename.replace(/\.\w+$/, ""));
    }

    setTimeout(function () {
        // async use
        jasmineEnv.execute();
    },200);

}

redpajama_set_name: RedPajamaGithub


text: Nya Spinner-ikoner i region sidebar


text:
package org.elasticsearch.rest.action.cat;

import org.elasticsearch.action.admin.cluster.node.info.NodeInfo;
import org.elasticsearch.action.admin.cluster.node.info.NodesInfoRequest;
import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse;
import org.elasticsearch.action.admin.cluster.node.stats.NodeStats;
import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsRequest;
import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse;
import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.Table;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.RestActionListener;
import org.elasticsearch.rest.action.RestResponseListener;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.threadpool.ThreadPoolStats;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import static org.elasticsearch.rest.RestRequest.Method.GET;

public class RestThreadPoolAction extends AbstractCatAction {

    public RestThreadPoolAction(RestController controller) {
        controller.registerHandler(GET, "/_cat/thread_pool", this);
        controller.registerHandler(GET, "/_cat/thread_pool/{thread_pool_patterns}", this);
    }

    @Override
    public String getName() {
        return "cat_threadpool_action";
    }

    @Override
    protected void documentation(StringBuilder sb) {
        sb.append("/_cat/thread_pool\n");
        sb.append("/_cat/thread_pool/{thread_pools}\n");
    }

    @Override
    public RestChannelConsumer doCatRequest(final RestRequest request, final NodeClient client) {
        final ClusterStateRequest clusterStateRequest = new ClusterStateRequest();
        clusterStateRequest.clear().nodes(true);
        clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));
        clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout()));

        return channel -> client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) {
            @Override
            public void processResponse(final ClusterStateResponse clusterStateResponse) {
                NodesInfoRequest nodesInfoRequest = new NodesInfoRequest();
                nodesInfoRequest.clear().process(true).threadPool(true);
                client.admin().cluster().nodesInfo(nodesInfoRequest, new RestActionListener<NodesInfoResponse>(channel) {
                    @Override
                    public void processResponse(final NodesInfoResponse nodesInfoResponse) {
                        NodesStatsRequest nodesStatsRequest = new NodesStatsRequest();
                        nodesStatsRequest.clear().threadPool(true);
                        client.admin().cluster().nodesStats(nodesStatsRequest, new RestResponseListener<NodesStatsResponse>(channel) {
                            @Override
                            public RestResponse buildResponse(NodesStatsResponse nodesStatsResponse) throws Exception {
                                return RestTable.buildResponse(
                                    buildTable(request, clusterStateResponse, nodesInfoResponse, nodesStatsResponse), channel);
                            }
                        });
                    }
                });
            }
        });
    }

    private static final Set<String> RESPONSE_PARAMS;

    static {
        final Set<String> responseParams = new HashSet<>(AbstractCatAction.RESPONSE_PARAMS);
        responseParams.add("thread_pool_patterns");
        RESPONSE_PARAMS = Collections.unmodifiableSet(responseParams);
    }

    @Override
    protected Set<String> responseParams() {
        return RESPONSE_PARAMS;
    }

    @Override
    protected Table getTableWithHeader(final RestRequest request) {
        final Table table = new Table();
        table.startHeaders();
        table.addCell("node_name", "default:true;alias:nn;desc:node name");
        table.addCell("node_id", "default:false;alias:id;desc:persistent node id");
        table.addCell("ephemeral_node_id", "default:false;alias:eid;desc:ephemeral node id");
        table.addCell("pid", "default:false;alias:p;desc:process id");
        table.addCell("host", "default:false;alias:h;desc:host name");
        table.addCell("ip", "default:false;alias:i;desc:ip address");
        table.addCell("port", "default:false;alias:po;desc:bound transport port");
        table.addCell("name", "default:true;alias:n;desc:thread pool name");
        table.addCell("type", "alias:t;default:false;desc:thread pool type");
        table.addCell("active", "alias:a;default:true;text-align:right;desc:number of active threads");
        table.addCell("pool_size", "alias:psz;default:false;text-align:right;desc:number of threads");
        table.addCell("queue", "alias:q;default:true;text-align:right;desc:number of tasks currently in queue");
        table.addCell("queue_size", "alias:qs;default:false;text-align:right;desc:maximum number of tasks permitted in queue");
        table.addCell("rejected", "alias:r;default:true;text-align:right;desc:number of rejected tasks");
        table.addCell("largest", "alias:l;default:false;text-align:right;desc:highest number of seen active threads");
        table.addCell("completed", "alias:c;default:false;text-align:right;desc:number of completed tasks");
        table.addCell("core", "alias:cr;default:false;text-align:right;desc:core number of threads in a scaling thread pool");
        table.addCell("max", "alias:mx;default:false;text-align:right;desc:maximum number of threads in a scaling thread pool");
        table.addCell("size", "alias:sz;default:false;text-align:right;desc:number of threads in a fixed thread pool");
        table.addCell("keep_alive", "alias:ka;default:false;text-align:right;desc:thread keep alive time");
        table.endHeaders();
        return table;
    }

    private Table buildTable(RestRequest req, ClusterStateResponse state, NodesInfoResponse nodesInfo, NodesStatsResponse nodesStats) {
        final String[] threadPools = req.paramAsStringArray("thread_pool_patterns", new String[] { "*" });
        final DiscoveryNodes nodes = state.getState().nodes();
        final Table table = getTableWithHeader(req);

        // collect all thread pool names that we see across the nodes
        final Set<String> candidates = new HashSet<>();
        for (final NodeStats nodeStats : nodesStats.getNodes()) {
            for (final ThreadPoolStats.Stats threadPoolStats : nodeStats.getThreadPool()) {
                candidates.add(threadPoolStats.getName());
            }
        }

        // collect all thread pool names that match the specified thread pool patterns
        final Set<String> included = new HashSet<>();
        for (final String candidate : candidates) {
            if (Regex.simpleMatch(threadPools, candidate)) {
                included.add(candidate);
            }
        }

        for (final DiscoveryNode node : nodes) {
            final NodeInfo info = nodesInfo.getNodesMap().get(node.getId());
            final NodeStats stats = nodesStats.getNodesMap().get(node.getId());

            final Map<String, ThreadPoolStats.Stats> poolThreadStats;
            final Map<String, ThreadPool.Info> poolThreadInfo;

            if (stats == null) {
                poolThreadStats = Collections.emptyMap();
                poolThreadInfo = Collections.emptyMap();
            } else {
                // we use a sorted map to ensure that thread pools are sorted by name
                poolThreadStats = new TreeMap<>();
                poolThreadInfo = new HashMap<>();

                ThreadPoolStats threadPoolStats = stats.getThreadPool();
                for (ThreadPoolStats.Stats threadPoolStat : threadPoolStats) {
                    poolThreadStats.put(threadPoolStat.getName(), threadPoolStat);
                }
                if (info != null) {
                    for (ThreadPool.Info threadPoolInfo : info.getThreadPool()) {
                        poolThreadInfo.put(threadPoolInfo.getName(), threadPoolInfo);
                    }
                }
            }
            for (Map.Entry<String, ThreadPoolStats.Stats> entry : poolThreadStats.entrySet()) {

                if (!included.contains(entry.getKey())) continue;

                table.startRow();

                table.addCell(node.getName());
                table.addCell(node.getId());
                table.addCell(node.getEphemeralId());
                table.addCell(info == null ? null : info.getProcess().getId());
                table.addCell(node.getHostName());
                table.addCell(node.getHostAddress());
                table.addCell(node.getAddress().address().getPort());
                final ThreadPoolStats.Stats poolStats = entry.getValue();
                final ThreadPool.Info poolInfo = poolThreadInfo.get(entry.getKey());

                Long maxQueueSize = null;
                String keepAlive = null;
                Integer core = null;
                Integer max = null;
                Integer size = null;

                if (poolInfo != null) {
                    if (poolInfo.getQueueSize() != null) {
                        maxQueueSize = poolInfo.getQueueSize().singles();
                    }
                    if (poolInfo.getKeepAlive() != null) {
                        keepAlive = poolInfo.getKeepAlive().toString();
                    }

                    if (poolInfo.getThreadPoolType() == ThreadPool.ThreadPoolType.SCALING) {
                        assert poolInfo.getMin() >= 0;
                        core = poolInfo.getMin();
                        assert poolInfo.getMax() > 0;
                        max = poolInfo.getMax();
                    } else {
                        assert poolInfo.getMin() == poolInfo.getMax() && poolInfo.getMax() > 0;
                        size = poolInfo.getMax();
                    }
                }

                table.addCell(entry.getKey());
                table.addCell(poolInfo == null  ? null : poolInfo.getThreadPoolType().getType());
                table.addCell(poolStats == null ? null : poolStats.getActive());
                table.addCell(poolStats == null ? null : poolStats.getThreads());
                table.addCell(poolStats == null ? null : poolStats.getQueue());
                table.addCell(maxQueueSize == null ? -1 : maxQueueSize);
                table.addCell(poolStats == null ? null : poolStats.getRejected());
                table.addCell(poolStats == null ? null : poolStats.getLargest());
                table.addCell(poolStats == null ? null : poolStats.getCompleted());
                table.addCell(core);
                table.addCell(max);
                table.addCell(size);
                table.addCell(keepAlive);

                table.endRow();
            }
        }

        return table;
    }
}


text:
namespace llvm {

class Triple;

namespace opt {

class ArgList;

} // namespace opt

namespace vfs {

class FileSystem;

} // namespace vfs

} // namespace llvm

namespace clang {

class DiagnosticsEngine;
class HeaderSearchOptions;
class PreprocessorOptions;
class TargetOptions;

/// Fill out Opts based on the options given in Args.
///
/// Args must have been created from the OptTable returned by
/// createCC1OptTable().
///
/// When errors are encountered, return false and, if Diags is non-null,
/// report the error(s).
bool ParseDiagnosticArgs(DiagnosticOptions &Opts, llvm::opt::ArgList &Args,
                         DiagnosticsEngine *Diags = nullptr,
                         bool DefaultDiagColor = true);

class CompilerInvocationBase {
public:
  /// Options controlling the language variant.
  std::shared_ptr<LangOptions> LangOpts;

  /// Options controlling the target.
  std::shared_ptr<TargetOptions> TargetOpts;

  /// Options controlling the diagnostic engine.
  IntrusiveRefCntPtr<DiagnosticOptions> DiagnosticOpts;

  /// Options controlling the \#include directive.
  std::shared_ptr<HeaderSearchOptions> HeaderSearchOpts;

  /// Options controlling the preprocessor (aside from \#include handling).
  std::shared_ptr<PreprocessorOptions> PreprocessorOpts;

  CompilerInvocationBase();
  CompilerInvocationBase(const CompilerInvocationBase &X);
  CompilerInvocationBase &operator=(const CompilerInvocationBase &) = delete;
  ~CompilerInvocationBase();

  LangOptions *getLangOpts() { return LangOpts.get(); }
  const LangOptions *getLangOpts() const { return LangOpts.get(); }

  TargetOptions &getTargetOpts() { return *TargetOpts.get(); }
  const TargetOptions &getTargetOpts() const { return *TargetOpts.get(); }

  DiagnosticOptions &getDiagnosticOpts() const { return *DiagnosticOpts; }

  HeaderSearchOptions &getHeaderSearchOpts() { return *HeaderSearchOpts; }

  const HeaderSearchOptions &getHeaderSearchOpts() const {
    return *HeaderSearchOpts;
  }

  std::shared_ptr<HeaderSearchOptions> getHeaderSearchOptsPtr() const {
    return HeaderSearchOpts;
  }

  std::shared_ptr<PreprocessorOptions> getPreprocessorOptsPtr() {
    return PreprocessorOpts;
  }

  PreprocessorOptions &getPreprocessorOpts() { return *PreprocessorOpts; }

  const PreprocessorOptions &getPreprocessorOpts() const {
    return *PreprocessorOpts;
  }
};

/// Helper class for holding the data necessary to invoke the compiler.
///
/// This class is designed to represent an abstract "invocation" of the
/// compiler, including data such as the include paths, the code generation
/// options, the warning flags, and so on.
class CompilerInvocation : public CompilerInvocationBase {
  /// Options controlling the static analyzer.
  AnalyzerOptionsRef AnalyzerOpts;

  MigratorOptions MigratorOpts;

  /// Options controlling IRgen and the backend.
  CodeGenOptions CodeGenOpts;

  /// Options controlling dependency output.
  DependencyOutputOptions DependencyOutputOpts;

  /// Options controlling file system operations.
  FileSystemOptions FileSystemOpts;

  /// Options controlling the frontend itself.
  FrontendOptions FrontendOpts;

  /// Options controlling preprocessed output.
  PreprocessorOutputOptions PreprocessorOutputOpts;

public:
  CompilerInvocation() : AnalyzerOpts(new AnalyzerOptions()) {}

  /// @name Utility Methods
  /// @{

  /// Create a compiler invocation from a list of input options.
  /// \returns true on success.
  ///
  /// \returns false if an error was encountered while parsing the arguments
  /// and attempts to recover and continue parsing the rest of the arguments.
  /// The recovery is best-effort and only guarantees that \p Res will end up in
  /// one of the vaild-to-access (albeit arbitrary) states.
  ///
  /// \param [out] Res - The resulting invocation.
  static bool CreateFromArgs(CompilerInvocation &Res,
                             ArrayRef<const char *> CommandLineArgs,
                             DiagnosticsEngine &Diags);

  /// Get the directory where the compiler headers
  /// reside, relative to the compiler binary (found by the passed in
  /// arguments).
  ///
  /// \param Argv0 - The program path (from argv[0]), for finding the builtin
  /// compiler path.
  /// \param MainAddr - The address of main (or some other function in the main
  /// executable), for finding the builtin compiler path.
  static std::string GetResourcesPath(const char *Argv0, void *MainAddr);

  /// Set language defaults for the given input language and
  /// language standard in the given LangOptions object.
  ///
  /// \param Opts - The LangOptions object to set up.
  /// \param IK - The input language.
  /// \param T - The target triple.
  /// \param PPOpts - The PreprocessorOptions affected.
  /// \param LangStd - The input language standard.
  static void setLangDefaults(LangOptions &Opts, InputKind IK,
                   const llvm::Triple &T, PreprocessorOptions &PPOpts,
                   LangStandard::Kind LangStd = LangStandard::lang_unspecified);

  /// Retrieve a module hash string that is suitable for uniquely
  /// identifying the conditions under which the module was built.
  std::string getModuleHash() const;

  /// @}
  /// @name Option Subgroups
  /// @{

  AnalyzerOptionsRef getAnalyzerOpts() const { return AnalyzerOpts; }

  MigratorOptions &getMigratorOpts() { return MigratorOpts; }
  const MigratorOptions &getMigratorOpts() const { return MigratorOpts; }

  CodeGenOptions &getCodeGenOpts() { return CodeGenOpts; }
  const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }

  DependencyOutputOptions &getDependencyOutputOpts() {
    return DependencyOutputOpts;
  }

  const DependencyOutputOptions &getDependencyOutputOpts() const {
    return DependencyOutputOpts;
  }

  FileSystemOptions &getFileSystemOpts() { return FileSystemOpts; }

  const FileSystemOptions &getFileSystemOpts() const {
    return FileSystemOpts;
  }

  FrontendOptions &getFrontendOpts() { return FrontendOpts; }
  const FrontendOptions &getFrontendOpts() const { return FrontendOpts; }

  PreprocessorOutputOptions &getPreprocessorOutputOpts() {
    return PreprocessorOutputOpts;
  }

  const PreprocessorOutputOptions &getPreprocessorOutputOpts() const {
    return PreprocessorOutputOpts;
  }

  /// @}
};

IntrusiveRefCntPtr<llvm::vfs::FileSystem>
createVFSFromCompilerInvocation(const CompilerInvocation &CI,
                                DiagnosticsEngine &Diags);

IntrusiveRefCntPtr<llvm::vfs::FileSystem> createVFSFromCompilerInvocation(
    const CompilerInvocation &CI, DiagnosticsEngine &Diags,
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS);

} // namespace clang

#endif // LLVM_CLANG_FRONTEND_COMPILERINVOCATION_H


text:
package org.apache.skywalking.apm.testcase.xxljob.job;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.skywalking.apm.testcase.xxljob.Utils;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class MethodJob {

    @XxlJob("MethodJobHandler")
    public ReturnT<String> work(String param) throws IOException {

        log.info("MethodJobHandler execute. param: {}", param);

        Request request = new Request.Builder().url("http://localhost:8080/xxl-job-2.x-scenario/case/methodJob").build();
        Response response = Utils.OK_CLIENT.newCall(request).execute();
        response.body().close();

        return ReturnT.SUCCESS;
    }
}


text:
import { Component } from '@angular/core';
import { WorkService} from './work-service';
import { Location }                 from '@angular/common';
import { ValidateService }  from '../validate.service';
import { Work }  from './work';

@Component({
  moduleId:module.id,
  selector: 'basicNew',
  templateUrl: 'basicNew.component.html'
})

export class BasicNewComponent {
  constructor(
    private workService:WorkService,
    private location: Location,
    private validateService:ValidateService
  ){}
//提交創建前內部驗證

  passNum:number;
  new(form:any,newWork:Work):void{
    this.passNum=0;
    let that = this;
    for(let i=0;i<form.children.length-1;i++){
      let item:any = form.children[i].children[1].children[0];
      this.check(item,form).then((function(item) {
        //計算通過項目
        that.passNum = item.Error?that.passNum-1:that.passNum+1;
        that.passNum = Math.max(that.passNum,0);
        //判定通過項目是否都通過
        if(that.passNum === form.children.length-1){
          that.workService.create(newWork).then(() => that.location.back());
        }
      }));
    }
  }
//單獨輸入塊驗證
  check(item:any,form:any): Promise<any>{
      let _this = this
      let other:any = item.dataset["vEqualto"]?form.children[+item.dataset["vEqualto"]].children[1].children[0]:"";
      return this.validateService.check(item,other).then(function(prams) {
        prams.item.Error = prams.mes;
        prams.item.pass=!prams.mes;
        return Promise.resolve(prams.item);
      });
  }

}


text:
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingFile"
			      type="log4net.Appender.RollingFileAppender">
    <file value="..\..\..\..\..\logs\sample.webservicebridge.InternalInventoryService.log" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <datePattern value="yyyyMMdd" />
    <!-- files rolled at day -->
    <maxSizeRollBackups value="10" />
    <!-- only 10 days kept -->
    <maximumFileSize value="1MB" />
    <!-- file size capped at 1MB -->

    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5p %d{hh:mm:ss} %message%newline" />
    </layout>
  </appender>

  <!-- Custom appender for MassTransit's Messages -->
  <appender name="MT.Messages"
			      type="log4net.Appender.FileAppender">
    <file value="masstransit.messages.log" />
    <appendToFile value="false" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5p %d{hh:mm:ss} %message%newline" />
    </layout>
  </appender>

  <!-- Custom appender for MassTransit's Messages -->
  <appender name="NH.SQL"
			      type="log4net.Appender.FileAppender">
    <file value="nhibernate.sql.log" />
    <appendToFile value="false" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%d{hh:mm:ss} %message%newline" />
    </layout>
  </appender>

  <!-- Set root logger level to DEBUG and its only appender to Console -->
  <root>
    <level value="INFO" />
    <appender-ref ref="RollingFile" />
  </root>

  <!-- Seeing service messages would be good here -->
  <logger name="InternalInventoryService">
    <level value="INFO"/>
  </logger>

  <!-- Standard MassTransit Logging Settings -->
  <logger name="MassTransit">
    <level value="INFO" />
  </logger>

  <logger name="MassTransit.Messages">
    <level value="OFF" />
    <appender-ref ref="MT.Messages" />
  </logger>
</log4net>


text:
import React from 'react'
import {SearchArtistCollection, SearchCollection} from '../models/models'

const HomeView = React.createClass({
	render: function(){
		return (

					<SearchBar/>

			)
	}
})

const Header = React.createClass({
		handleHeaderClick: function(){
			document.getElementById('artistSuggestions').style.visibility = 'hidden'
		},
		render: function(){
			return (

						Spotify App

				)
		}
	})

const SearchBar = React.createClass({
	getInitialState: function(){
	return {
			suggestionState: []
		}

	},

	handleKeyUp: function(event){
		this.refs.suggestionsDiv.style.visibility = 'visible'
		if (event.keyCode !== 13){
			var suggestions = new SearchCollection()
			suggestions.fetch({
				dataType: 'json',
				data: {
					type: 'artist',
					q: event.target.value,
					limit: 10
				}
			}).then(()=>{
				this.setState({
					suggestionState: suggestions.models[0].attributes.items
				})
			})
		}
		else if (event.keyCode === 13){
			let artistName = event.target.value.replace(/ /g,'%20')
			location.hash = 'artist/' + artistName
			this.refs.suggestionsDiv.style.visibility = 'hidden'
			event.target.value = artistName
		}
	},

	handleClick: function(name){
			return (event)=>{
				location.hash = 'artist/' + name
				this.refs.searchInput.value = name
				this.refs.suggestionsDiv.style.visibility = 'hidden'
			}
	},

	handleInputClick: function(event){
		event.target.value = ''
	},

	handleSearchBarClick:function(){
		document.getElementById('artistSuggestions').style.visibility = 'hidden'
	},

	getSuggestions: function(){
		let artistJSXArr = []
		this.state.suggestionState.forEach((artist)=>{
			artistJSXArr.push(
{artist.name}
)
		})
		return artistJSXArr
	},

	render: function(){
		return (

							<input placeholder='Search Artists' ref='searchInput' list='artistSuggestions' onKeyUp={this.handleKeyUp} onClick={this.handleInputClick} type='text'/>

									{this.getSuggestions()}

			)
		}
	})

export default HomeView


text:
package sample

import (
	"fmt"
	"math"
	"testing"
)

func TestPowerOf2NilSampler(t *testing.T) {
	var sampler Sampler
	var err error

	sampler, err = NewPowerOf2(0)
	if err == nil {
		t.Fatal("NewPowerOf2 must error if rate = 0", err)
	}

	sampler, err = NewPowerOf2(1023)
	if err == nil {
		t.Fatal("NewPowerOf2 must error if rate not power of 2 (e.g. 1023)", err)
	}

	_ = sampler
}

func TestPowerOf2Rate1(t *testing.T) {
	var sampler Sampler
	var err error

	// Sample 1
	sampler, err = NewPowerOf2(1)
	if err != nil {
		t.Fatal("NewPowerOf2 must not error", err)
	}

	// must return true for all cases
	if sampler.SampleFrom(0) != true {
		t.Error("sampling 0 with rate 1 did not return true")
	}
	if sampler.SampleFrom(math.MaxUint64) != true {
		t.Error("sampling MaxUint64 with rate 1 did not return true")
	}
	for i := 1; i < 20; i++ {
		if sampler.Sample() != true {
			t.Error("sampling with rate 1 did not return true")
		}
	}
}

func TestPowerOf2SampleFrom(t *testing.T) {
	var sampler Sampler
	var err error

	// Sample 1024 with from
	sampler, err = NewPowerOf2(1024)
	if err != nil {
		t.Fatal("NewPowerOf2 must not error", err)
	}
	// true
	if sampler.SampleFrom(0) != true {
		t.Error("sampling 0 with rate 1024 did not return true")
	}
	if sampler.SampleFrom(1024) != true {
		t.Error("sampling 0 with rate 1024 did not return true")
	}
	// false
	if sampler.SampleFrom(1023) != false {
		t.Error("sampling 1023 with rate 1024 did not return false")
	}
	if sampler.SampleFrom(1025) != false {
		t.Error("sampling 1024 with rate 1024 did not return false")
	}
	if sampler.SampleFrom(math.MaxUint64) != false {
		t.Error("sampling MaxUint64 with rate 1024 did not return false")
	}
}

func TestPowerOf2SeedSample(t *testing.T) {
	var sampler Sampler
	var err error

	// Sample with seed, false
	sampler, err = NewPowerOf2Seeded(1024, 0)
	if err != nil {
		t.Fatal("NewPowerOf2 must not error", err)
	}
	if sampler.Sample() != false {
		t.Error("sampling with seed 0 and rate 1024 did not return false")
	}

	// Sample with seed, true
	sampler, err = NewPowerOf2Seeded(1024, 643)
	if err != nil {
		t.Fatal("NewPowerOf2 must not error", err)
	}

	if sampler.Sample() != true {
		t.Error("sampling with seed 643 and rate 1024 did not return true")
	}
}

func TestPowerOf2String(t *testing.T) {
	var sampler Sampler

	sampler = &powerOf2{sampleState: sampleState{rate: 1024, seed: 0, sampleCount: 1000, trueCount: 100}}

	if sampler.String() != "&{sampleState:{rate:1024 seed:0 sampleCount:1000 trueCount:100 rnd:<nil>}}" {
		t.Error("Expected: &{sampleState:{rate:1024 seed:0 sampleCount:1000 trueCount:100 rnd:<nil>}}, Got:", sampler.String())
	}
}

func ExampleNewPowerOf2Seeded() {
	s, err := NewPowerOf2Seeded(16, 0)
	if err != nil {
		fmt.Println("Unable to initialize sampler", err)
	}
	for i := 0; i < 100; i++ {
		if s.Sample() {
			fmt.Println(i, "got sampled by PowerOf2 sampler")
		}
	}
	fmt.Println(Stats(s))
	// Output:
	// 26 got sampled by PowerOf2 sampler
	// 45 got sampled by PowerOf2 sampler
	// Rate: 16, SampleCount: 100, TrueCount: 2, Deviation: -212.5000%

}


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />

        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <link rel="stylesheet" type="text/css" href="css/animationbild.css" />
        <title>Formelsammlung Mathematik</title>

		Formelsammlung Geometrie

		Flächeninhalt Dreieck

				\(F = \frac{1}{2} \cdot \ g \cdot h\)

				Flächeninhalt des Dreiecks:

				\(F = \frac{1}{2} \cdot \ 5cm \cdot 3\)

				\(F = 7,5cm^2\)

			Klicke auf das Bild um die Animation nochmal zu starten


text:
/* eslint-disable no-new-wrappers */

'use strict';

var Number = require( '@stdlib/number/ctor' );
var isNegativeNumberArray = require( './../lib' );

var bool = isNegativeNumberArray( [ -5.0, -0.2, -3.9 ] );
console.log( bool );
// => true

bool = isNegativeNumberArray( [ -1, -2, -3 ] );
console.log( bool );
// => true

bool = isNegativeNumberArray( [ -1, new Number( -6 ), -3 ] );
console.log( bool );
// => true

bool = isNegativeNumberArray( [ 0, -2, -4 ] );
console.log( bool );
// => false

bool = isNegativeNumberArray( [ -1, 'abc', -3 ] );
console.log( bool );
// => false

bool = isNegativeNumberArray( -78.0 );
console.log( bool );
// => false

bool = isNegativeNumberArray( [] );
console.log( bool );
// => false


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

import {browserProxy} from './browser_proxy/browser_proxy.js';
import {assertInstanceof} from './chrome_util.js';
import * as util from './util.js';

/**
 * Updates the toast message.
 * @param {string} message Message to be updated.
 * @param {boolean} spoken Whether the toast is spoken only.
 */
function update(message, spoken) {
  // TTS speaks changes of on-screen aria-live elements. Force content changes
  // and clear content once inactive to avoid stale content being read out.
  const element =
      assertInstanceof(document.querySelector('#toast'), HTMLElement);
  util.animateCancel(element);  // Cancel the active toast if any.
  element.textContent = '';     // Force to reiterate repeated messages.
  element.textContent = browserProxy.getI18nMessage(message) || message;

  element.classList.toggle('spoken', spoken);
  util.animateOnce(element, () => element.textContent = '');
}

/**
 * Shows a toast message.
 * @param {string} message Message to be shown.
 */
export function show(message) {
  update(message, false);
}

/**
 * Speaks a toast message.
 * @param {string} message Message to be spoken.
 */
export function speak(message) {
  update(message, true);
}


text:
package com.cesarvaliente.permissionssample.presentation.view.contactlist.recyclerview;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by Cesar on 10/09/15.
 */
public class ItemClickListener implements RecyclerView.OnItemTouchListener {

    private OnItemClickListener listener;
    private GestureDetector gestureDetector;

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    public ItemClickListener(Context context, OnItemClickListener listener) {
        this.listener = listener;
        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        View childView = rv.findChildViewUnder(e.getX(), e.getY());
        if (childView != null && listener != null && gestureDetector.onTouchEvent(e)) {
            listener.onItemClick(childView, rv.getChildAdapterPosition(childView));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {

    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}


text:
          <a href="<?php echo site_url("admin"); ?>">
            <?php echo ucfirst($this->uri->segment(1));?>

          /

          <?php echo ucfirst($this->uri->segment(2));?>

          <?php echo ucfirst($this->uri->segment(2));?>
          <a  href="<?php echo site_url("admin").'/'.$this->uri->segment(2); ?>/add" class="btn btn-success">Add a new

            <?php

            $attributes = array('class' => 'form-inline reset-margin', 'id' => 'myform');
            $options_manufacture = array(0 => "all");
            foreach ($manufactures as $row)
            {
              $options_manufacture[$row['id']] = $row['name'];
            }
            //save the columns names in a array that we will use as filter
            $options_products = array();
            foreach ($products as $array) {
                foreach ($array as $key => $value) {
                    $options_products[$key] = $key;
                }
                break;
            }

            echo form_open('admin/products', $attributes);
                echo form_label('Search:', 'search_string');
                echo form_input('search_string', $search_string_selected, 'style="width: 170px;
                height: 26px;"');

                echo form_label('Filter by manufacturer:', 'manufacture_id');
                echo form_dropdown('manufacture_id', $options_manufacture, $manufacture_selected, 'class="span2"');

                echo form_label('Order by:', 'order');
                echo form_dropdown('order', $options_products, $order, 'class="span2"');

                $options_order_type = array('Asc' => 'Asc', 'Desc' => 'Desc');
                echo form_dropdown('order_type', $options_order_type, $order_type_selected, 'class="span1"');

                $data_submit = array('name' => 'mysubmit', 'class' => 'btn btn-primary', 'value' => 'Go');
                echo form_submit($data_submit);

            echo form_close();
            ?>

                #
                Description
                Stock
                Cost Price
                Sell Price
                Manufacture
                Actions

              <?php
              foreach($products as $row)
              {
                echo '
';
                echo ''.$row['id'].'	';
                echo ''.$row['description'].'	';
                echo ''.$row['stock'].'	';
                echo ''.$row['cost_price'].'	';
                echo ''.$row['sell_price'].'	';
                echo ''.$row['manufacture_name'].'	';
                echo '
                  view & edit
                  delete
                	';
                echo '
';
              }
              ?>

          <?php echo '
'.$this->pagination->create_links().'
'; ?>


text:
package com.founder.fix.fixflow.core.impl.cmd;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import com.founder.fix.fixflow.core.exception.FixFlowBizException;
import com.founder.fix.fixflow.core.impl.bpmn.behavior.ProcessDefinitionBehavior;
import com.founder.fix.fixflow.core.impl.interceptor.Command;
import com.founder.fix.fixflow.core.impl.interceptor.CommandContext;
import com.founder.fix.fixflow.core.impl.persistence.definition.ResourceEntity;

public class GetFlowGraphicsImgStreamCmd  implements Command<InputStream> {

	protected String processDefinitionId;
	protected String processDefinitionKey;

	public GetFlowGraphicsImgStreamCmd(String processDefinitionId,String processDefinitionKey){
		this.processDefinitionId=processDefinitionId;
		this.processDefinitionKey=processDefinitionKey;
	}

	public InputStream execute(CommandContext commandContext) {
		// TODO Auto-generated method stub
		ProcessDefinitionBehavior processDefinitionBehavior=null;

		if(this.processDefinitionId!=null&&!this.processDefinitionId.equals("")){

			processDefinitionBehavior=commandContext.getProcessDefinitionManager().findLatestProcessDefinitionById(this.processDefinitionId);

		}else{
			if(this.processDefinitionKey!=null&&!this.processDefinitionKey.equals("")){
				processDefinitionBehavior=commandContext.getProcessDefinitionManager().findLatestProcessDefinitionByKey(processDefinitionKey);
			}
			else{
				throw new FixFlowBizException("查询流程图的processDefinitionId、processDefinitionKey不能都为空!");
			}
		}

		String deploymentId=processDefinitionBehavior.getDeploymentId();
		String diagramResourceName=processDefinitionBehavior.getDiagramResourceName();
		ResourceEntity resourceEntity=commandContext.getResourceManager().findResourceByDeploymentIdAndResourceName(deploymentId, diagramResourceName);
		InputStream inputStream = new ByteArrayInputStream(resourceEntity.getBytes());
		return inputStream;

	}

}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


text:
import collections
import inspect
import warnings

class FunctionSet(collections.MutableSet):
    """ A mutable set of functions.

    """

    def __init__(self, functions=None):
        """ Initialize the function container class.

        Parameters
        ----------
        recorder : object
            A subclass of :class:`~pikos.recorders.AbstractRecorder` or a class
            that implements the same interface to handle the values to be
            logged.

        functions : list
            A list of function or method objects inside which recording will
            take place.

        """
        self._code_map = {}
        self.functions = []
        for function in functions:
            self.add(function)

    def __contains__(self, item):
        """ Check it the function set contains the provided code object or
        function.

        """
        if inspect.iscode(item):
            return item in self._code_map
        else:
            return item in self.functions

    def __iter__(self):
        """ Iterate over the function objects.

        """
        return iter(self.functions)

    def __len__(self):
        return len(self.functions)

    def add(self, function):
        """ Add the Python function to the list of monitored functions.

        Parameters
        ----------
        function : object
            A function or method object to add to the list of monitored
            functions. If the function is already included then the method
            exits silently.

        Notes
        -----
        Code adapted from the line_profiler package.

        """
        try:
            code = function.func_code
        except AttributeError:
            if inspect.isbuiltin(function):
                msg = "Built-in functions are not supported for: {0}"
            else:
                msg = "Could not extract a code object for: {0}"
            warnings.warn(msg.format(function))
        else:
            if code not in self._code_map:
                self._code_map[code] = {}
                self.functions.append(function)

    def discard(self, function):
        """ Remove the Python function form the list of monitored functions.

        Parameters
        ----------
        function : object
            The function or method object to remove from the list of monitored
            functions. If the function does not exist in the list then the
            method exists silently.

        """
        try:
            code = function.func_code
        except AttributeError:
            msg = "Could not extract a code object for the object {0}"
            warnings.warn(msg.format(function))
        else:
            if code in self._code_map:
                self._code_map.pop(code)
                self.functions.remove(function)


text:
import React, { Component } from 'react';
import {Route,Link } from 'react-router-dom';
import './App.css';
import Library from './library'
import * as BooksAPI from './BooksAPI'
import Search from './search'
class App extends Component {
  state={
    books:[]
  }

  componentDidMount() {
    BooksAPI.getAll().then((data) => this.setState({
      books:data
    }))
  }
  moveBooktoAnotherShelf=(book,shelf)=>{
    BooksAPI.update(book,shelf).then(
      ()=>{
        console.log("books updated")
        BooksAPI.getAll().then(
          (data) => this.setState(
            {
              books:data
            })
          )
        }
      )
    }
    render() {
      return (

          <Route exact path="/" render={()=>(

              <Library onBookChange={this.moveBooktoAnotherShelf}  books={this.state.books}/>
              <Link to="/search" className="open-search">

Add a book

            </Link>

        )}/>
        <Route path="/search" render={()=><Search onBookChange={this.moveBooktoAnotherShelf}/>}/>

    );
  }
}
export default App;


text:
package com.tle.mypages.web.event;

import com.tle.beans.item.ItemPack;
import com.tle.web.sections.SectionId;
import com.tle.web.sections.SectionInfo;

/*
 * @author aholland
 */
public class SaveItemEvent extends AbstractMyPagesEvent<SaveItemEventListener> {
  private final ItemPack itemPack;
  private boolean commit;

  public SaveItemEvent(ItemPack itemPack, String sessionId) {
    super(sessionId);
    this.itemPack = itemPack;
    this.commit = true;
  }

  @Override
  public void fire(SectionId sectionId, SectionInfo info, SaveItemEventListener listener)
      throws Exception {
    listener.doSaveItemEvent(info, this);
  }

  @Override
  public Class<SaveItemEventListener> getListenerClass() {
    return SaveItemEventListener.class;
  }

  public boolean isCommit() {
    return commit;
  }

  public void setCommit(boolean commit) {
    this.commit = commit;
  }

  public ItemPack getItemPack() {
    return itemPack;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>dropwizard-monitoring-parent</artifactId>
        <groupId>org.jgille.mumon</groupId>
        <version>0.1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>dropwizard-monitoring-api</artifactId>

    <dependencies>

        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-validation</artifactId>
            <version>${dropwizard.version}</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

    </dependencies>

</project>


text:
This project defines casting from upper case to lower case and vice versa for
the Dutch language. This is of course extremely trivial. However, the list
provided here can be used to do casting or to test casting software.

The casting is defined in the tab-seprated file [case-casting.tsv](case-casting.tsv?raw=true)
of which the first line holds the header. For the lines following, the first column holds lower case characters and the second column upper case
characters. This file can be used in a text editor, spreadsheet application or
custom software. A more readable  rendered version can be found [here](case-casting.tsv).

For the Dutch language, there are no requirements for casting of characters
which are not in the list provided here. Casting between such characters can be
done by the default behaviour of the used programming language or software
library. This is also trivial for casting between the Polish Ł and ł but can
prove a problem for casting between the Greek Σ and σ or ς (only used at the end
of a word) when there is no context provided. The default is to cast Σ to σ.


text:
package uristqwerty.CraftGuide.api;

import java.util.ArrayList;
import java.util.List;

import org.lwjgl.opengl.GL11;

import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;

public class PseudoFluidFilter implements ItemFilter
{
	private static NamedTexture containerTexture = null;
	public PseudoFluidStack liquid;
	private String liquidName;
	private List<String> tooltip = new ArrayList<>();

	public PseudoFluidFilter(PseudoFluidStack liquid)
	{
		if(containerTexture == null)
		{
			containerTexture = Util.instance.getTexture("liquidFilterContainer");
		}

		setLiquid(liquid);
	}

	public void setLiquid(PseudoFluidStack liquid)
	{
		String name = liquid.getLocalizedName();
		this.liquid = liquid;
		liquidName = name.toLowerCase();
		tooltip.clear();
		tooltip.add(name);
	}

	@Override
	public boolean matches(Object item)
	{
		if(item instanceof PseudoFluidStack)
		{
			return liquid.isFluidEqual((PseudoFluidStack)item);
		}
		else if(item instanceof String)
		{
			return liquidName.contains(((String)item).toLowerCase());
		}
		else if(item instanceof List)
		{
			for(Object object: ((List<?>)item))
			{
				if(matches(object))
				{
					return true;
				}
			}
		}

		return false;
	}

	@Override
	public void draw(Renderer renderer, int x, int y)
	{
		if(liquid != null)
		{
			TextureManager textureManager = Minecraft.getMinecraft().getTextureManager();

			TextureAtlasSprite icon = Util.getFluidIcon(liquid.getIcon());

			if(icon != null)
			{
				textureManager.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);

				double u = icon.getInterpolatedU(3.0);
				double u2 = icon.getInterpolatedU(13.0);
				double v = icon.getInterpolatedV(1.0);
				double v2 = icon.getInterpolatedV(15.0);

				GlStateManager.enableTexture2D();
				GlStateManager.color(1, 1, 1, 1);

				GL11.glBegin(GL11.GL_QUADS);
					GL11.glTexCoord2d(u, v);
					GL11.glVertex2i(x + 3, y + 1);

					GL11.glTexCoord2d(u, v2);
					GL11.glVertex2i(x + 3, y + 15);

					GL11.glTexCoord2d(u2, v2);
					GL11.glVertex2i(x + 13, y + 15);

					GL11.glTexCoord2d(u2, v);
					GL11.glVertex2i(x + 13, y + 1);
				GL11.glEnd();
			}
		}

		renderer.renderRect(x - 1, y - 1, 18, 18, containerTexture);
	}

	@Override
	public List<String> getTooltip()
	{
		return tooltip;
	}
}


text:
jest.mock("lib/relay/createEnvironment", () => ({
  defaultEnvironment: require("relay-test-utils").createMockEnvironment(),
}))

import { Button, Sans, Serif } from "@artsy/palette"
import { merge } from "lodash"
import React from "react"
import { NativeModules, Text, TouchableWithoutFeedback } from "react-native"
import "react-native"
import * as renderer from "react-test-renderer"

import { LinkText } from "../../../Text/LinkText"
import { BidInfoRow } from "../../Components/BidInfoRow"
import { Checkbox } from "../../Components/Checkbox"

import { BidResultScreen } from "../BidResult"
import { BillingAddress } from "../BillingAddress"
import { ConfirmBid, ConfirmBidProps } from "../ConfirmBid"
import { CreditCardForm } from "../CreditCardForm"

jest.mock("lib/Components/Bidding/Screens/ConfirmBid/BidderPositionQuery", () => ({
  bidderPositionQuery: jest.fn(),
}))
import { bidderPositionQuery } from "lib/Components/Bidding/Screens/ConfirmBid/BidderPositionQuery"
const bidderPositionQueryMock = bidderPositionQuery as jest.Mock<any>

// This lets us import the actual react-relay module, and replace specific functions within it with mocks.
jest.unmock("react-relay")
import relay from "react-relay"

const commitMutationMock = (fn?: typeof relay.commitMutation) =>
  jest.fn<typeof relay.commitMutation, Parameters<typeof relay.commitMutation>>(fn as any)

jest.mock("tipsi-stripe", () => ({
  setOptions: jest.fn(),
  paymentRequestWithCardForm: jest.fn(),
  createTokenWithCard: jest.fn(),
}))
import stripe from "tipsi-stripe"

import { BidderPositionQueryResponse } from "__generated__/BidderPositionQuery.graphql"
import { ConfirmBid_sale_artwork } from "__generated__/ConfirmBid_sale_artwork.graphql"
import { ConfirmBidCreateBidderPositionMutationResponse } from "__generated__/ConfirmBidCreateBidderPositionMutation.graphql"
import { ConfirmBidCreateCreditCardMutationResponse } from "__generated__/ConfirmBidCreateCreditCardMutation.graphql"
import { ConfirmBidUpdateUserMutationResponse } from "__generated__/ConfirmBidUpdateUserMutation.graphql"
import { FakeNavigator } from "lib/Components/Bidding/__tests__/Helpers/FakeNavigator"
import { Modal } from "lib/Components/Modal"
import Spinner from "lib/Components/Spinner"
import { defaultEnvironment } from "lib/relay/createEnvironment"
import { waitUntil } from "lib/tests/waitUntil"

import { BiddingThemeProvider } from "../../Components/BiddingThemeProvider"
import { Address } from "../../types"
import { SelectMaxBidEdit } from "../SelectMaxBidEdit"

let nextStep
const mockNavigator = { push: route => (nextStep = route) }
jest.useFakeTimers()
const mockPostNotificationName = jest.fn()

const findPlaceBidButton = component => {
  return component.root.findAllByType(Button)[1]
}

const mountConfirmBidComponent = props => {
  return renderer.create(
    <BiddingThemeProvider>
      <ConfirmBid {...props} />
    </BiddingThemeProvider>
  )
}

beforeEach(() => {
  nextStep = null // reset nextStep between tests
  // Because of how we mock metaphysics, the mocked value from one test can bleed into another.
  bidderPositionQueryMock.mockReset()
  mockPostNotificationName.mockReset()
  NativeModules.ARNotificationsManager = { postNotificationName: mockPostNotificationName }
  NativeModules.Emission = {
    options: {
      AROptionsPriceTransparency: true,
    },
  }
})

it("renders properly", () => {
  const component = mountConfirmBidComponent(initialProps).toJSON()

  expect(component).toMatchSnapshot()
})

it("enables the bid button when checkbox is ticked", () => {
  const component = mountConfirmBidComponent(initialProps)

  expect(findPlaceBidButton(component).props.onPress).toBeFalsy()

  component.root.findByType(Checkbox).props.onPress()

  expect(findPlaceBidButton(component).props.onPress).toBeDefined()
})

it("enables the bid button by default if the user is registered", () => {
  const component = mountConfirmBidComponent(initialPropsForRegisteredUser)

  expect(findPlaceBidButton(component).props.onPress).toBeDefined()
})

it("displays the artwork title correctly with date", () => {
  const component = mountConfirmBidComponent(initialProps)

  expect(serifChildren(component)).toContain(", 2015")
})

it("displays the artwork title correctly without date", () => {
  const datelessProps = merge({}, initialProps, { sale_artwork: { artwork: { date: null } } })
  const component = renderer.create(
    <BiddingThemeProvider>
      <ConfirmBid {...datelessProps} />
    </BiddingThemeProvider>
  )

  expect(serifChildren(component)).not.toContain(`${saleArtwork.artwork.title},`)
})

it("can load and display price summary", () => {
  const component = mountConfirmBidComponent(initialProps)

  expect(component.root.findAllByType(Spinner).length).toEqual(1)
  ;(defaultEnvironment as any).mock.resolveMostRecentOperation(() => ({
    data: {
      node: {
        __typename: "SaleArtwork",
        calculatedCost: {
          buyersPremium: {
            display: "$9,000.00",
          },
          subtotal: {
            display: "$54,000.00",
          },
        },
      },
    },
  }))

  expect(component.root.findAllByType(Spinner).length).toEqual(0)

  const sansText = component.root
    .findAllByType(Sans)
    .map(sansComponent => sansComponent.props.children as string)
    .join(" ")

  expect(sansText).toContain("Your max bid $45,000.00")
  expect(sansText).toContain("Buyer's premium $9,000.00")
  expect(sansText).toContain("Subtotal $54,000.00")
})

it("does not display price summary when the feature flag is off", () => {
  NativeModules.Emission.options.AROptionsPriceTransparency = false

  const component = mountConfirmBidComponent(initialProps)

  expect(component.root.findAllByType(Spinner).length).toEqual(0)

  const sansText = component.root
    .findAllByType(Sans)
    .map(sansComponent => sansComponent.props.children as string)
    .join(" ")

  expect(sansText).not.toContain("Your max bid $45,000.00")
  expect(sansText).not.toContain("Buyer's premium $9,000.00")
  expect(sansText).not.toContain("Subtotal $54,000.00")
})

describe("checkbox and payment info display", () => {
  it("shows no checkbox or payment info if the user is registered", () => {
    const component = mountConfirmBidComponent(initialPropsForRegisteredUser)

    expect(component.root.findAllByType(Checkbox).length).toEqual(0)
    expect(component.root.findAllByType(BidInfoRow).length).toEqual(1)

    const serifs = component.root.findAllByType(Serif)
    expect(serifs.find(s => s.props.children.join && s.props.children.join("").includes("You agree to"))).toBeTruthy()
  })

  it("shows a checkbox but no payment info if the user is not registered and has cc on file", () => {
    const component = mountConfirmBidComponent(initialProps)

    expect(component.root.findAllByType(Checkbox).length).toEqual(1)
    expect(component.root.findAllByType(BidInfoRow).length).toEqual(1)
  })

  it("shows a checkbox and payment info if the user is not registered and has no cc on file", () => {
    const component = mountConfirmBidComponent(initialPropsForUnqualifiedUser)

    expect(component.root.findAllByType(Checkbox).length).toEqual(1)
    expect(component.root.findAllByType(BidInfoRow).length).toEqual(3)
  })
})

describe("when pressing bid button", () => {
  it("commits mutation", () => {
    const component = mountConfirmBidComponent(initialProps)

    component.root.findByType(Checkbox).props.onPress()

    relay.commitMutation = jest.fn()

    findPlaceBidButton(component).props.onPress()
    expect(relay.commitMutation).toHaveBeenCalled()
  })

  it("shows a spinner", () => {
    const component = mountConfirmBidComponent(initialProps)

    component.root.findByType(Checkbox).props.onPress()
    relay.commitMutation = jest.fn()
    const placeBidButton = findPlaceBidButton(component)

    placeBidButton.props.onPress()

    expect(placeBidButton.props.loading).toEqual(true)
  })

  it("disables tap events while a spinner is being shown", () => {
    const navigator = { push: jest.fn() } as any
    relay.commitMutation = jest.fn()

    const component = mountConfirmBidComponent({ ...initialPropsForUnqualifiedUser, navigator })

    component.root.findByType(ConfirmBid).instance.setState({
      conditionsOfSaleChecked: true,
      creditCardToken: stripeToken,
      billingAddress,
    })

    findPlaceBidButton(component).props.onPress()

    const yourMaxBidRow = component.root.findAllByType(TouchableWithoutFeedback)[0]
    const creditCardRow = component.root.findAllByType(TouchableWithoutFeedback)[1]
    const billingAddressRow = component.root.findAllByType(TouchableWithoutFeedback)[2]
    const conditionsOfSaleLink = component.root.findByType(LinkText)
    const conditionsOfSaleCheckbox = component.root.findByType(Checkbox)

    yourMaxBidRow.instance.props.onPress()

    expect(navigator.push).not.toHaveBeenCalled()

    creditCardRow.instance.props.onPress()

    expect(navigator.push).not.toHaveBeenCalled()

    billingAddressRow.instance.props.onPress()

    expect(navigator.push).not.toHaveBeenCalled()
    expect(conditionsOfSaleLink.props.onPress).toBeNull()
    expect(conditionsOfSaleCheckbox.props.disabled).toBeTruthy()
  })

  describe("when pressing bid", () => {
    it("commits the mutation", () => {
      const component = mountConfirmBidComponent(initialProps)

      component.root.findByType(Checkbox).props.onPress()
      bidderPositionQueryMock.mockReturnValueOnce(Promise.resolve(mockRequestResponses.pollingForBid.highestBidder))
      relay.commitMutation = jest.fn()

      findPlaceBidButton(component).props.onPress()

      expect(relay.commitMutation).toHaveBeenCalled()
    })

    describe("when mutation fails", () => {
      it("does not verify bid position", () => {
        // Probably due to a network problem.
        const component = mountConfirmBidComponent(initialProps)

        component.root.findByType(Checkbox).props.onPress()
        console.error = jest.fn() // Silences component logging.
        relay.commitMutation = commitMutationMock((_, { onError }) => {
          onError(new Error("An error occurred."))
          return null
        }) as any

        findPlaceBidButton(component).props.onPress()

        expect(relay.commitMutation).toHaveBeenCalled()
        expect(bidderPositionQueryMock).not.toHaveBeenCalled()
      })

      it("displays an error message on a network failure", () => {
        const component = mountConfirmBidComponent(initialProps)

        component.root.findByType(Checkbox).props.onPress()
        console.error = jest.fn() // Silences component logging.

        // A TypeError is raised when the device has no internet connection.
        relay.commitMutation = commitMutationMock((_, { onError }) => {
          onError(new TypeError("Network request failed"))
          return null
        }) as any

        findPlaceBidButton(component).props.onPress()

        expect(nextStep.component).toEqual(BidResultScreen)
        expect(nextStep.passProps).toEqual(
          expect.objectContaining({
            bidderPositionResult: {
              message_header: "An error occurred",
              message_description_md:
                "Your bid couldn't be placed. Please\ncheck your internet connection\nand try again.",
            },
          })
        )
      })

      it("displays an error message on a createBidderPosition mutation failure", async () => {
        const error = {
          message: 'GraphQL Timeout Error: Mutation.createBidderPosition has timed out after waiting for 5000ms"}',
        }

        relay.commitMutation = commitMutationMock((_, { onCompleted }) => {
          onCompleted({}, [error])
          return null
        }) as any

        const component = mountConfirmBidComponent(initialProps)

        component.root.findByType(Checkbox).props.onPress()
        findPlaceBidButton(component).props.onPress()

        await waitUntil(() => !!nextStep)

        expect(nextStep.component).toEqual(BidResultScreen)
        expect(nextStep.passProps).toEqual(
          expect.objectContaining({
            bidderPositionResult: {
              message_header: "An error occurred",
              message_description_md:
                "Your bid couldn't be placed. Please\ncheck your internet connection\nand try again.",
            },
          })
        )
      })
    })
  })
})

describe("editing bid amount", () => {
  it("allows you to go to the max bid edit screen and select a new max bid", () => {
    const fakeNavigator = new FakeNavigator()
    const fakeNavigatorProps = {
      ...initialPropsForRegisteredUser,
      navigator: fakeNavigator,
    }
    fakeNavigator.push({ component: ConfirmBid, id: "", title: "", passProps: fakeNavigatorProps })

    const component = mountConfirmBidComponent({ ...initialPropsForRegisteredUser, navigator: fakeNavigator })

    const selectMaxBidRow = component.root.findAllByType(TouchableWithoutFeedback)[0]

    expect(selectMaxBidRow.findAllByType(Serif)[1].props.children).toEqual("$45,000")

    selectMaxBidRow.instance.props.onPress()

    const editScreen = fakeNavigator.nextStep().root.findByType(SelectMaxBidEdit)

    expect(editScreen.props.selectedBidIndex).toEqual(0)

    editScreen.instance.setState({ selectedBidIndex: 1 })
    editScreen.findByType(Button).props.onPress()

    const updatedBidRow = component.root.findAllByType(TouchableWithoutFeedback)[0]
    expect(updatedBidRow.findAllByType(Serif)[1].props.children).toEqual("$46,000")
  })
})

describe("polling to verify bid position", () => {
  describe("bid success", () => {
    it("polls for new results", async () => {
      const component = mountConfirmBidComponent(initialProps)

      component.root.findByType(Checkbox).props.onPress()
      relay.commitMutation = commitMutationMock((_, { onCompleted }) => {
        onCompleted(mockRequestResponses.placingBid.bidAccepted, null)
        return null
      }) as any
      let requestCounter = 0 // On the fifth attempt, return highestBidder
      bidderPositionQueryMock.mockImplementation(() => {
        requestCounter++
        if (requestCounter > 5) {
          return Promise.resolve(mockRequestResponses.pollingForBid.highestBidder)
        } else {
          return Promise.resolve(mockRequestResponses.pollingForBid.pending)
        }
      })

      findPlaceBidButton(component).props.onPress()
      await waitUntil(() => {
        if (!nextStep) {
          jest.runOnlyPendingTimers()
          jest.runAllTicks()
          return false
        }
        return true
      })

      expect(nextStep.component).toEqual(BidResultScreen)
      expect(nextStep.passProps).toEqual(
        expect.objectContaining({
          bidderPositionResult: mockRequestResponses.pollingForBid.highestBidder.me.bidder_position,
        })
      )
    })

    it("shows error when polling attempts exceed max", async () => {
      const component = mountConfirmBidComponent(initialProps)

      component.root.findByType(Checkbox).props.onPress()
      bidderPositionQueryMock.mockReturnValue(Promise.resolve(mockRequestResponses.pollingForBid.pending))
      relay.commitMutation = commitMutationMock((_, { onCompleted }) => {
        onCompleted(mockRequestResponses.placingBid.bidAccepted, null)
        return null
      }) as any

      findPlaceBidButton(component).props.onPress()
      await waitUntil(() => {
        if (!nextStep) {
          jest.runOnlyPendingTimers()
          jest.runAllTicks()
          return false
        }
        return true
      })

      expect(nextStep.component).toEqual(BidResultScreen)
      expect(nextStep.passProps).toEqual(
        expect.objectContaining({
          bidderPositionResult: mockRequestResponses.pollingForBid.pending.me.bidder_position,
        })
      )
    })

    it("shows successful bid result when highest bidder", async () => {
      const component = mountConfirmBidComponent(initialProps)

      component.root.findByType(Checkbox).props.onPress()
      bidderPositionQueryMock.mockReturnValueOnce(Promise.resolve(mockRequestResponses.pollingForBid.highestBidder))
      relay.commitMutation = commitMutationMock((_, { onCompleted }) => {
        onCompleted(mockRequestResponses.placingBid.bidAccepted, null)
        return null
      }) as any

      findPlaceBidButton(component).props.onPress()
      await waitUntil(() => !!nextStep)

      expect(nextStep.component).toEqual(BidResultScreen)
      expect(nextStep.passProps).toEqual(
        expect.objectContaining({
          bidderPositionResult: mockRequestResponses.pollingForBid.highestBidder.me.bidder_position,
        })
      )
    })

    it("shows outbid bidSuccessResult when outbid", async () => {
      const component = mountConfirmBidComponent(initialProps)

      component.root.findByType(Checkbox).props.onPress()
      bidderPositionQueryMock.mockReturnValueOnce(Promise.resolve(mockRequestResponses.pollingForBid.outbid))
      relay.commitMutation = commitMutationMock((_, { onCompleted }) => {
        onCompleted(mockRequestResponses.placingBid.bidAccepted, null)
        return null
      }) as any

      findPlaceBidButton(component).props.onPress()
      await waitUntil(() => !!nextStep)

      expect(nextStep.component).toEqual(BidResultScreen)
      expect(nextStep.passProps).toEqual(
        expect.objectContaining({
          bidderPositionResult: mockRequestResponses.pollingForBid.outbid.me.bidder_position,
        })
      )
    })

    it("shows reserve not met when reserve is not met", async () => {
      const component = mountConfirmBidComponent(initialProps)

      component.root.findByType(Checkbox).props.onPress()
      bidderPositionQueryMock.mockReturnValueOnce(Promise.resolve(mockRequestResponses.pollingForBid.reserveNotMet))
      relay.commitMutation = commitMutationMock((_, { onCompleted }) => {
        onCompleted(mockRequestResponses.placingBid.bidAccepted, null)
        return null
      }) as any

      findPlaceBidButton(component).props.onPress()
      await waitUntil(() => !!nextStep)

      expect(nextStep.component).toEqual(BidResultScreen)
      expect(nextStep.passProps).toEqual(
        expect.objectContaining({
          bidderPositionResult: mockRequestResponses.pollingForBid.reserveNotMet.me.bidder_position,
        })
      )
    })

    it("updates the main auction screen", async () => {
      const mockedMockNavigator = { push: jest.fn() }
      const component = mountConfirmBidComponent({
        ...initialProps,
        navigator: mockedMockNavigator as any,
        refreshSaleArtwork: jest.fn(),
      })
      component.root.findByType(Checkbox).props.onPress()
      bidderPositionQueryMock.mockReturnValueOnce(Promise.resolve(mockRequestResponses.pollingForBid.reserveNotMet))
      relay.commitMutation = commitMutationMock((_, { onCompleted }) => {
        onCompleted(mockRequestResponses.placingBid.bidAccepted, null)
        return null
      }) as any

      findPlaceBidButton(component).props.onPress()
      await waitUntil(() => mockPostNotificationName.mock.calls.length > 0)

      expect(mockPostNotificationName).toHaveBeenCalledWith("ARAuctionArtworkRegistrationUpdated", {
        ARAuctionID: "best-art-sale-in-town",
      })
      expect(mockPostNotificationName).toHaveBeenCalledWith("ARAuctionArtworkBidUpdated", {
        ARAuctionID: "best-art-sale-in-town",
        ARAuctionArtworkID: "meteor-shower",
      })

      // navigates to bid result screen
      expect(mockedMockNavigator.push).toHaveBeenCalledWith({
        component: BidResultScreen,
        passProps: {
          bidderPositionResult: {
            position: {
              internalID: "bidder-position-id-from-polling",
            },
            status: "RESERVE_NOT_MET",
          },
          refreshBidderInfo: expect.anything(),
          refreshSaleArtwork: expect.anything(),
          sale_artwork: {
            id: "node-id",
            internalID: "internal-id",
            " $fragmentRefs": null,
            " $refType": null,
            artwork: {
              artist_names: "Makiko Kudo",
              date: "2015",
              slug: "meteor-shower",
              title: "Meteor Shower",
              image: {
                url: "https://d32dm0rphc51dk.cloudfront.net/5RvuM9YF68AyD8OgcdLw7g/small.jpg",
              },
            },
            lot_label: "538",
            sale: {
              end_at: "2018-05-10T20:22:42+00:00",
              isBenefit: false,
              live_start_at: "2018-05-09T20:22:42+00:00",
              partner: {
                name: "Christie's",
              },
              slug: "best-art-sale-in-town",
            },
          },
        },
        title: "",
      })
    })
  })

  describe("bid failure", () => {
    it("shows the error screen with a failure", async () => {
      const component = mountConfirmBidComponent(initialProps)

      component.root.findByType(Checkbox).props.onPress()
      relay.commitMutation = commitMutationMock((_, { onCompleted }) => {
        onCompleted(mockRequestResponses.placingBid.bidRejected, null)
        return null
      }) as any

      findPlaceBidButton(component).props.onPress()
      await waitUntil(() => !!nextStep)

      expect(nextStep.component).toEqual(BidResultScreen)
      expect(nextStep.passProps).toEqual(
        expect.objectContaining({
          bidderPositionResult: mockRequestResponses.placingBid.bidRejected.createBidderPosition.result,
        })
      )
    })
  })
})

describe("ConfirmBid for unqualified user", () => {
  const fillOutFormAndSubmit = component => {
    // manually setting state to avoid duplicating tests for skipping UI interaction, but practically better not to do this.
    component.root.findByType(ConfirmBid).instance.setState({ billingAddress })
    component.root.findByType(ConfirmBid).instance.setState({ creditCardToken: stripeToken })
    component.root.findByType(Checkbox).props.onPress()
    findPlaceBidButton(component).props.onPress()

    jest.runAllTicks()
  }

  it("shows the billing address that the user typed in the billing address form", () => {
    const billingAddressRow = mountConfirmBidComponent(initialPropsForUnqualifiedUser).root.findAllByType(
      TouchableWithoutFeedback
    )[2]

    billingAddressRow.instance.props.onPress()

    expect(nextStep.component).toEqual(BillingAddress)

    nextStep.passProps.onSubmit(billingAddress)

    expect(billingAddressRow.findAllByType(Serif)[1].props.children).toEqual("401 Broadway 25th floor New York NY")
  })

  it("shows the credit card form when the user tap the edit text in the credit card row", () => {
    const creditcardRow = mountConfirmBidComponent(initialPropsForUnqualifiedUser).root.findAllByType(
      TouchableWithoutFeedback
    )[1]

    creditcardRow.instance.props.onPress()

    expect(nextStep.component).toEqual(CreditCardForm)
  })

  it("shows the error screen when stripe's API returns an error", () => {
    relay.commitMutation = commitMutationMock((_, { onCompleted }) => {
      onCompleted({}, null)
      return null
    }) as any
    stripe.createTokenWithCard.mockImplementationOnce(() => {
      throw new Error("Error tokenizing card")
    })

    jest.useFakeTimers()
    const component = mountConfirmBidComponent(initialPropsForUnqualifiedUser)
    fillOutFormAndSubmit(component)

    expect(stripe.createTokenWithCard.mock.calls.length).toEqual(1)

    const modal = component.root.findByType(Modal)

    expect(modal.props.detailText).toEqual(
      "There was a problem processing your information. Check your payment details and try again."
    )
    expect(modal.props.visible).toEqual(true)
  })

  it("shows the error screen with the correct error message on a createCreditCard mutation failure", () => {
    console.error = jest.fn() // Silences component logging.
    stripe.createTokenWithCard.mockReturnValueOnce(stripeToken)
    relay.commitMutation = commitMutationMock((_, { onCompleted }) => {
      onCompleted(mockRequestResponses.creatingCreditCardError, null)
      return null
    }) as any

    const component = mountConfirmBidComponent(initialPropsForUnqualifiedUser)

    fillOutFormAndSubmit(component)

    expect(component.root.findByType(Modal).findAllByType(Text)[1].props.children).toEqual(
      "Your card's security code is incorrect."
    )
    component.root
      .findByType(Modal)
      .findByType(Button)
      .props.onPress()

    expect(component.root.findByType(Modal).props.visible).toEqual(false)
  })

  it("shows the error screen with the default error message if there are unhandled errors from the createCreditCard mutation", () => {
    const errors = [{ message: "malformed error" }]

    console.error = jest.fn() // Silences component logging.
    stripe.createTokenWithCard.mockReturnValueOnce(stripeToken)
    relay.commitMutation = commitMutationMock((_, { onCompleted }) => {
      onCompleted({}, errors)
      return null
    }) as any

    const component = mountConfirmBidComponent(initialPropsForUnqualifiedUser)

    fillOutFormAndSubmit(component)

    expect(component.root.findByType(Modal).findAllByType(Text)[1].props.children).toEqual(
      "There was a problem processing your information. Check your payment details and try again."
    )
    component.root
      .findByType(Modal)
      .findByType(Button)
      .props.onPress()

    // it dismisses the modal
    expect(component.root.findByType(Modal).props.visible).toEqual(false)
  })

  it("shows the error screen with the default error message if the creditCardMutation error message is empty", () => {
    console.error = jest.fn() // Silences component logging.
    stripe.createTokenWithCard.mockReturnValueOnce(stripeToken)
    relay.commitMutation = commitMutationMock((_, { onCompleted }) => {
      onCompleted(mockRequestResponses.creatingCreditCardEmptyError, null)
      return null
    }) as any

    const component = mountConfirmBidComponent(initialPropsForUnqualifiedUser)

    fillOutFormAndSubmit(component)

    expect(component.root.findByType(Modal).findAllByType(Text)[1].props.children).toEqual(
      "There was a problem processing your information. Check your payment details and try again."
    )
    component.root
      .findByType(Modal)
      .findByType(Button)
      .props.onPress()

    expect(component.root.findByType(Modal).props.visible).toEqual(false)
  })

  it("shows the generic error screen on a createCreditCard mutation network failure", () => {
    console.error = jest.fn() // Silences component logging.
    stripe.createTokenWithCard.mockReturnValueOnce(stripeToken)
    relay.commitMutation = commitMutationMock((_, { onError }) => {
      onError(new TypeError("Network request failed"))
      return null
    }) as any

    const component = mountConfirmBidComponent(initialPropsForUnqualifiedUser)

    fillOutFormAndSubmit(component)

    expect(nextStep.component).toEqual(BidResultScreen)
    expect(nextStep.passProps).toEqual(
      expect.objectContaining({
        bidderPositionResult: {
          message_header: "An error occurred",
          message_description_md: "Your bid couldn't be placed. Please\ncheck your internet connection\nand try again.",
        },
      })
    )
  })

  describe("After successful mutations", () => {
    beforeEach(() => {
      stripe.createTokenWithCard.mockReturnValueOnce(stripeToken)
      relay.commitMutation = jest
        .fn()
        .mockImplementationOnce((_, { onCompleted }) => onCompleted(mockRequestResponses.updateMyUserProfile))
        .mockImplementationOnce((_, { onCompleted }) => onCompleted(mockRequestResponses.creatingCreditCardSuccess))
        .mockImplementationOnce((_, { onCompleted }) => onCompleted(mockRequestResponses.placingBid.bidAccepted))
    })

    it("commits two mutations, createCreditCard followed by createBidderPosition on a successful bid", async () => {
      bidderPositionQueryMock
        .mockReturnValueOnce(Promise.resolve(mockRequestResponses.pollingForBid.pending))
        .mockReturnValueOnce(Promise.resolve(mockRequestResponses.pollingForBid.highestBidder))

      const component = mountConfirmBidComponent(initialPropsForUnqualifiedUser)

      fillOutFormAndSubmit(component)

      expect(relay.commitMutation).toHaveBeenCalled()
      expect(relay.commitMutation).toHaveBeenCalledWith(
        expect.any(Object),
        expect.objectContaining({
          variables: {
            input: {
              phone: "111 222 4444",
            },
          },
        })
      )

      expect(relay.commitMutation).toHaveBeenCalledWith(
        expect.any(Object),
        expect.objectContaining({
          variables: {
            input: {
              token: "fake-token",
            },
          },
        })
      )

      expect(relay.commitMutation).toHaveBeenCalledWith(
        expect.any(Object),
        expect.objectContaining({
          variables: {
            input: {
              saleID: saleArtwork.sale.slug,
              artworkID: saleArtwork.artwork.slug,
              maxBidAmountCents: 450000,
            },
          },
        })
      )

      await waitUntil(() => {
        if (bidderPositionQueryMock.mock.calls.length !== 2) {
          jest.runOnlyPendingTimers()
          return false
        }
        return true
      })

      expect(bidderPositionQueryMock.mock.calls[0][0]).toEqual("bidder-position-id-from-mutation")
      expect(bidderPositionQueryMock.mock.calls[1][0]).toEqual("bidder-position-id-from-polling")
    })

    it("displays an error message on polling failure", async () => {
      console.error = jest.fn() // Silences component logging.
      bidderPositionQueryMock.mockReturnValueOnce(Promise.reject({ message: "error" }))

      const component = mountConfirmBidComponent(initialPropsForUnqualifiedUser)

      fillOutFormAndSubmit(component)
      await waitUntil(() => !!nextStep)

      expect(nextStep.component).toEqual(BidResultScreen)
      expect(nextStep.passProps).toEqual(
        expect.objectContaining({
          bidderPositionResult: {
            message_header: "An error occurred",
            message_description_md:
              "Your bid couldn't be placed. Please\ncheck your internet connection\nand try again.",
          },
        })
      )
    })
  })
})

const serifChildren = comp =>
  comp.root
    .findAllByType(Serif)
    .map(c => (c.props.children.join ? c.props.children.join("") : c.props.children))
    .join(" ")

const saleArtwork: ConfirmBid_sale_artwork = {
  id: "node-id",
  internalID: "internal-id",
  artwork: {
    slug: "meteor-shower",
    title: "Meteor Shower",
    date: "2015",
    artist_names: "Makiko Kudo",
    image: {
      url: "https://d32dm0rphc51dk.cloudfront.net/5RvuM9YF68AyD8OgcdLw7g/small.jpg",
    },
  },
  sale: {
    slug: "best-art-sale-in-town",
    live_start_at: "2018-05-09T20:22:42+00:00",
    end_at: "2018-05-10T20:22:42+00:00",
    isBenefit: false,
    partner: {
      name: "Christie's",
    },
  },
  lot_label: "538",
  " $fragmentRefs": null, // needs this to keep TS happy
  " $refType": null, // needs this to keep TS happy
}

const mockRequestResponses = {
  updateMyUserProfile: {
    updateMyUserProfile: {
      user: {
        phone: "111 222 4444",
      },
    },
  } as ConfirmBidUpdateUserMutationResponse,
  creatingCreditCardSuccess: {
    createCreditCard: {
      creditCardOrError: {
        creditCard: {
          internalID: "new-credit-card",
          brand: "VISA",
          name: "TEST",
          last_digits: "4242",
          expiration_month: 1,
          expiration_year: 2020,
        },
      },
    },
  } as ConfirmBidCreateCreditCardMutationResponse,
  creatingCreditCardEmptyError: {
    createCreditCard: {
      creditCardOrError: {
        mutationError: {
          detail: "",
          message: "Payment information could not be processed.",
          type: "payment_error",
        },
      },
    },
  } as ConfirmBidCreateCreditCardMutationResponse,
  creatingCreditCardError: {
    createCreditCard: {
      creditCardOrError: {
        mutationError: {
          detail: "Your card's security code is incorrect.",
          message: "Payment information could not be processed.",
          type: "payment_error",
        },
      },
    },
  } as ConfirmBidCreateCreditCardMutationResponse,
  placingBid: {
    bidAccepted: {
      createBidderPosition: {
        result: {
          status: "SUCCESS",
          message_header: "Success",
          message_description_md: "",
          position: {
            internalID: "bidder-position-id-from-mutation",
          },
        },
      },
    } as ConfirmBidCreateBidderPositionMutationResponse,
    bidRejected: {
      createBidderPosition: {
        result: {
          status: "ERROR",
          message_header: "An error occurred",
          message_description_md: "Some markdown description",
        },
      },
    } as ConfirmBidCreateBidderPositionMutationResponse,
  },
  pollingForBid: {
    highestBidder: {
      me: {
        bidder_position: {
          status: "WINNING",
          position: {
            internalID: "bidder-position-id-from-polling",
          },
        },
      },
    } as BidderPositionQueryResponse,
    outbid: {
      me: {
        bidder_position: {
          status: "OUTBID",
          position: {
            internalID: "bidder-position-id-from-polling",
          },
        },
      },
    } as BidderPositionQueryResponse,
    pending: {
      me: {
        bidder_position: {
          position: {
            internalID: "bidder-position-id-from-polling",
          },
          status: "PENDING",
        },
      },
    } as BidderPositionQueryResponse,
    reserveNotMet: {
      me: {
        bidder_position: {
          position: {
            internalID: "bidder-position-id-from-polling",
          },
          status: "RESERVE_NOT_MET",
        },
      },
    } as BidderPositionQueryResponse,
  },
}

const billingAddress: Address = {
  fullName: "Yuki Stockmeier",
  addressLine1: "401 Broadway",
  addressLine2: "25th floor",
  city: "New York",
  state: "NY",
  postalCode: "10013",
  phoneNumber: "111 222 4444",
  country: {
    longName: "United States",
    shortName: "US",
  },
}

const stripeToken = {
  tokenId: "fake-token",
  created: "1528229731",
  livemode: 0,
  card: {
    brand: "VISA",
    last4: "4242",
  },
  bankAccount: null,
  extra: null,
}

const initialProps: ConfirmBidProps = {
  sale_artwork: saleArtwork,
  increments: [
    {
      cents: 450000,
      display: "$45,000",
    },
    {
      cents: 460000,
      display: "$46,000",
    },
  ],
  selectedBidIndex: 0,
  relay: {
    environment: null,
  },
  me: {
    has_qualified_credit_cards: true,
    bidders: null,
  },
  navigator: mockNavigator,
} as any

const initialPropsForUnqualifiedUser = {
  ...initialProps,
  me: {
    has_qualified_credit_cards: false,
  },
} as any

const initialPropsForRegisteredUser = {
  ...initialProps,
  me: {
    bidders: [{ qualified_for_bidding: true }],
  },
} as any


text:
namespace SharpAima.Tests.Agents
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using SharpAima.Agents;

    [TestClass]
    public class TrivialVacuumEnvironmentTests
    {
        [TestMethod]
        public void GetAgentPerception()
        {
            TrivialVacuumEnvironment environment = new TrivialVacuumEnvironment();
            environment.SetStatus(VacuumLocation.A, VacuumStatus.Clean);
            var agent = new RandomVacuumAgent();
            agent.Location = VacuumLocation.A;

            var result = environment.GetPerception(agent);

            Assert.AreEqual(VacuumLocation.A, result.Location);
            Assert.AreEqual(VacuumStatus.Clean, result.Status);
        }

        [TestMethod]
        public void ExecuteSuckActionOnDirtyStatus()
        {
            TrivialVacuumEnvironment environment = new TrivialVacuumEnvironment();
            environment.SetStatus(VacuumLocation.A, VacuumStatus.Dirty);
            var agent = new RandomVacuumAgent();
            agent.Location = VacuumLocation.A;

            environment.ExecuteAction(agent, VacuumAction.Suck);

            Assert.AreEqual(VacuumLocation.A, agent.Location);
            Assert.AreEqual(10, agent.Performance);
            Assert.AreEqual(VacuumStatus.Clean, environment.GetStatus(VacuumLocation.A));
        }

        [TestMethod]
        public void ExecuteSuckActionOnCleanStatus()
        {
            TrivialVacuumEnvironment environment = new TrivialVacuumEnvironment();
            environment.SetStatus(VacuumLocation.A, VacuumStatus.Clean);
            var agent = new RandomVacuumAgent();
            agent.Location = VacuumLocation.A;

            environment.ExecuteAction(agent, VacuumAction.Suck);

            Assert.AreEqual(VacuumLocation.A, agent.Location);
            Assert.AreEqual(0, agent.Performance);
            Assert.AreEqual(VacuumStatus.Clean, environment.GetStatus(VacuumLocation.A));
        }

        [TestMethod]
        public void ExecuteRightAction()
        {
            TrivialVacuumEnvironment environment = new TrivialVacuumEnvironment();
            environment.SetStatus(VacuumLocation.A, VacuumStatus.Clean);
            var agent = new RandomVacuumAgent();
            agent.Location = VacuumLocation.A;

            environment.ExecuteAction(agent, VacuumAction.Right);

            Assert.AreEqual(VacuumLocation.B, agent.Location);
            Assert.AreEqual(-1, agent.Performance);
            Assert.AreEqual(VacuumStatus.Clean, environment.GetStatus(VacuumLocation.A));
        }

        [TestMethod]
        public void ExecuteLeftAction()
        {
            TrivialVacuumEnvironment environment = new TrivialVacuumEnvironment();
            environment.SetStatus(VacuumLocation.A, VacuumStatus.Clean);
            var agent = new RandomVacuumAgent();
            agent.Location = VacuumLocation.B;

            environment.ExecuteAction(agent, VacuumAction.Left);

            Assert.AreEqual(VacuumLocation.A, agent.Location);
            Assert.AreEqual(-1, agent.Performance);
            Assert.AreEqual(VacuumStatus.Clean, environment.GetStatus(VacuumLocation.A));
        }
    }
}