<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#ifndef JUBATUS_SERVER_FRAMEWORK_SERVER_UTIL_HPP_
#define JUBATUS_SERVER_FRAMEWORK_SERVER_UTIL_HPP_

#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>

#include <msgpack.hpp>
#include "jubatus/util/lang/noncopyable.h"
#include "jubatus/util/concurrent/lock.h"
#include "jubatus/util/concurrent/rwmutex.h"
#include "jubatus/util/lang/function.h"
#include "jubatus/util/lang/shared_ptr.h"

#include "jubatus/core/common/exception.hpp"
#include "jubatus/server/common/logger/logger.hpp"
#include "../common/system.hpp"
#include "../common/lock_service.hpp"

namespace cmdline {
class parser;
}

namespace jubatus {

namespace core {
namespace fv_converter {
class datum_to_fv_converter;
}  // namespace fv_converter
}  // namespace core

namespace server {
namespace framework {

struct config_json {
  config_json() {
  }

  std::string config;

  void load_json(
      const std::string& zkhosts,
      const std::string& type,
      const std::string& name);
  void load_json(const std::string& filepath);
};

struct server_argv {
  server_argv(int args, char** argv, const std::string& type);
  server_argv();

  int port;
  std::string bind_address;
  std::string bind_if;
  int timeout;
  int zookeeper_timeout;
  int interconnect_timeout;
  int threadnum;
  std::string program_name;
  std::string type;
  std::string z;
  std::string name;
  std::string datadir;
  std::string logdir;
  std::string log_config;
  std::string configpath;
  std::string modelpath;
  std::string eth;
  int interval_sec;
  int interval_count;
  std::string mixer;
  bool daemon;

  MSGPACK_DEFINE(port, bind_address, bind_if, timeout,
      zookeeper_timeout, interconnect_timeout, threadnum,
      program_name, type, z, name, datadir, logdir, log_config, eth,
      interval_sec, interval_count, mixer, daemon);

  bool is_standalone() const {
    return (z == "");
  }
  void boot_message(const std::string& progname) const;
  void set_log_destination(const std::string& progname) const;
};

void daemonize_process(const std::string& logdir);
std::string get_server_identifier(const server_argv& a);

struct proxy_argv {
  proxy_argv(int args, char** argv, const std::string& t);
  proxy_argv();

  int port;
  std::string bind_address;
  std::string bind_if;
  int timeout;
  int zookeeper_timeout;
  int interconnect_timeout;
  int threadnum;
  std::string program_name;
  std::string z;
  std::string logdir;
  std::string log_config;
  std::string eth;
  const std::string type;
  int session_pool_expire;
  int session_pool_size;
  bool daemon;

  void boot_message(const std::string& progname) const;
  void set_log_destination(const std::string& progname) const;
};

std::string get_proxy_identifier(const proxy_argv& a);

void register_lock_service(
    jubatus::util::lang::shared_ptr<common::lock_service> ls);
void close_lock_service();

template<class ImplServerClass>
int run_server(int args, char** argv, const std::string& type) {
  try {
    server_argv parsed_argv(args, argv, type);
    ImplServerClass impl_server(parsed_argv);
    if (!parsed_argv.is_standalone()) {
      impl_server.get_p()->get_mixer()->register_api(impl_server);
    }
    return impl_server.run();
  } catch (const jubatus::core::common::exception::jubatus_exception& e) {
    LOG(FATAL) << "exception in main thread: "
               << e.diagnostic_information(true);
    return -1;
  } catch (const std::exception& e) {
    LOG(FATAL) << "error in main thread: " << e.what();
  }
}

std::string get_conf(const server_argv& a);

}  // namespace framework
}  // namespace server
}  // namespace jubatus

#endif  // JUBATUS_SERVER_FRAMEWORK_SERVER_UTIL_HPP_
<commit_msg>eliminate warnings (refs #822)<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#ifndef JUBATUS_SERVER_FRAMEWORK_SERVER_UTIL_HPP_
#define JUBATUS_SERVER_FRAMEWORK_SERVER_UTIL_HPP_

#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>

#include <msgpack.hpp>
#include "jubatus/util/lang/noncopyable.h"
#include "jubatus/util/concurrent/lock.h"
#include "jubatus/util/concurrent/rwmutex.h"
#include "jubatus/util/lang/function.h"
#include "jubatus/util/lang/shared_ptr.h"

#include "jubatus/core/common/exception.hpp"
#include "jubatus/server/common/logger/logger.hpp"
#include "../common/system.hpp"
#include "../common/lock_service.hpp"

namespace cmdline {
class parser;
}

namespace jubatus {

namespace core {
namespace fv_converter {
class datum_to_fv_converter;
}  // namespace fv_converter
}  // namespace core

namespace server {
namespace framework {

struct config_json {
  config_json() {
  }

  std::string config;

  void load_json(
      const std::string& zkhosts,
      const std::string& type,
      const std::string& name);
  void load_json(const std::string& filepath);
};

struct server_argv {
  server_argv(int args, char** argv, const std::string& type);
  server_argv();

  int port;
  std::string bind_address;
  std::string bind_if;
  int timeout;
  int zookeeper_timeout;
  int interconnect_timeout;
  int threadnum;
  std::string program_name;
  std::string type;
  std::string z;
  std::string name;
  std::string datadir;
  std::string logdir;
  std::string log_config;
  std::string configpath;
  std::string modelpath;
  std::string eth;
  int interval_sec;
  int interval_count;
  std::string mixer;
  bool daemon;

  MSGPACK_DEFINE(port, bind_address, bind_if, timeout,
      zookeeper_timeout, interconnect_timeout, threadnum,
      program_name, type, z, name, datadir, logdir, log_config, eth,
      interval_sec, interval_count, mixer, daemon);

  bool is_standalone() const {
    return (z == "");
  }
  void boot_message(const std::string& progname) const;
  void set_log_destination(const std::string& progname) const;
};

void daemonize_process(const std::string& logdir);
std::string get_server_identifier(const server_argv& a);

struct proxy_argv {
  proxy_argv(int args, char** argv, const std::string& t);
  proxy_argv();

  int port;
  std::string bind_address;
  std::string bind_if;
  int timeout;
  int zookeeper_timeout;
  int interconnect_timeout;
  int threadnum;
  std::string program_name;
  std::string z;
  std::string logdir;
  std::string log_config;
  std::string eth;
  const std::string type;
  int session_pool_expire;
  int session_pool_size;
  bool daemon;

  void boot_message(const std::string& progname) const;
  void set_log_destination(const std::string& progname) const;
};

std::string get_proxy_identifier(const proxy_argv& a);

void register_lock_service(
    jubatus::util::lang::shared_ptr<common::lock_service> ls);
void close_lock_service();

template<class ImplServerClass>
int run_server(int args, char** argv, const std::string& type) {
  try {
    server_argv parsed_argv(args, argv, type);
    ImplServerClass impl_server(parsed_argv);
    if (!parsed_argv.is_standalone()) {
      impl_server.get_p()->get_mixer()->register_api(impl_server);
    }
    return impl_server.run();
  } catch (const jubatus::core::common::exception::jubatus_exception& e) {
    LOG(FATAL) << "exception in main thread: "
               << e.diagnostic_information(true);
    return -1;
  } catch (const std::exception& e) {
    LOG(FATAL) << "error in main thread: " << e.what();
    return -1;
  }
}

std::string get_conf(const server_argv& a);

}  // namespace framework
}  // namespace server
}  // namespace jubatus

#endif  // JUBATUS_SERVER_FRAMEWORK_SERVER_UTIL_HPP_
<|endoftext|>


<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/register.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"

struct IopadmapPass : public Pass {
	IopadmapPass() : Pass("iopadmap", "technology mapping of flip-flops") { }
	virtual void help()
	{
		log("\n");
		log("    iopadmap [options] [selection]\n");
		log("\n");
		log("Map module inputs/outputs to PAD cells from a library. This pass\n");
		log("can only map to very simple PAD cells. Use 'techmap' to further map\n");
		log("the resulting cells to more sophisticated PAD cells.\n");
		log("\n");
		log("    -inpad <celltype> <portname>\n");
		log("        Map module input ports to the given cell type with\n");
		log("        the given port name.\n");
		log("\n");
		log("    -outpad <celltype> <portname>\n");
		log("    -inoutpad <celltype> <portname>\n");
		log("        Similar to -inpad, but for output and inout ports.\n");
		log("\n");
		log("    -widthparam <param_name>\n");
		log("        Use the specified parameter name to set the port width.\n");
		log("\n");
		log("    -nameparam <param_name>\n");
		log("        Use the specified parameter to set the port name.\n");
		log("\n");
	}
	virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
	{
		log_header("Executing IOPADMAP pass (mapping inputs/outputs to IO-PAD cells).\n");

		std::string inpad_celltype, inpad_portname;
		std::string outpad_celltype, outpad_portname;
		std::string inoutpad_celltype, inoutpad_portname;
		std::string widthparam, nameparam;

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			std::string arg = args[argidx];
			if (arg == "-inpad" && argidx+2 < args.size()) {
				inpad_celltype = args[++argidx];
				inpad_portname = args[++argidx];
				continue;
			}
			if (arg == "-outpad" && argidx+2 < args.size()) {
				outpad_celltype = args[++argidx];
				outpad_portname = args[++argidx];
				continue;
			}
			if (arg == "-inoutpad" && argidx+2 < args.size()) {
				inoutpad_celltype = args[++argidx];
				inoutpad_portname = args[++argidx];
				continue;
			}
			if (arg == "-widthparam" && argidx+1 < args.size()) {
				widthparam = args[++argidx];
				continue;
			}
			if (arg == "-nameparam" && argidx+1 < args.size()) {
				nameparam = args[++argidx];
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		for (auto &it : design->modules)
		{
			RTLIL::Module *module = it.second;

			if (!design->selected(module))
				continue;

			for (auto &it2 : module->wires)
			{
				RTLIL::Wire *wire = it2.second;

				if (!wire->port_id || !design->selected(module, wire))
					continue;

				std::string celltype, portname;

				if (wire->port_input && !wire->port_output) {
					if (inpad_celltype.empty()) {
						log("Don't map input port %s.%s: Missing option -inpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
						continue;
					}
					celltype = inpad_celltype;
					portname = inpad_portname;
				} else
				if (!wire->port_input && wire->port_output) {
					if (outpad_celltype.empty()) {
						log("Don't map output port %s.%s: Missing option -outpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
						continue;
					}
					celltype = outpad_celltype;
					portname = outpad_portname;
				} else
				if (wire->port_input && wire->port_output) {
					if (inoutpad_celltype.empty()) {
						log("Don't map inout port %s.%s: Missing option -inoutpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
						continue;
					}
					celltype = inoutpad_celltype;
					portname = inoutpad_portname;
				} else
					log_abort();

				if (wire->width != 1 && widthparam.empty()) {
					log("Don't map multi-bit port %s.%s: Missing option -widthparam.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
					continue;
				}

				log("Mapping port %s.%s.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));

				RTLIL::Cell *cell = new RTLIL::Cell;
				cell->name = NEW_ID;
				cell->type = RTLIL::escape_id(celltype);
				cell->connections[RTLIL::escape_id(portname)] = RTLIL::SigSpec(wire);
				if (!widthparam.empty())
					cell->parameters[RTLIL::escape_id(widthparam)] = RTLIL::Const(wire->width);
				if (!nameparam.empty())
					cell->parameters[RTLIL::escape_id(nameparam)] = RTLIL::Const(RTLIL::id2cstr(wire->name));
				cell->attributes["\\keep"] = RTLIL::Const(1);
				module->add(cell);

				wire->port_id = 0;
				wire->port_input = false;
				wire->port_output = false;
			}

			module->fixup_ports();
		}
	}
} IopadmapPass;

<commit_msg>Added support for i/o buffers to iopadmap<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/register.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"

static void split_portname_pair(std::string &port1, std::string &port2)
{
	size_t pos = port1.find_first_of(':');
	if (pos != std::string::npos) {
		port2 = port1.substr(pos+1);
		port1 = port1.substr(0, pos);
	}
}

struct IopadmapPass : public Pass {
	IopadmapPass() : Pass("iopadmap", "technology mapping of i/o pads (or buffers)") { }
	virtual void help()
	{
		log("\n");
		log("    iopadmap [options] [selection]\n");
		log("\n");
		log("Map module inputs/outputs to PAD cells from a library. This pass\n");
		log("can only map to very simple PAD cells. Use 'techmap' to further map\n");
		log("the resulting cells to more sophisticated PAD cells.\n");
		log("\n");
		log("    -inpad <celltype> <portname>[:<portname>]\n");
		log("        Map module input ports to the given cell type with\n");
		log("        the given port name. if a 2nd portname is given, the\n");
		log("        signal is passed through the pad call, using the 2nd\n");
		log("        portname as output.\n");
		log("\n");
		log("    -outpad <celltype> <portname>[:<portname>]\n");
		log("    -inoutpad <celltype> <portname>[:<portname>]\n");
		log("        Similar to -inpad, but for output and inout ports.\n");
		log("\n");
		log("    -widthparam <param_name>\n");
		log("        Use the specified parameter name to set the port width.\n");
		log("\n");
		log("    -nameparam <param_name>\n");
		log("        Use the specified parameter to set the port name.\n");
		log("\n");
	}
	virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
	{
		log_header("Executing IOPADMAP pass (mapping inputs/outputs to IO-PAD cells).\n");

		std::string inpad_celltype, inpad_portname, inpad_portname2;
		std::string outpad_celltype, outpad_portname, outpad_portname2;
		std::string inoutpad_celltype, inoutpad_portname, inoutpad_portname2;
		std::string widthparam, nameparam;

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			std::string arg = args[argidx];
			if (arg == "-inpad" && argidx+2 < args.size()) {
				inpad_celltype = args[++argidx];
				inpad_portname = args[++argidx];
				split_portname_pair(inpad_portname, inpad_portname2);
				continue;
			}
			if (arg == "-outpad" && argidx+2 < args.size()) {
				outpad_celltype = args[++argidx];
				outpad_portname = args[++argidx];
				split_portname_pair(outpad_portname, outpad_portname2);
				continue;
			}
			if (arg == "-inoutpad" && argidx+2 < args.size()) {
				inoutpad_celltype = args[++argidx];
				inoutpad_portname = args[++argidx];
				split_portname_pair(inoutpad_portname, inoutpad_portname2);
				continue;
			}
			if (arg == "-widthparam" && argidx+1 < args.size()) {
				widthparam = args[++argidx];
				continue;
			}
			if (arg == "-nameparam" && argidx+1 < args.size()) {
				nameparam = args[++argidx];
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		for (auto &it : design->modules)
		{
			RTLIL::Module *module = it.second;

			if (!design->selected(module))
				continue;

			for (auto &it2 : module->wires)
			{
				RTLIL::Wire *wire = it2.second;

				if (!wire->port_id || !design->selected(module, wire))
					continue;

				std::string celltype, portname, portname2;

				if (wire->port_input && !wire->port_output) {
					if (inpad_celltype.empty()) {
						log("Don't map input port %s.%s: Missing option -inpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
						continue;
					}
					celltype = inpad_celltype;
					portname = inpad_portname;
					portname2 = inpad_portname2;
				} else
				if (!wire->port_input && wire->port_output) {
					if (outpad_celltype.empty()) {
						log("Don't map output port %s.%s: Missing option -outpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
						continue;
					}
					celltype = outpad_celltype;
					portname = outpad_portname;
					portname2 = outpad_portname2;
				} else
				if (wire->port_input && wire->port_output) {
					if (inoutpad_celltype.empty()) {
						log("Don't map inout port %s.%s: Missing option -inoutpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
						continue;
					}
					celltype = inoutpad_celltype;
					portname = inoutpad_portname;
					portname2 = inoutpad_portname2;
				} else
					log_abort();

				if (wire->width != 1 && widthparam.empty()) {
					log("Don't map multi-bit port %s.%s: Missing option -widthparam.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
					continue;
				}

				log("Mapping port %s.%s using %s.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name), celltype.c_str());

				RTLIL::Cell *cell = new RTLIL::Cell;
				cell->name = NEW_ID;
				cell->type = RTLIL::escape_id(celltype);
				cell->connections[RTLIL::escape_id(portname)] = RTLIL::SigSpec(wire);
				if (!portname2.empty()) {
					RTLIL::Wire *new_wire = new RTLIL::Wire;
					*new_wire = *wire;
					wire->name = NEW_ID;
					module->wires[wire->name] = wire;
					module->wires[new_wire->name] = new_wire;
					cell->connections[RTLIL::escape_id(portname2)] = RTLIL::SigSpec(new_wire);
				}
				if (!widthparam.empty())
					cell->parameters[RTLIL::escape_id(widthparam)] = RTLIL::Const(wire->width);
				if (!nameparam.empty())
					cell->parameters[RTLIL::escape_id(nameparam)] = RTLIL::Const(RTLIL::id2cstr(wire->name));
				cell->attributes["\\keep"] = RTLIL::Const(1);
				module->add(cell);

				wire->port_id = 0;
				wire->port_input = false;
				wire->port_output = false;
			}

			module->fixup_ports();
		}
	}
} IopadmapPass;

<|endoftext|>


<commit_before>// -*- coding: us-ascii-unix -*-
// Copyright 2012 Lukas Kemmer
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You
// may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.

#include "app/canvas.hh"
#include "app/context-commands.hh"
#include "bitmap/auto-crop.hh" // Fixme: Move most-common-yada to color-counting
#include "commands/command-bunch.hh"
#include "commands/flip-rotate-cmd.hh"
#include "commands/group-objects-cmd.hh"
#include "geo/axis.hh"
#include "geo/geo-func.hh"
#include "geo/rect.hh"
#include "geo/scale.hh"
#include "geo/size.hh"
#include "tools/tool-id.hh"
#include "util/apply-target.hh"
#include "util/command-util.hh"
#include "util/image.hh"
#include "util/object-util.hh"
#include "util/visit-selection.hh"

namespace faint{

Command* context_targetted(BitmapCommand* cmd, Canvas& canvas){
  return sel::visit(canvas.GetRasterSelection(),
    [=](const sel::Empty&){
      return target_full_image(cmd);
    },
    [=](const sel::Rectangle& s){
      return target_rectangle(cmd, s.Rect());
    },
    [=](const sel::Floating&){
      return target_floating_selection(cmd);
    });
}

Command* get_apply_command(const Canvas& canvas, const Operation& op){
  return dispatch_target(get_apply_target(canvas),
    [&](OBJECT_SELECTION){
      return op.DoObjects(canvas.GetImage().GetObjectSelection());
    },
    [&](RASTER_SELECTION){
      return op.DoRasterSelection(canvas.GetImage());
    },
    [&](IMAGE){
      return op.DoImage();
    });
}

static Command* context_crop_raster(const Image& active, const Paint& bg){
  return crop_to_raster_selection_command(active, bg);
}

static Command* context_crop_object(const Image& active){
  return get_crop_command(active.GetObjectSelection());
}

Command* context_crop(Canvas& canvas, const Paint& bg){
  const Image& active(canvas.GetImage());
  const Layer layer = canvas.GetTool().GetLayerType();

  Command* cmd = layer == Layer::RASTER ?
    context_crop_raster(active, bg) :
    context_crop_object(active);

  return cmd != nullptr ?
    cmd :
    // No active raster selections and no croppable objects selected,
    // do an auto-crop
    get_auto_crop_command(active);
}

void context_delete(Canvas& canvas, const Paint& bg){
  ToolInterface& tool = canvas.GetTool();

  if (tool.SupportsSelection()){
    tool.Delete();
    return;
  }

  if (tool.GetLayerType() == Layer::OBJECT){
    const Image& image = canvas.GetImage();
    const objects_t& objects = image.GetObjectSelection();
    if (objects.empty()){
      return;
    }
    canvas.RunCommand(get_delete_objects_command(objects, image));
  }
  else if (tool.GetLayerType() == Layer::RASTER){
    Command* cmd = get_delete_raster_selection_command(canvas.GetImage(), bg);
    if (cmd != nullptr){
      canvas.RunCommand(cmd);
    }
  }
  canvas.Refresh();
}

Command* context_deselect(Canvas& canvas){
  ToolInterface& tool(canvas.GetTool());
  if (tool.Deselect()){
    return nullptr;
  }

  Layer layer = tool.GetLayerType();
  if (layer == Layer::RASTER){
    const RasterSelection& selection(canvas.GetImage().GetRasterSelection());
    return selection.Exists() ?
      get_deselect_raster_command(sel::Existing(selection)) :
      nullptr;
  }
  else {
    canvas.DeselectObjects();
    canvas.Refresh(); // Fixme: Tricky, required, because no command is used
    return nullptr;
  }
}

Command* context_flatten(Canvas& canvas){
  const Image& active = canvas.GetImage();
  const objects_t& allObjects = active.GetObjects();
  if (allObjects.empty()){
    // No objects to flatten.
    return nullptr;
  }
  const objects_t& selected = active.GetObjectSelection();
  return get_flatten_command(selected.empty() ?
    allObjects : selected,
    active);
}

Command* context_flip_horizontal(const Canvas& canvas){
  return get_apply_command(canvas, OperationFlip(Axis::HORIZONTAL));
}

Command* context_flip_vertical(const Canvas& canvas){
  return get_apply_command(canvas, OperationFlip(Axis::VERTICAL));
}

Command* context_offset(Canvas& canvas, const IntPoint& delta){
  return dispatch_target(get_apply_target(canvas),
    [&](OBJECT_SELECTION){
      const objects_t& objectSelection(canvas.GetImage().GetObjectSelection());
      return get_offset_objects_command(objectSelection,
        floated(delta));
    },
    [&](RASTER_SELECTION){
      return get_offset_raster_selection_command(canvas.GetImage(), delta);
    },
    [&](IMAGE) -> Command*{
      canvas.SetScrollPos(canvas.GetScrollPos() + delta);
      return nullptr;
    });
}

static Command* pixel_snap(const objects_t& objects){
  if (objects.empty()){
    return nullptr;
  }

  std::vector<Command*> cmds;
  for (auto obj : objects){
    auto* cmd = get_pixel_snap_command(obj);
    if (obj != nullptr){
      cmds.push_back(cmd);
    }
  }
  if (cmds.empty()){
    return nullptr;
  }
  else if (cmds.size() == 1){
    return cmds.front();
  }
  else{
    return perhaps_bunch(CommandType::OBJECT, bunch_name("Pixel Snap"),
      cmds);
  }
}

Command* context_pixel_snap(Canvas& canvas){
  const objects_t& objectSelection(canvas.GetImage().GetObjectSelection());
  return objectSelection.empty() ? pixel_snap(canvas.GetImage().GetObjects())
    : pixel_snap(objectSelection);
}

Command* context_rotate90cw(const Canvas& canvas){
  return dispatch_target(get_apply_target(canvas),
    [&](OBJECT_SELECTION){
      const objects_t& objectSelection(canvas.GetImage().GetObjectSelection());
      Point origin = bounding_rect(objectSelection).Center();
      return get_rotate_command(objectSelection,
        pi / 2,
        origin);
    },

    [&](RASTER_SELECTION){
      return get_rotate_selection_command(canvas.GetImage());
    },

    [&](IMAGE){
      return rotate_image_90cw_command();
    });
}

Command* context_rotate(const Canvas& canvas,
  const Angle& angle,
  const Paint& bg)
{
  return dispatch_target(get_apply_target(canvas),
    [&](OBJECT_SELECTION){
      const objects_t& objectSelection(canvas.GetImage().GetObjectSelection());
      Point origin = bounding_rect(objectSelection).Center();
      return get_rotate_command(objectSelection, angle, origin);
    },

    [&](RASTER_SELECTION){
      return get_rotate_selection_command(canvas.GetImage(),
        angle, bg);
    },

    [&](IMAGE){
      const Bitmap& bmp(canvas.GetBackground().Expect<Bitmap>());
      auto altBg(alternate(Paint(most_common_edge_color(bmp))));
      return rotate_image_command(angle, bg, altBg);
    });
}

Command* context_select_all(Canvas& canvas, const change_tool_f& selectTool){
  ToolInterface& tool(canvas.GetTool());

  if (tool.SelectAll()){
    // Selection within a tool is not handled by a command
    return nullptr;
  }

  Layer layer = tool.GetLayerType();
  if (layer == Layer::RASTER){
    const Image& active(canvas.GetImage());
    selectTool(ToolId::SELECTION);
    return get_select_all_command(active,
      active.GetRasterSelection());
  }
  else {
    canvas.SelectObjects(canvas.GetObjects(), deselect_old(true));
    selectTool(ToolId::SELECTION);
    // Object selection is not handled with commands
    return nullptr;
  }
}

Command* context_set_alpha(Canvas& canvas, uchar alpha){
  BitmapCommand* cmd = get_set_alpha_command(alpha);
  return context_targetted(cmd, canvas);
}

Command* context_scale_objects(const Canvas& canvas, const Size& size){
  // Fixme: Make this take the list of objects instead
  const Image& active = canvas.GetImage();
  const objects_t& objectSelection(active.GetObjectSelection());
  Rect oldRect = bounding_rect(objectSelection);
  Point origin = oldRect.TopLeft();
  Scale scale(New(size), oldRect.GetSize());
  return get_scale_command(objectSelection, scale, origin);
}

Command* group_selected_objects(Canvas& canvas){
  const Image& active(canvas.GetImage());
  const objects_t& objectSelection(active.GetObjectSelection());

  if (objectSelection.size() <= 1){
    // Need at least two objects to group
    return nullptr;
  }
  cmd_and_group_t cmd =
    group_objects_command(objectSelection, select_added(true));
  return cmd.first;
}

Command* context_objects_backward(Canvas& canvas){
  const Image& active(canvas.GetImage());
  const objects_t& objectSelection(active.GetObjectSelection());
  if (objectSelection.empty()){
    return nullptr;
  }
  return get_objects_backward_command(objectSelection, active);
}

Command* context_objects_forward(Canvas& canvas){
  const Image& active(canvas.GetImage());
  const objects_t& objectSelection(active.GetObjectSelection());
  if (objectSelection.empty()){
    return nullptr;
  }
  return get_objects_forward_command(objectSelection, active);
}

Command* context_objects_to_front(Canvas& canvas){
  const Image& active(canvas.GetImage());
  const objects_t& objectSelection(active.GetObjectSelection());
  if (objectSelection.empty()){
    return nullptr;
  }
  return get_objects_to_front_command(objectSelection, active);
}

Command* context_objects_to_path(Canvas& canvas){
  const Image& image(canvas.GetImage());
  const objects_t& selection(image.GetObjectSelection());
  if (selection.empty()){
    return nullptr;
  }

  return get_objects_to_paths_command(selection, image, select_added(true));
}

Command* context_objects_to_back(Canvas& canvas){
  const Image& active(canvas.GetImage());
  const objects_t& objectSelection(active.GetObjectSelection());
  if (objectSelection.empty()){
    return nullptr;
  }
  return get_objects_to_back_command(objectSelection, active);
}

Command* ungroup_selected_objects(Canvas& canvas){
  const Image& active(canvas.GetImage());
  objects_t groups = get_groups(active.GetObjectSelection());
  if (groups.empty()){
    return nullptr;
  }
  return ungroup_objects_command(groups, select_added(true));
}

}  // namespace
<commit_msg>Removed fixme comment.<commit_after>// -*- coding: us-ascii-unix -*-
// Copyright 2012 Lukas Kemmer
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You
// may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.

#include "app/canvas.hh"
#include "app/context-commands.hh"
#include "bitmap/auto-crop.hh"
#include "commands/command-bunch.hh"
#include "commands/flip-rotate-cmd.hh"
#include "commands/group-objects-cmd.hh"
#include "geo/axis.hh"
#include "geo/geo-func.hh"
#include "geo/rect.hh"
#include "geo/scale.hh"
#include "geo/size.hh"
#include "tools/tool-id.hh"
#include "util/apply-target.hh"
#include "util/command-util.hh"
#include "util/image.hh"
#include "util/object-util.hh"
#include "util/visit-selection.hh"

namespace faint{

Command* context_targetted(BitmapCommand* cmd, Canvas& canvas){
  return sel::visit(canvas.GetRasterSelection(),
    [=](const sel::Empty&){
      return target_full_image(cmd);
    },
    [=](const sel::Rectangle& s){
      return target_rectangle(cmd, s.Rect());
    },
    [=](const sel::Floating&){
      return target_floating_selection(cmd);
    });
}

Command* get_apply_command(const Canvas& canvas, const Operation& op){
  return dispatch_target(get_apply_target(canvas),
    [&](OBJECT_SELECTION){
      return op.DoObjects(canvas.GetImage().GetObjectSelection());
    },
    [&](RASTER_SELECTION){
      return op.DoRasterSelection(canvas.GetImage());
    },
    [&](IMAGE){
      return op.DoImage();
    });
}

static Command* context_crop_raster(const Image& active, const Paint& bg){
  return crop_to_raster_selection_command(active, bg);
}

static Command* context_crop_object(const Image& active){
  return get_crop_command(active.GetObjectSelection());
}

Command* context_crop(Canvas& canvas, const Paint& bg){
  const Image& active(canvas.GetImage());
  const Layer layer = canvas.GetTool().GetLayerType();

  Command* cmd = layer == Layer::RASTER ?
    context_crop_raster(active, bg) :
    context_crop_object(active);

  return cmd != nullptr ?
    cmd :
    // No active raster selections and no croppable objects selected,
    // do an auto-crop
    get_auto_crop_command(active);
}

void context_delete(Canvas& canvas, const Paint& bg){
  ToolInterface& tool = canvas.GetTool();

  if (tool.SupportsSelection()){
    tool.Delete();
    return;
  }

  if (tool.GetLayerType() == Layer::OBJECT){
    const Image& image = canvas.GetImage();
    const objects_t& objects = image.GetObjectSelection();
    if (objects.empty()){
      return;
    }
    canvas.RunCommand(get_delete_objects_command(objects, image));
  }
  else if (tool.GetLayerType() == Layer::RASTER){
    Command* cmd = get_delete_raster_selection_command(canvas.GetImage(), bg);
    if (cmd != nullptr){
      canvas.RunCommand(cmd);
    }
  }
  canvas.Refresh();
}

Command* context_deselect(Canvas& canvas){
  ToolInterface& tool(canvas.GetTool());
  if (tool.Deselect()){
    return nullptr;
  }

  Layer layer = tool.GetLayerType();
  if (layer == Layer::RASTER){
    const RasterSelection& selection(canvas.GetImage().GetRasterSelection());
    return selection.Exists() ?
      get_deselect_raster_command(sel::Existing(selection)) :
      nullptr;
  }
  else {
    canvas.DeselectObjects();
    canvas.Refresh(); // Fixme: Tricky, required, because no command is used
    return nullptr;
  }
}

Command* context_flatten(Canvas& canvas){
  const Image& active = canvas.GetImage();
  const objects_t& allObjects = active.GetObjects();
  if (allObjects.empty()){
    // No objects to flatten.
    return nullptr;
  }
  const objects_t& selected = active.GetObjectSelection();
  return get_flatten_command(selected.empty() ?
    allObjects : selected,
    active);
}

Command* context_flip_horizontal(const Canvas& canvas){
  return get_apply_command(canvas, OperationFlip(Axis::HORIZONTAL));
}

Command* context_flip_vertical(const Canvas& canvas){
  return get_apply_command(canvas, OperationFlip(Axis::VERTICAL));
}

Command* context_offset(Canvas& canvas, const IntPoint& delta){
  return dispatch_target(get_apply_target(canvas),
    [&](OBJECT_SELECTION){
      const objects_t& objectSelection(canvas.GetImage().GetObjectSelection());
      return get_offset_objects_command(objectSelection,
        floated(delta));
    },
    [&](RASTER_SELECTION){
      return get_offset_raster_selection_command(canvas.GetImage(), delta);
    },
    [&](IMAGE) -> Command*{
      canvas.SetScrollPos(canvas.GetScrollPos() + delta);
      return nullptr;
    });
}

static Command* pixel_snap(const objects_t& objects){
  if (objects.empty()){
    return nullptr;
  }

  std::vector<Command*> cmds;
  for (auto obj : objects){
    auto* cmd = get_pixel_snap_command(obj);
    if (obj != nullptr){
      cmds.push_back(cmd);
    }
  }
  if (cmds.empty()){
    return nullptr;
  }
  else if (cmds.size() == 1){
    return cmds.front();
  }
  else{
    return perhaps_bunch(CommandType::OBJECT, bunch_name("Pixel Snap"),
      cmds);
  }
}

Command* context_pixel_snap(Canvas& canvas){
  const objects_t& objectSelection(canvas.GetImage().GetObjectSelection());
  return objectSelection.empty() ? pixel_snap(canvas.GetImage().GetObjects())
    : pixel_snap(objectSelection);
}

Command* context_rotate90cw(const Canvas& canvas){
  return dispatch_target(get_apply_target(canvas),
    [&](OBJECT_SELECTION){
      const objects_t& objectSelection(canvas.GetImage().GetObjectSelection());
      Point origin = bounding_rect(objectSelection).Center();
      return get_rotate_command(objectSelection,
        pi / 2,
        origin);
    },

    [&](RASTER_SELECTION){
      return get_rotate_selection_command(canvas.GetImage());
    },

    [&](IMAGE){
      return rotate_image_90cw_command();
    });
}

Command* context_rotate(const Canvas& canvas,
  const Angle& angle,
  const Paint& bg)
{
  return dispatch_target(get_apply_target(canvas),
    [&](OBJECT_SELECTION){
      const objects_t& objectSelection(canvas.GetImage().GetObjectSelection());
      Point origin = bounding_rect(objectSelection).Center();
      return get_rotate_command(objectSelection, angle, origin);
    },

    [&](RASTER_SELECTION){
      return get_rotate_selection_command(canvas.GetImage(),
        angle, bg);
    },

    [&](IMAGE){
      const Bitmap& bmp(canvas.GetBackground().Expect<Bitmap>());
      auto altBg(alternate(Paint(most_common_edge_color(bmp))));
      return rotate_image_command(angle, bg, altBg);
    });
}

Command* context_select_all(Canvas& canvas, const change_tool_f& selectTool){
  ToolInterface& tool(canvas.GetTool());

  if (tool.SelectAll()){
    // Selection within a tool is not handled by a command
    return nullptr;
  }

  Layer layer = tool.GetLayerType();
  if (layer == Layer::RASTER){
    const Image& active(canvas.GetImage());
    selectTool(ToolId::SELECTION);
    return get_select_all_command(active,
      active.GetRasterSelection());
  }
  else {
    canvas.SelectObjects(canvas.GetObjects(), deselect_old(true));
    selectTool(ToolId::SELECTION);
    // Object selection is not handled with commands
    return nullptr;
  }
}

Command* context_set_alpha(Canvas& canvas, uchar alpha){
  BitmapCommand* cmd = get_set_alpha_command(alpha);
  return context_targetted(cmd, canvas);
}

Command* context_scale_objects(const Canvas& canvas, const Size& size){
  // Fixme: Make this take the list of objects instead
  const Image& active = canvas.GetImage();
  const objects_t& objectSelection(active.GetObjectSelection());
  Rect oldRect = bounding_rect(objectSelection);
  Point origin = oldRect.TopLeft();
  Scale scale(New(size), oldRect.GetSize());
  return get_scale_command(objectSelection, scale, origin);
}

Command* group_selected_objects(Canvas& canvas){
  const Image& active(canvas.GetImage());
  const objects_t& objectSelection(active.GetObjectSelection());

  if (objectSelection.size() <= 1){
    // Need at least two objects to group
    return nullptr;
  }
  cmd_and_group_t cmd =
    group_objects_command(objectSelection, select_added(true));
  return cmd.first;
}

Command* context_objects_backward(Canvas& canvas){
  const Image& active(canvas.GetImage());
  const objects_t& objectSelection(active.GetObjectSelection());
  if (objectSelection.empty()){
    return nullptr;
  }
  return get_objects_backward_command(objectSelection, active);
}

Command* context_objects_forward(Canvas& canvas){
  const Image& active(canvas.GetImage());
  const objects_t& objectSelection(active.GetObjectSelection());
  if (objectSelection.empty()){
    return nullptr;
  }
  return get_objects_forward_command(objectSelection, active);
}

Command* context_objects_to_front(Canvas& canvas){
  const Image& active(canvas.GetImage());
  const objects_t& objectSelection(active.GetObjectSelection());
  if (objectSelection.empty()){
    return nullptr;
  }
  return get_objects_to_front_command(objectSelection, active);
}

Command* context_objects_to_path(Canvas& canvas){
  const Image& image(canvas.GetImage());
  const objects_t& selection(image.GetObjectSelection());
  if (selection.empty()){
    return nullptr;
  }

  return get_objects_to_paths_command(selection, image, select_added(true));
}

Command* context_objects_to_back(Canvas& canvas){
  const Image& active(canvas.GetImage());
  const objects_t& objectSelection(active.GetObjectSelection());
  if (objectSelection.empty()){
    return nullptr;
  }
  return get_objects_to_back_command(objectSelection, active);
}

Command* ungroup_selected_objects(Canvas& canvas){
  const Image& active(canvas.GetImage());
  objects_t groups = get_groups(active.GetObjectSelection());
  if (groups.empty()){
    return nullptr;
  }
  return ungroup_objects_command(groups, select_added(true));
}

}  // namespace
<|endoftext|>


<commit_before>/*
    Copyright (c) 2013, Taiga Nomi
    All rights reserved.

    Use of this source code is governed by a BSD-style license that can be found
    in the LICENSE file.
*/
#include <iostream>
#include "tiny_dnn/tiny_dnn.h"

using namespace tiny_dnn;
using namespace tiny_dnn::activation;

static void construct_net(network<sequential>& nn) {
// connection table [Y.Lecun, 1998 Table.1]
#define O true
#define X false
  // clang-format off
    static const bool tbl[] = {
        O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O,
        O, O, X, X, X, O, O, O, X, X, O, O, O, O, X, O,
        O, O, O, X, X, X, O, O, O, X, X, O, X, O, O, O,
        X, O, O, O, X, X, O, O, O, O, X, X, O, X, O, O,
        X, X, O, O, O, X, X, O, O, O, O, X, O, O, X, O,
        X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O
    };
// clang-format on
#undef O
#undef X

  // by default will use backend_t::tiny_dnn unless you compiled
  // with -DUSE_AVX=ON and your device supports AVX intrinsics
  core::backend_t backend_type = core::default_engine();

  // construct nets
  //
  // C : convolution
  // S : sub-sampling
  // F : fully connected
  nn << convolutional_layer<tan_h>(32, 32, 5, 1,
                                   6,  // C1, 1@32x32-in, 6@28x28-out
                                   padding::valid, true, 1, 1, backend_type)
     << average_pooling_layer<tan_h>(28, 28, 6,
                                     2)  // S2, 6@28x28-in, 6@14x14-out
     << convolutional_layer<tan_h>(14, 14, 5, 6,
                                   16,  // C3, 6@14x14-in, 16@10x10-out
                                   connection_table(tbl, 6, 16), padding::valid,
                                   true, 1, 1, backend_type)
     << average_pooling_layer<tan_h>(10, 10, 16,
                                     2)  // S4, 16@10x10-in, 16@5x5-out
     << convolutional_layer<tan_h>(5, 5, 5, 16,
                                   120,  // C5, 16@5x5-in, 120@1x1-out
                                   padding::valid, true, 1, 1, backend_type)
     << fully_connected_layer<tan_h>(120, 10,  // F6, 120-in, 10-out
                                     true, backend_type);
}

static void train_lenet(const std::string& data_dir_path) {
  // specify loss-function and learning strategy
  network<sequential> nn;
  adagrad optimizer;

  construct_net(nn);

  std::cout << "load models..." << std::endl;

  // load MNIST dataset
  std::vector<label_t> train_labels, test_labels;
  std::vector<vec_t> train_images, test_images;

  parse_mnist_labels(data_dir_path + "/train-labels.idx1-ubyte", &train_labels);
  parse_mnist_images(data_dir_path + "/train-images.idx3-ubyte", &train_images,
                     -1.0, 1.0, 2, 2);
  parse_mnist_labels(data_dir_path + "/t10k-labels.idx1-ubyte", &test_labels);
  parse_mnist_images(data_dir_path + "/t10k-images.idx3-ubyte", &test_images,
                     -1.0, 1.0, 2, 2);

  std::cout << "start training" << std::endl;

  progress_display disp(static_cast<unsigned long>(train_images.size()));
  timer t;
  int minibatch_size = 10;
  int num_epochs     = 30;

  optimizer.alpha *= static_cast<tiny_dnn::float_t>(std::sqrt(minibatch_size));

  // create callback
  auto on_enumerate_epoch = [&]() {
    std::cout << t.elapsed() << "s elapsed." << std::endl;
    tiny_dnn::result res = nn.test(test_images, test_labels);
    std::cout << res.num_success << "/" << res.num_total << std::endl;

    disp.restart(static_cast<unsigned long>(train_images.size()));
    t.restart();
  };

  auto on_enumerate_minibatch = [&]() { disp += minibatch_size; };

  // training
  nn.train<mse>(optimizer, train_images, train_labels, minibatch_size,
                num_epochs, on_enumerate_minibatch, on_enumerate_epoch);

  std::cout << "end training." << std::endl;

  // test and show results
  nn.test(test_images, test_labels).print_detail(std::cout);

  // save network model & trained weights
  nn.save("LeNet-model");
}

int main(int argc, char** argv) {
  if (argc != 2) {
    std::cerr << "Usage : " << argv[0] << " path_to_data (example:../data)"
              << std::endl;
    return -1;
  }
  train_lenet(argv[1]);
  return 0;
}
<commit_msg>MNIST enhanced performance. Faster convergence, better score (#574)<commit_after>/*
    Copyright (c) 2013, Taiga Nomi
    All rights reserved.

    Use of this source code is governed by a BSD-style license that can be found
    in the LICENSE file.
*/
#include <iostream>
#include "tiny_dnn/tiny_dnn.h"

using namespace tiny_dnn;
using namespace tiny_dnn::activation;

static void construct_net(network<sequential>& nn) {
// connection table [Y.Lecun, 1998 Table.1]
#define O true
#define X false
  // clang-format off
    static const bool tbl[] = {
        O, X, X, X, O, O, O, X, X, O, O, O, O, X, O, O,
        O, O, X, X, X, O, O, O, X, X, O, O, O, O, X, O,
        O, O, O, X, X, X, O, O, O, X, X, O, X, O, O, O,
        X, O, O, O, X, X, O, O, O, O, X, X, O, X, O, O,
        X, X, O, O, O, X, X, O, O, O, O, X, O, O, X, O,
        X, X, X, O, O, O, X, X, O, O, O, O, X, O, O, O
    };
// clang-format on
#undef O
#undef X

  // by default will use backend_t::tiny_dnn unless you compiled
  // with -DUSE_AVX=ON and your device supports AVX intrinsics
  core::backend_t backend_type = core::default_engine();

  // construct nets
  //
  // C : convolution
  // S : sub-sampling
  // F : fully connected
  nn << convolutional_layer<tan_h>(32, 32, 5, 1,
                                   6,  // C1, 1@32x32-in, 6@28x28-out
                                   padding::valid, true, 1, 1, backend_type)
     << average_pooling_layer<tan_h>(28, 28, 6,
                                     2)  // S2, 6@28x28-in, 6@14x14-out
     << convolutional_layer<tan_h>(14, 14, 5, 6,
                                   16,  // C3, 6@14x14-in, 16@10x10-out
                                   connection_table(tbl, 6, 16), padding::valid,
                                   true, 1, 1, backend_type)
     << average_pooling_layer<tan_h>(10, 10, 16,
                                     2)  // S4, 16@10x10-in, 16@5x5-out
     << convolutional_layer<tan_h>(5, 5, 5, 16,
                                   120,  // C5, 16@5x5-in, 120@1x1-out
                                   padding::valid, true, 1, 1, backend_type)
     << fully_connected_layer<tan_h>(120, 10,  // F6, 120-in, 10-out
                                     true, backend_type);
}

static void train_lenet(const std::string& data_dir_path) {
  // specify loss-function and learning strategy
  network<sequential> nn;
  adagrad optimizer;

  construct_net(nn);

  std::cout << "load models..." << std::endl;

  // load MNIST dataset
  std::vector<label_t> train_labels, test_labels;
  std::vector<vec_t> train_images, test_images;

  parse_mnist_labels(data_dir_path + "/train-labels.idx1-ubyte", &train_labels);
  parse_mnist_images(data_dir_path + "/train-images.idx3-ubyte", &train_images,
                     -1.0, 1.0, 2, 2);
  parse_mnist_labels(data_dir_path + "/t10k-labels.idx1-ubyte", &test_labels);
  parse_mnist_images(data_dir_path + "/t10k-images.idx3-ubyte", &test_images,
                     -1.0, 1.0, 2, 2);

  std::cout << "start training" << std::endl;

  progress_display disp(static_cast<unsigned long>(train_images.size()));
  timer t;
  int minibatch_size = 16;
  int num_epochs     = 30;

  optimizer.alpha *=
    std::min(tiny_dnn::float_t(4),
             static_cast<tiny_dnn::float_t>(std::sqrt(minibatch_size)));

  // create callback
  auto on_enumerate_epoch = [&]() {
    std::cout << t.elapsed() << "s elapsed." << std::endl;
    tiny_dnn::result res = nn.test(test_images, test_labels);
    std::cout << res.num_success << "/" << res.num_total << std::endl;

    disp.restart(static_cast<unsigned long>(train_images.size()));
    t.restart();
  };

  auto on_enumerate_minibatch = [&]() { disp += minibatch_size; };

  // training
  nn.train<mse>(optimizer, train_images, train_labels, minibatch_size,
                num_epochs, on_enumerate_minibatch, on_enumerate_epoch);

  std::cout << "end training." << std::endl;

  // test and show results
  nn.test(test_images, test_labels).print_detail(std::cout);

  // save network model & trained weights
  nn.save("LeNet-model");
}

int main(int argc, char** argv) {
  if (argc != 2) {
    std::cerr << "Usage : " << argv[0] << " path_to_data (example:../data)"
              << std::endl;
    return -1;
  }
  train_lenet(argv[1]);
  return 0;
}
<|endoftext|>


<commit_before>// STL
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>

// Boost
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/scoped_ptr.hpp>

// Local
#include "pyp-topics.hh"
#include "corpus.hh"
#include "contexts_corpus.hh"
#include "gzstream.hh"
#include "mt19937ar.h"

static const char *REVISION = "$Rev$";

// Namespaces
using namespace boost;
using namespace boost::program_options;
using namespace std;

int main(int argc, char **argv)
{
 cout << "Pitman Yor topic models: Copyright 2010 Phil Blunsom\n";
 cout << REVISION << '\n' <<endl;

  ////////////////////////////////////////////////////////////////////////////////////////////
  // Command line processing
  variables_map vm;

  // Command line processing
  {
    options_description cmdline_options("Allowed options");
    cmdline_options.add_options()
      ("help,h", "print help message")
      ("data,d", value<string>(), "file containing the documents and context terms")
      ("topics,t", value<int>()->default_value(50), "number of topics")
      ("document-topics-out,o", value<string>(), "file to write the document topics to")
      ("default-topics-out", value<string>(), "file to write default term topic assignments.")
      ("topic-words-out,w", value<string>(), "file to write the topic word distribution to")
      ("samples,s", value<int>()->default_value(10), "number of sampling passes through the data")
      ("backoff-type", value<string>(), "backoff type: none|simple")
      ("filter-singleton-contexts", "filter singleton contexts")
      ("hierarchical-topics", "Use a backoff hierarchical PYP as the P0 for the document topics distribution.")
      ;
    store(parse_command_line(argc, argv, cmdline_options), vm);
    notify(vm);

    if (vm.count("help")) {
      cout << cmdline_options << "\n";
      return 1;
    }
  }
  ////////////////////////////////////////////////////////////////////////////////////////////

  if (!vm.count("data")) {
    cerr << "Please specify a file containing the data." << endl;
    return 1;
  }

  // seed the random number generator
  //mt_init_genrand(time(0));

  PYPTopics model(vm["topics"].as<int>(), vm.count("hierarchical-topics"));

  // read the data
  BackoffGenerator* backoff_gen=0;
  if (vm.count("backoff-type")) {
    if (vm["backoff-type"].as<std::string>() == "none") {
      backoff_gen = 0;
    }
    else if (vm["backoff-type"].as<std::string>() == "simple") {
      backoff_gen = new SimpleBackoffGenerator();
    }
    else {
     cerr << "Backoff type (--backoff-type) must be one of none|simple." <<endl;
      return(1);
    }
  }

  ContextsCorpus contexts_corpus;
  contexts_corpus.read_contexts(vm["data"].as<string>(), backoff_gen, vm.count("filter-singleton-contexts"));
  model.set_backoff(contexts_corpus.backoff_index());

  if (backoff_gen)
    delete backoff_gen;

  // train the sampler
  model.sample(contexts_corpus, vm["samples"].as<int>());

  if (vm.count("document-topics-out")) {
    ogzstream documents_out(vm["document-topics-out"].as<string>().c_str());

    int document_id=0;
   map<int,int> all_terms;
    for (Corpus::const_iterator corpusIt=contexts_corpus.begin();
         corpusIt != contexts_corpus.end(); ++corpusIt, ++document_id) {
     vector<int> unique_terms;
      for (Document::const_iterator docIt=corpusIt->begin();
           docIt != corpusIt->end(); ++docIt) {
        if (unique_terms.empty() || *docIt != unique_terms.back())
          unique_terms.push_back(*docIt);
      }
      documents_out << contexts_corpus.key(document_id) << '\t';
      for (std::vector<int>::const_iterator termIt=unique_terms.begin();
           termIt != unique_terms.end(); ++termIt) {
        if (termIt != unique_terms.begin())
          documents_out << " ||| ";
       vector<std::string> strings = contexts_corpus.context2string(*termIt);
       copy(strings.begin(), strings.end(),ostream_iterator<std::string>(documents_out, " "));
        documents_out << "||| C=" << model.max(document_id, *termIt);

        // increment this terms frequency
        pair<map<int,int>::iterator,bool> insert_result = all_terms.insert(make_pair(*termIt,1));
        if (!insert_result.second)
          //insert_result.first++;
          all_terms[*termIt] += 1;
      }
      documents_out <<endl;
    }
    documents_out.close();

   ofstream default_topics(vm["default-topics-out"].as<string>().c_str());
    default_topics << model.max_topic() <<endl;
    for (std::map<int,int>::const_iterator termIt=all_terms.begin(); termIt != all_terms.end(); ++termIt) {
     vector<std::string> strings = contexts_corpus.context2string(termIt->first);
      default_topics << model.max(-1, termIt->first) << " ||| " << termIt->second << " ||| ";
     copy(strings.begin(), strings.end(),ostream_iterator<std::string>(default_topics, " "));
      default_topics <<endl;
    }
  }

  if (vm.count("topic-words-out")) {
    ogzstream topics_out(vm["topic-words-out"].as<string>().c_str());
    model.print_topic_terms(topics_out);
    topics_out.close();
  }

 cout <<endl;

  return 0;
}
<commit_msg><commit_after>// STL
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>

// Boost
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/scoped_ptr.hpp>

// Local
#include "pyp-topics.hh"
#include "corpus.hh"
#include "contexts_corpus.hh"
#include "gzstream.hh"
#include "mt19937ar.h"

static const char *REVISION = "$Rev$";

// Namespaces
using namespace boost;
using namespace boost::program_options;
using namespace std;

int main(int argc, char **argv)
{
 cout << "Pitman Yor topic models: Copyright 2010 Phil Blunsom\n";
 cout << REVISION << '\n' <<endl;

  ////////////////////////////////////////////////////////////////////////////////////////////
  // Command line processing
  variables_map vm;

  // Command line processing
  {
    options_description cmdline_options("Allowed options");
    cmdline_options.add_options()
      ("help,h", "print help message")
      ("data,d", value<string>(), "file containing the documents and context terms")
      ("topics,t", value<int>()->default_value(50), "number of topics")
      ("document-topics-out,o", value<string>(), "file to write the document topics to")
      ("default-topics-out", value<string>(), "file to write default term topic assignments.")
      ("topic-words-out,w", value<string>(), "file to write the topic word distribution to")
      ("samples,s", value<int>()->default_value(10), "number of sampling passes through the data")
      ("backoff-type", value<string>(), "backoff type: none|simple")
      ("filter-singleton-contexts", "filter singleton contexts")
      ("hierarchical-topics", "Use a backoff hierarchical PYP as the P0 for the document topics distribution.")
      ;
    store(parse_command_line(argc, argv, cmdline_options), vm);
    notify(vm);

    if (vm.count("help")) {
      cout << cmdline_options << "\n";
      return 1;
    }
  }
  ////////////////////////////////////////////////////////////////////////////////////////////

  if (!vm.count("data")) {
    cerr << "Please specify a file containing the data." << endl;
    return 1;
  }

  // seed the random number generator
  //mt_init_genrand(time(0));

  PYPTopics model(vm["topics"].as<int>(), vm.count("hierarchical-topics"));

  // read the data
  BackoffGenerator* backoff_gen=0;
  if (vm.count("backoff-type")) {
    if (vm["backoff-type"].as<std::string>() == "none") {
      backoff_gen = 0;
    }
    else if (vm["backoff-type"].as<std::string>() == "simple") {
      backoff_gen = new SimpleBackoffGenerator();
    }
    else {
     cerr << "Backoff type (--backoff-type) must be one of none|simple." <<endl;
      return(1);
    }
  }

  ContextsCorpus contexts_corpus;
  contexts_corpus.read_contexts(vm["data"].as<string>(), backoff_gen, vm.count("filter-singleton-contexts"));
  model.set_backoff(contexts_corpus.backoff_index());

  if (backoff_gen)
    delete backoff_gen;

  // train the sampler
  model.sample(contexts_corpus, vm["samples"].as<int>());

  if (vm.count("document-topics-out")) {
    ogzstream documents_out(vm["document-topics-out"].as<string>().c_str());

    int document_id=0;
   map<int,int> all_terms;
    for (Corpus::const_iterator corpusIt=contexts_corpus.begin();
         corpusIt != contexts_corpus.end(); ++corpusIt, ++document_id) {
     vector<int> unique_terms;
      for (Document::const_iterator docIt=corpusIt->begin();
           docIt != corpusIt->end(); ++docIt) {
        if (unique_terms.empty() || *docIt != unique_terms.back())
          unique_terms.push_back(*docIt);
        // increment this terms frequency
        pair<map<int,int>::iterator,bool> insert_result = all_terms.insert(make_pair(*docIt,1));
        if (!insert_result.second)
          insert_result.first++;
      }
      documents_out << contexts_corpus.key(document_id) << '\t';
      for (std::vector<int>::const_iterator termIt=unique_terms.begin();
           termIt != unique_terms.end(); ++termIt) {
        if (termIt != unique_terms.begin())
          documents_out << " ||| ";
       vector<std::string> strings = contexts_corpus.context2string(*termIt);
       copy(strings.begin(), strings.end(),ostream_iterator<std::string>(documents_out, " "));
        documents_out << "||| C=" << model.max(document_id, *termIt);

      }
      documents_out <<endl;
    }
    documents_out.close();

   ofstream default_topics(vm["default-topics-out"].as<string>().c_str());
    default_topics << model.max_topic() <<endl;
    for (std::map<int,int>::const_iterator termIt=all_terms.begin(); termIt != all_terms.end(); ++termIt) {
     vector<std::string> strings = contexts_corpus.context2string(termIt->first);
      default_topics << model.max(-1, termIt->first) << " ||| " << termIt->second << " ||| ";
     copy(strings.begin(), strings.end(),ostream_iterator<std::string>(default_topics, " "));
      default_topics <<endl;
    }
  }

  if (vm.count("topic-words-out")) {
    ogzstream topics_out(vm["topic-words-out"].as<string>().c_str());
    model.print_topic_terms(topics_out);
    topics_out.close();
  }

 cout <<endl;

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/test/trace_event_analyzer.h"
#include "base/version.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/tracing.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/gpu/gpu_blacklist.h"
#include "content/browser/gpu/gpu_data_manager.h"
#include "net/base/net_util.h"
#include "ui/gfx/gl/gl_switches.h"

namespace {

typedef uint32 GpuResultFlags;
#define EXPECT_NO_GPU_PROCESS         GpuResultFlags(1<<0)
// Expect a SwapBuffers to occur (see gles2_cmd_decoder.cc).
#define EXPECT_GPU_SWAP_BUFFERS       GpuResultFlags(1<<1)

class GpuFeatureTest : public InProcessBrowserTest {
 public:
  GpuFeatureTest() {}

  virtual void SetUpCommandLine(CommandLine* command_line) {
    // This enables DOM automation for tab contents.
    EnableDOMAutomation();
#if !defined(OS_MACOSX)
    CHECK(test_launcher_utils::OverrideGLImplementation(
        command_line, gfx::kGLImplementationOSMesaName)) <<
        "kUseGL must not be set by test framework code!";
#endif
  }

  void SetupBlacklist(const std::string& json_blacklist) {
    scoped_ptr<Version> os_version(Version::GetVersionFromString("1.0"));
    GpuBlacklist* blacklist = new GpuBlacklist("1.0");

    ASSERT_TRUE(blacklist->LoadGpuBlacklist(
        json_blacklist, GpuBlacklist::kAllOs));
    GpuDataManager::GetInstance()->SetGpuBlacklist(blacklist);
  }

  void RunTest(const FilePath& url, GpuResultFlags expectations) {
    using namespace trace_analyzer;

    FilePath test_path;
    PathService::Get(chrome::DIR_TEST_DATA, &test_path);
    test_path = test_path.Append(FILE_PATH_LITERAL("gpu"));
    test_path = test_path.Append(url);

    ASSERT_TRUE(file_util::PathExists(test_path))
        << "Missing test file: " << test_path.value();

    ASSERT_TRUE(tracing::BeginTracing("test_gpu"));

    ui_test_utils::DOMMessageQueue message_queue;
    // Have to use a new tab for the blacklist to work.
    ui_test_utils::NavigateToURLWithDisposition(
        browser(), net::FilePathToFileURL(test_path), NEW_FOREGROUND_TAB,
        ui_test_utils::BROWSER_TEST_NONE);
    // Wait for message indicating the test has finished running.
    ASSERT_TRUE(message_queue.WaitForMessage(NULL));

    std::string json_events;
    ASSERT_TRUE(tracing::EndTracing(&json_events));

    scoped_ptr<TraceAnalyzer> analyzer(TraceAnalyzer::Create(json_events));
    analyzer->AssociateBeginEndEvents();
    TraceEventVector events;

    // This measurement is flaky, because the GPU process is sometimes
    // started before the test (always with force-compositing-mode on CrOS).
    if (expectations & EXPECT_NO_GPU_PROCESS) {
      EXPECT_EQ(0u, analyzer->FindEvents(
          Query::MatchBeginName("OnGraphicsInfoCollected"), &events));
    }

    // Check for swap buffers if expected:
    if (expectations & EXPECT_GPU_SWAP_BUFFERS) {
      EXPECT_GT(analyzer->FindEvents(Query(EVENT_NAME) ==
                                     Query::String("SwapBuffers"), &events),
                size_t(0));
    }
  }
};

IN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingAllowed) {
  GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
  EXPECT_EQ(flags.flags(), 0u);

  const FilePath url(FILE_PATH_LITERAL("feature_compositing.html"));
  RunTest(url, EXPECT_GPU_SWAP_BUFFERS);
}

IN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingBlocked) {
  const std::string json_blacklist =
      "{\n"
      "  \"name\": \"gpu blacklist\",\n"
      "  \"version\": \"1.0\",\n"
      "  \"entries\": [\n"
      "    {\n"
      "      \"id\": 1,\n"
      "      \"blacklist\": [\n"
      "        \"accelerated_compositing\"\n"
      "      ]\n"
      "    }\n"
      "  ]\n"
      "}";
  SetupBlacklist(json_blacklist);
  GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
  EXPECT_EQ(
      flags.flags(),
      static_cast<uint32>(GpuFeatureFlags::kGpuFeatureAcceleratedCompositing));

  const FilePath url(FILE_PATH_LITERAL("feature_compositing.html"));
  RunTest(url, EXPECT_NO_GPU_PROCESS);
}

IN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLAllowed) {
  GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
  EXPECT_EQ(flags.flags(), 0u);

  const FilePath url(FILE_PATH_LITERAL("feature_webgl.html"));
  RunTest(url, EXPECT_GPU_SWAP_BUFFERS);
}

IN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLBlocked) {
  const std::string json_blacklist =
      "{\n"
      "  \"name\": \"gpu blacklist\",\n"
      "  \"version\": \"1.0\",\n"
      "  \"entries\": [\n"
      "    {\n"
      "      \"id\": 1,\n"
      "      \"blacklist\": [\n"
      "        \"webgl\"\n"
      "      ]\n"
      "    }\n"
      "  ]\n"
      "}";
  SetupBlacklist(json_blacklist);
  GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
  EXPECT_EQ(
      flags.flags(),
      static_cast<uint32>(GpuFeatureFlags::kGpuFeatureWebgl));

  const FilePath url(FILE_PATH_LITERAL("feature_webgl.html"));
  RunTest(url, EXPECT_NO_GPU_PROCESS);
}

#if defined(OS_LINUX)
// http://crbug.com/104142
#define Canvas2DAllowed DISABLED_Canvas2DAllowed
#endif
IN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DAllowed) {
  GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
  EXPECT_EQ(flags.flags(), 0u);

  const FilePath url(FILE_PATH_LITERAL("feature_canvas2d.html"));
  RunTest(url, EXPECT_GPU_SWAP_BUFFERS);
}

IN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DBlocked) {
  const std::string json_blacklist =
      "{\n"
      "  \"name\": \"gpu blacklist\",\n"
      "  \"version\": \"1.0\",\n"
      "  \"entries\": [\n"
      "    {\n"
      "      \"id\": 1,\n"
      "      \"blacklist\": [\n"
      "        \"accelerated_2d_canvas\"\n"
      "      ]\n"
      "    }\n"
      "  ]\n"
      "}";
  SetupBlacklist(json_blacklist);
  GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
  EXPECT_EQ(
      flags.flags(),
      static_cast<uint32>(GpuFeatureFlags::kGpuFeatureAccelerated2dCanvas));

  const FilePath url(FILE_PATH_LITERAL("feature_canvas2d.html"));
  RunTest(url, EXPECT_NO_GPU_PROCESS);
}

}  // namespace anonymous

<commit_msg>Revert 114500 - Disable Canvas2DAllowed for OS_LINUX, it times out on Linux debug shared build bot.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/test/trace_event_analyzer.h"
#include "base/version.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/tracing.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/gpu/gpu_blacklist.h"
#include "content/browser/gpu/gpu_data_manager.h"
#include "net/base/net_util.h"
#include "ui/gfx/gl/gl_switches.h"

namespace {

typedef uint32 GpuResultFlags;
#define EXPECT_NO_GPU_PROCESS         GpuResultFlags(1<<0)
// Expect a SwapBuffers to occur (see gles2_cmd_decoder.cc).
#define EXPECT_GPU_SWAP_BUFFERS       GpuResultFlags(1<<1)

class GpuFeatureTest : public InProcessBrowserTest {
 public:
  GpuFeatureTest() {}

  virtual void SetUpCommandLine(CommandLine* command_line) {
    // This enables DOM automation for tab contents.
    EnableDOMAutomation();
#if !defined(OS_MACOSX)
    CHECK(test_launcher_utils::OverrideGLImplementation(
        command_line, gfx::kGLImplementationOSMesaName)) <<
        "kUseGL must not be set by test framework code!";
#endif
  }

  void SetupBlacklist(const std::string& json_blacklist) {
    scoped_ptr<Version> os_version(Version::GetVersionFromString("1.0"));
    GpuBlacklist* blacklist = new GpuBlacklist("1.0");

    ASSERT_TRUE(blacklist->LoadGpuBlacklist(
        json_blacklist, GpuBlacklist::kAllOs));
    GpuDataManager::GetInstance()->SetGpuBlacklist(blacklist);
  }

  void RunTest(const FilePath& url, GpuResultFlags expectations) {
    using namespace trace_analyzer;

    FilePath test_path;
    PathService::Get(chrome::DIR_TEST_DATA, &test_path);
    test_path = test_path.Append(FILE_PATH_LITERAL("gpu"));
    test_path = test_path.Append(url);

    ASSERT_TRUE(file_util::PathExists(test_path))
        << "Missing test file: " << test_path.value();

    ASSERT_TRUE(tracing::BeginTracing("test_gpu"));

    ui_test_utils::DOMMessageQueue message_queue;
    // Have to use a new tab for the blacklist to work.
    ui_test_utils::NavigateToURLWithDisposition(
        browser(), net::FilePathToFileURL(test_path), NEW_FOREGROUND_TAB,
        ui_test_utils::BROWSER_TEST_NONE);
    // Wait for message indicating the test has finished running.
    ASSERT_TRUE(message_queue.WaitForMessage(NULL));

    std::string json_events;
    ASSERT_TRUE(tracing::EndTracing(&json_events));

    scoped_ptr<TraceAnalyzer> analyzer(TraceAnalyzer::Create(json_events));
    analyzer->AssociateBeginEndEvents();
    TraceEventVector events;

    // This measurement is flaky, because the GPU process is sometimes
    // started before the test (always with force-compositing-mode on CrOS).
    if (expectations & EXPECT_NO_GPU_PROCESS) {
      EXPECT_EQ(0u, analyzer->FindEvents(
          Query::MatchBeginName("OnGraphicsInfoCollected"), &events));
    }

    // Check for swap buffers if expected:
    if (expectations & EXPECT_GPU_SWAP_BUFFERS) {
      EXPECT_GT(analyzer->FindEvents(Query(EVENT_NAME) ==
                                     Query::String("SwapBuffers"), &events),
                size_t(0));
    }
  }
};

IN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingAllowed) {
  GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
  EXPECT_EQ(flags.flags(), 0u);

  const FilePath url(FILE_PATH_LITERAL("feature_compositing.html"));
  RunTest(url, EXPECT_GPU_SWAP_BUFFERS);
}

IN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingBlocked) {
  const std::string json_blacklist =
      "{\n"
      "  \"name\": \"gpu blacklist\",\n"
      "  \"version\": \"1.0\",\n"
      "  \"entries\": [\n"
      "    {\n"
      "      \"id\": 1,\n"
      "      \"blacklist\": [\n"
      "        \"accelerated_compositing\"\n"
      "      ]\n"
      "    }\n"
      "  ]\n"
      "}";
  SetupBlacklist(json_blacklist);
  GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
  EXPECT_EQ(
      flags.flags(),
      static_cast<uint32>(GpuFeatureFlags::kGpuFeatureAcceleratedCompositing));

  const FilePath url(FILE_PATH_LITERAL("feature_compositing.html"));
  RunTest(url, EXPECT_NO_GPU_PROCESS);
}

IN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLAllowed) {
  GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
  EXPECT_EQ(flags.flags(), 0u);

  const FilePath url(FILE_PATH_LITERAL("feature_webgl.html"));
  RunTest(url, EXPECT_GPU_SWAP_BUFFERS);
}

IN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLBlocked) {
  const std::string json_blacklist =
      "{\n"
      "  \"name\": \"gpu blacklist\",\n"
      "  \"version\": \"1.0\",\n"
      "  \"entries\": [\n"
      "    {\n"
      "      \"id\": 1,\n"
      "      \"blacklist\": [\n"
      "        \"webgl\"\n"
      "      ]\n"
      "    }\n"
      "  ]\n"
      "}";
  SetupBlacklist(json_blacklist);
  GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
  EXPECT_EQ(
      flags.flags(),
      static_cast<uint32>(GpuFeatureFlags::kGpuFeatureWebgl));

  const FilePath url(FILE_PATH_LITERAL("feature_webgl.html"));
  RunTest(url, EXPECT_NO_GPU_PROCESS);
}

IN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DAllowed) {
  GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
  EXPECT_EQ(flags.flags(), 0u);

  const FilePath url(FILE_PATH_LITERAL("feature_canvas2d.html"));
  RunTest(url, EXPECT_GPU_SWAP_BUFFERS);
}

IN_PROC_BROWSER_TEST_F(GpuFeatureTest, Canvas2DBlocked) {
  const std::string json_blacklist =
      "{\n"
      "  \"name\": \"gpu blacklist\",\n"
      "  \"version\": \"1.0\",\n"
      "  \"entries\": [\n"
      "    {\n"
      "      \"id\": 1,\n"
      "      \"blacklist\": [\n"
      "        \"accelerated_2d_canvas\"\n"
      "      ]\n"
      "    }\n"
      "  ]\n"
      "}";
  SetupBlacklist(json_blacklist);
  GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();
  EXPECT_EQ(
      flags.flags(),
      static_cast<uint32>(GpuFeatureFlags::kGpuFeatureAccelerated2dCanvas));

  const FilePath url(FILE_PATH_LITERAL("feature_canvas2d.html"));
  RunTest(url, EXPECT_NO_GPU_PROCESS);
}

}  // namespace anonymous

<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/javascript_test_util.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"

namespace {

class DromaeoTest : public UITest {
 public:
  typedef std::map<std::string, std::string> ResultsMap;

  DromaeoTest() : reference_(false) {
    dom_automation_enabled_ = true;
    show_window_ = true;
  }

  void RunTest(const FilePath::CharType* suite) {
    FilePath test_path = GetDromaeoDir();
    test_path = test_path.Append(
        FilePath::StringType(FILE_PATH_LITERAL("index.html?")) +
        FilePath::StringType(suite) +
        FilePath::StringType(FILE_PATH_LITERAL("&automated")));
    GURL test_url(net::FilePathToFileURL(test_path));

    scoped_refptr<TabProxy> tab(GetActiveTab());
    tab->NavigateToURL(test_url);

    // Wait for the test to finish.
    ASSERT_TRUE(WaitUntilTestCompletes(tab.get(), test_url));

    PrintResults(tab.get());
  }

 protected:
  bool reference_;  // True if this is a reference build.

 private:
  // Return the path to the dromaeo benchmark directory on the local filesystem.
  FilePath GetDromaeoDir() {
    FilePath test_dir;
    PathService::Get(chrome::DIR_TEST_DATA, &test_dir);
    return test_dir.AppendASCII("dromaeo");
  }

  bool WaitUntilTestCompletes(TabProxy* tab, const GURL& test_url) {
    return WaitUntilCookieValue(tab, test_url, "__done", 1000,
                                UITest::test_timeout_ms(), "1");
  }

  bool GetScore(TabProxy* tab, std::string* score) {
    std::wstring score_wide;
    bool succeeded = tab->ExecuteAndExtractString(L"",
        L"window.domAutomationController.send(automation.GetScore());",
        &score_wide);

    // Note that we don't use ASSERT_TRUE here (and in some other places) as it
    // doesn't work inside a function with a return type other than void.
    EXPECT_TRUE(succeeded);
    if (!succeeded)
      return false;

    score->assign(WideToUTF8(score_wide));
    return true;
  }

  bool GetResults(TabProxy* tab, ResultsMap* results) {
    std::wstring json_wide;
    bool succeeded = tab->ExecuteAndExtractString(L"",
        L"window.domAutomationController.send("
        L"    JSON.stringify(automation.GetResults()));",
        &json_wide);

    EXPECT_TRUE(succeeded);
    if (!succeeded)
      return false;

    std::string json = WideToUTF8(json_wide);
    return JsonDictionaryToMap(json, results);
  }

  void PrintResults(TabProxy* tab) {
    std::string score;
    ASSERT_TRUE(GetScore(tab, &score));

    ResultsMap results;
    ASSERT_TRUE(GetResults(tab, &results));

    std::string trace_name = reference_ ? "score_ref" : "score";
    std::string unit_name = "runs/s";

    PrintResult("score", "", trace_name, score, unit_name, true);

    ResultsMap::const_iterator it = results.begin();
    for (; it != results.end(); ++it) {
      std::string test_name = it->first;
      for (size_t i = 0; i < test_name.length(); i++)
        if (!isalnum(test_name[i]))
          test_name[i] = '_';
      PrintResult(test_name, "", trace_name, it->second, unit_name, false);
    }
  }

  DISALLOW_COPY_AND_ASSIGN(DromaeoTest);
};

class DromaeoReferenceTest : public DromaeoTest {
 public:
  DromaeoReferenceTest() : DromaeoTest() {
    reference_ = true;
  }

  // Override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
    FilePath dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
    dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
    dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
    dir = dir.AppendASCII("chrome_mac");
#endif
    browser_directory_ = dir;
    UITest::SetUp();
  }
};

TEST_F(DromaeoTest, DOMCorePerf) {
  RunTest(FILE_PATH_LITERAL("dom"));
}

TEST_F(DromaeoTest, JSLibPerf) {
  RunTest(FILE_PATH_LITERAL("jslib"));
}

TEST_F(DromaeoReferenceTest, DOMCorePerf) {
  RunTest(FILE_PATH_LITERAL("dom"));
}

TEST_F(DromaeoReferenceTest, JSLibPerf) {
  RunTest(FILE_PATH_LITERAL("jslib"));
}

}  // namespace
<commit_msg>Revert -r 40634 to wait until masters' configs get updated.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/javascript_test_util.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"

namespace {

static const FilePath::CharType kStartFile[] =
    FILE_PATH_LITERAL("index.html?dom|jslib&automated");

const wchar_t kRunDromaeo[] = L"run-dromaeo-benchmark";

class DromaeoTest : public UITest {
 public:
  typedef std::map<std::string, std::string> ResultsMap;

  DromaeoTest() : reference_(false) {
    dom_automation_enabled_ = true;
    show_window_ = true;
  }

  void RunTest() {
    FilePath::StringType start_file(kStartFile);
    FilePath test_path = GetDromaeoDir();
    test_path = test_path.Append(start_file);
    GURL test_url(net::FilePathToFileURL(test_path));

    scoped_refptr<TabProxy> tab(GetActiveTab());
    tab->NavigateToURL(test_url);

    // Wait for the test to finish.
    ASSERT_TRUE(WaitUntilTestCompletes(tab.get(), test_url));

    PrintResults(tab.get());
  }

 protected:
  bool reference_;  // True if this is a reference build.

 private:
  // Return the path to the dromaeo benchmark directory on the local filesystem.
  FilePath GetDromaeoDir() {
    FilePath test_dir;
    PathService::Get(chrome::DIR_TEST_DATA, &test_dir);
    return test_dir.AppendASCII("dromaeo");
  }

  bool WaitUntilTestCompletes(TabProxy* tab, const GURL& test_url) {
    return WaitUntilCookieValue(tab, test_url, "__done", 1000,
                                UITest::test_timeout_ms(), "1");
  }

  bool GetScore(TabProxy* tab, std::string* score) {
    std::wstring score_wide;
    bool succeeded = tab->ExecuteAndExtractString(L"",
        L"window.domAutomationController.send(automation.GetScore());",
        &score_wide);

    // Note that we don't use ASSERT_TRUE here (and in some other places) as it
    // doesn't work inside a function with a return type other than void.
    EXPECT_TRUE(succeeded);
    if (!succeeded)
      return false;

    score->assign(WideToUTF8(score_wide));
    return true;
  }

  bool GetResults(TabProxy* tab, ResultsMap* results) {
    std::wstring json_wide;
    bool succeeded = tab->ExecuteAndExtractString(L"",
        L"window.domAutomationController.send("
        L"    JSON.stringify(automation.GetResults()));",
        &json_wide);

    EXPECT_TRUE(succeeded);
    if (!succeeded)
      return false;

    std::string json = WideToUTF8(json_wide);
    return JsonDictionaryToMap(json, results);
  }

  void PrintResults(TabProxy* tab) {
    std::string score;
    ASSERT_TRUE(GetScore(tab, &score));

    ResultsMap results;
    ASSERT_TRUE(GetResults(tab, &results));

    std::string trace_name = reference_ ? "score_ref" : "score";
    std::string unit_name = "runs/s";

    PrintResult("score", "", trace_name, score, unit_name, true);

    ResultsMap::const_iterator it = results.begin();
    for (; it != results.end(); ++it) {
      std::string test_name = it->first;
      for (size_t i = 0; i < test_name.length(); i++)
        if (!isalnum(test_name[i]))
          test_name[i] = '_';
      PrintResult(test_name, "", trace_name, it->second, unit_name, false);
    }
  }

  DISALLOW_COPY_AND_ASSIGN(DromaeoTest);
};

class DromaeoReferenceTest : public DromaeoTest {
 public:
  DromaeoReferenceTest() : DromaeoTest() {
    reference_ = true;
  }

  // Override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
    FilePath dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
    dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
    dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
    dir = dir.AppendASCII("chrome_mac");
#endif
    browser_directory_ = dir;
    UITest::SetUp();
  }
};

TEST_F(DromaeoTest, Perf) {
  if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDromaeo))
    return;

  RunTest();
}

TEST_F(DromaeoReferenceTest, Perf) {
  if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDromaeo))
    return;

  RunTest();
}

}  // namespace
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/javascript_test_util.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"

namespace {

static const FilePath::CharType kStartFile[] =
    FILE_PATH_LITERAL("index.html?dom|jslib&automated");

const wchar_t kRunDromaeo[] = L"run-dromaeo-benchmark";

class DromaeoTest : public UITest {
 public:
  typedef std::map<std::string, std::string> ResultsMap;

  DromaeoTest() : reference_(false) {
    dom_automation_enabled_ = true;
    show_window_ = true;
  }

  void RunTest() {
    FilePath::StringType start_file(kStartFile);
    FilePath test_path = GetDromaeoDir();
    test_path = test_path.Append(start_file);
    GURL test_url(net::FilePathToFileURL(test_path));

    scoped_refptr<TabProxy> tab(GetActiveTab());
    tab->NavigateToURL(test_url);

    // Wait for the test to finish.
    ASSERT_TRUE(WaitUntilTestCompletes(tab.get(), test_url));

    PrintResults(tab.get());
  }

 protected:
  bool reference_;  // True if this is a reference build.

 private:
  // Return the path to the dromaeo benchmark directory on the local filesystem.
  FilePath GetDromaeoDir() {
    FilePath test_dir;
    PathService::Get(chrome::DIR_TEST_DATA, &test_dir);
    return test_dir.AppendASCII("dromaeo");
  }

  bool WaitUntilTestCompletes(TabProxy* tab, const GURL& test_url) {
    return WaitUntilCookieValue(tab, test_url, "__done", 1000,
                                UITest::test_timeout_ms(), "1");
  }

  bool GetScore(TabProxy* tab, std::string* score) {
    std::wstring score_wide;
    bool succeeded = tab->ExecuteAndExtractString(L"",
        L"window.domAutomationController.send(automation.GetScore());",
        &score_wide);

    // Note that we don't use ASSERT_TRUE here (and in some other places) as it
    // doesn't work inside a function with a return type other than void.
    EXPECT_TRUE(succeeded);
    if (!succeeded)
      return false;

    score->assign(WideToUTF8(score_wide));
    return true;
  }

  bool GetResults(TabProxy* tab, ResultsMap* results) {
    std::wstring json_wide;
    bool succeeded = tab->ExecuteAndExtractString(L"",
        L"window.domAutomationController.send("
        L"    JSON.stringify(automation.GetResults()));",
        &json_wide);

    EXPECT_TRUE(succeeded);
    if (!succeeded)
      return false;

    std::string json = WideToUTF8(json_wide);
    return JsonDictionaryToMap(json, results);
  }

  void PrintResults(TabProxy* tab) {
    std::string score;
    ASSERT_TRUE(GetScore(tab, &score));

    ResultsMap results;
    ASSERT_TRUE(GetResults(tab, &results));

    std::string trace_name = reference_ ? "score_ref" : "score";
    std::string unit_name = "runs/s";

    PrintResult("score", "", trace_name, score, unit_name, true);

    ResultsMap::const_iterator it = results.begin();
    for (; it != results.end(); ++it)
      PrintResult(it->first, "", trace_name, it->second, unit_name, false);
  }

  DISALLOW_COPY_AND_ASSIGN(DromaeoTest);
};

class DromaeoReferenceTest : public DromaeoTest {
 public:
  DromaeoReferenceTest() : DromaeoTest() {
    reference_ = true;
  }

  // Override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
    FilePath dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
    dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
    dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
    dir = dir.AppendASCII("chrome_mac");
#endif
    browser_directory_ = dir;
    UITest::SetUp();
  }
};

TEST_F(DromaeoTest, Perf) {
  if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDromaeo))
    return;

  RunTest();
}

TEST_F(DromaeoReferenceTest, Perf) {
  if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDromaeo))
    return;

  RunTest();
}

}  // namespace
<commit_msg>Disable the dromaeo benchmark tests until they are fixed<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/json_value_serializer.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/javascript_test_util.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"

namespace {

static const FilePath::CharType kStartFile[] =
    FILE_PATH_LITERAL("index.html?dom|jslib&automated");

const wchar_t kRunDromaeo[] = L"run-dromaeo-benchmark";

class DromaeoTest : public UITest {
 public:
  typedef std::map<std::string, std::string> ResultsMap;

  DromaeoTest() : reference_(false) {
    dom_automation_enabled_ = true;
    show_window_ = true;
  }

  void RunTest() {
    FilePath::StringType start_file(kStartFile);
    FilePath test_path = GetDromaeoDir();
    test_path = test_path.Append(start_file);
    GURL test_url(net::FilePathToFileURL(test_path));

    scoped_refptr<TabProxy> tab(GetActiveTab());
    tab->NavigateToURL(test_url);

    // Wait for the test to finish.
    ASSERT_TRUE(WaitUntilTestCompletes(tab.get(), test_url));

    PrintResults(tab.get());
  }

 protected:
  bool reference_;  // True if this is a reference build.

 private:
  // Return the path to the dromaeo benchmark directory on the local filesystem.
  FilePath GetDromaeoDir() {
    FilePath test_dir;
    PathService::Get(chrome::DIR_TEST_DATA, &test_dir);
    return test_dir.AppendASCII("dromaeo");
  }

  bool WaitUntilTestCompletes(TabProxy* tab, const GURL& test_url) {
    return WaitUntilCookieValue(tab, test_url, "__done", 1000,
                                UITest::test_timeout_ms(), "1");
  }

  bool GetScore(TabProxy* tab, std::string* score) {
    std::wstring score_wide;
    bool succeeded = tab->ExecuteAndExtractString(L"",
        L"window.domAutomationController.send(automation.GetScore());",
        &score_wide);

    // Note that we don't use ASSERT_TRUE here (and in some other places) as it
    // doesn't work inside a function with a return type other than void.
    EXPECT_TRUE(succeeded);
    if (!succeeded)
      return false;

    score->assign(WideToUTF8(score_wide));
    return true;
  }

  bool GetResults(TabProxy* tab, ResultsMap* results) {
    std::wstring json_wide;
    bool succeeded = tab->ExecuteAndExtractString(L"",
        L"window.domAutomationController.send("
        L"    JSON.stringify(automation.GetResults()));",
        &json_wide);

    EXPECT_TRUE(succeeded);
    if (!succeeded)
      return false;

    std::string json = WideToUTF8(json_wide);
    return JsonDictionaryToMap(json, results);
  }

  void PrintResults(TabProxy* tab) {
    std::string score;
    ASSERT_TRUE(GetScore(tab, &score));

    ResultsMap results;
    ASSERT_TRUE(GetResults(tab, &results));

    std::string trace_name = reference_ ? "score_ref" : "score";
    std::string unit_name = "runs/s";

    PrintResult("score", "", trace_name, score, unit_name, true);

    ResultsMap::const_iterator it = results.begin();
    for (; it != results.end(); ++it)
      PrintResult(it->first, "", trace_name, it->second, unit_name, false);
  }

  DISALLOW_COPY_AND_ASSIGN(DromaeoTest);
};

class DromaeoReferenceTest : public DromaeoTest {
 public:
  DromaeoReferenceTest() : DromaeoTest() {
    reference_ = true;
  }

  // Override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
    FilePath dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
    dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
    dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
    dir = dir.AppendASCII("chrome_mac");
#endif
    browser_directory_ = dir;
    UITest::SetUp();
  }
};

TEST_F(DromaeoTest, Perf) {
  //if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDromaeo))
  //  return;

  //RunTest();
}

TEST_F(DromaeoReferenceTest, Perf) {
  //if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunDromaeo))
  //  return;

  //RunTest();
}

}  // namespace
<|endoftext|>