/**
 * \file PancakeTest.cpp
 *
 * Some simple tests to make sure the pancake domain works properly.
 *
 * \author eaburns
 * \date 18-01-2010
 */

#include "pancake/PancakeTypes.hpp"
#include "pancake/PancakeState.hpp"

#include <stdlib.h>

int main(void)
{
	boost::array<Pancake, 14> cakes;

	for (unsigned int i = 0; i < 14; i += 1)
		cakes[i] = i +  1;

 	PancakeState14 s(cakes);

	std::cout << s << std::endl;
	std::cout << s.flip(4) << std::endl;
	std::cout << s.flip(5) << std::endl;

	return EXIT_FAILURE;
}

/**
 * \file PancakeTest.cpp
 *
 * Some simple tests to make sure the pancake domain works properly.
 *
 * \author eaburns
 * \date 18-01-2010
 */

#include "pancake/PancakeTypes.hpp"
#include "pancake/PancakeState.hpp"

#include <stdlib.h>

int main(void)
{
	boost::array<Pancake, 14> cakes;

	for (unsigned int i = 0; i < 14; i += 1)
		cakes[i] = i +  1;

 	PancakeState14 s(cakes);

	std::cout << s.get_hash_value() << ": " << s << std::endl;
	std::cout << s s.get_hash_value() << ": " <<.flip(4) << std::endl;
	std::cout << s s.get_hash_value() << ": " <<.flip(5) << std::endl;

	return EXIT_SUCCESS;
}

Exit the pancake test with success instead of failure and print the hash values too.


/*
    Copyright 2008 Brain Research Institute, Melbourne, Australia

    Written by Robert E. Smith, 04/08/14.

    This file is part of MRtrix.

    MRtrix is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MRtrix 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with MRtrix.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "file/ofstream.h"

#include "file/utils.h"

namespace MR
{
  namespace File
  {

  void OFStream::open (const std::string& path, const std::ios_base::openmode mode)
  {
    if (!(mode & std::ios_base::app) && !(mode & std::ios_base::ate) && !(mode & std::ios_base::in))
      if (!File::is_tempfile (path))
        File::output_file_check (path);

    std::ofstream::open (path.c_str(), mode);
    if (std::ofstream::operator!())
      throw Exception ("error opening output file \"" + path + "\": " + std::strerror (errno));
  }

  }
}

/*
    Copyright 2008 Brain Research Institute, Melbourne, Australia

    Written by Robert E. Smith, 04/08/14.

    This file is part of MRtrix.

    MRtrix is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MRtrix 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with MRtrix.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "file/ofstream.h"

#include "file/utils.h"

namespace MR
{
  namespace File
  {

  void OFStream::open (const std::string& path, const std::ios_base::openmode mode)
  {
    if (!(mode & std::ios_base::app) && !(mode & std::ios_base::ate) && !(mode & std::ios_base::in)) {
      if (!File::is_tempfile (path))
        File::create (path);
    }

    std::ofstream::open (path.c_str(), mode);
    if (std::ofstream::operator!())
      throw Exception ("error opening output file \"" + path + "\": " + std::strerror (errno));
  }

  }
}

File::OFStream: Use File::create() instead of File::output_file_check()

This should provide slightly more robust behaviour regarding race conditions.


#include "stdafx.h"

using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;

//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute("openalprnet")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("")];
[assembly:AssemblyProductAttribute("openalprnet")];
[assembly:AssemblyCopyrightAttribute("Copyright (c)  2015")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];

//
// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:

[assembly: AssemblyVersionAttribute("2.1.0")]
[assembly: AssemblyFileVersionAttribute("2.1.0")]
[assembly: AssemblyInformationalVersionAttribute("2.1.0")]

[assembly:ComVisible(false)];

[assembly:CLSCompliantAttribute(true)];

[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];

Fix visual studio deprecation warning.

Fix visual studio deprecation warning.


#include <unistd.h>

#include <event/event_callback.h>
#include <event/event_main.h>

#include <io/stream_handle.h>

class Sink {
	LogHandle log_;

	StreamHandle fd_;
	Action *action_;
public:
	Sink(int fd)
	: log_("/sink"),
	  fd_(fd),
	  action_(NULL)
	{
		EventCallback *cb = callback(this, &Sink::read_complete);
		action_ = fd_.read(0, cb);
	}

	~Sink()
	{
		ASSERT(log_, action_ == NULL);
	}

	void read_complete(Event e)
	{
		action_->cancel();
		action_ = NULL;

		switch (e.type_) {
		case Event::Done:
		case Event::EOS:
			break;
		default:
			HALT(log_) << "Unexpected event: " << e;
			return;
		}

		if (e.type_ == Event::EOS) {
			SimpleCallback *cb = callback(this, &Sink::close_complete);
			action_ = fd_.close(cb);
			return;
		}

		EventCallback *cb = callback(this, &Sink::read_complete);
		action_ = fd_.read(0, cb);
	}

	void close_complete(void)
	{
		action_->cancel();
		action_ = NULL;
	}
};

int
main(void)
{
	Sink sink(STDIN_FILENO);

	event_main();
}

#include <unistd.h>

#include <event/callback_handler.h>
#include <event/event_callback.h>
#include <event/event_handler.h>
#include <event/event_main.h>

#include <io/stream_handle.h>

class Sink {
	LogHandle log_;

	StreamHandle fd_;
	CallbackHandler close_handler_;
	EventHandler read_handler_;
public:
	Sink(int fd)
	: log_("/sink"),
	  fd_(fd),
	  read_handler_()
	{
		read_handler_.handler(Event::Done, this, &Sink::read_done);
		read_handler_.handler(Event::EOS, this, &Sink::read_eos);

		close_handler_.handler(this, &Sink::close_done);

		read_handler_.wait(fd_.read(0, read_handler_.callback()));
	}

	~Sink()
	{ }

	void read_done(Event)
	{
		read_handler_.wait(fd_.read(0, read_handler_.callback()));
	}

	void read_eos(Event)
	{
		close_handler_.wait(fd_.close(close_handler_.callback()));
	}

	void close_done(void)
	{ }
};

int
main(void)
{
	Sink sink(STDIN_FILENO);

	event_main();
}

Convert to use Handlers.  Could be simpler.

git-svn-id: 9e2532540f1574e817ce42f20b9d0fb64899e451@952 4068ffdb-0463-0410-8185-8cc71e3bd399


#include <iostream>

int main() {
  std::cout << "Hello, compiler!\n\n";
  std::cout <<

#if defined(__clang__)
  "Clang " << __clang_version__ <<

#elif defined(__ICC) || defined(__INTEL_COMPILER)
  "Intel " << __INTEL_COMPILER <<

#elif defined(__GNUC__) || defined(__GNUG__)
  "GCC " << __VERSION__ <<

#elif defined(__HP_cc) || defined(__HP_aCC)
  "HP " << __HP_aCC <<

#elif defined(__IBMC__) || defined(__IBMCPP__)
  "IBM " << __IBMCPP__ <<

#elif defined(_MSC_VER)
  "MSVC " << _MSC_FULL_VER <<

#elif defined(__PGI)
  "Portland PGCPP" << __VERSION__ <<

#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC)
  "Solaris Studio" << __SUNPRO_CC <<

#endif

 '\n';
}

#include <iostream>

//toggle to check for boost version
#define CHECK_BOOST_VERSION 0
#if CHECK_BOOST_VERSION
#include <boost/version.hpp>
#endif

int main() {
  std::cout << "Hello, compiler!\n\n";
  std::cout <<

#if defined(__clang__)
  "Clang " << __clang_version__ <<

#elif defined(__ICC) || defined(__INTEL_COMPILER)
  "Intel " << __INTEL_COMPILER <<

#elif defined(__GNUC__) || defined(__GNUG__)
  "GCC " << __VERSION__ <<

#elif defined(__HP_cc) || defined(__HP_aCC)
  "HP " << __HP_aCC <<

#elif defined(__IBMC__) || defined(__IBMCPP__)
  "IBM " << __IBMCPP__ <<

#elif defined(_MSC_VER)
  "MSVC " << _MSC_FULL_VER <<

#elif defined(__PGI)
  "Portland PGCPP" << __VERSION__ <<

#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC)
  "Solaris Studio" << __SUNPRO_CC <<

#else
  "Unknown compiler" <<
#endif

 '\n';
#if CHECK_BOOST_VERSION
  std::cout << "\nBoost version: " << BOOST_LIB_VERSION << '\n';
#endif

}

Add test for boost version

Add test for boost version


// RUN: c-index-test -test-load-source all -triple x86_64-apple-darwin10 -fasm-blocks -Wno-microsoft %s 2>&1 | FileCheck %s

// Test that we diagnose when the application hasn't initialized LLVM targets
// supporting the MS-style inline asm parser.

void Break() {
  __asm { int 3 }
}
// CHECK: error: MS-style inline assembly is not available

// REQUIRES: x86-registered-target
// RUN: c-index-test -test-load-source all -fasm-blocks -Wno-microsoft %s 2>&1 | FileCheck %s

// Test that we diagnose when the application hasn't initialized LLVM targets
// supporting the MS-style inline asm parser.

void Break() {
  __asm { int 3 }
}
// CHECK: error: MS-style inline assembly is not available

Fix triple / REQUIRES in test from r193685

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@193686 91177308-0d34-0410-b5e6-96231b3b80d8


#include "gen.h"
#include "interface.h"
#include <iostream>

int main(int argc, char *argv[])
{
	Generate Gen;

	std::string Args;
	int i;
	for (i = 1; i < argc; i++) {
		if (argv[i] != NULL)
			Args = argv[1];
		if (argv[i] == NULL) {
		}
		if ((Args == "-new") || (Args == "--new") || (Args == "-n")) {
			Gen.GenBlankConfig();
			return 1;
		}
		if ((Args == "-help") || (Args == "--help") || (Args == "-h")) {
			printHelp();
		}
		if ((Args == "-debug") || (Args == "--debug")) {
			Gen.CheckMake();
			Gen.CheckFiles();
		}
	}
	return 0;
}

#include <iostream>
#include "gen.h"
#include "interface.h"

int main(int argc, char *argv[])
{
	Generate Gen;

	std::string Args;
	int i;
	for (i = 1; i < argc; i++) {
		if (argv[i] != NULL)
			Args = argv[1];
		if (argv[i] == NULL) {
		}
		if ((Args == "-new") || (Args == "--new") || (Args == "-n")) {
			Gen.GenBlankConfig();
			return 1;
		}
		if ((Args == "-help") || (Args == "--help") || (Args == "-h")) {
			printHelp();
		}
		if ((Args == "-debug") || (Args == "--debug")) {
			Gen.CheckMake();
			Gen.WriteMake();
			Gen.GenMakeFromTemplate();
			Gen.WalkDir(Gen.currentDir, ".\\.cpp$", FS_DEFAULT | FS_MATCHDIRS);
			Gen.WalkDir(Gen.currentDir, ".\\.h$", FS_DEFAULT | FS_MATCHDIRS);
		}
	}
	return 0;
}

Add interface for new Generate member functions

Signed-off-by: Alberto Corona <c1a4158909d6c23f73df353c7cc0bbe963891a65@0x1a.us>


#include "playerHUD.hpp"

#include "player.hpp"

#include <sstream>

#include <SFML/Graphics/RenderWindow.hpp>

namespace aw
{
	PlayerHUD::PlayerHUD()
	{
		m_font.loadFromFile("data/fonts/visitor1.ttf");
		m_displaySpeed.setFont(m_font);
		m_displaySpeed.setColor(sf::Color::White);
		m_displaySpeed.setCharacterSize(18);

		m_displayGravity = m_displaySpeed;

		m_displaySpeed.setPosition(sf::Vector2f(5, 5));
		m_displayGravity.setPosition(sf::Vector2f(5, 25));
	}

	void PlayerHUD::update(const Player &player)
	{
		//static_cast<int> to avoid showing ugly floating numbers...
		std::stringstream sstr;
		sstr << "Speed: " << static_cast<int>(player.getSpeed().x);
		m_displaySpeed.setString(sstr.str());

		sstr.str("");
		sstr << "Gravity: " << static_cast<int>(player.getGravitation());
		m_displayGravity.setString(sstr.str());
	}

	void PlayerHUD::render(sf::RenderWindow &window)
	{
		window.draw(m_displaySpeed);
		window.draw(m_displayGravity);
	}
}

#include "playerHUD.hpp"

#include "player.hpp"

#include <sstream>

#include <SFML/Graphics/RenderWindow.hpp>

namespace aw
{
	PlayerHUD::PlayerHUD()
	{
		m_font.loadFromFile("data/fonts/visitor1.ttf");
		m_displaySpeed.setFont(m_font);
		m_displaySpeed.setColor(sf::Color::White);
		m_displaySpeed.setCharacterSize(18);

		m_displayGravity = m_displaySpeed;

		m_displaySpeed.setPosition(sf::Vector2f(5, 5));
		m_displayGravity.setPosition(sf::Vector2f(5, 25));
	}

	void PlayerHUD::update(const Player &player)
	{
		//std::round to avoid showing ugly floating numbers...
		std::stringstream sstr;
		sstr << "Speed: " << std::round(player.getSpeed().x);
		m_displaySpeed.setString(sstr.str());

		sstr.str("");
		sstr << "Gravity: " << std::round(player.getGravitation());
		m_displayGravity.setString(sstr.str());
	}

	void PlayerHUD::render(sf::RenderWindow &window)
	{
		window.draw(m_displaySpeed);
		window.draw(m_displayGravity);
	}
}

Use std::round to remove ugly float numbers


// Copyright 2014 Toggl Desktop developers.

#include "./client.h"

#include <sstream>

namespace kopsik {

std::string Client::String() {
  std::stringstream ss;
  ss  << "ID=" << id_
  << " local_id=" << local_id_
  << " name=" << name_
  << " wid=" << wid_
  << " guid=" << guid_;
  return ss.str();
}

void Client::SetID(Poco::UInt64 value) {
  if (id_ != value) {
    id_ = value;
    dirty_ = true;
  }
}

void Client::SetName(std::string value) {
  if (name_ != value) {
    name_ = value;
    dirty_ = true;
  }
}

void Client::SetUID(Poco::UInt64 value) {
  if (uid_ != value) {
    uid_ = value;
    dirty_ = true;
  }
}

void Client::SetGUID(std::string value) {
  if (guid_ != value) {
    guid_ = value;
    dirty_ = true;
  }
}

void Client::SetWID(Poco::UInt64 value) {
  if (wid_ != value) {
    wid_ = value;
    dirty_ = true;
  }
}

bool CompareClientByName(Client *a, Client *b) {
  return (strcmp(a->Name().c_str(), b->Name().c_str()) < 0);
}

}   // namespace kopsik

// Copyright 2014 Toggl Desktop developers.

#include "./client.h"

#include <sstream>
#include <cstring>

namespace kopsik {

std::string Client::String() {
  std::stringstream ss;
  ss  << "ID=" << id_
  << " local_id=" << local_id_
  << " name=" << name_
  << " wid=" << wid_
  << " guid=" << guid_;
  return ss.str();
}

void Client::SetID(Poco::UInt64 value) {
  if (id_ != value) {
    id_ = value;
    dirty_ = true;
  }
}

void Client::SetName(std::string value) {
  if (name_ != value) {
    name_ = value;
    dirty_ = true;
  }
}

void Client::SetUID(Poco::UInt64 value) {
  if (uid_ != value) {
    uid_ = value;
    dirty_ = true;
  }
}

void Client::SetGUID(std::string value) {
  if (guid_ != value) {
    guid_ = value;
    dirty_ = true;
  }
}

void Client::SetWID(Poco::UInt64 value) {
  if (wid_ != value) {
    wid_ = value;
    dirty_ = true;
  }
}

bool CompareClientByName(Client *a, Client *b) {
  return (strcmp(a->Name().c_str(), b->Name().c_str()) < 0);
}

}   // namespace kopsik

Fix strcmp include in lib

Fix strcmp include in lib


//
//  simple_item.cc
//  GameEngine
//
//  Created by Jon Sharkey on 2010-04-30.
//  Copyright 2010 Sharkable. All rights reserved.
//

#include "gameengine/entities/simple_item.h"

#include "gameengine/resource_loader.h"

using std::vector;

SimpleItem::SimpleItem()
    : Animatable(),
      sprite_(0) {
}

SimpleItem::SimpleItem(Sprite sprite, GamePoint position)
    : Animatable(position),
      sprite_(0) {
  sprites_.push_back(sprite);
}

SimpleItem::SimpleItem(vector<Sprite> sprites, GamePoint position)
    : Animatable(position),
      sprites_(sprites),
      sprite_(0) {
}

SimpleItem::~SimpleItem() {
  for (int i = 0; i < sprites_.size(); i++) {
    // TODO ResourceLoader::Instance().ReleaseResource(sprites_[i].texture());
  }
}

#pragma mark - ViewEntity

void SimpleItem::Render(GamePoint render_offset, float render_angle) {
  sprites_[sprite_].Draw(position() + render_offset, angle() + render_angle, alpha(), zoom());
}

GameRect SimpleItem::Rect() {
  return game_rect_make(position(), sprites_[sprite_].content_size());
}

//
//  simple_item.cc
//  GameEngine
//
//  Created by Jon Sharkey on 2010-04-30.
//  Copyright 2010 Sharkable. All rights reserved.
//

#include "gameengine/entities/simple_item.h"

#include "gameengine/resource_loader.h"

using std::vector;

SimpleItem::SimpleItem()
    : Animatable(),
      sprite_(0) {
}

SimpleItem::SimpleItem(Sprite sprite, GamePoint position)
    : Animatable(position),
      sprite_(0) {
  sprites_.push_back(sprite);
}

SimpleItem::SimpleItem(vector<Sprite> sprites, GamePoint position)
    : Animatable(position),
      sprites_(sprites),
      sprite_(0) {
}

SimpleItem::~SimpleItem() {
  for (int i = 0; i < sprites_.size(); i++) {
    // TODO ResourceLoader::Instance().ReleaseResource(sprites_[i].texture());
  }
}

#pragma mark - ViewEntity

void SimpleItem::Render(GamePoint render_offset, float render_angle) {
  sprites_[sprite_].Draw(position() + render_offset, angle() + render_angle, alpha(), zoom());
}

GameRect SimpleItem::Rect() {
  SpriteAnchor anchor = sprites_[sprite_].anchor();
  switch (anchor) {
    case kSpriteAnchorTopLeft:
      return game_rect_make(position(), sprites_[sprite_].content_size());
    case kSpriteAnchorCenter:
      GameSize content_size = sprites_[sprite_].content_size();
      GamePoint origin = position() - game_point_make(content_size.width / 2.f,
                                                      content_size.height / 2.f);
      return game_rect_make(origin, content_size);
  }
}

Return the correct Rect value for the anchor.


// C++11 passing exceptions around using std::exception_ptr

#include <exception>
#include <thread>
#include <iostream>
#include <cassert>

std::exception_ptr g_stashed_exception_ptr;

auto bad_task() -> void
{
  try
  {
    std::thread().detach(); // Oops !!
  }
  catch ( ... )
  {
    g_stashed_exception_ptr = std::current_exception();
  }
}

auto main() -> int
{
  assert( g_stashed_exception_ptr == nullptr );
  assert( !g_stashed_exception_ptr );

  std::thread task( bad_task );
  task.join();

  assert( g_stashed_exception_ptr != nullptr );
  assert( g_stashed_exception_ptr );

  try
  {
    std::rethrow_exception( g_stashed_exception_ptr );
  }
  catch ( std::exception & e )
  {
    std::cerr << "Task failed exceptionally: " << e.what() << "\n";
  }
}

// C++11 passing exceptions around using std::exception_ptr

#include <exception>
#include <thread>
#include <iostream>
#include <cassert>

std::exception_ptr g_stashed_exception_ptr;

void bad_task()
{
  try
  {
    std::thread().detach(); // Oops !!
  }
  catch ( ... )
  {
    g_stashed_exception_ptr = std::current_exception();
  }
}

int main()
{
  assert( g_stashed_exception_ptr == nullptr );
  assert( !g_stashed_exception_ptr );

  std::thread task( bad_task );
  task.join();

  assert( g_stashed_exception_ptr != nullptr );
  assert( g_stashed_exception_ptr );

  try
  {
    std::rethrow_exception( g_stashed_exception_ptr );
  }
  catch ( std::exception & e )
  {
    std::cerr << "Task failed exceptionally: " << e.what() << "\n";
  }
}

Change to traditional style for function return type declarations rather than new trailing return type syntax - it is more consistent with rest of example code and shorter


// 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 "chrome/browser/extensions/extension_function.h"

#include "chrome/browser/extensions/extension_function_dispatcher.h"

void ExtensionFunction::SendResponse(bool success) {
  if (success) {
    dispatcher_->SendResponse(this);
  } else {
    // TODO(aa): In case of failure, send the error message to an error
    // callback.
  }
}

// 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 "chrome/browser/extensions/extension_function.h"

#include "chrome/browser/extensions/extension_function_dispatcher.h"

void ExtensionFunction::SendResponse(bool success) {
  if (success) {
    if (has_callback()) {
      dispatcher_->SendResponse(this);
    }
  } else {
    // TODO(aa): In case of failure, send the error message to an error
    // callback.
  }
}

Check that the ExtensionFunction has a callback for attempting to send a response.

Review URL: http://codereview.chromium.org/63130

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@13406 0039d316-1c4b-4281-b951-d872f2087c98


#include <cpp/tasks.hh>

namespace cpp
{
    void cpp_generator()
    {
        assert(ast::program_ast && "No ast to transform to cpp");

        std::cout << "#include <repy/repy.hh>" << std::endl;

        CodeGenerator cgen(std::cout);

        cgen.visit(ast::program_ast);
        cgen.generate_main();
    }

    void header_generator()
    {
        assert(ast::program_ast && "No ast to transform to cpp header");

        HeaderGenerator hgen(std::cout);

        hgen.visit(ast::program_ast);
    }
} // namespace cpp

#include <cpp/tasks.hh>

namespace cpp
{
    void cpp_generator()
    {
        assert(ast::program_ast && "No ast to transform to cpp");

        CodeGenerator cgen(std::cout);

        cgen.visit(ast::program_ast);
        cgen.generate_main();
    }

    void header_generator()
    {
        assert(ast::program_ast && "No ast to transform to cpp header");

        std::cout << "#include <repy/repy.hh>" << std::endl;

        HeaderGenerator hgen(std::cout);

        hgen.visit(ast::program_ast);
    }
} // namespace cpp

Change include on generated C++

[GENERATOR] Change include on generated C++


//===-- MCAsmInfoCOFF.cpp - COFF asm properties -----------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines target asm properties related what form asm statements
// should take in general on COFF-based targets
//
//===----------------------------------------------------------------------===//

#include "llvm/MC/MCAsmInfoCOFF.h"
#include "llvm/ADT/SmallVector.h"
using namespace llvm;

MCAsmInfoCOFF::MCAsmInfoCOFF() {
  GlobalPrefix = "_";
  COMMDirectiveAlignmentIsInBytes = false;
  HasLCOMMDirective = true;
  HasSetDirective = false;
  HasDotTypeDotSizeDirective = false;
  HasSingleParameterDotFile = false;
  PrivateGlobalPrefix = "L";  // Prefix for private global symbols
  WeakRefDirective = "\t.weak\t";
  LinkOnceDirective = "\t.linkonce discard\n";

  // Doesn't support visibility:
  HiddenVisibilityAttr = ProtectedVisibilityAttr = MCSA_Invalid;

  // Set up DWARF directives
  HasLEB128 = true;  // Target asm supports leb128 directives (little-endian)
  SupportsDebugInformation = true;
  DwarfSectionOffsetDirective = "\t.secrel32\t";
  HasMicrosoftFastStdCallMangling = true;
}

//===-- MCAsmInfoCOFF.cpp - COFF asm properties -----------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines target asm properties related what form asm statements
// should take in general on COFF-based targets
//
//===----------------------------------------------------------------------===//

#include "llvm/MC/MCAsmInfoCOFF.h"
#include "llvm/ADT/SmallVector.h"
using namespace llvm;

MCAsmInfoCOFF::MCAsmInfoCOFF() {
  GlobalPrefix = "_";
  COMMDirectiveAlignmentIsInBytes = false;
  HasLCOMMDirective = true;
  HasDotTypeDotSizeDirective = false;
  HasSingleParameterDotFile = false;
  PrivateGlobalPrefix = "L";  // Prefix for private global symbols
  WeakRefDirective = "\t.weak\t";
  LinkOnceDirective = "\t.linkonce discard\n";

  // Doesn't support visibility:
  HiddenVisibilityAttr = ProtectedVisibilityAttr = MCSA_Invalid;

  // Set up DWARF directives
  HasLEB128 = true;  // Target asm supports leb128 directives (little-endian)
  SupportsDebugInformation = true;
  DwarfSectionOffsetDirective = "\t.secrel32\t";
  HasMicrosoftFastStdCallMangling = true;
}

Revert part of my last commit. the mingw32 build bot doesn't seem to like it.

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@111793 91177308-0d34-0410-b5e6-96231b3b80d8


#include <iostream>
#include <vector>
#include <iomanip>

#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

// printes the hex (in ascii) of an ascii message

int main(int argc, char* argv[])
{
    if(argc < 2) {
        cerr << "Usage: " << argv[0] << " m, where m is a string " <<  endl;
        return -1;
    }

    std::string m(argv[1]);
    if(m.length() < 1)
    {
        cerr << "m must have length > 0" << endl;
        return -1;
    }

    for(int i = 0; i < m.size(); ++i)
    {
        unsigned char ch = m[i];

        cout << hex << setw(2) << setfill('0') << (unsigned int)ch;
    }

    cout << dec << endl;

    return 0;
}

#include <iostream>
#include <vector>
#include <iomanip>

#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

// printes the hex (in ascii) of an ascii message

int main(int argc, char* argv[])
{
    if(argc < 1 || (argc>=2 && strcmp(argv[1],"-h")==0)) {
        cerr << "Usage: " << argv[0] << " [-h] [m], where m is a string." <<  endl;
        cerr << "If no argument is given, string is read from stdin" << endl;
        return -1;
    }

    std::string m;
    if(argc >= 2)
    {
        m = argv[1];
    }
    else
    {
        getline(cin, m);
    }

    if(m.length() < 1)
    {
        cerr << "m must have length > 0" << endl;
        return -1;
    }

    for(int i = 0; i < m.size(); ++i)
    {
        unsigned char ch = m[i];

        cout << hex << setw(2) << setfill('0') << (unsigned int)ch;
    }

    cout << dec << endl;

    return 0;
}

Make so it reads from stdin if no argument is given


#include "audioutil.h"
#include <QFileInfo>

namespace AudioUtil {

QStringList audioExtensions = { "wav", "aif", "ogg", "flac", "iff", "svx" };

bool isAudioFileName(QString file)
{
    return audioExtensions.contains(QFileInfo(file).suffix().toLower());
}

QString audioFileFilter()
{
    QString f = "Audio Files (";
    for (int i = 0; i < audioExtensions.length(); i++)
    {
        if (i > 0) {
            f.append(" ");
        }
        f.append("*.");
        f.append(audioExtensions[i]);
    }
    f.append(")");
    return f;
}

}

#include "audioutil.h"
#include <QFileInfo>

namespace AudioUtil {

QStringList audioExtensions = { "wav", "caf", "aif", "ogg", "flac", "iff", "svx" };

bool isAudioFileName(QString file)
{
    return audioExtensions.contains(QFileInfo(file).suffix().toLower());
}

QString audioFileFilter()
{
    QString f = "Audio Files (";
    for (int i = 0; i < audioExtensions.length(); i++)
    {
        if (i > 0) {
            f.append(" ");
        }
        f.append("*.");
        f.append(audioExtensions[i]);
    }
    f.append(")");
    return f;
}

}

Add support for .caf extension

Add support for .caf extension


// RUN: rm -rf %t
// RUN: mkdir %t
// RUN: echo '[{"directory":".","command":"clang++ '$(llvm-config --cppflags all)' -c %s","file":"%s"}]' > %t/compile_commands.json
// RUN: remove-cstr-calls %t %s | FileCheck %s

#include <string>

namespace llvm { struct StringRef { StringRef(const char *p); }; }

void f1(const std::string &s) {
  f1(s.c_str());  // CHECK:remove-cstr-calls.cpp:11:6:11:14:s
}
void f2(const llvm::StringRef r) {
  std::string s;
  f2(s.c_str());  // CHECK:remove-cstr-calls.cpp:15:6:15:14:s
}
void f3(const llvm::StringRef &r) {
  std::string s;
  f3(s.c_str());  // CHECK:remove-cstr-calls.cpp:19:6:19:14:s
}

// RUN: rm -rf %t
// RUN: mkdir %t
// RUN: echo '[{"directory":".","command":"clang++ '$(llvm-config --cppflags all)' -c %s","file":"%s"}]' > %t/compile_commands.json
// RUN: remove-cstr-calls %t %s | FileCheck %s
// XFAIL: *

#include <string>

namespace llvm { struct StringRef { StringRef(const char *p); }; }

void f1(const std::string &s) {
  f1(s.c_str());  // CHECK:remove-cstr-calls.cpp:11:6:11:14:s
}
void f2(const llvm::StringRef r) {
  std::string s;
  f2(s.c_str());  // CHECK:remove-cstr-calls.cpp:15:6:15:14:s
}
void f3(const llvm::StringRef &r) {
  std::string s;
  f3(s.c_str());  // CHECK:remove-cstr-calls.cpp:19:6:19:14:s
}

Fix test breakage due to example not being built.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@132376 91177308-0d34-0410-b5e6-96231b3b80d8


#include "tests-base.hpp"

#include "utf8rewind.h"

int main(int argc, char** argv)
{
	const char* input = "Hello World!";

	static const size_t output_size = 256;
	char output[output_size];
	wchar_t output_wide[output_size];
	const char* input_seek;
	size_t converted_size;
	int32_t errors;

	memset(output, 0, output_size * sizeof(char));
	memset(output_wide, 0, output_size * sizeof(wchar_t));

	/*
		Convert input to uppercase:

		"Hello World!" -> "HELLO WORLD!"
	*/

	converted_size = utf8toupper(
		input, strlen(input),
		output, output_size - 1,
		&errors);
	if (converted_size == 0 ||
		errors != UTF8_ERR_NONE)
	{
		return -1;
	}

	/*
		Convert UTF-8 input to wide (UTF-16 or UTF-32) encoded text:

		"HELLO WORLD!" -> L"HELLO WORLD!"
	*/

	converted_size = utf8towide(
		output, strlen(output),
		output_wide, (output_size - 1) * sizeof(wchar_t),
		&errors);
	if (converted_size == 0 ||
		errors != UTF8_ERR_NONE)
	{
		return -1;
	}

	/*
		Seek in input:

		"Hello World!" -> "World!"
	*/

	input_seek = utf8seek(input, input, 6, SEEK_SET);

	::testing::InitGoogleTest(&argc, argv);

	int result = RUN_ALL_TESTS();

	return result;
}

#include "tests-base.hpp"

int main(int argc, char** argv)
{
	::testing::InitGoogleTest(&argc, argv);

	int result = RUN_ALL_TESTS();

	if (result != 0)
	{
		std::cout << "Press any key to continue.";

		int wait = 0;
		std::cin >> wait;
	}

	return result;
}

Clean up main entry point.

Clean up main entry point.


// Copyright (c) 2010 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/histogram.h"
#include "net/base/net_test_suite.h"
#if defined(OS_WIN)
#include "net/socket/ssl_client_socket_nss_factory.h"
#endif

int main(int argc, char** argv) {
  // Record histograms, so we can get histograms data in tests.
  StatisticsRecorder recorder;
  NetTestSuite test_suite(argc, argv);

#if defined(OS_WIN)
  // Use NSS for SSL on Windows.  TODO(wtc): this should eventually be hidden
  // inside DefaultClientSocketFactory::CreateSSLClientSocket.
  net::ClientSocketFactory::SetSSLClientSocketFactory(
      net::SSLClientSocketNSSFactory);
  // We want to be sure to init NSPR on the main thread.
  base::EnsureNSPRInit();
#endif

  // TODO(phajdan.jr): Enforce test isolation, http://crbug.com/12710.
  return test_suite.Run();
}

// Copyright (c) 2010 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 "build/build_config.h"
#include "base/histogram.h"
#include "net/base/net_test_suite.h"
#if defined(OS_WIN)
#include "net/socket/ssl_client_socket_nss_factory.h"
#endif

int main(int argc, char** argv) {
  // Record histograms, so we can get histograms data in tests.
  StatisticsRecorder recorder;
  NetTestSuite test_suite(argc, argv);

#if defined(OS_WIN)
  // Use NSS for SSL on Windows.  TODO(wtc): this should eventually be hidden
  // inside DefaultClientSocketFactory::CreateSSLClientSocket.
  net::ClientSocketFactory::SetSSLClientSocketFactory(
      net::SSLClientSocketNSSFactory);
  // We want to be sure to init NSPR on the main thread.
  base::EnsureNSPRInit();
#endif

  // TODO(phajdan.jr): Enforce test isolation, http://crbug.com/12710.
  return test_suite.Run();
}

Include "build/build_config.h" explicitly because we test the
OS_WIN macro.

R=willchan
BUG=43142
TEST=No compilation error.
Review URL: http://codereview.chromium.org/1929005

git-svn-id: http://src.chromium.org/svn/trunk/src@46367 4ff67af0-8c30-449e-8e8b-ad334ec8d88c

Former-commit-id: 9df0e2ea7ef365d6caeba391cbc2486e0696c70d


#include "texture.h"

spectrum SolidColor::at_point(const IntersectionView& isect) const
{
  return color;
}

spectrum SolidColor::at_coord(const Vec2& uv) const
{
  return color;
}

Checkerboard2D::Checkerboard2D(spectrum a, spectrum b, int gsx, int gsy)
  : c1(a), c2(b), grid_size_x(gsx), grid_size_y(gsy > 0 ? gsy : gsx)
{
}

spectrum Checkerboard2D::at_coord(const Vec2& uv) const
{
  int m = int(uv.u * grid_size_x) + int(uv.v * grid_size_y);
  return m % 2 == 0 ? c1 : c2;
}

spectrum GridTexture2D::at_coord(const Vec2& uv) const
{
  scalar xf = fmod(uv.u * grid_size, 1.0);
  scalar yf = fmod(uv.v * grid_size, 1.0);

  if (min(xf, yf) < border_pct * 0.5 || max(xf, yf) > (1 - border_pct * 0.5))
    return border;
  else
    return solid;
}

#include "texture.h"

spectrum SolidColor::at_point(const IntersectionView& isect) const
{
  return color;
}

spectrum SolidColor::at_coord(const Vec2& uv) const
{
  return color;
}

Checkerboard2D::Checkerboard2D(spectrum a, spectrum b, int gsx, int gsy)
  : c1(a), c2(b), grid_size_x(gsx), grid_size_y(gsy > 0 ? gsy : gsx)
{
}

spectrum Checkerboard2D::at_coord(const Vec2& uv) const
{
  int m = std::floor(uv.u * grid_size_x) + std::floor(uv.v * grid_size_y);
  return m % 2 == 0 ? c1 : c2;
}

spectrum GridTexture2D::at_coord(const Vec2& uv) const
{
  scalar xf = fmod(uv.u * grid_size, 1.0);
  scalar yf = fmod(uv.v * grid_size, 1.0);

  if (min(xf, yf) < border_pct * 0.5 || max(xf, yf) > (1 - border_pct * 0.5))
    return border;
  else
    return solid;
}

Fix checkerboard for negative uv

Fix checkerboard for negative uv


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// UNSUPPORTED: c++98, c++03

// <future>

// class packaged_task<R(ArgTypes...)>
// template <class F>
//   packaged_task(F&& f);
// These constructors shall not participate in overload resolution if
//    decay<F>::type is the same type as std::packaged_task<R(ArgTypes...)>.

#include <future>
#include <cassert>

struct A {};
typedef std::packaged_task<A(int, char)> PT;
typedef volatile std::packaged_task<A(int, char)> VPT;

int main()
{
    VPT init{};
    PT p{init}; // expected-error {{no matching constructor for initialization of 'PT' (aka 'packaged_task<A (int, char)>')}}
    // expected-note@future:* 1 {{candidate template ignored: disabled by 'enable_if'}}
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// UNSUPPORTED: c++98, c++03

// <future>

// class packaged_task<R(ArgTypes...)>
// template <class F>
//   packaged_task(F&& f);
// These constructors shall not participate in overload resolution if
//    decay<F>::type is the same type as std::packaged_task<R(ArgTypes...)>.

#include <future>
#include <cassert>

struct A {};
typedef std::packaged_task<A(int, char)> PT;
typedef volatile std::packaged_task<A(int, char)> VPT;

int main()
{
    VPT init{};
    auto const& c_init = init;
    PT p1{init}; // expected-error {{no matching constructor}}
    PT p2{c_init}; // expected-error {{no matching constructor}}
    PT p3{std::move(init)}; // expected-error {{no matching constructor for initialization of 'PT' (aka 'packaged_task<A (int, char)>')}}
}

Add more test cases to packaged_task copyability test

git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@289034 91177308-0d34-0410-b5e6-96231b3b80d8


// RUN: %clangxx_asan %s -o %t && %run %t | FileCheck %s

#include <stdio.h>

static void foo() {
  printf("foo\n");
}

int main() {
  return 0;
}

__attribute__((section(".preinit_array")))
void (*call_foo)(void) = &foo;

__attribute__((section(".init_array")))
void (*call_foo_2)(void) = &foo;

__attribute__((section(".fini_array")))
void (*call_foo_3)(void) = &foo;

// CHECK: foo
// CHECK: foo
// CHECK: foo

// RUN: %clangxx_asan %s -o %t && %run %t | FileCheck %s

#include <stdio.h>

int c = 0;

static void foo() {
  ++c;
}

static void fini() {
  printf("fini\n");
}

int main() {
  printf("c=%d\n", c);
  return 0;
}

__attribute__((section(".preinit_array")))
void (*call_foo)(void) = &foo;

__attribute__((section(".init_array")))
void (*call_foo_2)(void) = &foo;

__attribute__((section(".fini_array")))
void (*call_foo_3)(void) = &fini;

// CHECK: c=2
// CHECK: fini

Fix test on Android i686/fugu

[asan] Fix test on Android i686/fugu

printf from .preinit_array may crash.

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@306940 91177308-0d34-0410-b5e6-96231b3b80d8


#include "QGVGraphPrivate.h"

QGVGraphPrivate::QGVGraphPrivate(Agraph_t *graph)
{
	setGraph(graph);
}

void QGVGraphPrivate::setGraph(Agraph_t *graph)
{
	_graph = graph;
}

Agraph_t* QGVGraphPrivate::graph() const
{
	return _graph;
}

#include "QGVGraphPrivate.h"

QGVGraphPrivate::QGVGraphPrivate(Agraph_t *graph)
  : _graph (NULL)
{
	setGraph(graph);
}

void QGVGraphPrivate::setGraph(Agraph_t *graph)
{
  if (_graph != NULL)
    agclose(_graph);
	_graph = graph;
}

Agraph_t* QGVGraphPrivate::graph() const
{
	return _graph;
}

Call agclose when clearing the graph

Call agclose when clearing the graph


/*
 * Copyright (C) 2008, 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * 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 St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "boolsysfspooler.h"

class BoolSysFsPoolerUnitTest : public QObject
{
    Q_OBJECT

private slots:
    void basic();
};

void BoolSysFsPoolerUnitTest::basic()
{
    BoolSysFsPooler pooler("input1.txt");
    QCOMPARE(pooler.getState(), BoolSysFsPooler::TriStateTrue);
}

#include "boolsysfspoolerunittest.moc"
QTEST_MAIN(BoolSysFsPoolerUnitTest);

/*
 * Copyright (C) 2008, 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * 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 St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "boolsysfspooler.h"

class BoolSysFsPoolerUnitTest : public QObject
{
    Q_OBJECT

private slots:
    void basic();
    void fileMissing();
};

void BoolSysFsPoolerUnitTest::basic()
{
    BoolSysFsPooler pooler("input1.txt");
    QCOMPARE(pooler.getState(), BoolSysFsPooler::TriStateTrue);
}

void BoolSysFsPoolerUnitTest::fileMissing()
{
    BoolSysFsPooler pooler("does-not-exist.txt");
    QCOMPARE(pooler.getState(), BoolSysFsPooler::TriStateUnknown);
}

#include "boolsysfspoolerunittest.moc"
QTEST_MAIN(BoolSysFsPoolerUnitTest);

Test missing file in BoolSysFsPooler.

Test missing file in BoolSysFsPooler.


#include "stdafx.h"
#include "internal/internal_datastore.h"
#include "internal/constants.h"
#include "datastore.h"

namespace You {
namespace DataStore {

DataStore& DataStore::get() {
	static DataStore ds;
	return ds;
}

Transaction DataStore::begin() {
	return Internal::DataStore::get().begin();
}

void DataStore::post(TaskId taskId, const KeyValuePairs& task) {
	Internal::DataStore::get().post(taskId, task);
}

void DataStore::put(TaskId taskId, const KeyValuePairs& task) {
	Internal::DataStore::get().put(taskId, task);
}

void DataStore::erase(TaskId taskId) {
	Internal::DataStore::get().erase(taskId);
}

std::vector<KeyValuePairs> DataStore::getAllTasks() {
	return Internal::DataStore::get().getAll(Internal::TASKS_NODE);
}

std::vector<KeyValuePairs> DataStore::getAllResources() {
	return Internal::DataStore::get().getAll(Internal::RESOURCES_NODE);
}

}  // namespace DataStore
}  // namespace You

#include "stdafx.h"
#include "internal/internal_datastore.h"
#include "internal/constants.h"
#include "datastore.h"

namespace You {
namespace DataStore {

DataStore& DataStore::get() {
	static DataStore ds;
	return ds;
}

Transaction DataStore::begin() {
	return Internal::DataStore::get().begin();
}

void DataStore::post(TaskId taskId, const KeyValuePairs& task) {
	std::wstring stringId = boost::lexical_cast<std::wstring>(taskId);
	Internal::DataStore::get().post(Internal::TASKS_NODE, stringId, task);
}

void DataStore::put(TaskId taskId, const KeyValuePairs& task) {
	std::wstring stringId = boost::lexical_cast<std::wstring>(taskId);
	Internal::DataStore::get().put(Internal::TASKS_NODE, stringId, task);
}

void DataStore::erase(TaskId taskId) {
	std::wstring stringId = boost::lexical_cast<std::wstring>(taskId);
	Internal::DataStore::get().erase(Internal::TASKS_NODE, stringId);
}

std::vector<KeyValuePairs> DataStore::getAllTasks() {
	return Internal::DataStore::get().getAll(Internal::TASKS_NODE);
}

std::vector<KeyValuePairs> DataStore::getAllResources() {
	return Internal::DataStore::get().getAll(Internal::RESOURCES_NODE);
}

}  // namespace DataStore
}  // namespace You

Fix post, put, erase for tasks to follow the changes


#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using namespace testing;
using std::tr1::make_tuple;
using std::tr1::get;

CV_ENUM(Mat_Type, CV_8UC1, CV_8UC3, CV_32FC1, CV_32FC3)

typedef TestBaseWithParam< tr1::tuple<Size, int, Mat_Type> > TestBilateralFilter;

PERF_TEST_P( TestBilateralFilter, BilateralFilter,
             Combine(
                Values( szVGA, sz1080p ), // image size
                Values( 3, 5 ), // d
                Mat_Type::all() // image type
             )
)
{
    Size sz;
    int d, type;
    const double sigmaColor = 1., sigmaSpace = 1.;

    sz         = get<0>(GetParam());
    d          = get<1>(GetParam());
    type       = get<2>(GetParam());

    Mat src(sz, type);
    Mat dst(sz, type);

    declare.in(src, WARMUP_RNG).out(dst).time(20);

    TEST_CYCLE() bilateralFilter(src, dst, d, sigmaColor, sigmaSpace, BORDER_DEFAULT);

    SANITY_CHECK(dst);
}

#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using namespace testing;
using std::tr1::make_tuple;
using std::tr1::get;

CV_ENUM(Mat_Type, CV_8UC1, CV_8UC3, CV_32FC1, CV_32FC3)

typedef TestBaseWithParam< tr1::tuple<Size, int, Mat_Type> > TestBilateralFilter;

PERF_TEST_P( TestBilateralFilter, BilateralFilter,
             Combine(
                Values( szVGA, sz1080p ), // image size
                Values( 3, 5 ), // d
                Mat_Type::all() // image type
             )
)
{
    Size sz;
    int d, type;
    const double sigmaColor = 1., sigmaSpace = 1.;

    sz         = get<0>(GetParam());
    d          = get<1>(GetParam());
    type       = get<2>(GetParam());

    Mat src(sz, type);
    Mat dst(sz, type);

    declare.in(src, WARMUP_RNG).out(dst).time(20);

    TEST_CYCLE() bilateralFilter(src, dst, d, sigmaColor, sigmaSpace, BORDER_DEFAULT);

    SANITY_CHECK(dst, .01, ERROR_RELATIVE);
}

Change sanity check for perfomance test of bilateral filter


#include <ncurses.h>

#include "lightsout.hpp"

namespace roadagain
{

lightsout::lightsout(int width, int height) : width(width), height(height)
{
    lights = new bool*[height + 2]();
    for (int i = 0; i < height + 2; i++){
        lights[i] = new bool[width + 2]();
    }
}

lightsout::~lightsout()
{
    ;
}

}

#include <ncurses.h>

#include "lightsout.hpp"

namespace roadagain
{

board::board(int width, int height) : width(width), height(height)
{
    lights = new bool*[height + 2]();
    for (int i = 0; i < height + 2; i++){
        lights[i] = new bool[width + 2]();
    }
}

board::~board()
{
    ;
}

}

Fix name of class and constructor

Fix name of class and constructor


#include <common/buffer.h>

#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>

#include <io/pipe.h>

#include <xcodec/xcodec.h>
#include <xcodec/xcodec_encoder.h>
#include <xcodec/xcodec_encoder_pipe.h>

XCodecEncoderPipe::XCodecEncoderPipe(XCodec *codec)
: PipeSimple("/xcodec/encoder/pipe"),
  encoder_(codec)
{
	encoder_.set_pipe(this);
}

XCodecEncoderPipe::~XCodecEncoderPipe()
{
	encoder_.set_pipe(NULL);
}

void
XCodecEncoderPipe::output_ready(void)
{
	PipeSimple::output_spontaneous();
}

bool
XCodecEncoderPipe::process(Buffer *out, Buffer *in)
{
	encoder_.encode(out, in);
	return (true);
}

#include <common/buffer.h>

#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>

#include <io/pipe.h>

#include <xcodec/xcodec.h>
#include <xcodec/xcodec_encoder.h>
#include <xcodec/xcodec_encoder_pipe.h>

XCodecEncoderPipe::XCodecEncoderPipe(XCodec *codec)
: PipeSimple("/xcodec/encoder/pipe"),
  encoder_(codec)
{
	encoder_.set_pipe(this);
}

XCodecEncoderPipe::~XCodecEncoderPipe()
{
	encoder_.set_pipe(NULL);
}

void
XCodecEncoderPipe::output_ready(void)
{
}

bool
XCodecEncoderPipe::process(Buffer *out, Buffer *in)
{
	encoder_.encode(out, in);
	return (true);
}

Remove output_spontaneous use for now.

Remove output_spontaneous use for now.

git-svn-id: 9e2532540f1574e817ce42f20b9d0fb64899e451@568 4068ffdb-0463-0410-8185-8cc71e3bd399


#include "ofp/unittest.h"
#include "ofp/hello.h"

using namespace ofp;

TEST(hello, HelloBuilder1) {
  HelloBuilder msg{ProtocolVersions{1, 2, 3, 4}};

  MemoryChannel channel{99};
  msg.send(&channel);

  EXPECT_EQ(0x10, channel.size());
  EXPECT_HEX("0400-0010-00000001 00010008-0000001E", channel.data(),
             channel.size());
}

TEST(hello, HelloBuilder2) {
  HelloBuilder msg{ProtocolVersions{1, 4}};

  MemoryChannel channel{OFP_VERSION_1};
  msg.send(&channel);

  EXPECT_EQ(0x10, channel.size());
  EXPECT_HEX("0400-0010-00000001 00010008-00000012", channel.data(),
             channel.size());
}

TEST(hello, HelloBuilder3) {
  HelloBuilder msg{ProtocolVersions{1}};

  MemoryChannel channel{OFP_VERSION_4};
  msg.send(&channel);

  EXPECT_EQ(0x08, channel.size());
  EXPECT_HEX("0100-0008-00000001", channel.data(), channel.size());
}

TEST(hello, HelloBuilder4) {
  HelloBuilder msg{OFP_VERSION_1};

  MemoryChannel channel{0};
  msg.send(&channel);

  EXPECT_EQ(0x08, channel.size());
  EXPECT_HEX("0100-0008-00000001", channel.data(), channel.size());
}

Add a HelloBuilder unit test.

Add a HelloBuilder unit test.


#include <map>
#include <ncurses.h>
#include <string>

#include "file_contents.hh"
#include "mode.hh"
#include "show_message.hh"
#include "prefix.hh"

prefix::prefix(std::string message)
    : message(message) { }

void prefix::push_back(char ch, std::function<void(contents&, boost::optional<int>)> fun) {
    this->map[ch] = fun;
}

void prefix::operator()(contents& cont, boost::optional<int> op) {
    show_message(message + "-");
    char ch = getch();
    auto it = map.find(ch);
    if(it == map.end()) {
        show_message(std::string("Didn't recognize key sequence: '")
                     + message + '-' + ch + '\'');
    } else {
        it->second(cont, op);
        showing_message = false;
    }
}

prefix::operator std::function < void ( contents&,
                                        boost::optional<int> ) > () {
    return std::function < void ( contents&,
                                  boost::optional<int> ) >
        ([&,this] (contents& cont, boost::optional<int> op)
         {
             (*this)(cont,op);
         });
}

#include <map>
#include <ncurses.h>
#include <string>

#include "file_contents.hh"
#include "mode.hh"
#include "show_message.hh"
#include "prefix.hh"

prefix::prefix(std::string message)
    : message(message) { }

void prefix::push_back(char ch, std::function<void(contents&, boost::optional<int>)> fun) {
    this->map[ch] = fun;
}

void prefix::operator()(contents& cont, boost::optional<int> op) {
    show_message(message + "-");
    char ch = getch();
    auto it = map.find(ch);
    if(it == map.end()) {
        show_message(std::string("Didn't recognize key sequence: '")
                     + message + '-' + ch + '\'');
    } else {
        it->second(cont, op);
        showing_message = false;
    }
}

prefix::operator std::function < void ( contents&,
                                        boost::optional<int> ) > () {
    return std::function < void ( contents&,
                                  boost::optional<int> ) >
        ([this] (contents& cont, boost::optional<int> op)
         {
             (*this)(cont,op);
         });
}

Make lambda capture *pointer* to ``this`` by value


/* JEBTest: A C++ unit testing framework
 * Copyright 2013 Jan Erik Breimo
 * All rights reserved.
 *
 * This file is distributed under the BSD License.
 * License text is included with the source distribution.
 */
#include "MacroUtilities.hpp"

#include "JEB/Sys/Path.hpp"
#include "JEB/String/String.hpp"

#undef JEB

using namespace JEBTestLib::String;
using namespace JEBTestLib::Sys;

namespace JEB { namespace Test {

// std::string extractTestName(const std::string& name)
// {
//     if (startsWith(name, "test_", FindFlags::CaseInsensitive))
//         return name.substr(5);
//     return name;
// }

std::vector<std::string> extractTestNames(const std::string& names)
{
    return split(names, ",");
}

std::string extractSuiteName(const std::string& path)
{
    return Path::baseName(Path::removeExtension(path));
}

}}

/* JEBTest: A C++ unit testing framework
 * Copyright 2013 Jan Erik Breimo
 * All rights reserved.
 *
 * This file is distributed under the BSD License.
 * License text is included with the source distribution.
 */
#include "MacroUtilities.hpp"

#include <algorithm>
#include "JEB/Sys/Path.hpp"
#include "JEB/String/String.hpp"

#undef JEB

using namespace JEBTestLib::String;
using namespace JEBTestLib::Sys;

namespace JEB { namespace Test {

// std::string extractTestName(const std::string& name)
// {
//     if (startsWith(name, "test_", FindFlags::CaseInsensitive))
//         return name.substr(5);
//     return name;
// }

std::vector<std::string> extractTestNames(const std::string& names)
{
    std::vector<std::string> result = split(names, ",", 0, SplitFlags::IgnoreEmpty);
    for (auto it = result.begin(); it != result.end(); ++it)
      *it = trim(*it);
    return result;
}

std::string extractSuiteName(const std::string& path)
{
    return Path::baseName(Path::removeExtension(path));
}

}}

Remove white space characters from test names


#include "Registration.hpp"

#include "comp/StaticObjRefID.hpp"
#include "comp/Transform.hpp"
#include "comp/ConstantRotation.hpp"
#include "comp/CameraSelect.hpp"
#include "comp/ClickBox2D.hpp"
#include "comp/StaticCamera.hpp"
#include "comp/StaticOrthoCamera.hpp"
#include "comp/StaticMouseInput.hpp"
#include "comp/StaticKeyboardInput.hpp"
#include "comp/StaticScreenDims.hpp"
#include "comp/StaticGlobalTime.hpp"

#include "systems/ConstantRotationSys.hpp"
#include "systems/ClickBox2DSys.hpp"

namespace gen {

void registerAll(CPM_ES_CEREAL_NS::CerealCore& core)
{
  // Register systems
  registerSystem_ConstantRotation();
  registerSystem_ClickBox2D();

  // Register components
  core.registerComponent<ConstantRotation>();
  core.registerComponent<Transform>();
  core.registerComponent<CameraSelect>();
  core.registerComponent<ClickBox2D>();
  core.registerComponent<StaticMouseInput>();
  core.registerComponent<StaticKeyboardInput>();
  core.registerComponent<StaticScreenDims>();
  core.registerComponent<StaticGlobalTime>();
  core.registerComponent<StaticCamera>();
  core.registerComponent<StaticOrthoCamera>();
  core.registerComponent<StaticObjRefID>();
}

} // namespace gen

#include "Registration.hpp"

#include "comp/StaticObjRefID.hpp"
#include "comp/Transform.hpp"
#include "comp/ConstantRotation.hpp"
#include "comp/CameraSelect.hpp"
#include "comp/ClickBox2D.hpp"
#include "comp/StaticCamera.hpp"
#include "comp/StaticOrthoCamera.hpp"
#include "comp/StaticMouseInput.hpp"
#include "comp/StaticKeyboardInput.hpp"
#include "comp/StaticScreenDims.hpp"
#include "comp/StaticGlobalTime.hpp"
#include "comp/StaticRandom.hpp"

#include "systems/ConstantRotationSys.hpp"
#include "systems/ClickBox2DSys.hpp"

namespace gen {

void registerAll(CPM_ES_CEREAL_NS::CerealCore& core)
{
  // Register systems
  registerSystem_ConstantRotation();
  registerSystem_ClickBox2D();

  // Register components
  core.registerComponent<ConstantRotation>();
  core.registerComponent<Transform>();
  core.registerComponent<CameraSelect>();
  core.registerComponent<ClickBox2D>();
  core.registerComponent<StaticMouseInput>();
  core.registerComponent<StaticKeyboardInput>();
  core.registerComponent<StaticScreenDims>();
  core.registerComponent<StaticGlobalTime>();
  core.registerComponent<StaticCamera>();
  core.registerComponent<StaticOrthoCamera>();
  core.registerComponent<StaticObjRefID>();
  core.registerComponent<StaticRandom>();
}

} // namespace gen

Add StaticRandom component to registration.


#include "core/example_module.hpp"

using namespace core;

int ExampleModule::getme(void){
    return -value;
}

void ExampleModule::setme(int newvalue){
    value = newvalue;
}

#include "core/example_module.hpp"

using namespace core;

int ExampleModule::getme(void){
    return value;
}

void ExampleModule::setme(int newvalue){
    value = newvalue;
}

Fix intentional bug in example module

Fix intentional bug in example module

Fix the intentional bug added in the last commit to check that travis
builds now complete successfully.


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
  public:
    TreeNode *invertTree(TreeNode *root) {
        if (!root || (!root->left && !root->right))
            return root;
        auto t = root->left;
        root->left = root->right;
        root->right = t;
        if (root->left)
            invertTree(root->left);
        if (root->right)
            invertTree(root->right);
        return root;
    }
};

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
  public:
    TreeNode *invertTree(TreeNode *root) {
        if (!root || (!root->left && !root->right)) {
            return root;
        }
        auto t = root->left;
        root->left = root->right;
        root->right = t;
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};

Update leetcode solution for problem 226


//! [0]
QPainter painter(this);
QPen pen(Qt::green, 3, Qt::DashDotLine, Qt::RoundCap, Qt::RoundJoin);
painter.setPen(pen);
//! [0]

//! [1]
QPainter painter(this);
QPen pen();  // creates a default pen

pen.setStyle(Qt::DashDotLine);
pen.setWidth(3);
pen.setBrush(Qt::green);
pen.setCapStyle(Qt::RoundCap);
pen.setJoinStyle(Qt::RoundJoin);

painter.setPen(pen);
//! [1]

//! [2]
QPen pen;
QVector<qreal> dashes;
qreal space = 4;

dashes << 1 << space << 3 << space << 9 << space
           << 27 << space << 9;

pen.setDashPattern(dashes);
//! [2]

//! [3]
QPen pen;
QVector<qreal> dashes;
qreal space = 4;
dashes << 1 << space << 3 << space << 9 << space
           << 27 << space << 9;
pen.setDashPattern(dashes);
//! [3]

//! [0]
QPainter painter(this);
QPen pen(Qt::green, 3, Qt::DashDotLine, Qt::RoundCap, Qt::RoundJoin);
painter.setPen(pen);
//! [0]

//! [1]
QPainter painter(this);
QPen pen();  // creates a default pen

pen.setStyle(Qt::DashDotLine);
pen.setWidth(3);
pen.setBrush(Qt::green);
pen.setCapStyle(Qt::RoundCap);
pen.setJoinStyle(Qt::RoundJoin);

painter.setPen(pen);
//! [1]

//! [2]
QPen pen;
QVector<qreal> dashes;
qreal space = 4;

dashes << 1 << space << 3 << space << 9 << space
           << 27 << space << 9 << space;

pen.setDashPattern(dashes);
//! [2]

//! [3]
QPen pen;
QVector<qreal> dashes;
qreal space = 4;
dashes << 1 << space << 3 << space << 9 << space
           << 27 << space << 9 << space;
pen.setDashPattern(dashes);
//! [3]

Fix the dash pattern examples in the documentation of QPen

The custom dash pattern must have an even number of entries. Our
examples were using an odd number.


#include "client.h"

DEFINE_string(config_filename, "", "Where to find the config file.");

int main(int argc, char* argv[]) {
  InitGoogle(argv[0], &argc, &argv, true);
  grr::Client::StaticInit();
  grr::Client client(FLAGS_config_filename);
  client.Run();
  return 0;
}

#include "client.h"

int main(int argc, char* argv[]) {
  grr::Client::StaticInit();
  if (argc != 2) {
    GOOGLE_LOG(FATAL) << "Usage is: client <config>";
  }
  grr::Client client(argv[1]);
  client.Run();
  return 0;
}

Remove dependency on Google argument parsing.


#include "VolumeSlider.h"

#include "..\Controllers\Volume\CoreAudio.h"
#include "..\Error.h"
#include "..\Settings.h"
#include "..\Skin.h"
#include "SliderKnob.h"

VolumeSlider::VolumeSlider(CoreAudio &volumeCtrl) :
SliderWnd(L"3RVX-VolumeSlider", L"3RVX Volume Slider"),
_settings(*Settings::Instance()),
_volumeCtrl(volumeCtrl) {

    Skin *skin = _settings.CurrentSkin();

    Gdiplus::Bitmap *bg = skin->ControllerBgImg("volume");
    BackgroundImage(bg);

    _knob = skin->Knob("volume");
    _vertical = _knob->Vertical();

    std::list<Meter*> meters = skin->Meters("volume");
    for (Meter *m : meters) {
        AddMeter(m);
    }

    Knob(_knob);
}

void VolumeSlider::SliderChanged() {
    _volumeCtrl.Volume(_knob->Value());
}

void VolumeSlider::MeterLevels(float level) {
    if (Visible() && _dragging == false) {
        MeterWnd::MeterLevels(level);
        Update();
    }
    _level = level;
}

void VolumeSlider::Show() {
    MeterWnd::MeterLevels(_level);
    Update();
    SliderWnd::Show();
}

bool VolumeSlider::Visible() {
    return _visible;
}

#include "VolumeSlider.h"

#include "..\Controllers\Volume\CoreAudio.h"
#include "..\Error.h"
#include "..\Settings.h"
#include "..\Skin.h"
#include "SliderKnob.h"

VolumeSlider::VolumeSlider(CoreAudio &volumeCtrl) :
SliderWnd(L"3RVX-VolumeSlider", L"3RVX Volume Slider"),
_settings(*Settings::Instance()),
_volumeCtrl(volumeCtrl) {

    Skin *skin = _settings.CurrentSkin();

    Gdiplus::Bitmap *bg = skin->ControllerBgImg("volume");
    BackgroundImage(bg);

    _knob = skin->Knob("volume");
    _vertical = _knob->Vertical();

    std::list<Meter*> meters = skin->Meters("volume");
    for (Meter *m : meters) {
        AddMeter(m);
    }

    Knob(_knob);
}

void VolumeSlider::SliderChanged() {
    _volumeCtrl.Volume(_knob->Value());
}

void VolumeSlider::MeterLevels(float level) {
    if (Visible() && _dragging == false) {
        MeterWnd::MeterLevels(level);
        Update();
    }
    _level = level;
}

void VolumeSlider::Show() {
    MeterWnd::MeterLevels(_level);
    Update();
    SliderWnd::Show();
    SetActiveWindow(_hWnd);
    SetForegroundWindow(_hWnd);
}

bool VolumeSlider::Visible() {
    return _visible;
}

Make slider the foreground window upon Show()

This helps us detect when the window loses focus


#include "common.th"

// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
    pushall(h,i,j)

    b <- 0
    i <- d == 0
    i <- c == 0 + i
    i <- i <> 0
    jnzrel(i, L_done)

    h <- 1

    j <- d >> 31    // save sign bit in j
    j <- -j         // convert sign to flag
    d <- d ^ j      // adjust multiplier
    d <- d - j

L_top:
    // use constant 1 in h to combine instructions
    i <- d & h - 1
    i <- c &~ i
    b <- b + i
    c <- c << 1
    d <- d >> 1
    i <- d <> 0
    jnzrel(i, L_top)

    b <- b ^ j      // adjust product for signed math
    b <- b - j

L_done:
    popall(h,i,j)
    ret

#include "common.th"

// c <- multiplicand
// d <- multiplier
// b -> product
.global imul
imul:
    pushall(h,i,j)

    b <- 0
#if IMUL_EARLY_EXITS
    i <- d == 0
    i <- c == 0 + i
    i <- i <> 0
    jnzrel(i, L_done)
#endif

    h <- 1

    j <- d >> 31    // save sign bit in j
    j <- -j         // convert sign to flag
    d <- d ^ j      // adjust multiplier
    d <- d - j

L_top:
    // use constant 1 in h to combine instructions
    i <- d & h - 1
    i <- c &~ i
    b <- b + i
    c <- c << 1
    d <- d >> 1
    i <- d <> 0
    jnzrel(i, L_top)

    b <- b ^ j      // adjust product for signed math
    b <- b - j

L_done:
    popall(h,i,j)
    ret

Make imul early exits optional, disabled


#pragma once

#include "CurveWrapperCodec.h"

namespace spotify
{
namespace json
{

using CurveWrapper = noise::module::Wrapper<noise::module::Curve>;

codec::object_t<CurveWrapper> default_codec_t<CurveWrapper>::codec()
    {
        auto codec = codec::object<CurveWrapper>();
        codec.required("type", codec::eq<std::string>("Curve"));
        codec.required("SourceModule", codec::ignore_t<int>());
        codec.optional("ControlPoints",
                       [](const CurveWrapper& mw)
                       {
                           std::vector<std::pair<double, double>> all_control_points;
                           const noise::module::ControlPoint* raw_control_points = mw.module->GetControlPointArray();
                           const int control_point_count = mw.module->GetControlPointCount();
                           for (int i = 0; i < control_point_count; i++)
                           {
                               const noise::module::ControlPoint control_point = raw_control_points[i];
                               all_control_points.push_back({control_point.inputValue, control_point.outputValue});
                           }
                           return all_control_points;
                       },
                                      [](CurveWrapper& mw, std::vector<std::pair<double, double>> all_control_points)
                       {
                           for (std::pair<double, double> control_point : all_control_points)
                           {
                               mw.module->AddControlPoint(control_point.first, control_point.second);
                           }
                       },
                       default_codec<std::vector<std::pair<double, double>>>());
        return codec;
    }

}
}

#pragma once

#include "CurveWrapperCodec.h"

namespace spotify
{
namespace json
{

using CurveWrapper = noise::module::Wrapper<noise::module::Curve>;

codec::object_t<CurveWrapper> default_codec_t<CurveWrapper>::codec()
    {
        auto codec = codec::object<CurveWrapper>();
        codec.required("type", codec::eq<std::string>("Curve"));
        codec.required("SourceModule", codec::ignore_t<int>());
        codec.optional("ControlPoints",
                       [](const CurveWrapper& mw)
                       {
                           std::vector<std::pair<double, double>> all_control_points;
                           const noise::module::ControlPoint* raw_control_points = mw.module->GetControlPointArray();
                           const int control_point_count = mw.module->GetControlPointCount();
                           std::transform(raw_control_points,
                                          raw_control_points + control_point_count,
                                          std::inserter(all_control_points, all_control_points.begin()),
                                          [](noise::module::ControlPoint control_point)
                           {
                               return std::make_pair(control_point.inputValue, control_point.outputValue);
                           });
                           return all_control_points;
                       },
                       [](CurveWrapper& mw, std::vector<std::pair<double, double>> all_control_points)
                       {
                           for (std::pair<double, double> control_point : all_control_points)
                           {
                               mw.module->AddControlPoint(control_point.first, control_point.second);
                           }
                       },
                       default_codec<std::vector<std::pair<double, double>>>());
        return codec;
    }

}
}

Use std::transform in Curve codec

Use std::transform in Curve codec


// RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm -main-file-name cxx-virtual-destructor-calls.cpp %s -o - -fprofile-instrument=clang | FileCheck %s

struct Member {
  ~Member();
};

struct A {
  virtual ~A();
};

struct B : A {
  Member m;
  virtual ~B();
};

// Base dtor
// CHECK: @__profn__ZN1BD2Ev = private constant [9 x i8] c"_ZN1BD2Ev"

// Complete dtor must not be instrumented
// CHECK-NOT: @__profn__ZN1BD1Ev = private constant [9 x i8] c"_ZN1BD1Ev"

// Deleting dtor must not be instrumented
// CHECK-NOT: @__profn__ZN1BD0Ev = private constant [9 x i8] c"_ZN1BD0Ev"

// Base dtor counters and profile data
// CHECK: @__profc__ZN1BD2Ev = private global [1 x i64] zeroinitializer
// CHECK: @__profd__ZN1BD2Ev =

// Complete dtor counters and profile data must absent
// CHECK-NOT: @__profc__ZN1BD1Ev = private global [1 x i64] zeroinitializer
// CHECK-NOT: @__profd__ZN1BD1Ev =

// Deleting dtor counters and profile data must absent
// CHECK-NOT: @__profc__ZN1BD0Ev = private global [1 x i64] zeroinitializer
// CHECK-NOT: @__profd__ZN1BD0Ev =

B::~B() { }

// RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm -main-file-name cxx-virtual-destructor-calls.cpp %s -o - -fprofile-instrument=clang | FileCheck %s

struct Member {
  ~Member();
};

struct A {
  virtual ~A();
};

struct B : A {
  Member m;
  virtual ~B();
};

// Base dtor counters and profile data
// CHECK: @__profc__ZN1BD2Ev = private global [1 x i64] zeroinitializer
// CHECK: @__profd__ZN1BD2Ev =

// Complete dtor counters and profile data must absent
// CHECK-NOT: @__profc__ZN1BD1Ev = private global [1 x i64] zeroinitializer
// CHECK-NOT: @__profd__ZN1BD1Ev =

// Deleting dtor counters and profile data must absent
// CHECK-NOT: @__profc__ZN1BD0Ev = private global [1 x i64] zeroinitializer
// CHECK-NOT: @__profd__ZN1BD0Ev =

B::~B() { }

[profiling] Update test case to deal with name variable change (NFC)

The 'profn' name variables shouldn't show up after we run the instrprof
pass, see https://reviews.llvm.org/D29921 for more details.

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@295085 91177308-0d34-0410-b5e6-96231b3b80d8


#include "CuteHMILockScreenQMLPlugin.hpp"
#include "cutehmi/lock_screen/Auth.hpp"

#include <QtQml>

void CuteHMILockScreenQMLPlugin::registerTypes(const char * uri)
{
    Q_ASSERT(uri == QLatin1String("CuteHMI.LockScreen"));
    qmlRegisterSingletonType<cutehmi::lockscreen::Auth>(uri, 1, 0, "Auth", AuthProvider);
}

QObject * CuteHMILockScreenQMLPlugin::AuthProvider(QQmlEngine * engine, QJSEngine * scriptEngine)
{
    Q_UNUSED(scriptEngine)

    cutehmi::lockscreen::Auth *interface = new cutehmi::lockscreen::Auth();
    engine->setObjectOwnership(interface, QQmlEngine::CppOwnership);
    return interface;
}

#include "CuteHMILockScreenQMLPlugin.hpp"
#include "cutehmi/lock_screen/Auth.hpp"

#include <QtQml>

#include <memory>

void CuteHMILockScreenQMLPlugin::registerTypes(const char * uri)
{
    Q_ASSERT(uri == QLatin1String("CuteHMI.LockScreen"));
    qmlRegisterSingletonType<cutehmi::lockscreen::Auth>(uri, 1, 0, "Auth", AuthProvider);
}

QObject * CuteHMILockScreenQMLPlugin::AuthProvider(QQmlEngine * engine, QJSEngine * scriptEngine)
{
    Q_UNUSED(scriptEngine)
    Q_UNUSED(engine)

    std::unique_ptr<cutehmi::lockscreen::Auth> instance(new cutehmi::lockscreen::Auth);
    return instance.release();
}

Change AuthProvider to be handled by unique_ptr.


// 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 "chrome/browser/ui/views/dropdown_bar_host.h"

#include "base/logging.h"
#include "ui/aura/window.h"
#include "ui/views/widget/widget.h"

using content::WebContents;

NativeWebKeyboardEvent DropdownBarHost::GetKeyboardEvent(
     const WebContents* contents,
     const views::KeyEvent& key_event) {
  return NativeWebKeyboardEvent(key_event.native_event());
}

void DropdownBarHost::SetWidgetPositionNative(const gfx::Rect& new_pos,
                                              bool no_redraw) {
  if (!host_->IsVisible())
    host_->GetNativeView()->Show();
  host_->GetNativeView()->SetBounds(new_pos);
}

// Copyright (c) 2012 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 "chrome/browser/ui/views/dropdown_bar_host.h"

#include "base/logging.h"
#include "ui/aura/window.h"
#include "ui/views/widget/widget.h"

using content::WebContents;

NativeWebKeyboardEvent DropdownBarHost::GetKeyboardEvent(
     const WebContents* contents,
     const views::KeyEvent& key_event) {
  return NativeWebKeyboardEvent(key_event.native_event());
}

void DropdownBarHost::SetWidgetPositionNative(const gfx::Rect& new_pos,
                                              bool no_redraw) {
  if (!host_->IsVisible())
    host_->GetNativeView()->Show();
  host_->GetNativeView()->SetBounds(new_pos);
  host_->StackAtTop();
}

aura: Fix findbar visibility when switching between tabs.

BUG=110936
TEST=manually

Review URL: https://chromiumcodereview.appspot.com/9293031

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@119909 0039d316-1c4b-4281-b951-d872f2087c98


#include "OptionsManager.h"

#include <fstream>

#include <spotify/json.hpp>

#include "codecs/OptionsCodec.h"

OptionsManager::OptionsManager(std::string filename)
{
    std::ifstream ifs(filename);
    if (!ifs.good())
    {
        throw std::runtime_error("Could not open options file");
    }

    std::string str{std::istreambuf_iterator<char>(ifs),
                    std::istreambuf_iterator<char>()};

    mOptions = spotify::json::decode<Options>(str.c_str());
    mOptions.filename = filename;
}

void OptionsManager::loadOptions(std::string filename)
{
    std::ifstream ifs(filename);
    if (!ifs.good())
    {
        throw std::runtime_error("Could not open options file");
    }

    std::string str{std::istreambuf_iterator<char>(ifs),
                    std::istreambuf_iterator<char>()};

    Options options = spotify::json::decode<Options>(str.c_str());
    options.filename = filename;
}

const Options& OptionsManager::getOptions() const
{
    return mOptions;
}

#include "OptionsManager.h"

#include <fstream>

#include <boost/filesystem.hpp>

#include <spotify/json.hpp>

#include "codecs/OptionsCodec.h"

OptionsManager::OptionsManager(std::string filename)
{
    std::ifstream ifs(filename);
    if (!ifs.good())
    {
        throw std::runtime_error("Could not open options file");
    }

    std::string str{std::istreambuf_iterator<char>(ifs),
                    std::istreambuf_iterator<char>()};

    mOptions = spotify::json::decode<Options>(str.c_str());
    mOptions.filename = filename;

    // TODO(hryniuk): move it elsewhere
    auto outputDirectory = mOptions.outputDirectory;
    boost::filesystem::path p(filename);
    p.remove_filename();
    p.append(outputDirectory);
    boost::filesystem::create_directories(p);
    auto relativeOutputDirectory = p.string();
    mOptions.relativeOutputDirectory = relativeOutputDirectory;
}

void OptionsManager::loadOptions(std::string filename)
{
    std::ifstream ifs(filename);
    if (!ifs.good())
    {
        throw std::runtime_error("Could not open options file");
    }

    std::string str{std::istreambuf_iterator<char>(ifs),
                    std::istreambuf_iterator<char>()};

    Options options = spotify::json::decode<Options>(str.c_str());
    options.filename = filename;
}

const Options& OptionsManager::getOptions() const
{
    return mOptions;
}

Add missing output directory creation

Add missing output directory creation


/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QApplication>
#include <QPushButton>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QPushButton *hello("Hello world!");
    hello.resize(100, 30);

    hello.show();
    return app.exec();
}

Add license header to this file

Add license header to this file


#include <evpp/exp.h>
#include <evpp/tcp_server.h>
#include <evpp/buffer.h>
#include <evpp/tcp_conn.h>

void OnMessage(const evpp::TCPConnPtr& conn,
               evpp::Buffer* msg,
               evpp::Timestamp ts) {
    std::string s = msg->NextAllString();
    LOG_INFO << "Received a message [" << s << "]";
    conn->Send(s);

    if (s == "quit" || s == "exit") {
        conn->Close();
    }
}

int main(int argc, char* argv[]) {
    std::string port = "9099";

    if (argc == 2) {
        port = argv[1];
    }

    std::string addr = std::string("0.0.0.0:") + port;
    evpp::EventLoop loop;
    evpp::TCPServer server(&loop, addr, "TCPEcho", 0);
    server.SetMessageCallback(&OnMessage);
    server.Start();
    loop.Run();
    return 0;
}

#ifdef WIN32
#include "winmain-inl.h"
#endif

#include <evpp/exp.h>
#include <evpp/tcp_server.h>
#include <evpp/buffer.h>
#include <evpp/tcp_conn.h>

#ifdef _WIN32
#include "winmain-inl.h"
#endif

void OnMessage(const evpp::TCPConnPtr& conn,
               evpp::Buffer* msg,
               evpp::Timestamp ts) {
    std::string s = msg->NextAllString();
    LOG_INFO << "Received a message [" << s << "]";
    conn->Send(s);

    if (s == "quit" || s == "exit") {
        conn->Close();
    }
}

void OnConnection(const evpp::TCPConnPtr& conn) {
    if (conn->IsConnected()) {
        LOG_INFO << "Accept a new connection from " << conn->remote_addr();
    } else {
        LOG_INFO << "Disconnected from " << conn->remote_addr();
    }
}

int main(int argc, char* argv[]) {
    std::string port = "9099";
    if (argc == 2) {
        port = argv[1];
    }
    std::string addr = std::string("0.0.0.0:") + port;
    evpp::EventLoop loop;
    evpp::TCPServer server(&loop, addr, "TCPEcho", 0);
    server.SetMessageCallback(&OnMessage);
    server.SetConnectionCallback(&OnConnection);
    server.Start();
    loop.Run();
    return 0;
}

Add OnConnection callback for echo tcp server


/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * 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 <sys/sysinfo.h>

#include "test/gtest_and_gmock.h"

namespace perfetto {

TEST(PerfettoDeviceFeatureTest, TestMaxCpusForAtraceChmod) {
  // Check that there are no more than 16 CPUs so that the assumption in the
  // atrace.rc for clearing CPU buffers is valid.
  ASSERT_LE(sysconf(_SC_NPROCESSORS_CONF), 16);
}

}  // namespace perfetto

/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * 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 <sys/sysinfo.h>

#include "test/gtest_and_gmock.h"

namespace perfetto {

TEST(PerfettoDeviceFeatureTest, TestMaxCpusForAtraceChmod) {
  // Check that there are no more than 24 CPUs so that the assumption in the
  // atrace.rc for clearing CPU buffers is valid.
  ASSERT_LE(sysconf(_SC_NPROCESSORS_CONF), 24);
}

}  // namespace perfetto

Increase core count for PerfettoDeviceFeatureTest

Increase core count limit for CtsPerfettoTestCases
PerfettoDeviceFeatureTest#TestMaxCpusForAtraceChmod to support
future devices with more cores

Bug: 203651019
Test: atest CtsPerfettoTestCases

Change-Id: I2246d9ef10e553df3f9d12ccde78d8009f3fd7cd
Merged-In: I2246d9ef10e553df3f9d12ccde78d8009f3fd7cd
(cherry picked from commit b4868da668898d53a66087af776b295fea2f2731)


/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Nathan Osman
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include <nitroshare/application.h>

#include "trayplugin.h"

void TrayPlugin::initialize(Application *application)
{
    mIcon = new QSystemTrayIcon;
    mMenu = new QMenu;

    mIcon->setContextMenu(mMenu);

    mMenu->addAction(tr("Quit"), application, &Application::quit);
}

void TrayPlugin::cleanup(Application *)
{
    delete mMenu;
    delete mIcon;
}

/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Nathan Osman
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include <nitroshare/application.h>

#include "trayplugin.h"

void TrayPlugin::initialize(Application *application)
{
    mIcon = new QSystemTrayIcon;
    mMenu = new QMenu;

    mIcon->setContextMenu(mMenu);

    mMenu->addAction(tr("Quit"), application, SLOT(quit()));
}

void TrayPlugin::cleanup(Application *)
{
    delete mMenu;
    delete mIcon;
}

Fix compilation error with Qt 5.4.

Fix compilation error with Qt 5.4.


class MyClass
{
public:
  int memberResult()
  {
    return 1;
  }
  static int staticResult()
  {
    return 1;
  }
  int externResult();
};

// --

int MyClass::externResult()
{
  return 1;
}

// --

MyClass m;

// --

enum MyEnum {
  myEnumOne = 1,
  myEnumTwo,
  myEnumThree
};

// --

class AnotherClass
{
public:
    __attribute__ ((always_inline)) int complicatedFunction()
    {
        struct {
            int i;
        } s = { 15 };

        int as[4] = { 2, 3, 4, 5 };

        for (signed char a : as)
        {
            s.i -= a;
        }

        return s.i;
    }
};

// --

int doTest()
{
    return m.memberResult() + MyClass::staticResult() + m.externResult() + MyEnum::myEnumThree + myEnumOne + AnotherClass().complicatedFunction();
}

// --

class MyClass
{
public:
  int memberResult()
  {
    return 1;
  }
  static int staticResult()
  {
    return 1;
  }
  int externResult();
};

// --

int MyClass::externResult()
{
  return 1;
}

// --

MyClass m;

// --

enum MyEnum {
  myEnumOne = 1,
  myEnumTwo,
  myEnumThree
};

// --

class AnotherClass
{
public:
    __attribute__ ((always_inline)) int complicatedFunction()
    {
        struct {
            int i;
        } s = { 15 };

        int as[4] = { 2, 3, 4, 5 };

        for (signed char a : as)
        {
            s.i -= a;
        }

        return s.i;
    }
};

// --

class DiamondA
{
private:
  struct {
    int m_i;
  };
public:
  DiamondA(int i) : m_i(i) { }
  int accessor() { return m_i; }
};

// --

class DiamondB : public virtual DiamondA
{
public:
  DiamondB(int i) : DiamondA(i) { }
};

// --

class DiamondC : public virtual DiamondA
{
public:
  DiamondC(int i) : DiamondA(i) { }
};

// --

class DiamondD : public DiamondB, public DiamondC
{
public:
  DiamondD(int i) : DiamondA(i), DiamondB(i), DiamondC(i) { }
};

// --

int doTest()
{
    int a = m.memberResult();
    a += MyClass::staticResult();
    a += m.externResult();
    a += MyEnum::myEnumThree;
    a += myEnumOne;
    a += AnotherClass().complicatedFunction();
    a += DiamondD(3).accessor();
    return a;
}

// --

Test diamond virtual inheritance in top-level expressions.

git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@269698 91177308-0d34-0410-b5e6-96231b3b80d8


#include <string.h>
#include "gfx/texture_atlas.h"

const AtlasFont *Atlas::getFontByName(const char *name) const
{
	for (int i = 0; i < num_fonts; i++) {
		if (!strcmp(name, fonts[i]->name))
			return fonts[i];
	}
}

const AtlasImage *Atlas::getImageByName(const char *name) const
{
	for (int i = 0; i < num_images; i++) {
		if (!strcmp(name, images[i].name))
			return &images[i];
	}
}

#include <string.h>
#include "gfx/texture_atlas.h"

const AtlasFont *Atlas::getFontByName(const char *name) const
{
	for (int i = 0; i < num_fonts; i++) {
		if (!strcmp(name, fonts[i]->name))
			return fonts[i];
	}
  return 0;
}

const AtlasImage *Atlas::getImageByName(const char *name) const
{
	for (int i = 0; i < num_images; i++) {
		if (!strcmp(name, images[i].name))
			return &images[i];
	}
  return 0;
}

Return 0 if resource missing

Return 0 if resource missing


#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"

using namespace ci;
using namespace ci::app;
using namespace std;

class EntityCreationApp : public App {
  public:
	void setup() override;
	void mouseDown( MouseEvent event ) override;
	void update() override;
	void draw() override;
};

void EntityCreationApp::setup()
{
}

void EntityCreationApp::mouseDown( MouseEvent event )
{
}

void EntityCreationApp::update()
{
}

void EntityCreationApp::draw()
{
	gl::clear( Color( 0, 0, 0 ) );
}

CINDER_APP( EntityCreationApp, RendererGl )

#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"

#include "entityx/System.h"

using namespace ci;
using namespace ci::app;
using namespace std;

class EntityCreationApp : public App {
public:
	EntityCreationApp();

	void setup() override;
	void mouseDown( MouseEvent event ) override;
	void update() override;
	void draw() override;
private:
	entityx::EventManager	 events;
	entityx::EntityManager entities;
	entityx::SystemManager systems;
};

EntityCreationApp::EntityCreationApp()
: entities(events),
	systems(entities, events)
{}

void EntityCreationApp::setup()
{

}

void EntityCreationApp::mouseDown( MouseEvent event )
{
}

void EntityCreationApp::update()
{
}

void EntityCreationApp::draw()
{
	gl::clear( Color( 0, 0, 0 ) );
}

CINDER_APP( EntityCreationApp, RendererGl )

Add stub entityx classes to sample.

Add stub entityx classes to sample.


#include <stdio.h>
#include "interface.h"

void printHelp()
{
	printf("Usage: yabs [options]\n\n"
	       "yabs, a simple build system.\n"
	       "Options:\n"
	       "\t-new\tCreate a new yabs build file\n"
	       "\t-help\tPrint this dialog\n");
}

#include <stdio.h>
#include "interface.h"

void printHelp()
{
	printf("Usage: yabs [options]\n\n"
	       "yabs, a simple build system.\n"
	       "Options:\n"
	       "\t-n\tCreate a new yabs build file\n"
	       "\t-h\tPrint this dialog\n");
}

Fix help print to reflect parameter changes

Signed-off-by: Alberto Corona <c1a4158909d6c23f73df353c7cc0bbe963891a65@0x1a.us>


#include "FlareScalingRule.h"

float UFlareScalingRule::GetDPIScaleBasedOnSize(FIntPoint Size) const
{
	float NominalAspectRatio = (16.0f / 9.0f);

	// Wide screen : scale 1 at 1920, scale 2 at 3840...
	if (Size.X / Size.Y > NominalAspectRatio)
	{
		return (Size.Y / 1080.0f);
	}

	// Square ratio : scale 1 at 1080p
	else
	{
		return (Size.X / 1920.0f);
	}
}

#include "FlareScalingRule.h"

float UFlareScalingRule::GetDPIScaleBasedOnSize(FIntPoint Size) const
{
	float NominalAspectRatio = (16.0f / 9.0f);

	// Loading game
	if (Size.X == 0 || Size.Y == 0)
	{
		return 1;
	}

	// Wide screen : scale 1 at 1920, scale 2 at 3840...
	else if (Size.X / Size.Y > NominalAspectRatio)
	{
		return (Size.Y / 1080.0f);
	}

	// Square ratio : scale 1 at 1080p
	else
	{
		return (Size.X / 1920.0f);
	}
}

Fix crash when loading UE editor with custom UI scaling


// Copyright 2013 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/android/important_file_writer_android.h"

#include <string>

#include "base/android/jni_string.h"
#include "base/files/important_file_writer.h"
#include "jni/ImportantFileWriterAndroid_jni.h"

namespace base {
namespace android {

static jboolean WriteFileAtomically(JNIEnv* env,
                                    jclass /* clazz */,
                                    jstring file_name,
                                    jbyteArray data) {
  std::string native_file_name;
  base::android::ConvertJavaStringToUTF8(env, file_name, &native_file_name);
  base::FilePath path(native_file_name);
  int data_length = env->GetArrayLength(data);
  jbyte* native_data = env->GetByteArrayElements(data, NULL);
  std::string native_data_string(reinterpret_cast<char *>(native_data),
                                 data_length);
  bool result = base::ImportantFileWriter::WriteFileAtomically(
      path, native_data_string);
  env->ReleaseByteArrayElements(data, native_data, JNI_ABORT);
  return result;
}

bool RegisterImportantFileWriterAndroid(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

}  // namespace android
}  // namespace base

// Copyright 2013 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/android/important_file_writer_android.h"

#include <string>

#include "base/android/jni_string.h"
#include "base/files/important_file_writer.h"
#include "base/threading/thread_restrictions.h"
#include "jni/ImportantFileWriterAndroid_jni.h"

namespace base {
namespace android {

static jboolean WriteFileAtomically(JNIEnv* env,
                                    jclass /* clazz */,
                                    jstring file_name,
                                    jbyteArray data) {
  // This is called on the UI thread during shutdown to save tab data, so
  // needs to enable IO.
  base::ThreadRestrictions::ScopedAllowIO();
  std::string native_file_name;
  base::android::ConvertJavaStringToUTF8(env, file_name, &native_file_name);
  base::FilePath path(native_file_name);
  int data_length = env->GetArrayLength(data);
  jbyte* native_data = env->GetByteArrayElements(data, NULL);
  std::string native_data_string(reinterpret_cast<char *>(native_data),
                                 data_length);
  bool result = base::ImportantFileWriter::WriteFileAtomically(
      path, native_data_string);
  env->ReleaseByteArrayElements(data, native_data, JNI_ABORT);
  return result;
}

bool RegisterImportantFileWriterAndroid(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

}  // namespace android
}  // namespace base

Allow atomic file writes from Android on the UI thread.

This is needed because Android writes its tab data during closedown or
when the browser goes into the background. This has to be done on
the UI thread to ensure timely completion.

BUG=148011

Review URL: https://codereview.chromium.org/12457007
Patch from Anthony Berent <aberent@chromium.org>.

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@186392 0039d316-1c4b-4281-b951-d872f2087c98


//===-- sanitizer_common_nolibc.cc ----------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains stubs for libc function to facilitate optional use of
// libc in no-libcdep sources.
//===----------------------------------------------------------------------===//

#include "sanitizer_platform.h"
#include "sanitizer_common.h"

namespace __sanitizer {

void WriteToSyslog(const char *buffer) {}

}

//===-- sanitizer_common_nolibc.cc ----------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains stubs for libc function to facilitate optional use of
// libc in no-libcdep sources.
//===----------------------------------------------------------------------===//

#include "sanitizer_platform.h"
#include "sanitizer_common.h"

namespace __sanitizer {

#if SANITIZER_LINUX
void WriteToSyslog(const char *buffer) {}
#endif

}

Fix double definition of a function.

[sanitizer] Fix double definition of a function.

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@243055 91177308-0d34-0410-b5e6-96231b3b80d8


#include <cstdio>
#include <cstdlib>
#include <fcntl.h>
#include <unistd.h>
#include "touchscreen.h"

int main()
{
    touchscreen_init();

    while(1) {
	int x, y;
	float z;

        TouchscreenEvent e;
	while((e = touchscreen_read(&x, &y, &z)) != TOUCHSCREEN_IDLE) {
	    switch(e) {
		case TOUCHSCREEN_START:
		    printf("start %d %d %f\n", x, y, z);
		    break;
		case TOUCHSCREEN_DRAG:
		    printf("drag %d %d %f\n", x, y, z);
		    break;
		case TOUCHSCREEN_STOP:
		    printf("stop\n");
		    break;
		case TOUCHSCREEN_IDLE:
		default:
		    break;
	    }
	}

	// usleep(100000);
    }
}

#include <cstdio>
#include <cstdlib>
#include <fcntl.h>
#include <unistd.h>
#include "touchscreen.h"

int main()
{
    touchscreen_init();

    while(1) {
	static bool dragging = false;
	int x, y;
	float z;

        TouchscreenEvent e;
	while((e = touchscreen_read(&x, &y, &z)) != TOUCHSCREEN_IDLE) {
	    switch(e) {
		case TOUCHSCREEN_START:
		    printf("start %d %d %f\n", x, y, z);
		    if(dragging)
			printf("ERROR: START WHILE ALREADY DRAGGING\n");
		    dragging = true;
		    break;
		case TOUCHSCREEN_DRAG:
		    printf("drag %d %d %f\n", x, y, z);
		    if(!dragging)
			printf("ERROR: DRAG WHILE NOT STARTED\n");
		    break;
		case TOUCHSCREEN_STOP:
		    printf("stop\n");
		    if(!dragging)
			printf("ERROR: STOP WHILE NOT STARTED\n");
		    dragging = false;
		    break;
		case TOUCHSCREEN_IDLE:
		default:
		    break;
	    }
	}

	// usleep(100000);
    }
}

Add ERROR prints on unexpected conditions


// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Justin Madsen
// =============================================================================
//
// Base class for a vehicle wheel.
// A wheel subsystem does not own a body. Instead, when attached to a suspension
// subsystem, the wheel's mass properties are used to update those of the
// spindle body owned by the suspension.
// A concrete wheel subsystem can optionally carry its own visualization assets
// and/or contact geometry (which are associated with the suspension's spindle
// body).
// =============================================================================

namespace chrono {

}  // end namespace chrono

Add missing comment block at top of file.


/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow/core/platform/resource_loader.h"

#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {

const char kDataDependencyPath[] = "tensorflow/core/platform/resource_loader.h";

TEST(ResourceLoaderTest, FindsAndOpensFile) {
  string filepath = GetDataDependencyFilepath(kDataDependencyPath);
  Status s = Env::Default()->FileExists(filepath);
  EXPECT_TRUE(s.ok()) << "No file found at this location: " << filepath;
}

}  // namespace tensorflow

/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow/core/platform/resource_loader.h"

#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/path.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace {

string DataDependencyPath() {
  return io::JoinPath("tensorflow", "core", "platform", "resource_loader.h");
}

TEST(ResourceLoaderTest, FindsAndOpensFile) {
  string filepath = GetDataDependencyFilepath(DataDependencyPath());
  Status s = Env::Default()->FileExists(filepath);
  EXPECT_TRUE(s.ok()) << "No file found at this location: " << filepath;
}

}  // namespace
}  // namespace tensorflow

Use JoinPath over a fixed string for building paths.

The fixed path doesn't work well on Windows when the correct path separator is used.

PiperOrigin-RevId: 296095586
Change-Id: I9fe0459ef58a310bf471cf2548b3f7e23b764502