text:
Ohai.plugin(:Virtualbox) do
  depends "virtualization"
  provides "virtualbox"

  # query virtualbox for each configured vm, as well as
  # each guest's individual configuration settings
  def vboxmanage_list_vms
    vms = Mash.new
    so_cmd = "VBoxManage list --sorted vms"
    logger.trace(so_cmd)
    so = shell_out(so_cmd)

    if so.exitstatus == 0
      # parse the output
      so.stdout.lines.each do |line|
        case line
        when /^"(\S*)" \{(\S*)\}$/
          name = Regexp.last_match(1)
          uuid = Regexp.last_match(2)
          vms[name] = vboxmanage_vminfo(uuid)
        end
      end
    end
    vms
  rescue Ohai::Exceptions::Exec
    logger.trace("Plugin VboxHost: Could not run 'VBoxManage list --sorted vms'. Skipping data")
  end

  # query the vminfo for particular guest instance, normalizing
  # the fields so that they're not enclosed in double-quotes (")
  def vboxmanage_vminfo(machine_id)
    vm = Mash.new

    so_cmd = "VBoxManage showvminfo #{machine_id} --machinereadable"
    logger.trace(so_cmd)
    so = shell_out(so_cmd)

    if so.exitstatus == 0
      so.stdout.lines.each do |line|
        line.chomp!
        left, right = line.split("=")

        # remove enclosing quotes, if needed
        key = left.delete_prefix('"').delete_suffix('"')

        # skip the name attribute since that is the parent key
        next if key == "name"

        vm[key.downcase] = right.delete_prefix('"').delete_suffix('"')
      end
    end
    vm
  rescue Ohai::Exceptions::Exec
    logger.trace("Plugin VboxHost: Could not run '#{so_cmd}'. Skipping data")
  end

  # query virtualbox for a list of #{query_type} items
  # these queries return a result set that is delimited by
  # multiple successive newlines, with each block containing
  # key/value pairs delimited by a colon (:) and column aligned
  #
  # the keys of each k/v pair are normalized to lowercase
  def vboxmanage_list_blocks(query_type, name_key)
    # ignore unrecognized query type
    supported_queries = %w{
      bridgedifs dhcpservers dvds hdds hostdvds
      hostfloppies hostonlyifs natnets
    }
    return nil unless supported_queries.include? query_type

    results = Mash.new

    so_cmd = "VBoxManage list --sorted #{query_type}"
    logger.trace(so_cmd)
    so = shell_out(so_cmd)
      # raise an exception if the command fails
      # so.error!

    if so.exitstatus == 0
      # break the result into paragraph blocks, on successive newlines
      so.stdout.each_line("") do |blk|
        # remove the multiple newlines of each record
        blk.chomp!.chomp!
        # initialize a blank record hash
        record = Mash.new
        # parse the record block into key/value pairs
        blk.each_line do |line|
          next unless line.include? ":"

          # split the line into key/value pair
          key, right = line.split(":", 2)

          # strip the leading/trailing whitespace if the value is not nil
          value = right.nil? ? "" : right.strip
          record[key.downcase] = value
        end

        # insert the record into the list of results
        if record.key? name_key.downcase
          name = record.delete(name_key.downcase)
          results[name] = record
        end
      end
    end
    results
  rescue Ohai::Exceptions::Exec
    logger.trace("Plugin VboxHost: Could not run '#{so_cmd}'. Skipping data")
  end

  collect_data(:default) do
    case virtualization.dig("systems", "vbox")
    when "guest"
      logger.trace("Plugin Virtualbox: Node detected as vbox guest. Collecting guest data.")
      begin
        so = shell_out("VBoxControl guestproperty enumerate")

        if so.exitstatus == 0
          virtualbox Mash.new
          virtualbox[:host] = Mash.new
          virtualbox[:guest] = Mash.new
          so.stdout.lines.each do |line|
            case line
            when /LanguageID, value: (\S*),/
              virtualbox[:host][:language] = Regexp.last_match(1)
            when /VBoxVer, value: (\S*),/
              virtualbox[:host][:version] = Regexp.last_match(1)
            when /VBoxRev, value: (\S*),/
              virtualbox[:host][:revision] = Regexp.last_match(1)
            when %r{GuestAdd/VersionExt, value: (\S*),}
              virtualbox[:guest][:guest_additions_version] = Regexp.last_match(1)
            when %r{GuestAdd/Revision, value: (\S*),}
              virtualbox[:guest][:guest_additions_revision] = Regexp.last_match(1)
            end
          end
        end
      rescue Ohai::Exceptions::Exec
        logger.trace('Plugin Virtualbox: Could not execute "VBoxControl guestproperty enumerate". Skipping data collection.')
      end
    when "host"
      logger.trace("Plugin Virtualbox: Node detected as vbox host. Collecting host data.")
      virtualbox Mash.new
      begin
        # get a list of virtualbox guest vms
        virtualbox["guests"] = vboxmanage_list_vms

        # get a list of virtualbox virtual hard disk drives
        virtualbox["hdds"] = vboxmanage_list_blocks("hdds", "Location")

        # get a list of virtualbox virtual dvd drives
        virtualbox["dvds"] = vboxmanage_list_blocks("dvds", "Location")

        # get a list of virtualbox host dvd drives
        virtualbox["hostdvds"] = vboxmanage_list_blocks("hostdvds", "Name")

        # get a list of virtualbox host floppy drives
        virtualbox["hostfloppies"] = vboxmanage_list_blocks("hostfloppies", "Name")

        # get a list of virtualbox hostonly network interfaces
        virtualbox["hostonlyifs"] = vboxmanage_list_blocks("hostonlyifs", "Name")

        # get a list of virtualbox bridged network interfaces
        virtualbox["bridgedifs"] = vboxmanage_list_blocks("bridgedifs", "Name")

        # get a list of virtualbox dhcp servers
        virtualbox["dhcpservers"] = vboxmanage_list_blocks("dhcpservers", "NetworkName")

        # get a list of virtualbox nat networks
        virtualbox["natnets"] = vboxmanage_list_blocks("natnets", "NetworkName")
      rescue Ohai::Exceptions::Exec
        logger.trace("Plugin VboxHost: Could not collect data for VirtualBox host. Skipping data")
      end
    else
      logger.trace("Plugin Virtualbox: Not on a Virtualbox host or guest. Skipping plugin.")
    end
  end
end


text:
/*
 GET login page
 */
exports.loginForm = function (req, res) {
    if (req.session.login) {
        res.redirect('/');
    }
    else {
        res.render('login', {
            title: 'Login'
        });
    }

};

/*
 logout (destroy session)
 */
exports.destroy = function (req, res) {
    req.session.login = null;
    req.session.destroy();
    res.redirect('/');
};

/*
 POST login page (for user authentication)
 */
exports.attemptLogin = function (req, res) {

    db.User.login(req.body.username, req.body.password)
        .then(function (user) {
            req.session.login = user;
            res.redirect('/feed');
        }, function (reason) {
            req.flash('errors', {login: [reason.message]});
            res.redirect('/sessions/new');
        })
        .catch(function (err) {
            console.log(err);
            req.flash('errors', {serverError: ['Server Error! Please contact an administrator.']});
            res.redirect(500, '/sessions/new');
        });
};

redpajama_set_name: RedPajamaGithub


text:
package org.kaaproject.kaa.server.transports.http.transport.netty;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.kaaproject.kaa.common.avro.AvroByteArrayConverter;
import org.kaaproject.kaa.server.transport.GenericTransportContext;
import org.kaaproject.kaa.server.transport.TransportContext;
import org.kaaproject.kaa.server.transport.TransportProperties;
import org.kaaproject.kaa.server.transport.http.config.gen.AvroHttpConfig;
import org.kaaproject.kaa.server.transport.message.MessageHandler;
import org.kaaproject.kaa.server.transport.message.SessionInitMessage;
import org.kaaproject.kaa.server.transport.session.SessionAware;
import org.kaaproject.kaa.server.transports.http.transport.HttpTransport;
import org.kaaproject.kaa.server.transports.http.transport.commands.SyncCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * NettyHttpServerIT Class to test Netty HTTP Server, using serious of http
 * requests to check validity of transmission.
 *
 * @author Andrey Panasenko <apanasenko@cybervisiontech.com>
 *
 */
public class NettyHttpServerIT {

    /** The Constant logger. */
    private static final Logger LOG = LoggerFactory.getLogger(NettyHttpServerIT.class);

    /** Port which used to bind to for Netty HTTP */
    public static final String TEST_HOST = "localhost";

    /** Port which used to bind to for Netty HTTP */
    public static final int TEST_PORT = 9193;

    /** Max HTTP request size which used in Netty framework */
    public static final int MAX_HTTP_REQUEST_SIZE = 65536;

    private static ExecutorService executor = null;

    private static HttpTransport netty;

    /**
     * Inits the.
     *
     * @throws Exception
     *             the exception
     */
    @BeforeClass
    public static void init() throws Exception {
        executor = Executors.newFixedThreadPool(5);
        netty = new HttpTransport();
    }

    /**
     * After.
     *
     * @throws Exception
     *             the exception
     */
    @AfterClass
    public static void after() throws Exception {
        executor.shutdown();
    }

    /**
     * Before test.
     *
     * @throws Exception
     */
    @Before
    public void beforeTest() throws Exception {
        GenericTransportContext context = new GenericTransportContext(new TransportContext(new TransportProperties(new Properties()), null,
                new MessageHandler() {

                    @Override
                    public void process(SessionInitMessage message) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void process(SessionAware message) {
                        // TODO Auto-generated method stub

                    }
                }), getTestConfig());
        netty.init(context);
        netty.start();
    }

    /**
     * After test.
     *
     * @throws Exception
     *             the exception
     */
    @After
    public void afterTest() throws Exception {
        netty.stop();
    }

    /**
     * Test on incorrect URL
     */
    @Test
    public void testIncorrectRequest() {
        LOG.info("Test Incorrect request");
        PostParameters params = new PostParameters();
        // Incorrect command name
        String commandName = "test";
        try {
            final HttpTestClient client = new HttpTestClient(params, new HttpActivity() {

                @Override
                public void httpRequestComplete(IOException ioe, Map<String, List<String>> header, String body) {
                    assertNotNull(ioe);
                    LOG.info("Test complete, Error 500 got.");
                }
            }, commandName);
            executor.execute(client);
            Thread.sleep(100);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            fail(e.toString());
        }
    }

    /**
     * Test on incorrect HTTP method
     */
    @Test
    public void testIncorrectMethod() {
        LOG.info("Test Incorrect Method request");
        try {
            URLConnection connection = new URL("http://" + TEST_HOST + ":" + TEST_PORT + "/domain/" + SyncCommand.getCommandName())
                    .openConnection();
            StringBuffer b = new StringBuffer();
            InputStreamReader r = new InputStreamReader(connection.getInputStream(), "UTF-8");
            int c;
            while ((c = r.read()) != -1) {
                b.append((char) c);
            }
            fail("Exception not cauth");
        } catch (IOException e) {
            assertNotNull(e);
            if (!e.toString().contains("HTTP response code: 400 for URL")) {
                fail(e.toString());
            } else {
                LOG.info("Test for incorrect method pass");
            }
        }
    }

    private byte[] getTestConfig() throws IOException {
        AvroHttpConfig config = new AvroHttpConfig();
        config.setBindInterface(TEST_HOST);
        config.setBindPort(TEST_PORT);
        config.setPublicInterface(TEST_HOST);
        config.setPublicPort(TEST_PORT);
        config.setMaxBodySize(MAX_HTTP_REQUEST_SIZE);
        AvroByteArrayConverter<AvroHttpConfig> converter = new AvroByteArrayConverter<AvroHttpConfig>(AvroHttpConfig.class);
        return converter.toByteArray(config);
    }
}


text:
package tw.com.integration;

import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;
import tw.com.EnvironmentSetupForTests;
import tw.com.providers.CFNClient;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public class TestHaveValidTemplateFiles {

	@Before
	public void beforeTestsRun() {
	}

	@Test
	public void testAllTestCfnFilesAreValid() throws InterruptedException {
		software.amazon.awssdk.services.cloudformation.CloudFormationClient cfnClient = EnvironmentSetupForTests.createCFNClient();
		CFNClient cloudClient = new CFNClient(cfnClient);
		File folder = new File("src/cfnScripts");

		assertTrue(folder.exists());
		validateFolder(cloudClient, folder);
	}

	private void validateFolder(CFNClient cloudClient, File folder) throws InterruptedException
	{
		File[] files = folder.listFiles();
		for(File file : files) {
			if (file.isDirectory()) {
				validateFolder(cloudClient, file);
			} else
			{
				if (!file.isHidden()) {
                    try {
                        String contents = FileUtils.readFileToString(file, Charset.defaultCharset());
                        cloudClient.validateTemplate(contents);
                    } catch (IOException | CloudFormationException e) {
                        fail(file.getAbsolutePath() + ": " + e);
                    }
                }

				Thread.sleep(200); // to avoid rate limit errors on AWS api
			}
		}
	}

}


text:
alias cdtv="cd $PWD"

RANGE_V3_INSTALL_PATH="$HOME/src/range-v3-trunk"
export RANGE_V3_INSTALL_PATH


text:
__author__ = 'hujin'

import json

from twisted.internet import reactor
from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET
from twisted.python.failure import Failure

"""
API

GET /services      Get a list of services
GET /services/:id  Get information of a service
PUT /services/:id  Run or Stop a service

"""

class BaseResource(Resource):

    def __init__(self, application):
        """
        :param application:dockerman.application.Application
        :return:
        """
        self.application = application
        Resource.__init__(self)

    def render(self, request):
        content_type = request.getHeader('Content-Type')
        if request.method != 'GET' and not content_type.startswith('application/json'):
            request.setResponseCode(400)
            return 'Invalid Request'
        else:
            return Resource.render(self, request)

    def handle_deferred(self, d, request, code_on_success=200):
        def done(result):
            if isinstance(result, Failure):
                request.write(result.getTraceback())
            else:
                request.setResponseCode(code_on_success)
                request.write(json.dumps(result))
            request.finish()

        d.addBoth(done)

class Root(BaseResource):

    def __init__(self, application):
        BaseResource.__init__(self, application)

        self.putChild('services', ServiceList(self.application))
        self.putChild('events', EventList(self.application))
        self.putChild('images', ImageList(self.application))

class ServiceList(BaseResource):

    def getChild(self, path, request):
        return Service(self.application, path)

    def render_GET(self, request):
        services = self.application.store.get_all()
        return json.dumps(services)

    def render_POST(self, request):
        """
        :type request: twisted.web.server.Request
        """
        definition = json.load(request.content)

        d = self.application.manager.create_service(definition)

        self.handle_deferred(d, request, code_on_success=201)

        return NOT_DONE_YET

class Service(BaseResource):

    def __init__(self, application, _id):
        self.id = _id
        BaseResource.__init__(self, application)

    def render_GET(self, request):
        d = self.application.manager.get_service(self.id)

        self.handle_deferred(d, request, code_on_success=200)

        return NOT_DONE_YET

    def render_PUT(self, request):
        """
        :type request: twisted.web.server.Request
        :return:
        """
        command = json.load(request.content)

        if 'status' not in command:
            request.setResponseCode(400)
            return 'Missing required status field'

        if command['status'] not in ['running', 'stopped']:
            request.setResponseCode(400)
            return 'The status: %s is invalid' % str(command['status'])

        if command['status'] == 'running':
            d = self.application.manager.start_service(self.id)
        else:
            d = self.application.manager.stop_service(self.id)

        self.handle_deferred(d, request, code_on_success=200)

        return NOT_DONE_YET

class EventList(BaseResource):

    def render_GET(self, request):
        return "<html>Hello, GET /events!</html>"

class ImageList(BaseResource):

    def getChild(self, path, request):
        return Image(self.application, path)

    def render_POST(self, request):
        data = json.load(request.content)

        d = self.application.client.pull_image(**data)
        self.handle_deferred(d, request, code_on_success=201)
        return NOT_DONE_YET

class Image(BaseResource):

    def render_GET(self, request):
        return ''


text:
package org.uiautomation.ios.drivers;

import org.openqa.selenium.remote.SessionId;
import org.uiautomation.ios.ServerSideSession;
import org.uiautomation.ios.instruments.ApplicationCrashedOnStartException;
import org.uiautomation.ios.instruments.commandExecutor.UIAutomationCommandExecutor;
import org.uiautomation.ios.instruments.Instruments;
import org.uiautomation.ios.instruments.TakeScreenshotService;
import org.uiautomation.ios.instruments.InstrumentsFailedToStartException;

import java.net.URL;
import java.util.logging.Logger;

public class RemoteIOSNativeDriver extends ServerSideNativeDriver {

  private final Instruments instruments;
  private static final Logger log = Logger.getLogger(RemoteIOSNativeDriver.class.getName());

  public RemoteIOSNativeDriver(URL url, ServerSideSession session,Instruments impl) {
    super(url, new SessionId(session.getSessionId()));
    this.instruments = impl;
  }

  public void start(long timeOut) throws InstrumentsFailedToStartException, ApplicationCrashedOnStartException {
    try {
      instruments.start(timeOut);
    } catch (InstrumentsFailedToStartException|ApplicationCrashedOnStartException e) {
      stop();
      throw e;
    }
  }

  public void stop() {
    instruments.stop();
  }

  public UIAutomationCommandExecutor communication() {
    return instruments.getChannel();
  }

  public TakeScreenshotService getScreenshotService() {
    return instruments.getScreenshotService();
  }

  public Instruments getInstruments() {
    return instruments;
  }
}


text:
package com.thinkgem.jeesite.modules.weixin.service;

import java.util.Date;
import java.util.List;

import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.modules.weixin.vo.ReceiveMsgPlain;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.modules.weixin.entity.WeixinMsg;
import com.thinkgem.jeesite.modules.weixin.dao.WeixinMsgDao;

/**
 * 所有微信的消息收发表Service
 * @author mawj
 * @version 2016-10-28
 */
@Service
@Transactional(readOnly = true)
public class WeixinMsgService extends CrudService<WeixinMsgDao, WeixinMsg> {

	public WeixinMsg get(String id) {
		return super.get(id);
	}

	public List<WeixinMsg> findList(WeixinMsg weixinMsg) {
		return super.findList(weixinMsg);
	}

	public Page<WeixinMsg> findPage(Page<WeixinMsg> page, WeixinMsg weixinMsg) {
		return super.findPage(page, weixinMsg);
	}

	@Transactional(readOnly = false)
	public void save(WeixinMsg weixinMsg) {
		super.save(weixinMsg);
	}

	@Transactional(readOnly = false)
	public void delete(WeixinMsg weixinMsg) {
		super.delete(weixinMsg);
	}

	@Transactional(readOnly = false)
	public void save(ReceiveMsgPlain msgPlain){
		WeixinMsg msg = new WeixinMsg();

		msg.setToUserName(msgPlain.getToUserName());
		msg.setContent(msgPlain.getContent());
		try{
			msg.setCreateTime(new Date(Long.parseLong(msgPlain.getCreateTime())*1000));
		}catch (Exception e){}

		msg.setDescription(msgPlain.getDescription());
		msg.setFormat(msgPlain.getFormat());
		msg.setFromUserName(msgPlain.getFromUserName());
		msg.setLabel(msgPlain.getLabel());
		msg.setLocationX(msgPlain.getLocation_X());
		msg.setLocationY(msgPlain.getLocation_Y());
		msg.setMediaId(msgPlain.getMediaId());
		msg.setMsgType(msgPlain.getMsgType());
		msg.setMsgId(msgPlain.getMsgId());
		msg.setPicUrl(msgPlain.getPicUrl());
		msg.setScale(msgPlain.getScale());
		msg.setTitle(msgPlain.getTitle());
		msg.setUrl(msgPlain.getUrl());
		save(msg);
	}
}


text:
require "dropbox_sdk"

module Dragonfly
  class DropboxDataStore
    module Rake
      extend self

      def authorize(app_key, app_secret, access_type)
        session = create_new_session(app_key, app_secret)

        puts "Visit this URL: #{session.get_authorize_url}"
        print "And after you approved the authorization confirm it here (y/n): "

        assert_answer!
        session.get_access_token
        dropbox_client = DropboxClient.new(session, access_type)
        account_info = dropbox_client.account_info

        puts <<-MESSAGE

Authorization was successful. Here you go:

access_token: #{session.access_token.key}
access_token_secret: #{session.access_token.secret}
user_id: #{account_info["uid"]}
        MESSAGE
      end

      def create_new_session(app_key, app_secret)
        DropboxSession.new(app_key, app_secret)
      end

      def assert_answer!
        answer = STDIN.gets.strip
        exit if answer == "n"
      end
    end
  end
end


text:
namespace Nest
{
	public partial interface ICatSnapshotsRequest { }

	public partial class CatSnapshotsRequest { }

	public partial class CatSnapshotsDescriptor { }
}


text:
package org.apache.geronimo.console.configcreator.configData;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashSet;

import javax.portlet.PortletRequest;

import org.apache.geronimo.j2ee.deployment.WebModule;
import org.apache.openejb.jee.JndiConsumer;
import org.apache.geronimo.xbeans.geronimo.security.GerSecurityType;
import org.apache.geronimo.xbeans.geronimo.web.GerWebAppDocument;
import org.apache.geronimo.xbeans.geronimo.web.GerWebAppType;
import org.apache.xmlbeans.XmlOptions;

/**
 *
 * @version $Rev$ $Date$
 */
public class WARConfigData {
    private GerWebAppType webApp = GerWebAppType.Factory.newInstance();

    private EnvironmentConfigData environmentConfig;

    private JndiRefsConfigData jndiRefsConfig;

    private MessageDestinationConfigData messageDestinationConfig;

    private SecurityConfigData securityConfig;

    private String uploadedWarUri;

    private String deploymentPlan;

    public void parseWeb(WebModule module) {
        environmentConfig = new EnvironmentConfigData(getWebApp().addNewEnvironment());
        environmentConfig.parseEnvironment(module.getEnvironment());
        getWebApp().setContextRoot(getWebApp().getEnvironment().getModuleId().getArtifactId());

        parseReferences(module.getSpecDD());
        parseSecurity(module.getSpecDD());
    }

    public void parseReferences(JndiConsumer annotatedApp) {
        jndiRefsConfig = new JndiRefsConfigData();
        jndiRefsConfig.parseWebDD(annotatedApp, webApp);
        messageDestinationConfig = new MessageDestinationConfigData();
        messageDestinationConfig.parseWebDD(annotatedApp, webApp);
    }

    public void parseSecurity(JndiConsumer annotatedApp) {
        securityConfig = new SecurityConfigData();
        securityConfig.parseWebDD(annotatedApp);
    }

    public void readEnvironmentData(PortletRequest request) {
        getWebApp().setContextRoot(request.getParameter("contextRoot"));
        environmentConfig.readEnvironmentData(request);
    }

    public void readReferencesData(PortletRequest request) {
        jndiRefsConfig.readReferencesData(request, getWebApp());
        messageDestinationConfig.readReferencesData(request, getWebApp());
    }

    public void readSecurityData(PortletRequest request) {
        getWebApp().setSecurityRealmName(request.getParameter("securityRealmName"));
        securityConfig.readSecurityData(request);
    }

    public HashSet<String> consolidateDependencies() {
        HashSet<String> deps = environmentConfig.getDependenciesSet();
        deps.addAll(jndiRefsConfig.getDependenciesSet());
        deps.addAll(messageDestinationConfig.getDependenciesSet());
        deps.addAll(securityConfig.getDependenciesSet());
        return deps;
    }

    public String createDeploymentPlan() throws IOException {
        environmentConfig.storeDependencies();
        jndiRefsConfig.storeResourceRefs(getWebApp());
        if (securityConfig.getSecurity() != null) {
            getWebApp().setSecurity(securityConfig.getSecurity());
        }

        GerWebAppDocument webAppDocument = GerWebAppDocument.Factory.newInstance();
        webAppDocument.setWebApp(getWebApp());
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        XmlOptions options = new XmlOptions();
        options.setSavePrettyPrint();
        options.setSavePrettyPrintIndent(4);
        options.setUseDefaultNamespace();
        webAppDocument.save(outputStream, options);
        outputStream.close();
        deploymentPlan = new String(outputStream.toByteArray(), "US-ASCII");
        return deploymentPlan;
    }

    public GerWebAppType getWebApp() {
        return webApp;
    }

    public EnvironmentConfigData getEnvironmentConfig() {
        return environmentConfig;
    }

    public JndiRefsConfigData getJndiRefsConfig() {
        return jndiRefsConfig;
    }

    public GerSecurityType getSecurity() {
        return securityConfig.getSecurity();
    }

    public boolean isReferenceNotResolved() {
        return jndiRefsConfig.isReferenceNotResolved() || messageDestinationConfig.isReferenceNotResolved();
    }

    public void setUploadedWarUri(String uploadedWarUri) {
        this.uploadedWarUri = uploadedWarUri;
    }

    public String getUploadedWarUri() {
        return uploadedWarUri;
    }

    public String getDeploymentPlan() {
        return deploymentPlan;
    }

    public void setDeploymentPlan(String deploymentPlan) {
        this.deploymentPlan = deploymentPlan;
    }

    public boolean needsResolveReferences() {
        if (getWebApp().getEjbRefArray().length > 0 || getWebApp().getEjbLocalRefArray().length > 0
                || getWebApp().getServiceRefArray().length > 0 || getWebApp().getResourceEnvRefArray().length > 0
                || getJndiRefsConfig().getJdbcPoolRefs().size() > 0
                || getJndiRefsConfig().getJavaMailSessionRefs().size() > 0
                || getJndiRefsConfig().getJmsConnectionFactoryRefs().size() > 0) {
            return true;
        }
        return false;
    }
}


text:
using System.Threading.Tasks;
using QuizApp.Core.Enums;
using QuizApp.Core.POs;

namespace QuizApp.Core.Services
{
	public interface IQuestionsService
	{
		Task<QuestionPO> GetQuestionAsync(int categoryId, QuestionDifficulty difficulty);
		Task PrefetchQuestions(int categoryId);
		Task WipeMemoryAsync();
	}
}


text:
import java.awt.*;

public class ServerDemo extends Helper {

// a slot to hold an arbitrary object pointer that can
// be filled in by the app. and referenced in actions
public Object arg;

public Label label_1;
public TextField password;
public Label label_2;
public TextField entry_2;
public Button button_1;
public TextField result;

//methods to support form introspection
public static String names[] = {
	"label_1","password","label_2","entry_2","button_1","result",
};
public String[] getNames() {
	return names;
}

//There should be an easier way to do this
public Object[] getWidgets() {
	Object[] list = new Object[6];
	list[0] = label_1;
	list[1] = password;
	list[2] = label_2;
	list[3] = entry_2;
	list[4] = button_1;
	list[5] = result;
	return list;
}

// Application specific widget data
private static String datatype_private[] = {
	null, null, null, null, null, null,
};
public String[] datatype() {
	return datatype_private;
}

private static String writeAccess_private[] = {
	"", "", "", "", "", "",
};
public String[] writeAccess() {
	return writeAccess_private;
}

private static String appletParams_private[] = {
	null, null, null, null, null, null,
};
public String[] appletParams() {
	return appletParams_private;
}

private static String helpURL_private[] = {
	"", "", "", "", "", "",
};
public String[] helpURL() {
	return helpURL_private;
}

public void init() {

	// main panel
	GridBagLayout grid = new GridBagLayout();
	int rowHeights[] = {0,30,30,30};
	int columnWidths[] = {0,30,30};
	double rowWeights[] = {0.0,0.0,0.0,0.0};
	double columnWeights[] = {0.0,0.0,0.0};
	grid.rowHeights = rowHeights;
	grid.columnWidths = columnWidths;
	grid.rowWeights = rowWeights;
	grid.columnWeights = columnWeights;

	label_1 = new Label();
	label_1.setText("Enter password");
	this.add(label_1);

	password = new TextField(20);
	password.setEchoCharacter('*');
	this.add(password);

	label_2 = new Label();
	label_2.setText("Sensitive data");
	this.add(label_2);

	entry_2 = new TextField(20);
	this.add(entry_2);

	button_1 = new Button();
	button_1.setLabel("compute");
	this.add(button_1);

	result = new TextField(64);
	result.setFont(new Font("Helvetica",Font.PLAIN , 12));
	this.add(result);

	// Geometry management
	GridBagConstraints con = new GridBagConstraints();
	reset(con);
	con.gridx = 1;
	con.gridy = 1;
	con.anchor = GridBagConstraints.CENTER;
	con.fill = GridBagConstraints.NONE;
	grid.setConstraints(label_1, con);

	reset(con);
	con.gridx = 2;
	con.gridy = 1;
	con.anchor = GridBagConstraints.WEST;
	con.fill = GridBagConstraints.NONE;
	grid.setConstraints(password, con);

	reset(con);
	con.gridx = 1;
	con.gridy = 2;
	con.anchor = GridBagConstraints.CENTER;
	con.fill = GridBagConstraints.NONE;
	grid.setConstraints(label_2, con);

	reset(con);
	con.gridx = 2;
	con.gridy = 2;
	con.anchor = GridBagConstraints.SOUTHWEST;
	con.fill = GridBagConstraints.NONE;
	grid.setConstraints(entry_2, con);

	reset(con);
	con.gridx = 1;
	con.gridy = 3;
	con.anchor = GridBagConstraints.CENTER;
	con.fill = GridBagConstraints.NONE;
	grid.setConstraints(button_1, con);

	reset(con);
	con.gridx = 2;
	con.gridy = 3;
	con.anchor = GridBagConstraints.CENTER;
	con.fill = GridBagConstraints.NONE;
	grid.setConstraints(result, con);

	// Resize behavior management and parent heirarchy
	setLayout(grid);

	// Give the application a chance to do its initialization
	super.init();
}

public boolean handleEvent(Event event) {
	if (event.target == button_1 && event.id == event.ACTION_EVENT) {
		result.setText(digest(password.getText()));
	} else
	if (event.target == entry_2 && event.id == event.ACTION_EVENT) {
		result.setText(js(entry_2.getText()));
	} else
	if (event.id==event.KEY_ACTION && event.key==event.F4 && event.modifiers==event.ALT_MASK) {  // Alt-F4 always exits
		System.exit(3);
	} else
		return super.handleEvent(event);
	return true;
}

public static void main(String[] args) {
    Frame f = new Frame("ServerDemo Test");
    ServerDemo win = new ServerDemo();
    win.init();
    f.add("Center", win);
    f.pack();
    f.show();
}

private void reset(GridBagConstraints con) {
    con.gridx = GridBagConstraints.RELATIVE;
    con.gridy = GridBagConstraints.RELATIVE;
    con.gridwidth = 1;
    con.gridheight = 1;

    con.weightx = 0;
    con.weighty = 0;
    con.anchor = GridBagConstraints.CENTER;
    con.fill = GridBagConstraints.NONE;

    con.insets = new Insets(0, 0, 0, 0);
    con.ipadx = 0;
    con.ipady = 0;
}

}


text:
using Qubiz.QuizEngine.Database.Entities;
using Qubiz.QuizEngine.Infrastructure;
using System.Data.Entity;

namespace Qubiz.QuizEngine.Database
{
    public class QuizEngineDataContext : DbContext
    {
        public QuizEngineDataContext(string connectionString)
            : base(connectionString)
        {
#if DEBUG
            this.Database.Log = (msg) => { System.Diagnostics.Debug.WriteLine(msg); };
#endif
        }

        public DbSet<Admin> Admins { get; set; }
        public DbSet<QuestionDefinition> Questions { get; set; }
        public DbSet<OptionDefinition> Options { get; set; }
        public DbSet<Exam> Exams { get; set; }
        public DbSet<ExamAnswer> Anwers { get; set; }
        public DbSet<Section> Sections { get; set; }
        public DbSet<TestDefinition> Tests { get; set; }
        public DbSet<TestSection> TestGenerationDetails { get; set; }
        public DbSet<TestQuestion> TestQuestions { get; set; }
		public DbSet<FeatureFlag> FeatureFlags { get; set; }
    }
}


text:
Edit Email

        <form class="form-horizontal" data-ng-submit="update()" novalidate>
            <fieldset>

                    Subject

                        <input type="text" data-ng-model="email.subject" id="subject" class="form-control" >

                    Content

                        <textarea type="text" data-ng-model="email.content" id="content" class="form-control"  required></textarea>

                    <input type="submit" value="Update" class="btn btn-default">

            </fieldset>
        </form>


text:
#include "DatahubStatusCodeHandlerDxe.h"

EFI_EVENT                 mExitBootServicesEvent     = NULL;
EFI_RSC_HANDLER_PROTOCOL  *mRscHandlerProtocol       = NULL;

/**
  Unregister status code callback functions only available at boot time from
  report status code router when exiting boot services.

  @param  Event         Event whose notification function is being invoked.
  @param  Context       Pointer to the notification function's context, which is
                        always zero in current implementation.

**/
VOID
EFIAPI
UnregisterBootTimeHandlers (
  IN EFI_EVENT        Event,
  IN VOID             *Context
  )
{
  mRscHandlerProtocol->Unregister (DataHubStatusCodeReportWorker);
}

/**
  Entry point of DXE Status Code Driver.

  This function is the entry point of this DXE Status Code Driver.
  It initializes registers status code handlers, and registers event for EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE.

  @param  ImageHandle       The firmware allocated handle for the EFI image.
  @param  SystemTable       A pointer to the EFI System Table.

  @retval EFI_SUCCESS       The entry point is executed successfully.

**/
EFI_STATUS
EFIAPI
DatahubStatusCodeHandlerDxeEntry (
  IN EFI_HANDLE         ImageHandle,
  IN EFI_SYSTEM_TABLE   *SystemTable
  )
{
  EFI_STATUS  Status;

  if (FeaturePcdGet (PcdStatusCodeUseDataHub)) {
    Status = gBS->LocateProtocol (
                    &gEfiRscHandlerProtocolGuid,
                    NULL,
                    (VOID **) &mRscHandlerProtocol
                    );
    ASSERT_EFI_ERROR (Status);

    //
    // Dispatch initialization request to supported devices
    //
    DataHubStatusCodeInitializeWorker ();

    mRscHandlerProtocol->Register (DataHubStatusCodeReportWorker, TPL_HIGH_LEVEL);

    Status = gBS->CreateEventEx (
                    EVT_NOTIFY_SIGNAL,
                    TPL_NOTIFY,
                    UnregisterBootTimeHandlers,
                    NULL,
                    &gEfiEventExitBootServicesGuid,
                    &mExitBootServicesEvent
                    );
    ASSERT_EFI_ERROR (Status);
  }

  return EFI_SUCCESS;
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Renci.SshNet.Channels;
using Renci.SshNet.Common;

namespace Renci.SshNet.Tests.Classes
{
    [TestClass]
    public class SubsystemSession_OnChannelDataReceived_Connected
    {
        private Mock<ISession> _sessionMock;
        private Mock<IChannelSession> _channelMock;
        private string _subsystemName;
        private SubsystemSessionStub _subsystemSession;
        private int _operationTimeout;
        private IList<EventArgs> _disconnectedRegister;
        private IList<ExceptionEventArgs> _errorOccurredRegister;
        private ChannelDataEventArgs _channelDataEventArgs;
        private MockSequence _sequence;

        [TestInitialize]
        public void Setup()
        {
            Arrange();
            Act();
        }

        protected void Arrange()
        {
            var random = new Random();
            _subsystemName = random.Next().ToString(CultureInfo.InvariantCulture);
            _operationTimeout = 30000;
            _disconnectedRegister = new List<EventArgs>();
            _errorOccurredRegister = new List<ExceptionEventArgs>();
            _channelDataEventArgs = new ChannelDataEventArgs(
                (uint)random.Next(0, int.MaxValue),
                new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) });

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelMock = new Mock<IChannelSession>(MockBehavior.Strict);

            _sequence = new MockSequence();
            _sessionMock.InSequence(_sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object);
            _channelMock.InSequence(_sequence).Setup(p => p.Open());
            _channelMock.InSequence(_sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true);

            _subsystemSession = new SubsystemSessionStub(
                _sessionMock.Object,
                _subsystemName,
                _operationTimeout);
            _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args);
            _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args);
            _subsystemSession.Connect();
        }

        protected void Act()
        {
            _channelMock.Raise(s => s.DataReceived += null, _channelDataEventArgs);
        }

        [TestMethod]
        public void DisconnectHasNeverFired()
        {
            Assert.AreEqual(0, _disconnectedRegister.Count);
        }

        [TestMethod]
        public void ErrorOccurredHasNeverFired()
        {
            Assert.AreEqual(0, _errorOccurredRegister.Count);
        }

        [TestMethod]
        public void OnDataReceivedShouldBeInvokedOnce()
        {
            Assert.AreEqual(1, _subsystemSession.OnDataReceivedInvocations.Count);

            var received = _subsystemSession.OnDataReceivedInvocations[0];
            Assert.AreEqual(_channelDataEventArgs.Data, received.Data);
        }

        [TestMethod]
        public void IsOpenShouldReturnTrueWhenChannelIsOpen()
        {
            _channelMock.InSequence(_sequence).Setup(p => p.IsOpen).Returns(true);

            Assert.IsTrue(_subsystemSession.IsOpen);

            _channelMock.Verify(p => p.IsOpen, Times.Once);
        }

        [TestMethod]
        public void IsOpenShouldReturnFalseWhenSessionIsNotConnected()
        {
            _channelMock.InSequence(_sequence).Setup(p => p.IsOpen).Returns(false);

            Assert.IsFalse(_subsystemSession.IsOpen);

            _channelMock.Verify(p => p.IsOpen, Times.Once);
        }

        [TestMethod]
        public void DisposeOnChannelShouldNeverBeInvoked()
        {
            _channelMock.Verify(p => p.Dispose(), Times.Never);
        }
    }
}


text:
using Distributions

module GKDistribution

  import Distributions:
         ContinuousUnivariateDistribution,
         location,
         scale,
         skewness,
         kurtosis,
         params,
         minimum,
         maximum,
         insupport,
         quantile,
         logpdf,
         fit_mle,
         Normal,
         cdf,
         pdf

  import Optim:
         optimize
  import Roots:
         fzero

  include("gk.jl")
  export GK,
         logpdf,
         quantile,
         location,
         scale,
         skewness,
         kurtosis,
         asymmetry,
         logpdf,
         quantile,
         params,
         minimum,
         maximum,
         insupport,
         pdf

end # module


text:
package corejava.lambdastwo.problemthree;

/**
 * an interface for which lambdas can be applied.
 * @author m
 * @param <T>
 */

@FunctionalInterface
public interface TwoElementPredicate<T> {

	/**
	 * Returns true if the first entry is "better" than the second, returns false otherwise.
	 * Concrete classes or lambdas that implement this interface will implement their meaning
	 * of what "better" is.
	 * @param element1
	 * @param element2
	 * @return
	 */
	boolean isBetter(T element1, T element2);
}


text:
#ifndef itkWaveletUtilities_h
#define itkWaveletUtilities_h

#include <algorithm>
#include <cmath>
#include <vector>
#include <itkFixedArray.h>
#include <itkMath.h>
#include <itkSize.h>

#include "IsotropicWaveletsExport.h"

namespace itk
{
namespace utils
{
  using IndexPairType = std::pair<unsigned int, unsigned int>;

  /** Get the (Level,Band) from a linear index output.
   * The index corresponding to the low-pass image is the last one, corresponding to the IndexPairType(this->GetLevels(), 0).
   * In a steerable pyramid: TotalOutputs = 1 + Levels * Bands
   * The outputs are ordered, if n is the \c linearIndex:
   * n:0 ---> level:0 band:1,
   * n:1 ---> l:0, b:2, etc. until b == bands.
   * n:bands-1 ---> l:0, b=bands
   * If there is more than one level:
   * n:bands ---> l:1, b=1
   * if only one level:
   * n:bands ---> l:0, b=0
   * Independently of the numbers of levels or bands, the last index is always the low pass:
   * nLowPass ---> l:Levels - 1, b=0
   *
   * Note that bands and levels are always >= 1. The level/bands returned here corresponds to an index.
   */
  IsotropicWavelets_EXPORT IndexPairType IndexToLevelBandSteerablePyramid(
    unsigned int linearIndex, unsigned int levels, unsigned int bands);

  /** Compute max number of levels depending on the size of the image.
   * Return J: $ J = \text{min_element}\{J_0,\ldots, J_d\} $;
   * where each $J_i$ is the  number of integer divisions that can be done with the $i$ size and the scale factor.
   * returns 1 if any size is not divisible by the scale factor.
   */
template < unsigned int VImageDimension >
ITK_TEMPLATE_EXPORT unsigned int ComputeMaxNumberOfLevels(
  const Size< VImageDimension >& inputSize, const unsigned int & scaleFactor)
  {
  FixedArray< unsigned int, VImageDimension > exponentPerAxis;
  // The minimum level is 1.
  exponentPerAxis.Fill(1);
  for ( unsigned int axis = 0; axis < VImageDimension; ++axis )
    {
    size_t sizeAxis = inputSize[axis];
    double exponent = std::log(static_cast<double>(sizeAxis)) / std::log(static_cast< double >(scaleFactor));
    // check that exponent is integer: the fractional part is 0
    double exponentIntPart;
    double exponentFractionPart = std::modf(exponent, &exponentIntPart );
    if ( itk::Math::FloatAlmostEqual(exponentFractionPart, 0.0) )
      {
      exponentPerAxis[axis] = static_cast< unsigned int >(exponent);
      }
    else
      {
      // increase valid levels until the division size/scale_factor gives a non-integer.
      auto sizeAtLevel = static_cast<double>(sizeAxis);
      for (;;)
        {
        double division = sizeAtLevel / static_cast<double>(scaleFactor);
        double intPartDivision;
        double fractionPartDivision = std::modf(division, &intPartDivision );
        if ( itk::Math::FloatAlmostEqual(fractionPartDivision, 0.0) )
          {
          exponentPerAxis[axis]++;
          sizeAtLevel = intPartDivision;
          }
        else
          {
          break;
          }
        }
      }
    }
  // return the min_element of array:
  //  - 1 is any size is not divisible by scale factor
  return *std::min_element(exponentPerAxis.Begin(), exponentPerAxis.End());
  }

} // end namespace utils
} // end namespace itk

#endif


text:
import {
  breakLines
} from '../../../helpers/break-lines';
import { module, test } from 'qunit';

module('BreakLinesHelper');

// Replace this with your real tests.
test('it works', function(assert) {
  var result = breakLines(42);
  assert.ok(result);
});


text:
<?php

namespace Instudies\SiteBundle\Entity;

use
    Doctrine\ORM\Mapping as ORM,
    Doctrine\Common\Collections\ArrayCollection,
    Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert,
    Symfony\Component\Validator\Constraints as Assert
;

/**
 * Instudies\SiteBundle\Entity\EducationGroupTeacher
 *
 * @ORM\Table(name="EducationGroupTeacher")
 * @ORM\HasLifecycleCallbacks()
 * @ORM\Entity(repositoryClass="Instudies\SiteBundle\Entity\EducationGroupTeacherRepository")
 */
class EducationGroupTeacher extends BaseTimestampableIdableEntity
{

    /**********************************************************************************
     * FIELDS
     *********************************************************************************/

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

    /**
     * @var string $telephone
     *
     * @ORM\Column(name="telephone", type="string", length=255, nullable=true)
     */
    protected $telephone;

    /**
     * @var string $email
     *
     * @ORM\Column(name="email", type="string", length=255, nullable=true)
     */
    protected $email;

    /**
     * @ORM\ManyToOne(targetEntity="EducationGroupSubject", inversedBy="teachers")
     * @ORM\JoinColumn(onDelete="CASCADE")
     */
    protected $subject;

    /**********************************************************************************
     * CONSTRUCT
     *********************************************************************************/

    public function __toString()
    {
        return $this->title;
    }

    /**********************************************************************************
     * GETTERS & SETTERS
     *********************************************************************************/

    /**
     * Set title
     *
     * @param string $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

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

    /**
     * Set telephone
     *
     * @param string $telephone
     */
    public function setTelephone($telephone)
    {
        $this->telephone = $telephone;
    }

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

    /**
     * Set email
     *
     * @param string $email
     */
    public function setEmail($email)
    {
        $this->email = $email;
    }

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

    /**
     * Set subject
     *
     * @param Instudies\SiteBundle\Entity\EducationGroupSubject $subject
     */
    public function setSubject(\Instudies\SiteBundle\Entity\EducationGroupSubject $subject)
    {
        $this->subject = $subject;
    }

    /**
     * Get subject
     *
     * @return Instudies\SiteBundle\Entity\EducationGroupSubject
     */
    public function getSubject()
    {
        return $this->subject;
    }

}


text:
const helper = require('./_helper');
const cli = require('../index');
const path = require('path');
const fs = require('fs');
const typeOf = require('type-of');
const isSteram = require('isstream');
const assign = require('object-assign');
const devNull = require('dev-null');
const endpoint = helper.endpoint();
const imgIndex = `${endpoint}/img/index.html`;
const imgLocalDir = 'img/img';
const imgRemoteDir = `${endpoint}/${imgLocalDir}`;
const fileLocalDir = 'img/file';
const fileRemoteDir = `${endpoint}/${fileLocalDir}`;

describe('cheerio:download', () => {
  beforeEach(() => {
    cli.download.removeAllListeners();
    cli.download.clearCache();
    cli.download.on('ready', () => {});
  });
  afterEach(() => {
    cli.set('timeout', 30000);
  });

  test('ダウンロードマネージャー未設定', () => {
    return new Promise((resolve) => {
      cli.download.removeAllListeners('ready');
      cli.fetch(imgIndex, (err, $, res, body) => {
        expect(() => $('.rel').download()).toThrow('download manager configured no event');
        resolve();
      });
    });
  });

  test('a,img要素以外 => エラー', () => {
    return new Promise((resolve) => {
      cli.fetch(imgIndex, (err, $, res, body) => {
        expect(() => $('body').download()).toThrow('element is neither a link nor img');
        expect(() => $('div').download()).toThrow('element is neither a link nor img');
        resolve();
      });
    });
  });

  describe('同時実行数指定', () => {
    afterAll(() => {
      cli.download.parallel = 3;
    });

    test('1未満', () => {
      return new Promise((resolve) => {
        cli.fetch(imgIndex, (err, $, res, body) => {
          cli.download.parallel = 0;
          expect(() => $('.rel').download()).toThrow('valid download parallel range is 1 and 5');
          resolve();
        });
      });
    });

    test('6以上', () => {
      return new Promise((resolve) => {
        cli.fetch(imgIndex, (err, $, res, body) => {
          cli.download.parallel = 6;
          expect(() => $('.rel').download()).toThrow('valid download parallel range is 1 and 5');
          resolve();
        });
      });
    });
  });

  test('画像のStreamがreadyイベントに送られる', () => {
    return new Promise((resolve, reject) => {
      cli.download
        .on('ready', (stream) => {
          try {
            expect(stream.url.href).toStrictEqual(`${imgRemoteDir}/cat.png`);
            expect(stream.type).toStrictEqual('image/png');
            expect(stream).toHaveLength(15572);
            expect(isSteram(stream)).toStrictEqual(true);
            stream.end();
            resolve();
          } catch (e) {
            reject(e);
            stream.end();
          }
        })
        .on('error', reject);
      cli.fetch(imgIndex, (err, $, res, body) => {
        expect($('.rel').download()).toStrictEqual(1);
      });
    });
  });

  test('画像とリンクをまとめて登録 => いずれもダウンロードされる', () => {
    return new Promise((resolve, reject) => {
      const expected = assign({}, cli.download.state);
      expected.complete += 3;
      cli.download
        .on('ready', (stream) => {
          try {
            stream.end();
          } catch (e) {
            reject(e);
          }
        })
        .on('error', reject)
        .on('end', function () {
          expect(this.state).toStrictEqual(expected);
          resolve();
        });
      cli.fetch(imgIndex, (err, $, res, body) => {
        expect($('.rel,.zip,.txt').download()).toStrictEqual(3);
      });
    });
  });

  test('子インスタンスからdownloadを実行 => 親インスタンスのreadyイベントに送られる', () => {
    return new Promise((resolve, reject) => {
      cli.download
        .on('ready', (stream) => {
          try {
            expect(stream.url.href).toStrictEqual(`${imgRemoteDir}/cat.png`);
            expect(stream.type).toStrictEqual('image/png');
            expect(stream).toHaveLength(15572);
            expect(isSteram(stream)).toStrictEqual(true);
            stream.end();
            resolve();
          } catch (e) {
            reject(e);
          }
        })
        .on('error', reject);
      const child = cli.fork();
      child.fetch(imgIndex, (err, $, res, body) => {
        expect($('.rel').download()).toStrictEqual(1);
      });
    });
  });

  describe('stream.toBuffer()', () => {
    test('streamがBuffer化される', () => {
      return new Promise((resolve, reject) => {
        const expected = assign({}, cli.download.state);
        expected.complete++;
        cli.download
          .on('ready', (stream) => {
            try {
              expect(stream.url.href).toStrictEqual(`${imgRemoteDir}/cat.png`);
              expect(stream.type).toStrictEqual('image/png');
              expect(stream).toHaveLength(15572);
              expect(
                stream.toBuffer((err, buffer) => {
                  try {
                    expect(err).toBeNull();
                    expect(buffer).toStrictEqual(helper.readBuffer(`${imgLocalDir}/cat.png`));
                    expect(cli.download.state).toStrictEqual(expected);
                    resolve();
                  } catch (e) {
                    reject(e);
                    stream.end();
                  }
                })
              ).toBeUndefined();
            } catch (e) {
              reject(e);
              stream.end();
            }
          })
          .on('error', reject);
        cli.fetch(imgIndex, (err, $, res, body) => {
          expect($('.rel').download()).toStrictEqual(1);
        });
      });
    });

    test('stream使用後に実行 => エラー', () => {
      return new Promise((resolve, reject) => {
        cli.download
          .on('ready', (stream) => {
            try {
              stream.pipe(devNull());
              stream.toBuffer((err, buffer) => {
                try {
                  expect(err).toBeDefined();
                  expect(err.message).toStrictEqual('stream has already been read');
                  expect(buffer).toBeUndefined();
                  resolve();
                  stream.end();
                } catch (e) {
                  reject(e);
                  stream.end();
                }
              });
            } catch (e) {
              reject(e);
              stream.end();
            }
          })
          .on('error', reject);
        cli.fetch(imgIndex, (err, $, res, body) => {
          expect($('.rel').download()).toStrictEqual(1);
        });
      });
    });

    test('コールバック未指定 => promiseオブジェクトを返す', () => {
      return new Promise((resolve, reject) => {
        const expected = assign({}, cli.download.state);
        expected.complete++;
        cli.download
          .on('ready', (stream) => {
            try {
              const promise = stream.toBuffer();
              expect(typeOf(promise)).toStrictEqual('object');
              expect(typeOf(promise.then)).toStrictEqual('function');
              expect(typeOf(promise.catch)).toStrictEqual('function');
              expect(typeOf(promise.finally)).toStrictEqual('function');
              promise
                .then((buffer) => {
                  expect(buffer).toStrictEqual(helper.readBuffer(`${fileLocalDir}/foobarbaz.zip`));
                  expect(cli.download.state).toStrictEqual(expected);
                  resolve();
                })
                .catch(reject);
            } catch (e) {
              reject(e);
              stream.end();
            }
          })
          .on('error', reject);
        cli.fetch(imgIndex).then(({ $ }) => {
          expect($('.zip').download()).toStrictEqual(1);
        });
      });
    });
  });

  test('Base64エンコードされた画像 => Buffer化される', () => {
    return new Promise((resolve, reject) => {
      const expected = assign({}, cli.download.state);
      expected.complete++;
      cli.download
        .on('ready', function (stream) {
          try {
            expect(stream.url).toStrictEqual('base64');
            expect(stream.type).toStrictEqual('image/jpg');
            expect(stream).toHaveLength(2268);
            expect(isSteram(stream)).toStrictEqual(true);
            stream.toBuffer((err, buffer) => {
              try {
                expect(buffer).toStrictEqual(helper.readBuffer(`${imgLocalDir}/sports.jpg`));
                expect(cli.download.state).toStrictEqual(expected);
                resolve();
              } catch (e) {
                reject(e);
                stream.end();
              }
            });
          } catch (e) {
            reject(e);
            stream.end();
          }
        })
        .on('error', reject);
      cli.fetch(imgIndex, (err, $, res, body) => {
        expect($('.base64').download()).toStrictEqual(1);
      });
    });
  });

  describe('stream.saveAs()', () => {
    const tmpFiles = [];
    const testFile = () => {
      const file = helper.tmppath();
      tmpFiles.push(file);
      return file;
    };

    afterAll(() => {
      tmpFiles.forEach((t) => {
        if (fs.existsSync(t)) {
          fs.unlinkSync(t);
        }
      });
    });

    test('streamがファイルに保存される', () => {
      return new Promise((resolve, reject) => {
        const expected = assign({}, cli.download.state);
        expected.complete++;
        cli.download
          .on('ready', (stream) => {
            try {
              const savePath = testFile();
              expect(
                stream.saveAs(savePath, (err) => {
                  try {
                    expect(err).toBeUndefined();
                    const actual = Buffer.from(fs.readFileSync(savePath));
                    expect(actual).toStrictEqual(helper.readBuffer(`${imgLocalDir}/cat.png`));
                    expect(cli.download.state).toStrictEqual(expected);
                    resolve();
                  } catch (e) {
                    reject(e);
                    stream.end();
                  }
                })
              ).toBeUndefined();
            } catch (e) {
              reject(e);
              stream.end();
            }
          })
          .on('error', reject);
        cli.fetch(imgIndex, (err, $, res, body) => {
          expect($('.rel').download()).toStrictEqual(1);
        });
      });
    });

    test('コールバック未指定 => promiseオブジェクトを返す', () => {
      return new Promise((resolve, reject) => {
        const expected = assign({}, cli.download.state);
        expected.complete++;
        cli.download
          .on('ready', (stream) => {
            try {
              const savePath = testFile();
              const promise = stream.saveAs(savePath);
              expect(typeOf(promise)).toStrictEqual('object');
              expect(typeOf(promise.then)).toStrictEqual('function');
              expect(typeOf(promise.catch)).toStrictEqual('function');
              expect(typeOf(promise.finally)).toStrictEqual('function');
              promise
                .then(() => {
                  const actual = Buffer.from(fs.readFileSync(savePath));
                  expect(actual).toStrictEqual(helper.readBuffer(`${fileLocalDir}/foobarbaz.zip`));
                  expect(cli.download.state).toStrictEqual(expected);
                  resolve();
                })
                .catch(reject);
            } catch (e) {
              reject(e);
              stream.end();
            }
          })
          .on('error', reject);
        cli.fetch(imgIndex, (err, $, res, body) => {
          expect($('.zip').download()).toStrictEqual(1);
        });
      });
    });

    test('Base64エンコードされた画像 => Buffer化してファイルに保存される', () => {
      return new Promise((resolve, reject) => {
        const expected = assign({}, cli.download.state);
        expected.complete++;
        cli.download
          .on('ready', function (stream) {
            try {
              const savePath = testFile();
              stream.saveAs(savePath, (err) => {
                try {
                  const actual = Buffer.from(fs.readFileSync(savePath));
                  expect(actual).toStrictEqual(helper.readBuffer(`${imgLocalDir}/sports.jpg`));
                  expect(cli.download.state).toStrictEqual(expected);
                  resolve();
                } catch (e) {
                  reject(e);
                  stream.end();
                }
              });
            } catch (e) {
              reject(e);
              stream.end();
            }
          })
          .on('error', reject);
        cli.fetch(imgIndex, (err, $, res, body) => {
          expect($('.base64').download()).toStrictEqual(1);
        });
      });
    });

    test('ファイル名未指定 => エラー', () => {
      return new Promise((resolve, reject) => {
        cli.download
          .on('ready', async (stream) => {
            try {
              await expect(stream.saveAs()).rejects.toThrow('save filepath is not specified');
              stream.end();
              resolve();
            } catch (e) {
              reject(e);
              stream.end();
            }
          })
          .on('error', reject);
        cli.fetch(imgIndex, (err, $, res, body) => {
          expect($('.rel').download()).toStrictEqual(1);
        });
      });
    });

    test('存在しないパス => エラー', async () => {
      return new Promise((resolve, reject) => {
        cli.download
          .on('ready', (stream) => {
            try {
              const dummyDir = path.join(__dirname, '!!not_exists!!');
              const dummyPath = path.join(dummyDir, 'foobarbaz.zip');
              stream.saveAs(dummyPath, (err) => {
                try {
                  expect(err).toBeDefined();
                  expect(err.message).toStrictEqual(
                    `ENOENT: no such file or directory, access '${dummyDir}'`
                  );
                  resolve();
                } catch (e) {
                  reject(e);
                  stream.end();
                }
              });
            } catch (e) {
              reject(e);
              stream.end();
            }
          })
          .on('error', reject);
        cli.fetch(imgIndex, (err, $, res, body) => {
          expect($('.zip').download()).toStrictEqual(1);
        });
      });
    });

    test('stream使用後に実行 => エラー', () => {
      return new Promise((resolve, reject) => {
        cli.download
          .on('ready', (stream) => {
            stream.on('data', async (data) => {
              try {
                const savePath = testFile();
                await expect(stream.saveAs(savePath)).rejects.toThrow(
                  'stream has already been read'
                );
                resolve();
                stream.end();
              } catch (e) {
                reject(e);
                stream.end();
              }
            });
          })
          .on('error', reject);
        cli.fetch(imgIndex, (err, $, res, body) => {
          expect($('.rel').download()).toStrictEqual(1);
        });
      });
    });

    test('すでにファイルが存在 => 上書き', () => {
      return new Promise((resolve, reject) => {
        const expected = assign({}, cli.download.state);
        expected.complete++;
        cli.download
          .on('ready', (stream) => {
            try {
              const savePath = testFile();
              fs.writeFileSync(savePath, 'dummy');
              expect(fs.readFileSync(savePath, 'utf-8')).toStrictEqual('dummy');
              stream.saveAs(savePath, (err) => {
                try {
                  expect(err).toBeUndefined();
                  const actual = Buffer.from(fs.readFileSync(savePath));
                  expect(actual).toStrictEqual(helper.readBuffer(`${imgLocalDir}/cat.png`));
                  expect(cli.download.state).toStrictEqual(expected);
                  resolve();
                } catch (e) {
                  reject(e);
                  stream.end();
                }
              });
            } catch (e) {
              reject(e);
              stream.end();
            }
          })
          .on('error', reject);
        cli.fetch(imgIndex, (err, $, res, body) => {
          expect($('.rel').download()).toStrictEqual(1);
        });
      });
    });
  });

  test('画像要素なし => ダウンロードキューに登録されない', () => {
    return new Promise((resolve) => {
      cli.fetch(imgIndex, (err, $, res, body) => {
        expect($('.xxxxyyyyzzzz').download()).toStrictEqual(0);
        resolve();
      });
    });
  });

  test('javascript => ダウンロードキューに登録されない', () => {
    return new Promise((resolve) => {
      cli.fetch(imgIndex, (err, $, res, body) => {
        expect($('.js').download()).toStrictEqual(0);
        resolve();
      });
    });
  });

  test('404 => errorイベントに送られる', () => {
    return new Promise((resolve, reject) => {
      const expected = assign({}, cli.download.state);
      expected.error++;
      cli.download
        .on('ready', (stream) => {
          stream.end();
          throw new Error('not thrown');
        })
        .on('error', function (e) {
          try {
            expect(e.url).toStrictEqual(`${endpoint}/img/not-found.gif`);
            expect(e.message).toStrictEqual('server status');
            expect(this.state).toStrictEqual(expected);
            resolve();
          } catch (e) {
            reject(e);
          }
        });
      cli.fetch(imgIndex, (err, $, res, body) => {
        expect($('.err404').download()).toStrictEqual(1);
      });
    });
  });

  test('リクエストタイムアウト => errorイベントに送られる', () => {
    return new Promise((resolve, reject) => {
      const expected = assign({}, cli.download.state);
      expected.error++;
      cli.download
        .on('ready', (stream) => {
          stream.end();
          throw new Error('not thrown');
        })
        .on('error', function (e) {
          try {
            expect(e.url).toStrictEqual(`${imgRemoteDir}/cat.png`);
            expect(helper.isTimedOut(e)).toStrictEqual(true);
            expect(this.state).toStrictEqual(expected);
            resolve();
          } catch (e) {
            reject(e);
          }
        });
      cli.fetch(imgIndex, (err, $, res, body) => {
        cli.set('timeout', 1);
        expect($('.rel').download()).toStrictEqual(1);
      });
    });
  });

  test('streamを使用しないままタイムアウト時間が過ぎるとエラー', () => {
    return new Promise((resolve, reject) => {
      const expected = assign({}, cli.download.state);
      expected.error++;
      cli.download
        .on('ready', (stream) => {})
        .on('error', function (e) {
          try {
            expect(e.url).toStrictEqual(`${endpoint}/img/~mega`);
            expect(e.message).toStrictEqual('stream timeout (maybe stream is not used)');
            expect(this.state).toStrictEqual(expected);
            resolve();
          } catch (e) {
            reject(e);
          }
        });
      cli.fetch(imgIndex, (err, $, res, body) => {
        cli.set('timeout', 3000);
        expect($('.mega').download()).toStrictEqual(1);
      });
    });
  });

  test('ダウンロードが完了するまではqueueにカウントされている', () => {
    return new Promise((resolve, reject) => {
      const state = assign({}, cli.download.state);
      let expected = null;
      cli.download
        .on('ready', function (stream) {
          try {
            stream.toBuffer((err, buffer) => {
              try {
                expect(this.state).toStrictEqual({
                  queue: state.queue,
                  complete: state.complete + 1,
                  error: state.error
                });
              } catch (e) {
                reject(e);
                stream.end();
              }
            });
          } catch (e) {
            reject(e);
            stream.end();
          }
        })
        .on('add', function (url) {
          try {
            expect(url).toStrictEqual(expected);
            expect(this.state).toStrictEqual({
              queue: state.queue + 1,
              complete: state.complete,
              error: state.error
            });
          } catch (e) {
            reject(e);
          }
        })
        .on('error', reject)
        .on('end', resolve);
      cli.fetch(imgIndex, (err, $, res, body) => {
        $('.root').attr('src', `${$('.root').attr('src')}&wait=1000`);
        expected = $('.root').url();
        expect($('.root').download()).toStrictEqual(1);
      });
    });
  });

  describe('srcAttrs', () => {
    test('無指定 => デフォルトの優先順で属性を検索してダウンロード', () => {
      return new Promise((resolve, reject) => {
        const expected = {
          url: `${imgRemoteDir}/cat.png`,
          buffer: helper.readBuffer(`${imgLocalDir}/cat.png`)
        };
        cli.download
          .on('ready', (stream) => {
            try {
              stream.toBuffer((err, buffer) => {
                try {
                  expect({
                    url: stream.url.href,
                    buffer: buffer
                  }).toStrictEqual(expected);
                  resolve();
                } catch (e) {
                  reject(e);
                  stream.end();
                }
              });
            } catch (e) {
              reject(e);
              stream.end();
            }
          })
          .on('error', reject);
        cli.fetch(imgIndex, (err, $, res, body) => {
          expect($('.lazy1').download()).toStrictEqual(1);
        });
      });
    });

    test('文字列 => 指定した文字列属性をsrcよりも優先してダウンロード', () => {
      return new Promise((resolve, reject) => {
        const expected = {
          url: `${imgRemoteDir}/sports.jpg`,
          buffer: helper.readBuffer(`${imgLocalDir}/sports.jpg`)
        };
        cli.download
          .on('ready', (stream) => {
            try {
              expect(stream.type).toStrictEqual('image/jpeg');
              expect(stream).toHaveLength(2268);
              stream
                .toBuffer()
                .then((buffer) => {
                  expect({
                    url: stream.url.href,
                    buffer: buffer
                  }).toStrictEqual(expected);
                  resolve();
                })
                .catch(reject);
            } catch (e) {
              reject(e);
              stream.end();
            }
          })
          .on('error', reject);
        cli.fetch(imgIndex, (err, $, res, body) => {
          expect($('.lazy3').download('data-original-src')).toStrictEqual(1);
        });
      });
    });

    test('空配列 => srcのURLをダウンロード', () => {
      return new Promise((resolve, reject) => {
        const expected = {
          url: `${imgRemoteDir}/1x1.gif`,
          buffer: helper.readBuffer(`${imgLocalDir}/1x1.gif`)
        };
        cli.download
          .on('ready', (stream) => {
            try {
              expect(stream.type).toStrictEqual('image/gif');
              expect(stream).toHaveLength(37);
              stream
                .toBuffer()
                .then((buffer) => {
                  expect({
                    url: stream.url.href,
                    buffer: buffer
                  }).toStrictEqual(expected);
                  resolve();
                })
                .catch(reject);
            } catch (e) {
              reject(e);
              stream.end();
            }
          })
          .on('error', reject);
        cli.fetch(imgIndex, (err, $, res, body) => {
          expect($('.lazy2').download([])).toStrictEqual(1);
        });
      });
    });
  });

  describe('link', () => {
    [
      ['テキスト', 'foobarbaz.txt', 'text/plain', 9, '.txt'],
      ['zip', 'foobarbaz.zip', 'application/zip', 270, '.zip']
    ].forEach(([type, file, mime, size, sel]) => {
      test(`${type}ファイル => ファイルをダウンロード`, () => {
        return new Promise((resolve, reject) => {
          const expected = {
            url: `${fileRemoteDir}/${file}`,
            buffer: helper.readBuffer(`${fileLocalDir}/${file}`)
          };
          cli.download
            .on('ready', (stream) => {
              try {
                expect(stream.type).toStrictEqual(mime);
                expect(stream).toHaveLength(size);
                stream.toBuffer((err, buffer) => {
                  try {
                    expect({
                      url: stream.url.href,
                      buffer: buffer
                    }).toStrictEqual(expected);
                    resolve();
                  } catch (e) {
                    reject(e);
                    stream.end();
                  }
                });
              } catch (e) {
                reject(e);
                stream.end();
              }
            })
            .on('error', reject);
          cli.fetch(imgIndex, (err, $, res, body) => {
            expect($(sel).download()).toStrictEqual(1);
          });
        });
      });
    });
  });

  describe('URL登録', () => {
    test('二重登録不可', () => {
      return new Promise((resolve, reject) => {
        const state = assign({}, cli.download.state);
        const list = ['.rel', '.rel'];
        let added = 0;
        cli.fetch(imgIndex, (err, $, res, body) => {
          cli.download
            .on('add', () => {
              try {
                added++;
                if (list.length === 0) return;
                $(list.shift()).download();
              } catch (e) {
                reject(e);
              }
            })
            .on('end', function () {
              try {
                expect(added).toStrictEqual(1);
                expect(this.state).toStrictEqual({
                  queue: state.queue,
                  complete: state.complete + 1,
                  error: state.error
                });
                resolve();
              } catch (e) {
                reject(e);
              }
            })
            .on('error', reject);
          $(list.shift()).download();
        });
      });
    });

    test('clearCahce()後は再度登録可能', () => {
      return new Promise((resolve, reject) => {
        const state = assign({}, cli.download.state);
        const list = ['.rel', '.rel'];
        let added = 0;
        cli.fetch(imgIndex, (err, $, res, body) => {
          cli.download
            .on('add', function () {
              try {
                added++;
                this.clearCache();
                if (list.length === 0) return;
                $(list.shift()).download();
              } catch (e) {
                reject(e);
              }
            })
            .on('end', function () {
              try {
                expect(added).toStrictEqual(2);
                expect(this.state).toStrictEqual({
                  queue: state.queue,
                  complete: state.complete + 2,
                  error: state.error
                });
                resolve();
              } catch (e) {
                reject(e);
              }
            })
            .on('error', reject);
          $(list.shift()).download();
        });
      });
    });
  });
});


text:
#include <armadillo>

using namespace arma;

#ifndef UTILS_HPP_
#define UTILS_HPP_

//===============================================================================//
// BASIC MATRIX-HANDLING FUNCTIONS
// create a row-vector of the form: start:1:stop
mat createInterval(int start, int stop);
// convert a matrix in MAT format to float format
float** matToFloat(mat &matrix);
// convert a matrix in float format to MAT format
mat floatToMat(float** matrix, int Nrows, int Ncols);
//===============================================================================//

//===============================================================================//
// FILTERING FUNCTIONS
// compute the median value of a vector
double median(rowvec &vector);
// perform median filtering on a matrix
void medianFilter(mat &matrix, int size);
// apply ChebyshevI filter on a matrix
mat ChebyshevFilter(mat matrix);
//===============================================================================//

#endif


text:
A JavaScript library for building modern HTML presentations. deck.js is flexible enough to let advanced CSS and JavaScript authors craft highly customized decks, but also provides templates and themes for the HTML novice to build a standard slideshow.

## Quick Start

This repository includes a `boilerplate.html` as a starting point, with all the extensions included. Just [download it](https://github.com/imakewebthings/deck.js/archive/latest.zip), open `boilerplate.html`, and start editing your slides.

## Documentation

Check out the [documentation page](http://imakewebthings.github.com/deck.js/docs) for more information on the methods, events, and options available in core and all the included extensions.  A sample standard slide deck is included in the package under the `introduction` folder.  You can also [view that sample deck](http://imakewebthings.github.com/deck.js/introduction) online to play with the available style and transition themes.

## Extensions, Themes, and Related Projects

Take a look at [the wiki](https://github.com/imakewebthings/deck.js/wiki) for lists of extensions, themes, and other related goodies.  If you have a publicly available project of your own, feel free to add to the list.

## Dependencies (included in this repository)

- [jQuery](http://jquery.com)
- [Modernizr](http://modernizr.com)

## Tests & Support

Unit tests are written with [Jasmine](http://jasmine.github.io/) and [jasmine-jquery](https://github.com/velesin/jasmine-jquery). You can [run them here](http://imakewebthings.github.com/deck.js/test).

deck.js has been tested with jQuery 1.6+ and works in IE7+, Chrome, FF, Safari, and Opera. The more capable browsers receive greater enhancements, but a basic cutaway slideshow will work for all browsers listed above. Please don't give your presentations in IE6.

For any questions or general discussion about deck.js please direct your attention to the [mailing list](http://groups.google.com/group/deckjs) (uses Google groups.)  If you would like to report a bug, please see the [issues page](https://github.com/imakewebthings/deck.js/issues).

## Printing

Core includes stripped down black and white print styles for the standard slide template that is suitable for handouts.

## Awesome Contributors

- [jbuck](https://github.com/jbuck)
- [cykod](https://github.com/cykod)
- [dougireton](https://github.com/dougireton)
- [awirick](https://github.com/awirick)
- Daniel Knittl-Frank
- [alexch](https://github.com/alexch)
- [twitwi](https://github.com/twitwi)

If you would like to contribute a patch to deck.js please do as much as you can of the following:

- Add or amend Jasmine tests.
- Add inline documentation.
- If the standard snippet of an extension changes, please change it in both the introduction deck and the snippet html in the extension folder.
- If the API changes, it would be awesome to receive a parallel pull request to the gh-pages branch which updates the public-facing documentation.

## License

Copyright (c) 2011-2014 Caleb Troughton

Licensed under the [MIT license](https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt)

## Donations

[![Gittip donate
button](http://img.shields.io/gittip/imakewebthings.png)](https://www.gittip.com/imakewebthings/ "Donate weekly to this project using Gittip")


text:
<?php

namespace app\admin\controller;

use think\Controller;
use think\Session;
use think\Config;
use think\Db;
use think\Request;

class Content extends \app\common\Root{

  public function index(){
    $page=request_data('get','page',1);
    $pagesize=Config::get('common_pagesize');
    $clist = Db::name('web_content')
      ->where(['is_delete'=>0])
      ->order('c_time desc')
      ->limit(($page-1)*$pagesize,$pagesize)
      ->select();
    $total=Db::name('web_content')
      ->where(['is_delete'=>0])
      ->count();
    $total_page=total_page($total,$pagesize);
    $this->assign('clist',$clist);
    $this->assign('total',$total);
    $this->assign('total_page',$total_page);
    $this->assign('cur_page',$page);
    return $this->fetch();
  }

  public function createContent(){
    $script='<link rel="stylesheet" href="/resource/css/wangEditor.min.css" type="text/css">';
    $this->assign('_script_text',$script);
    return $this->fetch('new_content');
  }

  public function editContent(){
    $script='<link rel="stylesheet" href="/resource/css/wangEditor.min.css" type="text/css">';
    $this->assign('_script_text',$script);
    $cid = request_data('get','cid','');
    $a=['cid'=>0,'c_title'=>'','c_content'=>'','top_image'=>''];
    if(!is_numeric($cid)||$cid<=0){
      $this->assign("content",$a);
    }
    else{
      $art = Db::name('web_content')->where(['cid'=>$cid])->find();
      if(empty($art)){
        $this->assign("content",$a);
      }
      else{
        $this->assign("content",$art);
      }
    }

    return $this->fetch('edit_content');
  }

}


text:
function tick2text(varargin)
%TICK2TEXT Changes tick labels to text objects
%
% tick2text
% tick2text(ax)
% tick2text(ax, param1, val1, ...)
% tick2text(ax, 'undo')
%
% This function allows for more versatile labeling of axis ticks.  It
% offers two possible modifications: 1) automatic reformatting of tick
% labels based on a user-supplied format or function, and 2) conversion of
% tick labels to text objects.
%
% The first option simply offers a shortcut to manual reformatting via
% the [X/Y/Z]TickLabel properties of axes.  It also overrides the zoom/pan
% function of the axis so that ticks will update with your specified
% formatting as you zoom and pan.
%
% With the second option, the original tick labels are removed, and new
% text objects are created that mimic x, y, and/or z tick labels. The text
% object format allows more modification (such as color, rotation, etc)
% than the original tick labels, and also allows TeX strings to be utilized
% in tick labels (see xformat and yformat inputs for more details).
%
% The handles of these new tick-like text objects are saved in the
% application data of the axis as '[X/Y/Z]TickText'.  Using these handles,
% the text objects can be modified as a group or individually (this method
% is used, rather than simply returning the handles of the new text
% objects, since zooming and panning will cause new objects to be created
% and old ones to be deleted).
%
% Note that with the conversion-to-text method, there will be a delay in
% the relabeling when panning, i.e. the old labels will drag with the mouse
% until you release the button, at which point the new labels will appear.
% Also note that the new tick label format cannot be updated if you reset
% tick locations or axis limits manually, so apply tick2text to an axis
% after these adjustments have already been made.
%
% This function should be robust to all axis properties for 2D plots (i.e.
% log and linear, normal and reversed axis order, and left/right/top/bottom
% axis location).  This is also true in 3D, but it is not robust to
% rotation; if your axis is rotated such that the y-axis is to the left,
% ticks will not align properly.
%
% Note: Under Matlab 2014b or later, ticks now support rotation, latex
% formatting, etc.  So the text conversion option is now a bit obsolete.
% I've left it there for backward compatibility.  The non-conversion option
% remains applicable to all versions.
%
% Input variables:
%
%   ax:         handle of axis to be modified (default to current axis)
%
% Optional input variables (passed as parameter/value pairs, defauts in [])
%
%   axis:       string containing characters 'x', 'y', and/or 'z',
%               indicating whether to format xticks, yticks, and/or
%               zticks, respectively. ['xy']
%
%   convert:    logical scalar, or 1 x n array, where n is the length of
%               the axis string, indicating whether to replace ticks with
%               text objects (true) or simply reformat the text of existing
%               ticks (false).
%
%   xformat:    formatting for x tick label.  This can be either a
%               formatting string (see sprintf) or the handle to a function
%               that takes as input a scalar number and returns a character
%               array. [@num2str]
%
%   yformat:    formatting for y tick label.  This can be either a
%               formatting string (see sprintf) or the handle to a function
%               that takes as input a scalar number and returns a character
%               array. [@num2str]
%
%   zformat:    formatting for z tick label.  This can be either a
%               formatting string (see sprintf) or the handle to a function
%               that takes as input a scalar number and returns a character
%               array. [@num2str]
%
%   panon:      logical scalar.  If true, set the customized pan
%               function to update tick labels when panning.  Because
%               custom panning can only be set for a figure, not an
%               individual axis, you may want to disable this if you are
%               applying customized ticks to multiple axes in a figure.
%               [true]
%
%   'undo':     delete any added text objects associated with tick2text,
%               and reset tick labels to their defaults (auto mode).  Note
%               that this doesn't undo non-convert formatting; that can be
%               reset via set(ax, '[XYZ]TickLabelMode', 'auto');
%
% Example:
%
%   This example creates two axes.  The top axis shows Matlab's default
%   tick labels.  The tick2text function is applied to the bottom axis,
%   changing the x axis to show ticks as multiples of pi, and the y axis to
%   label with full fixed-point values.  To demonstrate how to retrieve the
%   new tick handles, the x labels are then rotated 340 degrees (note that
%   by default x-text-ticks are centered; they may need to be left- or
%   right-aligned if rotated).
%
%     x = linspace(0,2*pi);
%     y = sin(x) + 100000;
%
%     ax(1) = subplot(2,1,1);
%     plot(x,y);
%     title('Original tick marks');
%
%     ax(2) = subplot(2,1,2);
%     plot(x,y);
%     title('Modified tick marks');
%
%     set(ax, 'xlim', [0 2*pi]);
%
%     tick2text(ax(2), 'yformat', '%.2f', ...
%                      'xformat', @(x) sprintf('%.2g\\pi', x/pi), ...
%                      'convert', [true false])
%
%     hx = getappdata(ax(2), 'XTickText');
%     set(hx, 'Rotation', 340, 'fontsize', 12, 'horiz', 'left');

% Copyright 2009 Kelly Kearney

%----------------------------
% Parse and check input
%----------------------------

% Get axis handle

if ishandle(varargin{1})
    ax = varargin{1};
    pv = varargin(2:end);
else
    ax = gca;
    pv = varargin;
end

if ~isscalar(ax) || ~ishandle(ax) || ~ismember(get(ax, 'type'), {'axes','colorbar'})
    error('Handle must be to a single axis');
end

% Check for undo option

if length(pv) == 1 && strcmp(pv{1}, 'undo')
    Ad = getappdata(ax);
    if isfield(Ad, 'YTickText')
        delete(Ad.YTickText);
        rmappdata(ax, 'YTickText');
    end
    set(ax, 'yticklabelmode', 'auto');
    if isfield(Ad, 'XTickText')
        delete(Ad.XTickText);
        rmappdata(ax, 'XTickText');
    end
    set(ax, 'xticklabelmode', 'auto');
    if isfield(Ad, 'ZTickText')
        delete(Ad.ZTickText);
        rmappdata(ax, 'ZTickText');
    end
    set(ax, 'zticklabelmode', 'auto');
    return
end

% Get parent figure (for panning)

fig = ancestor(ax, 'figure');

% Parse and check optional variables

Options = struct('xformat', [], 'yformat', [], 'zformat', [], ...
                 'ytickoffset', .04, 'xtickoffset', .04, ...
                 'ztickoffset', .08, 'axis', 'xy', 'panon', true, ...
                 'convert', false);

Options = parsepv(Options, pv);

if ~isscalar(Options.ytickoffset) || ~isscalar(Options.xtickoffset) || ~isscalar(Options.ztickoffset)
    error('Offset values must be numerical scalars');
end

if ~ischar(Options.axis) || ~isempty(regexp(Options.axis, '[^xyz]'))
    error('Axis must be string including x, y, and/or z');
end
loc = arrayfun(@(a) strfind(Options.axis, a), 'xyz', 'uni', 0);
labelflag = ~cellfun('isempty', loc);

convertflag = false(1,3);
if isscalar(Options.convert)
    convertflag(:) = Options.convert;
elseif isequal(size(Options.axis), size(Options.convert))
    for ii = 1:length(Options.axis)
        convertflag(loc{ii}) = Options.convert(ii);
    end
else
    error('Convert array must be same length as axis string');
end

% Set formatting functions

if isempty(Options.xformat)
    xformatfun = @num2str;
elseif ischar(Options.xformat)
    xformatfun = @(x) num2str(x, Options.xformat);
elseif strcmp(class(Options.xformat), 'function_handle')
    xformatfun = Options.xformat;
else
    error('xformat must be a formatting string or function handle');
end

if isempty(Options.yformat)
    yformatfun = @num2str;
elseif ischar(Options.yformat)
    yformatfun = @(x) num2str(x, Options.yformat);
elseif strcmp(class(Options.yformat), 'function_handle')
    yformatfun = Options.yformat;
else
    error('yformat must be a formatting string or function handle');
end

if isempty(Options.zformat)
    zformatfun = @num2str;
elseif ischar(Options.zformat)
    zformatfun = @(x) num2str(x, Options.zformat);
elseif strcmp(class(Options.zformat), 'function_handle')
    zformatfun = Options.zformat;
else
    error('zformat must be a formatting string or function handle');
end

P.ax = ax;
P.xfun = xformatfun;
P.yfun = yformatfun;
P.zfun = zformatfun;
P.lflag = labelflag;
P.cflag = convertflag;

%----------------------------
% Change exisiting tick
% labels
%----------------------------

texttick(P);

% Add customized zoom

try
    hzoom = zoom(ax);
    set(hzoom, 'ActionPostCallback', {@newzoompan, P});
catch
    warning('Unable to apply customized zoom');
end

% Add customized pan

if Options.panon
    hpan = pan(fig);
    set(hpan, 'ActionPostCallback', {@newzoompan, P});
end

%----------------------------
% Update tick labels when
% zooming and panning
%----------------------------

function newzoompan(h, ed, P)
if P.lflag(1) && ~P.cflag(1)
    set(P.ax, 'XTickMode', 'auto', 'XTickLabelMode', 'auto');
end
if P.lflag(2) && ~P.cflag(2)
    set(P.ax, 'YTickMode', 'auto', 'YTickLabelMode', 'auto');
end
if P.lflag(3) && ~P.cflag(3)
    set(P.ax, 'ZTickMode', 'auto', 'ZTickLabelMode', 'auto');
end

texttick(P)

%----------------------------
% Change tick labels to text
% objects
%----------------------------

function texttick(P)

% Get current values of ticks and axis limits

A = get(P.ax);

% Create new labels

if ~verLessThan('matlab', '8.4.0') && strcmp(P.ax.Type, 'colorbar')
    cbflag = true;
else
    cbflag = false;
end

if cbflag
    xticklab = arrayfun(P.xfun, A.Ticks, 'uni', 0);
else
    xticklab = arrayfun(P.xfun, A.XTick, 'uni', 0);
    yticklab = arrayfun(P.yfun, A.YTick, 'uni', 0);
    zticklab = arrayfun(P.zfun, A.ZTick, 'uni', 0);
end

% If no-convert option, simply replace tick labels

if cbflag
    if any(P.cflag)
        error('Conversion option not offered for colorbars yet');
    end
    set(P.ax, 'Ticks', A.Ticks, 'TickLabels', xticklab);
else
    if P.lflag(1) && ~P.cflag(1)
        set(P.ax, 'XTick', A.XTick, 'XTickLabel', xticklab);
    end
    if P.lflag(2) && ~P.cflag(2)
        set(P.ax, 'YTick', A.YTick, 'YTickLabel', yticklab);
    end
    if P.lflag(3) && ~P.cflag(3)
        set(P.ax, 'ZTick', A.ZTick, 'ZTickLabel', zticklab);
    end
end

% Exit if no conversion calcs necessary

if ~any(P.cflag)
    return
end

% Determine location of ticks in coordinate space

if isequal(A.View, [0 90])
    is2d = true;
elseif isequal(A.View, [-37.5 30])
    is2d = false;
else
    is2d = false;
    warning('Not robust to roation in 3D; ticks may be oddly positioned');
end

if is2d

    % Where in x-coords is the Y axis?

    islin = strcmp(A.YScale, 'linear');
    if islin
        pos = A.XLim(2) + A.TickLength(1) .* diff(A.XLim);
        neg = A.XLim(1) - A.TickLength(1) .* diff(A.XLim);
    else
        pos = 10.^(A.XLim(2) + A.TickLength(1) .* diff(log10(A.XLim)));
        neg = 10.^(A.XLim(1) - A.TickLength(1) .* diff(log10(A.XLim)));
    end

    if strcmp(A.XDir, 'normal') && strcmp(A.YAxisLocation, 'left')
        ytkx = neg;
        ytkh = 'right';
        ytkv = 'middle';
    elseif strcmp(A.XDir, 'normal') && strcmp(A.YAxisLocation, 'right')
        ytkx = pos;
        ytkh = 'left';
        ytkv = 'middle';
    elseif strcmp(A.XDir, 'reverse') && strcmp(A.YAxisLocation, 'left')
        ytkx = pos;
        ytkh = 'right';
        ytkv = 'middle';
    elseif strcmp(A.XDir, 'reverse') && strcmp(A.YAxisLocation, 'right')
        ytkx = neg;
        ytkh = 'left';
        ytkv = 'middle';
    end

    % Where in y-coords is the X axis?

    islin = strcmp(A.YScale, 'linear');
    if islin
        pos = A.YLim(2) + A.TickLength(1) .* diff(A.YLim);
        neg = A.YLim(1) - A.TickLength(1) .* diff(A.YLim);
    else
        pos = 10.^(log10(A.YLim(2)) + A.TickLength(1) .* diff(log10(A.YLim)));
        neg = 10.^(log10(A.YLim(1)) - A.TickLength(1) .* diff(log10(A.YLim)));
    end

    if strcmp(A.YDir, 'normal') && strcmp(A.XAxisLocation, 'bottom')
       	xtky = neg;
        xtkh = 'center';
        xtkv = 'top';
    elseif strcmp(A.YDir, 'normal') && strcmp(A.XAxisLocation, 'top')
        xtky = pos;
        xtkh = 'center';
        xtkv = 'bottom';
    elseif strcmp(A.YDir, 'reverse') && strcmp(A.XAxisLocation, 'bottom')
        xtky = pos;
        xtkh = 'center';
        xtkv = 'top';
    elseif strcmp(A.YDir, 'reverse') && strcmp(A.XAxisLocation, 'top')
        xtky = neg;
        xtkh = 'center';
        xtkv = 'bottom';
    end

    xtkz = 0;
    ytkz = 0;

else

    % Where in y-coords are the X and Z axes?

    islin = strcmp(A.YScale, 'linear');
    if islin
        pos = A.YLim(2) + A.TickLength(2) .* diff(A.YLim);
        neg = A.YLim(1) - A.TickLength(2) .* diff(A.YLim);
    else
        pos = 10.^(A.YLim(2) + A.TickLength(2) .* diff(log10(A.YLim)));
        neg = 10.^(A.YLim(1) - A.TickLength(2) .* diff(log10(A.YLim)));
    end

    if strcmp(A.YDir, 'normal')
        xtky = neg;
        ztky = pos;
    else
        xtky = pos;
        ztky = neg;
    end

    % Where in x-coords are the Y and Z axes?

    islin = strcmp(A.YScale, 'linear');
    if islin
        pos = A.XLim(2) + A.TickLength(1) .* diff(A.XLim);
        neg = A.XLim(1) - A.TickLength(1) .* diff(A.XLim);
    else
        pos = 10.^(A.XLim(2) + A.TickLength(1) .* diff(log10(A.XLim)));
        neg = 10.^(A.XLim(1) - A.TickLength(1) .* diff(log10(A.XLim)));
    end

    if strcmp(A.XDir, 'normal')
        ztkx = A.XLim(1);
        ytkx = neg;
    else
        ztkx = A.XLim(2);
        ytkx = pos;
    end

    % Where in z-coords are the X and Y axes?

    if strcmp(A.ZDir, 'normal')
        xtkz = A.ZLim(1);
        ytkz = A.ZLim(1);
    else
        xtkz = A.ZLim(2);
        ytkz = A.ZLim(2);
    end

    % Alignment (this assumes the z-axis is to the left)

    xtkh = 'left';
    xtkv = 'top';
    ytkh = 'right';
    ytkv = 'top';
    ztkh = 'right';
    ztkv = 'middle';

end

% Replace ticks with text

if P.lflag(1) && P.cflag(1)
    xcoord = A.XTick;
    ycoord = ones(size(A.XTick)) * xtky;
    zcoord = ones(size(A.XTick)) * xtkz;
    if isappdata(P.ax, 'XTickText')
        replaceoldticks(P.ax, 'XTickText', xcoord, ycoord, zcoord, xticklab);
    else
        set(P.ax, 'xticklabel', '');
        createnewticks(P.ax, 'XTickText', xcoord, ycoord, zcoord, xticklab, xtkh, xtkv);
    end
end

if P.lflag(2) && P.cflag(2)
    xcoord = ones(size(A.YTick)) * ytkx;
    ycoord = A.YTick;
    zcoord = ones(size(A.YTick)) * ytkz;
    set(P.ax, 'yticklabel', '');
    if isappdata(P.ax, 'YTickText')
        replaceoldticks(P.ax, 'YTickText', xcoord, ycoord, zcoord, yticklab);
    else
        createnewticks(P.ax, 'YTickText', xcoord, ycoord, zcoord, yticklab, ytkh, ytkv);
    end
end

if P.lflag(3) && P.cflag(3)
    xcoord = ones(size(A.ZTick)) * ztkx;
    ycoord = ones(size(A.ZTick)) * ztky;
    zcoord = A.ZTick;
    set(P.ax, 'zticklabel', '');
    if isappdata(P.ax, 'ZTickText')
        replaceoldticks(P.ax, 'ZTickText', xcoord, ycoord, zcoord, zticklab);
    else
        createnewticks(P.ax, 'ZTickText', xcoord, ycoord, zcoord, zticklab, ztkh, ztkv);
    end
end

%----------------------------
% Create new tick-like text
% objects
%----------------------------

function createnewticks(ax, appfld, xcoord, ycoord, zcoord, txt, horiz, vert);

if ~verLessThan('matlab', '8.4.0')
    warning('tick2text:notext', 'In Matlab 2014b and later, conversion to text is no longer necessary for formatting or rotation');
end

h = text(xcoord, ycoord, zcoord, txt, 'parent', ax, 'horizontalalignment', horiz, 'verticalalignment', vert);
setappdata(ax, appfld, h);

%----------------------------
% Replace old tick-like text
% objects
%----------------------------

function replaceoldticks(ax, appfld, xcoord, ycoord, zcoord, txt)

hxold = getappdata(ax, appfld);

% Get properties of current ticks

props = get(hxold);
params = fieldnames(props(1));
vals = struct2cell(props(1));

% Ignore properties that always change between ticks or are read only

[tf,loc] = ismember({'Extent', 'String', 'BeingDeleted', 'Children', 'Position', 'Type', 'Annotation'}, params);
params(loc) = [];
vals(loc) = [];
paramval = [params'; vals'];

% Create new ticks with same properties

delete(hxold);
hx = text(xcoord, ycoord, zcoord, txt, 'parent', ax, paramval{:});
setappdata(ax, appfld, hx);