/*
 *
 * Copyright 2019 Asylo authors
 *
 * 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 <unistd.h>

namespace asylo {

extern "C" {

int __asylo_handle_signal(const char *input, size_t input_len) {
  return 0;
}

int __asylo_take_snapshot(char **output, size_t *output_len) {
  return 0;
}

int __asylo_restore(const char *snapshot_layout, size_t snapshot_layout_len,
                    char **output, size_t *output_len) {
  return 0;
}

int __asylo_transfer_secure_snapshot_key(const char *input, size_t input_len,
                                         char **output, size_t *output_len) {
  return 0;
}

}  // extern "C"

}  // namespace asylo

/*
 *
 * Copyright 2019 Asylo authors
 *
 * 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 <unistd.h>

namespace asylo {

extern "C" {

int __asylo_take_snapshot(char **output, size_t *output_len) {
  return 0;
}

int __asylo_restore(const char *snapshot_layout, size_t snapshot_layout_len,
                    char **output, size_t *output_len) {
  return 0;
}

int __asylo_transfer_secure_snapshot_key(const char *input, size_t input_len,
                                         char **output, size_t *output_len) {
  return 0;
}

}  // extern "C"

}  // namespace asylo

Revert dummy handle signal definition

Revert dummy handle signal definition

Revert entry point definitions which have been migrated to
trusted application

PiperOrigin-RevId: 260610866
Change-Id: I8613155a78aecff97c1ceec493037648c5a09722


#include "stdafx.h"
#include "CppUnitTest.h"
#include "../DNAnalyzerServer/Dictionnaire.h"
#include <exception>
#include <cstring>

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace DNAnalyzerServerTest
{
	TEST_CLASS(DictionnaireTest)
	{
	public:
		//ObtenirInstance
		TEST_METHOD(ObtenirInstance_NotNull)
		{
			// L'instance retourne ne doit pas tre null
			Assert::IsTrue(&(Dictionnaire::ObtenirInstance())!=(Dictionnaire*) nullptr);
		}

		TEST_METHOD(ObtenirInstance_SameReference)
		{
			// L'instance retourne doit toujours tre la mme
			Assert::IsTrue(&(Dictionnaire::ObtenirInstance()) == &(Dictionnaire::ObtenirInstance()));
		}
	};
}

#include "stdafx.h"
#include "CppUnitTest.h"
#include "../DNAnalyzerServer/Dictionnaire.h"
#include "../DNAnalyzerServer/Mots.h"
#include <exception>
#include <unordered_set>
#include <cstring>
#include <string>

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace DNAnalyzerServerTest
{
	TEST_CLASS(DictionnaireTest)
	{
	public:
		//ObtenirInstance
		TEST_METHOD(ObtenirInstance_NotNull)
		{
			// L'instance retourne ne doit pas tre null
			Assert::IsTrue(&(Dictionnaire::ObtenirInstance())!=(Dictionnaire*) nullptr);
		}

		TEST_METHOD(ObtenirInstance_SameReference)
		{
			// L'instance retourne doit toujours tre la mme
			Assert::IsTrue(&(Dictionnaire::ObtenirInstance()) == &(Dictionnaire::ObtenirInstance()));
		}
		TEST_METHOD(ObtenirMaladie_KnownMaladie) {

		}
		TEST_METHOD(ObtenirMaladie_UnKnownMaladie) {

		}
		TEST_METHOD(ObtenirMaladies_NoMaladies) {
			char motInexistant[] = "ATCGINEXISTANT";
			unsigned int indexMotInexistant = Mots::ObtenirInstance().InsererMot(motInexistant);
			const unordered_set<const Maladie*> resutat = Dictionnaire::ObtenirInstance().ObtenirMaladies(indexMotInexistant);
			Assert::AreEqual(resutat.size, 0);
		}
		TEST_METHOD(ObtenirMaladies_OneMaladies) {

		}
		TEST_METHOD(ObtenirMaladies_TwoMaladies) {

		}
		TEST_METHOD(ObtenirNomMaladies_EmptyDictionnaire) {

		}
		TEST_METHOD(ObtenirNomMaladies_NotEmptyDictionnaire) {

		}
	};
}

Revert "Revert "Ajout de methode de test (incomplete) de Dictionnaire""

This reverts commit c0a5540b2f83139a18d18956eb7a59f5d78692ee.


#include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <scxcorelib/scxstrencodingconv.h>
#include "getusername.h"

TEST(GetUserName,simple)
{
	// allocate a WCHAR_T buffer to receive username
	DWORD lpnSize = L_cuserid;
	WCHAR_T lpBuffer[lpnSize];

	BOOL result = GetUserName(lpBuffer, &lpnSize);

	// GetUserName returns 1 on success
	ASSERT_EQ(1, result);

	// get expected username
	std::string username(getlogin());

	// GetUserName sets lpnSize to length of username including null
	ASSERT_EQ(username.size()+1, lpnSize);

	// copy UTF-16 bytes (excluding null) from lpBuffer to vector for conversion
	unsigned char *begin = reinterpret_cast<unsigned char *>(&lpBuffer[0]);
	// -1 to skip null; *2 because UTF-16 encodes two bytes per character
	unsigned char *end = begin + (lpnSize-1)*2;
	std::vector<unsigned char> input(begin, end);
	// convert to UTF-8 for assertion
	std::string output;
	SCXCoreLib::Utf16leToUtf8(input, output);

	EXPECT_EQ(username, output);
}

#include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <scxcorelib/scxstrencodingconv.h>
#include "getusername.h"

class GetUserNameTest : public ::testing::Test {
protected:
	DWORD lpnSize;
	std::vector<WCHAR_T> lpBuffer;
	BOOL result;
	std::string userName;

	GetUserNameTest(): userName(std::string(getlogin())) {}

	void GetUserNameWithSize(DWORD size) {
		lpnSize = size;
		// allocate a WCHAR_T buffer to receive username
		lpBuffer.assign(lpnSize, '\0');
		result = GetUserName(&lpBuffer[0], &lpnSize);
	}
};

TEST_F(GetUserNameTest, NormalUse) {
	GetUserNameWithSize(L_cuserid);

	// GetUserName returns 1 on success
	ASSERT_EQ(1, result);

	// GetUserName sets lpnSize to length of username including null
	ASSERT_EQ(userName.size()+1, lpnSize);

	// copy UTF-16 bytes (excluding null) from lpBuffer to vector for conversion
	unsigned char *begin = reinterpret_cast<unsigned char *>(&lpBuffer[0]);
	// -1 to skip null; *2 because UTF-16 encodes two bytes per character
	unsigned char *end = begin + (lpnSize-1)*2;
	std::vector<unsigned char> input(begin, end);
	// convert to UTF-8 for assertion
	std::string output;
	SCXCoreLib::Utf16leToUtf8(input, output);

	EXPECT_EQ(userName, output);
}

Use test fixture in GetUserName unit tests


#include "textfile.ih"

vector<unsigned char> indexedcorpus::readFile(string const &filename)
{
	QFileInfo p(filename.c_str());
	if (p.isFile())
          throw runtime_error(string("readFile: '") + filename + "' is not a regular file!");

	vector<unsigned char> data;

	ifstream dataStream(filename.c_str());
	if (!dataStream)
          throw runtime_error(string("readFile: '") + filename + "' could be read!");

	dataStream >> noskipws;

	copy(istream_iterator<char>(dataStream), istream_iterator<char>(),
		back_inserter(data));

	return data;
}

#include "textfile.ih"

vector<unsigned char> indexedcorpus::readFile(string const &filename)
{
	QFileInfo p(filename.c_str());
	if (!p.isFile())
          throw runtime_error(string("readFile: '") + filename + "' is not a regular file!");

	vector<unsigned char> data;

	ifstream dataStream(filename.c_str());
	if (!dataStream)
          throw runtime_error(string("readFile: '") + filename + "' could be read!");

	dataStream >> noskipws;

	copy(istream_iterator<char>(dataStream), istream_iterator<char>(),
		back_inserter(data));

	return data;
}

Fix a flawed check in indexedcorpus::readFile.


/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

#include "Exceptions.h"

using namespace antlr4;

RuntimeException::RuntimeException(const std::string &msg) : std::exception(), _message(msg) {
}

const char* RuntimeException::what() const NOEXCEPT {
  return _message.c_str();
}

//------------------ IOException ---------------------------------------------------------------------------------------

IOException::IOException(const std::string &msg) : std::exception(), _message(msg) {
}

const char* IOException::what() const NOEXCEPT {
  return _message.c_str();
}

IllegalStateException::~IllegalStateException() = default;
IllegalArgumentException::~IllegalArgumentException() = default;
NullPointerException::~NullPointerException() = default;
IndexOutOfBoundsException::~IndexOutOfBoundsException() = default;
UnsupportedOperationException::~UnsupportedOperationException() = default;
EmptyStackException::~EmptyStackException() = default;
CancellationException::~CancellationException() = default;
ParseCancellationException::~ParseCancellationException() = default;

Change virtual dtor to empty bodies

Convention: Change virtual dtor to empty bodies


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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Popup) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("popup")) << message_;
}

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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

// Flaky, http://crbug.com/46601.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Popup) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("popup")) << message_;
}

Mark ExtensionApiTest.Popup as FLAKY, it is still flaky.

TBR=twiz

BUG=46601
TEST=browser_tests

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

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


/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <memory>

#include "absl/debugging/failure_signal_handler.h"
#include "absl/debugging/symbolize.h"
#include "test/test_main_lib.h"

int main(int argc, char* argv[]) {
  // Initialize the symbolizer to get a human-readable stack trace
  absl::InitializeSymbolizer(argv[0]);

  absl::FailureSignalHandlerOptions options;
  absl::InstallFailureSignalHandler(options);

  std::unique_ptr<webrtc::TestMain> main = webrtc::TestMain::Create();
  int err_code = main->Init(&argc, argv);
  if (err_code != 0) {
    return err_code;
  }
  return main->Run(argc, argv);
}

/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <memory>

#include "absl/debugging/failure_signal_handler.h"
#include "absl/debugging/symbolize.h"
#include "test/test_main_lib.h"

int main(int argc, char* argv[]) {
  // Initialize the symbolizer to get a human-readable stack trace
  // TODO(crbug.com/1050976): Breaks iossim tests, re-enable when fixed.
  // absl::InitializeSymbolizer(argv[0]);

  // absl::FailureSignalHandlerOptions options;
  // absl::InstallFailureSignalHandler(options);

  std::unique_ptr<webrtc::TestMain> main = webrtc::TestMain::Create();
  int err_code = main->Init(&argc, argv);
  if (err_code != 0) {
    return err_code;
  }
  return main->Run(argc, argv);
}

Revert "Re-enable absl FailureSignalHandler in tests."

This reverts commit 46e9629dda1de4315b5106741cc7072b4e01548c.

Reason for revert: Speculative revert.

Original change's description:
> Re-enable absl FailureSignalHandler in tests.
>
> It was not the cause of the SIGSEGV on iossim, so it is fine to
> re-enable it.
>
> TBR: titovartem@webrtc.org
> Bug: None
> Change-Id: I593a010f83f1a0df6b3419dd4f925380210844c9
> Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/175105
> Commit-Queue: Mirko Bonadei <d2c43c210eae6feef04f53bae50885e8152edcca@webrtc.org>
> Reviewed-by: Artem Titov <titovartem@webrtc.org>
> Reviewed-by: Markus Handell <handellm@webrtc.org>
> Cr-Commit-Position: refs/heads/master@{#31277}

TBR=d2c43c210eae6feef04f53bae50885e8152edcca@webrtc.org,titovartem@webrtc.org,handellm@webrtc.org

Change-Id: I5e8456ea2918f740428517ee7eb5c561cb016652
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: None
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/175112
Reviewed-by: Mirko Bonadei <d2c43c210eae6feef04f53bae50885e8152edcca@webrtc.org>
Commit-Queue: Mirko Bonadei <d2c43c210eae6feef04f53bae50885e8152edcca@webrtc.org>
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#31280}


#include "DotGraphOutput.hh"
#include "EdgeType.hh"

string getEdgeStyle(EdgeType t) {
  switch (t) {
  case EdgeType::Plane:
    return "[color=red]";
  case EdgeType::Train:
    return "[color=blue,style=dotted]";
  default:
    return "";
  }
}

template <typename V>
void DotGraphOutput<V>::output(string path) {

  cout << "Exporting " << this->graph_.name() << " to " << path << endl;

  ofstream st(path, ofstream::out);

  st << "digraph " << this->graph_.name() << " {" << endl;

  for (unsigned int i = 0; i < this->graph_.verticesNb(); i++)
    for (auto e : this->graph_.outgoingEdges(i)) {
      st << "\t" << i
	 << " -> " << e->getOtherEnd(i)
	 << " " << getEdgeStyle(e->type())
	 << ";" << endl;
    }

  st << "}" << endl;

  st.close();
}

template class DotGraphOutput<double>;

#include "DotGraphOutput.hh"
#include "EdgeType.hh"

string getEdgeStyle(EdgeType t) {
  switch (t) {
  case EdgeType::Plane:
    return "[color=red]";
  case EdgeType::Train:
    return "[color=blue,style=dotted]";
  default:
    return "";
  }
}

template <typename V>
void DotGraphOutput<V>::output(string path) {

  cout << "Exporting " << this->graph_.name() << " to " << path << endl;

  ofstream st(path, ofstream::out);

  st << "digraph " << this->graph_.name() << " {" << endl;

  for (unsigned int i = 0; i < this->graph_.verticesNb(); i++)
    for (auto e : this->graph_.outgoingEdges(i)) {
      st << "\t" << this->graph_.getVertex(i).name()
	 << " -> " << this->graph_.getVertex(e->getOtherEnd(i)).name()
	 << " " << getEdgeStyle(e->type())
	 << ";" << endl;
    }

  st << "}" << endl;

  st.close();
}

template class DotGraphOutput<double>;

Add the nodes name to the dot output

Add the nodes name to the dot output


#include "cpr/timeout.h"

#include <limits>
#include <stdexcept>
#include <string>
#include <type_traits>

namespace cpr {

long Timeout::Milliseconds() const {
    static_assert(std::is_same<std::chrono::milliseconds, decltype(ms)>::value,
                  "Following casting expects milliseconds.");

    if (ms.count() > std::numeric_limits<long>::max()) {
        throw std::overflow_error("cpr::Timeout: timeout value overflow: " +
                                  std::to_string(ms.count()) + " ms.");
    }
    if (ms.count() < std::numeric_limits<long>::min()) {
        throw std::underflow_error("cpr::Timeout: timeout value underflow: " +
                                   std::to_string(ms.count()) + " ms.");
    }

    return ms.count();
}

} // namespace cpr

#include "cpr/timeout.h"

#include <limits>
#include <stdexcept>
#include <string>
#include <type_traits>

namespace cpr {

long Timeout::Milliseconds() const {
    static_assert(std::is_same<std::chrono::milliseconds, decltype(ms)>::value,
                  "Following casting expects milliseconds.");

    if (ms.count() > std::numeric_limits<long>::max()) {
        throw std::overflow_error("cpr::Timeout: timeout value overflow: " +
                                  std::to_string(ms.count()) + " ms.");
    }
    if (ms.count() < std::numeric_limits<long>::min()) {
        throw std::underflow_error("cpr::Timeout: timeout value underflow: " +
                                   std::to_string(ms.count()) + " ms.");
    }

    return static_cast<long>(ms.count());
}

} // namespace cpr

Revert some casts that are needed.

Revert some casts that are needed.


#include "Log.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <string.h>
#include <iostream>

Log m_globalLog;

Log* Log::instance()
{
	return &m_globalLog;
}

Log::Log()
: m_fd(-1)
{
}

Log::~Log()
{
	close(m_fd);
}

void Log::open(const std::string& path)
{
	m_fd = ::open(path.c_str(),S_IRUSR);
}

void Log::write(Type type, const char* text)
{
	std::cerr << "log " << text << std::endl;
	::write(m_fd,text,strlen(text));
}

#include "Log.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <string.h>
#include <iostream>

Log m_globalLog;

Log* Log::instance()
{
	return &m_globalLog;
}

Log::Log()
: m_fd(-1)
{
}

Log::~Log()
{
	close(m_fd);
}

void Log::open(const std::string& path)
{
	m_fd = ::open(path.c_str(),S_IRUSR);
}

void Log::write(Type type, const char* text)
{
	switch (type)
	{
		case Info:
			std::cerr << "INFO  ";
			break;
		case Warn:
			std::cerr << "WARN  ";
			break;
		case Error:
			std::cerr << "ERROR ";
			break;
	}
	std::cerr << text << std::endl;

	if (m_fd >= 0)
	{
		::write(m_fd,text,strlen(text));
	}
}

Add entry type information at the start of each log file entry.


#include "eval.h"
#include "env.h"

namespace mclisp
{
ConsCell *Eval(const ConsCell *exp, ConsCell *env /* env::g_user_env */)
{
  if (Atom(exp))
    return env::Lookup(env, exp);

  if (Atom(Car(exp)))
  {
    if (Eq(Car(exp), g_builtin_symbols["QUOTE"]))
      return Cadr(exp);

    if (Eq(Car(exp), g_builtin_symbols["ATOM"]))
      return FromBool(Atom(Eval(Cadr(exp), env)));
  }

  return MakeSymbol("42");
}

} // namespace mclisp

#include "eval.h"
#include "env.h"

namespace
{
using namespace mclisp;

ConsCell *Evcon(const ConsCell *clauses, ConsCell *env)
{
  // TODO Might want throw something more descriptive than TypeError.
  TYPECHECK(clauses, Listp);

  if (Null(clauses))
    return kNil;

  TYPECHECK(Car(clauses), Consp);

  if (*Eval(Caar(clauses), env))
    return Eval(Cadar(clauses), env);

  return Evcon(Cdr(clauses), env);
}
} // namespace

namespace mclisp
{
ConsCell *Eval(const ConsCell *exp, ConsCell *env /* env::g_user_env */)
{
#define EQ(exp, sym) Eq(exp, g_builtin_symbols[#sym])

  if (Atom(exp))
    return env::Lookup(env, exp);

  if (Atom(Car(exp)))
  {
    if (EQ(Car(exp), QUOTE))
      return Cadr(exp);

    if (EQ(Car(exp), ATOM))
      return FromBool(Atom(Eval(Cadr(exp), env)));

    if (EQ(Car(exp), EQ))
      return FromBool(Eq(Eval(Cadr(exp), env), Eval(Caddr(exp), env)));

    if (EQ(Car(exp), COND))
      return Evcon(Cdr(exp), env);

    if (EQ(Car(exp), CAR))
      return Car(Eval(Cadr(exp), env));

    if (EQ(Car(exp), CDR))
      return Cdr(Eval(Cadr(exp), env));

    if (EQ(Car(exp), CONS))
      return Cons(Eval(Cadr(exp), env), Eval(Caddr(exp), env));
  }

#undef EQ
  return MakeSymbol("42");
}

} // namespace mclisp

Add EQ, COND, CAR, CDR and CONS to Eval.


#include "localserver.h"

namespace rclog {

LocalServer::LocalServer(boost::asio::io_service &io_service, std::string socket_path)
    :socket_(io_service, datagram_protocol::endpoint(socket_path)) {
    do_receive();
}

void LocalServer::do_receive() {
    socket_.async_receive_from(boost::asio::buffer(data_, max_length), sender_endpoint_,
                               boost::bind(&LocalServer::handle_message, this, _1, _2));
}

void LocalServer::do_send(std::size_t length) {
  std::cout << "EP: " << sender_endpoint_ << std::endl;
  socket_.async_send_to(
      boost::asio::buffer(data_, length), sender_endpoint_,
      [this](boost::system::error_code /*ec*/, std::size_t /*bytes_sent*/) {
        do_receive();
  });
}

void LocalServer::handle_message(boost::system::error_code ec, std::size_t bytes_recvd)
{
    if (!ec && bytes_recvd > 0) {
        std::cout << "Got: '";
        std::cout.write(data_, bytes_recvd);
        std::cout << "'" << std::endl;
        do_send(bytes_recvd);
    }
    else
        do_receive();
}

}

#include "localserver.h"

namespace rclog {

LocalServer::LocalServer(boost::asio::io_service &io_service, std::string socket_path)
    :socket_(io_service, datagram_protocol::endpoint(socket_path)) {
    do_receive();
}

void LocalServer::do_receive() {
    socket_.async_receive_from(boost::asio::buffer(data_, max_length), sender_endpoint_,
                               boost::bind(&LocalServer::handle_message, this, _1, _2));
}

void LocalServer::do_send(std::size_t length) {
  std::cout << "EP: " << sender_endpoint_ << std::endl;
  socket_.async_send_to(
      boost::asio::buffer(data_, length), sender_endpoint_,
      [this](boost::system::error_code /*ec*/, std::size_t /*bytes_sent*/) {
        do_receive();
  });
}

void LocalServer::handle_message(boost::system::error_code ec, std::size_t bytes_recvd)
{
    if (!ec && bytes_recvd > 0) {
        std::cout << "Got: '";
        std::cout.write(data_, bytes_recvd);
        std::cout << "'" << std::endl;
        do_send(bytes_recvd);
        return;
    }

    if (ec == boost::asio::error::message_size)
        std::cerr << "Error: got message greater then buffer size";    // TODO: send error

    do_receive();
}

}

Add message_size error handle to rclogd

Add message_size error handle to rclogd


#include "gamescene.h"

void GameScene::append_gameItem(QDeclarativeListProperty<GameItem> *list, GameItem *gameItem)
{
    GameScene *scene = qobject_cast<GameScene *>(list->object);
    if (scene) {
        gameItem->setParentItem(scene);
        scene->m_gameItems.append(gameItem);
    }
}

GameScene::GameScene(QQuickItem *parent)
    : QQuickItem(parent)
{
}

QDeclarativeListProperty<GameItem> GameScene::gameItems()
{
    return QDeclarativeListProperty<GameItem>(this, 0, &GameScene::append_gameItem);
}

void GameScene::update(long delta)
{
    if (!m_running) // TODO: stop Qt animations as well
        return;

    GameItem *item;

    foreach (item, m_gameItems)
        item->update(delta);
}

bool GameScene::running() const
{
    return m_running;
}

void GameScene::setRunning(bool running)
{
    m_running = running;

    emit runningChanged();
}

#include "gamescene.h"

void GameScene::append_gameItem(QDeclarativeListProperty<GameItem> *list, GameItem *gameItem)
{
    GameScene *scene = qobject_cast<GameScene *>(list->object);
    if (scene) {
        gameItem->setParentItem(scene);
        scene->m_gameItems.append(gameItem);
    }
}

GameScene::GameScene(QQuickItem *parent)
    : QQuickItem(parent)
    , m_running(true)
{
}

QDeclarativeListProperty<GameItem> GameScene::gameItems()
{
    return QDeclarativeListProperty<GameItem>(this, 0, &GameScene::append_gameItem);
}

void GameScene::update(long delta)
{
    if (!m_running) // TODO: stop Qt animations as well
        return;

    GameItem *item;

    foreach (item, m_gameItems)
        item->update(delta);
}

bool GameScene::running() const
{
    return m_running;
}

void GameScene::setRunning(bool running)
{
    m_running = running;

    emit runningChanged();
}

Change default running state to true

Change default running state to true


#include <stan/math/prim/scal.hpp>
#include <gtest/gtest.h>
#include <limits>

TEST(MathFunctions, is_nan) {
  using stan::math::is_nan;
  double infinity = std::numeric_limits<double>::infinity();
  double nan = std::numeric_limits<double>::quiet_NaN();
  double min = std::numeric_limits<double>::min();
  double max = std::numeric_limits<double>::max();
  EXPECT_TRUE(stan::math::is_nan(nan));
  EXPECT_FALSE(stan::math::is_nan(infinity));
  EXPECT_FALSE(stan::math::is_nan(0));
  EXPECT_FALSE(stan::math::is_nan(1));
  EXPECT_FALSE(stan::math::is_nan(min));
  EXPECT_FALSE(stan::math::is_nan(max));
}

#include <stan/math/prim/scal.hpp>
#include <gtest/gtest.h>
#include <limits>

TEST(MathFunctions, is_nan) {
  using stan::math::is_nan;
  double infinity = std::numeric_limits<double>::infinity();
  double nan = std::numeric_limits<double>::quiet_NaN();
  double min = std::numeric_limits<double>::min();
  double max = std::numeric_limits<double>::max();
  EXPECT_TRUE(is_nan(nan));
  EXPECT_FALSE(is_nan(infinity));
  EXPECT_FALSE(is_nan(0));
  EXPECT_FALSE(is_nan(1));
  EXPECT_FALSE(is_nan(min));
  EXPECT_FALSE(is_nan(max));
}

TEST(MathFunctions, is_nan_variadic) {
  using stan::math::is_nan;
  double infinity = std::numeric_limits<double>::infinity();
  double nan = std::numeric_limits<double>::quiet_NaN();
  double min = std::numeric_limits<double>::min();
  double max = std::numeric_limits<double>::max();

  EXPECT_TRUE(is_nan(nan, infinity, 1.0));
  EXPECT_TRUE(is_nan(max, infinity, nan, 2.0, 5.0));
  EXPECT_TRUE(is_nan(max, min, nan));
  EXPECT_FALSE(is_nan(1.0, 2.0, 20.0, 1, 2));
}

Add tests for variadic calls

Add tests for variadic calls


//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "mtac/Loop.hpp"
#include "mtac/basic_block.hpp"

using namespace eddic;

mtac::Loop::Loop(const std::set<mtac::basic_block_p>& blocks) : m_blocks(blocks) {
    //Nothing
}

mtac::Loop::iterator mtac::Loop::begin(){
    return m_blocks.begin();
}

mtac::Loop::iterator mtac::Loop::end(){
    return m_blocks.begin();
}

int mtac::Loop::estimate(){
    return m_estimate;
}

void mtac::Loop::set_estimate(int estimate){
    this->m_estimate = estimate;
}

mtac::Loop::iterator mtac::begin(std::shared_ptr<mtac::Loop> loop){
    return loop->end();
}

mtac::Loop::iterator mtac::end(std::shared_ptr<mtac::Loop> loop){
    return loop->begin();
}

std::set<mtac::basic_block_p>& mtac::Loop::blocks(){
    return m_blocks;
}

//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "mtac/Loop.hpp"
#include "mtac/basic_block.hpp"

using namespace eddic;

mtac::Loop::Loop(const std::set<mtac::basic_block_p>& blocks) : m_blocks(blocks) {
    //Nothing
}

mtac::Loop::iterator mtac::Loop::begin(){
    return m_blocks.begin();
}

mtac::Loop::iterator mtac::Loop::end(){
    return m_blocks.end();
}

int mtac::Loop::estimate(){
    return m_estimate;
}

void mtac::Loop::set_estimate(int estimate){
    this->m_estimate = estimate;
}

mtac::Loop::iterator mtac::begin(std::shared_ptr<mtac::Loop> loop){
    return loop->begin();
}

mtac::Loop::iterator mtac::end(std::shared_ptr<mtac::Loop> loop){
    return loop->end();
}

std::set<mtac::basic_block_p>& mtac::Loop::blocks(){
    return m_blocks;
}

Fix iteration through loop bb

Fix iteration through loop bb


#include <turbodbc/time_helpers.h>

#include <sql.h>

#include <boost/date_time/gregorian/gregorian_types.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>

namespace turbodbc {

    boost::posix_time::ptime const timestamp_epoch({1970, 1, 1}, {0, 0, 0, 0});

    int64_t timestamp_to_microseconds(char const * data_pointer)
    {
        auto & sql_ts = *reinterpret_cast<SQL_TIMESTAMP_STRUCT const *>(data_pointer);
        intptr_t const microseconds = sql_ts.fraction / 1000;
        boost::posix_time::ptime const ts({static_cast<unsigned short>(sql_ts.year), sql_ts.month, sql_ts.day},
                {sql_ts.hour, sql_ts.minute, sql_ts.second, microseconds});
        return (ts - timestamp_epoch).total_microseconds();
    }

    boost::gregorian::date const date_epoch(1970, 1, 1);

    intptr_t date_to_days(char const * data_pointer)
    {
        auto & sql_date = *reinterpret_cast<SQL_DATE_STRUCT const *>(data_pointer);
        boost::gregorian::date const date(sql_date.year, sql_date.month, sql_date.day);
        return (date - date_epoch).days();
    }

}

#include <turbodbc/time_helpers.h>

#ifdef _WIN32
#include <windows.h>
#endif
#include <cstring>
#include <sql.h>

#include <boost/date_time/gregorian/gregorian_types.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>

namespace turbodbc {

    boost::posix_time::ptime const timestamp_epoch({1970, 1, 1}, {0, 0, 0, 0});

    int64_t timestamp_to_microseconds(char const * data_pointer)
    {
        auto & sql_ts = *reinterpret_cast<SQL_TIMESTAMP_STRUCT const *>(data_pointer);
        intptr_t const microseconds = sql_ts.fraction / 1000;
        boost::posix_time::ptime const ts({static_cast<unsigned short>(sql_ts.year), sql_ts.month, sql_ts.day},
                {sql_ts.hour, sql_ts.minute, sql_ts.second, microseconds});
        return (ts - timestamp_epoch).total_microseconds();
    }

    boost::gregorian::date const date_epoch(1970, 1, 1);

    intptr_t date_to_days(char const * data_pointer)
    {
        auto & sql_date = *reinterpret_cast<SQL_DATE_STRUCT const *>(data_pointer);
        boost::gregorian::date const date(sql_date.year, sql_date.month, sql_date.day);
        return (date - date_epoch).days();
    }

}

Add missing includes for Windows

Add missing includes for Windows


#include "../include/parlex/detail/abstract_syntax_tree.hpp"

#include "graphviz_dot.hpp"

#include "parlex/builder.hpp"
#include "parlex/detail/grammar.hpp"

parlex::detail::ast_node::ast_node(match const & m, std::vector<ast_node> const & children, leaf const * l) : match(m), children(children), l(l) {}

std::string parlex::detail::ast_node::to_dot(grammar const & g) const
{
	auto const nameFunc = [&](ast_node const * n)
	{
		std::stringstream result;
		result << g.get_recognizer(uint16_t(n->l->recognizer_index)).name << " (" << n << ")";
		return result.str();
	};
	auto const edgeFunc = [&](ast_node const * n) {
		std::vector<std::pair<std::string, ast_node const *>> results;
		for (auto i = n->children.begin(); i != n->children.end(); ++i) {
			results.emplace_back("label=" + enquote(std::to_string(i - n->children.begin() + 1)), &*i);
		}
		return results;
	};
	auto const propFunc = [&](ast_node const * n) { return std::string(); };
	return directed_graph<ast_node const *>(this, nameFunc, edgeFunc, propFunc);
}

#include "../include/parlex/detail/abstract_syntax_tree.hpp"

#include "graphviz_dot.hpp"

#include "parlex/builder.hpp"
#include "parlex/detail/grammar.hpp"

parlex::detail::ast_node::ast_node(match const & m, std::vector<ast_node> const & children, leaf const * l) : match(m), children(children), l(l) {}

std::string parlex::detail::ast_node::to_dot(grammar const & g) const
{
	auto const nameFunc = [&](ast_node const * n)
	{
		std::stringstream result;
		result << g.get_recognizer(n->recognizer_index).name << " (" + std::to_string(n->document_position + 1) + " - " + std::to_string(n->consumed_character_count + n->document_position) + ")";
		return result.str();
	};
	auto const edgeFunc = [&](ast_node const * n) {
		std::vector<std::pair<std::string, ast_node const *>> results;
		for (auto i = n->children.begin(); i != n->children.end(); ++i) {
			results.emplace_back("label=" + enquote(std::to_string(i - n->children.begin() + 1)), &*i);
		}
		return results;
	};
	auto const propFunc = [&](ast_node const * n) { return std::string(); };
	return directed_graph<ast_node const *>(this, nameFunc, edgeFunc, propFunc);
}

Make the output of ast_node::to_dot give friendlier node names.


#include <iostream>
#include <QtConcurrent>
#include <QCoreApplication>
#include <stdint.h>
#include <pulse/simple.h>

#include "DBMeter.hpp"

using namespace std;

DBMeter::DBMeter()
{
	settings.setCodec("audio/PCM");
	settings.setChannelCount(1);
	settings.setSampleRate(16000);

	recorder = new QAudioRecorder(this);
	recorder->setAudioInput("pulseaudio:");
	recorder->setAudioSettings(settings);

	QUrl url = QString("/dev/null");
	recorder->setOutputLocation(url);

	probe = new QAudioProbe(this);
	connect(probe, SIGNAL(audioBufferProbed(QAudioBuffer)), this, SLOT(AudioCb(QAudioBuffer)));
	probe->setSource(recorder);
}

DBMeter::~DBMeter()
{
	delete recorder;
}

void DBMeter::Start()
{
	recorder->record();
}

void DBMeter::Stop()
{
	recorder->stop();
}

void DBMeter::AudioCb(const QAudioBuffer &buffer)
{
	const int16_t *ptr = buffer.constData<int16_t>();
	uint16_t maxVal = 0, val;
	int nbFrame = buffer.sampleCount();

	while (nbFrame--) {
		val = abs(*ptr++);
		if (val > maxVal) maxVal = val;
	}
	cerr << " maxVal " << maxVal << endl;
}

#include <iostream>
#include <QtConcurrent>
#include <QCoreApplication>
#include <stdint.h>

#include "DBMeter.hpp"

using namespace std;

DBMeter::DBMeter()
{
	settings.setCodec("audio/PCM");
	settings.setChannelCount(1);
	settings.setSampleRate(16000);

	recorder = new QAudioRecorder(this);
	recorder->setAudioInput("pulseaudio:");
	recorder->setAudioSettings(settings);

	QUrl url = QString("/dev/null");
	recorder->setOutputLocation(url);

	probe = new QAudioProbe(this);
	connect(probe, SIGNAL(audioBufferProbed(QAudioBuffer)), this, SLOT(AudioCb(QAudioBuffer)));
	probe->setSource(recorder);
}

DBMeter::~DBMeter()
{
	delete recorder;
}

void DBMeter::Start()
{
	recorder->record();
}

void DBMeter::Stop()
{
	recorder->stop();
}

void DBMeter::AudioCb(const QAudioBuffer &buffer)
{
	const int16_t *ptr = buffer.constData<int16_t>();
	uint16_t maxVal = 0, val;
	int nbFrame = buffer.sampleCount();

	while (nbFrame--) {
		val = abs(*ptr++);
		if (val > maxVal) maxVal = val;
	}
	cerr << " maxVal " << maxVal << endl;
}

Remove an include not needed

Remove an include not needed


// Copyright 2016 Zheng Xian Qiu

#include "Seeker.h"

namespace Seeker {

  vector<ISubscriber*> Event::subscribers;

  void Event::Refresh() {
    SDL_Event ev;
    while(SDL_PollEvent(&ev)) {
      switch(ev.type) {
        case SDL_KEYDOWN:
          Dispatch(EventType::Key);
          break;
        case SDL_QUIT:
          Dispatch(EventType::Quit);
          break;
        case SDL_MOUSEBUTTONDOWN:
          Dispatch(EventType::Mouse);
          break;
      }
    }
  }

  void Event::On(ISubscriber* event) {
    if(Exists(event)) return;
    subscribers.push_back(event);
  }

  void Event::Off(ISubscriber* event) {
    if(Exists(event)) {
      subscribers.erase(std::remove(subscribers.begin(), subscribers.end(), event), subscribers.end());
    }
  }

  bool Event::Exists(ISubscriber* event) {
    for(auto &current : subscribers) {
      if(current == event) {
        return true;
      }
    }
    return false;
  }

  void Event::Dispatch(const EventType type) {
    for(auto &current : subscribers) {
      current->OnEvent(type);
    }
  }
}

// Copyright 2016 Zheng Xian Qiu

#include "Seeker.h"

#include<algorithm> // Prevent use C++17 std::remove

namespace Seeker {

  vector<ISubscriber*> Event::subscribers;

  void Event::Refresh() {
    SDL_Event ev;
    while(SDL_PollEvent(&ev)) {
      switch(ev.type) {
        case SDL_KEYDOWN:
          Dispatch(EventType::Key);
          break;
        case SDL_QUIT:
          Dispatch(EventType::Quit);
          break;
        case SDL_MOUSEBUTTONDOWN:
          Dispatch(EventType::Mouse);
          break;
      }
    }
  }

  void Event::On(ISubscriber* event) {
    if(Exists(event)) return;
    subscribers.push_back(event);
  }

  void Event::Off(ISubscriber* event) {
    if(Exists(event)) {
      subscribers.erase(std::remove(subscribers.begin(), subscribers.end(), event), subscribers.end());
    }
  }

  bool Event::Exists(ISubscriber* event) {
    for(auto &current : subscribers) {
      if(current == event) {
        return true;
      }
    }
    return false;
  }

  void Event::Dispatch(const EventType type) {
    for(auto &current : subscribers) {
      current->OnEvent(type);
    }
  }
}

Fix compiler use wrong version std::remove


/*
 * This program 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.
 *
 * Written (W) 2012 Chiyuan Zhang
 * Copyright (C) 2012 Chiyuan Zhang
 */

#include <shogun/multiclass/ecoc/ECOCOVOEncoder.h>

using namespace shogun;

SGMatrix<int32_t> CECOCOVOEncoder::create_codebook(int32_t num_classes)
{
    SGMatrix<int32_t> code_book(num_classes*(num_classes-1)/2, num_classes, true);
    code_book.zero();
    int32_t k=0;
    for (int32_t i=0; i < num_classes; ++i)
    {
        for (int32_t j=0; j < num_classes; ++j)
        {
            code_book(k, i) = 1;
            code_book(k, j) = -1;
            k++;
        }
    }

    return code_book;
}

/*
 * This program 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.
 *
 * Written (W) 2012 Chiyuan Zhang
 * Copyright (C) 2012 Chiyuan Zhang
 */

#include <shogun/multiclass/ecoc/ECOCOVOEncoder.h>

using namespace shogun;

SGMatrix<int32_t> CECOCOVOEncoder::create_codebook(int32_t num_classes)
{
    SGMatrix<int32_t> code_book(num_classes*(num_classes-1)/2, num_classes, true);
    code_book.zero();
    int32_t k=0;
    for (int32_t i=0; i < num_classes; ++i)
    {
        for (int32_t j=i+1; j < num_classes; ++j)
        {
            code_book(k, i) = 1;
            code_book(k, j) = -1;
            k++;
        }
    }

    return code_book;
}

Fix bug in ECOC OvO encoder

Fix bug in ECOC OvO encoder


// Standard includes
#include <stdlib.h>

// OpenGL includes
#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include "fluidDynamics.h"

void simulate() {
    // We ping-pong back and forth between two buffers on the GPU
    // u = advect(u);
    // u = diffuse(u);
    // u = addForces(u);
    //
    // p = computePressure(u);
    // u = subtractPressureGradient(u, p);
}

int main(int argc, char** argv) {
    GLFWmonitor* monitor = glfwGetPrimaryMonitor();
    GLFWwindow* window;

    if (!glfwInit()) {
        return -1;
    }

    window = glfwCreateWindow(640, 480, "FlickFlow", monitor, NULL);

    if (!window) {
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);

    while (!glfwWindowShouldClose(window))
    {
        /* Render here */

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
    return EXIT_SUCCESS;
}

// Standard includes
#include <stdlib.h>

// OpenGL includes
#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include "fluidDynamics.h"

#define DEFAULT_WIDTH 640
#define DEFAULT_HEIGHT 480

void simulate() {
    // We ping-pong back and forth between two buffers on the GPU
    // u = advect(u);
    // u = diffuse(u);
    // u = addForces(u);
    //
    // p = computePressure(u);
    // u = subtractPressureGradient(u, p);
}

int main(int argc, char** argv) {
    GLFWmonitor* monitor = glfwGetPrimaryMonitor();
    GLFWwindow* window;

    if (!glfwInit()) {
        return -1;
    }

    window = glfwCreateWindow(DEFAULT_WIDTH, DEFAULT_HEIGHT, "FlickFlow", monitor, NULL);

    if (!window) {
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);
    if (glewInit() != GLEW_OK) {
        return -1;
    }

    printf("%s", glGetString(GL_VERSION));

    loadShaders();

    while (!glfwWindowShouldClose(window))
    {
        /* Render here */

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
    return EXIT_SUCCESS;
}

Call glewInit before trying to load shaders


#include "serialutil.h"
#include "usbutil.h"
#include "listener.h"
#include "signals.h"
#include "log.h"

#define VERSION_CONTROL_COMMAND 0x80
#define RESET_CONTROL_COMMAND 0x81

// USB
#define DATA_ENDPOINT 1

extern void reset();
void setup();
void loop();

const char* VERSION = "2.0-pre";

#ifdef __CHIPKIT__
SerialDevice serialDevice = {&Serial1};
#else
SerialDevice serialDevice;
#endif // __CHIPKIT__

UsbDevice USB_DEVICE = {
#ifdef CHIPKIT
    USBDevice(usbCallback),
#endif // CHIPKIT
    DATA_ENDPOINT,
    MAX_USB_PACKET_SIZE_BYTES};

Listener listener = {&USB_DEVICE, &serialDevice};

int main(void) {
#ifdef CHIPKIT
	init();
#endif
	setup();

	for (;;)
		loop();

	return 0;
}

bool handleControlRequest(uint8_t request) {
    switch(request) {
    case VERSION_CONTROL_COMMAND:
        char combinedVersion[strlen(VERSION) + strlen(getMessageSet()) + 4];
        sprintf(combinedVersion, "%s (%s)", VERSION, getMessageSet());
        debug("Version: %s", combinedVersion);

        sendControlMessage((uint8_t*)combinedVersion, strlen(combinedVersion));
        return true;
    case RESET_CONTROL_COMMAND:
        debug("Resetting...");
        reset();
        return true;
    default:
        return false;
    }
}

#include "serialutil.h"
#include "usbutil.h"
#include "listener.h"
#include "signals.h"
#include "log.h"

#define VERSION_CONTROL_COMMAND 0x80
#define RESET_CONTROL_COMMAND 0x81

// USB
#define DATA_ENDPOINT 1

extern void reset();
void setup();
void loop();

const char* VERSION = "2.0-pre";

#ifdef __CHIPKIT__
SerialDevice serialDevice = {&Serial1};
#else
SerialDevice serialDevice;
#endif // __CHIPKIT__

UsbDevice USB_DEVICE = {
#ifdef CHIPKIT
    USBDevice(usbCallback),
#endif // CHIPKIT
    DATA_ENDPOINT,
    MAX_USB_PACKET_SIZE_BYTES};

Listener listener = {&USB_DEVICE, &serialDevice};

int main(void) {
#ifdef CHIPKIT
	init();
#endif
	setup();

	for (;;)
		loop();

	return 0;
}

bool handleControlRequest(uint8_t request) {
    switch(request) {
    case VERSION_CONTROL_COMMAND:
        char combinedVersion[strlen(VERSION) + strlen(getMessageSet()) + 4];
        sprintf(combinedVersion, "%s (%s)", VERSION, getMessageSet());
        debug("Version: %s\r\n", combinedVersion);

        sendControlMessage((uint8_t*)combinedVersion, strlen(combinedVersion));
        return true;
    case RESET_CONTROL_COMMAND:
        debug("Resetting...\r\n");
        reset();
        return true;
    default:
        return false;
    }
}

Add newlines to control commands.

Add newlines to control commands.


//===-- AVRTargetInfo.cpp - AVR Target Implementation ---------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/IR/Module.h"
#include "llvm/Support/TargetRegistry.h"
namespace llvm {
Target &getTheAVRTarget() {
  static Target TheAVRTarget;
  return TheAVRTarget;
}
}

extern "C" void LLVMInitializeAVRTargetInfo() {
  llvm::RegisterTarget<llvm::Triple::avr> X(llvm::getTheAVRTarget(), "avr",
                                            "Atmel AVR Microcontroller");
}

//===-- AVRTargetInfo.cpp - AVR Target Implementation ---------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/IR/Module.h"
#include "llvm/Support/TargetRegistry.h"
namespace llvm {
Target &getTheAVRTarget() {
  static Target TheAVRTarget;
  return TheAVRTarget;
}
}

extern "C" void LLVMInitializeAVRTargetInfo() {
  llvm::RegisterTarget<llvm::Triple::avr> X(llvm::getTheAVRTarget(), "avr",
                                            "Atmel AVR Microcontroller", "AVR");
}

Add backend name to AVR Target to enable runtime info to be fed back into TableGen

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


#include <SFML\Window.hpp>

int main()
{
	sf::Window window(sf::VideoMode(800, 600), "SFML works!");

	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();
		}

		window.display();
	}

	return 0;
}

#include <SFML\Window.hpp>

int main()
{
	bool fullscreen = false;
	sf::Window window(sf::VideoMode(800, 600), "SFML works!");

	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();

			if (event.type == sf::Event::KeyPressed) {
				if (event.key.code == sf::Keyboard::F) {
					window.close();
					if (fullscreen) {
						window.create(sf::VideoMode(800, 600), "SFML works!");
						fullscreen = false;
					}
					else {
						window.create(sf::VideoMode(800, 600), "SFML works!", sf::Style::Fullscreen);
						fullscreen = true;
					}
				}
				else if (event.key.code == sf::Keyboard::Escape) {
					window.close();
				}
			}
		}

		window.display();
	}

	return 0;
}

ADD fullscreen option for sfml window, press F atm


#include "arithmetics.hpp"
#include "gtest/gtest.h"

TEST(AddTest, PerformsAdditionOnTwoIntegers) {
  EXPECT_EQ(2, arithmetics::add(1, 1));
  EXPECT_EQ(2, arithmetics::add_buggy(1, 1));
}

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

#include "arithmetics.hpp"
#include "gtest/gtest.h"

TEST(TestAdd, PerformsAdditionOnTwoIntegers) {
  EXPECT_EQ(2, arithmetics::add(1, 1));
}

TEST(TestAdd, PerformsAdditionOnTwoIntegers_2) {
  EXPECT_EQ(2, arithmetics::add_buggy(1, 1));
}

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

Split tests into 2 distict tests

Split tests into 2 distict tests


/*
 * Copyright (c) 2015 Cossack Labs Limited
 *
 * 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 <common/sput.h>
#include "secure_cell_test.hpp"
#include "secure_message_test.hpp"
#include "secure_session_test.hpp"

int main(){
  sput_start_testing();
  themispp::secure_cell_test::run_secure_cell_test();
  themispp::secure_message_test::run_secure_message_test();
  themispp::secure_session_test::run_secure_session_test();
  sput_finish_testing();
  return sput_get_return_value();
}

/*
 * Copyright (c) 2015 Cossack Labs Limited
 *
 * 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 <common/sput.h>
#include "secure_cell_test.hpp"
#include "secure_message_test.hpp"
#include "secure_session_test.hpp"
#include "secure_comparator_test.hpp"

int main(){
  sput_start_testing();
  themispp::secure_cell_test::run_secure_cell_test();
  themispp::secure_message_test::run_secure_message_test();
  themispp::secure_session_test::run_secure_session_test();
  themispp::secure_session_test::run_secure_comparator_test();
  sput_finish_testing();
  return sput_get_return_value();
}

Add secure comparator C++ wrapper test

Add secure comparator C++ wrapper test


#include "xchainer/python/device.h"

#include <sstream>

#include "xchainer/device.h"

namespace xchainer {

namespace py = pybind11;  // standard convention

void InitXchainerDevice(pybind11::module& m) {
    py::class_<Device>(m, "Device").def("__repr__", [](Device device) {
        std::ostringstream os;
        os << "<Device " << device.name << ">";
        return os.str();
    });

    m.def("get_current_device", []() { return GetCurrentDevice(); });
    m.def("set_current_device", [](const Device& device) { SetCurrentDevice(device); });
    m.def("set_current_device", [](const std::string& name) { SetCurrentDevice(name); });
}

}  // namespace xchainer

#include "xchainer/python/device.h"

#include <sstream>

#include "xchainer/device.h"

namespace xchainer {

namespace py = pybind11;  // standard convention

void InitXchainerDevice(pybind11::module& m) {
    py::class_<Device>(m, "Device")
        .def(py::init(&MakeDevice))
        .def("__eq__", py::overload_cast<const Device&, const Device&>(&operator==))
        .def("__ne__", py::overload_cast<const Device&, const Device&>(&operator!=))
        .def("__repr__",
             [](Device device) {
                 std::ostringstream os;
                 os << "<Device " << device.name << ">";
                 return os.str();
             });

    m.def("get_current_device", []() { return GetCurrentDevice(); });
    m.def("set_current_device", [](const Device& device) { SetCurrentDevice(device); });
    m.def("set_current_device", [](const std::string& name) { SetCurrentDevice(name); });
}

}  // namespace xchainer

Support Python-level Device ctor and comparison


// RUN: clang-cc -fsyntax-only -verify %s

struct add_pointer {
  template<typename T>
  struct apply {
    typedef T* type;
  };
};

struct add_reference {
  template<typename T>
  struct apply {
    typedef T& type; // expected-error{{cannot form a reference to 'void'}}
  };
};

template<typename MetaFun, typename T>
struct apply1 {
  typedef typename MetaFun::template apply<T>::type type; // expected-note{{in instantiation of template class 'struct add_reference::apply<void>' requested here}}
};

int i;
apply1<add_pointer, int>::type ip = &i;
apply1<add_reference, int>::type ir = i;
apply1<add_reference, float>::type fr = i; // expected-error{{non-const lvalue reference to type 'float' cannot be initialized with a value of type 'int'}}

void test() {
  apply1<add_reference, void>::type t; // expected-note{{in instantiation of template class 'struct apply1<struct add_reference, void>' requested here}} \
  // FIXME: expected-error{{unexpected type name 'type': expected expression}}
}

// RUN: clang-cc -fsyntax-only -verify %s

struct add_pointer {
  template<typename T>
  struct apply {
    typedef T* type;
  };
};

struct add_reference {
  template<typename T>
  struct apply {
    typedef T& type; // expected-error{{cannot form a reference to 'void'}}
  };
};

struct bogus {
  struct apply {
    typedef int type;
  };
};

template<typename MetaFun, typename T>
struct apply1 {
  typedef typename MetaFun::template apply<T>::type type; // expected-note{{in instantiation of template class 'struct add_reference::apply<void>' requested here}} \
  // expected-error{{'apply' following the 'template' keyword does not refer to a template}} \
  // FIXME: expected-error{{type 'MetaFun::template apply<int>' cannot be used prior to '::' because it has no members}}
};

int i;
apply1<add_pointer, int>::type ip = &i;
apply1<add_reference, int>::type ir = i;
apply1<add_reference, float>::type fr = i; // expected-error{{non-const lvalue reference to type 'float' cannot be initialized with a value of type 'int'}}

void test() {
  apply1<add_reference, void>::type t; // expected-note{{in instantiation of template class 'struct apply1<struct add_reference, void>' requested here}} \
  // FIXME: expected-error{{unexpected type name 'type': expected expression}}

  apply1<bogus, int>::type t2; // expected-note{{in instantiation of template class 'struct apply1<struct bogus, int>' requested here}} \
  // FIXME: expected-error{{unexpected type name 'type': expected expression}}
}

Improve the dependent nested-name-specifier test a bit

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


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "platform/globals.h"
#if defined(TARGET_OS_FUCHSIA)

#include "bin/crypto.h"

#include <magenta/syscalls.h>

namespace dart {
namespace bin {

bool Crypto::GetRandomBytes(intptr_t count, uint8_t* buffer) {
  intptr_t read = 0;
  while (read < count) {
    const intptr_t remaining = count - read;
    const intptr_t len =
        (MX_CPRNG_DRAW_MAX_LEN < remaining) ? MX_CPRNG_DRAW_MAX_LEN
                                            : remaining;
    const mx_ssize_t res = mx_cprng_draw(buffer + read, len);
    if (res == ERR_INVALID_ARGS) {
      return false;
    }
    read += res;
  }
  return true;
}

}  // namespace bin
}  // namespace dart

#endif  // defined(TARGET_OS_FUCHSIA)

// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "platform/globals.h"
#if defined(TARGET_OS_FUCHSIA)

#include "bin/crypto.h"

#include <magenta/syscalls.h>

namespace dart {
namespace bin {

bool Crypto::GetRandomBytes(intptr_t count, uint8_t* buffer) {
  intptr_t read = 0;
  while (read < count) {
    const intptr_t remaining = count - read;
    const intptr_t len =
        (MX_CPRNG_DRAW_MAX_LEN < remaining) ? MX_CPRNG_DRAW_MAX_LEN
                                            : remaining;
    mx_size_t res = 0;
    const mx_status_t status = mx_cprng_draw(buffer + read, len, &res);
    if (status != NO_ERROR) {
      return false;
    }
    read += res;
  }
  return true;
}

}  // namespace bin
}  // namespace dart

#endif  // defined(TARGET_OS_FUCHSIA)

Use the new argument ordering for mx_cprng_draw

BUG=
R=abarth@google.com, zra@google.com

Review URL: https://codereview.chromium.org/2479683002 .


/*
 * Copyright 2017 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkSGDraw.h"

#include "SkSGGeometryNode.h"
#include "SkSGInvalidationController.h"
#include "SkSGPaintNode.h"

namespace sksg {

Draw::Draw(sk_sp<GeometryNode> geometry, sk_sp<PaintNode> paint)
    : fGeometry(std::move(geometry))
    , fPaint(std::move(paint)) {
    fGeometry->addInvalReceiver(this);
    fPaint->addInvalReceiver(this);
}

Draw::~Draw() {
    fGeometry->removeInvalReceiver(this);
    fPaint->removeInvalReceiver(this);
}

void Draw::onRender(SkCanvas* canvas) const {
    fGeometry->draw(canvas, fPaint->makePaint());
}

SkRect Draw::onRevalidate(InvalidationController* ic, const SkMatrix& ctm) {
    SkASSERT(this->hasInval());

    // TODO: adjust bounds for paint
    const auto bounds = fGeometry->revalidate(ic, ctm);
    fPaint->revalidate(ic, ctm);

    return bounds;
}

} // namespace sksg

/*
 * Copyright 2017 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkSGDraw.h"

#include "SkSGGeometryNode.h"
#include "SkSGInvalidationController.h"
#include "SkSGPaintNode.h"

namespace sksg {

Draw::Draw(sk_sp<GeometryNode> geometry, sk_sp<PaintNode> paint)
    : fGeometry(std::move(geometry))
    , fPaint(std::move(paint)) {
    fGeometry->addInvalReceiver(this);
    fPaint->addInvalReceiver(this);
}

Draw::~Draw() {
    fGeometry->removeInvalReceiver(this);
    fPaint->removeInvalReceiver(this);
}

void Draw::onRender(SkCanvas* canvas) const {
    fGeometry->draw(canvas, fPaint->makePaint());
}

SkRect Draw::onRevalidate(InvalidationController* ic, const SkMatrix& ctm) {
    SkASSERT(this->hasInval());

    auto bounds = fGeometry->revalidate(ic, ctm);
    fPaint->revalidate(ic, ctm);

    const auto& paint = fPaint->makePaint();
    SkASSERT(paint.canComputeFastBounds());

    return paint.computeFastBounds(bounds, &bounds);
}

} // namespace sksg

Adjust Draw node bounds for paint

[skotty] Adjust Draw node bounds for paint

TBR=

Change-Id: I88b3fe9c0ed4be2244b82d78995d6e27fa022296
Reviewed-on: https://skia-review.googlesource.com/93301
Reviewed-by: Florin Malita <a8262bf13ea8c26821e91ea9bca6740a77c96dcd@chromium.org>
Commit-Queue: Florin Malita <a8262bf13ea8c26821e91ea9bca6740a77c96dcd@chromium.org>


// [TODO] This belongs into the cmake platform files!!
#if defined(WIN32) && !defined(_DEBUG)
#pragma comment(linker, "/SUBSYSTEM:WINDOWS /entry:mainCRTStartup")
#endif

#include <memory>

#include <gloperate/ext-includes-begin.h>
#include <widgetzeug/dark_fusion_style.hpp>
#include <gloperate/ext-includes-end.h>

#include <gloperate-qt/viewer/Viewer.h>

#include "Application.h"

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

    widgetzeug::enableDarkFusionStyle();

    gloperate_qt::Viewer viewer;
    viewer.show();

    viewer.loadPainter("Logo");

    return app.exec();
}

// [TODO] This belongs into the cmake platform files!!
#if defined(WIN32) && !defined(_DEBUG)
#pragma comment(linker, "/SUBSYSTEM:WINDOWS /entry:mainCRTStartup")
#endif

#include <memory>

#include <gloperate/ext-includes-begin.h>
#include <widgetzeug/dark_fusion_style.hpp>
#include <gloperate/ext-includes-end.h>

#include <gloperate-qt/viewer/Viewer.h>

#include "Application.h"

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

    widgetzeug::enableDarkFusionStyle();

    gloperate_qt::Viewer viewer;
    viewer.show();

    std::string painterName = (argc > 1) ? argv[1] : "Logo";
    viewer.loadPainter(painterName);

    return app.exec();
}

Allow user to specify the initial painter on the commandline for gloperate-viewer


#include "ofxShadersFX.h"

namespace ofxShadersFX {
    Shader::Shader(ShaderType p_type)
    {
        setShaderType(p_type);
    }

    void Shader::begin() {
        // The shader needs reload if not loaded
        // or if modifications in attributes occurred since last frame
        if (!m_shader.isLoaded() || m_needsReload) {
            reload();
            m_needsReload = false;
        }
        m_shader.begin();
    }

    void Shader::end() {
        m_shader.end();
    }

    ShaderType Shader::shaderType() const {
        return m_type;
    }

    void Shader::setShaderType(ShaderType p_type) {
        m_type = p_type;
    }

    void Shader::reload() {
        this->m_shader.setupShaderFromSource(GL_VERTEX_SHADER, getShader(GL_VERTEX_SHADER));
        this->m_shader.setupShaderFromSource(GL_FRAGMENT_SHADER, getShader(GL_FRAGMENT_SHADER));
        if(ofIsGLProgrammableRenderer()) {
            this->m_shader.bindDefaults();
        }
        this->m_shader.linkProgram();
    }
}

// The MIT License (MIT)
// Copyright (c) 2016 Alexandre Baron (Scylardor)

// 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 "ofxShadersFX.h"

namespace ofxShadersFX {
    Shader::Shader(ShaderType p_type)
    {
        setShaderType(p_type);
    }

    void Shader::begin() {
        // The shader needs reload if not loaded
        // or if modifications in attributes occurred since last frame
        if (!m_shader.isLoaded() || m_needsReload) {
            reload();
            m_needsReload = false;
        }
        m_shader.begin();
    }

    void Shader::end() {
        m_shader.end();
    }

    ShaderType Shader::shaderType() const {
        return m_type;
    }

    void Shader::setShaderType(ShaderType p_type) {
        m_type = p_type;
    }

    void Shader::reload() {
        m_shader.setupShaderFromSource(GL_VERTEX_SHADER, getShader(GL_VERTEX_SHADER));
        m_shader.setupShaderFromSource(GL_FRAGMENT_SHADER, getShader(GL_FRAGMENT_SHADER));
        if(ofIsGLProgrammableRenderer()) {
            m_shader.bindDefaults();
        }
        m_shader.linkProgram();
    }
}

Remove unnecessary "this->" (style issue)


// @palcu
// InfoOltenia 2015, teleport, backtracking

#include <cstdio>
#include <algorithm>

using namespace std;

const int NMAX = 100000,
          PASI_INFINITI = NMAX*2;

int v[NMAX],
    nVector, sizeOfCheat;

int back(int pozitieCurenta, int cheatsAvailable) {
    if (pozitieCurenta > nVector)
        return PASI_INFINITI;

    if (pozitieCurenta == nVector)
        return 0;

    int sol = min(back(pozitieCurenta+1, cheatsAvailable) + 1,
                  back(pozitieCurenta+v[pozitieCurenta], cheatsAvailable) + 1);
    if (cheatsAvailable)
        sol = min(sol, back(pozitieCurenta+sizeOfCheat, cheatsAvailable-1) + 1);
    return sol;
}

int main() {
    freopen("teleport.in", "r", stdin);
    freopen("teleport.out", "w", stdout);

    int nCheats;
    scanf("%d%d%d", &nVector, &nCheats, &sizeOfCheat);

    for(int i=0; i<nVector; i++)
        scanf("%d", &v[i]);

    printf("%d\n", back(0, nCheats));

    return 0;
}

Add comments in the source code

Add comments in the source code


// RUN: %clang_cc1 -analyze -analyzer-experimental-internal-checks -analyzer-check-objc-mem  -analyzer-experimental-checks -verify %s
struct X0 { };
bool operator==(const X0&, const X0&);

// PR7287
struct test { int a[2]; };

void t2() {
  test p = {{1,2}};
  test q;
  q = p;
}

bool PR7287(X0 a, X0 b) {
  return a == b;
}

// RUN: %clang_cc1 -analyze -analyzer-experimental-internal-checks -analyzer-check-objc-mem  -analyzer-experimental-checks -verify %s
struct X0 { };
bool operator==(const X0&, const X0&);

// PR7287
struct test { int a[2]; };

void t2() {
  test p = {{1,2}};
  test q;
  q = p;
}

bool PR7287(X0 a, X0 b) {
  return operator==(a, b);
}

Make my test case test what it meant to

Make my test case test what it meant to

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


/* Copyright 2012 Dietrich Epp <depp@zdome.net> */
#include "level.hpp"
#include "gamescreen.hpp"
using namespace LD24;

Level::~Level()
{ }

void Level::nextLevel()
{
    screen.nextLevel();
}

void Level::setTipFlags(unsigned flags)
{
    if (flags == m_tipflag)
        return;
    levelTips.clear();
    for (int i = 0; i < 32; ++i) {
        if (flags & (1u << i))
            levelTips.push_back(m_allTips[i]);
    }
}

void Level::addTip(int index)
{
    setTipFlags(m_tipflag | (1u << index));
}

void Level::removeTip(int index)
{
    setTipFlags(m_tipflag & ~(1u << index));
}

/* Copyright 2012 Dietrich Epp <depp@zdome.net> */
#include "level.hpp"
#include "gamescreen.hpp"
using namespace LD24;

Level::~Level()
{ }

void Level::nextLevel()
{
    screen.nextLevel();
}

void Level::setTipFlags(unsigned flags)
{
    if (flags == m_tipflag)
        return;
    levelTips.clear();
    for (int i = 0; i < 32; ++i) {
        if (flags & (1u << i))
            levelTips.push_back(m_allTips[i]);
    }
    m_tipflag = flags;
}

void Level::addTip(int index)
{
    setTipFlags(m_tipflag | (1u << index));
}

void Level::removeTip(int index)
{
    setTipFlags(m_tipflag & ~(1u << index));
}

Fix problems with multiple tips

Fix problems with multiple tips


// Rel native launcher for Linux.

#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <libgen.h>
#include <string>
#include <fstream>
#include <streambuf>

int main(int argc, char **argv)
{
  // Convert first argument of argv[0] (full pathspec to this executable) to path where executable is found
  char *dir = dirname(argv[0]);
  chdir(dir);

  // Read the ini file
  std::string iniFileName("lib/Rel.ini");
  std::ifstream configfile(iniFileName);
  std::string cmd((std::istreambuf_iterator<char>(configfile)), std::istreambuf_iterator<char>());

  // Empty or no ini file?
  if (cmd.length() == 0) {
    std::cerr << (std::string("Missing or Damaged .ini File: Unable to find ") + iniFileName).c_str() << std::endl;
    return 10;
  }

  // Include command-line args.
  std::string args("");
  for (int i = 1; i < argc; i++)
  	args += std::string(" ") + std::string(argv[i]);

  setenv("SWT_GTK3", "0", 1);
  return system((cmd + args).c_str());
}

// Rel native launcher for Linux.

#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <libgen.h>
#include <string>
#include <fstream>
#include <streambuf>

int main(int argc, char **argv)
{
  // Convert first argument of argv[0] (full pathspec to this executable) to path where executable is found
  char *dir = dirname(argv[0]);
  chdir(dir);

  // Read the ini file
  std::string iniFileName("lib/Rel.ini");
  std::ifstream configfile(iniFileName);
  std::string cmd((std::istreambuf_iterator<char>(configfile)), std::istreambuf_iterator<char>());

  // Empty or no ini file?
  if (cmd.length() == 0) {
    std::cerr << (std::string("Missing or Damaged .ini File: Unable to find ") + iniFileName).c_str() << std::endl;
    return 10;
  }

  // Include command-line args.
  std::string args("");
  for (int i = 1; i < argc; i++)
    args += std::string(" \"") + std::string(argv[i]) + std::string("\"");

  setenv("SWT_GTK3", "0", 1);
  return system((cmd + args).c_str());
}

Add double-quote delimiters to args.

Add double-quote delimiters to args.


// 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 "content/public/common/context_menu_params.h"

namespace content {

const int32 CustomContextMenuContext::kCurrentRenderWidget = kint32max;

CustomContextMenuContext::CustomContextMenuContext()
    : is_pepper_menu(false),
      request_id(0),
      render_widget_id(kCurrentRenderWidget) {
}

ContextMenuParams::ContextMenuParams()
    : media_type(blink::WebContextMenuData::MediaTypeNone),
      x(0),
      y(0),
      has_image_contents(true),
      frame_id(0),
      media_flags(0),
      misspelling_hash(0),
      speech_input_enabled(false),
      spellcheck_enabled(false),
      is_editable(false),
      writing_direction_default(
          blink::WebContextMenuData::CheckableMenuItemDisabled),
      writing_direction_left_to_right(
          blink::WebContextMenuData::CheckableMenuItemEnabled),
      writing_direction_right_to_left(
          blink::WebContextMenuData::CheckableMenuItemEnabled),
      edit_flags(0),
      referrer_policy(blink::WebReferrerPolicyDefault) {
}

ContextMenuParams::~ContextMenuParams() {
}

}  // namespace content

// 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 "content/public/common/context_menu_params.h"

namespace content {

const int32 CustomContextMenuContext::kCurrentRenderWidget = kint32max;

CustomContextMenuContext::CustomContextMenuContext()
    : is_pepper_menu(false),
      request_id(0),
      render_widget_id(kCurrentRenderWidget) {
}

ContextMenuParams::ContextMenuParams()
    : media_type(blink::WebContextMenuData::MediaTypeNone),
      x(0),
      y(0),
      has_image_contents(true),
      frame_id(0),
      media_flags(0),
      misspelling_hash(0),
      speech_input_enabled(false),
      spellcheck_enabled(false),
      is_editable(false),
      writing_direction_default(
          blink::WebContextMenuData::CheckableMenuItemDisabled),
      writing_direction_left_to_right(
          blink::WebContextMenuData::CheckableMenuItemEnabled),
      writing_direction_right_to_left(
          blink::WebContextMenuData::CheckableMenuItemEnabled),
      edit_flags(0),
      referrer_policy(blink::WebReferrerPolicyDefault),
      source_type(ui::MENU_SOURCE_NONE) {
}

ContextMenuParams::~ContextMenuParams() {
}

}  // namespace content

Initialize all members of ContextMenuParams in the ctor

BUG=332271
R=thestig@chromium.org,joi@chromium.org

Review URL: https://codereview.chromium.org/128413002

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


// RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++17

void foo(int* a, int *b) {
  a -= b; // expected-warning {{incompatible integer to pointer conversion assigning to 'int *' from 'long'}}
}

template<typename T> T declval();
struct true_type { static const bool value = true; };
struct false_type { static const bool value = false; };
template<bool, typename T, typename U> struct select { using type = T; };
template<typename T, typename U> struct select<false, T, U> { using type = U; };

template<typename T>
typename select<(sizeof(declval<T>() -= declval<T>(), 1) != 1), true_type, false_type>::type test(...);
template<typename T> false_type test(...);

template<typename T>
static const auto has_minus_assign = decltype(test<T>())::value;

static_assert(has_minus_assign<int*>, "failed"); // expected-error {{static_assert failed due to requirement 'has_minus_assign<int *>' "failed"}}

// RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++17

void foo(int* a, int *b) {
  a -= b; // expected-warning {{incompatible integer to pointer conversion assigning to 'int *' from}}
}

template<typename T> T declval();
struct true_type { static const bool value = true; };
struct false_type { static const bool value = false; };
template<bool, typename T, typename U> struct select { using type = T; };
template<typename T, typename U> struct select<false, T, U> { using type = U; };

template<typename T>
typename select<(sizeof(declval<T>() -= declval<T>(), 1) != 1), true_type, false_type>::type test(...);
template<typename T> false_type test(...);

template<typename T>
static const auto has_minus_assign = decltype(test<T>())::value;

static_assert(has_minus_assign<int*>, "failed"); // expected-error {{static_assert failed due to requirement 'has_minus_assign<int *>' "failed"}}

Fix test failure from r351495

Fix test failure from r351495

The test has problems due to some platforms having a different type for
ptrdiff_t, so the error message is different.  The error message doesn't
matter to the test for anything other than an incompatible intger to
pointer conversion, so this patch removes the integral type from the
expected message.

Change-Id: I80e786f9b80268163813774bbf25a9ca25b6c60c

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


#include "variant/pwm_platform.hpp"

#include "hal.h"

static const PWMConfig motor_pwm_config = {
  500000,    // 500 kHz PWM clock frequency.
  1000,      // PWM period 2.0 ms.
  NULL,      // No callback.
  {
    {PWM_OUTPUT_ACTIVE_HIGH, NULL},
    {PWM_OUTPUT_ACTIVE_HIGH, NULL},
    {PWM_OUTPUT_ACTIVE_HIGH, NULL},
    {PWM_OUTPUT_ACTIVE_HIGH, NULL}
  },   // Channel configurations
  0,0   // HW dependent
};

PWMPlatform::PWMPlatform() {
  pwmStart(&PWMD8, &motor_pwm_config);
  palSetPadMode(GPIOC, 6, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 7, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 8, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 9, PAL_MODE_ALTERNATE(4));
}

void PWMPlatform::set(std::uint8_t ch, float dc) {
  pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD8, dc * 10000.0f);
  pwmEnableChannel(&PWMD8, ch, width);
}

#include "variant/pwm_platform.hpp"

#include "hal.h"

static const PWMConfig motor_pwm_config = {
  500000,    // 500 kHz PWM clock frequency.
  2000,      // PWM period 2.0 ms.
  NULL,      // No callback.
  {
    {PWM_OUTPUT_ACTIVE_HIGH, NULL},
    {PWM_OUTPUT_ACTIVE_HIGH, NULL},
    {PWM_OUTPUT_ACTIVE_HIGH, NULL},
    {PWM_OUTPUT_ACTIVE_HIGH, NULL}
  },   // Channel configurations
  0,0   // HW dependent
};

PWMPlatform::PWMPlatform() {
  pwmStart(&PWMD8, &motor_pwm_config);
  palSetPadMode(GPIOC, 6, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 7, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 8, PAL_MODE_ALTERNATE(4));
  palSetPadMode(GPIOC, 9, PAL_MODE_ALTERNATE(4));
}

void PWMPlatform::set(std::uint8_t ch, float dc) {
  pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD8, dc * 10000.0f);
  pwmEnableChannel(&PWMD8, ch, width);
}

Fix PWM period on F3.

Fix PWM period on F3.


#include "yebash.hpp"
#include "History.hpp"

#include "catch.hpp"
#include <sstream>

using namespace yb;

TEST_CASE( "No suggestions when history is empty", "[basic.empty_history]"  ) {
    std::stringstream ss;
    History history;
    history.read(ss);
    HistorySuggestion suggestion(history);

    auto c = yebash(suggestion, 'a');
    REQUIRE(c == 'a');
}

#include "yebash.hpp"
#include "History.hpp"

#include "catch.hpp"
#include <sstream>

using namespace yb;

TEST_CASE( "No suggestions when history is empty", "[basic.empty_history]"  ) {
    std::stringstream ss;
    std::stringstream output;
    History history;
    history.read(ss);
    HistorySuggestion suggestion(history);
    Printer printer(output);

    auto c = yebash(suggestion, printer, 'a');
    std::string result{output.str()};

    REQUIRE(c == 'a');
    REQUIRE(output.str() == "");
}

Update tests - allow checking the output


#include <QTest>
#include "mainwindow.h"
#include "test-suite.h"

QMap<QDateTime, QString> _log;
QMap<QString, QString> _md5;
mainWindow *_mainwindow;

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

    int failed = 0;
    for (QObject *suite : TestSuite::suites)
    {
        int result = QTest::qExec(suite);
        if (result != 0)
        {
            failed++;
        }
    }

    return failed;
}

#include <QTest>
#include "mainwindow.h"
#include "test-suite.h"

QMap<QDateTime, QString> _log;
QMap<QString, QString> _md5;
mainWindow *_mainwindow;

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    int failed = 0;
    for (QObject *suite : TestSuite::suites)
    {
        int result = QTest::qExec(suite);
        if (result != 0)
        {
            failed++;
        }
    }

    return failed;
}

Replace gui application by core app to run in cli


#include "Thread/Unix/ThreadImpl.hh"
#include "Thread/ThreadException.hh"

namespace LilWrapper
{
  ThreadImpl::ThreadImpl(Thread *thread)
  {
    this->_isActive = pthread_create(&this->_thread, NULL,
	&ThreadImpl::entryPoint, thread) == 0;
    if (!this->_isActive)
      throw ThreadException("Thread Exception: "
	  "Error while creating the Thread.");
  }

  ThreadImpl::~ThreadImpl()
  {
    if (this->_isActive)
      terminate();
  }

  void ThreadImpl::wait()
  {
    if (this->_isActive)
    {
      if (pthread_equal(pthread_self(), this->_thread) != 0)
	throw ThreadException("Thread Exception: "
	    "A thread cannot wait for itself.");
      pthread_join(this->_thread, NULL);
    }
  }

  void ThreadImpl::terminate()
  {
    if (this->_isActive)
      pthread_cancel(this->_thread);
  }

  void *ThreadImpl::entryPoint(void *data)
  {
    Thread *self = static_cast<Thread *>(data);

    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
    self->run();
    return (NULL);
  }
}

#include "Thread/Unix/ThreadImpl.hh"
#include "Thread/ThreadException.hh"

namespace LilWrapper
{
  ThreadImpl::ThreadImpl(Thread *thread)
  {
    this->_isActive = pthread_create(&this->_thread, NULL,
        &ThreadImpl::entryPoint, thread) == 0;
    if (!this->_isActive)
      throw ThreadException("Thread Exception: "
          "Error while creating the Thread.");
  }

  ThreadImpl::~ThreadImpl()
  {
    if (this->_isActive)
      terminate();
  }

  void ThreadImpl::wait()
  {
    if (this->_isActive)
    {
      if (pthread_equal(pthread_self(), this->_thread) != 0)
        throw ThreadException("Thread Exception: "
            "A thread cannot wait for itself.");
      pthread_join(this->_thread, NULL);
    }
  }

  void ThreadImpl::terminate()
  {
    if (this->_isActive)
      pthread_cancel(this->_thread);
    this->_isActive = false;
  }

  void *ThreadImpl::entryPoint(void *data)
  {
    Thread *self = static_cast<Thread *>(data);

    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
    self->run();
    return (NULL);
  }
}

Set the Thread as inactive when terminating it.


/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkTypes.h"

static const size_t kBufferSize = 256;

#define LOG_TAG "skia"
#include <android/log.h>

void SkDebugf(const char format[], ...) {
    va_list args;
    va_start(args, format);
    __android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args);
    va_end(args);
}

/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkTypes.h"

static const size_t kBufferSize = 256;

#define LOG_TAG "skia"
#include <android/log.h>

static bool gSkDebugToStdOut = false;

extern "C" void AndroidSkDebugToStdOut(bool debugToStdOut) {
    gSkDebugToStdOut = debugToStdOut;
}

void SkDebugf(const char format[], ...) {
    va_list args;
    va_start(args, format);
    __android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args);

    // Print debug output to stdout as well.  This is useful for command
    // line applications (e.g. skia_launcher)
    if (gSkDebugToStdOut) {
        vprintf(format, args);
    }

    va_end(args);
}

Enable Android executables (like skia_launcher) to redirect SkDebugf output to stdout as well as the system logs.

Review URL: https://codereview.appspot.com/6733065

git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@6059 2bbb7eff-a529-9590-31e7-b0007b416f81


/*
 * Copyright (c) 2016 Lech Kulina
 *
 * This file is part of the Realms Of Steel.
 * For conditions of distribution and use, see copyright details in the LICENSE file.
 */
#include <cstdlib>
#include <boost/property_tree/info_parser.hpp>
#include <application/Logger.h>
#include <application/Application.h>
#include <resources/ResourceCache.h>

int main() {
    int exitCode = EXIT_FAILURE;

    ros::PropertyTree config;
    boost::property_tree::read_info("Config.info", config);

    if (!ros::Logger::initInstance(config.get_child("Logger")) ||
        !ros::Application::initInstance(config.get_child("application")) ||
        !ros::ResourceCache::initInstance(config.get_child("resources"))) {
        return exitCode;
    }

    ros::ApplicationPtr application = ros::Application::getInstance();
    if (application) {
        exitCode = application->run();
        application->uninit();
    }

    return exitCode;
}

/*
 * Copyright (c) 2016 Lech Kulina
 *
 * This file is part of the Realms Of Steel.
 * For conditions of distribution and use, see copyright details in the LICENSE file.
 */
#include <cstdlib>
#include <boost/property_tree/info_parser.hpp>
#include <application/Logger.h>
#include <application/Application.h>
#include <resources/FileSystem.h>
#include <resources/ResourcesCache.h>

int main() {
    int exitCode = EXIT_FAILURE;

    ros::PropertyTree config;
    boost::property_tree::read_info("Config.info", config);

    if (!ros::Logger::initInstance(config.get_child("Logger")) ||
        !ros::Application::initInstance(config.get_child("application")) ||
        !ros::FileSystem::initInstance(config.get_child("file-system")) ||
        !ros::ResourcesCache::initInstance(config.get_child("resources-cache"))) {
        return exitCode;
    }

    ros::ApplicationPtr application = ros::Application::getInstance();
    if (application) {
        exitCode = application->run();
        application->uninit();
    }

    return exitCode;
}

Initialize FileSystem and ResourcesCache from config file


#include <iostream>
#include <cstlib>
#include <vector>

#include <iostream>
#include <cstdlib>
#include <vector>
#include <bitset>
#include <cstring>
#include <string>
#include <fstream>
#include <cstdio>

#include "rand.h"

using namespace std;

class individual {
public:
  int key[26];
  float fit;

};

// user functions go here

int main() {

  // get cipher from cin
  string cipher, tmp;
  while( getline( cin, tmp ) ) {
    cipher.append( tmp );
  }

  // read in freq.txt
  FILE *freq = fopen( "freq.txt", "r" );
  char eng1[488], eng2[488];
  float engnum[488];

  // check if file is open
  if( freq != NULL ) {
    for( int i = 0; i < 488; i++ ) {
      fscanf( freq, "%c%c %f ", &eng1[i], &eng2[i], &engnum[i] );
      //      eng1[i] = fgetc( freq );
      //eng2[i] = fgetc( freq );

      cout << eng1[i] << eng2[i] << " " << engnum[i] <<endl;
    }
  }

  // create cipher count tables
  char cipher1[488], cipher2[488];
  float ciphernum[488];

  for( int i = 0; i < cipher.size(); i++ ){

  }

} // end main

Use fscanf to read in file.

Use fscanf to read in file.


#include <stdexcept>
#include "Person.h"

Person::Person(std::string name) {
	if(name.empty()){
		throw std::invalid_argument("Name can not be empty.");
	}
	this->name = name;
};

#include <stdexcept>
#include "Person.h"

Person::Person(std::string name) {
	if(name.empty()){
		throw std::invalid_argument("Name cannot be empty.");
	}
	this->name = name;
};

Add verification to Person constructor

Add verification to Person constructor


#include "gtest/gtest.h"

int main(int argc, char *argv[])
{
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

#include "gtest/gtest.h"

class ThrowListener : public testing::EmptyTestEventListener
{
  void OnTestPartResult(const testing::TestPartResult& result) override
  {
    if (result.type() == testing::TestPartResult::kFatalFailure)
    {
      throw testing::AssertionException(result);
    }
  }
};

int main(int argc, char *argv[])
{
  ::testing::InitGoogleTest(&argc, argv);
  ::testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener);
  return RUN_ALL_TESTS();
}

Make ASSERTs in helper functions fail the parent testcase


#include "BoardMarker.hpp"

BoardMarker::BoardMarker (void) : m(NONE), c(' ') {}

bool BoardMarker::apply_modifier(Modifier& m) {
  if (this->m != NONE) {
    return false;
  }
  this->m = m;
  return true;
}

bool BoardMarker::set_char(char& c) {
  if (this->c != ' ') {
    return false;
  }
  this->c = toupper(c);
  return true;
}

void BoardMarker::print_marker(void) {
  string pre = " ";
  string col = "";
  string post = " ";
  if (this->m != NONE) {
    pre = " \033[";
    post = "\033[0m ";
    switch (this->m) {
      case DOUBLE_L:
        col = "1;43;37m";
        break;
      case DOUBLE_W:
        col = "1;42;37m";
        break;
      case TRIPLE_L:
        col = "1;44;37m";
        break;
      case TRIPLE_W:
        col = "1;41;37m";
        break;
      case NONE:
        cout << "Shouldn't reach this line!" << endl;
    }
  }

  cout << pre << col << this->c << post;
}

#include "BoardMarker.hpp"

BoardMarker::BoardMarker (void) : m(NONE), c(' ') {}

bool BoardMarker::apply_modifier(Modifier& m) {
  if (this->m != NONE) {
    return false;
  }
  this->m = m;
  return true;
}

bool BoardMarker::set_char(char& c) {
  if (this->c != ' ') {
    return this->c == c;
  }
  this->c = toupper(c);
  return true;
}

void BoardMarker::print_marker(void) {
  string pre = " ";
  string col = "";
  string post = " ";
  if (this->m != NONE) {
    pre = " \033[";
    post = "\033[0m ";
    switch (this->m) {
      case DOUBLE_L:
        col = "1;43;37m";
        break;
      case DOUBLE_W:
        col = "1;42;37m";
        break;
      case TRIPLE_L:
        col = "1;44;37m";
        break;
      case TRIPLE_W:
        col = "1;41;37m";
        break;
      case NONE:
        cout << "Shouldn't reach this line!" << endl;
    }
  }

  cout << pre << col << this->c << post;
}

Allow set_char when char is the same - updating words


// 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/tabs/dock_info.h"

#include "chrome/browser/ui/views/tabs/tab.h"
#include "build/build_config.h"

#if !defined(OS_WIN)
// static
int DockInfo::GetHotSpotDeltaY() {
  return Tab::GetMinimumUnselectedSize().height() - 1;
}
#endif

// 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/tabs/dock_info.h"

#include "chrome/browser/ui/views/tabs/tab.h"
#include "build/build_config.h"

#if defined(USE_AURA) || defined(USE_ASH) || defined(OS_CHROMEOS)
// static
int DockInfo::GetHotSpotDeltaY() {
  return Tab::GetMinimumUnselectedSize().height() - 1;
}
#endif

views/tabs: Fix win_aura build enabling GetHotSpotDeltaY() in aura too.

BUG=125846
TBR=ben@chromium.org
NOTRY=true

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

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


#include "messagedirector.h"
#include "../core/config.h"
ConfigVariable<std::string> bind_addr("messagedirector/bind", "unspecified");

MessageDirector MessageDirector::singleton;

void MessageDirector::InitializeMD()
{
	if(!m_initialized)
	{
		if(bind_addr.get_val() != "unspecified")
		{
		}
	}
}

MessageDirector::MessageDirector() : m_acceptor(NULL), m_initialized(false)
{
}

#include "../core/global.h"
#include "messagedirector.h"
#include "../core/config.h"
using boost::asio::ip::tcp; // I don't want to type all of that god damned shit
ConfigVariable<std::string> bind_addr("messagedirector/bind", "unspecified");

MessageDirector MessageDirector::singleton;

void MessageDirector::InitializeMD()
{
	if(!m_initialized)
	{
		if(bind_addr.get_val() != "unspecified")
		{
			std::string str_ip = bind_addr.get_val();
			std::string str_port = str_ip.substr(str_ip.find(':', 0)+1, std::string::npos);
			str_ip = str_ip.substr(0, str_ip.find(':', 0));
			tcp::resolver resolver(io_service);
			tcp::resolver::query query(str_ip, str_port);
			tcp::resolver::iterator it = resolver.resolve(query);
			m_acceptor = new tcp::acceptor(io_service, *it, true);
			tcp::socket socket(io_service);
			tcp::endpoint peerEndpoint;
			m_acceptor->accept(socket);
		}
	}
}

MessageDirector::MessageDirector() : m_acceptor(NULL), m_initialized(false)
{
}

Put in some placeholder synhronous accept code


//===----------------------------------------------------------------------===//
//
//                     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>

// template <class F, class... Args>
//     future<typename result_of<F(Args...)>::type>
//     async(F&& f, Args&&... args);

// template <class F, class... Args>
//     future<typename result_of<F(Args...)>::type>
//     async(launch policy, F&& f, Args&&... args);

#include <future>
#include <atomic>
#include <memory>
#include <cassert>

#include "test_macros.h"

int foo (int x) { return x; }

int main ()
{
	std::async(                    foo, 3); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}}
	std::async(std::launch::async, foo, 3); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}}
}

//===----------------------------------------------------------------------===//
//
//                     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, c++11, c++14, c++17
// UNSUPPORTED: clang-3.3, clang-3.4, clang-3.5, clang-3.6, clang-3.7, clang-3.8

// <future>

// template <class F, class... Args>
//     future<typename result_of<F(Args...)>::type>
//     async(F&& f, Args&&... args);

// template <class F, class... Args>
//     future<typename result_of<F(Args...)>::type>
//     async(launch policy, F&& f, Args&&... args);

#include <future>
#include <atomic>
#include <memory>
#include <cassert>

#include "test_macros.h"

int foo (int x) { return x; }

int main ()
{
	std::async(                    foo, 3); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}}
	std::async(std::launch::async, foo, 3); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}}
}

Add additional 'UNSUPPORTED' to the test case.

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


// RUN: %clang  -emit-llvm -g -S %s -o - | FileCheck %s

// TAG_member is used to encode debug info for 'z' in A.
// CHECK: TAG_member
class A {
public:
  int z;
};

A *foo (A* x) {
  A *a = new A(*x);
  return a;
}

// Verify that we're not emitting a full definition of B in limit debug mode.
// RUN: %clang -emit-llvm -g -flimit-debug-info -S %s -o - | FileCheck %s
// CHECK-NOT: TAG_member

class B {
public:
  int y;
};

extern int bar(B *b);
int baz(B *b) {
  return bar(b);
}

Add a test to verify that -flimit-debug-info is working in some way.

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


#include <opencv2/opencv.hpp>
#include <unistd.h>
int main(int argc, char** argv){
  if(argc!=2){
    std::cout << "Nope.\n";
    return -1;
  }
  cv::VideoCapture _capture(CV_CAP_OPENNI);
  std::cout << "Started streaming data to main system..\n";
  int c=0;
  while(1){
    cv::Mat depthMap, rgb;
    usleep(500000);
    _capture.grab();
    _capture.retrieve(depthMap, CV_CAP_OPENNI_DEPTH_MAP);
    _capture.retrieve(rgb, CV_CAP_OPENNI_BGR_IMAGE);
    imwrite(std::string(argv[1])+"/rgb.png", rgb);
    imwrite(std::string(argv[1])+"/depth.png", depthMap);
    std::cout << ++c << "\n";
  }
  return 0;
}

#include <opencv2/opencv.hpp>
#include <opencv/highgui.h>
#include <unistd.h>
int main(int argc, char** argv){
  if(argc!=2){
    std::cout << "Nope.\n";
    return -1;
  }
  cv::VideoCapture _capture(CV_CAP_OPENNI);
  std::cout << "Started streaming data to main system..\n";
  int c=0;
  cv::namedWindow("DEPTH");
  while(1){
    cv::Mat depthMap, rgb;
    usleep(500000);
    _capture.grab();
    _capture.retrieve(depthMap, CV_CAP_OPENNI_DEPTH_MAP);
    cv::imshow("DEPTH", depthMap);
    cv::waitKey(1);
    _capture.retrieve(rgb, CV_CAP_OPENNI_BGR_IMAGE);
    cv::imshow("RGB", rgb);
    cv::waitKey(1);
    std::string name=std::string(argv[1])+"/";
    imwrite(name+"/rgb1.png", rgb);
    imwrite(name+"/depth1.png", depthMap);
    system(("mv "+name+"rgb1.png "+name+"rgb.png ; mv "+name+"depth1.png "+name+"depth.png").c_str());
    std::cout << ++c << "\n";
  }
  return 0;
}

Make a more robust streamer

Make a more robust streamer


/*  This file is part of Fabula.
    Copyright (C) 2010 Mike McQuaid <mike@mikemcquaid.com>

    Fabula 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.

    Fabula 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 Fabula. If not, see <http://www.gnu.org/licenses/>.
*/

#include "MainWindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication application(argc, argv);
    application.setApplicationName(QString::fromAscii("Fabula"));
    application.setApplicationVersion(QString::fromAscii(PROJECT_VERSION));
    application.setOrganizationDomain(QString::fromAscii("mikemcquaid.com"));
    application.setOrganizationName(QString::fromAscii("Mike McQuaid"));

#ifdef Q_WS_MAC
    application.setAttribute(Qt::AA_DontShowIconsInMenus);
#else
    application.setWindowIcon(":/icons/audio-input-microphone.png");
#endif

    MainWindow mainWindow;
    mainWindow.show();
    return application.exec();
}

/*  This file is part of Fabula.
    Copyright (C) 2010 Mike McQuaid <mike@mikemcquaid.com>

    Fabula 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.

    Fabula 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 Fabula. If not, see <http://www.gnu.org/licenses/>.
*/

#include "MainWindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication application(argc, argv);
    application.setApplicationName(QString::fromAscii("Fabula"));
    application.setApplicationVersion(QString::fromAscii(PROJECT_VERSION));
    application.setOrganizationDomain(QString::fromAscii("mikemcquaid.com"));
    application.setOrganizationName(QString::fromAscii("Mike McQuaid"));

#ifdef Q_WS_MAC
    application.setAttribute(Qt::AA_DontShowIconsInMenus);
#else
    application.setWindowIcon(QIcon(":/icons/audio-input-microphone.png"));
#endif

    MainWindow mainWindow;
    mainWindow.show();
    return application.exec();
}

Fix Windows window icon failure.

Fix Windows window icon failure.


#include "imageviewer.h"
#include "ui_imageviewer.h"

ImageViewer::ImageViewer(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ImageViewer)
{
    ui->setupUi(this);

    QImage image("/Users/Wojtek/Pictures/Three-eyed_crow.jpg");
    ui->imageLabel->setPixmap(QPixmap::fromImage(image));
}

ImageViewer::~ImageViewer()
{
    delete ui;
}

#include "imageviewer.h"
#include "ui_imageviewer.h"

ImageViewer::ImageViewer(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ImageViewer)
{
    ui->setupUi(this);

    ui->imageLabel->setBackgroundRole(QPalette::Base);
    ui->imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    ui->imageLabel->setScaledContents(true);

    ui->scrollArea->setBackgroundRole(QPalette::Dark);

    QImage image("/Users/Wojtek/Pictures/Three-eyed_crow.jpg");
    ui->imageLabel->setPixmap(QPixmap::fromImage(image));

    setWindowTitle(tr("Image Viewer"));
}

ImageViewer::~ImageViewer()
{
    delete ui;
}

Set imageLabel and scrollArea properties


#include <stdio.h>
#include <stdarg.h>
#include <iostream>
#include <fstream>
#include <string>

#include "platform.h"

void logMsg(const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
}

std::string stringFromResource(const char* _path) {
    std::string into;

    std::ifstream file;
    std::string buffer;

    file.open(_path);
    if(!file.is_open()) {
        return std::string();
    }

    while(!file.eof()) {
        getline(file, buffer);
        into += buffer + "\n";
    }

    file.close();
    return into;
}

unsigned char* bytesFromResource(const char* _path, unsigned int* _size) {
    std::ifstream resource(_path, std::ifstream::ate | std::ifstream::binary);

    if(!resource.is_open()) {
        logMsg("Failed to read file at path: %s\n", _path);
        *_size = 0;
        return nullptr;
    }

    *_size = resource.tellg();

    resource.seekg(std::ifstream::beg);

    char* cdata = (char*) malloc(sizeof(char) * (*_size));

    resource.read(cdata, *_size);
    resource.close();

    return reinterpret_cast<unsigned char *>(cdata);
}

#include <stdio.h>
#include <stdarg.h>
#include <iostream>
#include <fstream>
#include <string>

#include "platform.h"

void logMsg(const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
}

void requestRender() {
    // TODO: implement non-continuous rendering on RPi
}

void setContinuousRendering(bool _isContinuous) {
    // TODO: implement non-continuous rendering on RPi
}

bool isContinuousRendering() {
    // TODO: implement non-continuous rendering on RPi
}

std::string stringFromResource(const char* _path) {
    std::string into;

    std::ifstream file;
    std::string buffer;

    file.open(_path);
    if(!file.is_open()) {
        return std::string();
    }

    while(!file.eof()) {
        getline(file, buffer);
        into += buffer + "\n";
    }

    file.close();
    return into;
}

unsigned char* bytesFromResource(const char* _path, unsigned int* _size) {
    std::ifstream resource(_path, std::ifstream::ate | std::ifstream::binary);

    if(!resource.is_open()) {
        logMsg("Failed to read file at path: %s\n", _path);
        *_size = 0;
        return nullptr;
    }

    *_size = resource.tellg();

    resource.seekg(std::ifstream::beg);

    char* cdata = (char*) malloc(sizeof(char) * (*_size));

    resource.read(cdata, *_size);
    resource.close();

    return reinterpret_cast<unsigned char *>(cdata);
}

Fix missing symbols for RPi

Fix missing symbols for RPi

Currently the Pi will ignore requests for non-continuous rendering