/*----------------------------------------*/
// Test receiving messages from master
//
// This receives a message from master (command 0x01),
// which tells it to turn an LED on or off.
//
/*----------------------------------------*/

#include <stdint.h>

#include "MultidropSlave.h"
#include "MultidropDataUart.h"

#define NODE_COUNT 5

int main() {
  uint8_t ledOn = 0;

  // LED on PB0
  DDRB |= (1 << PB0);
  PORTB &= ~(1 << PB0);

  MultidropDataUart serial;
  serial.begin(9600);

  MultidropSlave slave(&serial);
  slave.setAddress(1);

  while(1) {
    slave.read();
    if (slave.isReady() && slave.isAddressedToMe() && slave.getCommand() == 0x01) {
      ledOn = slave.getData()[0];

      if (ledOn) {
        PORTB |= (1 << PB0);
      } else {
        PORTB &= ~(1 << PB0);
      }
      slave.reset();
    }
  }
}

/*----------------------------------------*/
// Test receiving messages from master
//
// This receives a message from master (command 0x01),
// which tells it to turn an LED on or off.
//
/*----------------------------------------*/

#include <stdint.h>

#include "MultidropSlave.h"
#include "MultidropDataUart.h"

#define NODE_ADDRESS 1

int main() {
  uint8_t ledOn = 0;

  // LED on PB0
  DDRB |= (1 << PB0);
  PORTB &= ~(1 << PB0);

  MultidropDataUart serial;
  serial.begin(9600);

  MultidropSlave slave(&serial);
  slave.setAddress(NODE_ADDRESS);

  while(1) {
    slave.read();
    if (slave.isReady() && slave.isAddressedToMe() && slave.getCommand() == 0x01) {
      ledOn = slave.getData()[0];

      if (ledOn) {
        PORTB |= (1 << PB0);
      } else {
        PORTB &= ~(1 << PB0);
      }
      slave.reset();
    }
  }
}

Add NODE_ADDRESS value to slave_node program


// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WatermarkDataFactory.h"

namespace ExampleApp
{
    namespace Watermark
    {
        namespace View
        {
            WatermarkDataFactory::WatermarkDataFactory(const std::string& appName,
                                                       const std::string& googleAnalyticsReferrerToken)
            : m_appName(appName)
            , m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken)
            {

            }

            WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl,
                                                       const std::string& popupTitle,
                                                       const std::string& popupBody,
                                                       const std::string& webUrl,
                                                       const bool shouldShowShadow)
            {
                return WatermarkData(imageAssetUrl,
                                     popupTitle,
                                     popupBody,
                                     webUrl,
                                     shouldShowShadow);
            }

            WatermarkData WatermarkDataFactory::CreateDefaultEegeo()
            {
                std::string imageAssetName = "eegeo_logo";
                std::string popupTitle = "Maps by WRLD";
                std::string popupBody = "This app is open source. It's built using the WRLD maps SDK, a cross platform API for building engaging, customizable apps.";
                std::string webUrl = "http://wrld3d.com/?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo";

                return Create(imageAssetName,
                              popupTitle,
                              popupBody,
                              webUrl);
            }
        }
    }
}

// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WatermarkDataFactory.h"

namespace ExampleApp
{
    namespace Watermark
    {
        namespace View
        {
            WatermarkDataFactory::WatermarkDataFactory(const std::string& appName,
                                                       const std::string& googleAnalyticsReferrerToken)
            : m_appName(appName)
            , m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken)
            {

            }

            WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl,
                                                       const std::string& popupTitle,
                                                       const std::string& popupBody,
                                                       const std::string& webUrl,
                                                       const bool shouldShowShadow)
            {
                return WatermarkData(imageAssetUrl,
                                     popupTitle,
                                     popupBody,
                                     webUrl,
                                     shouldShowShadow);
            }

            WatermarkData WatermarkDataFactory::CreateDefaultEegeo()
            {
                std::string imageAssetName = "eegeo_logo";
                std::string popupTitle = "Maps by WRLD";
                std::string popupBody = "This app is open source. It's built using the WRLD maps SDK, a cross platform API for building engaging, customizable apps.";
                std::string utmSource = m_googleAnalyticsReferrerToken.empty() ? "unspecified" : m_googleAnalyticsReferrerToken;
                std::string webUrl = "http://wrld3d.com/?utm_source=" + utmSource + "&utm_medium=referral&utm_campaign=eegeo";

                return Create(imageAssetName,
                              popupTitle,
                              popupBody,
                              webUrl);
            }
        }
    }
}

[MPLY-8929] Fix for generation of QR code when google analytics referrer token is unset.  Buddy: Jonty


#include <iostream>
using std::cout;
using std::endl;

#include "problems/Factory.h"
#include "util/Timer.h"
using util::Timer;

int main(int argc, char **argv) {

  auto problem = problems::Factory::create(1);

  Timer t;

  t.start();
  for (int i = 0; i < 1000000; ++i)
    problem->solve();
  t.stop();

  cout << problem->answer() << endl;
  cout << "Time elapsed: " << t << endl;

  return 0;
}

#include <iostream>
using std::cout;
using std::endl;

#include "problems/Factory.h"
#include "util/Timer.h"
using util::Timer;

int main(int argc, char **argv) {

  auto problem = problems::Factory::create(1);

  Timer t;

  t.start();
  problem->solve();
  t.stop();

  cout << problem->answer() << endl;
  cout << "Time elapsed: " << t << endl;

  return 0;
}

Make apps/pe only run a problem once

Make apps/pe only run a problem once


#include <iostream>

#include "cons.h"
#include "error.h"
#include "eval.h"
#include "init.h"
#include "load.h"
#include "reader.h"
#include "utils.h"

namespace
{

class Repl
{
  std::istream& in_;
  std::ostream& out_;
  std::string prompt_ = "mclisp> ";
  mclisp::Reader reader_;

  public:
    explicit Repl(std::istream& in=std::cin, std::ostream& out=std::cout):
      in_(in), out_(out), reader_(in_) {};

    int loop();
};

int Repl::loop()
{
  while (true)
  {
    out_ << prompt_;
    try
    {
      mclisp::ConsCell *exp = reader_.Read();

      if (mclisp::ShouldQuit(exp))
        break;

      mclisp::ConsCell *value = Eval(exp);
      out_ << *value << std::endl;
    }
    catch (mclisp::Error& e)
    {
      out_ << e.what() << std::endl;
    }
  }
  return 0;
}

} //end namespace

int main()
{
  // InitLisp must be called before the Reader object is initialized.
  mclisp::InitLisp();
  mclisp::LoadFile("mclisp.lisp");

  Repl repl;
  return repl.loop();
}

#include <iostream>

#include "cons.h"
#include "error.h"
#include "eval.h"
#include "init.h"
#include "load.h"
#include "reader.h"
#include "utils.h"

namespace
{

class Repl
{
  std::istream& in_;
  std::ostream& out_;
  std::string prompt_ = "mclisp> ";
  mclisp::Reader reader_;

  public:
    explicit Repl(std::istream& in=std::cin, std::ostream& out=std::cerr):
      in_(in), out_(out), reader_(in_) {};

    int loop();
};

int Repl::loop()
{
  while (true)
  {
    out_ << prompt_;
    try
    {
      mclisp::ConsCell *exp = reader_.Read();

      if (mclisp::ShouldQuit(exp))
        break;

      mclisp::ConsCell *value = Eval(exp);
      out_ << *value << std::endl;
    }
    catch (mclisp::Error& e)
    {
      out_ << e.what() << std::endl;
    }
  }
  return 0;
}

} //end namespace

int main()
{
  // InitLisp must be called before the Reader object is initialized.
  mclisp::InitLisp();
  mclisp::LoadFile("mclisp.lisp");

  Repl repl;
  return repl.loop();
}

Print REPL output on std::cerr instead of cout.


#include "RequestParser.h"
#include <sstream>
#include <vector>

std::vector<std::string> ApiMock::RequestParser::projectToCollection(std::string const& request) {
	std::vector<std::string> fromRequest;
	std::string::size_type pos = 0;
	std::string::size_type prev = 0;

	while ((pos = request.find('\n', prev)) != std::string::npos) {
		fromRequest.push_back(request.substr(prev, pos - prev));
		prev = pos + 1;
	}

	fromRequest.push_back(request.substr(prev));
	return fromRequest;
}

ApiMock::RequestData ApiMock::RequestParser::parse(std::string const& requestBuffer) {
	std::vector<std::string> entireRequest = projectToCollection(requestBuffer);
	RequestData request;

	return request;
}

#include "RequestParser.h"
#include <sstream>
#include <vector>

std::vector<std::string> ApiMock::RequestParser::projectToCollection(std::string const& request) {
	const std::string CRLF = "\r\n";
	std::vector<std::string> fromRequest;
	std::string::size_type pos = 0;
	std::string::size_type prev = 0;

	while ((pos = request.find(CRLF, prev)) != std::string::npos) {
		fromRequest.push_back(request.substr(prev, pos - prev));
		prev = pos + 1;
	}

	fromRequest.push_back(request.substr(prev));
	return fromRequest;
}

ApiMock::RequestData ApiMock::RequestParser::parse(std::string const& requestBuffer) {
	std::vector<std::string> entireRequest = projectToCollection(requestBuffer);
	RequestData request;

	return request;
}

Use CRLF in requests instead of just LF

Use CRLF in requests instead of just LF


#include <iostream>

#include "rapidcheck/detail/NonRandomData.h"

namespace rc {
RandomData::RandomData(const uint8_t *Data, size_t Size) {
  std::cout << Data << std::endl;
  // TODO: really stupid way to fill the container
  const size_t size64 = Size / 8;
  auto Data64 = reinterpret_cast<const uint64_t *>(Data);
  for (size_t i = 0; i < size64; i++) {
    m_data.push(Data64[i]);
  }
}
} // namespace rc

#include <iostream>

#include "rapidcheck/detail/NonRandomData.h"

namespace rc {
RandomData::RandomData(const uint8_t *Data, size_t Size) {
  // TODO: really stupid way to fill the container
  const size_t size64 = Size / 8;
  auto Data64 = reinterpret_cast<const uint64_t *>(Data);
  for (size_t i = 0; i < size64; i++) {
    m_data.push(Data64[i]);
  }
}
} // namespace rc

Address Sanitation for the win: found memory bug.


#include <iostream>

using namespace std;

int main()
{
    cout << "Hello World!" << endl;
    return 0;
}

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv) {
    VideoCapture cap(0);

    namedWindow("MyVideo", CV_WINDOW_AUTOSIZE);

    int w = cap.get(CV_CAP_PROP_FRAME_WIDTH);
    int h = cap.get(CV_CAP_PROP_FRAME_HEIGHT);

    //cap.set(CV_CAP_PROP_SETTINGS, 1);

    // 24 x 19

    while (true) {
        Mat frame, frame2;
        cap.read(frame);

        Point2f src[] = {Point2f(140, 0), Point2f(520, 0), Point2f(73, 479), Point2f(586, 479)};
        Point2f dst[] = {Point2f(0, 0), Point2f(640, 0), Point2f(0, 480), Point2f(640, 480)};
        Mat m = getPerspectiveTransform(src, dst);

        warpPerspective(frame, frame2, m, cv::Size(w, h));
        resize(frame2, frame, cv::Size(21 * 30, 24 * 30));

        //cvtColor(frame, frame2, CV_BGR2GRAY);
        Mat frameParts[3];
        split(frame, frameParts);

        inRange(frameParts[1], cv::Scalar(60), cv::Scalar(255), frame);
        inRange(frameParts[0], cv::Scalar(60), cv::Scalar(255), frame2);

        Mat result = frame & ~frame2;
        Mat result2;

        auto kernel = getStructuringElement(MORPH_RECT, cv::Size(3, 3));
        erode(result, result2, kernel);

        auto kernel2 = getStructuringElement(MORPH_RECT, cv::Size(9, 9));
        dilate(result2, result, kernel2);

        imshow("MyVideo", result);

        if (waitKey(10) == 27) {
            break;
        }
    }

    return 0;
}

Add basic thresholding of green markers

Add basic thresholding of green markers


#include "board.h"
#include <aery32/gpio.h>
#include <aery32/delay.h>
#include <aery32/intc.h>

using namespace aery;

void isrhandler_group2(void)
{
	gpio_toggle_pin(LED);
	delay_ms(100); /* Reduce glitch */
	porta->ifrc = (1 << 0); /* Remember to clear the interrupt */
}

int main(void)
{
	init_board();

	/* GPIO pins 0-13 can be "wired" to int group 2, see datasheet p. 42 */
	gpio_init_pin(AVR32_PIN_PA00, GPIO_INPUT|GPIO_PULLUP|GPIO_INT_PIN_CHANGE);

	/* Init interrupt controller */
	intc_init();
	intc_register_isrhandler(
		&isrhandler_group2, /* Function pointer to the ISR handler */
		2, /* Interrupt group number */
		0  /* Priority level */
	);

	/* Enable interrupts globally */
	intc_enable_globally();

	for(;;) {
		/*
		 * Now try to connect PA00 to GND and then disconnecting it
		 * to let pull-up to set the pin state high again. The LED
		 * should toggle between the pin change.
		 */

	}

	return 0;
}

#include "board.h"
#include <aery32/gpio.h>
#include <aery32/delay.h>
#include <aery32/intc.h>

using namespace aery;

void isrhandler_group2(void)
{
	gpio_toggle_pin(LED);
	delay_ms(100); /* Reduce glitches */
	porta->ifrc = (1 << 0); /* Remember to clear the interrupt */
}

int main(void)
{
	init_board();

	/* GPIO pins 0-13 can be "wired" to int group 2, see datasheet p. 42 */
	gpio_init_pin(AVR32_PIN_PA00, GPIO_INPUT|GPIO_PULLUP|GPIO_INT_PIN_CHANGE);

	/* Init interrupt controller */
	intc_init();
	intc_register_isrhandler(
		&isrhandler_group2, /* Function pointer to the ISR handler */
		2, /* Interrupt group number */
		0  /* Priority level */
	);

	/* Enable interrupts globally */
	intc_enable_globally();

	for(;;) {
		/*
		 * Now try to connect PA00 to GND and then disconnecting it
		 * to let the pull-up to set the pin state high again. The LED
		 * should toggle on the pin change.
		 */

	}

	return 0;
}

Improve comments in the external interrupt pin change example


// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Tasks/SimpleTasks/ControlTask.hpp>
#include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp>

namespace RosettaStone::SimpleTasks
{
ControlTask::ControlTask(EntityType entityType) : ITask(entityType)
{
    // Do nothing
}

TaskID ControlTask::GetTaskID() const
{
    return TaskID::CONTROL;
}

TaskStatus ControlTask::Impl(Player& player)
{
    auto entities =
        IncludeTask::GetEntities(m_entityType, player, m_source, m_target);
    auto& myField = player.GetField();
    auto& opField = player.opponent->GetField();

    for (auto& entity : entities)
    {
        const auto minion = dynamic_cast<Minion*>(entity);
        if (minion == nullptr)
        {
            continue;
        }

        if (myField.IsFull())
        {
            entity->Destroy();
            continue;
        }

        const auto minionClone = new Minion(*minion);
        myField.AddMinion(*minionClone);
        opField.RemoveMinion(*minion);
    }

    return TaskStatus::COMPLETE;
}
}  // namespace RosettaStone::SimpleTasks

// This code is based on Sabberstone project.
// Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

#include <Rosetta/Tasks/SimpleTasks/ControlTask.hpp>
#include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp>

namespace RosettaStone::SimpleTasks
{
ControlTask::ControlTask(EntityType entityType) : ITask(entityType)
{
    // Do nothing
}

TaskID ControlTask::GetTaskID() const
{
    return TaskID::CONTROL;
}

TaskStatus ControlTask::Impl(Player& player)
{
    auto entities =
        IncludeTask::GetEntities(m_entityType, player, m_source, m_target);
    auto& myField = player.GetField();
    auto& opField = player.opponent->GetField();

    for (auto& entity : entities)
    {
        const auto minion = dynamic_cast<Minion*>(entity);
        if (minion == nullptr)
        {
            continue;
        }

        if (myField.IsFull())
        {
            entity->Destroy();
            continue;
        }

        const auto minionClone = new Minion(*minion);
        minionClone->owner = &player;

        myField.AddMinion(*minionClone);
        opField.RemoveMinion(*minion);
    }

    return TaskStatus::COMPLETE;
}
}  // namespace RosettaStone::SimpleTasks

Add missing code that assigns new owner

fix: Add missing code that assigns new owner


#include "Boot.hpp"

using namespace HomieInternals;

Boot::Boot(const char* name)
: _name(name) {
}

void Boot::setup() {
  if (Interface::get().led.enabled) {
    pinMode(Interface::get().led.pin, OUTPUT);
    digitalWrite(Interface::get().led.pin, !Interface::get().led.on);
  }

  WiFi.persistent(true);  // Persist data on SDK as it seems Wi-Fi connection is faster

  Interface::get().getLogger() << F("🔌 Booting into ") << _name << F(" mode 🔌") << endl;
}

void Boot::loop() {
}

#include "Boot.hpp"

using namespace HomieInternals;

Boot::Boot(const char* name)
: _name(name) {
}

void Boot::setup() {
  if (Interface::get().led.enabled) {
    pinMode(Interface::get().led.pin, OUTPUT);
    digitalWrite(Interface::get().led.pin, !Interface::get().led.on);
  }

  WiFi.persistent(true);  // Persist data on SDK as it seems Wi-Fi connection is faster

  Interface::get().getLogger() << F("💡 Firmware ") << Interface::get().firmware.name << F(" (") << Interface::get().firmware.version << F(")") << endl;
  Interface::get().getLogger() << F("🔌 Booting into ") << _name << F(" mode 🔌") << endl;
}

void Boot::loop() {
}

Print firmware name and version at boot

:art: Print firmware name and version at boot


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        if(nums.size()==0) return NULL;
        return insertnode(0,nums.size(),nums);
    }
private:
    TreeNode* insertnode(int f,int r,vector<int>& nums){
        cout<<f<<" "<<r<<endl;
        if(f==r && f!=0) return NULL;
        if(f==nums.size()) return NULL;
        if(f==r || f==r-1){
            TreeNode* now=new TreeNode(nums[f]);
            return now;
        }
        TreeNode* now=new TreeNode(nums[(f+r)/2]);
        now->left=insertnode(f,(f+r)/2,nums);
        now->right=insertnode((f+r)/2+1,r,nums);
        return now;
    }
};

Convert Sorted Array to Binary Search Tree


#include "util.h"

#include <sstream>
#include <vector>

Header cpr::util::parseHeader(std::string headers) {
    Header header;
    std::vector<std::string> lines;
    std::istringstream stream(headers);
    {
        std::string line;
        while (std::getline(stream, line, '\n')) {
            lines.push_back(line);
        }
    }

    for (auto line = lines.begin(); line != lines.end(); ++line) {
        if (line->substr(0, 5) == "HTTP/") {
            header.clear();
        }

        if (line->length() > 0) {
            auto found = line->find(":");
            if (found != std::string::npos) {
                auto value = line->substr(found + 2, line->length() - 1);
                if (value.back() == '\r') {
                    value = value.substr(0, value.length() - 1);
                }
                header[line->substr(0, found)] = value;
            }
        }
    }

    return header;
}

std::string cpr::util::parseResponse(std::string response) {
    if (!response.empty()) {
        if (response.back() == '\n') {
            return response.substr(0, response.length() - 1);
        }
    }

    return response;
}

size_t cpr::util::writeFunction(void *ptr, size_t size, size_t nmemb, std::string* data) {
    data->append((char*) ptr, size * nmemb);
    return size * nmemb;
}

#include "util.h"

#include <sstream>
#include <vector>

Header cpr::util::parseHeader(std::string headers) {
    Header header;
    std::vector<std::string> lines;
    std::istringstream stream(headers);
    {
        std::string line;
        while (std::getline(stream, line, '\n')) {
            lines.push_back(line);
        }
    }

    for (auto& line : lines) {
        if (line.substr(0, 5) == "HTTP/") {
            header.clear();
        }

        if (line.length() > 0) {
            auto found = line.find(":");
            if (found != std::string::npos) {
                auto value = line.substr(found + 2, line.length() - 1);
                if (value.back() == '\r') {
                    value = value.substr(0, value.length() - 1);
                }
                header[line.substr(0, found)] = value;
            }
        }
    }

    return header;
}

std::string cpr::util::parseResponse(std::string response) {
    if (!response.empty()) {
        if (response.back() == '\n') {
            return response.substr(0, response.length() - 1);
        }
    }

    return response;
}

size_t cpr::util::writeFunction(void *ptr, size_t size, size_t nmemb, std::string* data) {
    data->append((char*) ptr, size * nmemb);
    return size * nmemb;
}

Use a for each loop

Use a for each loop


#include "GUI.hpp"

#if __APPLE__
#import <IOKit/pwr_mgt/IOPMLib.h>
#elif _WIN32
#include <Windows.h>
#pragma comment(lib, "user32.lib")
#endif

namespace Slic3r { namespace GUI {

IOPMAssertionID assertionID;

void
disable_screensaver()
{
    #if __APPLE__
    CFStringRef reasonForActivity = CFSTR("Slic3r");
    IOReturn success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep,
        kIOPMAssertionLevelOn, reasonForActivity, &assertionID);
    // ignore result: success == kIOReturnSuccess
    #elif _WIN32
    SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
    #endif
}

void
enable_screensaver()
{
    #if __APPLE__
    IOReturn success = IOPMAssertionRelease(assertionID);
    #elif _WIN32
    SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
    #endif
}

} }

#include "GUI.hpp"

#if __APPLE__
#import <IOKit/pwr_mgt/IOPMLib.h>
#elif _WIN32
#include <Windows.h>
#pragma comment(lib, "user32.lib")
#endif

namespace Slic3r { namespace GUI {

#if __APPLE__
IOPMAssertionID assertionID;
#endif

void
disable_screensaver()
{
    #if __APPLE__
    CFStringRef reasonForActivity = CFSTR("Slic3r");
    IOReturn success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep,
        kIOPMAssertionLevelOn, reasonForActivity, &assertionID);
    // ignore result: success == kIOReturnSuccess
    #elif _WIN32
    SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
    #endif
}

void
enable_screensaver()
{
    #if __APPLE__
    IOReturn success = IOPMAssertionRelease(assertionID);
    #elif _WIN32
    SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
    #endif
}

} }

Fix a compilation error on Win32

Fix a compilation error on Win32


#include <cstdlib>
#include <iostream>
using namespace std;

int const n = 50;
long long save[n + 1];

long long fibonanci(int n){

	if (n <= 1)
		return 1;

	if (save[n])
		return save[n];

	return save[n] = fibonanci(n - 2) + fibonanci(n - 1);
}

/*

// CAUTION: This code will take too much time

int fibonanci(int n){

	if (n <= 1)
		return 1;

	return fibonanci(n - 2) + fibonanci(n - 1);
}

*/

int main(){

	printf("fibonanci of %d = %lld\n", n, fibonanci(n));

	return 0;
}

#include <cstdlib>
#include <iostream>
using namespace std;

int const n = 50;
long long save[n + 1];

long long fibonanci_dp(int n){

	if (n <= 0) return 0;

	if (n <= 2) return 1;

	if (save[n])
		return save[n];

	return save[n] = fibonanci_dp(n - 2) + fibonanci_dp(n - 1);
}

/*

// CAUTION: This code will take too much time

long long fibonanci(int n){

	if (n <= 0) return 0;

	if (n <= 2) return 1;

	return fibonanci(n - 2) + fibonanci(n - 1);
}

*/

long long fibonanci_loop(int n){

	long long a = 0, t = 0, b = 1;

	while (n--){
		// cout << a << endl;
		t = a, a = b;
		b = t + b;
	}

	// cout << a << endl;
	return a;
}

int main() {

	// using DP
	cout << fibonanci_dp(n) << endl;

	// using loop
	cout << fibonanci_loop(n) << endl;

	return 0;
}

Add fibonanci_loop method & Fix bug

Add fibonanci_loop method & Fix bug

- Add fibonanci_loop method
- Fix bug of F(0) =0


#include "compress.hpp"
#include "decompress.hpp"

#include<iostream>
#include<fstream>

void printUsage() {
	std::cout << "Give option\n";
}

const std::string COMPRESS_COMMAND = "c";
const std::string DECOMPRESS_COMMAND = "d";

int main(int argc, char** argv) {
	if(argc < 2) {
		printUsage();
		return 1;
	}

	std::istream* const in = argc > 2 ? new std::ifstream(argv[2]) : &std::cin;
	std::ostream* const out = argc > 3 ? new std::ofstream(argv[3]) : &std::cout;

	if(argv[1] == COMPRESS_COMMAND) {
		std::string data;
		data.assign(std::istreambuf_iterator<char>(*in), std::istreambuf_iterator<char>());
		*out << compress(data);
	}
	else if(argv[1] == DECOMPRESS_COMMAND) {
		std::string data;
		data.assign(std::istreambuf_iterator<char>(*in), std::istreambuf_iterator<char>());
		*out << decompress(data);
	}
	else {
		printUsage();
		return 1;
	}
}

#include "compress.hpp"
#include "decompress.hpp"

#include<iostream>
#include<fstream>

void printUsage() {
	std::cout << "Give option\n";
}

const std::string COMPRESS_COMMAND = "c";
const std::string DECOMPRESS_COMMAND = "d";
const std::string ARCHIVE_COMMAND = "a";
const std::string EXTRACT_COMMAND = "x";

int main(int argc, char** argv) {
	if(argc < 2) {
		printUsage();
		return 1;
	}

	std::istream* const in = argc > 2 ? new std::ifstream(argv[2]) : &std::cin;
	std::ostream* const out = argc > 3 ? new std::ofstream(argv[3]) : &std::cout;

	if(argv[1] == COMPRESS_COMMAND) {
		std::string data;
		data.assign(std::istreambuf_iterator<char>(*in), std::istreambuf_iterator<char>());
		*out << compress(data);
	}
	else if(argv[1] == DECOMPRESS_COMMAND) {
		std::string data;
		data.assign(std::istreambuf_iterator<char>(*in), std::istreambuf_iterator<char>());
		*out << decompress(data);
	}
	else if(argv[1] == ARCHIVE_COMMAND) {
		std::cerr << "Archive is not implemented\n";
		return 1;
	}
	else if(argv[1] == EXTRACT_COMMAND) {
		std::cerr << "Extract is not implemented\n";
		return 1;
	}
	else {
		printUsage();
		return 1;
	}
}

Prepare to add archive and extract

Prepare to add archive and extract


// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "WindowAndroid.h"

namespace ouzel
{
    WindowAndroid::WindowAndroid(const Size2& pSize, bool pResizable, bool pFullscreen, uint32_t pSampleCount, const std::string& pTitle):
        Window(pSize, pResizable, pFullscreen, pSampleCount, pTitle)
    {

    }

    WindowAndroid::~WindowAndroid()
    {

    }

    bool WindowAndroid::init()
    {
        return Window::init();
    }
}

// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "WindowAndroid.h"
#include "Engine.h"
#include "opengl/RendererOGL.h"

namespace ouzel
{
    WindowAndroid::WindowAndroid(const Size2& pSize, bool pResizable, bool pFullscreen, uint32_t pSampleCount, const std::string& pTitle):
        Window(pSize, pResizable, pFullscreen, pSampleCount, pTitle)
    {

    }

    WindowAndroid::~WindowAndroid()
    {

    }

    bool WindowAndroid::init()
    {
        std::shared_ptr<graphics::RendererOGL> rendererOGL = std::static_pointer_cast<graphics::RendererOGL>(sharedEngine->getRenderer());

        rendererOGL->setAPIVersion(2);

        return Window::init();
    }
}

Set OpenGL ES version to 2 on Android

Set OpenGL ES version to 2 on Android


/* This file is part of python_mapnik (c++/python mapping toolkit)
 * Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon
 *
 * Mapnik is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//$Id$

#include <boost/python.hpp>
#include <mapnik.hpp>

using mapnik::text_symbolizer;
using mapnik::Color;

void export_text_symbolizer()
{
    using namespace boost::python;

    class_<text_symbolizer>("TextSymbolizer",
			    init<std::string const&,unsigned,Color const&>("TODO"))
	;
}

/* This file is part of python_mapnik (c++/python mapping toolkit)
 * Copyright (C) 2005 Artem Pavlenko, Jean-Francois Doyon
 *
 * Mapnik is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//$Id$

#include <boost/python.hpp>
#include <mapnik.hpp>

using mapnik::text_symbolizer;
using mapnik::Color;

void export_text_symbolizer()
{
    using namespace boost::python;

    class_<text_symbolizer>("TextSymbolizer",
			    init<std::string const&,unsigned,Color const&>())
        .add_property("halo_fill",make_function(
                      &text_symbolizer::get_halo_fill,return_value_policy<copy_const_reference>()),
                      &text_symbolizer::set_halo_fill)
        .add_property("halo_radius",&text_symbolizer::get_halo_radius, &text_symbolizer::set_halo_radius)
	;
}

Add support for halo's to TextSymbolizer().


#include "mainwindow.h"
#include <QApplication>
#include <QStyleFactory> // TODO

int main(int argc, char *argv[])
{
    using namespace HedgeEdit;
    QApplication a(argc, argv);
    QApplication::setStyle(QStyleFactory::create("WindowsVista"));

    UI::MainWindow w;
    w.show();

    return a.exec();
}

#include "mainwindow.h"
#include <QApplication>

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

    UI::MainWindow w;
    w.show();

    return a.exec();
}

Test to see if AppVeyor styles work when not explicitly set


#include "CalculatorBase.h"
#include <algorithm>
#include <numeric>
#include "common.h"

namespace tilegen
{
namespace alpha
{

CalculatorBase::CalculatorBase():
    mAlphas((int)CORNERS)
{
    zeroAlphas();
}

void CalculatorBase::zeroAlphas()
{
    for (auto& alpha : mAlphas)
        alpha = 0;
}

sf::Uint8 & CalculatorBase::getAlpha(size_t index)
{
    return mAlphas[index];
}

const CalculatorBase::Alphas & CalculatorBase::getAlphas() const
{
    return mAlphas;
}

void CalculatorBase::updateAlphas(const Weights & weights)
{
    zeroAlphas();
    for (double weight : weights)
    {
        if(!isfinite(weight))
            return;
    }
    updateAlphasAux(weights);
}

} // namespace alpha
} // namespace tilegen

#include "CalculatorBase.h"
#include <algorithm>
#include <cmath>
#include "common.h"

namespace tilegen
{
namespace alpha
{

CalculatorBase::CalculatorBase():
    mAlphas((int)CORNERS)
{
    zeroAlphas();
}

void CalculatorBase::zeroAlphas()
{
    for (auto& alpha : mAlphas)
        alpha = 0;
}

sf::Uint8 & CalculatorBase::getAlpha(size_t index)
{
    return mAlphas[index];
}

const CalculatorBase::Alphas & CalculatorBase::getAlphas() const
{
    return mAlphas;
}

void CalculatorBase::updateAlphas(const Weights & weights)
{
    zeroAlphas();
    for (double weight : weights)
    {
        if(!std::isfinite(weight))
            return;
    }
    updateAlphasAux(weights);
}

} // namespace alpha
} // namespace tilegen

Use correct header and namespace for isfinite


#include <netinet/ether.h>
#include <netinet/ip.h>
#include "sll.h"
#include "IPv4Processor.h"
#include "LinuxCookedProcessor.h"

void LinuxCookedProcessor::process(const struct pcap_pkthdr *pkthdr, const u_char *packet, const vector<NetData> &netData) {

    struct ip* ipHeader;
    struct ether_header* etherHeader = (struct ether_header*)packet;

    int etherType = ntohs(etherHeader->ether_type);
    switch (etherType) {
        case ETHERTYPE_IP:
            ipHeader = (struct ip*)(packet + SLL_HDR_LEN);
            IPv4Processor().process(ipHeader, pkthdr, netData);
            break;
        default:
            break;
    }
}

#include <netinet/ether.h>
#include <netinet/ip.h>
#include "sll.h"
#include "IPv4Processor.h"
#include "LinuxCookedProcessor.h"

void LinuxCookedProcessor::process(const struct pcap_pkthdr *pkthdr, const u_char *packet, const vector<NetData> &netData) {

    struct ip* ipHeader;
    struct sll_header* linuxCookedHeader = (struct sll_header*)packet;

    int etherType = ntohs(linuxCookedHeader->sll_protocol);
    switch (etherType) {
        case ETHERTYPE_IP:
            ipHeader = (struct ip*)(packet + SLL_HDR_LEN);
            IPv4Processor().process(ipHeader, pkthdr, netData);
            break;
        default:
            break;
    }
}

Fix linux cooked header ether type

Fix linux cooked header ether type


// 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: de016e52bd170d2d4f2344f9bf92d50478b649e0@81023 0039d316-1c4b-4281-b951-d872f2087c98


// Copyright 2016 Zheng Xian Qiu

#include "framework.h"

Window::Window() {
}

// Display Information

int Window::DISPLAY_INDEX = 0;
bool Window::displayModeLoaded = false;
SDL_DisplayMode Window::displayMode;

int Window::getDisplayWidth() {
  loadDisplayMode();
  return displayMode.w;
}

int Window::getDisplayHeight() {
  loadDisplayMode();
  return displayMode.h;
}

void Window::loadDisplayMode(bool reload) {
  if(!displayModeLoaded || reload) {
    if(SDL_GetCurrentDisplayMode(DISPLAY_INDEX, &displayMode) != 0) {
      displayModeLoaded = false;
    }
    displayModeLoaded = true;
  }
}

// Window Manager
bool Window::create(string title, bool hide) {
  uint flags = hide ? 0 : SDL_WINDOW_SHOWN;
  flags = flags | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_INPUT_GRABBED;

  currentWindow = SDL_CreateWindow(title.c_str(), 0, 0, getDisplayWidth(), getDisplayHeight(), flags);
  if(currentWindow == NULL) {
    SDL_DestroyWindow(currentWindow);
    return false;
  }

  Logger::Debug("Initialize window with %dx%dpx resolution.", getDisplayWidth(), getDisplayHeight());

  return true;
}

void Window::destroy() {
  SDL_DestroyWindow(currentWindow);
}

// Copyright 2016 Zheng Xian Qiu

#include "framework.h"

Window::Window() {
}

// Display Information

int Window::DISPLAY_INDEX = 0;
bool Window::displayModeLoaded = false;
SDL_DisplayMode Window::displayMode;

int Window::getDisplayWidth() {
  loadDisplayMode();
  return displayMode.w;
}

int Window::getDisplayHeight() {
  loadDisplayMode();
  return displayMode.h;
}

void Window::loadDisplayMode(bool reload) {
  if(!displayModeLoaded || reload) {
    if(SDL_GetCurrentDisplayMode(DISPLAY_INDEX, &displayMode) != 0) {
      displayModeLoaded = false;
    }
    displayModeLoaded = true;
  }
}

// Window Manager
bool Window::create(string title, bool hide) {
  uint flags = hide ? 0 : SDL_WINDOW_SHOWN;
  flags = flags | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_INPUT_GRABBED;

  currentWindow = SDL_CreateWindow(title.c_str(), 0, 0, getDisplayWidth(), getDisplayHeight(), flags);
  if(currentWindow == NULL) {
    SDL_DestroyWindow(currentWindow);
    return false;
  }

  Logger::Info("Initialize window with %dx%dpx resolution.", getDisplayWidth(), getDisplayHeight());

  return true;
}

void Window::destroy() {
  SDL_DestroyWindow(currentWindow);
}

Switch create window message from debug to info


#include "DebugAndroid.hpp"

#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <cutils/properties.h>

void AndroidEnterDebugger()
{
    ALOGE(__FUNCTION__);
#ifndef NDEBUG
    static volatile int * const makefault = nullptr;
    char value[PROPERTY_VALUE_MAX];
    property_get("debug.db.uid", value, "-1");
    int debug_uid = atoi(value);
    if ((debug_uid >= 0) && (geteuid() < static_cast<uid_t>(debug_uid)))
    {
        ALOGE("Waiting for debugger: gdbserver :${PORT} --attach %u", gettid());
        while (1) {
            pause();
        }
    } else {
        ALOGE("No debugger");
    }
#endif
}

void trace(const char *format, ...)
{
    va_list vararg;
    va_start(vararg, format);
    android_vprintLog(ANDROID_LOG_VERBOSE, NULL, LOG_TAG, format, vararg);
    va_end(vararg);
}

#include "DebugAndroid.hpp"

#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <cutils/properties.h>

void AndroidEnterDebugger()
{
    ALOGE(__FUNCTION__);
#ifndef NDEBUG
    static volatile int * const makefault = nullptr;
    char value[PROPERTY_VALUE_MAX];
    property_get("debug.db.uid", value, "-1");
    int debug_uid = atoi(value);
    if ((debug_uid >= 0) && (geteuid() < static_cast<uid_t>(debug_uid)))
    {
        ALOGE("Waiting for debugger: gdbserver :${PORT} --attach %u. Look for thread %u", getpid(), gettid());
        volatile int waiting = 1;
        while (waiting) {
            sleep(1);
        }
    } else {
        ALOGE("No debugger");
    }
#endif
}

void trace(const char *format, ...)
{
    va_list vararg;
    va_start(vararg, format);
    android_vprintLog(ANDROID_LOG_VERBOSE, NULL, LOG_TAG, format, vararg);
    va_end(vararg);
}

Improve advice for attaching the debugger

Change-Id: I6ca5697a8b672a1e20bcb7999cf4d9ba544f9558
Reviewed-on: https://swiftshader-review.googlesource.com/3117
Reviewed-by: Nicolas Capens <0612353e1fcebbfd4b302d9337447ca0cdfa9122@google.com>
Tested-by: Greg Hartman <1491e78df1ea2169b62fa2ceaf1a32538792aab8@google.com>


#include "MasterClient_p.h"

#include <QtCore/QString>
#include <QtDBus/QDBusMessage>
#include <QtDBus/QDBusReply>
#include <QtDBus/QDBusObjectPath>

#include "PositionProvider.h"

using namespace GeoCute;

static QString createClientPath() {
    SimpleDBusInterface masterInterface(serviceName, masterPathName,
        masterInterfaceName);
    QDBusReply<QDBusObjectPath> reply = masterInterface.call("Create");
    if (reply.isValid())
        return reply.value().path();
    else
	return QString();
}

MasterClient::Private::Private()
    : interface(serviceName, createClientPath(), interfaceName) { }

MasterClient::MasterClient(QObject* parent)
    : QObject(parent), d(new Private) { }

MasterClient::~MasterClient() {
    delete d;
}

void MasterClient::setRequirements(AccuracyLevel accuracy, int min_time,
    SignallingFlags signalling, ResourceFlags resources)
{
    d->interface.call("SetRequirements", accuracy, min_time,
        signalling == SignallingRequired, resources);
}

PositionProvider* MasterClient::positionProvider() {
    if (!d->interface.path().isEmpty()) {
        d->interface.call("PositionStart");
        return new PositionProvider(d->interface.service(), d->interface.path());
    } else
        return 0;
}

#include "MasterClient.moc"

#include "MasterClient_p.h"

#include <QtCore/QString>
#include <QtDBus/QDBusMessage>
#include <QtDBus/QDBusReply>
#include <QtDBus/QDBusObjectPath>

#include "PositionProvider.h"

using namespace GeoCute;

static QString createClientPath() {
    SimpleDBusInterface masterInterface(serviceName, masterPathName,
        masterInterfaceName);
    QDBusReply<QDBusObjectPath> reply = masterInterface.call("Create");
    if (reply.isValid())
        return reply.value().path();
    else
	return QString();
}

MasterClient::Private::Private()
    : interface(serviceName, createClientPath(), interfaceName) { }

MasterClient::MasterClient(QObject* parent)
    : QObject(parent), d(new Private) { }

MasterClient::~MasterClient() {
    delete d;
}

void MasterClient::setRequirements(AccuracyLevel accuracy, int min_time,
    SignallingFlags signalling, ResourceFlags resources)
{
    if (!d->interface.path().isEmpty()) {
        d->interface.call("SetRequirements", accuracy, min_time,
        signalling == SignallingRequired, resources);
    }
}

PositionProvider* MasterClient::positionProvider() {
    if (!d->interface.path().isEmpty()) {
        d->interface.call("PositionStart");
        return new PositionProvider(d->interface.service(), d->interface.path());
    } else
        return 0;
}

#include "MasterClient.moc"

Make geoclue-support more robust to missing master, second attempt

svn path=/branches/marble/marble-gsoc-2009/; revision=983224


#include "Device.h"
#include "../../Drivers/SPIDisplay/SPIDisplay.h"
#include "../../Drivers/DevicesInterop/GHIElectronics_TinyCLR_Devices.h"
#include "../../Drivers/DevicesInterop/GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Interop.h"

void STM32F4_Startup_OnSoftResetDevice(const TinyCLR_Api_Provider* apiProvider, const TinyCLR_Interop_Provider* interopProvider) {
    apiProvider->Add(apiProvider, SPIDisplay_GetApi());
    interopProvider->Add(interopProvider, &Interop_GHIElectronics_TinyCLR_Devices);
}

#include "Device.h"
#include "../../Drivers/SPIDisplay/SPIDisplay.h"
#include "../../Drivers/DevicesInterop/GHIElectronics_TinyCLR_Devices.h"
#include "../../Drivers/DevicesInterop/GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Interop.h"

void STM32F4_Startup_OnSoftResetDevice(const TinyCLR_Api_Manager* apiManager, const TinyCLR_Interop_Manager* interopManager) {
    apiManager->Add(apiManager, SPIDisplay_GetApi());
    interopManager->Add(interopManager, &Interop_GHIElectronics_TinyCLR_Devices);
}

Update Provider to Manager from clean branch


#include "helloworld.h"

#include <QCoreApplication>
#include <QDebug>

#include <qhttpserver.h>
#include <qhttprequest.h>
#include <qhttpresponse.h>

Hello::Hello()
{
    QHttpServer *server = new QHttpServer;
    server->listen(QHostAddress::Any, 5000);
    connect(server, SIGNAL(newRequest(QHttpRequest*, QHttpResponse*)),
            this, SLOT(handle(QHttpRequest*, QHttpResponse*)));
}

void Hello::handle(QHttpRequest *req, QHttpResponse *resp)
{
    qDebug() << "Handling request";
    qDebug() << "Method" << req->method();
    qDebug() << "HTTP Version" << req->httpVersion();
    qDebug() << "URL" << req->url();
    resp->setHeader("Content-Type", "text/html");
    resp->setHeader("Content-Length", "11");
    resp->writeHead(200);
    resp->write(QString("Hello World"));
    resp->end();
}

int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);

    Hello hello;

    app.exec();
}

#include "helloworld.h"

#include <QCoreApplication>

#include <qhttpserver.h>
#include <qhttprequest.h>
#include <qhttpresponse.h>

Hello::Hello()
{
    QHttpServer *server = new QHttpServer;
    server->listen(QHostAddress::Any, 5000);
    connect(server, SIGNAL(newRequest(QHttpRequest*, QHttpResponse*)),
            this, SLOT(handle(QHttpRequest*, QHttpResponse*)));
}

void Hello::handle(QHttpRequest *req, QHttpResponse *resp)
{
    resp->setHeader("Content-Length", "11");
    resp->writeHead(200);
    resp->write(QString("Hello World"));
    resp->end();
}

int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);
    Hello hello;
    app.exec();
}

Remove extra stuff from simplest example


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

struct A;
typedef int A::*param_t;
struct {
  const char *name;
  param_t par;
} *ptr;

// CHECK: type { i8*, i32 }

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

struct A;
typedef int A::*param_t;
struct {
  const char *name;
  param_t par;
} *ptr;

// CHECK: type { i8*, {{i..}} }

Make test 64 bit safe.

Make test 64 bit safe.

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


// RUN: %clang_cc1 -emit-llvm %s -gcodeview -debug-info-kind=limited -o - | FileCheck %s

struct a {
  ~a();
};
template <typename b> struct c : a {
  c(void (b::*)());
};
struct B {
  virtual void e();
};
c<B> *d() { static c<B> f(&B::e); return &f; }

// CHECK: define internal void @"??__Ff@?1??d@@YAPEAU?$c@UB@@@@XZ@YAXXZ"()
// CHECK-SAME: !dbg ![[SUBPROGRAM:[0-9]+]] {
// CHECK: call void @"??1?$c@UB@@@@QEAA@XZ"(%struct.c* @"?f@?1??d@@YAPEAU?$c@UB@@@@XZ@4U2@A"), !dbg ![[LOCATION:[0-9]+]]
// CHECK-NEXT: ret void, !dbg ![[LOCATION]]
// CHECK: ![[SUBPROGRAM]] = distinct !DISubprogram(name: "`dynamic atexit destructor for 'f'"
// CHECK-SAME: flags: DIFlagArtificial
// CHECK: ![[LOCATION]] = !DILocation(line: 0, scope: ![[SUBPROGRAM]])

// RUN: %clang_cc1 -triple x86_64-windows-msvc -emit-llvm %s -gcodeview -debug-info-kind=limited -o - | FileCheck %s

struct a {
  ~a();
};
template <typename b> struct c : a {
  c(void (b::*)());
};
struct B {
  virtual void e();
};
c<B> *d() { static c<B> f(&B::e); return &f; }

// CHECK: define internal void @"??__Ff@?1??d@@YAPEAU?$c@UB@@@@XZ@YAXXZ"()
// CHECK-SAME: !dbg ![[SUBPROGRAM:[0-9]+]] {
// CHECK: call void @"??1?$c@UB@@@@QEAA@XZ"(%struct.c* @"?f@?1??d@@YAPEAU?$c@UB@@@@XZ@4U2@A"), !dbg ![[LOCATION:[0-9]+]]
// CHECK-NEXT: ret void, !dbg ![[LOCATION]]
// CHECK: ![[SUBPROGRAM]] = distinct !DISubprogram(name: "`dynamic atexit destructor for 'f'"
// CHECK-SAME: flags: DIFlagArtificial
// CHECK: ![[LOCATION]] = !DILocation(line: 0, scope: ![[SUBPROGRAM]])

Add triple to new test to try to pacify bots

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


#include "state_machine.hpp"

namespace kg {
    void StateMachine::startState(StateRef newState, bool isReplacing) {
        if (isReplacing && !_states.empty()) {
            _states.pop();
        }

        _states.push(std::move(newState));
        _states.top()->start();
    }

    void StateMachine::exitState() {
        if (_states.empty()) return;

        _states.pop();
        if (!_states.empty()) {
            _states.top()->resume();
        }
    }
}

#include "state_machine.hpp"

namespace kg {
    void StateMachine::startState(StateRef newState, bool isReplacing) {
        if (isReplacing && !_states.empty()) {
            _states.pop();
        }

        if (!isReplacing) {
            _states->top()->pause();
        }

        _states.push(std::move(newState));
        _states.top()->start();
    }

    void StateMachine::exitState() {
        if (_states.empty()) return;

        _states.pop();
        if (!_states.empty()) {
            _states.top()->resume();
        }
    }
}

Call state pause method when not replacing state.


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

#include "base/logging.h"

namespace extensions {

void RegisterChromeServicesForFrame(content::RenderFrameHost* render_frame_host,
                                    const Extension* extension) {
  DCHECK(render_frame_host);
  DCHECK(extension);

  // TODO(kmarshall): Add Mojo service registration.
}

}  // namespace extensions

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

#include "base/bind.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "chrome/common/chrome_switches.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/service_registry.h"
#include "extensions/common/extension.h"
#include "extensions/common/permissions/api_permission.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/common/switches.h"

#if defined(ENABLE_MEDIA_ROUTER)
#include "chrome/browser/media/router/media_router_mojo_impl.h"
#endif

namespace extensions {

void RegisterChromeServicesForFrame(content::RenderFrameHost* render_frame_host,
                                    const Extension* extension) {
  DCHECK(render_frame_host);
  DCHECK(extension);

  content::ServiceRegistry* service_registry =
      render_frame_host->GetServiceRegistry();

#if defined(ENABLE_MEDIA_ROUTER)
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          ::switches::kEnableMediaRouter)) {
    if (extension->permissions_data()->HasAPIPermission(
            APIPermission::kMediaRouterPrivate)) {
      service_registry->AddService(base::Bind(
          media_router::MediaRouterMojoImpl::BindToRequest, extension->id(),
          render_frame_host->GetProcess()->GetBrowserContext()));
    }
  }
#endif  // defined(ENABLE_MEDIA_ROUTER)
}

}  // namespace extensions

Add Media Router Mojo service to the renderer service registry.
Guard access to the Media Router service using a manifest permission.

BUG=464205
R=imcheng

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

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


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// UNSUPPORTED: c++98, c++03

// Verify TEST_WORKAROUND_C1XX_BROKEN_IS_TRIVIALLY_COPYABLE.

#include <type_traits>

#include "test_workarounds.h"

struct S {
  S(S const&) = default;
  S(S&&) = default;
  S& operator=(S const&) = delete;
  S& operator=(S&&) = delete;
};

int main() {
#if defined(TEST_WORKAROUND_C1XX_BROKEN_IS_TRIVIALLY_COPYABLE)
  static_assert(!std::is_trivially_copyable<S>::value, "");
#else
  static_assert(std::is_trivially_copyable<S>::value, "");
#endif
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// UNSUPPORTED: c++98, c++03

// This workaround option is specific to MSVC's C1XX, so we don't care that
// it isn't set for older GCC versions.
// XFAIL: gcc-4.9

// Verify TEST_WORKAROUND_C1XX_BROKEN_IS_TRIVIALLY_COPYABLE.

#include <type_traits>

#include "test_workarounds.h"

struct S {
  S(S const&) = default;
  S(S&&) = default;
  S& operator=(S const&) = delete;
  S& operator=(S&&) = delete;
};

int main() {
#if defined(TEST_WORKAROUND_C1XX_BROKEN_IS_TRIVIALLY_COPYABLE)
  static_assert(!std::is_trivially_copyable<S>::value, "");
#else
  static_assert(std::is_trivially_copyable<S>::value, "");
#endif
}

Fix test failure with GCC 4.9

Fix test failure with GCC 4.9

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


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

#include <limits>

#include "skia/ext/paint_simplifier.h"
#include "third_party/skia/include/core/SkPaint.h"

namespace skia {

PaintSimplifier::PaintSimplifier()
  : INHERITED() {

}

PaintSimplifier::~PaintSimplifier() {

}

bool PaintSimplifier::filter(SkPaint* paint, Type type) {

  // Preserve a modicum of text quality; black & white text is
  // just too blocky, even during a fling.
  if (type != kText_Type) {
    paint->setAntiAlias(false);
  }
  paint->setSubpixelText(false);
  paint->setLCDRenderText(false);

  // Reduce filter level to medium or less. Note that reducing the filter to
  // less than medium can have a negative effect on performance as the filtered
  // image is not cached in this case.
  paint->setFilterLevel(
      std::min(paint->getFilterLevel(), SkPaint::kMedium_FilterLevel));

  paint->setMaskFilter(NULL);

  // Uncomment this line to shade simplified tiles pink during debugging.
  //paint->setColor(SkColorSetRGB(255, 127, 127));

  return true;
}

}  // namespace skia

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

#include "skia/ext/paint_simplifier.h"
#include "third_party/skia/include/core/SkPaint.h"

namespace skia {

PaintSimplifier::PaintSimplifier()
  : INHERITED() {

}

PaintSimplifier::~PaintSimplifier() {

}

bool PaintSimplifier::filter(SkPaint* paint, Type type) {

  // Preserve a modicum of text quality; black & white text is
  // just too blocky, even during a fling.
  if (type != kText_Type) {
    paint->setAntiAlias(false);
  }
  paint->setSubpixelText(false);
  paint->setLCDRenderText(false);

  paint->setMaskFilter(NULL);

  // Uncomment this line to shade simplified tiles pink during debugging.
  //paint->setColor(SkColorSetRGB(255, 127, 127));

  return true;
}

}  // namespace skia

Revert 273648 "skia: Use medium filter quality in PaintSimplifier."

> skia: Use medium filter quality in PaintSimplifier.
>
> Preventing all bitmap filtering in the paint simplifier is a bad
> idea as it's very cache unfriendly when down-sampling due to
> requiring both the full size decoded image and the high/medium
> quality image normally used to be cached for good performance.
>
> However, forcing medium quality filtering is worthwhile as it's
> faster than high quality and still provides caching benefits.
>
> BUG=
>
> Review URL: https://codereview.chromium.org/305623008

Looks like this had a negative effect on memory usage.

TBR=reveman@chromium.org
BUG=379164

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

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


/*******************************************************
 * Copyright (c) 2016, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#if defined(WITH_GRAPHICS)
#include <err_cuda.hpp>
#include <GraphicsResourceManager.hpp>

namespace cuda
{
ShrdResVector GraphicsResourceManager::registerResources(std::vector<uint32_t> resources)
{
    ShrdResVector output;

    auto deleter = [](CGR_t* handle) {
        CUDA_CHECK(cudaGraphicsUnregisterResource(*handle));
        delete handle;
    };

    for (auto id: resources) {
        CGR_t r;
        CUDA_CHECK(cudaGraphicsGLRegisterBuffer(&r, id, cudaGraphicsMapFlagsWriteDiscard));
        output.emplace_back(new CGR_t(r), deleter);
    }

    return output;
}
}
#endif

/*******************************************************
 * Copyright (c) 2016, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#if defined(WITH_GRAPHICS)
#include <err_cuda.hpp>
#include <GraphicsResourceManager.hpp>

namespace cuda
{
ShrdResVector GraphicsResourceManager::registerResources(std::vector<uint32_t> resources)
{
    ShrdResVector output;

    auto deleter = [](CGR_t* handle) {
        //FIXME Having a CUDA_CHECK around unregister
        //call is causing invalid GL context.
        //Moving ForgeManager class singleton as data
        //member of DeviceManager with proper ordering
        //of member destruction doesn't help either.
        //Calling makeContextCurrent also doesn't help.
        cudaGraphicsUnregisterResource(*handle);
        delete handle;
    };

    for (auto id: resources) {
        CGR_t r;
        CUDA_CHECK(cudaGraphicsGLRegisterBuffer(&r, id, cudaGraphicsMapFlagsWriteDiscard));
        output.emplace_back(new CGR_t(r), deleter);
    }

    return output;
}
}
#endif

Work around for gfx interop resource cleanup in cuda backend


#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetEventTest
#include <boost/test/unit_test.hpp>

#include "../JPetAnalysisTools/JPetAnalysisTools.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(constructor_getHitsOrderedByTime)
{
  std::vector<JPetHit> hits(4);
  hits[0].setTime(2);
  hits[1].setTime(1);
  hits[2].setTime(4);
  hits[3].setTime(3);
  auto results = JPetAnalysisTools::getHitsOrderedByTime(hits);
  BOOST_REQUIRE_EQUAL(results[0].getTime(), 1);
  BOOST_REQUIRE_EQUAL(results[1].getTime(), 2);
  BOOST_REQUIRE_EQUAL(results[2].getTime(), 3);
  BOOST_REQUIRE_EQUAL(results[3].getTime(), 4);
}

BOOST_AUTO_TEST_SUITE_END()

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetEventTest
#include <boost/test/unit_test.hpp>

#include "../JPetAnalysisTools/JPetAnalysisTools.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(constructor_getHitsOrderedByTime)
{
  std::vector<JPetHit> hits(4);
  hits[0].setTime(2);
  hits[1].setTime(1);
  hits[2].setTime(4);
  hits[3].setTime(3);
  auto results = JPetAnalysisTools::getHitsOrderedByTime(hits);
  double epsilon = 0.0001;
  BOOST_REQUIRE_CLOSE(results[0].getTime(), 1, epsilon );
  BOOST_REQUIRE_CLOSE(results[1].getTime(), 2, epsilon );
  BOOST_REQUIRE_CLOSE(results[2].getTime(), 3, epsilon );
  BOOST_REQUIRE_CLOSE(results[3].getTime(), 4, epsilon );
}

BOOST_AUTO_TEST_SUITE_END()

Change tests in JPetAnalysisTools to use double instead of int


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

SimpleString::SimpleString ()
: buffer(new char [1])
{
	buffer [0] = '\0';
}

SimpleString::SimpleString (const char *otherBuffer)
: buffer (new char [strlen (otherBuffer) + 1])
{
	strcpy (buffer, otherBuffer);
}

SimpleString::SimpleString (const SimpleString& other)
{
	buffer = new char [other.size() + 1];
	strcpy(buffer, other.buffer);
}

SimpleString & SimpleString::operator= (const SimpleString& other)
{
	delete buffer;
	buffer = new char [other.size() + 1];
	strcpy(buffer, other.buffer);
	return *this;
}

char *SimpleString::asCharString () const
{
	return buffer;
}

int SimpleString::size() const
{
	return strlen (buffer);
}

SimpleString::~SimpleString ()
{
	delete [] buffer;
}

bool operator== (const SimpleString& left, const SimpleString& right)
{
	return !strcmp (left.asCharString (), right.asCharString ());
}

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

SimpleString::SimpleString ()
: buffer(new char [1])
{
	buffer [0] = '\0';
}

SimpleString::SimpleString (const char *otherBuffer)
: buffer (new char [strlen (otherBuffer) + 1])
{
	strcpy (buffer, otherBuffer);
}

SimpleString::SimpleString (const SimpleString& other)
{
	buffer = new char [other.size() + 1];
	strcpy(buffer, other.buffer);
}

SimpleString & SimpleString::operator= (const SimpleString& other)
{
	delete []buffer;
	buffer = new char [other.size() + 1];
	strcpy(buffer, other.buffer);
	return *this;
}

char *SimpleString::asCharString () const
{
	return buffer;
}

int SimpleString::size() const
{
	return strlen (buffer);
}

SimpleString::~SimpleString ()
{
	delete [] buffer;
}

bool operator== (const SimpleString& left, const SimpleString& right)
{
	return !strcmp (left.asCharString (), right.asCharString ());
}

Fix a bug found by @rperrot

Fix a bug found by @rperrot


// Copyright 2017 The CRC32C Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include "gtest/gtest.h"

#include "./crc32c_arm64.h"
#include "./crc32c_extend_unittests.h"

namespace crc32c {

#if HAVE_ARM64_CRC32C

struct Arm64TestTraits {
  static uint32_t Extend(uint32_t crc, const uint8_t* data, size_t count) {
    return ExtendArm64(crc, data, count);
  }
};

INSTANTIATE_TYPED_TEST_CASE_P(Arm64, ExtendTest, Arm64TestTraits);

#endif  // HAVE_ARM64_CRC32C

}  // namespace crc32c

// Copyright 2017 The CRC32C Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include "gtest/gtest.h"

#include "./crc32c_arm64.h"
#include "./crc32c_extend_unittests.h"

namespace crc32c {

#if HAVE_ARM64_CRC32C

struct Arm64TestTraits {
  static uint32_t Extend(uint32_t crc, const uint8_t* data, size_t count) {
    return ExtendArm64(crc, data, count);
  }
};

INSTANTIATE_TYPED_TEST_SUITE_P(Arm64, ExtendTest, Arm64TestTraits);

#endif  // HAVE_ARM64_CRC32C

}  // namespace crc32c

Replace missed instance of TEST_CASE with TEST_SUITE.


//============================================================================
// Name        : benchpress.cpp
// Author      : Ulrik Kofoed Pedersen
// Version     :
// Copyright   : MIT. See LICENSE file.
// Description : Use blosc with different algorithms to compress data from
//               datasets in an HDF5 file - and benchmark the performance
//============================================================================

#include <iostream>
using namespace std;

#include <blosc.h>
#include <hdf5_hl.h>

int main() {
	cout << "hi there" << endl; // prints hi there
	return 0;
}

//============================================================================
// Name        : benchpress.cpp
// Author      : Ulrik Kofoed Pedersen
// Version     :
// Copyright   : MIT. See LICENSE file.
// Description : Use blosc with different algorithms to compress data from
//               datasets in an HDF5 file - and benchmark the performance
//============================================================================

#include <iostream>
using namespace std;

#include <blosc.h>
#include <hdf5.h>
#include <hdf5_hl.h>

int main() {
	cout << "hi there" << endl; // prints hi there
	return 0;
}

Include main hdf5 header to successful build


#include "paddle.h"

int Paddle::numOfPaddles = 0;

void Paddle::update()
{
    al_get_mouse_state(&mouseState);
    mouseY = al_get_mouse_state_axis(&mouseState, 1);

    setPosition(x, mouseY);
}

void Paddle::reset()
{
    al_get_mouse_state(&mouseState);
    mouseY = al_get_mouse_state_axis(&mouseState, 1);

    setPosition(x, mouseY);
}

#include "Paddle.h"

int Paddle::numOfPaddles = 0;

void Paddle::update()
{
    al_get_mouse_state(&mouseState);
    mouseY = al_get_mouse_state_axis(&mouseState, 1);

    setPosition(x, mouseY);
}

void Paddle::reset()
{
    al_get_mouse_state(&mouseState);
    mouseY = al_get_mouse_state_axis(&mouseState, 1);

    setPosition(x, mouseY);
}

FIx GCC was unable to compile in Linux

FIx GCC was unable to compile in Linux

GCC is a case sensitive program in Linux and a #include directive was incorrectly typed.

Previous              New
paddle.h      ->      Paddle.h


#include <stdio.h>

#include "mutex.h"
#include "thread.h"
#include "window.h"

using System::Window;

class DisplayThreadEntry : public System::ThreadEntry {
public:
	virtual ~DisplayThreadEntry() {}

	virtual void *Run(void *arg) {
		Window *mainWindow = Window::Create();
		int exitValue = mainWindow->DoMessageLoop();
		delete mainWindow;
	}
};

int applicationMain()
{
	DisplayThreadEntry displayThreadEntry;
	System::Thread *displayThread = System::Thread::Create(&displayThreadEntry);
	displayThread->Start();
	displayThread->Wait();
	return 0;
}

#include <stdio.h>

#include "mutex.h"
#include "thread.h"
#include "window.h"

using System::Window;
using System::Thread;
using System::ThreadEntry;

class DisplayThreadEntry : public ThreadEntry {
public:
	virtual ~DisplayThreadEntry() {}

	virtual void *Run(void *arg) {
		Window *mainWindow = Window::Create();
		int exitValue = mainWindow->DoMessageLoop();
		delete mainWindow;
	}
};

int applicationMain()
{
	DisplayThreadEntry displayThreadEntry;
	Thread *displayThread = Thread::Create(&displayThreadEntry);
	displayThread->Start();
	displayThread->Wait();
	return 0;
}

Clean up some namespace things

Clean up some namespace things


#include <GL/glew.h>
#include <SDL2/SDL.h>

int main(void)
{
  int flags = SDL_WINDOW_OPENGL | SDL_RENDERER_PRESENTVSYNC;

  SDL_Init(SDL_INIT_EVERYTHING);
  auto window = SDL_CreateWindow("title", 0, 0, 320, 240, flags);
  auto context = SDL_GL_CreateContext(window);

  glewInit();
  glClearColor(0, 1, 0, 1);
  glClear(GL_COLOR_BUFFER_BIT);

  SDL_Event event;
  while (true)
  {
    while (SDL_PollEvent(&event) != 0)
      if (event.type == SDL_QUIT)
        goto quit;
    SDL_Delay(10);
    SDL_GL_SwapWindow(window);
  }

quit:
  SDL_Quit();
  return 0;
}

#include <GL/glew.h>
#include <SDL2/SDL.h>

int main(void)
{
  int flags = SDL_WINDOW_OPENGL | SDL_RENDERER_PRESENTVSYNC;

  SDL_Init(SDL_INIT_EVERYTHING);
  auto window = SDL_CreateWindow("title", 0, 0, 320, 240, flags);
  auto context = SDL_GL_CreateContext(window);

  glewInit();
  glClearColor(0, 1, 0, 1);
  glClear(GL_COLOR_BUFFER_BIT);

  SDL_Event event;
  while (true)
  {
    while (SDL_PollEvent(&event) != 0)
      if (event.type == SDL_QUIT)
        goto quit;
    SDL_Delay(10);
    SDL_GL_SwapWindow(window);
  }

quit:
  SDL_DestroyWindow(window);
  SDL_Quit();
  return 0;
}

Add code to destroy window upon quit

Add code to destroy window upon quit


#include <iostream>
#include "gtest/gtest.h"

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

#include "core/logging.hpp"
#include <iostream>
#include <gtest/gtest.h>

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

Test Main: Set up logging

Test Main: Set up logging

This will prevent segfaults that would otherwise happen in tests.


#include <glog/logging.h>
#include <atom/atom.h>
#include <core.h>

int main(int argc, char **argv)
{
  atom_initialize();
  {
    ATOM_GC;

    atom_attach_thread();

    start_core(argc, argv);
  }
  atom_terminate();

  return 0;
}

Remove extra blank line and include

Remove extra blank line and include


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "bucketfactory.h"

using document::BucketId;
using document::DocumentId;
using storage::spi::Bucket;
using storage::spi::PartitionId;

namespace proton {

BucketId
BucketFactory::getBucketId(const DocumentId &docId)
{
    BucketId bId = docId.getGlobalId().convertToBucketId();
    bId.setUsedBits(getNumBucketBits());
    return bId;
}

Bucket
BucketFactory::getBucket(const DocumentId &docId)
{
    return Bucket(document::Bucket(document::BucketSpace::placeHolder(), getBucketId(docId)), PartitionId(0));
}

} // namespace proton

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "bucketfactory.h"
#include <vespa/persistence/spi/test.h>

using document::BucketId;
using document::DocumentId;
using storage::spi::Bucket;
using storage::spi::PartitionId;
using storage::spi::test::makeBucket;

namespace proton {

BucketId
BucketFactory::getBucketId(const DocumentId &docId)
{
    BucketId bId = docId.getGlobalId().convertToBucketId();
    bId.setUsedBits(getNumBucketBits());
    return bId;
}

Bucket
BucketFactory::getBucket(const DocumentId &docId)
{
    return makeBucket(getBucketId(docId));
}

} // namespace proton

Consolidate creation of storage::spi::Bucket in unit tests.


#include <cstdint>
#include <memory>
#include <iostream>

class Box {
public:
    Box(int x) : x_(x) {}
    virtual ~Box() = default;
    void Print() {
        std::cout << x_ << "\n";
    }
private:
    int x_ {0};
};

std::unique_ptr<Box> Create(int x) {
    return std::make_unique<Box>(x);
}

int main(void) {
    std::unique_ptr<Box> p = std::move(Create(1));
    p->Print();
    std::unique_ptr<Box> q(Create(1));
    q->Print();

    using Num = int;
    constexpr bool y = true;
    constexpr Num x = static_cast<decltype(x)>(y);
    std::cout << x << " " << y << "\n";

    bool b = false;
    Num a = static_cast<decltype(a)>(b);
    std::cout << a << " " << b << "\n";
    return 0;
}

/*
Local Variables:
mode: c++
coding: utf-8-dos
tab-width: nil
c-file-style: "stroustrup"
Last:
*/

#include <cstdint>
#include <memory>
#include <iostream>

class Box {
public:
    Box(int x) : x_(x) {}
    virtual ~Box() = default;
    void Print() {
        std::cout << x_ << "\n";
    }
private:
    int x_ {0};
};

std::unique_ptr<Box> Create(int x) {
    return std::make_unique<Box>(x);
}

void moveUnique(void) {
    std::unique_ptr<Box> p = std::move(Create(1));
    p->Print();
}

void constructUnique(void) {
    std::unique_ptr<Box> p(Create(2));
    p->Print();
}

void moveToShared(void) {
    std::shared_ptr<Box> p = std::move(Create(3));
    p->Print();
}

void constructShared(void) {
    std::shared_ptr<Box> p(Create(4));
    p->Print();
}

void decltypeCast(void) {
    using Num = int;
    constexpr bool y = true;
    constexpr Num x = static_cast<decltype(x)>(y);
    std::cout << x << " " << y << "\n";

    bool b = false;
    Num a = static_cast<decltype(a)>(b);
    std::cout << a << " " << b << "\n";
}

int main(void) {
    moveUnique();
    constructUnique();
    moveToShared();
    constructShared();
    decltypeCast();
    return 0;
}

/*
Local Variables:
mode: c++
coding: utf-8-dos
tab-width: nil
c-file-style: "stroustrup"
Last:
*/

Create a shared_ptr from a unique_ptr

Create a shared_ptr from a unique_ptr


#define CATCH_CONFIG_RUNNER
#include <catch.hpp>

int main(int argc, char * const argv[])
{
	int result = Catch::Session().run(argc, argv);

#ifdef WIN32
	system("PAUSE");
#endif

	return result;
}

#define CATCH_CONFIG_RUNNER
#include <catch.hpp>

#include <ionCore.h>

int main(int argc, char * const argv[])
{
	int result = Catch::Session().run(argc, argv);

#ifdef WIN32
	ion::WaitForUser();
#endif

	return result;
}

[TestUnits] Use ionCore alternative to system("PAUSE")


#include <SFML/Graphics.hpp>
//#include "libs/GUI-SFML/include/GUI-SFML.hpp"
#include <iostream>
#include "Game.hpp"

int main()
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
    //gsf::GUIEnvironment environment( window );

    Game game(false, true, false);
    game.run();

    return 0;
}

#include <SFML/Graphics.hpp>
//#include "libs/GUI-SFML/include/GUI-SFML.hpp"
#include <iostream>
#include "Game.hpp"

int main()
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
    //gsf::GUIEnvironment environment( window );
	bool soundEnabled{ false };

    Game game(false, true, soundEnabled);
    game.run();

    return 0;
}

Use var for enabling or disabling sound

Use var for enabling or disabling sound


#include <iostream>
#include <opencv2/opencv.hpp>

#include "clicker.hpp"

using namespace cv;
using namespace std;

const char* window_title = "Join-Robockets Clientside Software";

int main() {
    //Initialize camera.
    VideoCapture cap(CV_CAP_ANY);
    if(!cap.isOpened()) {
        cerr << "Could not open image capture device!" << endl;
        exit(EXIT_FAILURE);
    }

    Mat frame;
    namedWindow(window_title);
    while(1) {
        //Capture and show image.
        cap >> frame;
        imshow(window_title, frame);

        //Quit if any key has been pressed.
        if(waitKey(30) >= 0) {
            break;
        }
    }
    //VideoCapture is closed automatically.
    return 0;
}

#include <iostream>
#include <opencv2/opencv.hpp>

#include "clicker.hpp"

using namespace cv;
using namespace std;

string window_title = "Join-Robockets Clientside Software";

int main() {
    //Initialize camera.
    VideoCapture cap(CV_CAP_ANY);
    if(!cap.isOpened()) {
        cerr << "Could not open image capture device!" << endl;
        exit(EXIT_FAILURE);
    }

    Mat frame;
    namedWindow(window_title);
    while(1) {
        //Capture and show image.
        cap >> frame;
        imshow(window_title, frame);

        //Quit if any key has been pressed.
        if(waitKey(30) >= 0) {
            break;
        }
    }
    //VideoCapture is closed automatically.
    return 0;
}

Use C++ string instead of C string

Use C++ string instead of C string


// Copyright 2015 PDFium 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 "testing/embedder_test.h"
#include "testing/gtest/include/gtest/gtest.h"

class FPDFRenderPatternEmbeddertest : public EmbedderTest {};

TEST_F(FPDFRenderPatternEmbeddertest, LoadError_547706) {
  // Test shading where object is a dictionary instead of a stream.
  EXPECT_TRUE(OpenDocument("bug_547706.pdf"));
  FPDF_PAGE page = LoadPage(0);
  RenderPage(page);
  UnloadPage(page);
}

// Copyright 2015 PDFium 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 "testing/embedder_test.h"
#include "testing/gtest/include/gtest/gtest.h"

class FPDFRenderPatternEmbeddertest : public EmbedderTest {};

TEST_F(FPDFRenderPatternEmbeddertest, LoadError_547706) {
  // Test shading where object is a dictionary instead of a stream.
  EXPECT_TRUE(OpenDocument("bug_547706.pdf"));
  FPDF_PAGE page = LoadPage(0);
  FPDF_BITMAP bitmap = RenderPage(page);
  FPDFBitmap_Destroy(bitmap);
  UnloadPage(page);
}

Fix a memory leak in FPDFPageFuncEmbeddertest.

R=dsinclair@chromium.org

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


/*******************************************************************************
 * Copyright 2013-2014 Aerospike, 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 <node.h>
#include "enums.h"

using namespace v8;

#define set(__obj, __name, __value) __obj->Set(String::NewSymbol(__name), Integer::New(__value), ReadOnly)

Handle<Object> indexType()
{
    HANDLESCOPE;
    Handle<Object> obj = Object::New();
    set(obj, "NUMERIC",    0);
    set(obj, "STRING",     1);
    return scope.Close(obj);
}

/*******************************************************************************
 * Copyright 2013-2014 Aerospike, 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 <node.h>
#include "enums.h"

using namespace v8;

#define set(__obj, __name, __value) __obj->Set(String::NewSymbol(__name), Integer::New(__value), ReadOnly)

Handle<Object> indexType()
{
    HANDLESCOPE;
    Handle<Object> obj = Object::New();
    set(obj, "STRING",    0);
    set(obj, "NUMERIC",     1);
    return scope.Close(obj);
}

Fix to match the enum definitions in C and nodejs for indextypes.


#include "Controller.h"
#include "JobHandler.h"
#include "JobQueue.h"
#include "Sensor.h"
#include <list>

std::list<Sensor> sensors;
std::list<Controller> controllers;
std::list<JobHandler> jobHandlers;
JobQueue jobQueue;

/** Initializes a Sensor object for each sensor */
void initializeSensors() {
	// "TODO: initializeSensors"
}

/** Initializes a Controller object for each controller */
void initializeControllers() {
	// "TODO: initializeControllers"
}

/** Initializes a JobHandler object for each job type */
void initializeJobHandlers() {
	// "TODO: initializeJobHandlers"
}

/** Initializes the JobQueue object */
void initializeJobQueue() {
	// "TODO: initializeJobQueue"
}

/** Returns the JobHandler object suited to deal with the given job */
JobHandler getHandlerByJob(std::string job) {
	// "TODO: initializeJobQueue"
}

int main(int argc, char *argv[]) {
	initializeSensors();
	initializeControllers();
	initializeJobHandlers();
	initializeJobQueue();

	/** Main execution loop */
	while (1) {
		std::string job;
		if (jobQueue.getJob(&job)) {
			JobHandler handler = getHandlerByJob(job);
			handler.execute(job);
		}

		// TODO: Complete this function
	}
}

#include "Controller.h"
#include "JobHandler.h"
#include "JobQueue.h"
#include "Sensor.h"
#include <vector>

std::vector<Sensor> sensors;
std::vector<Controller> controllers;
std::vector<JobHandler> jobHandlers;
JobQueue jobQueue;

/** Initializes a Sensor object for each sensor */
void initializeSensors() {
	// "TODO: initializeSensors"
}

/** Initializes a Controller object for each controller */
void initializeControllers() {
	// "TODO: initializeControllers"
}

/** Initializes a JobHandler object for each job type */
void initializeJobHandlers() {
	// "TODO: initializeJobHandlers"
}

/** Initializes the JobQueue object */
void initializeJobQueue() {
	// "TODO: initializeJobQueue"
}

/** Returns the JobHandler object suited to deal with the given job */
JobHandler getHandlerByJob(std::string job) {
	// "TODO: initializeJobQueue"
}

int main(int argc, char *argv[]) {
	initializeSensors();
	initializeControllers();
	initializeJobHandlers();
	initializeJobQueue();

	/** Main execution loop */
	while (1) {
		std::string job;
		if (jobQueue.getJob(&job)) {
			JobHandler handler = getHandlerByJob(job);
			handler.execute(job);
		}

		// TODO: Complete this function
	}
}

Use vector instead of list

Use vector instead of list


/******************************************************************************
 * This file is part of dirtsand.                                             *
 *                                                                            *
 * dirtsand is free software: you can redistribute it and/or modify           *
 * it under the terms of the GNU Affero General Public License as             *
 * published by the Free Software Foundation, either version 3 of the         *
 * License, or (at your option) any later version.                            *
 *                                                                            *
 * dirtsand is distributed in the hope that it will be useful,                *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
 * GNU Affero General Public License for more details.                        *
 *                                                                            *
 * You should have received a copy of the GNU Affero General Public License   *
 * along with dirtsand.  If not, see <http://www.gnu.org/licenses/>.          *
 ******************************************************************************/

#include "SimulationMsg.h"

void MOUL::SubWorldMsg::read(DS::Stream* stream)
{
    m_world.read(stream);
}

void MOUL::SubWorldMsg::write(DS::Stream* stream) const
{
    m_world.write(stream);
}

/******************************************************************************
 * This file is part of dirtsand.                                             *
 *                                                                            *
 * dirtsand is free software: you can redistribute it and/or modify           *
 * it under the terms of the GNU Affero General Public License as             *
 * published by the Free Software Foundation, either version 3 of the         *
 * License, or (at your option) any later version.                            *
 *                                                                            *
 * dirtsand is distributed in the hope that it will be useful,                *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
 * GNU Affero General Public License for more details.                        *
 *                                                                            *
 * You should have received a copy of the GNU Affero General Public License   *
 * along with dirtsand.  If not, see <http://www.gnu.org/licenses/>.          *
 ******************************************************************************/

#include "SimulationMsg.h"

void MOUL::SubWorldMsg::read(DS::Stream* stream)
{
    MOUL::Message::read(stream);
    m_world.read(stream);
}

void MOUL::SubWorldMsg::write(DS::Stream* stream) const
{
    MOUL::Message::write(stream);
    m_world.write(stream);
}

Fix missing write call in SubWorldMsg

Fix missing write call in SubWorldMsg


#include <QtGui/QApplication>
#include <QtCore/QProcess>
#include <QtWebKit/QWebView>

#if defined(Q_OS_SYMBIAN) && defined(ORIENTATIONLOCK)
#include <eikenv.h>
#include <eikappui.h>
#include <aknenv.h>
#include <aknappui.h>
#endif // Q_OS_SYMBIAN && ORIENTATIONLOCK

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

#if defined(Q_OS_SYMBIAN) && defined(ORIENTATIONLOCK)
    const CAknAppUiBase::TAppUiOrientation uiOrientation = CAknAppUi::EAppUiOrientationLandscape;
    CAknAppUi* appUi = dynamic_cast<CAknAppUi*> (CEikonEnv::Static()->AppUi());
    TRAPD(error,
        if (appUi)
            appUi->SetOrientationL(uiOrientation);
    );
    Q_UNUSED(error)
#endif // ORIENTATIONLOCK

    QWebView webView;
    webView.load(QString::fromLatin1("html/examples/kitchensink/index.html"));

#if defined(Q_OS_SYMBIAN)
    webView.showFullScreen();
#elif defined(Q_WS_MAEMO_5)
    webView.showMaximized();
#else
    webView.show();
#endif

    return app.exec();
}

#include <QtGui>
#include <QtWebKit>

#if defined(Q_OS_SYMBIAN) && defined(ORIENTATIONLOCK)
#include <eikenv.h>
#include <eikappui.h>
#include <aknenv.h>
#include <aknappui.h>
#endif // Q_OS_SYMBIAN && ORIENTATIONLOCK

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

#if defined(Q_OS_SYMBIAN) && defined(ORIENTATIONLOCK)
    const CAknAppUiBase::TAppUiOrientation uiOrientation = CAknAppUi::EAppUiOrientationLandscape;
    CAknAppUi* appUi = dynamic_cast<CAknAppUi*> (CEikonEnv::Static()->AppUi());
    TRAPD(error,
        if (appUi)
            appUi->SetOrientationL(uiOrientation);
    );
    Q_UNUSED(error)
#endif // ORIENTATIONLOCK

    const QSize screenSize(640, 360);

    QGraphicsScene scene;

    QGraphicsView view(&scene);
    view.setFrameShape(QFrame::NoFrame);
    view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    QGraphicsWebView webview;
    webview.resize(screenSize);
    webview.load(QString::fromLatin1("html/examples/kitchensink/index.html"));

    scene.addItem(&webview);

#if defined(Q_OS_SYMBIAN)
    view.showFullScreen();
#elif defined(Q_WS_MAEMO_5)
    view.showMaximized();
#else
    view.resize(screenSize);
    view.show();
#endif

    return app.exec();
}

Use QGraphicsWebView instead of QWebView

As suggested by http://trac.webkit.org/wiki/QtWebKitTiling

Works on Qt 4.6 and up.


#include "perf_precomp.hpp"

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

typedef std::tr1::tuple<String, bool> VideoCapture_Reading_t;
typedef perf::TestBaseWithParam<VideoCapture_Reading_t> VideoCapture_Reading;

PERF_TEST_P(VideoCapture_Reading, ReadFile,
            testing::Combine( testing::Values( "highgui/video/big_buck_bunny.avi",
                                               "highgui/video/big_buck_bunny.mov",
                                               "highgui/video/big_buck_bunny.mp4",
                                               "highgui/video/big_buck_bunny.mpg",
                                               "highgui/video/big_buck_bunny.wmv" ),
                              testing::Values(true, true, true, true, true) ))
{
  string filename = getDataPath(get<0>(GetParam()));

  VideoCapture cap;

  TEST_CYCLE() cap.open(filename);

  bool dummy = cap.isOpened();
  SANITY_CHECK(dummy);
}

#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<String> VideoCapture_Reading;

PERF_TEST_P(VideoCapture_Reading, ReadFile, testing::Values( "highgui/video/big_buck_bunny.avi",
                                               "highgui/video/big_buck_bunny.mov",
                                               "highgui/video/big_buck_bunny.mp4",
                                               "highgui/video/big_buck_bunny.mpg",
                                               "highgui/video/big_buck_bunny.wmv" ) )
{
  string filename = getDataPath(GetParam());

  VideoCapture cap;

  TEST_CYCLE() cap.open(filename);

  bool dummy = cap.isOpened();
  SANITY_CHECK(dummy);
}

Remove second argument from VideoCapture_Reading perf test


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

#define CHECK(f, s32, s64) \
    static_assert(offsetof(buffer_t, f) == (sizeof(void*) == 8 ? (s64) : (s32)), #f " is wrong")

int main(int argc, char **argv) {

    CHECK(dev, 0, 0);
    CHECK(host, 8, 8);
    CHECK(extent, 12, 16);
    CHECK(stride, 28, 32);
    CHECK(min, 44, 48);
    CHECK(elem_size, 60, 64);
    CHECK(host_dirty, 64, 68);
    CHECK(dev_dirty, 65, 69);
    CHECK(_padding, 66, 70);

    static_assert(sizeof(buffer_t) == (sizeof(void*) == 8 ? 72 : 68), "size is wrong");

    // Ensure alignment is at least that of a pointer.
    static_assert(alignof(buffer_t) >= alignof(uint8_t*), "align is wrong");

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

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

#define CHECK(f, s32, s64) \
    static_assert(offsetof(buffer_t, f) == (sizeof(void*) == 8 ? (s64) : (s32)), #f " is wrong")

int main(int argc, char **argv) {

    CHECK(dev, 0, 0);
    CHECK(host, 8, 8);
    CHECK(extent, 12, 16);
    CHECK(stride, 28, 32);
    CHECK(min, 44, 48);
    CHECK(elem_size, 60, 64);
    CHECK(host_dirty, 64, 68);
    CHECK(dev_dirty, 65, 69);
    CHECK(_padding, 66, 70);

    static_assert(sizeof(void*) == 8 ?
                    sizeof(buffer_t) == 72 :
                    // Some compilers may insert padding at the end of the struct
                    // so that an array will stay appropriately aligned for
                    // the int64 field.
                    (sizeof(buffer_t) == 68 || sizeof(buffer_t) == 72), "size is wrong");

    // Ensure alignment is at least that of a pointer.
    static_assert(alignof(buffer_t) >= alignof(uint8_t*), "align is wrong");

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

Allow for struct padding in test

Allow for struct padding in test

Former-commit-id: 5beecba366bb0e643172aeace0c57cde4672956a


//===-- TargetOptionsCommandFlags.cpp ---------------------------*- C++ -*-===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file exists as a place for global variables defined in LLVM's
// CodeGen/CommandFlags.def. By putting the resulting object file in
// an archive and linking with it, the definitions will automatically be
// included when needed and skipped when already present.
//
//===----------------------------------------------------------------------===//

#include "lld/Common/TargetOptionsCommandFlags.h"

#include "llvm/CodeGen/CommandFlags.def"
#include "llvm/Target/TargetOptions.h"

// Define an externally visible version of
// InitTargetOptionsFromCodeGenFlags, so that its functionality can be
// used without having to include llvm/CodeGen/CommandFlags.def, which
// would lead to multiple definitions of the command line flags.
llvm::TargetOptions lld::InitTargetOptionsFromCodeGenFlags() {
  return ::InitTargetOptionsFromCodeGenFlags();
}

llvm::Optional<llvm::CodeModel::Model> lld::GetCodeModelFromCMModel() {
  return getCodeModel();
}

std::string lld::GetCPUStr() { return ::getCPUStr(); }

//===-- TargetOptionsCommandFlags.cpp ---------------------------*- C++ -*-===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file exists as a place for global variables defined in LLVM's
// CodeGen/CommandFlags.def. By putting the resulting object file in
// an archive and linking with it, the definitions will automatically be
// included when needed and skipped when already present.
//
//===----------------------------------------------------------------------===//

#include "lld/Common/TargetOptionsCommandFlags.h"

#include "llvm/CodeGen/CommandFlags.inc"
#include "llvm/Target/TargetOptions.h"

// Define an externally visible version of
// InitTargetOptionsFromCodeGenFlags, so that its functionality can be
// used without having to include llvm/CodeGen/CommandFlags.def, which
// would lead to multiple definitions of the command line flags.
llvm::TargetOptions lld::InitTargetOptionsFromCodeGenFlags() {
  return ::InitTargetOptionsFromCodeGenFlags();
}

llvm::Optional<llvm::CodeModel::Model> lld::GetCodeModelFromCMModel() {
  return getCodeModel();
}

std::string lld::GetCPUStr() { return ::getCPUStr(); }

Rename to match an LLVM change

Rename to match an LLVM change

git-svn-id: f6089bf0e6284f307027cef4f64114ee9ebb0424@329841 91177308-0d34-0410-b5e6-96231b3b80d8


// Tests for instrumentation of C++ constructors and destructors.
//
// RUN: %clang_cc1 -triple x86_64-apple-macosx10.11.0 -x c++ %s -o - -emit-llvm -fprofile-instrument=clang | FileCheck %s

struct Foo {
  Foo() {}
  Foo(int) {}
  ~Foo() {}
};

struct Bar : public Foo {
  Bar() {}
  Bar(int x) : Foo(x) {}
  ~Bar();
};

Foo foo;
Foo foo2(1);
Bar bar;

// Profile data for complete constructors and destructors must absent.

// CHECK-NOT: @__profc__ZN3FooC1Ev
// CHECK-NOT: @__profc__ZN3FooC1Ei
// CHECK-NOT: @__profc__ZN3FooD1Ev
// CHECK-NOT: @__profc__ZN3BarC1Ev
// CHECK-NOT: @__profc__ZN3BarD1Ev
// CHECK-NOT: @__profc__ZN3FooD1Ev

int main() {
}

// Tests for instrumentation of C++ constructors and destructors.
//
// RUN: %clang_cc1 -triple x86_64-apple-macosx10.11.0 -x c++ %s -o %t -emit-llvm -fprofile-instrument=clang
// RUN: FileCheck %s -input-file=%t -check-prefix=INSTR
// RUN: FileCheck %s -input-file=%t -check-prefix=NOINSTR

struct Foo {
  Foo() {}
  Foo(int) {}
  ~Foo() {}
};

struct Bar : public Foo {
  Bar() {}
  Bar(int x) : Foo(x) {}
  ~Bar();
};

Foo foo;
Foo foo2(1);
Bar bar;

// Profile data for complete constructors and destructors must absent.

// INSTR: @__profc_main =
// INSTR: @__profc__ZN3FooC2Ev =
// INSTR: @__profc__ZN3FooD2Ev =
// INSTR: @__profc__ZN3FooC2Ei =
// INSTR: @__profc__ZN3BarC2Ev =

// NOINSTR-NOT: @__profc__ZN3FooC1Ev
// NOINSTR-NOT: @__profc__ZN3FooC1Ei
// NOINSTR-NOT: @__profc__ZN3FooD1Ev
// NOINSTR-NOT: @__profc__ZN3BarC1Ev
// NOINSTR-NOT: @__profc__ZN3BarD1Ev
// NOINSTR-NOT: @__profc__ZN3FooD1Ev

int main() {
}

Make a test more explicit. NFC.

[profiling] Make a test more explicit. NFC.

The cxx-structors.cpp test checks that some instrumentation doesn't
appear, but it should be more explicit about which instrumentation it
actually expects to appear.

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


//----------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2001, 2002, 2003 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------------------------------------------

// only compile this file if in 2d
#if deal_II_dimension == 2

#include <fe/fe_q.h>

// constraint matrices in 2d are now implemented by computing them on
// the fly for all polynomial degrees

template <>
const double * const
FE_Q<2>::Matrices::constraint_matrices[] = {};

template <>
const unsigned int
FE_Q<2>::Matrices::n_constraint_matrices = 0;

#else // #if deal_II_dimension
// On gcc2.95 on Alpha OSF1, the native assembler does not like empty
// files, so provide some dummy code
namespace { void dummy () {} }
#endif // #if deal_II_dimension == 2

//----------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2001, 2002, 2003, 2004 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------------------------------------------

// only compile this file if in 2d
#if deal_II_dimension == 2

#include <fe/fe_q.h>

// constraint matrices in 2d are now implemented by computing them on the fly
// for all polynomial degrees. the array is thus empty. unfortunately, some
// compilers dislike empty initializers for arrays of unknown size
// (particularly the hp compiler), so we simply initialize a single element
// with a null pointer
template <>
const double * const
FE_Q<2>::Matrices::constraint_matrices[] = { 0 };

template <>
const unsigned int
FE_Q<2>::Matrices::n_constraint_matrices = 0;

#else // #if deal_II_dimension
// On gcc2.95 on Alpha OSF1, the native assembler does not like empty
// files, so provide some dummy code
namespace { void dummy () {} }
#endif // #if deal_II_dimension == 2

Work around a trivial problem with the hp compiler.

git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@9540 0785d39b-7218-0410-832d-ea1e28bc413d