#include <MemoryManager.hh>

#include <cstddef>
#include <new>

void *operator new(std::size_t size)
{
   return MemoryManager::get().allocate(size);
}

void *operator new[](std::size_t size)
{
   return MemoryManager::get().allocate(size);
}

void operator delete(void* p)
{
   MemoryManager::get().deallocate(p);
}

void operator delete[](void* p)
{
   MemoryManager::get().deallocate(p);
}

void operator delete(void* p, std::size_t)
{
   MemoryManager::get().deallocate(p);
}

void operator delete[](void* p, std::size_t)
{
   MemoryManager::get().deallocate(p);
}

Add symbols for sized allocation

Add symbols for sized allocation


// 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/browser/renderer_host/render_view_host_observer.h"

#include "content/browser/renderer_host/render_view_host.h"

RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host)
    : render_view_host_(render_view_host),
      routing_id_(render_view_host->routing_id()) {
  render_view_host_->AddObserver(this);
}

RenderViewHostObserver::~RenderViewHostObserver() {
  if (render_view_host_)
    render_view_host_->RemoveObserver(this);
}

void RenderViewHostObserver::RenderViewHostDestroyed() {
  delete this;
}

bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) {
  return false;
}

bool RenderViewHostObserver::Send(IPC::Message* message) {
  if (!render_view_host_) {
    delete message;
    return false;
  }

  return render_view_host_->Send(message);
}

void RenderViewHostObserver::RenderViewHostDestruction() {
  render_view_host_->RemoveObserver(this);
  RenderViewHostDestroyed();
  render_view_host_ = NULL;
}

// 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/browser/renderer_host/render_view_host_observer.h"

#include "content/browser/renderer_host/render_view_host.h"

RenderViewHostObserver::RenderViewHostObserver(RenderViewHost* render_view_host)
    : render_view_host_(render_view_host),
      routing_id_(render_view_host->routing_id()) {
  render_view_host_->AddObserver(this);
}

RenderViewHostObserver::~RenderViewHostObserver() {
  if (render_view_host_)
    render_view_host_->RemoveObserver(this);
}

void RenderViewHostObserver::RenderViewHostDestroyed() {
  delete this;
}

bool RenderViewHostObserver::OnMessageReceived(const IPC::Message& message) {
  return false;
}

bool RenderViewHostObserver::Send(IPC::Message* message) {
  if (!render_view_host_) {
    delete message;
    return false;
  }

  return render_view_host_->Send(message);
}

void RenderViewHostObserver::RenderViewHostDestruction() {
  render_view_host_->RemoveObserver(this);
  render_view_host_ = NULL;
  RenderViewHostDestroyed();
}

Fix invalid write in RenderViewHostObserver.

TBR=avi
Review URL: http://codereview.chromium.org/6813065

git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@81023 4ff67af0-8c30-449e-8e8b-ad334ec8d88c


#include <QtPlugin>

#include "test_video_annotator.h"
#include "fish_detector/video_annotator/mainwindow.h"

#ifdef _WIN32
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
#endif

void TestVideoAnnotator::testLoadVideo() {
  fish_detector::video_annotator::MainWindow mainwin;
  mainwin.player_->loadVideo("slow_motion_drop.mp4");
}
void TestVideoAnnotator::testSaveAnnotationsNoFish() {
}

QTEST_MAIN(TestVideoAnnotator)
#include "test_video_annotator.moc"

#include <QtPlugin>

#include "test_video_annotator.h"
#include "fish_detector/video_annotator/mainwindow.h"

#ifdef _WIN32
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
#endif

void TestVideoAnnotator::testLoadVideo() {
  fish_detector::video_annotator::MainWindow mainwin;
  std::string name = "C:/local/FishDetector/test/video_annotator/slow_motion_drop.mp4";
  QVERIFY(mainwin.player_->loadVideo(name));
}
void TestVideoAnnotator::testSaveAnnotationsNoFish() {
  fish_detector::video_annotator::MainWindow mainwin;
  std::string filename = "slow_motion_drop.mp4";
  QVERIFY(mainwin.player_->loadVideo(filename));
  mainwin.onLoadVideoSuccess(QString::fromUtf8(filename.c_str()));
}

QTEST_MAIN(TestVideoAnnotator)
#include "test_video_annotator.moc"

Add content to second test

Add content to second test


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

#include "base/values.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/extensions/input_method_event_router.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"

GetInputMethodFunction::GetInputMethodFunction() {
}

GetInputMethodFunction::~GetInputMethodFunction() {
}

bool GetInputMethodFunction::RunImpl() {
#if !defined(OS_CHROMEOS)
  NOTREACHED();
#else
  chromeos::ExtensionInputMethodEventRouter* router =
      profile_->GetExtensionService()->input_method_event_router();
  chromeos::input_method::InputMethodManager* manager =
      chromeos::input_method::InputMethodManager::GetInstance();
  const std::string input_method =
      router->GetInputMethodForXkb(manager->current_input_method().id());
  result_.reset(Value::CreateStringValue(input_method));
  return true;
#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/extensions/extension_input_method_api.h"

#include "base/values.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/extensions/input_method_event_router.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"

GetInputMethodFunction::GetInputMethodFunction() {
}

GetInputMethodFunction::~GetInputMethodFunction() {
}

bool GetInputMethodFunction::RunImpl() {
#if !defined(OS_CHROMEOS)
  NOTREACHED();
  return false;
#else
  chromeos::ExtensionInputMethodEventRouter* router =
      profile_->GetExtensionService()->input_method_event_router();
  chromeos::input_method::InputMethodManager* manager =
      chromeos::input_method::InputMethodManager::GetInstance();
  const std::string input_method =
      router->GetInputMethodForXkb(manager->current_input_method().id());
  result_.reset(Value::CreateStringValue(input_method));
  return true;
#endif
}

Fix a build error when OS_CHROMEOS is not defined.

BUG=None
TEST=Manually

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

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


#include <vector>
#include <iostream>
#include <algorithm>

#ifndef REMOVE_VALUES
#ifndef CHECK_VALUES
#error "define one of REMOVE_VALUES or CHECK_VALUES"
#endif
#endif

#ifdef REMOVE_VALUES
#ifdef CHECK_VALUES
#error "define either REMOVE_VALUES or CHECK_VALUES"
#endif
#endif

int main()
{
	std::vector<int> myValues;
  for ( long int i=0L; i<100000000L; ++i )
		myValues.push_back(i%3);

	int iOriginalSize = myValues.size();
#ifdef REMOVE_VALUES
	myValues.erase(std::remove_if(myValues.begin(),myValues.end(),[](int i) { return i == 2; }),myValues.end());
#endif
	int sum = 0;
  for ( unsigned int i=0; i<myValues.size(); ++i )
	{
#ifdef CHECK_VALUES
		if ( myValues[i] != 2 )
		{
#endif
			sum += myValues[i];
#ifdef CHECK_VALUES
		}
#endif
	}

}

#include <vector>
#include <iostream>
#include <algorithm>

#ifndef REMOVE_VALUES
#ifndef CHECK_VALUES
#error "define one of REMOVE_VALUES or CHECK_VALUES"
#endif
#endif

#ifdef REMOVE_VALUES
#ifdef CHECK_VALUES
#error "define either REMOVE_VALUES or CHECK_VALUES"
#endif
#endif

int main()
{
	std::vector<int> myValues;
	for ( long int i=0L; i<10000000L; ++i )
		myValues.push_back(i%3);

	int iOriginalSize = myValues.size();
#ifdef REMOVE_VALUES
	myValues.erase(std::remove_if(myValues.begin(),myValues.end(),[](int i) { return i == 2; }),myValues.end());
#endif

	const int iterations = 100;
	for ( int iteration=0; iteration < iterations; ++iteration )
	{
		int sum = 0;
		for ( unsigned int i=0; i<myValues.size(); ++i )
		{
#ifdef CHECK_VALUES
			if ( myValues[i] != 2 )
			{
#endif
				sum += myValues[i];
#ifdef CHECK_VALUES
			}
#endif
		}
	}

}

Check vs Remove - not so not so clear

Check vs Remove - not so not so clear


#include "Test.h"

TEST_CASE("Nets") {
    auto tree = SyntaxTree::fromText(R"(
module Top;
    wire logic f = 1;
endmodule
)");

    Compilation compilation;
    compilation.addSyntaxTree(tree);
    NO_COMPILATION_ERRORS;
}

TEST_CASE("Continuous Assignments") {
    auto tree = SyntaxTree::fromText(R"(
module Top;
    wire foo;
    assign foo = 1, foo = 'z;

    logic bar;
    assign bar = 1;
endmodule
)");

    Compilation compilation;
    compilation.addSyntaxTree(tree);
    NO_COMPILATION_ERRORS;
}

#include "Test.h"

#include <nlohmann/json.hpp>

TEST_CASE("Nets") {
    auto tree = SyntaxTree::fromText(R"(
module Top;
    wire logic f = 1;
endmodule
)");

    Compilation compilation;
    compilation.addSyntaxTree(tree);
    NO_COMPILATION_ERRORS;
}

TEST_CASE("Continuous Assignments") {
    auto tree = SyntaxTree::fromText(R"(
module Top;
    wire foo;
    assign foo = 1, foo = 'z;

    logic bar;
    assign bar = 1;
endmodule
)");

    Compilation compilation;
    compilation.addSyntaxTree(tree);
    NO_COMPILATION_ERRORS;
}

TEST_CASE("JSON dump") {
    auto tree = SyntaxTree::fromText(R"(
interface I;
    modport m();
endinterface

package p1;
    parameter int BLAH = 1;
endpackage

module Top;
    wire foo;
    assign foo = 1;

    I array [3] ();

    always_comb begin
    end

    if (1) begin
    end

    for (genvar i = 0; i < 10; i++) begin
    end

    import p1::BLAH;

    import p1::*;

    logic f;
    I stuff();
    Child child(.i(stuff), .f);

    function logic func(logic bar);
    endfunction

endmodule

module Child(I.m i, input logic f = 1);
endmodule
)");

    Compilation compilation;
    compilation.addSyntaxTree(tree);
    NO_COMPILATION_ERRORS;

    // This basic test just makes sure that JSON dumping doesn't crash.
    json output = compilation.getRoot();
    output.dump();
}

Add test for JSON dumping

Add test for JSON dumping


#include <Automaton.h>
#include "Atm_blink.h"

Atm_blink & Atm_blink::begin( int attached_pin, int blinkrate )
{
  const static state_t state_table[] PROGMEM = {
  /*            ON_ENTER    ON_LOOP  ON_EXIT  EVT_TIMER   ELSE */
  /* LED_ON  */   ACT_ON,        -1,      -1,   LED_OFF,    -1,
  /* LED_OFF */  ACT_OFF,        -1,      -1,    LED_ON,    -1 };
  Machine::begin( state_table, ELSE );
  pin = attached_pin;
  timer.begin( this, blinkrate );
  pinMode( pin, OUTPUT );
  return *this;
}

int Atm_blink::event( int id )
{
  switch ( id ) {
  	case EVT_TIMER :
  	  return timer.expired();
   }
   return 0;
}

void Atm_blink::action( int id )
{
  switch ( id ) {
  	case ACT_ON :
  	  digitalWrite( pin, HIGH );
  	  return;
  	case ACT_OFF :
  	  digitalWrite( pin, LOW );
  	  return;
   }
}

Atm_blink & Atm_blink::onSwitch( swcb_sym_t switch_callback ) {

  Machine::onSwitch( switch_callback, "LED_ON\0LED_OFF", "EVT_TIMER\0ELSE" );
  return *this;
}

#include <Automaton.h>
#include "Atm_blink.h"

Atm_blink & Atm_blink::begin( int attached_pin, uint32_t blinkrate )
{
  const static state_t state_table[] PROGMEM = {
  /*            ON_ENTER    ON_LOOP  ON_EXIT  EVT_TIMER   ELSE */
  /* LED_ON  */   ACT_ON,        -1,      -1,   LED_OFF,    -1,
  /* LED_OFF */  ACT_OFF,        -1,      -1,    LED_ON,    -1 };
  Machine::begin( state_table, ELSE );
  pin = attached_pin;
  timer.begin( this, blinkrate );
  pinMode( pin, OUTPUT );
  return *this;
}

int Atm_blink::event( int id )
{
  switch ( id ) {
  	case EVT_TIMER :
  	  return timer.expired();
   }
   return 0;
}

void Atm_blink::action( int id )
{
  switch ( id ) {
  	case ACT_ON :
  	  digitalWrite( pin, HIGH );
  	  return;
  	case ACT_OFF :
  	  digitalWrite( pin, LOW );
  	  return;
   }
}

Atm_blink & Atm_blink::onSwitch( swcb_sym_t switch_callback ) {

  Machine::onSwitch( switch_callback, "LED_ON\0LED_OFF", "EVT_TIMER\0ELSE" );
  return *this;
}

Update blink_modular.ino: changed blinkrate argument to uint32_t


#include <iostream>

using namespace std;

class Complex {
	double re, im;
public:
	Complex(double r, double i) : re {r}, im {i} {}
	Complex operator+(Complex);
	Complex operator*(Complex);
	friend ostream &operator<<(ostream &os, Complex c);
};

ostream &operator<<(ostream &os, Complex c) {
	os << c.re;
	os << ((c.im >= 0) ? "+" : "-");
	os << c.im << "*i";
	return os;
}

Complex Complex::operator+(Complex c) {
	return Complex{this->re+c.re, this->im+c.im};
}

Complex Complex::operator*(Complex c) {
	double r = this->re*c.re - this->im*c.im;
	double i = this->im*c.re + this->re*c.im;
	// This is OK, probably because this is considered
	// as initializer
	return {r, i};
}

void f() {
	Complex a = Complex{1, 3.1};
	cout << a << endl;
	Complex b {1.2, 2};
	cout << b << endl;
	Complex c {b};
	cout << c << endl;

	cout << b+c << endl;
	cout << a*b + Complex{1, 2} << endl;
}

int main() {
	Complex c0 {0, 0};
	f();
	return 0;
}

#include <iostream>

using namespace std;

class Complex {
	double re, im;
public:
	Complex(double r, double i) : re {r}, im {i} {}
	Complex operator+(Complex);
	Complex operator*(Complex);
	friend ostream &operator<<(ostream &os, Complex c);
};

ostream &operator<<(ostream &os, Complex c) {
	os << c.re;
	os << ((c.im >= 0) ? "+" : "-");
	os << c.im << "*i";
	return os;
}

Complex Complex::operator+(Complex c) {
	return Complex{this->re+c.re, this->im+c.im};
}

Complex Complex::operator*(Complex c) {
	double r = this->re*c.re - this->im*c.im;
	double i = this->im*c.re + this->re*c.im;
	// This is OK, probably because this is considered
	// as initializer
	return {r, i};
}

void f() {
	Complex a = {1, 3.1};
	cout << a << endl;
	Complex b {1.2, 2};
	cout << b << endl;
	Complex c {b};
	cout << c << endl;

	cout << b+c << endl;
	cout << a*b + Complex{1, 2} << endl;
}

int main() {
	Complex c0 {0, 0};
	f();
	return 0;
}

Change to initilizer list construction

Change to initilizer list construction


/**
 * atom_types_init.cc
 *
 * Link Grammar Atom Types used during Viterbi parsing.
 *
 * Copyright (c) 2009 Linas Vepstas <linasvepstas@gmail.com>
 */

#include "opencog/viterbi/atom_types.definitions"

using namespace opencog;

// library initialization
#if defined(WIN32) && defined(_DLL)
namespace win {
#include <windows.h>
}

win::BOOL APIENTRY DllMain(win::HINSTANCE hinstDLL,  // handle to DLL module
                           win::DWORD fdwReason,     // reason for calling function
                           win::LPVOID lpvReserved)  // reserved
{
    System::setModuleHandle(hinstDLL);
    switch (fdwReason) {
        case DLL_PROCESS_ATTACH:
            #include "opencog/viterbi/atom_types.inheritance"
            break;
        case DLL_THREAD_ATTACH:
            break;
        case DLL_THREAD_DETACH:
            break;
        case DLL_PROCESS_DETACH:
            break;
    }
    return TRUE;
}
#elif __GNUC__
static __attribute__ ((constructor)) void viterbi_init(void)
{
    #include "opencog/viterbi/atom_types.inheritance"
}

static __attribute__ ((destructor)) void viterbi_fini(void)
{
}

#endif

/**
 * atom_types_init.cc
 *
 * Link Grammar Atom Types used during Viterbi parsing.
 *
 * Copyright (c) 2009, 2013 Linas Vepstas <linasvepstas@gmail.com>
 */

#include <opencog/server/Module.h>
#include "opencog/viterbi/atom_types.definitions"

using namespace opencog;

// library initialization
#if defined(WIN32) && defined(_DLL)
namespace win {
#include <windows.h>
}

win::BOOL APIENTRY DllMain(win::HINSTANCE hinstDLL,  // handle to DLL module
                           win::DWORD fdwReason,     // reason for calling function
                           win::LPVOID lpvReserved)  // reserved
{
    System::setModuleHandle(hinstDLL);
    switch (fdwReason) {
        case DLL_PROCESS_ATTACH:
            #include "opencog/viterbi/atom_types.inheritance"
            break;
        case DLL_THREAD_ATTACH:
            break;
        case DLL_THREAD_DETACH:
            break;
        case DLL_PROCESS_DETACH:
            break;
    }
    return TRUE;
}
#elif __GNUC__
static __attribute__ ((constructor)) void viterbi_init(void)
{
    #include "opencog/viterbi/atom_types.inheritance"
}

static __attribute__ ((destructor)) void viterbi_fini(void)
{
}

#endif

TRIVIAL_MODULE(ViterbiTypesModule)
DECLARE_MODULE(ViterbiTypesModule)

Use the new atom types module macro

Use the new atom types module macro

We need to define this as a valid module, so that loading can
happen, error-free.


Matrix2f M = Matrix2f::Random();
Matrix2f m;
m = M;
cout << "Here is the matrix m:" << endl << m << endl;
cout << "Now we want to replace m by its own transpose." << endl;
cout << "If we do m = m.transpose(), then m becomes:" << endl;
m = m.transpose() * 1;
cout << m << endl << "which is wrong!" << endl;
cout << "Now let us instead do m = m.transpose().eval(). Then m becomes" << endl;
m = M;
m = m.transpose().eval();
cout << m << endl << "which is right." << endl;

Matrix2f M = Matrix2f::Random();
Matrix2f m;
m = M;
cout << "Here is the matrix m:" << endl << m << endl;
cout << "Now we want to copy a column into a row." << endl;
cout << "If we do m.col(1) = m.row(0), then m becomes:" << endl;
m.col(1) = m.row(0);
cout << m << endl << "which is wrong!" << endl;
cout << "Now let us instead do m.col(1) = m.row(0).eval(). Then m becomes" << endl;
m = M;
m.col(1) = m.row(0).eval();
cout << m << endl << "which is right." << endl;

Make snippet run successfully again: the snippet for 'eval' was taking m=m.transpose() as an example of code that needs an explicit call to eval(), but that doesn't work anymore now that we have the clever assert detecting aliasing issues.


//===- llvm/unittest/Support/TimeValueTest.cpp - Time Value tests ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "llvm/Support/TimeValue.h"
#include <time.h>

using namespace llvm;
namespace {

TEST(TimeValue, time_t) {
  sys::TimeValue now = sys::TimeValue::now();
  time_t now_t = time(NULL);
  EXPECT_TRUE(abs(static_cast<long>(now_t - now.toEpochTime())) < 2);
}

}

//===- llvm/unittest/Support/TimeValueTest.cpp - Time Value tests ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "llvm/Support/TimeValue.h"
#include <time.h>

using namespace llvm;
namespace {

TEST(TimeValue, time_t) {
  sys::TimeValue now = sys::TimeValue::now();
  time_t now_t = time(NULL);
  EXPECT_TRUE(abs(static_cast<long>(now_t - now.toEpochTime())) < 2);
}

TEST(TimeValue, Win32FILETIME) {
  uint64_t epoch_as_filetime = 0x19DB1DED53E8000ULL;
  uint32_t ns = 765432100;
  sys::TimeValue epoch;

  // FILETIME has 100ns of intervals.
  uint64_t ft1970 = epoch_as_filetime + ns / 100;
  epoch.fromWin32Time(ft1970);

  // The "seconds" part in Posix time may be expected as zero.
  EXPECT_EQ(ns / 100, epoch.toPosixTime());

  // Confirm it reversible.
  EXPECT_EQ(ft1970, epoch.toWin32Time());
}

}

unittests/Support: Add TimeValue.Win32FILETIME, corresponding to r186374.

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


#include "GLPlatform.hpp"

void glPlatformInit()
{
#ifdef GL_PLATFORM_USING_WIN
  glewInit();
#endif
}

#include "GLPlatform.hpp"
#include <stdexcept>

void glPlatformInit()
{
#ifdef GL_PLATFORM_USING_WIN
  GLenum err = glewInit();
  if (GLEW_OK != err)
  {
    throw std::runtime_error("GLEW failed to initialize.");
  }
#endif
}

Add exception if GLEW fails to initialize.


#error Still to implement

string executable_path()
{
	char buffer[16 * 1024];

	int bytes = GetModuleFileName(NULL, buffer, sizeof(buffer));
	if (bytes == 0)
	{
		throw unable_to_find_executable_path{};
	}
	buffer[bytes] = '\0';
	string executable_path{buffer};

	return std::string{executable_path.cbegin(),
					   executable_path.cbegin() +
					   executable_path.find_last_of('/')};
}

#include <sdl_cpp/widgets/executable_path.h>
#include <string>
#include "Windows.h"
//#error Still to implement

using namespace ::std;

string executable_path()
{
	char buffer[16 * 1024];

	int bytes = GetModuleFileName(nullptr, buffer, sizeof(buffer));
	if (bytes == 0)
	{
		throw unable_to_find_executable_path{};
	}
	buffer[bytes] = '\0';
	string executable_path{buffer};

	return std::string{executable_path.cbegin(),
					   executable_path.cbegin() +
					   executable_path.find_last_of('\\')};
}

Add executable path on Windows

Add executable path on Windows


/**
* @file      BStringTests.cpp
* @copyright (c) 2014 by Petr Zemek (s3rvac@gmail.com) and contributors
* @license   BSD, see the @c LICENSE file for more details
* @brief     Tests for the BString class.
*/

#include <gtest/gtest.h>

#include "BString.h"

namespace bencoding {
namespace tests {

using namespace testing;

class BStringTests: public Test {};

TEST_F(BStringTests,
ValueReturnsCorrectValueAfterCreation) {
	auto i = BString::create("test");

	EXPECT_EQ("test", i->value());
}

TEST_F(BStringTests,
ValueReturnsCorrectValueAfterSet) {
	auto i = BString::create("test");
	i->setValue("other");

	EXPECT_EQ("other", i->value());
}

TEST_F(BStringTests,
LengthReturnsCorrectValue) {
	auto i = BString::create("test");

	EXPECT_EQ(4, i->length());
}

} // namespace tests
} // namespace bencoding

/**
* @file      BStringTests.cpp
* @copyright (c) 2014 by Petr Zemek (s3rvac@gmail.com) and contributors
* @license   BSD, see the @c LICENSE file for more details
* @brief     Tests for the BString class.
*/

#include <gtest/gtest.h>

#include "BString.h"

namespace bencoding {
namespace tests {

using namespace testing;

class BStringTests: public Test {};

TEST_F(BStringTests,
ValueReturnsCorrectValueAfterCreation) {
	auto s = BString::create("test");

	EXPECT_EQ("test", s->value());
}

TEST_F(BStringTests,
ValueReturnsCorrectValueAfterSet) {
	auto s = BString::create("test");
	s->setValue("other");

	EXPECT_EQ("other", s->value());
}

TEST_F(BStringTests,
LengthReturnsCorrectValue) {
	auto s = BString::create("test");

	EXPECT_EQ(4, s->length());
}

} // namespace tests
} // namespace bencoding

BString: Fix the names of variables in the tests.


// Copyright 2015 http://switchdevice.com

#include "Arduino.cc"
#include "EEPROM.cc"
#include "Serial.cc"
#include "SoftwareSerial.cc"
#include "serialHelper.cc"
#include "Spark.cc"
#include "WiFi.cc"
#include "Wire.cc"
#include "SPI.cc"
#include "OneWire.cc"

#include "IRremote.cc"

// Copyright 2015 http://switchdevice.com

#include "Arduino.cc"
#include "Serial.cc"
#include "serialHelper.cc"
#include "OneWire.cc"
#include "SoftwareSerial.cc"

/* At WiTraC we don't make use of any of the following mocks. They are therefore
 *  commented out to save precious build time
 */
//#include "EEPROM.cc"
//#include "Spark.cc"
//#include "WiFi.cc"
//#include "Wire.cc"
//#include "SPI.cc"
//#include "IRremote.cc"

Comment out unused mocks to save build time


#include "rastertext.hpp"

bool RasterText::loadTexture()
{
    return true;
}

#include "rastertext.hpp"

// FIXME: unimplemented
Font::Font(Font const &f)
{ }

Font::~Font()
{ }

Font &Font::operator=(Font const &f)
{
    return *this;
}

bool RasterText::loadTexture()
{
    return true;
}

Add placeholder font code for Windows

Add placeholder font code for Windows


/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2016] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/

#include <realm/util/interprocess_mutex.hpp>

#ifdef REALM_ROBUST_MUTEX_EMULATION

using namespace realm::util;

std::map<File::UniqueID, std::weak_ptr<InterprocessMutex::LockInfo>> InterprocessMutex::s_info_map;
Mutex InterprocessMutex::s_mutex;

#endif

/*************************************************************************
 *
 * Copyright 2016 Realm Inc.
 *
 * 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 <realm/util/interprocess_mutex.hpp>

#ifdef REALM_ROBUST_MUTEX_EMULATION

using namespace realm::util;

std::map<File::UniqueID, std::weak_ptr<InterprocessMutex::LockInfo>> InterprocessMutex::s_info_map;
Mutex InterprocessMutex::s_mutex;

#endif

Update header in recently added file.

Update header in recently added file.


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

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

// Disabled, http://crbug.com/30151.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Toolstrip) {
  ASSERT_TRUE(RunExtensionTest("toolstrip")) << 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 "chrome/browser/extensions/extension_apitest.h"

// Disabled, http://crbug.com/30151 (Linux and ChromeOS),
// http://crbug.com/35034 (others).
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Toolstrip) {
  ASSERT_TRUE(RunExtensionTest("toolstrip")) << message_;
}

Update bug reference link in ExtensionApiTest.Toolstrip

TBR=erikkay
TEST=no code change
BUG=30151, 35034

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

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


/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2020 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/base/platform_win.h"
#include "xenia/base/string.h"
#include "xenia/base/system.h"

namespace xe {

void LaunchWebBrowser(const std::string& url) {
  auto temp = xe::to_utf16(url);
  ShellExecuteW(nullptr, L"open", reinterpret_cast<LPCWSTR>(url.c_str()),
                nullptr, nullptr, SW_SHOWNORMAL);
}

void LaunchFileExplorer(const std::filesystem::path& url) {
  ShellExecuteW(nullptr, L"explore", url.c_str(), nullptr, nullptr,
                SW_SHOWNORMAL);
}

}  // namespace xe

/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2020 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/base/platform_win.h"
#include "xenia/base/string.h"
#include "xenia/base/system.h"

namespace xe {

void LaunchWebBrowser(const std::string& url) {
  auto temp = xe::to_utf16(url);
  ShellExecuteW(nullptr, L"open", reinterpret_cast<LPCWSTR>(temp.c_str()),
                nullptr, nullptr, SW_SHOWNORMAL);
}

void LaunchFileExplorer(const std::filesystem::path& url) {
  ShellExecuteW(nullptr, L"explore", url.c_str(), nullptr, nullptr,
                SW_SHOWNORMAL);
}

}  // namespace xe

[Base] Fix dangling pointer in LaunchWebBrowser.

[Base] Fix dangling pointer in LaunchWebBrowser. Fixes #1614.


// Copyright (c) 2015 Chaobin Zhang. All rights reserved.
// Use of this source code is governed by the BSD license that can be
// found in the LICENSE file.

#include "base/files/scoped_temp_dir.h"
#include "base/path_service.h"
#include "common/util.h"
#include "master/curl_helper.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace master {

TEST(CurlHelperTest, GetWithMD5) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());

  base::FilePath readme_file_path;
  PathService::Get(base::DIR_SOURCE_ROOT, &readme_file_path);
  readme_file_path = readme_file_path.AppendASCII("README.md");

  base::FilePath file_path = temp_dir.path().AppendASCII("tmp_file");
  CurlHelper curl_helper;
  const std::string kReadmeURL =
      "https://raw.githubusercontent.com/zhchbin/DN/master/README.md";
  EXPECT_EQ(curl_helper.Get(kReadmeURL, file_path),
            common::GetMd5Digest(readme_file_path));
}

}  // namespace master

// Copyright (c) 2015 Chaobin Zhang. All rights reserved.
// Use of this source code is governed by the BSD license that can be
// found in the LICENSE file.

#include "base/files/scoped_temp_dir.h"
#include "base/path_service.h"
#include "common/util.h"
#include "master/curl_helper.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace master {

TEST(CurlHelperTest, GetWithMD5) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());

  base::FilePath license_file_path;
  PathService::Get(base::DIR_SOURCE_ROOT, &license_file_path);
  license_file_path = license_file_path.AppendASCII("LICENSE");

  base::FilePath file_path = temp_dir.path().AppendASCII("tmp_file");
  CurlHelper curl_helper;
  const std::string klicenseURL =
      "https://raw.githubusercontent.com/zhchbin/DN/master/LICENSE";
  EXPECT_EQ(curl_helper.Get(klicenseURL, file_path),
            common::GetMd5Digest(license_file_path));
}

}  // namespace master

Use license file instead of readme.

[TEST] Use license file instead of readme.

Change of LICENSE is less than README.md.


/** @file
    @brief Implementation

    @date 2014

    @author
    Ryan Pavlik
    <ryan@sensics.com>
    <http://sensics.com>
*/

// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)

// Internal Includes
#include <ogvr/PluginKit/DeviceToken.h>

// Library/third-party includes
// - none

// Standard includes
// - none

namespace ogvr {
	DeviceToken::DeviceToken(std::string const& name);
	DeviceToken::~DeviceToken() {}

	AsyncDeviceToken * DeviceToken::asAsyncDevice() {
		return NULL;
	}

	SyncDeviceToken * DeviceToken::asSyncDevice() {
		return NULL;
	}
}

/** @file
    @brief Implementation

    @date 2014

    @author
    Ryan Pavlik
    <ryan@sensics.com>
    <http://sensics.com>
*/

// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)

// Internal Includes
#include <ogvr/PluginKit/DeviceToken.h>

// Library/third-party includes
// - none

// Standard includes
// - none

namespace ogvr {
DeviceToken::DeviceToken(std::string const &name) : m_name(name) {}
	DeviceToken::~DeviceToken() {}

	AsyncDeviceToken * DeviceToken::asAsyncDevice() {
		return NULL;
	}

	SyncDeviceToken * DeviceToken::asSyncDevice() {
		return NULL;
	}
}

Fix broken builds - stubs not stubby enough.


/***************************************************************************
 *  @file       main.cpp
 *  @author     Alan.W
 *  @date       02  Feb 2014
 *              13  Oct 2014
 *  @remark     This code is for the exercises from C++ Primer 5th Edition
 *  @note
 ***************************************************************************/
//!
//! Exercise 16.5:
//! Write a template version of the print function from § 6.2.4 (p. 217) that
//! takes a reference to an array and can handle arrays of any size and any
//! element type.
//!

#include <iostream>
#include <string>

/** @note
 *  1   any array is essentially a pointer, so the &ref here is a reference to pointer.
 *  2   size must be captured here to manage the loop.
 */
template<typename T, unsigned size>
void print(const T(&ref)[size])
{
    for (unsigned i = 0; i != size; ++i)
        std::cout << ref[i] << std::endl;
}

int main()
{
    std::string p[] = {"ssss","aaa","ssssss"};
    char c[] = {'a','b','c','d'};
    int  i[] = {1};
    print(i);
    print(c);
    print(p);

    std::cout << "\nexit normally\n";
    return 0;
}

/***************************************************************************
 *  @file       main.cpp
 *  @author     Alan.W
 *  @date       02  Feb 2014
 *              13  Oct 2014
 *  @remark     This code is for the exercises from C++ Primer 5th Edition
 *  @note
 ***************************************************************************/
//!
//! Exercise 16.5:
//! Write a template version of the print function from § 6.2.4 (p. 217) that
//! takes a reference to an array and can handle arrays of any size and any
//! element type.
//!

#include <iostream>
#include <string>

template<typename Arr>
void print(const Arr& a)
{
    for(const auto& elem : a)
        std::cout << elem << std::endl;
}

int main()
{
    std::string p[] = {"ssss","aaa","ssssss"};
    char c[] = {'a','b','c','d'};
    int  i[] = {1};
    print(i);
    print(c);
    print(p);

    std::cout << "\nexit normally\n";
    return 0;
}

Use range for instead of for

Use range for instead of for


#define BOOST_TEST_ALTERNATIVE_INIT_API
#include <boost/test/unit_test.hpp>
#include "ReservoirBenchmark.h"
#include "TMGas.h"
using namespace boost::unit_test;

void performMeasurement() {
    int iterations = 1000;
    ReservoirFactory *rFactory = new TMGas::Reservoir::Factory(16);
    reservoirBenchmark(rFactory,iterations);
    delete rFactory;
}

bool init_function() {
    for (int k=0; k<15; ++k) {
        framework::master_test_suite().add(BOOST_TEST_CASE(&performMeasurement),0,60);
    }
    framework::master_test_suite().p_name.value = "TMGasBenchmark";
    return true;
}

int main( int argc, char* argv[] )
{
    return ::boost::unit_test::unit_test_main( &init_function, argc, argv );
}

#define BOOST_TEST_ALTERNATIVE_INIT_API
#include <boost/test/unit_test.hpp>
#include "ReservoirBenchmark.h"
#include "TMGas.h"
using namespace boost::unit_test;

void performMeasurement() {
    int iterations = 100;
    ReservoirFactory *rFactory = new TMGas::Reservoir::Factory(16);
    reservoirBenchmark(rFactory,iterations);
    delete rFactory;
}

bool init_function() {
    for (int k=0; k<15; ++k) {
        framework::master_test_suite().add(BOOST_TEST_CASE(&performMeasurement),0,60);
    }
    framework::master_test_suite().p_name.value = "TMGasBenchmark";
    return true;
}

int main( int argc, char* argv[] )
{
    return ::boost::unit_test::unit_test_main( &init_function, argc, argv );
}

Reduce the size of the TMGas measurement by an order of magnitude.


#include "Renderer.hpp"
#include "../OpenGL/OpenGLRenderer.hpp"
#include "../Vulkan/VulkanRenderer.hpp"

Renderer::~Renderer() {

}

Renderer* Renderer::makeRenderer(BACKEND backend, Window & window){
    // Create and return backend.
    if(backend == BACKEND::OpenGL)
        return new OpenGLRenderer(window);

    else if(backend == BACKEND::Vulkan)
        return new VulkanRenderer(window);

    return nullptr;
}

void Renderer::render() {

}

Remove implementation of pure virtual function.


#include <QDesktopWidget>
#include "WindowMaximize.h"
#include "WebPage.h"
#include "WebPageManager.h"

WindowMaximize::WindowMaximize(WebPageManager *manager, QStringList &arguments, QObject *parent) : WindowCommand(manager, arguments, parent) {
}

void WindowMaximize::windowFound(WebPage *page) {
  QDesktopWidget *desktop = QApplication::desktop();
  QRect area = desktop->availableGeometry();
  page->resize(area.width(), area.height());
  finish(true);
}

Make sure to include QDesktopWidget

Make sure to include QDesktopWidget


/*
 * PartitionReader.cpp
 *
 *  Created on: 15.02.2013
 *      Author: Christian Staudt (christian.staudt@kit.edu)
 */

#include "PartitionReader.h"

namespace NetworKit {

Partition PartitionReader::read(std::string path) {

	std::ifstream file(path);

	// check if file readable
	if (!file) {
		throw std::runtime_error("invalid clustering file");
	}

	std::vector<index> temp;

	// push all cluster ids into vector in order of appearance
	std::string line;
	while(std::getline(file, line)) {
		index c = std::atoi(line.c_str());
		temp.push_back(c);
	}

	count n = temp.size();
	Partition zeta(n);

	#pragma omp parallel for
	for (node u = 0; u < n; ++u) {
		zeta[u] = temp[u];
	}

	return zeta;
}

} /* namespace NetworKit */

/*
 * PartitionReader.cpp
 *
 *  Created on: 15.02.2013
 *      Author: Christian Staudt (christian.staudt@kit.edu)
 */

#include "PartitionReader.h"

namespace NetworKit {

Partition PartitionReader::read(std::string path) {

	std::ifstream file(path);

	// check if file readable
	if (!file) {
		throw std::runtime_error("invalid clustering file");
	}

	Partition zeta(0);

	std::string line;
	index omega = 0;
	while(std::getline(file, line)) {
		index c = std::atoi(line.c_str());
		// extend the partition by one entry and store the cluster id
		zeta[zeta.extend()] = c;
		omega = std::max(c, omega);
	}

	zeta.setUpperBound(omega+1);

	return zeta;
}

} /* namespace NetworKit */

Simplify and fix the partition reader

Simplify and fix the partition reader

This fixes the partition reader to correctly set the upper bound of the
partition ids. Furthermore the partition reader is simplified to create
the partition directly in the partition instance instead of a separate
vector as the partition instance also simply expands a std::vector when
new nodes are added.


/*
 * Qumulus UML editor
 * Author: Frank Erens
 * Author: Randy Thiemann
 *
 */

#include "PackageShape.h"
#include <QtGui/QBrush>

QUML_BEGIN_NAMESPACE_UD

PackageShape::PackageShape(QuUK::Element* e,
        DiagramElement* p) :
        SelectableShape(e, p),
        mTabItem(new QGraphicsRectItem(0, 0, 30, 10, this)),
        mBodyItem(new QGraphicsRectItem(0, 10, 100, 50, this)) {
    mTabItem->setBrush(QBrush(Qt::white));
    mBodyItem->setBrush(QBrush(Qt::white));
    addToGroup(mTabItem);
    addToGroup(mBodyItem);
}

PackageShape::PackageShape(const PackageShape& c) :
        SelectableShape(c) {

}

void PackageShape::resize(double w, double h) {
     if(minimumSize().isValid()) {
        w = std::max(w, minimumSize().width());
        h = std::max(h, minimumSize().height());
    }

    mBodyItem->setRect(0, 10, w, h - 10);

    setSize({w, h});
}

QUML_END_NAMESPACE_UD

/*
 * Qumulus UML editor
 * Author: Frank Erens
 * Author: Randy Thiemann
 *
 */

#include "PackageShape.h"
#include <QtGui/QBrush>

QUML_BEGIN_NAMESPACE_UD

PackageShape::PackageShape(QuUK::Element* e,
        DiagramElement* p) :
        SelectableShape(e, p),
        mTabItem(new QGraphicsRectItem(0, 0, 30, 10, this)),
        mBodyItem(new QGraphicsRectItem(0, 10, 100, 50, this)) {
    constexpr int kPackageZOrdering = -2;
    mTabItem->setBrush(QBrush(Qt::white));
    mBodyItem->setBrush(QBrush(Qt::white));
    addToGroup(mTabItem);
    addToGroup(mBodyItem);
    setZValue(kPackageZOrdering);
}

PackageShape::PackageShape(const PackageShape& c) :
        SelectableShape(c) {}

void PackageShape::resize(double w, double h) {
     if(minimumSize().isValid()) {
        w = std::max(w, minimumSize().width());
        h = std::max(h, minimumSize().height());
    }

    mBodyItem->setRect(0, 10, w, h - 10);

    setSize({w, h});
}

QUML_END_NAMESPACE_UD

Change default Z-order for packages.

Change default Z-order for packages.


#include "ofMain.h"
#include "ofApp.h"

//========================================================================
int main( ){
    ofGLWindowSettings settings;
    settings.setGLVersion(3, 2); // Using programmable renderer. Comment out this line to use the 'standard' GL renderer.
    settings.width = 1024;
    settings.height = 768;
    ofCreateWindow(settings);
    ofRunApp(new ofApp());
}

#include "ofMain.h"
#include "ofApp.h"

//========================================================================
int main( ){
    ofWindowSettings winSettings;
    winSettings.setSize(1024, 768);
    ofGLWindowSettings glSettings(winSettings);
    glSettings.setGLVersion(3, 2); // Using programmable renderer. Comment out this line to use the 'standard' GL renderer.
    ofCreateWindow(glSettings);
    ofRunApp(new ofApp());
}

Update example for openFrameworks 0.11.0


/* Copyright (c) 2006, NIF File Format Library and Tools
All rights reserved.  Please see niflib.h for licence. */

#include "SkinPartition.h"
using namespace Niflib;

//Constructor
SkinPartition::SkinPartition() : numVertices((ushort)0), numTriangles((ushort)0), numBones((ushort)0), numStrips((ushort)0), numWeightsPerVertex((ushort)0), hasVertexMap(false), hasVertexWeights(false), hasStrips(false), hasBoneIndices(false) {};

//Destructor
SkinPartition::~SkinPartition() {};

// needs to be moved elsewhere but this will work for now
ushort SkinPartition::CalcNumTriangles() const {
   ushort size = 0;
   if (stripLengths.empty()) {
      size = (ushort)triangles.size();
   } else {
      for (size_t i=0; i<stripLengths.size(); ++i)
         size += (ushort)stripLengths[i];
      size -= 2;
   }
   return size;
}

/* Copyright (c) 2006, NIF File Format Library and Tools
All rights reserved.  Please see niflib.h for licence. */

#include "SkinPartition.h"
using namespace Niflib;

//Constructor
SkinPartition::SkinPartition() : numVertices((ushort)0), numTriangles((ushort)0), numBones((ushort)0), numStrips((ushort)0), numWeightsPerVertex((ushort)0), hasVertexMap(false), hasVertexWeights(false), hasStrips(false), hasBoneIndices(false) {};

//Destructor
SkinPartition::~SkinPartition() {};

// needs to be moved elsewhere but this will work for now
ushort SkinPartition::CalcNumTriangles() const {
   ushort size = 0;
   if (stripLengths.empty()) {
      size = (ushort)triangles.size();
   } else {
      for (size_t i=0; i<stripLengths.size(); ++i)
         size += ((ushort)stripLengths[i] - 2);
   }
   return size;
}

Fix length calc based on m444x's suggestion.


#include "socketmanager.h"

std::shared_ptr<Socket> SocketManager::getSocket(const std::string& socketType) {
	void* sockFile = dlopen(("sockets/" + socketType + ".so").c_str(), RTLD_NOW);
	if (sockFile == nullptr)
		throw SocketLoadFailed (dlerror());
	void* spawnFunc = dlsym(sockFile, "spawn");
	if (spawnFunc == nullptr) {
		const char* loadError = dlerror();
		dlclose(sockFile);
		if (loadError)
			throw SocketLoadFailed (loadError);
		throw SocketLoadFailed ("The spawn symbol has been set to null, but it must be a valid function.");
	}
	Socket*(*spawnCallFunc)() = static_cast<Socket*(*)()> (spawnFunc);
	std::shared_ptr<Socket> newSocket (spawnCallFunc(), std::bind(&SocketManager::removeSocket, this, socketType, sockFile, std::placeholders::_1));
	if (sockAPIVersions.find(newSocket->apiVersion()) == sockAPIVersions.end())
		throw SocketAPIMismatch ();
	return newSocket;
}

void SocketManager::removeSocket(const std::string& socketType, void* sockFile, Socket* deletingSocket) {
	delete deletingSocket;
	dlclose(sockFile);
	LogManager* logger = LogManager::getHandle();
	logger->log(LOG_DEBUG, "socket-request", "A " + socketType + " socket has been unloaded.");
}

#include "socketmanager.h"

std::shared_ptr<Socket> SocketManager::getSocket(const std::string& socketType) {
	void* sockFile = dlopen(("sockets/" + socketType + ".so").c_str(), RTLD_NOW);
	if (sockFile == nullptr)
		throw SocketLoadFailed (dlerror());
	void* spawnFunc = dlsym(sockFile, "spawn");
	if (spawnFunc == nullptr) {
		const char* loadError = dlerror();
		dlclose(sockFile);
		if (loadError)
			throw SocketLoadFailed (loadError);
		throw SocketLoadFailed ("The spawn symbol has been set to null, but it must be a valid function.");
	}
	Socket*(*spawnCallFunc)() = (Socket*(*)()) spawnFunc;
	std::shared_ptr<Socket> newSocket (spawnCallFunc(), std::bind(&SocketManager::removeSocket, this, socketType, sockFile, std::placeholders::_1));
	if (sockAPIVersions.find(newSocket->apiVersion()) == sockAPIVersions.end())
		throw SocketAPIMismatch ();
	return newSocket;
}

void SocketManager::removeSocket(const std::string& socketType, void* sockFile, Socket* deletingSocket) {
	delete deletingSocket;
	dlclose(sockFile);
	LogManager* logger = LogManager::getHandle();
	logger->log(LOG_DEBUG, "socket-request", "A " + socketType + " socket has been unloaded.");
}

Fix socket manager loader to use a C-style cast on the function pointer


#include <stdio.h>
#include <Halide.h>

using namespace Halide;

int main(int argc, char **argv) {
    Var x, y;
    Var xo, xi, yo, yi;

    Func f, g;

    printf("Defining function...\n");

    f(x, y) = cast<float>(x);
    g(x, y) = f(x+1, y) + f(x-1, y);

    Target target = get_jit_target_from_environment();
    if (target.has_gpu_feature()) {
        Var xi, yi;
        g.gpu_tile(x, y, 8, 8, GPU_DEFAULT);
        f.compute_at(g, Var("blockidx")).gpu_threads(x, y, GPU_DEFAULT);
    }

    printf("Realizing function...\n");

    Image<float> im = g.realize(32, 32, target);

    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < 32; j++) {
            if (im(i,j) != 2*i) {
                printf("im[%d, %d] = %f\n", i, j, im(i,j));
                return -1;
            }
        }
    }

    printf("Success!\n");
    return 0;
}

#include <stdio.h>
#include <Halide.h>

using namespace Halide;

int main(int argc, char **argv) {
    Var x, y;
    Var xo, xi, yo, yi;

    Func f, g;

    printf("Defining function...\n");

    f(x, y) = cast<float>(x);
    g(x, y) = f(x+1, y) + f(x-1, y);

    Target target = get_jit_target_from_environment();
    // shared memory not currently working in OpenCL
    if (target.features & Target::CUDA) {
        Var xi, yi;
        g.gpu_tile(x, y, 8, 8, GPU_CUDA);
        f.compute_at(g, Var("blockidx")).gpu_threads(x, y, GPU_CUDA);
    }

    printf("Realizing function...\n");

    Image<float> im = g.realize(32, 32, target);

    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < 32; j++) {
            if (im(i,j) != 2*i) {
                printf("im[%d, %d] = %f\n", i, j, im(i,j));
                return -1;
            }
        }
    }

    printf("Success!\n");
    return 0;
}

Disable shared memory test for OpenCL until bugginess is resolved.


/*
 * Copyright (c) 2007 Digital Bazaar, Inc.  All rights reserved.
 */

#include <iostream>

#include "db/io/OStreamOutputStream.h"

using namespace std;
using namespace db::io;
using namespace db::rt;

OStreamOutputStream* OStreamOutputStream::mStdoutStream =
   new OStreamOutputStream(&cout);

OStreamOutputStream::OStreamOutputStream(ostream* stream)
{
   // store ostream
   mStream = stream;
}

OStreamOutputStream::~OStreamOutputStream()
{
}

bool OStreamOutputStream::write(const char* b, int length)
{
   bool rval = false;

   // do write
   mStream->write(b, length);

   // see if a failure has occurred
   if(mStream->fail())
   {
      Exception::setLast(new IOException("Could not write to ostream!"));
   }
   else
   {
      rval = true;
   }

   return rval;
}

OStreamOutputStream* OStreamOutputStream::getStdoutStream()
{
   return sStdoutStream;
}

/*
 * Copyright (c) 2007 Digital Bazaar, Inc.  All rights reserved.
 */

#include <iostream>

#include "db/io/OStreamOutputStream.h"

using namespace std;
using namespace db::io;
using namespace db::rt;

OStreamOutputStream* OStreamOutputStream::sStdoutStream =
   new OStreamOutputStream(&cout);

OStreamOutputStream::OStreamOutputStream(ostream* stream)
{
   // store ostream
   mStream = stream;
}

OStreamOutputStream::~OStreamOutputStream()
{
}

bool OStreamOutputStream::write(const char* b, int length)
{
   bool rval = false;

   // do write
   mStream->write(b, length);

   // see if a failure has occurred
   if(mStream->fail())
   {
      Exception::setLast(new IOException("Could not write to ostream!"));
   }
   else
   {
      rval = true;
   }

   return rval;
}

OStreamOutputStream* OStreamOutputStream::getStdoutStream()
{
   return sStdoutStream;
}

Use s prefix for static class vars

Use s prefix for static class vars


#include <esp_log.h>
#include <FreeRTOS.h>
#include <string>
#include <Task.h>
#include <I2C.h>

#include "sdkconfig.h"

#define SDA_PIN 25
#define SCL_PIN 26

//static char tag[] = "task_cpp_utils";

class I2CScanner: public Task {
	void run(void *data) override {
		I2C i2c;
		i2c.init((gpio_num_t)SDA_PIN, (gpio_num_t)SCL_PIN);
		i2c.scan();
	} // End run
};

static I2CScanner i2cScanner = I2CScanner();

void task_i2c_scanner(void *ignore) {
	i2cScanner.start();
	FreeRTOS::deleteTask();
}

#include <esp_log.h>
#include <FreeRTOS.h>
#include <string>
#include <Task.h>
#include <I2C.h>

#include "sdkconfig.h"

#define DEVICE_ADDRESS 0
#define SDA_PIN 25
#define SCL_PIN 26

//static char tag[] = "task_cpp_utils";

class I2CScanner: public Task {
	void run(void *data) override {
		I2C i2c;
		i2c.init((uint8_t)DEVICE_ADDRESS, (gpio_num_t)SDA_PIN, (gpio_num_t)SCL_PIN);
		i2c.scan();
	} // End run
};

static I2CScanner i2cScanner = I2CScanner();

void task_i2c_scanner(void *ignore) {
	i2cScanner.start();
	FreeRTOS::deleteTask();
}

Fix params passed to i2c.init() to include DEVICE_ADDRESS in the first position. Otherwise SDA becomes SCL_PIN and SCL becomes Default.


#include "phonevalidator.h"

PhoneValidator::PhoneValidator(QObject *parent) :
    QValidator(parent)
{
}

QValidator::State PhoneValidator::validate(QString &input, int &pos) const
{
    //DDD
    QRegExp ddd("(\\d{2})+");
    if (ddd.exactMatch(input))
    {
        input.insert(input.length(), ") ");
        input.insert(0, "(");
        pos = input.length();
    }

    //Slash
    QRegExp slash("\\(\\d{2}\\)\\s*\\d{4}");
    if (slash.exactMatch(input))
    {
        input.insert(input.length(), "-");
        pos = input.length();
    }

    //Separator
    QRegExp sep("[\\(]{0,1}[\\d]\{0,2}[\\)]{0,1}\\s*\\d*[\\-]{0,1}\\d*");

    if (sep.exactMatch(input))
        return QValidator::Acceptable;

    return QValidator::Invalid;
}

bool PhoneValidator::isValid(QString str)
{
    QRegExp sep("[\\(]{0,1}[\\d]\{0,2}[\\)]{0,1}\\s*\\d*[\\-]{0,1}\\d*");
    return sep.exactMatch(str);
}

#include "phonevalidator.h"

PhoneValidator::PhoneValidator(QObject *parent) :
    QValidator(parent)
{
}

QValidator::State PhoneValidator::validate(QString &input, int &pos) const
{
    //DDD
    QRegExp ddd("(\\d{2})+");
    if (ddd.exactMatch(input))
    {
        input.insert(input.length(), ") ");
        input.insert(0, "(");
        pos = input.length();
    }

    //Slash
    QRegExp slash("\\(\\d{2}\\)\\s{0,1}\\d{5}");
    if (slash.exactMatch(input))
    {
        input.insert(input.length()-1, "-");
        pos = input.length();
    }

    //Separator
    QRegExp sep("[\\(]{0,1}[\\d]\{0,2}[\\)]{0,1}\\s{0,1}\\d*-{0,1}\\d*");

    if (sep.exactMatch(input))
        return QValidator::Acceptable;

    return QValidator::Invalid;
}

bool PhoneValidator::isValid(QString str)
{
    QRegExp sep("[\\(]{0,1}[\\d]\{0,2}[\\)]{0,1}\\s*\\d*[\\-]{0,1}\\d*");
    return sep.exactMatch(str);
}

Fix bug when deletig phone

Fix bug when deletig phone


/* Test program to test the thread callbacks
*/

#include <iostream>
#include "SDL.hh"
using namespace RAGE;

Logger testlog("testThread");

class ObjectWithThreadCall
{
	public:

	int threadcall(void* args)
	{
		testlog << nl << " --- Thread " << SDL::getCurrentThreadID() << "called --- " << std::endl;
		return 0;
	}

};

int main(int argc, char *argv[])
{
	testlog.enableFileLog("testThread.log");
	testlog << nl<<"SDL init...";

	SDL::App::getInstance();

	testlog << nl<<"Creating instance";
	ObjectWithThreadCall obj;

	testlog << nl<<"Creating instance timer";
	SDL::Thread<ObjectWithThreadCall> thread;

	thread.setThreadCall(&obj,&ObjectWithThreadCall::threadcall,(void*)NULL);

	thread.run();

	testlog << nl<<"Waiting for thread to finish" << std::endl;
	thread.wait();

	return 0;
}

/* Test program to test the thread callbacks
*/

#include <iostream>
#include "SDL.hh"
using namespace RAGE;

Logger testlog("testThread");

class ObjectWithThreadCall
{
	public:
	ObjectWithThreadCall() {}

	int threadcall(void* args)
	{
		testlog << nl << " --- Thread " << SDL::getCurrentThreadID() << "called. Counting from 0 to 20000 --- " << std::endl;
		for (int i = 0; i < 20000; i++)
		{
			testlog << nl << "Iteration N" << i << std::endl;
		}
		return 0;
	}

};

int main(int argc, char *argv[])
{
	testlog.enableFileLog("testThread.log");
	testlog << nl<<"SDL init...";

	SDL::App::getInstance();

	testlog << nl<<"Creating instance";
	ObjectWithThreadCall * obj = new ObjectWithThreadCall();

	testlog << nl<<"Creating instance timer";
	SDL::Thread<ObjectWithThreadCall>* thread = new SDL::Thread<ObjectWithThreadCall>();

	thread->setThreadCall(obj,&ObjectWithThreadCall::threadcall,(void*)NULL);

	thread->run();

	testlog << nl<<"Waiting for thread" << std::endl;
	thread->wait();
	SDL::Delay(3000);
	testlog << nl <<"Killing thread: After That No Iteration Should Be Present" << std::endl;
	thread->kill();
	SDL::Delay(3000);
	return 0;
}

Update Test Thread to show that wait() and kill() are not working as expected


#include "utils/progressBar.h"
#include <iostream>
#include <glog/logging.h>

using namespace std;

const std::string ProgressBar::BEGINNING = "[";
const std::string ProgressBar::END = "]";
const std::string ProgressBar::FILLER = "-";
const size_t ProgressBar::LENGTH = 50;

ProgressBar::ProgressBar()
    : mProgress(0)
{}

void ProgressBar::setProgress(float progress) {
    mProgress = progress;
}

void ProgressBar::print() const {
    cout << "\r" << BEGINNING;

    const int amountOfFiller = static_cast<int>(mProgress * LENGTH);
    for (size_t i = 0; i < amountOfFiller; i++) {
        cout << FILLER;
    }

    LOG_IF(ERROR, amountOfFiller > LENGTH) << "Bad size";
    const int remaningSpace = LENGTH - amountOfFiller;
    for (size_t i = 0; i < remaningSpace; i++) {
        cout << " ";
    }

    cout << END
        << static_cast<int>(mProgress * 100) << "%"
        << flush;
}

#include "utils/progressBar.h"
#include <iostream>
#include <cmath>
#include <glog/logging.h>

using namespace std;

const std::string ProgressBar::BEGINNING = "[";
const std::string ProgressBar::END = "]";
const std::string ProgressBar::FILLER = "-";
const size_t ProgressBar::LENGTH = 50;

ProgressBar::ProgressBar()
    : mProgress(0)
{}

void ProgressBar::setProgress(float progress) {
    mProgress = progress;
}

void ProgressBar::print() const {
    cout << "\r" << BEGINNING;

    const int amountOfFiller = static_cast<int>(mProgress * LENGTH);
    for (size_t i = 0; i < amountOfFiller; i++) {
        cout << FILLER;
    }

    LOG_IF(ERROR, amountOfFiller > LENGTH) << "Bad size";
    const int remaningSpace = LENGTH - amountOfFiller;
    for (size_t i = 0; i < remaningSpace; i++) {
        cout << " ";
    }

    cout << END
        << round(mProgress * 100) << "%"
        << flush;
}

Fix progress bar rounding issue

Fix progress bar rounding issue


#include "framework/applicationcontext.hh"
#include "framework/clientcode.hh"

using Framework::ApplicationContext;
using Framework::ClientCode;
using Framework::LoadClientCode;

using System::thread;

int applicationMain()
{
    ClientCode clientCode = LoadClientCode();

    ApplicationContext applicationContext;

    clientCode.ApplicationThreadEntry(&applicationContext);

    return 0;
}

#include "framework/applicationcontext.hh"
#include "framework/clientcode.hh"

using Framework::ApplicationContext;
using Framework::ClientCode;
using Framework::LoadClientCode;

int applicationMain()
{
    ClientCode clientCode = LoadClientCode();

    ApplicationContext applicationContext;

    clientCode.ApplicationThreadEntry(&applicationContext);

    return 0;
}

Remove unused reference to threads

Remove unused reference to threads


#include <QActiveResource.h>
#include <QDebug>

int main()
{
    qDebug() << getenv("AR_BASE");
    QActiveResource::Resource resource(QUrl(getenv("AR_BASE")), getenv("AR_RESOURCE"));

    const QString field = getenv("AR_FIELD");

    for(int i = 0; i < 100; i++)
    {
        qDebug() << i;
        foreach(QActiveResource::Record record, resource.find())
        {
            qDebug() << record[field].toString();
        }
    }

    return 0;
}

#include <QActiveResource.h>
#include <QDebug>

int main()
{
    Q_ASSERT(getenv("AR_BASE") && getenv("AR_RESOURCE") && getenv("AR_FIELD"));

    qDebug() << getenv("AR_BASE");
    QActiveResource::Resource resource(QUrl(getenv("AR_BASE")), getenv("AR_RESOURCE"));

    const QString field = getenv("AR_FIELD");

    for(int i = 0; i < 100; i++)
    {
        qDebug() << i;
        foreach(QActiveResource::Record record, resource.find())
        {
            qDebug() << record[field].toString();
        }
    }

    return 0;
}

Make sure the env variables are set

Make sure the env variables are set


#include "response_stream.h"

void rs::httpserver::ResponseStream::Flush() {
    socket_->Flush();
}

int rs::httpserver::ResponseStream::Write(const Stream::byte* buffer, int offset, int count) {
    auto written = 0;

    while (written < count) {
        auto sentBytes = socket_->Send(buffer + written, count - written);
        if (sentBytes <= 0) {
            throw SocketWriteException();
        }

        written += sentBytes;
        position_ += sentBytes;
        length_ += sentBytes;
    }

    return written;
}

#include "response_stream.h"

void rs::httpserver::ResponseStream::Flush() {
    socket_->Flush();
}

int rs::httpserver::ResponseStream::Write(const Stream::byte* buffer, int offset, int count) {
    auto written = 0;

    while (written < count) {
        auto sentBytes = socket_->Send(buffer + offset + written, count - written);
        if (sentBytes <= 0) {
            throw SocketWriteException();
        }

        written += sentBytes;
        position_ += sentBytes;
        length_ += sentBytes;
    }

    return written;
}

Fix response stream writes where we have a buffer offset


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

#include "SkColorMatrixFilter.h"

static SkScalar byte_to_scale(U8CPU byte) {
    if (0xFF == byte) {
        // want to get this exact
        return 1;
    } else {
        return byte * 0.00392156862745f;
    }
}

SkColorFilter* SkColorMatrixFilter::CreateLightingFilter(SkColor mul, SkColor add) {
    SkColorMatrix matrix;
    matrix.setScale(byte_to_scale(SkColorGetR(mul)),
                    byte_to_scale(SkColorGetG(mul)),
                    byte_to_scale(SkColorGetB(mul)),
                    1);
    matrix.postTranslate(SkIntToScalar(SkColorGetR(add)),
                         SkIntToScalar(SkColorGetG(add)),
                         SkIntToScalar(SkColorGetB(add)),
                         0);
    return SkColorMatrixFilter::Create(matrix);
}

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

#include "SkColorMatrixFilter.h"

static SkScalar byte_to_scale(U8CPU byte) {
    if (0xFF == byte) {
        // want to get this exact
        return 1;
    } else {
        return byte * 0.00392156862745f;
    }
}

SkColorFilter* SkColorMatrixFilter::CreateLightingFilter(SkColor mul, SkColor add) {
    if (0 == add) {
        return SkColorFilter::CreateModeFilter(mul | SK_ColorBLACK,
                                               SkXfermode::Mode::kModulate_Mode);
    }
    SkColorMatrix matrix;
    matrix.setScale(byte_to_scale(SkColorGetR(mul)),
                    byte_to_scale(SkColorGetG(mul)),
                    byte_to_scale(SkColorGetB(mul)),
                    1);
    matrix.postTranslate(SkIntToScalar(SkColorGetR(add)),
                         SkIntToScalar(SkColorGetG(add)),
                         SkIntToScalar(SkColorGetB(add)),
                         0);
    return SkColorMatrixFilter::Create(matrix);
}

Simplify LightingFilter in add-free case am: 0698300cc5 am: a184d5e49d
am: 7e02270397

* commit '7e0227039795fdc9891b14697f54b888d7f69fb6':
  Simplify LightingFilter in add-free case

Change-Id: I18f77ece7ae91da4965af29c4a2bf779d8a180c4


// Copyright (c) 2006-2008 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/thread_local.h"

#include <pthread.h>

#include "base/logging.h"

namespace base {

// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
  int error = pthread_key_create(&slot, NULL);
  CHECK(error == 0);
}

// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
  int error = pthread_key_delete(slot);
  DCHECK(error == 0);
}

// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
  return pthread_getspecific(slot_);
}

// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
  int error = pthread_setspecific(slot, value);
  CHECK(error == 0);
}

}  // namespace base

// Copyright (c) 2006-2008 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/thread_local.h"

#include <pthread.h>

#include "base/logging.h"

namespace base {

// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
  int error = pthread_key_create(&slot, NULL);
  CHECK(error == 0);
}

// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
  int error = pthread_key_delete(slot);
  DCHECK(error == 0);
}

// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
  return pthread_getspecific(slot);
}

// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
  int error = pthread_setspecific(slot, value);
  CHECK(error == 0);
}

}  // namespace base

Fix a typo that broke the posix build.

Fix a typo that broke the posix build.

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

Former-commit-id: 0d33ccade6de3e9eac09e0eb0a9092742762cbe9


//
//  application_context.cpp
//  usbtest
//
//  Created by Kristoffer Andersen on 13/07/15.
//  Copyright (c) 2015 Monolit ApS. All rights reserved.
//

#include "application_context.h"
#include <display_painter.h>

extern "C" {
#include <project.h>
}

using namespace mono;

ApplicationContext ApplicationContext::singleton;
IApplicationContext *IApplicationContext::Instance = NULL;

ApplicationContext::ApplicationContext() : dispController()
{
    PWM_Start();
    PWM_WriteCompare2(0);

    IApplicationContext::Instance = this;
    displayController = &dispController;

}

int ApplicationContext::exec()
{

}

void ApplicationContext::setMonoApplication(mono::IApplication *monoApp)
{
    this->application = monoApp;
    mono::IApplicationContext::Instance->displayController->init();

    monoApp->monoWakeFromReset();
}

//
//  application_context.cpp
//  usbtest
//
//  Created by Kristoffer Andersen on 13/07/15.
//  Copyright (c) 2015 Monolit ApS. All rights reserved.
//

#include "application_context.h"
#include "application_controller_interface.h"
#include <display_painter.h>

extern "C" {
#include <project.h>
}

using namespace mono;

ApplicationContext ApplicationContext::singleton;
IApplicationContext *IApplicationContext::Instance = NULL;

ApplicationContext::ApplicationContext() : dispController()
{
    PWM_Start();
    PWM_WriteCompare2(0);

    IApplicationContext::Instance = this;
    displayController = &dispController;
}

int ApplicationContext::exec()
{
    return 0;
}

void ApplicationContext::setMonoApplication(mono::IApplication *monoApp)
{
    this->application = monoApp;
    mono::IApplicationContext::Instance->displayController->init();

    monoApp->monoWakeFromReset();
}

Fix compile error in GCC 5.

Fix compile error in GCC 5.


#include "stdafx.h"
#include "CppUnitTest.h"

#include "datastore.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
using DataStore = You::DataStore::DataStore;

namespace YouDataStoreTests {
TEST_CLASS(DataStoreApiTest) {
public:
	TEST_METHOD(DataStore_Post_Basic_Test) {
		You::DataStore::DataStore sut;
		bool result = sut.post(0, DataStore::STask());
		Assert::IsTrue(result);
	}

	TEST_METHOD(DataStore_Post_DuplicateId_Test) {
		You::DataStore::DataStore sut;
		sut.post(0, DataStore::STask());
		bool result = sut.post(0, DataStore::STask());
		Assert::IsFalse(result);
	}
};
}  // namespace YouDataStoreTests

#include "stdafx.h"
#include "CppUnitTest.h"

#include "datastore.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
using DataStore = You::DataStore::DataStore;

namespace YouDataStoreTests {
TEST_CLASS(DataStoreApiTest) {
public:
	DataStore sut;

	TEST_METHOD(DataStore_Post_Basic_Test) {
		bool result = sut.post(0, DataStore::STask());
		Assert::IsTrue(result);
	}

	TEST_METHOD(DataStore_Post_DuplicateId_Test) {
		sut.post(0, DataStore::STask());
		bool result = sut.post(0, DataStore::STask());
		Assert::IsFalse(result);
	}

	TEST_METHOD(DataStore_Put_Basic_Test) {
		sut.post(0, DataStore::STask());
		bool result = sut.put(0, DataStore::STask());
		Assert::IsTrue(result);
	}
};
}  // namespace YouDataStoreTests

Add test for put method

Add test for put method


#include "settingsview.h"
#include "ui_settings.h"

SettingsView::SettingsView(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SettingsView)
{
    ui->setupUi(this);
    QSettings settings;
    int syncingPreference = settings.value("syncingPreference", QVariant(static_cast<int>(SyncOptions::MANUAL_ONLY))).toInt();

    QStringList syncingOptions({
                                   "Manual Only",  // SyncOptions::MANUAL_ONLY
                                   "On Startup (Always)",  // SyncOptions::ON_STARTUP
                                   "On Startup (WiFi)",  // SyncOptions::WIFI
                               });
    ui->comboBox->addItems(syncingOptions);
    ui->comboBox->setCurrentIndex(syncingPreference);
}

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

void SettingsView::on_pushButton_2_clicked()
{
    emit backButtonClicked();
}

void SettingsView::on_pushButton_clicked()
{
    emit syncButtonClicked();
}

void SettingsView::on_comboBox_currentIndexChanged(int index)
{
    QSettings settings;
    settings.setValue("syncingPreference", index);
    settings.sync();
}

void SettingsView::updateLastSync()
{
    QSettings settings;
    ui->label->setText(settings.value("lastUpdate").toString());
}

#include "settingsview.h"
#include "ui_settings.h"

SettingsView::SettingsView(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SettingsView)
{
    ui->setupUi(this);
    QSettings settings;
    int syncingPreference = settings.value("syncingPreference", QVariant(static_cast<int>(SyncOptions::MANUAL_ONLY))).toInt();

    QStringList syncingOptions({
                                   "Manual Only",  // SyncOptions::MANUAL_ONLY
                                   "On Startup (Always)",  // SyncOptions::ON_STARTUP
                                   "On Startup (WiFi)",  // SyncOptions::WIFI
                               });
    ui->comboBox->addItems(syncingOptions);
    ui->comboBox->setItemData(2, QVariant(0), Qt::UserRole - 1);  // Horrible hack according to peppe
    ui->comboBox->setCurrentIndex(syncingPreference);
}

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

void SettingsView::on_pushButton_2_clicked()
{
    emit backButtonClicked();
}

void SettingsView::on_pushButton_clicked()
{
    emit syncButtonClicked();
}

void SettingsView::on_comboBox_currentIndexChanged(int index)
{
    QSettings settings;
    settings.setValue("syncingPreference", index);
    settings.sync();
}

void SettingsView::updateLastSync()
{
    QSettings settings;
    ui->label->setText(settings.value("lastUpdate").toString());
}

Disable wireless entry in combobox for now


// RUN: clang-cc -emit-llvm-only -verify %s
// PR5454

class X {static void * operator new(unsigned long size) throw(); X(int); };
int a(), b();
void b(int x)
{
  new X(x ? a() : b());
}

// RUN: clang-cc -emit-llvm-only -verify %s
// PR5454
#include <stddef.h>

class X {static void * operator new(size_t size) throw(); X(int); };
int a(), b();
void b(int x)
{
  new X(x ? a() : b());
}

Make test more platform independent.

Make test more platform independent.

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


#include <cstdlib>
#include <iostream>

int main() {
#ifdef __APPLE__
  const char* name = "DYLD_LIBRARY_PATH";
#else
  const char* name = "LD_LIBRARY_PATH";
#endif

  const char* cetLDPathValue = getenv("CETD_LIBRARY_PATH");
  int res = setenv("DYLD_LIBRARY_PATH", cetLDPathValue, 1);

  const char* localLDPathValue = getenv(name);

  if(strcmp(localLDPathValue,cetLDPathValue) != 0) {
    return 1;
  }
  std::cout << localLDPathValue << std::endl;

  return 0;
}

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

int main() {
#ifdef __APPLE__
  const char* name = "DYLD_LIBRARY_PATH";
#else
  const char* name = "LD_LIBRARY_PATH";
#endif

  const char* cetLDPathValue = getenv("CETD_LIBRARY_PATH");
  int res = setenv("DYLD_LIBRARY_PATH", cetLDPathValue, 1);

  const char* localLDPathValue = getenv(name);

  if(strcmp(localLDPathValue,cetLDPathValue) != 0) {
    return 1;
  }
  std::cout << localLDPathValue << std::endl;

  return 0;
}

Add missing header on Linux

Add missing header on Linux


#include "GeometryObject.h"

GeometryObject::GeometryObject() {

}

GeometryObject::GeometryObject(const std::vector<Point3D>& vertices, const std::vector<uint8_t>& indices)
  : m_vertices(vertices), m_indices(indices){

}

GeometryObject::~GeometryObject() {

}

const std::vector<Triangle3D> GeometryObject::tessellate() const {
  //TODO: actual tessellation using vertices and indices

  return std::vector<Triangle3D> {
    Triangle3D(
      Point3D(-5.0f, 0.0f, 0.0f),
      Point3D(0.0f, 5.0f, 0.0f),
      Point3D(5.0f, 0.0f, 0.0f)
    )
  };
}

#include "GeometryObject.h"

GeometryObject::GeometryObject() {
  m_color = RGBColor(1, 0, 0);

}

GeometryObject::GeometryObject(const std::vector<Point3D>& vertices, const std::vector<uint8_t>& indices)
  : m_vertices(vertices), m_indices(indices){
  m_color = RGBColor(1, 0, 0);
}

GeometryObject::~GeometryObject() {

}

const std::vector<Triangle3D> GeometryObject::tessellate() const {
  //TODO: actual tessellation using vertices and indices

  return std::vector<Triangle3D> {
    Triangle3D(
      Point3D(-25.0f, 0.0f, 20.0f),
      Point3D(0.0f, 25.0f, 20.0f),
      Point3D(25.0f, 0.0f, 20.0f)
    )
  };
}

Initialize object color to red for testing purposes


// Copyright 2015 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/banners/app_banner_manager_desktop.h"

#include "base/command_line.h"
#include "chrome/browser/banners/app_banner_data_fetcher_desktop.h"
#include "chrome/common/chrome_switches.h"
#include "extensions/common/constants.h"

namespace {
// TODO(dominickn) Enforce the set of icons which will guarantee the best
// user experience.
int kMinimumIconSize = extension_misc::EXTENSION_ICON_LARGE;
}  // anonymous namespace

DEFINE_WEB_CONTENTS_USER_DATA_KEY(banners::AppBannerManagerDesktop);

namespace banners {

bool AppBannerManagerDesktop::IsEnabled() {
#if defined(OS_CHROMEOS)
  return !base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kDisableAddToShelf);
#else
  return base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableAddToShelf);
#endif
}

AppBannerDataFetcher* AppBannerManagerDesktop::CreateAppBannerDataFetcher(
    base::WeakPtr<AppBannerDataFetcher::Delegate> weak_delegate,
    const int ideal_icon_size) {
  return new AppBannerDataFetcherDesktop(web_contents(), weak_delegate,
                                         ideal_icon_size);
}

AppBannerManagerDesktop::AppBannerManagerDesktop(
    content::WebContents* web_contents)
    : AppBannerManager(web_contents, kMinimumIconSize) {
}

}  // namespace banners

// Copyright 2015 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/banners/app_banner_manager_desktop.h"

#include "base/command_line.h"
#include "chrome/browser/banners/app_banner_data_fetcher_desktop.h"
#include "chrome/common/chrome_switches.h"
#include "extensions/common/constants.h"

namespace {
// TODO(dominickn) Enforce the set of icons which will guarantee the best
// user experience.
int kMinimumIconSize = extension_misc::EXTENSION_ICON_LARGE;
}  // anonymous namespace

DEFINE_WEB_CONTENTS_USER_DATA_KEY(banners::AppBannerManagerDesktop);

namespace banners {

bool AppBannerManagerDesktop::IsEnabled() {
  return base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableAddToShelf);
}

AppBannerDataFetcher* AppBannerManagerDesktop::CreateAppBannerDataFetcher(
    base::WeakPtr<AppBannerDataFetcher::Delegate> weak_delegate,
    const int ideal_icon_size) {
  return new AppBannerDataFetcherDesktop(web_contents(), weak_delegate,
                                         ideal_icon_size);
}

AppBannerManagerDesktop::AppBannerManagerDesktop(
    content::WebContents* web_contents)
    : AppBannerManager(web_contents, kMinimumIconSize) {
}

}  // namespace banners

Disable app banners on ChromeOS.

Disable app banners on ChromeOS.

This feature has not passed launch review for M45.

BUG=491001,525871
R=benwells@chromium.org

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

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#346052}


#include "perf_precomp.hpp"

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

typedef perf::TestBaseWithParam<std::string> fast;

#define FAST_IMAGES \
    "cv/detectors_descriptors_evaluation/images_datasets/leuven/img1.png",\
    "stitching/a3.png"

PERF_TEST_P(fast, detectForORB, testing::Values(FAST_IMAGES))
{
    String filename = getDataPath(GetParam());
    Mat frame = imread(filename, IMREAD_GRAYSCALE);

    if (frame.empty())
        FAIL() << "Unable to load source image " << filename;

    declare.in(frame);

    FastFeatureDetector fd(20, true, FastFeatureDetector::TYPE_5_8);
    vector<KeyPoint> points;

    TEST_CYCLE() fd.detect(frame, points);
    fd = FastFeatureDetector(20, true, FastFeatureDetector::TYPE_7_12);
    TEST_CYCLE() fd.detect(frame, points);
    fd = FastFeatureDetector(20, true, FastFeatureDetector::TYPE_9_16);
    TEST_CYCLE() fd.detect(frame, points);
}

#include "perf_precomp.hpp"

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

enum { TYPE_5_8 =FastFeatureDetector::TYPE_5_8, TYPE_7_12 = FastFeatureDetector::TYPE_7_12, TYPE_9_16 = FastFeatureDetector::TYPE_9_16 };
CV_ENUM(FastType, TYPE_5_8, TYPE_7_12, TYPE_9_16)

typedef std::tr1::tuple<String, FastType> File_Type_t;
typedef perf::TestBaseWithParam<File_Type_t> fast;

#define FAST_IMAGES \
    "cv/detectors_descriptors_evaluation/images_datasets/leuven/img1.png",\
    "stitching/a3.png"

PERF_TEST_P(fast, detect, testing::Combine(
                            testing::Values(FAST_IMAGES),
                            testing::ValuesIn(FastType::all())
                          ))
{
    String filename = getDataPath(get<0>(GetParam()));
    int type = get<1>(GetParam());
    Mat frame = imread(filename, IMREAD_GRAYSCALE);

    if (frame.empty())
        FAIL() << "Unable to load source image " << filename;

    declare.in(frame);

    FastFeatureDetector fd(20, true, type);
    vector<KeyPoint> points;

    TEST_CYCLE() fd.detect(frame, points);

    SANITY_CHECK(points);
}

Fix terrible perf test for FAST detector


#include <iostream>
#include <memory>
#include <utility>

#include "parse/Parse.hpp"

using namespace parse;
using std::cout;

class TreePrinter : public tree::TermVisitor
{
public:

    virtual void acceptTerm(const tree::Abstraction& term) override
    {
        cout << "(^";

        for (const std::string& arg : term.arguments)
        {
            cout << arg << " ";
        }

        cout << ". ";

        term.body->applyVisitor(*this);

        cout << ")";
    }

    virtual void acceptTerm(const tree::Application& term) override
    {
        cout << "(";

        bool isFirst = true;

        for (int termNdx = 0; termNdx < term.terms.size(); ++termNdx)
        {
            if (!isFirst)
            {
                cout << " ";
            }

            isFirst = false;

            term.terms[termNdx]->applyVisitor(*this);
        }

        cout << ")";
    }

    virtual void acceptTerm(const tree::Variable& term) override
    {
        cout << term.name;
    }
};

int main()
{
    std::unique_ptr<tree::Variable> vx(new tree::Variable), vy(new tree::Variable);

    vx->name = "x";
    vy->name = "y";

    std::unique_ptr<tree::Application> body(new tree::Application);

    body->terms.push_back(std::move(vx));
    body->terms.push_back(std::move(vy));

    std::unique_ptr<tree::Abstraction> abs(new tree::Abstraction);

    abs->arguments.push_back("x");
    abs->body = std::move(body);

    TreePrinter treePrinter;

    abs->applyVisitor(treePrinter);

    cout << "\n";
}

Test tree and try printing it

Test tree and try printing it


/* BZWorkbench
 * Copyright (c) 1993 - 2008 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "windows/ConsoleWindow.h"

Console* ConsoleWindow::console = NULL;
bool ConsoleWindow::initialized = false;

// constructor
ConsoleWindow::ConsoleWindow(int lineLimit) :
	Fl_Window(DEFAULT_WIDTH, DEFAULT_HEIGHT, "BZWorkbench Messages") {

	end();

	console = new Console(10, 10, DEFAULT_WIDTH - 20, DEFAULT_HEIGHT - 20);
	add(console);

	initialized = true;

	console->setReadOnly(true);
}

// destructor
ConsoleWindow::~ConsoleWindow() {
	initialized = false;
}

// outputs text to the console widget
void ConsoleWindow::output(const char* text, ...) {

	// borrowed from TextUtils.cxx
	va_list args;
    va_start(args, text);
    string result = TextUtils::vformat(text, args);
    va_end(args);

	if(!initialized) {
	    printf("%s", result.c_str());
	}
	else {
		console->add( result );
	}
}

/* BZWorkbench
 * Copyright (c) 1993 - 2008 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include <stdio.h>
#include "windows/ConsoleWindow.h"

Console* ConsoleWindow::console = NULL;
bool ConsoleWindow::initialized = false;

// constructor
ConsoleWindow::ConsoleWindow(int lineLimit) :
	Fl_Window(DEFAULT_WIDTH, DEFAULT_HEIGHT, "BZWorkbench Messages") {

	end();

	console = new Console(10, 10, DEFAULT_WIDTH - 20, DEFAULT_HEIGHT - 20);
	add(console);

	initialized = true;

	console->setReadOnly(true);
}

// destructor
ConsoleWindow::~ConsoleWindow() {
	initialized = false;
}

// outputs text to the console widget
void ConsoleWindow::output(const char* text, ...) {

	// borrowed from TextUtils.cxx
	va_list args;
    va_start(args, text);
    string result = TextUtils::vformat(text, args);
    va_end(args);

	if(!initialized) {
	    printf("%s", result.c_str());
	}
	else {
		console->add( result );
	}
}

Include stdio.h for printf() declaration.

git-svn-id: 7c9ea37791cd259b24cbb3dc83a0e12673e3c8a9@20729 08b3d480-bf2c-0410-a26f-811ee3361c24


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

#include <sys/sysinfo.h>

#include "test/gtest_and_gmock.h"

namespace perfetto {

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

}  // namespace perfetto

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

#include <sys/sysinfo.h>

#include "test/gtest_and_gmock.h"

namespace perfetto {

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

}  // namespace perfetto

Increase core count for PerfettoDeviceFeatureTest

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

Bug: b/203651019
Test: atest CtsPerfettoTestCases
CQ-DEPEND: CL:1867150

Change-Id: I2246d9ef10e553df3f9d12ccde78d8009f3fd7cd


#include "queuemanager.h"
#include "rdkafka.h"

QueueManager::QueueManager(rd_kafka_t *rk) : rk_(rk)
{

}

QueueManager::~QueueManager()
{
    ASSERT(queues_.empty());
}

void QueueManager::add(rd_kafka_queue_t* queue)
{
    CritScope ss(&crt_);
    ASSERT(queues_.find(queue) == queues_.end());

    //remove the queue forwarding on the main queue.
    rd_kafka_queue_forward(queue, NULL);
    queues_.insert(queue);
}

bool QueueManager::remove(rd_kafka_queue_t* queue)
{
    CritScope ss(&crt_);
    auto it = queues_.find(queue);

    if(it == queues_.end())
        return false;

    //forward the queue back to the main queue
    rd_kafka_queue_forward(*it, rd_kafka_queue_get_consumer(rk_));
    queues_.erase(it);
    return true;
}

void QueueManager::clear_all()
{
    CritScope ss(&crt_);

    //forwards all queues back on the main queue

    for(auto it = queues_.begin(); it != queues_.end(); ++ it)
        rd_kafka_queue_forward(*it, rd_kafka_queue_get_consumer(rk_));

    queues_.clear();
}

#include "queuemanager.h"
#include "rdkafka.h"

QueueManager::QueueManager(rd_kafka_t *rk) : rk_(rk)
{

}

QueueManager::~QueueManager()
{
    ASSERT(queues_.empty());
}

void QueueManager::add(rd_kafka_queue_t* queue)
{
    CritScope ss(&crt_);
    ASSERT(queues_.find(queue) == queues_.end());

    //remove the queue forwarding on the main queue.
    rd_kafka_queue_forward(queue, NULL);
    queues_.insert(queue);
}

bool QueueManager::remove(rd_kafka_queue_t* queue)
{
    CritScope ss(&crt_);
    auto it = queues_.find(queue);

    if(it == queues_.end())
        return false;

    //forward the queue back to the main queue
    rd_kafka_queue_t* main_queue = rd_kafka_queue_get_consumer(rk_);
    rd_kafka_queue_forward(*it, main_queue);
    rd_kafka_queue_destroy(main_queue);
    queues_.erase(it);
    return true;
}

void QueueManager::clear_all()
{
    CritScope ss(&crt_);

    //forwards all queues back on the main queue

    for(auto it = queues_.begin(); it != queues_.end(); ++ it)
    {
        rd_kafka_queue_t* main_queue = rd_kafka_queue_get_consumer(rk_);
        rd_kafka_queue_forward(*it, main_queue);
        rd_kafka_queue_destroy(main_queue);
    }

    queues_.clear();
}

Fix memory leak found in xcode instruments


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

struct GrGLInterface;

const GrGLInterface* GrGLDefaultInterface() {
    return NULL;
}

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

#include "GrGLInterface.h"

const GrGLInterface* GrGLDefaultInterface() {
    return NULL;
}

Include GrGLInterface.h instead of forward declaring, since we have to get NULL defined anyway.

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


#include <vector>

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

int main (int argc, char const *argv[], char const *envp[])
{
    std::vector<int> ints;
    std::vector<short> shorts;
    for (int i=0; i<12; i++)
    {
        ints.push_back(i);
        shorts.push_back((short)i);
    }
    return 0;
}

#include <vector>

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

int main (int argc, char const *argv[], char const *envp[])
{
    std::vector<long> longs;
    std::vector<short> shorts;
    for (int i=0; i<12; i++)
    {
        longs.push_back(i);
        shorts.push_back(i);
    }
    return 0;
}

Make the first vector of "long" instead of "int" so we can tell the difference
easier since "short" ends up with "short int" in the template allocators.

git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@127661 91177308-0d34-0410-b5e6-96231b3b80d8


#include "cargoproject.h"

#include "cargoprojectnode.h"
#include "utils/fileutils.h"
#include "cargoprojectmanager.h"
#include "cargoprojectfile.h"

using namespace Rust;

CargoProject::CargoProject(CargoProjectManager* projectManager, QString projectFileName)
    : projectManager_(projectManager),
      projectFileName_(projectFileName),
      rootNode_(new CargoProjectNode(Utils::FileName::fromString(projectFileName))),
      projectFile_(new CargoProjectFile(projectFileName))
{

}

// The name of the project, that can be seen in the welcome project list,
// and in the project root's contextual menu.
QString CargoProject::displayName() const
{
    return QString::fromLatin1("Stub Display Name");
}

// Not sure in what context this document is used.
Core::IDocument* CargoProject::document() const
{
    return projectFile_.data();
}

ProjectExplorer::IProjectManager* CargoProject::projectManager() const
{
    return projectManager_;
}

// The returned object must be the same on each call to this method.
ProjectExplorer::ProjectNode* CargoProject::rootProjectNode() const
{
    return rootNode_.data();
}

QStringList CargoProject::files(ProjectExplorer::Project::FilesMode fileMode) const
{
    Q_UNUSED(fileMode)
    return QStringList();
}

#include "cargoproject.h"

#include "cargoprojectnode.h"
#include "utils/fileutils.h"
#include "cargoprojectmanager.h"
#include "cargoprojectfile.h"

using namespace Rust;

CargoProject::CargoProject(CargoProjectManager* projectManager, QString projectFileName)
    : projectManager_(projectManager),
      projectFileName_(projectFileName),
      rootNode_(new CargoProjectNode(Utils::FileName::fromString(projectFileName))),
      projectFile_(new CargoProjectFile(projectFileName))
{

}

// The name of the project, that can be seen in the welcome project list,
// and in the project root's contextual menu.
QString CargoProject::displayName() const
{
    return Utils::FileName::fromString(projectFileName_).parentDir().fileName();
}

// Not sure in what context this document is used.
Core::IDocument* CargoProject::document() const
{
    return projectFile_.data();
}

ProjectExplorer::IProjectManager* CargoProject::projectManager() const
{
    return projectManager_;
}

// The returned object must be the same on each call to this method.
ProjectExplorer::ProjectNode* CargoProject::rootProjectNode() const
{
    return rootNode_.data();
}

QStringList CargoProject::files(ProjectExplorer::Project::FilesMode fileMode) const
{
    Q_UNUSED(fileMode)
    return QStringList();
}

Change project name to the name of the Cargo.toml's parent dir


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

#include "base/metrics/field_trial.h"
#include "build/build_config.h"
#include "chrome/common/chrome_version_info.h"

namespace chrome_browser_net {

bool ConfigureAsyncDnsFieldTrial() {
#if defined(OS_ANDROID) || defined(OS_IOS) || defined(OS_CHROMEOS)
  // There is no DnsConfigService on those platforms so disable the field trial.
  return false;
#endif
  const base::FieldTrial::Probability kAsyncDnsDivisor = 100;
  base::FieldTrial::Probability enabled_probability = 0;

  // TODO(szym): expand to DEV channel after fixing http://crbug.com/121085
  if (chrome::VersionInfo::GetChannel() <= chrome::VersionInfo::CHANNEL_CANARY)
    enabled_probability = 0;

  scoped_refptr<base::FieldTrial> trial(
      base::FieldTrialList::FactoryGetFieldTrial(
          "AsyncDns", kAsyncDnsDivisor, "disabled", 2012, 9, 30, NULL));

  int enabled_group = trial->AppendGroup("enabled", enabled_probability);
  return trial->group() == enabled_group;
}

}  // namespace chrome_browser_net

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

#include "base/metrics/field_trial.h"
#include "build/build_config.h"
#include "chrome/common/chrome_version_info.h"

namespace chrome_browser_net {

bool ConfigureAsyncDnsFieldTrial() {
#if defined(OS_ANDROID) || defined(OS_IOS)
  // There is no DnsConfigService on those platforms so disable the field trial.
  return false;
#endif
  const base::FieldTrial::Probability kAsyncDnsDivisor = 100;
  base::FieldTrial::Probability enabled_probability = 0;

#if defined(OS_CHROMEOS)
  if (chrome::VersionInfo::GetChannel() <= chrome::VersionInfo::CHANNEL_DEV)
    enabled_probability = 50;
#endif

  scoped_refptr<base::FieldTrial> trial(
      base::FieldTrialList::FactoryGetFieldTrial(
          "AsyncDns", kAsyncDnsDivisor, "disabled", 2012, 10, 30, NULL));

  int enabled_group = trial->AppendGroup("enabled", enabled_probability);
  return trial->group() == enabled_group;
}

}  // namespace chrome_browser_net

[net] Enable async DNS field trial on CrOS (canary+dev channels).

BUG=143454

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

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


// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.

// Make sure LLVMFuzzerInitialize is called.
#include <assert.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static char *argv0;

extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
  assert(*argc > 0);
  argv0 = **argv;
  fprintf(stderr, "LLVMFuzzerInitialize: %s\n", argv0);
  return 0;
}

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  if (Size == strlen(argv0) &&
      !strnstr(reinterpret_cast<const char *>(Data), argv0, Size)) {
    fprintf(stderr, "BINGO %s\n", argv0);
    exit(1);
  }
  return 0;
}

// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.

// Make sure LLVMFuzzerInitialize is called.
#include <assert.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static char *argv0;

extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
  assert(*argc > 0);
  argv0 = **argv;
  fprintf(stderr, "LLVMFuzzerInitialize: %s\n", argv0);
  return 0;
}

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  if (Size == strlen(argv0) &&
      !strncmp(reinterpret_cast<const char *>(Data), argv0, Size)) {
    fprintf(stderr, "BINGO %s\n", argv0);
    exit(1);
  }
  return 0;
}

Revert "[libFuzzer tests] Use substring comparison in libFuzzer tests"

This reverts commit 3592d8049660dcdd07f7c2e797f2de9790f93111.

Breaks the bots, reverting for now.

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


// https://github.com/KubaO/stackoverflown/tree/master/questions/html-get-24965972
#include <QtNetwork>
#include <functional>

void htmlGet(const QUrl &url, const std::function<void(const QString&)> & fun) {
   QScopedPointer<QNetworkAccessManager> manager(new QNetworkAccessManager);
   QNetworkReply * response = manager->get(QNetworkRequest(QUrl(url)));
   QObject::connect(manager, &QNetworkAccessManager::finished, [manager, response]{
     response->deleteLater();
     manager->deleteLater();
     if (reponse->error() != QNetworkReply::NoError) return;
     QString contentType =
       response->header(QNetworkRequest::ContentTypeHeader).toString();
     if (!contentType.contains("charset=utf-8")) {
       qWarning() << "Content charsets other than utf-8 are not implemented yet.";
       return;
     }
     QString html = QString::fromUtf8(response->readAll());
     // do something with the data
   }) && manager.take();
}

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

   return a.exec();
}

// https://github.com/KubaO/stackoverflown/tree/master/questions/html-get-24965972
#include <QtNetwork>
#include <functional>

void htmlGet(const QUrl &url, const std::function<void(const QString&)> &fun) {
   QScopedPointer<QNetworkAccessManager> manager(new QNetworkAccessManager);
   QNetworkReply *response = manager->get(QNetworkRequest(QUrl(url)));
   QObject::connect(response, &QNetworkReply::finished, [response, fun]{
      response->deleteLater();
      response->manager()->deleteLater();
      if (response->error() != QNetworkReply::NoError) return;
      auto const contentType =
            response->header(QNetworkRequest::ContentTypeHeader).toString();
      static QRegularExpression re("charset=([!-~]+)");
      auto const match = re.match(contentType);
      if (!match.hasMatch() || 0 != match.captured(1).compare("utf-8", Qt::CaseInsensitive)) {
         qWarning() << "Content charsets other than utf-8 are not implemented yet:" << contentType;
         return;
      }
      auto const html = QString::fromUtf8(response->readAll());
      fun(html); // do something with the data
   }) && manager.take();
}

int main(int argc, char *argv[])
{
   QCoreApplication app(argc, argv);
   htmlGet({"http://www.google.com"}, [](const QString &body){ qDebug() << body; qApp->quit(); });
   return app.exec();
}

Fix to make it work.

Fix to make it work.


#include <Python.h>
#include "Quantuccia/ql/time/calendars/unitedstates.hpp"

static PyObject*
get_holiday_date(PyObject *self, PyObject *args)
{
    return NULL;
}

static PyMethodDef QuantucciaMethods[] = {
	{"get_holiday_date", (PyCFunction)get_holiday_date, METH_VARARGS, NULL},
	{NULL,     NULL}        /* Sentinel */
};

static struct PyModuleDef quantuccia_module_def = {
	PyModuleDef_HEAD_INIT,
	"quantuccia",
	NULL,
	-1,
	QuantucciaMethods,
};

PyObject* PyInit_pyQuantuccia(void){
    PyObject *m;
    m = PyCreate_Module(&quantuccia_module_def);
    return m;
}

#include <Python.h>
#include "Quantuccia/ql/time/calendars/unitedstates.hpp"

static PyObject*
get_holiday_date(PyObject *self, PyObject *args)
{
    return NULL;
}

static PyMethodDef QuantucciaMethods[] = {
	{"get_holiday_date", (PyCFunction)get_holiday_date, METH_VARARGS, NULL},
	{NULL,     NULL}        /* Sentinel */
};

static struct PyModuleDef quantuccia_module_def = {
	PyModuleDef_HEAD_INIT,
	"quantuccia",
	NULL,
	-1,
	QuantucciaMethods,
};

PyObject* PyInit_pyQuantuccia(void){
    PyObject *m;
    m = PyModule_Create(&quantuccia_module_def);
    return m;
}

Correct name of module initializer.

Correct name of module initializer.


//// Basic implementation of the icalcterm interface

#include "icalc/icalc.h"

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

#define EXPORT __attribute__ ((visibility ("default")))

extern "C" {

void EXPORT CI_init( CI_Config* config )
{
    printf("Starting defcalc.\n");
}

// Note: this function returns a pointer, but for some strange
// reason we must put the asterisk after the EXPORT.
CI_Result EXPORT * CI_submit( char const* input )
{
    CI_Result* res = new CI_Result;
    res->one_line = strdup( input );
    res->y = 3;
    res->grid = new char*[res->y];
    for( int i = 0; i < res->y; ++i )
        res->grid[i] = strdup( input );
    return res;
}

void EXPORT CI_result_release( CI_Result* result )
{
    free( result->one_line );
    for( int i = 0; i < result->y; ++i )
        free( result->grid[i] );
    delete[] result->grid;
    delete result;
}

} // extern "C"

Add basic implemention of icalc interface