text:
"use strict";
/* global define, config, templates, app, utils, ajaxify, socket, translator */

define('forum/api', ['composer', 'forum/pagination', 'forum/infinitescroll', 'share', 'navigator', 'forum/categoryTools'], function(composer, pagination, infinitescroll, share, navigator, categoryTools) {
    var Api = {};

    $(window).on('action:ajaxify.start', function(ev, data) {
        if(data && data.url.indexOf('api') !== 0) {
            navigator.hide();

//            removeListeners();
        }
    });

//    function removeListeners() {
//        socket.removeListener('event:new_topic', Api.onNewTopic);
//        socket.addListener
//        categoryTools.removeListeners();
//    }

    Api.init = function() {
        var	cid = ajaxify.variables.get('category_id');

        app.enterRoom('category_' + cid);

        share.addShareHandlers(ajaxify.variables.get('category_name'));

        $('#new_post').on('click', function () {
            composer.newTopic(cid);
        });

        socket.on('event:new_topic', Api.onNewTopic);

        categoryTools.init(cid);

        enableInfiniteLoadingOrPagination();

        if (!config.usePagination) {
            navigator.init('#topics-container > .category-item', ajaxify.variables.get('topic_count'), undefined, Api.toTop, Api.toBottom);
        }

        $('#topics-container').on('click', '.topic-title', function() {
            var clickedTid = $(this).parents('li.category-item[data-tid]').attr('data-tid');
            $('#topics-container li.category-item').each(function(index, el) {
                if($(el).offset().top - $(window).scrollTop() > 0) {
                    localStorage.setItem('category:bookmark', $(el).attr('data-tid'));
                    localStorage.setItem('category:bookmark:clicked', clickedTid);
                    return false;
                }
            });
        });
    };

    Api.toTop = function() {
        navigator.scrollTop(0);
    };

    Api.toBottom = function() {
        socket.emit('categories.lastTopicIndex', ajaxify.variables.get('category_id'), function(err, index) {
            navigator.scrollBottom(index);
        });
    };

    $(window).on('action:popstate', function(ev, data) {
        if(data.url.indexOf('category/') === 0) {
            var bookmark = localStorage.getItem('category:bookmark');
            var clicked = localStorage.getItem('category:bookmark:clicked');

            if (bookmark) {

                if(config.usePagination) {
                    socket.emit('topics.getTidPage', bookmark, function(err, page) {
                        if(err) {
                            return;
                        }
                        if(parseInt(page, 10) !== pagination.currentPage) {
                            pagination.loadPage(page);
                        } else {
                            Api.scrollToTopic(bookmark, clicked, 400);
                        }
                    });
                } else {

                    socket.emit('topics.getTidIndex', bookmark, function(err, index) {
                        if(err) {
                            return;
                        }

                        if(index === 0) {
                            Api.highlightTopic(clicked);
                            return;
                        }

                        if (index < 0) {
                            index = 0;
                        }

                        $('#topics-container').empty();

                        loadTopicsAfter(index, function() {
                            Api.scrollToTopic(bookmark, clicked, 0);
                        });
                    });
                }
            }
        }
    });

    Api.highlightTopic = function(tid) {
        var highlight = $('#topics-container li.category-item[data-tid="' + tid + '"]');
        if(highlight.length && !highlight.hasClass('highlight')) {
            highlight.addClass('highlight');
            setTimeout(function() {
                highlight.removeClass('highlight');
            }, 5000);
        }
    };

    Api.scrollToTopic = function(tid, clickedTid, duration, offset) {
        if(!tid) {
            return;
        }

        if(!offset) {
            offset = 0;
        }

        if($('#topics-container li.category-item[data-tid="' + tid + '"]').length) {
            var	cid = ajaxify.variables.get('category_id');
            var scrollTo = $('#topics-container li.category-item[data-tid="' + tid + '"]');

            if (cid && scrollTo.length) {
                $('html, body').animate({
                    scrollTop: (scrollTo.offset().top - $('#header-menu').height() - offset) + 'px'
                }, duration !== undefined ? duration : 400, function() {
                    Api.highlightTopic(clickedTid);
                    navigator.update();
                });
            }
        }
    };

    function enableInfiniteLoadingOrPagination() {
        if (!config.usePagination) {
            infinitescroll.init(Api.loadMoreTopics);
        } else {
            navigator.hide();
            pagination.init(ajaxify.variables.get('currentPage'), ajaxify.variables.get('pageCount'));
        }
    }

    Api.onNewTopic = function(topic) {
        $(window).trigger('filter:categories.new_topic', topic);

        ajaxify.loadTemplate('category', function(categoryTemplate) {
            var html = templates.parse(templates.getBlock(categoryTemplate, 'topics'), {
                privileges: {editable: !!$('.thread-tools').length},
                topics: [topic]
            });

            translator.translate(html, function(translatedHTML) {
                var topic = $(translatedHTML),
                    container = $('#topics-container'),
                    topics = $('#topics-container').children('.category-item'),
                    numTopics = topics.length;

                $('#topics-container, .category-sidebar').removeClass('hidden');

                var noTopicsWarning = $('#category-no-topics');
                if (noTopicsWarning.length) {
                    noTopicsWarning.remove();
                    ajaxify.widgets.render('category', window.location.pathname.slice(1));
                }

                if (numTopics > 0) {
                    for (var x = 0; x < numTopics; x++) {
                        var pinned = $(topics[x]).hasClass('pinned');
                        if (pinned) {
                            if(x === numTopics - 1) {
                                topic.insertAfter(topics[x]);
                            }
                            continue;
                        }
                        topic.insertBefore(topics[x]);
                        break;
                    }
                } else {
                    container.append(topic);
                }

                topic.hide().fadeIn('slow');

                socket.emit('categories.getPageCount', ajaxify.variables.get('category_id'), function(err, newPageCount) {
                    pagination.recreatePaginationLinks(newPageCount);
                });

                topic.find('span.timeago').timeago();
                app.createUserTooltips();
                updateTopicCount();

                $(window).trigger('action:categories.new_topic.loaded');
            });
        });
    };

    function updateTopicCount() {
        socket.emit('categories.getTopicCount', ajaxify.variables.get('category_id'), function(err, topicCount) {
            if(err) {
                return app.alertError(err.message);
            }
            navigator.setCount(topicCount);
        });
    }

    Api.onTopicsLoaded = function(data, callback) {
        if(!data || !data.topics.length) {
            return;
        }

        var topics = data.topics;

        function removeAlreadyAddedTopics() {
            topics = topics.filter(function(topic) {
                return $('#topics-container li[data-tid="' + topic.tid +'"]').length === 0;
            });
        }

        var after = null,
            before = null;

        function findInsertionPoint() {
            if (!$('#topics-container .category-item[data-tid]').length) {
                return;
            }
            var last = $('#topics-container .category-item[data-tid]').last();
            var lastIndex = last.attr('data-index');
            var firstIndex = topics[topics.length - 1].index;
            if (firstIndex > lastIndex) {
                after = last;
            } else {
                before = $('#topics-container .category-item[data-tid]').first();
            }
        }

        removeAlreadyAddedTopics();
        if(!topics.length) {
            return;
        }

        findInsertionPoint();

        ajaxify.loadTemplate('category', function(categoryTemplate) {
            var html = templates.parse(templates.getBlock(categoryTemplate, 'topics'), data);

            translator.translate(html, function(translatedHTML) {
                var container = $('#topics-container'),
                    html = $(translatedHTML);

                $('#topics-container, .category-sidebar').removeClass('hidden');
                $('#category-no-topics').remove();

                if(config.usePagination) {
                    container.empty().append(html);
                } else {
                    if(after) {
                        html.insertAfter(after);
                    } else if(before) {
                        html.insertBefore(before);
                    } else {
                        container.append(html);
                    }
                }

                if (typeof callback === 'function') {
                    callback();
                }
                html.find('span.timeago').timeago();
                app.createUserTooltips();
                utils.makeNumbersHumanReadable(html.find('.human-readable-number'));
            });
        });
    };

    Api.loadMoreTopics = function(direction) {
        if (!$('#topics-container').length || !$('#topics-container').children().length) {
            return;
        }

        infinitescroll.calculateAfter(direction, '#topics-container .category-item[data-tid]', config.topicsPerPage, function(after, offset, el) {

            loadTopicsAfter(after, function() {
                if (direction < 0 && el) {
                    Api.scrollToTopic(el.attr('data-tid'), null, 0, offset);
                }
            });
        });
    };

    function loadTopicsAfter(after, callback) {
        if(!utils.isNumber(after) || (after === 0 && $('#topics-container li.category-item[data-index="0"]').length)) {
            return;
        }

        $(window).trigger('action:categories.loading');
        infinitescroll.loadMore('categories.loadMore', {
            cid: ajaxify.variables.get('category_id'),
            after: after
        }, function (data, done) {

            if (data.topics && data.topics.length) {
                Api.onTopicsLoaded(data, function() {
                    done();
                    callback();
                });
                $('#topics-container').attr('data-nextstart', data.nextStart);
            } else {
                done();
            }

            $(window).trigger('action:categories.loaded');
        });
    }

    return Api;
});


text:
import fixtures
import mock
import testtools

from neutron.agent.linux import utils
from neutron.tests import base

class FakeCreateProcess(object):
    class FakeStdin(object):
        def close(self):
            pass

    def __init__(self, returncode):
        self.returncode = returncode
        self.stdin = self.FakeStdin()

    def communicate(self, process_input=None):
        return '', ''

class AgentUtilsExecuteTest(base.BaseTestCase):
    def setUp(self):
        super(AgentUtilsExecuteTest, self).setUp()
        self.root_helper = "echo"
        self.test_file = self.useFixture(
            fixtures.TempDir()).join("test_execute.tmp")
        open(self.test_file, 'w').close()
        self.mock_popen_p = mock.patch("subprocess.Popen.communicate")
        self.mock_popen = self.mock_popen_p.start()

    def test_without_helper(self):
        expected = "%s\n" % self.test_file
        self.mock_popen.return_value = [expected, ""]
        result = utils.execute(["ls", self.test_file])
        self.assertEqual(result, expected)

    def test_with_helper(self):
        expected = "ls %s\n" % self.test_file
        self.mock_popen.return_value = [expected, ""]
        result = utils.execute(["ls", self.test_file],
                               self.root_helper)
        self.assertEqual(result, expected)

    def test_stderr_true(self):
        expected = "%s\n" % self.test_file
        self.mock_popen.return_value = [expected, ""]
        out = utils.execute(["ls", self.test_file], return_stderr=True)
        self.assertIsInstance(out, tuple)
        self.assertEqual(out, (expected, ""))

    def test_check_exit_code(self):
        self.mock_popen.return_value = ["", ""]
        stdout = utils.execute(["ls", self.test_file[:-1]],
                               check_exit_code=False)
        self.assertEqual(stdout, "")

    def test_execute_raises(self):
        self.mock_popen.side_effect = RuntimeError
        self.assertRaises(RuntimeError, utils.execute,
                          ["ls", self.test_file[:-1]])

    def test_process_input(self):
        expected = "%s\n" % self.test_file[:-1]
        self.mock_popen.return_value = [expected, ""]
        result = utils.execute(["cat"], process_input="%s\n" %
                               self.test_file[:-1])
        self.assertEqual(result, expected)

    def test_with_addl_env(self):
        expected = "%s\n" % self.test_file
        self.mock_popen.return_value = [expected, ""]
        result = utils.execute(["ls", self.test_file],
                               addl_env={'foo': 'bar'})
        self.assertEqual(result, expected)

    def test_return_code_log_error_raise_runtime(self):
        with mock.patch.object(utils, 'create_process') as create_process:
            create_process.return_value = FakeCreateProcess(1), 'ls'
            with mock.patch.object(utils, 'LOG') as log:
                self.assertRaises(RuntimeError, utils.execute,
                                  ['ls'])
                self.assertTrue(log.error.called)

    def test_return_code_log_error_no_raise_runtime(self):
        with mock.patch.object(utils, 'create_process') as create_process:
            create_process.return_value = FakeCreateProcess(1), 'ls'
            with mock.patch.object(utils, 'LOG') as log:
                utils.execute(['ls'], check_exit_code=False)
                self.assertTrue(log.error.called)

    def test_return_code_log_debug(self):
        with mock.patch.object(utils, 'create_process') as create_process:
            create_process.return_value = FakeCreateProcess(0), 'ls'
            with mock.patch.object(utils, 'LOG') as log:
                utils.execute(['ls'])
                self.assertTrue(log.debug.called)

    def test_return_code_raise_runtime_do_not_log_fail_as_error(self):
        with mock.patch.object(utils, 'create_process') as create_process:
            create_process.return_value = FakeCreateProcess(1), 'ls'
            with mock.patch.object(utils, 'LOG') as log:
                self.assertRaises(RuntimeError, utils.execute,
                                  ['ls'], log_fail_as_error=False)
                self.assertTrue(log.debug.called)

class AgentUtilsGetInterfaceMAC(base.BaseTestCase):
    def test_get_interface_mac(self):
        expect_val = '01:02:03:04:05:06'
        with mock.patch('fcntl.ioctl') as ioctl:
            ioctl.return_value = ''.join(['\x00' * 18,
                                          '\x01\x02\x03\x04\x05\x06',
                                          '\x00' * 232])
            actual_val = utils.get_interface_mac('eth0')
        self.assertEqual(actual_val, expect_val)

class AgentUtilsReplaceFile(base.BaseTestCase):
    def test_replace_file(self):
        # make file to replace
        with mock.patch('tempfile.NamedTemporaryFile') as ntf:
            ntf.return_value.name = '/baz'
            with mock.patch('os.chmod') as chmod:
                with mock.patch('os.rename') as rename:
                    utils.replace_file('/foo', 'bar')

                    expected = [mock.call('w+', dir='/', delete=False),
                                mock.call().write('bar'),
                                mock.call().close()]

                    ntf.assert_has_calls(expected)
                    chmod.assert_called_once_with('/baz', 0o644)
                    rename.assert_called_once_with('/baz', '/foo')

class TestFindChildPids(base.BaseTestCase):

    def test_returns_empty_list_for_exit_code_1(self):
        with mock.patch.object(utils, 'execute',
                               side_effect=RuntimeError('Exit code: 1')):
            self.assertEqual(utils.find_child_pids(-1), [])

    def test_returns_empty_list_for_no_output(self):
        with mock.patch.object(utils, 'execute', return_value=''):
            self.assertEqual(utils.find_child_pids(-1), [])

    def test_returns_list_of_child_process_ids_for_good_ouput(self):
        with mock.patch.object(utils, 'execute', return_value=' 123 \n 185\n'):
            self.assertEqual(utils.find_child_pids(-1), ['123', '185'])

    def test_raises_unknown_exception(self):
        with testtools.ExpectedException(RuntimeError):
            with mock.patch.object(utils, 'execute',
                                   side_effect=RuntimeError()):
                utils.find_child_pids(-1)

redpajama_set_name: RedPajamaGithub


text:
package org.gradle.tooling;

import java.util.List;

/**
 * Thrown whenever a listener fails with an exception, which in general implies that
 * the build completed like it should, but that one of the listeners failed with an
 * exception.
 *
 * @since 2.5
 */
public class ListenerFailedException extends GradleConnectionException {
    private final List<? extends Throwable> listenerFailures;

    public ListenerFailedException(String message, List<? extends Throwable> failures) {
        super(message);
        listenerFailures = failures;
        if (!failures.isEmpty()) {
            initCause(failures.get(0));
        }
    }

    public List<? extends Throwable> getCauses() {
        return listenerFailures;
    }
}


text:
module DTK::Client
  module CLI::Command
    module Service
      subcommand_def 'set-default-target' do |c|
       c.arg Token::Arg.service_name, optional: true
        command_body c, 'set-default-context', 'Create a new service instance to refer to staged infrastructure that then can be deployed' do |sc|
          sc.flag Token.directory_path, :desc => 'Absolute or relative path to service instance directory containing updates to pull; not need if in the service instance directory'
           sc.action do |_global_options, options, args|
            service_instance = args[0]
            service_instance ||= service_instance_in_options_or_context(options)
            Operation::Service.set_default_target(:service_instance => service_instance)
          end
        end
      end
    end
  end
end


text:
package java.net;

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

/**
 * A CookieStore object represents a storage for cookie. Can store and retrieve
 * cookies.
 *
 *
{@link CookieManager} will call {@code CookieStore.add} to save cookies
 * for every incoming HTTP response, and call {@code CookieStore.get} to
 * retrieve cookie for every outgoing HTTP request. A CookieStore
 * is responsible for removing HttpCookie instances which have expired.
 *
 * @author Edward Wang
 * @since 1.6
 */
public interface CookieStore {
    /**
     * Adds one HTTP cookie to the store. This is called for every
     * incoming HTTP response.
     *
     *
A cookie to store may or may not be associated with an URI. If it
     * is not associated with an URI, the cookie's domain and path attribute
     * will indicate where it comes from. If it is associated with an URI and
     * its domain and path attribute are not specified, given URI will indicate
     * where this cookie comes from.
     *
     *
If a cookie corresponding to the given URI already exists,
     * then it is replaced with the new one.
     *
     * @param uri       the uri this cookie associated with.
     *                  if {@code null}, this cookie will not be associated
     *                  with an URI
     * @param cookie    the cookie to store
     *
     * @throws NullPointerException if {@code cookie} is {@code null}
     *
     * @see #get
     *
     */
    public void add(URI uri, HttpCookie cookie);

    /**
     * Retrieve cookies associated with given URI, or whose domain matches the
     * given URI. Only cookies that have not expired are returned.
     * This is called for every outgoing HTTP request.
     *
     * @return          an immutable list of HttpCookie,
     *                  return empty list if no cookies match the given URI
     *
     * @param uri       the uri associated with the cookies to be returned
     *
     * @throws NullPointerException if {@code uri} is {@code null}
     *
     * @see #add
     *
     */
    public List<HttpCookie> get(URI uri);

    /**
     * Get all not-expired cookies in cookie store.
     *
     * @return          an immutable list of http cookies;
     *                  return empty list if there's no http cookie in store
     */
    public List<HttpCookie> getCookies();

    /**
     * Get all URIs which identify the cookies in this cookie store.
     *
     * @return          an immutable list of URIs;
     *                  return empty list if no cookie in this cookie store
     *                  is associated with an URI
     */
    public List<URI> getURIs();

    /**
     * Remove a cookie from store.
     *
     * @param uri       the uri this cookie associated with.
     *                  if {@code null}, the cookie to be removed is not associated
     *                  with an URI when added; if not {@code null}, the cookie
     *                  to be removed is associated with the given URI when added.
     * @param cookie    the cookie to remove
     *
     * @return          {@code true} if this store contained the specified cookie
     *
     * @throws NullPointerException if {@code cookie} is {@code null}
     */
    public boolean remove(URI uri, HttpCookie cookie);

    /**
     * Remove all cookies in this cookie store.
     *
     * @return          {@code true} if this store changed as a result of the call
     */
    public boolean removeAll();
}


text:
import Tabs from './Tabs';
import Tab from './Tab';
import TabHeader from './TabHeader';
import TabContent from './TabContent';

Tabs.Tab = Tab;
Tab.Header = TabHeader;
Tab.Content = TabContent;

export default Tabs;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>What I learned about sales | Leo Lu</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

    <link href="css/clean-blog.min.css" rel="stylesheet">

        leolu.info
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
          Menu

        </button>

              Home

              Blog

              Projects

              About

What I learned about sales

Not just about hustling and getting the sale, but educating the client

              Posted by
                Leo Lu
                on September 17, 2017

In this digital age, access to information is only an arm's length away through our smartphones.

Is this bad news for salespeople? Not necessarily.

Gone are the days when sellers pushed products onto customers through exploiting their lack of information. Something as simple as a quick Google search can reveal a product's ratings, competitors, and detailed descriptions, leaving it rare for the conscious consumer to be fooled. Furthermore, in the event that a salesperson does find an easy buyer, he or she could easily be exposed on the internet as untrustworthy through customer feedback. It is thus much more difficult to profit off of a customer's lack of information on a product or service.

To effectively sell, it is crucial to educate to persuade. A knowledge-based approach on both sides, the goal is to understand the client's needs in order to provide the best product to suit them – a transparent process completely different from exploiting informational asymmetry.

Max Zheng, a licensed agent at New York Life Insurance Company, walked me through several aspects of educating how life insurance works to clients, which can be applied to many sorts of sales:

Know The Product

As a large insurance company with 172 years of history, New York Life has developed a great variety of product offerings to cater to a wide customer base. Options include term life insurance, which covers the individual for a specific period of time, as well as whole life and universal life, which are permanent. Navigating through these choices can be confusing, but luckily there are agents there to help. Max calls this "getting the maximum amount of money the customer needs at the minimum spend". Tailoring the insurance policy to the client through knowledge of every plan, he finds the right solution for every person.

Know The Customer

There is no hiding of information or shady coverings when writing policies for clients, for it's all in the algorithms of the actuaries. Policy premiums are determined based off of inputs from the customer, and Max takes into account the customer's assets, liabilities, and income in determining the amount and length of coverage of the policies. He then presents the appropriate options, with prices varying based on the level of coverage and budget.

To help me better understand what I could potentially use life insurance for as someone in my early 20's, he asked me to think about my future and what I could do to provide for my future dependents in case I were unable to. He also gave me a way of looking at it as investing for the future, pointing out that rates were cheaper at younger ages and locking in the insurability.

Develop Relationships

Life insurance is a business of trust. Insurance agents deal with confidential information in determining policy premiums, and a relationship must be developed between the agent and client. Ultimately, it is up to the customer to decide if he or she wants to purchase coverage and the agent can only do so much. What Max does is educate his clients, providing them with any information that could be helpful to them in making the decision and this way of selling helps to develop that relationship. Customers must first trust him enough to open up a dialogue, a trust strengthened through repeated interactions.

I once had a negative view of life insurance companies after applying for an internship at an agency – it felt like I was in the film "Boiler Room" with the person on the other end aggressively trying to persuade me. After being educated about the topic in a consultative manner, my view has changed. Sales should not be all about hustling, but more about educating.

I learned a good deal more about life insurance through Max educating me, and he can be reached at xzheng02@ft.nyl.com or (646)-812-4788 for his consultations.

Share via:

                      Follow Me

Copyright © Leo LL 2017


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package z6a1;

import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import static java.lang.Thread.sleep;

public class MainThread {

    public static void main(String[] args) throws Exception {
        if (args.length < 1) {
            System.out.println("Usage: java MainThread src_port");
            System.exit(0);
        }

        ServerSocket server = new ServerSocket(Integer.parseInt(args[0]));
        Socket srv = server.accept();
        System.out.print("Connection accepted");
        try (
                BufferedReader r = new BufferedReader(new InputStreamReader(srv.getInputStream(), "utf-8"));
                BufferedWriter w = new BufferedWriter(new OutputStreamWriter(srv.getOutputStream()));) {
            String line;
            while ((line = r.readLine()) != null) {
                System.out.println("Line red "+line);
                w.write(line+"\r\n");
                w.flush();
            }
        } catch (Exception ex) {
            System.err.println(ex.getMessage());
        } finally {
            System.out.print("Connection closed");
            srv.close();
        }
    }
}


text:
layout: page
title: Snow Edge Financial Award Ceremony
date: 2016-05-24
author: Vincent Vargas
tags: weekly links, java
status: published
summary: Quisque convallis sem id tellus.
banner: images/banner/office-01.jpg
booking:
  startDate: 02/07/2018
  endDate: 02/11/2018
  ctyhocn: TXKHPHX
  groupCode: SEFAC
published: true
---
Maecenas vestibulum, mi vitae efficitur molestie, nibh nulla fringilla mi, faucibus mattis odio ante accumsan mi. Phasellus consectetur, risus non iaculis semper, risus nisl bibendum neque, id malesuada lorem elit sed nisi. Integer euismod fringilla urna, a accumsan odio feugiat eu. Praesent at mi euismod, euismod risus vel, pretium leo. Etiam lectus quam, finibus a libero ut, facilisis faucibus mi. Maecenas ultricies felis ut faucibus faucibus. Nunc malesuada elit vitae nibh pretium fermentum. Vivamus luctus gravida posuere. Aliquam eget pellentesque nulla. Vivamus nec augue eros. Pellentesque non ultricies ex. Vivamus pellentesque ultricies tortor eget luctus. Vivamus gravida mi sit amet lacinia dictum. Nullam laoreet risus eu eros suscipit, vitae ornare lacus volutpat.

* Morbi sagittis nulla eu feugiat imperdiet
* Fusce fringilla nisl a arcu elementum, non accumsan libero dictum
* Curabitur sit amet justo in nibh elementum sagittis
* Pellentesque consequat arcu eget imperdiet venenatis
* Donec consequat ex eget tempus viverra.

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Integer eros elit, dignissim non tortor eget, viverra egestas libero. Vivamus convallis sit amet lectus in gravida. Proin scelerisque semper tristique. Maecenas tincidunt, tortor maximus vulputate bibendum, elit nunc euismod erat, at pretium leo ante at nisi. In sollicitudin tempor dui at tempor. Nulla at mi fringilla, finibus tellus vitae, scelerisque tortor.
Mauris non dictum diam, elementum volutpat metus. Quisque vestibulum magna ut neque sollicitudin egestas. Praesent consectetur suscipit velit, id varius justo lobortis eget. Pellentesque lobortis molestie dui at sollicitudin. Aenean fermentum lectus nec tincidunt pharetra. Donec id massa varius, malesuada justo eu, imperdiet risus. Donec eu sapien erat. Nulla facilisi.


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Golang Concurrent Server Demo</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" href="/styles/site.css">

Enter a number for which to find the maximum Collatz count:

                        <input type="text" class="form-control js-input-box" />

How many requests?

                        <select class="form-control js-request-options">
                            <option value="1">1</option>
                            <option value="10">10</option>
                            <option value="100">100</option>
                            <option value="1000">1000</option>
                        </select>

                            <input type="checkbox" class="js-goroutine-flag" />
                            Use goroutines?

                        <button class="btn btn-primary js-send-requests">Send Requests</button>


text:
.PHONY: all clean
include ../common.mk

TARGET_LDFLAGS += -Wl,-Tbootloader.ld -Wl,--Map,bootloader.map

OBJECTS := main.o start.o

all: bootloader.elf bootloader.bin bootloader.coe

bootloader.elf: $(OBJECTS)
	$(TARGET_LD) -o bootloader.elf $(TARGET_LDFLAGS) $(OBJECTS)
	$(TARGET_SIZE) bootloader.elf

clean:
	-$(RM) $(OBJECTS)
	-$(RM) bootloader.elf bootloader.bin bootloader.coe

# Object file rules:

main.o: main.c ../../potato.h
	$(TARGET_CC) -c -o $@ $(TARGET_CFLAGS) $<

start.o: ../start.S
	$(TARGET_CC) -DCOPY_DATA_TO_RAM -c -o $@ $(TARGET_CFLAGS) $<


text:
package cn.orgid.funny.config.domain.exception;

public class ApplicationException extends RuntimeException{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public ApplicationException(String msg){

		super(msg);

	}

}


text:
""" Do a sequence of checks on the parsed CNV data
"""


text:
package com.microsoft.azure.management.datafactory.v2018_06_01;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;

/**
 * A copy activity source for Sybase databases.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = SybaseSource.class)
@JsonTypeName("SybaseSource")
public class SybaseSource extends TabularSource {
    /**
     * Database query. Type: string (or Expression with resultType string).
     */
    @JsonProperty(value = "query")
    private Object query;

    /**
     * Get database query. Type: string (or Expression with resultType string).
     *
     * @return the query value
     */
    public Object query() {
        return this.query;
    }

    /**
     * Set database query. Type: string (or Expression with resultType string).
     *
     * @param query the query value to set
     * @return the SybaseSource object itself.
     */
    public SybaseSource withQuery(Object query) {
        this.query = query;
        return this;
    }

}


text:
import {createComponent as other, no} from "./local";

const Foo = other("div", {
    color: "red",
});

var nope = no();


text:
using namespace std;

int main(int argv,char ** argc)
{
	cout<<"hello world,cygwin"<<endl;
	return 0;
}


text:
/*!
 * Start Bootstrap - Creative Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

(function($) {
    "use strict"; // Start of use strict

    // jQuery for page scrolling feature - requires jQuery Easing plugin
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: ($($anchor.attr('href')).offset().top - 50)
        }, 1250, 'easeInOutExpo');
        event.preventDefault();
    });

    // Highlight the top nav as scrolling occurs
    $('body').scrollspy({
        target: '.navbar-fixed-top',
        offset: 51
    })

    // Closes the Responsive Menu on Menu Item Click
    $('.navbar-collapse ul li a').click(function() {
        $('.navbar-toggle:visible').click();
    });

    // Fit Text Plugin for Main Header
    $("h1").fitText(
        1.2, {
            minFontSize: '35px',
            maxFontSize: '65px'
        }
    );

    // Offset for Main Navigation
    $('#mainNav').affix({
        offset: {
            top: 100
        }
    })

    // Initialize WOW.js Scrolling Animations
    new WOW().init();

    // Intro text letter by letter.
    var showText = function (target, message, index, interval) {
        if (index < message.length) {
            $(target).append(message[index++]);
            setTimeout(function () { showText(target, message, index, interval); }, interval);
        }
    };
    $(window).load(function() {
        showText("#intro-text", "Sveiki užsukę ;)", 0, 90);
    });

    // Intro button on delay.
    setTimeout(function () { $('.header-content-inner a').animate({'opacity': 1}) }, 2000);

})(jQuery); // End of use strict


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<TITLE>
SPIM MIPS Simulator</TITLE>
<META http-equiv=Content-Type content="text/html; charset=iso-8859-1">
<META content="Microsoft FrontPage 6.0" name=GENERATOR>

SPIM

A MIPS32 Simulator

James Larus

larus@microsoft.com

Senior Researcher, Microsoft Research

Formerly: Professor, Computer
Sciences Department, University of Wisconsin-Madison

spim is a self-contained simulator that will run MIPS32 assembly language programs. It reads and executes assembly language
programs written for this processor. spim also provides a simple debugger and minimal set
of operating system services. spim does not execute binary
(compiled) programs.

spim implements almost the entire MIPS32 assembler-extended instruction
set. (It omits most floating point comparisons and
rounding modes
and the memory system page tables.) The MIPS architecture has several
variants that differ in various ways (e.g., the MIPS64 architecture supports 64-bit integers and addresses), which means that
spim will not run programs compiled for all types of MIPS processors. MIPS compilers also generate a number of assembler directives that
spim cannot process. These directives usually can be safely deleted.

Earlier versions of spim (before 7.0) implemented the MIPS-I
instruction set used on the MIPS R2000/R3000 computers. This architecture is
obsolete (though, has never been surpassed for its simplicity and elegance). spim now supports the more modern MIPS32 architecture, which
is the MIPS-I instruction set augmented with a large number of occasionally useful instructions. MIPS code from earlier
versions of SPIM should run without changes, except code that handles
exceptions and interrupts. This part of the architecture changed over time (and
was poorly implemented in earlier versions of spim). Code of this sort need to be updated. Examples of the
new code are in exceptions.s and
Tests/tt.io.s.

spim comes with complete source code and documentation. It also
include a torture test to verify a port to a new machine.

spim implements both a simple, terminal-style interface and a window interface. On Unix, Linux,
and Mac OS X the spim program provides a simple terminal interface and
the xspim program provides the windowing interface. On Microsoft Windows, the spim program
provides a  console interface and PCSpim provides a
Windows interface.

Downloading SPIM

    Platform
    Program
    Form
    File

    Unix or Linux system

    Mac OS X
    spim
xspim
    Source code
    http://www.cs.wisc.edu/~larus/SPIM/spim.tar.Z
      or
http://www.cs.wisc.edu/~larus/SPIM/spim.tar.gz

    Linux
    spim

    xspim
    Binary RPM for Fedora

	http://www.cs.wisc.edu/cbi/downloads/

    Microsoft Windows
(Windows  NT, 2000, XP)

    (spim 7.0 and later versions no longer run on Windows 95/98. Use version 6.5 or
    earlier.)
    spim
PCSpim
    Executable

    http://www.cs.wisc.edu/~larus/SPIM/pcspim.zip

    Source code
    http://www.cs.wisc.edu/~larus/SPIM/pcspim_src.zip

To run spim or xspim on a Unix, Linux, or
Mac OS X system, copy either the compressed
tar file (http://www.cs.wisc.edu/~larus/SPIM/spim.tar.Z)
or the gzip'ed tar file (http://www.cs.wisc.edu/~larus/SPIM/spim.tar.gz).
Both files contains source code and must be compiled for your system.

Ben Liblit of the Cooperative Bug Isolation Project
(http://www.cs.wisc.edu/cbi/)
produced a compiled version of spim for Fedora. It contains the
project's low-overhead monitoring code, which can help find bugs in spim.
If you are running Linux, this package can: save you the time and trouble of compiling
and installing spim, help find bugs, and aid an interesting
research project.

To run PCspim under Microsoft Windows, download the file

http://www.cs.wisc.edu/~larus/SPIM/pcspim.zip, unzip it, and click on setup.exe.

Source for the Microsoft Windows version (both PCspim and spim) is available separately in
the file http://www.cs.wisc.edu/~larus/SPIM/pcspim_src.zip.

There is no  Macintosh version of spim.
	However, the xspim will compiles and runs on Mac
OS X.

Installation

Microsoft Windows

Download the file

http://www.cs.wisc.edu/~larus/SPIM/pcspim.zip and save it on your machine.

Unzip the file.

Click on the setup.exe program.

Unix, Linux, or Mac OS X

(Note: the directions changed slightly for
version 7.2, to reflect a new directory structure. Please read carefully.)

Installation is a bit more complex for a Unix or Linux system, as
you need to compile the program for your particular computer and operating
system.

Download either the file http://www.cs.wisc.edu/~larus/SPIM/spim.tar.Z
      or http://www.cs.wisc.edu/~larus/SPIM/spim.tar.gz.

Decompress the file, using either the program uncompress
for the first file or gzip for the second file:

    % uncompress spim.tar.Z

or

    % gzip -d spim.tar.gz

Move the file spim.tar to the directory in which you want
to build spim and untar it:

    % tar xf spim.tar

It will create a directory named spim-7.2 (or the most recent version
number).

The simple terminal interface is contained in the
	spim-7.2/spim directory and the X-windows interfaces is in the
	spim-7.2/xspim directory. The other directories are described in
	the README file.

Next, you must set the directories in which spim will be
installed by editing the Makefile (the file that contains instructions on building
	spim).
In general, if you are installing spim and want the windowing version (xspim),
edit the file xspim/Imakefile. If you don't want xspim
or are running on a system without X-windows installed, you use the file
	spim/Makefile.

Set these pathnames to the appropriate locations for your system:

    EXCEPTION_DIR -- The full pathname of the directory
in which to install the spim exception handler (exceptions.s).

    BIN_DIR -- The full pathname of the directory
in which spim and xspim should be installed.

    MAN_DIR -- The full pathname of the directory
in which the manual pages for spim and xspim should be installed.

In general, the remaining parameters in a Makefile need not be changed.

Then, if you are using Imakefile file, change to
	the spim-7.2/xspim directory and type:

    % xmkmf
    % make

	If you do not have a copy of xmkmf, you can use the Makefile in
	the xspim directory, but beware that it may not work on your system
	because the paths to the X windows libraries could be different.

If you do not have X-windows, change to the spim-7.2/spim
	directory, edit Makefile, and type:

    %
	make

To run spim or xspim, the exception handler must be
installed in the directory specified by the variable EXCEPTION_DIR in the Makefile.
If the file exception.s is not installed, spim and xspim
fail  before they start running. You can either install this file
by hand or by typing

    % make install

which also installs
	spim or xspim, and the manual pages in the directories that
you set (above).

To test that spim is correctly built, change to the
	spim-7.2/spim directory and type:

    % make test

and examine the output of the test. (Note: the exception handler must be installed
before running the test.)

Resources

Elsevier (aka Morgan Kaufmann) has
generously provided the spim documentation (Appendix A) from the third
edition of Hennessy & Patterson,
Computer
Organization and Design: The Hardware/Software Interface. This
documentation is far more complete and  up-to-date than the documentation
included in the spim distribution. The COD documentation includes:

 Appendix A: Assemblers,
Linkers, and the SPIM Simulator (PDF). An overview
and reference manual for spim and the MIPS32 instruction set.

Getting Started with spim (PDF).
Overview of the console version of spim (both Unix and Windows).

Getting Started with xspim (PDF).
Overview of the X-windows version of spim.

Getting Starting with PCSpim
(PDF). Overview of the Microsoft Windows version of
spim.

SPIM Command-Line Options (PDF).
Overview of the command line options of spim (all versions).

The documentation included with spim is also online (as a postscript
or Adobe PDF
file). This document is for the original spim (pre-version 7.0),
which simulated the MIPS-I architecture rather than MIPS32, and so differs in
many minor aspects from the current version of spim. Appendix A of Hennessy & Patterson,
Computer
Organization and Design: The Hardware/Software Interface (above), is
more up-to-date and correct..

The best book on MIPS programming
is: Dominic Sweetman,
See
MIPS Run, Morgan Kaufmann, San Francisco, CA, 1999, ISBN
1-55860-410-3. MIPS, Inc. has excellent  free
documentation on the MIPS32 architecture on their website (registration
required):

MIPS32™ Architecture for Programmers Volume I: Introduction to the MIPS32™
Architecture v2.00 (1249 KB)

MIPS32™ Architecture for Programmers Volume II: The MIPS32™ Instruction Set
v2.00 (3258 KB)

MIPS32™ Architecture for Programmers Volume III: The MIPS32™ Privileged Resource
Architecture v2.00 (1507 KB)

An old reference manual for the MIPS architecture (including processors
subsequent to the R2000/R3000) is: Gerry Kane and Joe Heinrich, MIPS RISC
Architecture, Prentice Hall, Englewood Cliffs, N.J. 07632 ISBN 0-13-1059254.

Another good book for MIPS R2000 and R3000 programmers is: Erin Farquhar and
Philip Bunce,
The
MIPS Programmer's Handbook, Morgan Kaufmann, San Francisco, CA, 1994,
ISBN 1-55860-297-6.

The GNU C compiler can generate code
for the MIPS R3000 and can easily be used as a cross compiler. A retargeted port
of gcc is available on the MPS Resource
Page. I have not used this compiler.

Downcast Systems offers a very nice
text editor for MIPS assembly code called
MIPSter. It has syntax
highlight, MIPS-specific help, good integration with SPIM, and a number of other
features to make it easier to write assembly code. MIPSter is an inexpensive
commercial product, and it offers a limited time trial version.

Changes in Latest Version

The current version of spim is 7.3 (August 2006), which is
a minor release that cleans up a number of bugs in 7.2:

Fix for flex 2.5.33 (internal change broke spim's scanner).

Exception handler can be a semicolon-separated list of files that
will be loaded in order. On Unix, SPIM_EXCEPTION_HANDLER environment variable is
consulted before command line arguments.

Memory corruption caused spim to crash when label was defined
twice in succession.

PCSpim updates register and memory display after a parse error
while reading a file.

Eliminated unnecessary null char between strings in list of
strings produced by .asciiz.

Makefiles (in spim/ and xspim/) now contain clearly defined paths
for installing executables, exception handler, and man pages. The man pages are
no longer installed by the "make install" command.

Change psfig to epsfig in spim.tex (does anyone still use this
obsolete documentation?).

The previous version of spim is 7.2.1 (August 2005), which is
a minor release that cleans up a number of bugs in 7.1:

Fixed multiple problems in memory mapped IO in xspim and spim.
	(Note: to make programming uniform
	across all three platforms, memory mapped IO now follows"Unix" handling of
	carriage return (CR) and new line (NL) characters . On input, a CR is
	translated to a NL, and on output, a CR is printed after a NL. This was
	previously true for PCSpim and xspim, but not spim.)

Fixed bug in indexed address computation in LW and SW
	instructions.

Eliminated non-POSIX flags IUCLC and IXANY to facilitate port
	to Mac OS X.

Use termios(3) library calls instead of IOCTLs to fix bug
	introduced in port from termio to termios struct.

Test default case for jalr, without default $rd (=31).

Trap handler in test extracted wrong bits from ExcCode field
	of Cause register.

Pervasive restructuring of files to put 3 UIs (spim, xspim,
	PCSpim) in separate directories and cleanup organization and Makefiles.

Use correct help file in install process.

Added work-around for bug in flex 2.5.31 that left yytext_ptr
	undefined.

Epilogue code restored $at register, then used a pseduo
	instructions that smashed it.

Cleared filename when reinitializing PCSpim, which broke next
	reload command.

The previous version of spim is 7.1 (January 2005), which is
a minor release that cleans up a number of bugs in 7.0:

Minor cleanup.

Switched Windows installer to Microsoft .msi installer, from
	InstallShield.

exceptions.s used wrong mask for exception cause field.

Clearing the transmitter or receiver interrupt enable bits
	also clear interrupt pending bits in Cause register.

Code to poll for a console input character in X windows
	blocked and prevented any output until input occured.

Type of "mul" instruction was wrong, which lead to it being
	printed without destination register.

Print underlying instruction, not breakpoint.

Unparing error that unparsed beq as beql.

Eliminated dependence on obsolete termio.h in favor of POSIX
	termios.h since Mac OS X doesn't have termio.h any more.

Fix null pointer problem if no entries in registry.

Turn off EXL bit after break instruction, since break is
	handled by spim, not MIPS, code and the bit was never cleared.

Set default path for exceptions.s to C:\Program Files\PCSpim,
	the default installation directory.

Test for SQRT.S used double constant, which failed on SPARC
	(but not x86).

The previous version of spim is 7.0 (August 2004), which is
a major release that contains a significant number of changes from version 6.5:

Upgraded simulator to MIPS32, Version 1 architecture (except
details of FPU and memory).

Exceptions and interrupts reimplemented, to make them closer to the
actual hardware.

Memory mapped IO console reimplemented to make it work properly.

Implemented timer in CPU.

Renamed "trap" to "exception" to correspond to MIPS terminology.

Introduced short forms of command line arguments and dropped need
for "-file" argument.

Major internal cleanup and reorganization of code to eliminate
unused code and simplify implementation.

PCSpim prompts about reinitialization when file reloaded.

PCSpim lets user set font.

Word align all segment boundaries and ensure sbrk returns
word-aligned addresses.

Added new syscall (EXIT2_SYSCALL) that returns value from SPIM.

Improved implementation of delayed load instructions.

Refactored the test cases, so that endian-independent code is in
tt.core.s

Many small bug fixes.

Outstanding bugs in 7.0:

The trap handler (exceptions.s) fails when the trapping
instruction is in the delay slot of a branch or jump. The trap handler returns
by simplemindedly adding 4 to the EPC (which is the branch's address in this
case), so it does not return to the instruction executed after the trapping
instruction.

Handling of newlines and carriage returns is inconsistent between
platforms. When a program prints a newline, PCSpim also prints a carriage
return, spim and xspim don't. Or, is this consistent with the underlying
platform?

The previous version of spim is 6.5 (January 2003), which contains the
following changes from version 6.4:

If started program is started with only one argument, assume it is
a file name.

Added Alt-F4 shortcut to PCSpim.

Fixed trap.handler to return to instruction at EPC on interrupt.

Fixed (real!) hardware exception on integer overflow in division.

-trap_file did not properly parse argument in xspim.

Fixed printing of error on last line without a carriage return.

Print proper registers when printing hex FP numbers.

Properly zero newly allocated memory.

Added nops (addu $0, $0, 0) to trap handler, so that it works
properly in bare mode!

PCSPIM.HLP file was corrupted.

The previous version of spim is 6.4 (January 2002), which contains the
following changes from version 6.3:

PCSpim no longer shifts the focus of the register and data
segments when values change.

Fixed bug in the expansion of USH pseudo-op.

Add system calls for open, close, read, and write.

Fixed the Configure file to work with Mac OSX.

Made the REM pseudo-op require 3 arguments.

Fixed PCSpim dumping code to dump contents of console window.

Treat LUI's immediate value as unsigned, as it is not sign
extended.

More error checking for malformed programs.

Make symbol "main" as global.

Avoid clearing last few bytes of data segments when they expand.

Check that high-order 4 bits in jump instruction's PC match bits
in target PC.

The previous version of spim is 6.3 (January 2001), which contains the
following changes from version 6.2:

PCSpim interface simplified to 4 fixed panes, similar to xspim,
  which permit cut and paste.

PCSpim console stays on the screen after assembly program
  terminates.

Comments in assembly source displayed in text segment.

NOP is standardized to sll $0 $0 0 (= 0x00000000)

Fixed several bugs and missed optimization in computing
  immediate values in lw/sw instruction sequences.

High 2 bits in negative branch offsets were incorrect.

Display floating point registers with up to 18 digits of
  precision.

New spim command (print_all_regs) prints all registers.

Minor changes to compile spim under cygwin for Windows.

Validate the range of immediate values in MIPS (but not pseudo)
  instructions.

Fixed display of stack with non-word aligned $sp.

New flags:

-delayed-branches  Simulate MIPS delayed control
    transfers for branches, jumps, and calls

-delayed-loads Simulate MIPS non-interlocked loads.

Copyright

spim is copyrighted by James R. Larus and distributed under the
following conditions:

You may make copies of spim for your own use and modify those
  copies.

All copies of spim must retain my name and copyright notice.

You may not sell spim or distribute spim in conjunction with
  a commercial product or service without the expressed written consent of James
  Larus.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

 The DOS and Windows ports were
done by David A. Carley and are copyrighted by Morgan Kaufmann Publishers.

SPIMSAL Note

spimsal is an old version of spim that ran on PCs running Windows 3.1
and Macintoshes.
spimsal implements an extended version of the MIPS instruction set and is
based on an old version of spim. It also does NOT run under Windows 95 or
Windows NT.


text:
package com.huijimuhe.monolog.utils;

import java.text.NumberFormat;

public class NumUtils {

    public static String converNumToString(String numberStr) {
        int thousandInt = 1000;
        int number = Integer.valueOf(numberStr);
        if (number > thousandInt) {
            if (number > thousandInt * 100) {
                return new java.text.DecimalFormat("#.00").format((number / thousandInt * 10)) + "万";
            } else {
                return new java.text.DecimalFormat("#.0").format((number / thousandInt)) + "k";
            }
        }
        return String.valueOf(number);
    }
}


text:
namespace HotlineSav
{
    using System;
    using System.IO;
    using System.Text;

    class Program
    {
        static string basePath;
        static string saveFilename;
        static string unpackDirectory;

        static void Unpack()
        {
            Console.WriteLine("Creating unpack directory {0}", unpackDirectory);
            Directory.CreateDirectory(unpackDirectory);

            Console.WriteLine("Opening {0}", saveFilename);
            using (BinaryReader reader = new BinaryReader(File.Open(saveFilename, FileMode.Open)))
            {
                int version = reader.ReadByte();

                Console.WriteLine("Version {0}", version);

                uint filenameLength = reader.ReadUInt32();

                while ((filenameLength > 0) && (filenameLength != 0xDEADBEEF))
                {
                    byte[] filenameBytes = reader.ReadBytes((int)filenameLength);

                    string filename = Encoding.UTF8.GetString(filenameBytes, 0, filenameBytes.Length);

                    Console.WriteLine("working on file {0}", filename);

                    int fileLength = reader.ReadInt32();

                    byte[] fileBytes = reader.ReadBytes(fileLength);

                    using (BinaryWriter writer = new BinaryWriter(File.Open(unpackDirectory + @"\" + filename, FileMode.Create)))
                    {
                        writer.Write(fileBytes);
                    }

                    filenameLength = reader.ReadUInt32();
                }
            }
        }

        static void Pack()
        {
            string[] files = Directory.GetFiles(unpackDirectory);

            using (BinaryWriter writer = new BinaryWriter(File.Open(saveFilename, FileMode.Create)))
            {
                writer.Write((byte)1);

                foreach (string filename in files)
                {
                    byte[] filenameBytes = Encoding.UTF8.GetBytes(Path.GetFileName(filename));
                    writer.Write((uint)filenameBytes.Length);
                    writer.Write(filenameBytes);

                    using (BinaryReader reader = new BinaryReader(File.Open(filename, FileMode.Open)))
                    {
                        long length = (uint)reader.BaseStream.Length;
                        byte[] fileBytes = reader.ReadBytes((int)length);

                        writer.Write((uint)fileBytes.Length);
                        writer.Write(fileBytes);
                    }
                }

                writer.Write((uint)0xDEADBEEF);

                long position = writer.BaseStream.Position;
                long remainder = 262144 - position;

                byte[] emptyBytes = new byte[remainder];

                writer.Write(emptyBytes);
            }
        }

        static void ShowHelp()
        {
            Console.WriteLine("Hotline Miami Save Unpacker\r\n\r\nHotlineSav unpack - unpacks .sav file into unpack folder\r\nHotlineSav pack - pack unpack folder into .sav file\r\n");
        }

        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                ShowHelp();
                return;
            }

            basePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\my games\HotlineMiami";
            saveFilename = basePath + @"\SaveData.sav";
            unpackDirectory = basePath + @"\Unpack";

            switch (args[0])
            {
                case "pack": Pack(); break;
                case "unpack": Unpack(); break;
                default: ShowHelp(); break;
            }
        }
    }
}


text:
FROM golang

# Copy the local package files to the container's workspace.
ADD . /go/src/github.com/kunihiko-t/fv-mapper

# Build the app inside the container.
# (You may fetch or manage dependencies here,
# either manually or with a tool like "godep".)
RUN cd /go/src/github.com/kunihiko-t/fv-mapper && go get -t && go test ./... -v


text:
//@author xNovax
using System;
using System.Windows.Forms;
using Multi_Tool_V3.Properties;

namespace Multi_Tool_V3
{
    public partial class MinecraftUserMakerSettings : Form
    {
        private string ftpPort = ("8821");

        //Variables
        private int passwordLength = 8;

        private int passwordType;
        private string rootServerIP = ("192.168.1.1");

        public MinecraftUserMakerSettings()
        {
            InitializeComponent();
        }

        public void SaveSettings()
        {
            Settings.Default.minecraftPasswordLength = passwordLength;
            Settings.Default.minecraftPasswordType = passwordType;
            Settings.Default.minecraftUserMakerRootIP = rootServerIP;
            Settings.Default.minecraftFtpPort = ftpPort;
            Settings.Default.Save();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void ftpPortTextBox_MouseClick(object sender, MouseEventArgs e)
        {
            ftpPortTextBox.Text = ("");
        }

        private void ftpPortTextBox_TextChanged(object sender, EventArgs e)
        {
            if (ftpPortTextBox.Text != (""))
            {
                ftpPort = ftpPortTextBox.Text;
            }
        }

        private void MinecraftUserMakerSettings_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveSettings();
        }

        private void MinecraftUserMakerSettings_Load(object sender, EventArgs e)
        {
            string username = Settings.Default.username;
            usernameDisplay.Text = ("Logged in as: " + username);

            if (Settings.Default.minecraftPasswordLength != 8)
            {
                passwordLengthTextBox.Text = (Convert.ToString(Settings.Default.minecraftPasswordLength));
                passwordLength = Settings.Default.minecraftPasswordLength;
            }

            passwordTypeCombo.SelectedIndex = Settings.Default.minecraftPasswordType - 1;
            rootServerIPTextBox.Text = Settings.Default.minecraftUserMakerRootIP;
            ftpPortTextBox.Text = Settings.Default.minecraftFtpPort;
        }

        private void passwordLengthTextBox_MouseClick(object sender, MouseEventArgs e)
        {
            passwordLengthTextBox.Text = ("");
        }

        private void passwordLengthTextBox_TextChanged(object sender, EventArgs e)
        {
            if (passwordLengthTextBox.Text != (""))
            {
                passwordLength = Convert.ToInt32(passwordLengthTextBox.Text);
            }
        }

        private void passwordTypeCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (passwordTypeCombo.SelectedIndex)
            {
                case 0:
                    passwordType = 1;
                    break;

                case 1:
                    passwordType = 2;
                    break;

                case 2:
                    passwordType = 3;
                    break;

                case 3:
                    passwordType = 4;
                    break;

                default:
                    passwordType = 0;
                    break;
            }
        }

        private void rootServerIPTextBox_MouseClick(object sender, MouseEventArgs e)
        {
            rootServerIPTextBox.Text = ("");
        }

        private void rootServerIPTextBox_TextChanged(object sender, EventArgs e)
        {
            if (rootServerIPTextBox.Text != (""))
            {
                rootServerIP = rootServerIPTextBox.Text;
            }
        }

        private void saveSettingsButton_Click(object sender, EventArgs e)
        {
            SaveSettings();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveSettings();
        }
    }
}


text:
package com.siyeh.ig.style;

import com.intellij.codeInspection.CleanupLocalInspectionTool;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.lang.LanguageUtil;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class UnnecessarySemicolonInspection extends BaseInspection implements CleanupLocalInspectionTool {

  @Override
  @NotNull
  public String getDisplayName() {
    return InspectionGadgetsBundle.message(
      "unnecessary.semicolon.display.name");
  }

  @Override
  public boolean isEnabledByDefault() {
    return true;
  }

  @Override
  @NotNull
  public String buildErrorString(Object... infos) {
    return InspectionGadgetsBundle.message(
      "unnecessary.semicolon.problem.descriptor");
  }

  @Override
  public BaseInspectionVisitor buildVisitor() {
    return new UnnecessarySemicolonVisitor();
  }

  @Override
  public InspectionGadgetsFix buildFix(Object... infos) {
    return new UnnecessarySemicolonFix();
  }

  private static class UnnecessarySemicolonFix extends InspectionGadgetsFix {
    @Override
    @NotNull
    public String getFamilyName() {
      return getName();
    }

    @Override
    @NotNull
    public String getName() {
      return InspectionGadgetsBundle.message(
        "unnecessary.semicolon.remove.quickfix");
    }

    @Override
    public void doFix(Project project, ProblemDescriptor descriptor)
      throws IncorrectOperationException {
      final PsiElement semicolonElement = descriptor.getPsiElement();
      final PsiElement parent = semicolonElement.getParent();
      if (parent instanceof PsiEmptyStatement) {
        final PsiElement lastChild = parent.getLastChild();
        if (lastChild instanceof PsiComment) {
          parent.replace(lastChild);
        }
        else {
          deleteElement(parent);
        }
      }
      else {
        deleteElement(semicolonElement);
      }
    }
  }

  @Override
  public boolean shouldInspect(PsiFile file) {
    return !LanguageUtil.isInTemplateLanguageFile(file);
  }

  private static class UnnecessarySemicolonVisitor extends BaseInspectionVisitor {
    @Override
    public void visitFile(PsiFile file) {
      findTopLevelSemicolons(file);
      super.visitFile(file);
    }

    @Override
    public void visitImportList(PsiImportList list) {
      findTopLevelSemicolons(list);
      super.visitImportList(list);
    }

    private void findTopLevelSemicolons(PsiElement element) {
      for (PsiElement sibling = element.getFirstChild(); sibling != null; sibling = skipForwardWhiteSpacesAndComments(sibling)) {
        if (PsiUtil.isJavaToken(sibling, JavaTokenType.SEMICOLON)) {
          registerError(sibling, ProblemHighlightType.LIKE_UNUSED_SYMBOL);
        }
      }
    }

    @Override
    public void visitClass(@NotNull PsiClass aClass) {
      super.visitClass(aClass);

      findUnnecessarySemicolonsAfterEnumConstants(aClass);
      if (!aClass.isEnum()) {
        return;
      }
      final PsiField[] fields = aClass.getFields();
      final PsiElement element;
      if (fields.length > 0) {
        final PsiField lastField = fields[fields.length - 1];
        if (!(lastField instanceof PsiEnumConstant)) {
          return;
        }
        element = skipForwardWhiteSpacesAndComments(lastField);
      }
      else {
        final PsiElement lBrace = aClass.getLBrace();
        element = skipForwardWhiteSpacesAndComments(lBrace);
      }
      if (!(element instanceof PsiJavaToken)) {
        return;
      }
      final PsiJavaToken token = (PsiJavaToken)element;
      final IElementType tokenType = token.getTokenType();
      if (!tokenType.equals(JavaTokenType.SEMICOLON)) {
        return;
      }
      final PsiElement next = skipForwardWhiteSpacesAndComments(element);
      if (next == null || !next.equals(aClass.getRBrace())) {
        return;
      }
      registerError(element, ProblemHighlightType.LIKE_UNUSED_SYMBOL);
    }

    private void findUnnecessarySemicolonsAfterEnumConstants(
      @NotNull PsiClass aClass) {
      PsiElement child = aClass.getFirstChild();
      while (child != null) {
        if (child instanceof PsiJavaToken) {
          final PsiJavaToken token = (PsiJavaToken)child;
          final IElementType tokenType = token.getTokenType();
          if (tokenType.equals(JavaTokenType.SEMICOLON)) {
            final PsiElement prevSibling =
              skipBackwardWhiteSpacesAndComments(child);
            if (!(prevSibling instanceof PsiEnumConstant)) {
              if (prevSibling instanceof PsiJavaToken) {
                final PsiJavaToken javaToken =
                  (PsiJavaToken)prevSibling;
                final IElementType prevTokenType =
                  javaToken.getTokenType();
                if (!JavaTokenType.COMMA.equals(prevTokenType)
                    && !JavaTokenType.LBRACE.equals(
                  prevTokenType)) {
                  registerError(child, ProblemHighlightType.LIKE_UNUSED_SYMBOL);
                }
              }
              else {
                registerError(child, ProblemHighlightType.LIKE_UNUSED_SYMBOL);
              }
            }
          }
        }
        child = skipForwardWhiteSpacesAndComments(child);
      }
    }

    @Nullable
    private static PsiElement skipForwardWhiteSpacesAndComments(
      PsiElement element) {
      return PsiTreeUtil.skipSiblingsForward(element,
                                             PsiWhiteSpace.class, PsiComment.class);
    }

    @Nullable
    private static PsiElement skipBackwardWhiteSpacesAndComments(
      PsiElement element) {
      return PsiTreeUtil.skipSiblingsBackward(element,
                                              PsiWhiteSpace.class, PsiComment.class);
    }

    @Override
    public void visitEmptyStatement(PsiEmptyStatement statement) {
      super.visitEmptyStatement(statement);
      final PsiElement parent = statement.getParent();
      if (parent instanceof PsiCodeBlock) {
        final PsiElement semicolon = statement.getFirstChild();
        if (semicolon == null) {
          return;
        }
        registerError(semicolon, ProblemHighlightType.LIKE_UNUSED_SYMBOL);
      }
    }

    @Override
    public void visitResourceList(final PsiResourceList resourceList) {
      super.visitResourceList(resourceList);
      final PsiElement last = resourceList.getLastChild();
      if (last instanceof PsiJavaToken && ((PsiJavaToken)last).getTokenType() == JavaTokenType.RPARENTH) {
        final PsiElement prev = skipBackwardWhiteSpacesAndComments(last);
        if (prev instanceof PsiJavaToken && ((PsiJavaToken)prev).getTokenType() == JavaTokenType.SEMICOLON) {
          registerError(prev, ProblemHighlightType.LIKE_UNUSED_SYMBOL);
        }
      }
    }
  }
}


text:
package com.speedment.runtime.field.method;

import com.speedment.common.annotation.GeneratedCode;
import com.speedment.runtime.field.trait.HasBooleanValue;

import java.util.function.UnaryOperator;

/**
 * Represents a set-operation with all the metadata contained.
 *
 * @param <ENTITY> entity type
 * @param <D>      database type
 *
 * @author Emil Forslund
 * @since  3.0.0
 */
@GeneratedCode(value = "Speedment")
public interface SetToBoolean<ENTITY, D> extends UnaryOperator<ENTITY> {

    /**
     * Returns the field that this setter sets.
     *
     * @return the field
     */
    HasBooleanValue<ENTITY, D> getField();

    /**
     * Returns the value that this setter will set in the field when it is
     * applied.
     *
     * @return the field
     */
    boolean getValue();
}


text:
package com.chinamobile.excel;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;

import org.junit.Test;

import com.bing.excel.annotation.CellConfig;
import com.bing.excel.core.BingExcel;
import com.bing.excel.core.BingExcelBuilder;
import com.bing.excel.core.impl.BingExcelImpl.SheetVo;
import com.google.common.base.MoreObjects;

public class ReadTest {

	@Test
	public void readExcelTest() throws URISyntaxException {
		// InputStream in = Person.class.getResourceAsStream("/person.xlsx");
		URL url = Person.class.getResource("/person.xlsx");
		File f = new File(url.toURI());

		BingExcel bing = BingExcelBuilder.builderInstance();
		try {
			SheetVo<Person> vo = bing.readFile(f, Person.class, 1);
			System.out.println(vo.getSheetIndex());
			System.out.println(vo.getSheetName());
			System.out.println(vo.getObjectList());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	//ceshi
	@Test
	public void readExcelTest2() throws URISyntaxException {
		InputStream in = Person.class.getResourceAsStream("/person.xls");

		BingExcel bing = BingExcelBuilder.builderInstance();
		try {
			SheetVo<Person> vo = bing.readStream(in, Person.class, 1);
			System.out.println(vo.getSheetIndex());
			System.out.println(vo.getSheetName());
			System.out.println(vo.getObjectList());
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
	public static class Person {
		@CellConfig(index = 1)
		private int age;
		//@CellConfig(index = 0,readRequired=true)
		@CellConfig(index = 0)
		private String name;
		@CellConfig(index = 3)
		private Double salary;
		private int gongling;

		public int getGongling() {
			return gongling;
		}

		public void setGongling(int gongling) {
			this.gongling = gongling;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getAge() {
			return age;
		}

		public Double getSalary() {
			return salary;
		}

		public String toString() {
			return MoreObjects.toStringHelper(this.getClass()).omitNullValues()
					.add("name", name).add("age", age).add("salary", salary).add("gl",gongling)
					.toString();
		}
	}
}


text:
<navbar>

    Dashboard

    Add Movie

    Add User

</navbar>
<admin-dashboard-nav reports="(reports | filter:{status:'open'}).length"></admin-dashboard-nav>

    <legend>State</legend>

Open {{(reports | filter:{status:'open'}).length}}

Closed

All

    <alert type="'info'" class="text-center" ng-if="(reports | filter:{status:statusFilter}).length <= 0">
      No reports to show
    </alert>

          <media media-id="{{report.media}}"></media>
          {{report.body}}
          {{report.status}}

          <button ng-if="report.status != 'open'" class="btn btn-sm btn-primary" ng-click="updateStatus(report, 'open')">Reopen</button>
          <button ng-if="report.status != 'closed'" class="btn btn-sm btn-success" ng-click="updateStatus(report, 'closed')">Close</button>
          <button ng-if="report.status != 'discarted'" class="btn btn-sm btn-danger" ng-click="updateStatus(report, 'discarted')">Discard</button>


text:
class Qlrest < Cask
  version :latest
  sha256 :no_check

  url 'https://github.com/downloads/cluther/qlrest/QLRest.qlgenerator.zip'
  homepage 'https://github.com/cluther/qlrest'
  license :oss

  qlplugin 'QLRest.qlgenerator'
end


text:
You can run tests from the sbt console.

* To run all tests, run `test`.
* To run only one test class, run `testOnly` followed by the name of the class i.e. `testOnly my.namespace.MyTest`.
* To run only the tests that have failed, run `testQuick`.
* To run tests continually, run a command with a tilde in front, i.e. `~testQuick`.

## JUnit

The recommended test framework for Lagom is [JUnit](http://junit.org/)

@[test](code/docs/services/test/SimpleTest.java)

## Dependency

To use this feature add the following in your project's build.

```xml
<dependency>
    <groupId>com.lightbend.lagom</groupId>
    <artifactId>lagom-javadsl-testkit_2.11</artifactId>
    <version>${lagom.version}</version>
    <scope>test</scope>
</dependency>
```

In sbt:

@[testkit-dependency](code/build-service.sbt)

When using Cassandra the tests must be forked, which is enabled by adding the following in your project's build:

@[fork](code/build-service.sbt)

## How to test one service

Lagom provides support for writing functional tests for one service in isolation. The service is running in a server and in the test you can interact with it using its service client, i.e. calls to the service API. These utilities are defined in [ServiceTest](api/index.html?com/lightbend/lagom/javadsl/testkit/ServiceTest.html).

@[test](code/docs/services/test/HelloServiceTest.java)

Dependencies to other services must be replaced by stub or mock implementations by overriding the bindings of the `GuiceApplicationBuilder` in the `Setup`. If we are writing a test for the `HelloService` and that has a dependency to a `GreetingService` we must create an implementation of the `GreetingService` that can be used for the test without running the real `GreetingService`. Something like this:

@[stub](code/docs/services/test/StubDependencies.java)

Note how the dependency is overridden when constructing the test `Setup` object, which then can be used as parameter to the `withServer` method instead of the `defaultSetup()` in the above `HelloServiceTest`.

The server is by default running with [[pubsub|PubSub]], [[cluster|Cluster]] and [[persistence|PersistentEntity]] features disabled. You may want to enable cluster in the `Setup`:

@[setup2](code/docs/services/test/EnablePersistence.java)

If your service needs [[persistence|PersistentEntity]] you will need to enable it explicitly. Cassandra Persistence requires clustering, so when you enable Cassandra, cluster will also be enabled automatically. Enable Cassandra Persistence:

@[setup1](code/docs/services/test/EnablePersistence.java)

There's no way to explicitly enable or disable [[pubsub|PubSub]]. When cluster is enabled (either explicitly or transitively via enabling Cassandra), pubsub will be available.

There are two different styles that can be used when writing the tests. It is most convenient to use `withServer` as illustrated in the above `HelloServiceTest`. It automatically starts and stops the server before and after the given lambda.

When your tests have several test methods, and especially when using persistence, it is faster to only start the server once in a static method annotated with `@BeforeClass` and stop it in a method annotated with `@AfterClass`.

@[test](code/docs/services/test/AdvancedHelloServiceTest.java)

## How to test several services

Lagom will provide support for writing integration tests that involve several interacting services. This feature is [not yet implemented](https://github.com/lagom/lagom/issues/38).

## How to test streamed request/response

Let's say we have a service that have streaming request and/or response parameters. For example an `EchoService` like this:

@[echo-service](code/docs/services/test/EchoService.java)

When writing tests for that the [Akka Streams TestKit](http://doc.akka.io/docs/akka/2.4/java/stream/stream-testkit.html#Streams_TestKit) is very useful. We use the Streams TestKit together with the Lagom `ServiceTest` utilities:

@[test](code/docs/services/test/EchoServiceTest.java)

Read more about it in the documentation of the [Akka Streams TestKit](http://doc.akka.io/docs/akka/2.4/java/stream/stream-testkit.html#Streams_TestKit).

## How to test broker publishing and consuming

The section on [[Message Broker Testing|MessageBrokerTesting]] is related to Testing Services but is specific to testing the production and consumption via Brokers.

## How to test PersistentEntity

[[Persistent Entities|PersistentEntity#Unit-Testing]] can be used in the service tests described above. In addition to that you should write unit tests using the [PersistentEntityTestDriver](api/index.html?com/lightbend/lagom/javadsl/testkit/PersistentEntityTestDriver.html), which will run the `PersistentEntity` without using a database.

This is described in the documentation of [[Persistent Entity|PersistentEntity#Unit-Testing]]


text:
package io.quarkus.cli;

import picocli.AutoComplete.GenerateCompletion;
import picocli.CommandLine;

@CommandLine.Command(name = "completion", version = "generate-completion "
        + CommandLine.VERSION, header = "bash/zsh completion:  source <(${PARENT-COMMAND-FULL-NAME:-$PARENTCOMMAND} ${COMMAND-NAME})", helpCommand = true)
public class Completion extends GenerateCompletion {

}


text:
var assert = require("assert");
var path = require("path");
var rmdir = require("rimraf");
var spawn = require("child_process").spawn;
var asap = require("pdenodeify");
var fs = require("fs-extra");
var treeKill = require("tree-kill");
var fileExists = require("./file_exists");

require("steal");

var find = require("./helpers").find;
var open = require("./helpers").open;

var isWin = /^win/.test(process.platform);

function kill(pid) {
	return new Promise(function(resolve){
		treeKill(pid, undefined, function(){
			resolve();
		});
	});
}

function stealToolsC(args){
	var cli = path.resolve(__dirname + "/../bin/steal");
	args = args || [];

	if(isWin) {
		args.unshift.apply(args, ["/c", "node", cli]);
		cli = "cmd";
	}

	var child = spawn(cli, args || []);
	return child;
}

function stealTools(args){
	return new Promise(function(resolve, reject){
		var error = "";
		var child = stealToolsC(args);

		child.stderr.on("data", function(data) {
			error += data.toString();
		});

		child.on("close", function(code){
			if(code === 1) {
				return reject(error ?
					new Error(error) :
					new Error("Exited with status 1")
				);
			}
			return resolve();
		});
	});
}

describe("steal-tools cli", function () {
	this.timeout(25000);

	describe("build", function () {
		describe("basics", function () {
			beforeEach(function () {
				this.cwd = process.cwd();
				process.chdir(__dirname);
			});

			afterEach(function () {
				process.chdir(this.cwd);
			});

			it("works", function () {
				return stealTools(["build", "--config", "stealconfig.js",
					"--main", "basics/basics", "--no-minify"]);
			});

			it("uses build by default", function () {
				return stealTools(["--config", "stealconfig.js",
								  "--main", "basics/basics", "--no-minify"]);
			});
		});

		describe("without --config or --main", function () {
			this.timeout(15000);

			beforeEach(function (done) {
				this.cwd = process.cwd();
				process.chdir(path.resolve(__dirname + "/npm"));

				rmdir = asap(rmdir);
				var copy = asap(fs.copy);

				rmdir(path.join(__dirname, "npm", "node_modules"))
					.then(function () {
						return rmdir(path.join(__dirname, "npm", "dist"));
					})
					.then(function () {
						return copy(
							path.join(__dirname, "..", "node_modules", "jquery"),
							path.join(__dirname, "npm", "node_modules", "jquery")
						);
					})
					.then(done, done);
			});

			afterEach(function () {
				process.chdir(this.cwd);
			});

			it("uses package.json", function (done) {
				stealTools(["--no-minify"]).then(function () {
					open("test/npm/prod.html", function (browser, close) {
						var h1s = browser.window.document.getElementsByTagName('h1');
						assert.equal(h1s.length, 1, "Wrote H!.");
						close();
					}, done);
				});
			});
		});
	});

	describe("transform", function () {
		describe("basics", function () {
			beforeEach(function (done) {
				this.cwd = process.cwd();
				process.chdir(__dirname);

				rmdir(__dirname + "/pluginify/out.js", function (error) {
					done(error);
				});
			});

			afterEach(function () {
				process.chdir(this.cwd);
			});

			it("works", function (done) {
				var options = ["transform", "-c", "stealconfig.js", "-m",
					"pluginify/pluginify", "--out", "pluginify/out.js"];

				stealTools(options).then(function () {

					open("test/pluginify/index.html", function (browser, close) {

						find(browser, "RESULT", function (result) {
							assert(result.module.es6module, "have dependeny");
							assert(result.cjs(), "cjs");
							assert.equal(result.UMD, "works", "Doesn't mess with UMD modules");
							assert.equal(result.define, undefined, "Not keeping a global.define");
							assert.equal(result.System, undefined, "Not keeping a global.System");
							close();
						}, close);

					}, done);
				});
			});
		});
	});

	describe("live-reload", function(){
		this.timeout(30000);

		beforeEach(function () {
			this.cwd = process.cwd();
			process.chdir(__dirname);
		});

		afterEach(function () {
			process.chdir(this.cwd);
		});

		var isListening = /Live-reload server listening/;

		it.skip("logs that it is listening to stderr", function(done){
			var child = stealToolsC(["live-reload", "-c", "stealconfig.js",
									"-m", "basics/basics"]);

			child.stderr.setEncoding("utf8");
			child.stderr.on("data", function(d){
				if(isListening.test(d)) {
					child.kill();
					kill(child.pid).then(function(){
					   done();
					});
				}
			});
		});

		it.skip("fails if there is another process running on the same port",
		   function(done){
			var one = stealToolsC(["live-reload", "-c", "stealconfig.js",
									"-m", "basics/basics"]);

			one.stderr.setEncoding("utf8");
			one.stderr.on("data", function(d){
				if(isListening.test(d)) {
					startSecond();
				}
			});

			function startSecond() {
				var two = stealToolsC(["live-reload", "-c", "stealconfig.js",
									"-m", "basics/basics"]);

				two.stderr.setEncoding("utf8");
				two.stderr.on("data", function(d){
					if(/Can not start live-reload/.test(d)) {
						Promise.all([
							kill(two.pid),
							kill(one.pid)
						]).then(function(){
							done();
						});
					}
				});
			}
		});
	});

	describe("export", function() {
		this.timeout(10000);

		var distPath = path.join(
			__dirname,
			"pluginifier_builder_helpers",
			"dist"
		);

		before(copyDependencies);

		describe("with --cjs", function() {
			beforeEach(function() {
				this.cwd = process.cwd();

				process.chdir(path.join(
					__dirname,
					"pluginifier_builder_helpers"
				));

				fs.removeSync(distPath);
				return stealTools(["export", "--cjs"]);
			});

			afterEach(function() {
				process.chdir(this.cwd);
			});

			it("only outputs +cjs", function() {
				assert(fs.existsSync(path.join(distPath, "cjs")),
					"it should output cjs build");

				assert(!fs.existsSync(path.join(distPath, "amd")),
					"it should not output amd");

				assert(!fs.existsSync(path.join(distPath, "global")),
					"it should not output global-js");
			});
		});

		describe("with --amd", function() {
			beforeEach(function() {
				this.cwd = process.cwd();

				process.chdir(path.join(
					__dirname,
					"pluginifier_builder_helpers"
				));

				fs.removeSync(distPath);
				return stealTools(["export", "--amd"]);
			});

			afterEach(function() {
				process.chdir(this.cwd);
			});

			it("only outputs +amd", function() {
				assert(!fs.existsSync(path.join(distPath, "cjs")),
					"it should not output cjs");

				assert(!fs.existsSync(path.join(distPath, "global")),
					"it should not output global-js");
			});
		});

		function copyDependencies(done) {
			var prmdir = asap(rmdir);
			var pcopy = asap(fs.copy);

			var srcModulesPath = path.join(__dirname, "..", "node_modules");
			var destModulesPath = path.join(
				__dirname,
				"pluginifier_builder_helpers",
				"node_modules"
			);

			prmdir(destModulesPath)
				.then(function() {
					return pcopy(
						path.join(srcModulesPath,"jquery"),
						path.join(destModulesPath, "jquery")
					);
				})
				.then(function() {
					return pcopy(
						path.join(srcModulesPath, "cssify"),
						path.join(destModulesPath, "cssify")
					);
				})
				.then(function() {
					return pcopy(
						path.join(srcModulesPath, "steal-less"),
						path.join(destModulesPath, "steal-less")
					);
				})
				.then(function() {
					return pcopy(
						path.join(srcModulesPath, "steal-css"),
						path.join(destModulesPath, "steal-css")
					);
				})
				.then(function() {
					done();
				})
				.catch(function(error) {
					done(error);
				});
		}
	});

	describe("optimize", function() {
		this.timeout(10000);

		it("works", function() {
			var cwd = process.cwd();
			var base = path.join(__dirname, "slim", "worker", "single");

			process.chdir(base);

			return asap(rmdir)(path.join(base, "dist"))
				.then(function() {
					return stealTools([
						"optimize",
						"--config", "stealconfig.js",
						"--main", "main",
						"--no-minify",
						"--target", "web", "worker"
					]);
				})
				.then(function() {
					var bundles = path.join(base, "dist", "bundles");

					return Promise.all([
						fileExists(path.join(bundles, "worker", "main.js")),
						fileExists(path.join(bundles, "web", "main.js"))
					]);
				})
				.then(function() {
					process.chdir(cwd);
				});
		});

		it("'target' should be optional", function() {
			var cwd = process.cwd();
			var base = path.join(__dirname, "slim", "worker", "single");

			process.chdir(base);

			return asap(rmdir)(path.join(base, "dist"))
				.then(function() {
					return stealTools([
						"optimize",
						"--config", "stealconfig.js",
						"--main", "main",
						"--no-minify"
					]);
				})
				.then(function() {
					var bundles = path.join(base, "dist", "bundles");
					return fileExists(path.join(bundles, "main.js"));
				})
				.then(function() {
					process.chdir(cwd);
				});
		});
	});

	it("throws if an unknown 'target' is passed in", function(done) {
		var cwd = process.cwd();
		var base = path.join(__dirname, "slim", "worker", "single");

		process.chdir(base);

		asap(rmdir)(path.join(base, "dist"))
			.then(function() {
				return stealTools([
					"optimize",
					"--config", "stealconfig.js",
					"--main", "main",
					"--no-minify",
					"--target", "foo"
				]);
			})
			.then(
				function() {
					assert(false, "command should not succeed");
				},
				function(error) {
					process.chdir(cwd);
					assert(
						/Cannot create slim build, target/.test(error.message),
						"should throw a descriptive error message"
					);
				}
			)
			.then(done, done);
	});
});