/**
 * @file lrsdp.cpp
 * @author Ryan Curtin
 *
 * An implementation of Monteiro and Burer's formulation of low-rank
 * semidefinite programs (LR-SDP).
 */
#include "lrsdp.hpp"

using namespace mlpack;
using namespace mlpack::optimization;
using namespace std;

LRSDP::LRSDP(const size_t numSparseConstraints,
             const size_t numDenseConstraints,
             const arma::mat& initialPoint) :
    function(numSparseConstraints, numDenseConstraints, initialPoint),
    augLag(function)
{ }

double LRSDP::Optimize(arma::mat& coordinates)
{
  augLag.Sigma() = 20;
  augLag.Optimize(coordinates, 1000);

  return augLag.Function().Evaluate(coordinates);
}

// Convert the object to a string.
std::string LRSDP::ToString() const
{
  std::ostringstream convert;
  convert << "LRSDP [" << this << "]" << std::endl;
  convert << "  Optimizer: " << util::Indent(augLag.ToString(), 1) << std::endl;
  return convert.str();
}

/**
 * @file lrsdp.cpp
 * @author Ryan Curtin
 *
 * An implementation of Monteiro and Burer's formulation of low-rank
 * semidefinite programs (LR-SDP).
 */
#include "lrsdp.hpp"

using namespace mlpack;
using namespace mlpack::optimization;
using namespace std;

LRSDP::LRSDP(const size_t numSparseConstraints,
             const size_t numDenseConstraints,
             const arma::mat& initialPoint) :
    function(numSparseConstraints, numDenseConstraints, initialPoint),
    augLag(function)
{ }

double LRSDP::Optimize(arma::mat& coordinates)
{
  augLag.Sigma() = 10;
  augLag.Optimize(coordinates, 1000);

  return augLag.Function().Evaluate(coordinates);
}

// Convert the object to a string.
std::string LRSDP::ToString() const
{
  std::ostringstream convert;
  convert << "LRSDP [" << this << "]" << std::endl;
  convert << "  Optimizer: " << util::Indent(augLag.ToString(), 1) << std::endl;
  return convert.str();
}

Set the default starting penalty to 10

Set the default starting penalty to 10


#include "Logging.h"

#include <SenseKit/sensekit_types.h>

INITIALIZE_LOGGING

namespace sensekit {

    void initialize_logging(const char* logFilePath)
    {
        const char TRUE_STRING[] = "true";

        el::Loggers::addFlag(el::LoggingFlag::CreateLoggerAutomatically);
        el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput);
        el::Loggers::addFlag(el::LoggingFlag::HierarchicalLogging);

        el::Configurations defaultConf;

        defaultConf.setToDefault();
        defaultConf.setGlobally(el::ConfigurationType::Enabled, TRUE_STRING);
        defaultConf.setGlobally(el::ConfigurationType::ToStandardOutput, TRUE_STRING);
        defaultConf.setGlobally(el::ConfigurationType::ToFile, TRUE_STRING);
        defaultConf.setGlobally(el::ConfigurationType::Filename, logFilePath);

        el::Loggers::setDefaultConfigurations(defaultConf, true);
        el::Loggers::setLoggingLevel(el::Level::Debug);

        defaultConf.clear();
    }
}

#include "Logging.h"

#include <SenseKit/sensekit_types.h>

INITIALIZE_LOGGING

namespace sensekit {

    void initialize_logging(const char* logFilePath)
    {
        const char TRUE_STRING[] = "true";

        el::Loggers::addFlag(el::LoggingFlag::CreateLoggerAutomatically);
        el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput);
        el::Loggers::addFlag(el::LoggingFlag::HierarchicalLogging);

        el::Configurations defaultConf;

        defaultConf.setToDefault();
        defaultConf.setGlobally(el::ConfigurationType::Enabled, TRUE_STRING);
        defaultConf.setGlobally(el::ConfigurationType::ToStandardOutput, TRUE_STRING);
        defaultConf.setGlobally(el::ConfigurationType::ToFile, TRUE_STRING);
        defaultConf.setGlobally(el::ConfigurationType::Filename, logFilePath);

        el::Loggers::setDefaultConfigurations(defaultConf, true);
        el::Loggers::setLoggingLevel(el::Level::Fatal);

        defaultConf.clear();
    }
}

Change default log level to >= FATAL

Change default log level to >= FATAL


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

#include "chrome/browser/idle_query_linux.h"

#include <X11/Xlib.h>
#include <X11/extensions/scrnsaver.h>

namespace browser {

class IdleData {
 public:
  IdleData() {
    int event_base;
    int error_base;
    display = XOpenDisplay(NULL);
    if (XScreenSaverQueryExtension(display, &event_base, &error_base)) {
      mit_info = XScreenSaverAllocInfo();
    } else {
      mit_info = NULL;
    }
  }

  ~IdleData() {
    if (display) {
      XCloseDisplay(display);
      display = NULL;
    }
    if (mit_info)
      XFree(mit_info);
  }

  XScreenSaverInfo *mit_info;
  Display *display;
};

IdleQueryLinux::IdleQueryLinux() : idle_data_(new IdleData()) {}

IdleQueryLinux::~IdleQueryLinux() {}

int IdleQueryLinux::IdleTime() {
  if (!idle_data_->mit_info || !idle_data_->display)
    return 0;

  if (XScreenSaverQueryInfo(idle_data_->display,
                            RootWindow(idle_data_->display, 0),
                            idle_data_->mit_info)) {
    return (idle_data_->mit_info->idle) / 1000;
  } else {
    return 0;
  }
}

}  // namespace browser

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

#include "chrome/browser/idle_query_linux.h"

#include <X11/extensions/scrnsaver.h>
#include "ui/base/x/x11_util.h"

namespace browser {

class IdleData {
 public:
  IdleData() {
    int event_base;
    int error_base;
    if (XScreenSaverQueryExtension(ui::GetXDisplay(), &event_base,
                                   &error_base)) {
      mit_info = XScreenSaverAllocInfo();
    } else {
      mit_info = NULL;
    }
  }

  ~IdleData() {
    if (mit_info)
      XFree(mit_info);
  }

  XScreenSaverInfo *mit_info;
};

IdleQueryLinux::IdleQueryLinux() : idle_data_(new IdleData()) {}

IdleQueryLinux::~IdleQueryLinux() {}

int IdleQueryLinux::IdleTime() {
  if (!idle_data_->mit_info)
    return 0;

  if (XScreenSaverQueryInfo(ui::GetXDisplay(),
                            RootWindow(ui::GetXDisplay(), 0),
                            idle_data_->mit_info)) {
    return (idle_data_->mit_info->idle) / 1000;
  } else {
    return 0;
  }
}

}  // namespace browser

Use GetXDisplay() instead of XOpenDisplay() in IdleQueryLinux.

We weren't checking that XOpenDisplay was actually succeeding before
attempting to use the display.

BUG=82308
TEST=none

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

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


#include <iostream>
#include <system_error>

#include "controllers/main/MainModule.hpp"
#include "network/bsdsocket/Manager.hpp"

int main()
{
    tin::controllers::main::ControllerQueue ctrlQueue;
    tin::network::bsdsocket::ManagerQueue netManagerQueue;

    tin::controllers::main::MainModule mainCtrl(ctrlQueue, netManagerQueue);
    tin::network::bsdsocket::Manager networkManager(netManagerQueue, ctrlQueue, 3333);

    std::cout << "Hello agent!\n";

    auto mainCtrlThread = mainCtrl.createThread();
    auto netManager = networkManager.createThread();

    try
    {
        mainCtrlThread.join();
        netManager.join();
    }
    catch (std::system_error& e)
    {
        // Could not join one of the threads
    }

    return 0;
}

#include <iostream>
#include <system_error>

#include "controllers/main/MainModule.hpp"
#include "network/bsdsocket/Manager.hpp"
#include "network/sniffer/SnifferManager.hpp"

int main()
{
    tin::controllers::main::ControllerQueue ctrlQueue;
    tin::network::bsdsocket::ManagerQueue netManagerQueue;

    tin::controllers::main::MainModule mainCtrl(ctrlQueue, netManagerQueue);
    tin::network::bsdsocket::Manager networkManager(netManagerQueue, ctrlQueue, 3333);
    tin::network::sniffer::SnifferManager sniffManager(ctrlQueue, "lo", "src 127.0.0.1");

    std::cout << "Hello agent!\n";

    auto mainCtrlThread = mainCtrl.createThread();
    auto netManager = networkManager.createThread();

    try
    {
        mainCtrlThread.join();
        netManager.join();
    }
    catch (std::system_error& e)
    {
        // Could not join one of the threads
    }

    return 0;
}

Create a simple example of sniffing

Create a simple example of sniffing


// RUN: %clangxx_asan -std=c++11 %s -o %t && %run %t 2>&1
// Regression test for the versioned pthread_create interceptor on linux/i386.
// pthread_attr_init is not intercepted and binds to the new abi
// pthread_create is intercepted; dlsym always returns the oldest version.
// This results in a crash inside pthread_create in libc.

#include <pthread.h>
#include <stdlib.h>

void *ThreadFunc(void *) { return nullptr; }

int main() {
  pthread_t t;
  const size_t sz = 1024 * 1024;
  void *p = malloc(sz);
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setstack(&attr, p, sz);
  pthread_create(&t, &attr, ThreadFunc, nullptr);
  pthread_join(t, nullptr);
  free(p);
  return 0;
}

// RUN: %clangxx_asan -std=c++11 -pthread %s -o %t && %run %t 2>&1
// Regression test for the versioned pthread_create interceptor on linux/i386.
// pthread_attr_init is not intercepted and binds to the new abi
// pthread_create is intercepted; dlsym always returns the oldest version.
// This results in a crash inside pthread_create in libc.

#include <pthread.h>
#include <stdlib.h>

void *ThreadFunc(void *) { return nullptr; }

int main() {
  pthread_t t;
  const size_t sz = 1024 * 1024;
  void *p = malloc(sz);
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setstack(&attr, p, sz);
  pthread_create(&t, &attr, ThreadFunc, nullptr);
  pthread_join(t, nullptr);
  free(p);
  return 0;
}

Add missing -pthread in tests.

[asan] Add missing -pthread in tests.

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


// RUN: rm -rf %t
// RUN: %clang_cc1 -fsyntax-only -verify %s -fmodules -fmodules-cache-path=%t -I%S/Inputs/PR28438 -fimplicit-module-maps

#include "a.h"
#include "b2.h"

#pragma clang __debug macro FOO

FOO // xpected-no-diagnostics

// RUN: rm -rf %t
// RUN: %clang_cc1 -fsyntax-only -verify %s -fmodules -fmodules-cache-path=%t -I%S/Inputs/PR28438 -fimplicit-module-maps

#include "a.h"
#include "b2.h"

FOO // expected-no-diagnostics

Remove debugging aids from this test and fix its expectations.

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


#include "game_state.hpp"
#include "start_game_state.hpp"

namespace Quoridor {

GameState::GameState()
{
}

GameState::~GameState()
{
}

void GameState::handle_events(StateManager *stm, std::shared_ptr<UI::UIImpl> ui)
{
    UI::Event ev;
    if (ui->poll_event(&ev)) {
        switch (ev) {
        case UI::kEnter:
            break;
        case UI::kEsc: {
            std::shared_ptr<Quoridor::IState> menu_state(new StartGameState());
            stm->change_state(std::shared_ptr<IState>(menu_state));
            }
            break;
        default:
            break;
        }
    }
}

void GameState::update()
{
}

void GameState::draw(std::shared_ptr<UI::UIImpl> ui)
{
    ui->update(repr_);
}

void GameState::change_state()
{
}

void GameState::init_board_repr() const
{
}

}  /* namespace Quoridor */

#include "game_state.hpp"
#include "start_game_state.hpp"

namespace Quoridor {

GameState::GameState()
{
}

GameState::~GameState()
{
}

void GameState::handle_events(StateManager *stm, std::shared_ptr<UI::UIImpl> ui)
{
    UI::Event ev;
    if (ui->poll_event(&ev)) {
        switch (ev) {
        case UI::kEnter:
            break;
        case UI::kEsc: {
            std::shared_ptr<IState> start_game_state(new StartGameState(ui));
            stm->change_state(std::shared_ptr<IState>(start_game_state));
            }
            break;
        default:
            break;
        }
    }
}

void GameState::update()
{
}

void GameState::draw(std::shared_ptr<UI::UIImpl> ui)
{
    ui->update(repr_);
}

void GameState::change_state()
{
}

void GameState::init_board_repr() const
{
}

}  /* namespace Quoridor */

Fix var name in GameState::handle_events.


#include <omp.h>

#include "proctor/detector.h"
#include "proctor/proctor.h"
#include "proctor/scanning_model_source.h"
#include "proctor/basic_proposer.h"

using pcl::proctor::Detector;
//using pcl::proctor::ProctorMPI;
using pcl::proctor::Proctor;
using pcl::proctor::ScanningModelSource;
using pcl::proctor::BasicProposer;

int main(int argc, char **argv) {
  unsigned int model_seed = 2;
  unsigned int test_seed = 0; //time(NULL);

  if (argc >= 2)
  {
    model_seed = atoi(argv[1]);
  }

  if (argc >= 3)
  {
    test_seed = atoi(argv[2]);
  }

  Detector detector;
  Proctor proctor;

  BasicProposer::Ptr proposer(new BasicProposer);
  detector.setProposer(proposer);

  ScanningModelSource model_source("Princeton", "/home/justin/Documents/benchmark/db");
  model_source.loadModels();

  //detector.enableVisualization();
  proctor.setModelSource(&model_source);
  proctor.train(detector);
  proctor.test(detector, test_seed);
  proctor.printResults(detector);

  sleep(100000);

  return 0;
}

Remove unneeded OpenMP header import.

Remove unneeded OpenMP header import.

git-svn-id: e7ea667a1d39a4453c4efcc4ba7bca3d620c3f19@3877 a9d63959-f2ad-4865-b262-bf0e56cfafb6


#include "runtime/helpers/spy_reader.h"
#include <algorithm>

using std::string;

static const char * spy_read(void *data, size_t *bytes_read) {
  SpyReader *reader = static_cast<SpyReader *>(data);
  string result = reader->content.substr(reader->position, reader->chunk_size);
  reader->position += result.size();
  reader->strings_read.back() += result;
  *bytes_read = result.size();
  memcpy(reader->buffer, result.data(), result.size());
  return reader->buffer;
}

static int spy_seek(void *data, TSLength position) {
  SpyReader *reader = static_cast<SpyReader *>(data);
  reader->strings_read.push_back("");
  reader->position = position.bytes;
  return 0;
}

SpyReader::SpyReader(string content, size_t chunk_size) :
    buffer(new char[chunk_size]),
    content(content),
    position(0),
    chunk_size(chunk_size),
    input({
        this,
        spy_read,
        spy_seek,
        nullptr,
    }) {}

void SpyReader::clear() {
  strings_read.clear();
}

SpyReader::~SpyReader() {
  delete buffer;
}

#include "runtime/helpers/spy_reader.h"
#include <string.h>
#include <algorithm>

using std::string;

static const char * spy_read(void *data, size_t *bytes_read) {
  SpyReader *reader = static_cast<SpyReader *>(data);
  string result = reader->content.substr(reader->position, reader->chunk_size);
  reader->position += result.size();
  reader->strings_read.back() += result;
  *bytes_read = result.size();
  memcpy(reader->buffer, result.data(), result.size());
  return reader->buffer;
}

static int spy_seek(void *data, TSLength position) {
  SpyReader *reader = static_cast<SpyReader *>(data);
  reader->strings_read.push_back("");
  reader->position = position.bytes;
  return 0;
}

SpyReader::SpyReader(string content, size_t chunk_size) :
    buffer(new char[chunk_size]),
    content(content),
    position(0),
    chunk_size(chunk_size),
    input({
        this,
        spy_read,
        spy_seek,
        nullptr,
    }) {}

void SpyReader::clear() {
  strings_read.clear();
}

SpyReader::~SpyReader() {
  delete buffer;
}

Add missing import for string.h

Add missing import for string.h


#include "game.hpp"
#include "exception.hpp"
#include "walk_move.hpp"
#include "wall_move.hpp"

namespace Quoridor {

Game::Game() : board_(new Board(9, 9)), pawn_list_()
{
}

Game::~Game()
{
}

void Game::add_pawn(std::shared_ptr<Pawn> pawn)
{
    board_->add_pawn(pawn);
    pawn_list_.push_back(pawn);
}

pos_t Game::pawn_pos(std::shared_ptr<Pawn> pawn) const
{
    return board_->pawn_pos(pawn);
}

int Game::make_move(IMove *move, std::shared_ptr<Pawn> pawn)
{
    if (WalkMove *walk_move = dynamic_cast<WalkMove *>(move)) {
        return board_->make_walking_move(walk_move->dir(), pawn);
    }
    else if (WallMove *wall_move = dynamic_cast<WallMove *>(move)) {
        return board_->add_wall(wall_move->wall());
    }
    else {
        return -1;
    }
}

bool Game::is_win(std::shared_ptr<Pawn> pawn) const
{
    return board_->is_at_opposite_side(pawn);
}

}  /* namespace Quoridor */

#include "game.hpp"
#include "exception.hpp"
#include "walk_move.hpp"
#include "wall_move.hpp"

namespace Quoridor {

Game::Game() : board_(new Board(9, 9)), pawn_list_()
{
}

Game::~Game()
{
}

void Game::add_pawn(std::shared_ptr<Pawn> pawn)
{
    board_->add_pawn(pawn);
    pawn_list_.push_back(pawn);
}

pos_t Game::pawn_pos(std::shared_ptr<Pawn> pawn) const
{
    return board_->pawn_pos(pawn);
}

int Game::make_move(IMove *move, std::shared_ptr<Pawn> pawn)
{
    if (WalkMove *walk_move = dynamic_cast<WalkMove *>(move)) {
        return board_->make_walking_move(pawn, walk_move->node());
    }
    else if (WallMove *wall_move = dynamic_cast<WallMove *>(move)) {
        return board_->add_wall(wall_move->wall());
    }
    else {
        return -1;
    }
}

bool Game::is_win(std::shared_ptr<Pawn> pawn) const
{
    return board_->is_at_opposite_side(pawn);
}

}  /* namespace Quoridor */

Fix walking move in Game.

Fix walking move in Game.


#include "tile.hpp"
#include "vector_tile.pb.h"

#include <google/protobuf/io/zero_copy_stream_impl.h>

namespace avecado {

tile::tile(unsigned int z_, unsigned int x_, unsigned int y_)
  : z(z_), x(x_), y(y_), m_mapnik_tile(new mapnik::vector::tile) {
}

tile::~tile() {
}

std::string tile::get_data() const {
  std::string buffer;

  if (m_mapnik_tile->SerializeToString(&buffer)) {
    return buffer;

  } else {
    throw std::runtime_error("Error while serializing protocol buffer tile.");
  }
}

mapnik::vector::tile const &tile::mapnik_tile() const {
  return *m_mapnik_tile;
}

mapnik::vector::tile &tile::mapnik_tile() {
  return *m_mapnik_tile;
}

std::ostream &operator<<(std::ostream &out, const tile &t) {
  google::protobuf::io::OstreamOutputStream stream(&out);
  bool write_ok = t.mapnik_tile().SerializeToZeroCopyStream(&stream);

  if (!write_ok) {
    throw std::runtime_error("Unable to write tile to output stream.");
  }

  return out;
}

} // namespace avecado

#include "tile.hpp"
#include "vector_tile.pb.h"

#include <google/protobuf/io/zero_copy_stream_impl.h>

namespace avecado {

tile::tile(unsigned int z_, unsigned int x_, unsigned int y_)
  : z(z_), x(x_), y(y_), m_mapnik_tile(new mapnik::vector::tile) {
}

tile::~tile() {
}

std::string tile::get_data() const {
  std::ostringstream buffer;
  buffer << *this;
  return buffer.str();
}

mapnik::vector::tile const &tile::mapnik_tile() const {
  return *m_mapnik_tile;
}

mapnik::vector::tile &tile::mapnik_tile() {
  return *m_mapnik_tile;
}

std::ostream &operator<<(std::ostream &out, const tile &t) {
  google::protobuf::io::OstreamOutputStream stream(&out);
  bool write_ok = t.mapnik_tile().SerializeToZeroCopyStream(&stream);

  if (!write_ok) {
    throw std::runtime_error("Unable to write tile to output stream.");
  }

  return out;
}

} // namespace avecado

Make it so that serialisation to PBF happens in only one place.


#pragma once

#include "TerraceWrapperCodec.h"

namespace spotify
{
namespace json
{

using TerraceWrapper = noise::module::Wrapper<noise::module::Terrace>;

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

}
}

#pragma once

#include "TerraceWrapperCodec.h"

namespace spotify
{
namespace json
{

using TerraceWrapper = noise::module::Wrapper<noise::module::Terrace>;

codec::object_t<TerraceWrapper> default_codec_t<TerraceWrapper>::codec()
    {
        auto codec = codec::object<TerraceWrapper>();
        codec.required("type", codec::eq<std::string>("Terrace"));
        codec.required("SourceModule", codec::ignore_t<int>());
        codec.optional("InvertTerraces",
                       [](const TerraceWrapper& mw)
        {
            return mw.module->IsTerracesInverted();
        },
                       [](const TerraceWrapper& mw, bool invert_terraces)
        {
            mw.module->InvertTerraces(true);
        });
        codec.optional("ControlPoints",
                       [](const TerraceWrapper& mw)
                       {
                           std::vector<double> control_points;
                           const double* raw_control_points = mw.module->GetControlPointArray();
                           const int control_point_count = mw.module->GetControlPointCount();
                           for (int i = 0; i < control_point_count; i++)
                           {
                               control_points.push_back(raw_control_points[i]);
                           }
                           return control_points;
                       },
                       [](TerraceWrapper& mw, std::vector<double> all_control_points)
                       {
                           for (double control_point : all_control_points)
                           {
                               mw.module->AddControlPoint(control_point);
                           }
                       },
                       default_codec<std::vector<double>>());
        return codec;
    }

}
}

Add missing attribute to Terrace codec

Add missing attribute to Terrace codec


#include "EntityEditor.hpp"

#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <Engine/Geometry/Rectangle.hpp>
#include "TransformEditor.hpp"

using namespace GUI;

EntityEditor::EntityEditor(Widget* parent) : Widget(parent) {
    rectangle = Managers().resourceManager->CreateRectangle();
    entity = nullptr;
    transformEditor = new TransformEditor(this);
}

EntityEditor::~EntityEditor() {
    Managers().resourceManager->FreeRectangle();
    delete transformEditor;
}

void EntityEditor::Update() {
    transformEditor->Update();
}

void EntityEditor::Render(const glm::vec2& screenSize) {
    glm::vec3 color(0.06666666666f, 0.06274509803f, 0.08235294117f);
    rectangle->Render(GetPosition(), size, color, screenSize);

    transformEditor->Render(screenSize);
}

void EntityEditor::SetPosition(const glm::vec2& position) {
    Widget::SetPosition(position);

    transformEditor->SetPosition(position);
}

glm::vec2 EntityEditor::GetSize() const {
    return size;
}

void EntityEditor::SetSize(const glm::vec2& size) {
    this->size = size;
}

void EntityEditor::SetEntity(Entity* entity) {
    this->entity = entity;

    transformEditor->SetEntity(entity);
}

#include "EntityEditor.hpp"

#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <Engine/Geometry/Rectangle.hpp>
#include "TransformEditor.hpp"

using namespace GUI;

EntityEditor::EntityEditor(Widget* parent) : Widget(parent) {
    rectangle = Managers().resourceManager->CreateRectangle();
    entity = nullptr;
    transformEditor = new TransformEditor(this);
}

EntityEditor::~EntityEditor() {
    Managers().resourceManager->FreeRectangle();
    delete transformEditor;
}

void EntityEditor::Update() {
    transformEditor->Update();
}

void EntityEditor::Render(const glm::vec2& screenSize) {
    glm::vec3 color(0.06666666666f, 0.06274509803f, 0.08235294117f);
    rectangle->Render(GetPosition(), size, color, screenSize);

    transformEditor->Render(screenSize);
}

void EntityEditor::SetPosition(const glm::vec2& position) {
    Widget::SetPosition(position);

    transformEditor->SetPosition(position);
}

glm::vec2 EntityEditor::GetSize() const {
    return size;
}

void EntityEditor::SetSize(const glm::vec2& size) {
    this->size = size;

    transformEditor->SetSize(size);
}

void EntityEditor::SetEntity(Entity* entity) {
    this->entity = entity;

    transformEditor->SetEntity(entity);
}

Set the transform editor's size.

Set the transform editor's size.


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

#include "base/cancellation_flag.h"

#include "base/logging.h"

namespace base {

void CancellationFlag::Set() {
#if !defined(NDEBUG)
  DCHECK(set_on_ == PlatformThread::CurrentId());
#endif
  base::subtle::Release_Store(&flag_, 1);
}

bool CancellationFlag::IsSet() const {
  return base::subtle::Acquire_Load(&flag_) != 0;
}

}  // namespace base

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

#include "base/cancellation_flag.h"

#include "base/logging.h"

namespace base {

void CancellationFlag::Set() {
#if !defined(NDEBUG)
  DCHECK_EQ(set_on_, PlatformThread::CurrentId());
#endif
  base::subtle::Release_Store(&flag_, 1);
}

bool CancellationFlag::IsSet() const {
  return base::subtle::Acquire_Load(&flag_) != 0;
}

}  // namespace base

Replace a DCHECK with DCHECK_EQ.

Replace a DCHECK with DCHECK_EQ.

BUG=none
TEST=none
Review URL: http://codereview.chromium.org/2919013

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


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

struct X {
  template<typename T> T& f0(T);

  void g0(int i, double d) {
    int &ir = f0(i);
    double &dr = f0(d);
  }

  template<typename T> T& f1(T);
  template<typename T, typename U> U& f1(T, U);

  void g1(int i, double d) {
    int &ir1 = f1(i);
    int &ir2 = f1(d, i);
    int &ir3 = f1(i, i);
  }
};

void test_X_f0(X x, int i, float f) {
  int &ir = x.f0(i);
  float &fr = x.f0(f);
}

void test_X_f1(X x, int i, float f) {
  int &ir1 = x.f1(i);
  int &ir2 = x.f1(f, i);
  int &ir3 = x.f1(i, i);
}

void test_X_f0_address() {
  int& (X::*pm1)(int) = &X::f0;
  float& (X::*pm2)(float) = &X::f0;
}

void test_X_f1_address() {
  int& (X::*pm1)(int) = &X::f1;
  float& (X::*pm2)(float) = &X::f1;
  int& (X::*pm3)(float, int) = &X::f1;
}

Add test taking the address of a member function template and converting it to a member pointer.

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


#include "Timer.h"

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

#include <string>
#include <iostream>

BOOST_AUTO_TEST_CASE(timer_basic_test) {
  Timer timer;
  timer.start();
  BOOST_REQUIRE(timer.is_running());
  BOOST_REQUIRE(timer.get_elapsed_cpu_time() > 0.0);
  BOOST_REQUIRE(timer.get_elapsed_cpu_time_microseconds() > 0);
  BOOST_REQUIRE(timer.get_elapsed_wall_time() > 0.0);
  BOOST_REQUIRE(timer.get_elapsed_wall_time_microseconds() > 0);

  timer.restart();
  BOOST_REQUIRE(timer.is_running());
  BOOST_REQUIRE(timer.get_elapsed_cpu_time() > 0.0);
  BOOST_REQUIRE(timer.get_elapsed_cpu_time_microseconds() > 0);
  BOOST_REQUIRE(timer.get_elapsed_wall_time() > 0.0);
  BOOST_REQUIRE(timer.get_elapsed_wall_time_microseconds() > 0);

  const std::string s = timer.ToString();
  BOOST_REQUIRE(!s.empty());
}

#include "Timer.h"

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

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

BOOST_AUTO_TEST_CASE(timer_basic_test) {
  Timer timer;
  const int sleep_time_microsec = 40; // ad-hoc microseconds to pass unit tests.

  timer.start();
  BOOST_REQUIRE(timer.is_running());
  BOOST_REQUIRE(usleep(sleep_time_microsec) == 0);
  BOOST_CHECK(timer.get_elapsed_cpu_time() > 0.0);
  BOOST_CHECK(timer.get_elapsed_cpu_time_microseconds() > 0);
  BOOST_CHECK(timer.get_elapsed_wall_time() > 0.0);
  BOOST_CHECK(timer.get_elapsed_wall_time_microseconds() > 0);

  timer.restart();
  BOOST_REQUIRE(timer.is_running());
  BOOST_REQUIRE(usleep(sleep_time_microsec) == 0);
  BOOST_CHECK(timer.get_elapsed_cpu_time() > 0.0);
  BOOST_CHECK(timer.get_elapsed_cpu_time_microseconds() > 0);
  BOOST_CHECK(timer.get_elapsed_wall_time() > 0.0);
  BOOST_CHECK(timer.get_elapsed_wall_time_microseconds() > 0);

  const std::string s = timer.ToString();
  BOOST_CHECK(!s.empty());
}

Fix failure of the Timer unit test.

Fix failure of the Timer unit test.


 // //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <cassert>
#include <sstream>
// TravelCCM Basic
#include <travelccm/service/TRAVELCCM_ServiceContext.hpp>

namespace TRAVELCCM {

  // //////////////////////////////////////////////////////////////////////
  TRAVELCCM_ServiceContext::TRAVELCCM_ServiceContext()
    : _ownStdairService (false) {
  }

  // //////////////////////////////////////////////////////////////////////
  TRAVELCCM_ServiceContext::
  TRAVELCCM_ServiceContext (const TRAVELCCM_ServiceContext&) {
    assert (false);
  }

  // //////////////////////////////////////////////////////////////////////
  TRAVELCCM_ServiceContext::~TRAVELCCM_ServiceContext() {
  }

  // //////////////////////////////////////////////////////////////////////
  const std::string TRAVELCCM_ServiceContext::shortDisplay() const {
    std::ostringstream oStr;
    oStr << "TRAVELCCM_ServiceContext -- Owns StdAir service: "
         << _ownStdairService;
    return oStr.str();
  }

  // //////////////////////////////////////////////////////////////////////
  const std::string TRAVELCCM_ServiceContext::display() const {
    std::ostringstream oStr;
    oStr << shortDisplay();
    return oStr.str();
  }

  // //////////////////////////////////////////////////////////////////////
  const std::string TRAVELCCM_ServiceContext::describe() const {
    return shortDisplay();
  }

  // //////////////////////////////////////////////////////////////////////
  void TRAVELCCM_ServiceContext::reset() {

    // The shared_ptr<>::reset() method drops the refcount by one.
    // If the count result is dropping to zero, the resource pointed to
    // by the shared_ptr<> will be freed.

    // Reset the stdair shared pointer
    _stdairService.reset();
  }

}

[Dev] Reset the stdair service shared pointer in order to decrease the count by one every time (and not only when owning the stdair service).


#include "audio_mixer.hpp"
#include "timer.hpp"
#include "vorbis_stream.hpp"
#include <chrono>
#include <thread>
#include <cmath>

using namespace Granite::Audio;
using namespace std;

struct SineAudio : BackendCallback
{
	void mix_samples(float * const *channels, size_t num_frames) noexcept override
	{
		float *left = channels[0];
		float *right = channels[1];

		for (size_t i = 0; i < num_frames; i++)
		{
			double v = 0.15 * sin(phase);
			*left++ = float(v);
			*right++ = float(v);
			phase += 0.015;
		}
	}

	double phase = 0.0;
};

int main()
{
	Mixer mixer;
	auto *stream = create_vorbis_stream("/tmp/test.ogg");
	mixer.add_mixer_stream(stream);

	auto backend = create_default_audio_backend(44100.0f, 2);
	backend->start(&mixer);
	std::this_thread::sleep_for(std::chrono::seconds(100));
	backend->stop();
	std::this_thread::sleep_for(std::chrono::seconds(3));
	backend->start(&mixer);
	std::this_thread::sleep_for(std::chrono::seconds(100));
}

#include "audio_mixer.hpp"
#include "timer.hpp"
#include "vorbis_stream.hpp"
#include <chrono>
#include <thread>
#include <cmath>

using namespace Granite::Audio;
using namespace std;

struct SineAudio : BackendCallback
{
	void mix_samples(float * const *channels, size_t num_frames) noexcept override
	{
		float *left = channels[0];
		float *right = channels[1];

		for (size_t i = 0; i < num_frames; i++)
		{
			double v = 0.15 * sin(phase);
			*left++ = float(v);
			*right++ = float(v);
			phase += 0.015;
		}
	}

	double phase = 0.0;
};

int main()
{
	Mixer mixer;
	auto *stream = create_vorbis_stream("/tmp/test.ogg");
	if (stream)
		mixer.add_mixer_stream(stream);

	auto backend = create_default_audio_backend(32000.0f, 2);
	backend->start(&mixer);
	std::this_thread::sleep_for(std::chrono::seconds(100));
	backend->stop();
	std::this_thread::sleep_for(std::chrono::seconds(3));
	backend->start(&mixer);
	std::this_thread::sleep_for(std::chrono::seconds(100));
}

Test other sampling rates for good measure.


/*
    behaviourconfig_events.cpp

    Copyright (c) 2006       by Thorben Kröger         <thorbenk@gmx.net>

    Kopete    (c) 2002-2007  by the Kopete developers  <kopete-devel@kde.org>

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

#include "behaviorconfig_events.h"

BehaviorConfig_Events::BehaviorConfig_Events(QWidget *parent)
	: QWidget(parent)
{
	setupUi(this);
}

#include "behaviorconfig_events.moc"

/*
    behaviourconfig_events.cpp

    Copyright (c) 2006       by Thorben Kröger         <thorbenk@gmx.net>

    Kopete    (c) 2002-2007  by the Kopete developers  <kopete-devel@kde.org>

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

#include "behaviorconfig_events.h"

#include <QMovie>

BehaviorConfig_Events::BehaviorConfig_Events(QWidget *parent)
	: QWidget(parent)
{
	setupUi(this);

	bool supportsMng(false);
	QList<QByteArray> supportedFormats = QMovie::supportedFormats();
	foreach ( QByteArray format, supportedFormats )
	{
		supportsMng = supportsMng || format.toLower() == QByteArray("mng");
	}

	if ( !supportsMng )
	{
		kcfg_trayflashNotify->setEnabled(false);
		kcfg_trayflashNotify->setToolTip(i18n("Animation is not possible as your Qt version does not support the mng video format."));
	}
}

#include "behaviorconfig_events.moc"

Disable the systray animation setting if Qt lacks mng support and tell the user about it in the tooltip
BUG: 161800

svn path=/trunk/KDE/kdenetwork/kopete/; revision=808033


#include "Bmp180.h"

namespace rcr {
namespace level1payload {

Bmp180::Bmp180(void) {
  // Start the BMP-180. Trap the thread if no sensor is found.
  if (!bmp_.begin()) {
    Serial.println("No BMP sensor found. Program will not proceed.");
    while (1) { /* Trap the thread. */ }
  }
}

float Bmp180::temperature(void) {
  return bmp_.readTemperature();
}

int32_t Bmp180::ambient_pressure(void) {
  return bmp_.readPressure();
}

float Bmp180::pressure_altitude(void) {
  // Use default altimeter setting,
  // sealevelPressure = 101325 Pascals (std. atmosphere)
  return bmp_.readAltitude();
}

} // namespace level1_payload
} // namespace rcr

Implement the BMP180 container class

Implement the BMP180 container class


// 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 "../../fpdfsdk/include/fpdfview.h"
#include "../../fpdfsdk/include/fpdfdoc.h"
#include "testing/gtest/include/gtest/gtest.h"

class FPDFDataAvailEmbeddertest : public EmbedderTest {
};

TEST_F(FPDFDataAvailEmbeddertest, TrailerUnterminated) {
  // Document must open without crashing but is too malformed to be available.
  EXPECT_TRUE(OpenDocument("testing/resources/trailer_unterminated.pdf"));
  EXPECT_FALSE(FPDFAvail_IsDocAvail(avail_, &hints_));
}

TEST_F(FPDFDataAvailEmbeddertest, TrailerAsHexstring) {
  // Document must open without crashing but is too malformed to be available.
  EXPECT_TRUE(OpenDocument("testing/resources/trailer_as_hexstring.pdf"));
  EXPECT_FALSE(FPDFAvail_IsDocAvail(avail_, &hints_));
}

// 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 "../../fpdfsdk/include/fpdfview.h"
#include "../../fpdfsdk/include/fpdfdoc.h"
#include "testing/gtest/include/gtest/gtest.h"

class FPDFDataAvailEmbeddertest : public EmbedderTest {
};

TEST_F(FPDFDataAvailEmbeddertest, TrailerUnterminated) {
  // Document doesn't even open under XFA but must not crash.
  EXPECT_FALSE(OpenDocument("testing/resources/trailer_unterminated.pdf"));
}

TEST_F(FPDFDataAvailEmbeddertest, TrailerAsHexstring) {
  // Document doesn't even open under XFA but must not crash.
  EXPECT_FALSE(OpenDocument("testing/resources/trailer_as_hexstring.pdf"));
}

Fix test result under XFA.  This gives an error at an earlier
stage, but is fine so long as the crashes don't happen.

TBR=bo_xu@foxitsoftware.com

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


#include <aerial_autonomy/common/async_timer.h>

#include <iostream>
#include <stdexcept>

AsyncTimer::AsyncTimer(std::function<void()> function,
                       std::chrono::duration<double> timer_duration)
    : function_(function), timer_duration_(timer_duration), running_(false) {}

AsyncTimer::~AsyncTimer() {
  running_ = false;
  if (timer_thread_.joinable()) {
    timer_thread_.join();
  }
}

void AsyncTimer::start() {
  if (!running_) {
    running_ = true;
    timer_thread_ = std::thread(std::bind(&AsyncTimer::functionTimer, this));
  } else {
    throw std::logic_error("Cannot start AsyncTimer twice!");
  }
}

void AsyncTimer::functionTimer() {
  while (running_) {
    auto start = std::chrono::high_resolution_clock::now();
    function_();
    std::this_thread::sleep_until(start + timer_duration_);
  }
}

#include <aerial_autonomy/common/async_timer.h>

#include <stdexcept>

AsyncTimer::AsyncTimer(std::function<void()> function,
                       std::chrono::duration<double> timer_duration)
    : function_(function), timer_duration_(timer_duration), running_(false) {}

AsyncTimer::~AsyncTimer() {
  running_ = false;
  if (timer_thread_.joinable()) {
    timer_thread_.join();
  }
}

void AsyncTimer::start() {
  if (!running_) {
    running_ = true;
    timer_thread_ = std::thread(std::bind(&AsyncTimer::functionTimer, this));
  } else {
    throw std::logic_error("Cannot start AsyncTimer twice!");
  }
}

void AsyncTimer::functionTimer() {
  while (running_) {
    auto start = std::chrono::high_resolution_clock::now();
    function_();
    std::this_thread::sleep_until(start + timer_duration_);
  }
}

Remove unnecessary header from AsyncTimer


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

#include "default_benchmarks.h"

std::vector<std::string> DefaultBenchmarks::get()
{
    return std::vector<std::string>{
        "vertex:device-local=true",
        "vertex:device-local=false",
        "texture:anisotropy=0",
        "texture:anisotropy=16",
        "shading:shading=gouraud",
        "shading:shading=blinn-phong-inf",
        "shading:shading=phong",
        "shading:shading=cel",
        "desktop",
        "cube",
        "clear"
    };
}

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

#include "default_benchmarks.h"

std::vector<std::string> DefaultBenchmarks::get()
{
    return std::vector<std::string>{
        "vertex:device-local=true",
        "vertex:device-local=false",
        "texture:anisotropy=0",
        "texture:anisotropy=16",
        "shading:shading=gouraud",
        "shading:shading=blinn-phong-inf",
        "shading:shading=phong",
        "shading:shading=cel",
        "effect2d:kernel=edge",
        "effect2d:kernel=blur",
        "desktop",
        "cube",
        "clear"
    };
}

main: Add effect2d scene variants to default benchmarks


#include "Target.h"

#include <cassert>
#include <memory>

#include "MCTargetDesc/X86MCTargetDesc.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"

namespace exegesis {

void InitializeX86ExegesisTarget();

namespace {

using testing::Gt;
using testing::NotNull;
using testing::SizeIs;

class X86TargetTest : public ::testing::Test {
protected:
  X86TargetTest()
      : Target_(ExegesisTarget::lookup(llvm::Triple("x86_64-unknown-linux"))) {
    EXPECT_THAT(Target_, NotNull());
  }
  static void SetUpTestCase() { InitializeX86ExegesisTarget(); }

  const ExegesisTarget *const Target_;
};

TEST_F(X86TargetTest, SetRegToConstantGPR) {
  const auto Insts = Target_->setRegToConstant(llvm::X86::EAX);
  EXPECT_THAT(Insts, SizeIs(1));
  EXPECT_EQ(Insts[0].getOpcode(), llvm::X86::MOV32ri);
  EXPECT_EQ(Insts[0].getOperand(0).getReg(), llvm::X86::EAX);
}

TEST_F(X86TargetTest, SetRegToConstantXMM) {
  const auto Insts = Target_->setRegToConstant(llvm::X86::XMM1);
  EXPECT_THAT(Insts, SizeIs(Gt(0)));
}

} // namespace
} // namespace exegesis

#include "Target.h"

#include <cassert>
#include <memory>

#include "MCTargetDesc/X86MCTargetDesc.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"

namespace exegesis {

void InitializeX86ExegesisTarget();

namespace {

using testing::Gt;
using testing::NotNull;
using testing::SizeIs;

class X86TargetTest : public ::testing::Test {
protected:
  X86TargetTest()
      : Target_(ExegesisTarget::lookup(llvm::Triple("x86_64-unknown-linux"))) {
    EXPECT_THAT(Target_, NotNull());
  }
  static void SetUpTestCase() { InitializeX86ExegesisTarget(); }

  const ExegesisTarget *const Target_;
};

TEST_F(X86TargetTest, SetRegToConstantGPR) {
  const auto Insts = Target_->setRegToConstant(llvm::X86::EAX);
  EXPECT_THAT(Insts, SizeIs(1));
  EXPECT_EQ(Insts[0].getOpcode(), llvm::X86::MOV32ri);
  EXPECT_EQ(Insts[0].getOperand(0).getReg(), llvm::X86::EAX);
}

TEST_F(X86TargetTest, SetRegToConstantXMM) {
  const auto Insts = Target_->setRegToConstant(llvm::X86::XMM1);
  EXPECT_THAT(Insts, SizeIs(Gt(0U)));
}

} // namespace
} // namespace exegesis

Fix unsigned/signed comparison failure in unittest.

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


#include "runtime_internal.h"

#define INLINE inline __attribute__((weak)) __attribute__((used)) __attribute__((always_inline)) __attribute__((nothrow)) __attribute__((pure))

extern "C" {

INLINE float float_from_bits(uint32_t bits) {
    union {
        uint32_t as_uint;
        float as_float;
    } u;
    u.as_uint = bits;
    return u.as_float;
}

INLINE float nan_f32() {
    return float_from_bits(0x7fc00000);
}

INLINE float neg_inf_f32() {
    return float_from_bits(0xff800000);
}

INLINE float inf_f32() {
    return float_from_bits(0x7f800000);
}

INLINE float maxval_f32() {
    return float_from_bits(0x7f7fffff);
}

INLINE float minval_f32() {
    return float_from_bits(0xff7fffff);
}

}

#include "runtime_internal.h"

#define INLINE inline __attribute__((weak)) __attribute__((used)) __attribute__((always_inline)) __attribute__((nothrow)) __attribute__((pure))

extern "C" {

INLINE float float_from_bits(uint32_t bits) {
    union {
        uint32_t as_uint;
        float as_float;
    } u;
    u.as_uint = bits;
    return u.as_float;
}

INLINE float nan_f32() {
    return float_from_bits(0x7fc00000);
}

INLINE float neg_inf_f32() {
    return float_from_bits(0xff800000);
}

INLINE float inf_f32() {
    return float_from_bits(0x7f800000);
}

}

Remove some dead math intrinsics

Remove some dead math intrinsics


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

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

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

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

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

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

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

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

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

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

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

Former-commit-id: 58d33dfa0e2313d8b5966d2926bc54370c5bf399


#include <ast/function-var.hh>
#include <ast/any-list.hh>

namespace ast
{
    FunctionVar::FunctionVar(const yy::location& location,
                             Var* var,
                             ExprList* params)
        : Var(location)
        , var_(var)
        , params_(params)
    {}

    FunctionVar::~FunctionVar()
    {
        delete var_;
        delete params_;
    }

    const Var* FunctionVar::var_get() const
    {
        return var_;
    }

    Var* FunctionVar::var_get()
    {
        return var_;
    }

    const ExprList* FunctionVar::params_get() const
    {
        return params_;
    }

    ExprList* FunctionVar::params_get()
    {
        return params_;
    }

    const FunctionDec* FunctionVar::def_get() const
    {
        return def_;
    }

    FunctionDec* FunctionVar::def_get()
    {
        return def_;
    }

    void FunctionVar::def_set(FunctionDec* d)
    {
        def_ = d;
    }

    void FunctionVar::add_component(Var* v)
    {
        if (var_ == nullptr)
        {
            var_ = v;
            return;
        }

        var_->add_component(v);
    }

    void FunctionVar::accept(Visitor& v)
    {
        v(*this);
    }

    void FunctionVar::accept(ConstVisitor& v) const
    {
        v(*this);
    }
} // namespace ast

#include <ast/function-var.hh>
#include <ast/any-list.hh>

namespace ast
{
    FunctionVar::FunctionVar(const yy::location& location,
                             Var* var,
                             ExprList* params)
        : Var(location)
        , var_(var)
        , params_(params)
        , def_(nullptr)
    {}

    FunctionVar::~FunctionVar()
    {
        delete var_;
        delete params_;
    }

    const Var* FunctionVar::var_get() const
    {
        return var_;
    }

    Var* FunctionVar::var_get()
    {
        return var_;
    }

    const ExprList* FunctionVar::params_get() const
    {
        return params_;
    }

    ExprList* FunctionVar::params_get()
    {
        return params_;
    }

    const FunctionDec* FunctionVar::def_get() const
    {
        return def_;
    }

    FunctionDec* FunctionVar::def_get()
    {
        return def_;
    }

    void FunctionVar::def_set(FunctionDec* d)
    {
        def_ = d;
    }

    void FunctionVar::add_component(Var* v)
    {
        if (var_ == nullptr)
        {
            var_ = v;
            return;
        }

        var_->add_component(v);
    }

    void FunctionVar::accept(Visitor& v)
    {
        v(*this);
    }

    void FunctionVar::accept(ConstVisitor& v) const
    {
        v(*this);
    }
} // namespace ast

Set FunctionVar def_ to nullptr

[AST] Set FunctionVar def_ to nullptr


/*
Author: vpetrigo
Task:

               .
      .        .
   ,     .

      :        (   1000).

    -   .

*/

#include <iostream>

using namespace std;

int main() {
    int a, b, c;
    const int p_t = 2;

    cin >> a >> b >> c;

    int sum_p = a + b + c;

    cout << (sum_p + p_t - 1) / p_t << endl;

    return 0;
}

/*
Author: vpetrigo
Task:

               .
      .        .
   ,     .

      :        (   1000).

    -   .

*/

#include <iostream>

using namespace std;

int table_count(int st);

int main() {
    int a, b, c;

    cin >> a >> b >> c;

    cout << table_count(a) + table_count(b) + table_count(c) << endl;

    return 0;
}

int table_count(int st) {
    static const int p_t = 2;

    return (st + p_t - 1) / 2;
}

Change task 8 a little Previously it calculated quantity of tables for all studens without taking into account classes. Now it calulates tables needed for each class and then summarise results.


//===----------------------------------------------------------------------===//
//
//                     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, c++11, c++14, c++17
//
// TODO: Remove this when filesystem gets integrated into the dylib
// REQUIRES: c++filesystem

// <chrono>

// file_clock

// check clock invariants

#include <chrono>

template <class T>
void test(const T &) {}

int main()
{
    typedef std::chrono::system_clock C;
    static_assert((std::is_same<C::rep, C::duration::rep>::value), "");
    static_assert((std::is_same<C::period, C::duration::period>::value), "");
    static_assert((std::is_same<C::duration, C::time_point::duration>::value), "");
    static_assert((std::is_same<C::time_point::clock, C>::value), "");
    static_assert((C::is_steady || !C::is_steady), "");
    test(std::chrono::system_clock::is_steady);
}

//===----------------------------------------------------------------------===//
//
//                     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, c++11, c++14, c++17
//
// TODO: Remove this when filesystem gets integrated into the dylib
// REQUIRES: c++filesystem

// <chrono>

// file_clock

// check clock invariants

#include <chrono>

template <class T>
void test(const T &) {}

int main()
{
    typedef std::chrono::file_clock C;
    static_assert((std::is_same<C::rep, C::duration::rep>::value), "");
    static_assert((std::is_same<C::period, C::duration::period>::value), "");
    static_assert((std::is_same<C::duration, C::time_point::duration>::value), "");
    static_assert((std::is_same<C::time_point::clock, C>::value), "");
    static_assert(!C::is_steady, "");
    test(std::chrono::file_clock::is_steady);
}

Fix copy paste error in file_clock tests

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


// Copyright 2017 Google 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.

// Ports filebundle.cpp for different OS.

#include <common/port_flags.h>
#include <errno.h>
#include "khThread.h"

void khMutexBase::Lock(void) {}
void khMutexBase::Unlock(void) {}
khMutex::khMutex(void) {};
khMutex::~khMutex() {};

khCondVar::khCondVar(void) {}
khCondVar::~khCondVar() {}
void khCondVar::signal_one(void) {}
void khCondVar::broadcast_all(void) {}
void khCondVar::wait(khMutexBase &mutex) {}

// Copyright 2017 Google 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.

// Ports filebundle.cpp for different OS.

#include <common/port_flags.h>
#include <errno.h>
#include "khThread.h"

void khMutexBase::Lock(void) {}
void khMutexBase::Unlock(void) {}
bool khMutexBase::TimedTryLock(uint) { return true; }
khMutex::khMutex(void) {};
khMutex::~khMutex() {};

khCondVar::khCondVar(void) {}
khCondVar::~khCondVar() {}
void khCondVar::signal_one(void) {}
void khCondVar::broadcast_all(void) {}
void khCondVar::wait(khMutexBase &mutex) {}

Add new stub function for single threaded tests.


#include <limits>
#include "rdb_protocol/configured_limits.hpp"
#include "rdb_protocol/wire_func.hpp"
#include "rdb_protocol/func.hpp"

namespace ql {
configured_limits_t
from_optargs(rdb_context_t *ctx, signal_t *interruptor,
             const std::map<std::string, wire_func_t> &arguments)
{
    auto p = arguments.find("arrayLimit");
    if (p != arguments.end()) {
        // Fake an environment with no arguments.  We have to fake it
        // because of a chicken/egg problem; this function gets called
        // before there are any extant environments at all.  Only
        // because we use an empty argument list do we prevent an
        // infinite loop.
        env_t env(ctx, interruptor, std::map<std::string, wire_func_t>(),
                  profile_bool_t::DONT_PROFILE);
        return configured_limits_t(p->second.compile_wire_func()->call(&env)->as_int());
    } else {
        return configured_limits_t();
    }
}

RDB_IMPL_ME_SERIALIZABLE_1(configured_limits_t, array_size_limit_);
INSTANTIATE_SERIALIZABLE_SELF_FOR_CLUSTER(configured_limits_t);

const configured_limits_t configured_limits_t::unlimited(std::numeric_limits<size_t>::max());

} // namespace ql

#include "rdb_protocol/configured_limits.hpp"
#include <limits>
#include "rdb_protocol/wire_func.hpp"
#include "rdb_protocol/func.hpp"

namespace ql {
configured_limits_t
from_optargs(rdb_context_t *ctx, signal_t *interruptor,
             const std::map<std::string, wire_func_t> &arguments)
{
    auto p = arguments.find("arrayLimit");
    if (p != arguments.end()) {
        // Fake an environment with no arguments.  We have to fake it
        // because of a chicken/egg problem; this function gets called
        // before there are any extant environments at all.  Only
        // because we use an empty argument list do we prevent an
        // infinite loop.
        env_t env(ctx, interruptor, std::map<std::string, wire_func_t>(),
                  profile_bool_t::DONT_PROFILE);
        return configured_limits_t(p->second.compile_wire_func()->call(&env)->as_int());
    } else {
        return configured_limits_t();
    }
}

RDB_IMPL_ME_SERIALIZABLE_1(configured_limits_t, array_size_limit_);
INSTANTIATE_SERIALIZABLE_SELF_FOR_CLUSTER(configured_limits_t);

const configured_limits_t configured_limits_t::unlimited(std::numeric_limits<size_t>::max());

} // namespace ql

Reorder headers per style doc

Reorder headers per style doc


#include <cstdio>

#include "Werk/Math/SummaryStatistics.hpp"

int main()
{
	werk::SummaryStatistics<double> s;
	s.sample(5.0);
	s.sample(1.0);

	std::printf("Hello world! count=%llu average=%f stddev=%f", s.count(), s.average(), s.stddev());
	return 0;
}

#include <cinttypes>
#include <cstdio>

#include "Werk/Math/SummaryStatistics.hpp"

int main()
{
	werk::SummaryStatistics<double> s;
	s.sample(5.0);
	s.sample(1.0);

	std::printf("Hello world! count=%" PRIu64 " average=%f stddev=%f", s.count(), s.average(), s.stddev());
	return 0;
}

Use correct format specifier in HelloWorld


#include "archive.hpp"

void archive(const char* in_file, const char* out_file) {
	throw "Not implemented";
}

void archive(const char* in_file, std::ostream& out_stream) {
	throw "Not implemented";
}

void archive(std::istream& in_stream, std::ostream& out_stream) {
	throw "Not implemented";
}

#include "archive.hpp"
#include "../huffman/compress.hpp"

#include<fstream>
#include<vector>

void archive_files(const std::vector<std::string>& filenames, std::ostream& out_stream) {
	std::ostreambuf_iterator<char> out_iterator(out_stream);

	for(auto& fn : filenames) {
		for(char c : fn) *out_iterator = c;
		*out_iterator = '\0';
	}
	*out_iterator = '\0';

	for(auto& fn : filenames) {
		std::ifstream in(fn);
		auto freq_table = readTable(in);
		in.close();
		in.open(fn);
		compress(freq_table, in, out_iterator);
	}
}

void archive(const char* in_file, const char* out_file) {
	std::ofstream out(out_file);
	archive(in_file, out);
}

void archive(const char* in_file, std::ostream& out_stream) {
	throw "Not implemented";
}

void archive(std::istream& in_stream, std::ostream& out_stream) {
	std::vector<std::string> filenames;
	std::string fn;

	while(std::getline(in_stream, fn))
		filenames.push_back(fn);

	archive_files(filenames, out_stream);
}

Implement archiving list of files

Implement archiving list of files


// Test that coverage and MSVC CRT stdio work from a DLL. This ensures that the
// __local_stdio_printf_options function isn't instrumented for coverage.

// RUN: rm -rf %t && mkdir %t && cd %t
// RUN: %clang_cl_asan -fsanitize-coverage=func -O0 %p/dll_host.cc -Fet.exe
// RUN: %clang_cl_asan -fsanitize-coverage=func -LD -O0 %s -Fet.dll
// RUN: pwd
// RUN: %run ./t.exe t.dll 2>&1 | FileCheck %s

#include <stdio.h>

extern "C" __declspec(dllexport)
int test_function() {
  printf("hello world\n");
  // CHECK: hello world
  return 0;
}

// Test that coverage and MSVC CRT stdio work from a DLL. This ensures that the
// __local_stdio_printf_options function isn't instrumented for coverage.

// RUN: rm -rf %t && mkdir %t && cd %t
// RUN: %clang_cl_asan -fsanitize-coverage=func -O0 %p/dll_host.cc -Fet.exe
// RUN: %clang_cl_asan -fsanitize-coverage=func -LD -O0 %s -Fet.dll
// RUN: %run ./t.exe t.dll 2>&1 | FileCheck %s

#include <stdio.h>

extern "C" __declspec(dllexport)
int test_function() {
  printf("hello world\n");
  // CHECK: hello world
  return 0;
}

Remove pwd to fix WinASan bot

Remove pwd to fix WinASan bot

It only slipped in while I was debugging the test case.

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


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

#include "system_info/system_info_device_orientation.h"

#include "system_info/system_info_utils.h"

void SysInfoDeviceOrientation::Get(picojson::value& error,
                                   picojson::value& data) {
  system_info::SetPicoJsonObjectValue(error, "message",
      picojson::value("Device Orientation is not supported on desktop."));
}

void PlatformInitialize() { }

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

#include "system_info/system_info_device_orientation.h"

#include "system_info/system_info_utils.h"

void SysInfoDeviceOrientation::Get(picojson::value& error,
                                   picojson::value& data) {
  system_info::SetPicoJsonObjectValue(error, "message",
      picojson::value("Device Orientation is not supported on desktop."));
}

void SysInfoDeviceOrientation::PlatformInitialize() { }

Fix linking error at device orientation

[SystemInfo] Fix linking error at device orientation

Fix linking error while compiling on desktop.


/*
 *  Copyright 2002 California Institute of Technology
 */

#include "cantera/IdealGasMix.h"
#include "cantera/equilibrium.h"
#include "cantera/thermo/IdealSolnGasVPSS.h"
#include "cantera/thermo/ThermoFactory.h"

using namespace std;
using namespace Cantera;

int main(int argc, char** argv)
{
#ifdef _MSC_VER
    _set_output_format(_TWO_DIGIT_EXPONENT);
#endif
    try {
        Cantera::IdealSolnGasVPSS gg("silane.xml", "silane");
        ThermoPhase* g = ≫
        //ThermoPhase *g = newPhase("silane.xml", "silane");
        cout.precision(4);
        g->setState_TPX(1500.0, 100.0, "SIH4:0.01, H2:0.99");
        //g.setState_TPX(1500.0, 1.0132E5, "SIH4:0.01, H2:0.99");
        Cantera::ChemEquil_print_lvl = 40;
        equilibrate(*g, "TP");
        std::string r = g->report(true);
        cout << r;
        cout << endl;
        return 0;
    } catch (CanteraError& err) {
        std::cerr << err.what() << std::endl;
        cerr << "program terminating." << endl;
        return -1;
    }
}

/*
 *  Copyright 2002 California Institute of Technology
 */

#include "cantera/IdealGasMix.h"
#include "cantera/equilibrium.h"
#include "cantera/thermo/IdealSolnGasVPSS.h"
#include "cantera/thermo/ThermoFactory.h"

using namespace std;
using namespace Cantera;

int main(int argc, char** argv)
{
#ifdef _MSC_VER
    _set_output_format(_TWO_DIGIT_EXPONENT);
#endif
    try {
        Cantera::IdealSolnGasVPSS gg("silane.xml", "silane");
        ThermoPhase* g = ≫
        //ThermoPhase *g = newPhase("silane.xml", "silane");
        cout.precision(4);
        g->setState_TPX(1500.0, 100.0, "SIH4:0.01, H2:0.99");
        //g.setState_TPX(1500.0, 1.0132E5, "SIH4:0.01, H2:0.99");
        equilibrate(*g, "TP");
        std::string r = g->report(true);
        cout << r;
        cout << endl;
        return 0;
    } catch (CanteraError& err) {
        std::cerr << err.what() << std::endl;
        cerr << "program terminating." << endl;
        return -1;
    }
}

[Test] Fix failure of VPsilane_test when debug_verbose=y

Partially addresses Issue 69.


/*
   This file is part of the clang-lazy static checker.

  Copyright (C) 2015 Sergio Martins <smartins@kde.org>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) 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.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

#include <regex>

int main()
{
    std::regex r(R"(\s*(SIGNAL|SLOT)\s*\(\s*(.+)\s*\(.*)");
    return 0;
}

Add license to this test file so license checkers don't complain


/*
 * Entry point for the raytracer binary.
 * Autor: Dino Wernli
 */

#include <google/protobuf/stubs/common.h>
#include <memory>

#include "exporter/bmp_exporter.h"
#include "proto/configuration.pb.h"
#include "renderer/image.h"
#include "renderer/renderer.h"
#include "scene/camera.h"
#include "scene/point_light.h"
#include "scene/scene.h"
#include "util/point3.h"
#include "util/ray.h"
#include "util/vector3.h"

int main(int argc, char **argv) {
  raytracer::Configuration config;
  Scene scene;

  std::unique_ptr<Renderer> renderer(Renderer::FromConfig(config));

  Image image(300, 400);

  Vector3 vec(1, 2, 4);
  Point3 p(0, 0, 0);

  Camera* cam = new Camera(p, vec, vec, 0, 300, 500);
  Light* light = new PointLight(Point3(0, 0, 0), Color3(0, 0, 0));

  scene.AddLight(light);
  scene.set_camera(cam);

  scene.Init();

  BmpExporter* exporter = new BmpExporter();
  renderer->AddListener(exporter);

  // Free all memory in the protocol buffer library.
  google::protobuf::ShutdownProtobufLibrary();
  return 0;
}

/*
 * Entry point for the raytracer binary.
 * Autor: Dino Wernli
 */

#include <google/protobuf/stubs/common.h>
#include <memory>

#include "exporter/bmp_exporter.h"
#include "proto/configuration.pb.h"
#include "renderer/image.h"
#include "renderer/renderer.h"
#include "scene/camera.h"
#include "scene/point_light.h"
#include "scene/scene.h"
#include "util/point3.h"
#include "util/ray.h"
#include "util/vector3.h"

// This is just to test some objects.
// TODO(dinow): Remove this when actual functionality... happens.
void TestStuff() {
  Image image(300, 400);
  Vector3 vec(1, 2, 4);
  Point3 p(0, 0, 0);

  raytracer::Configuration config;

  std::unique_ptr<Renderer> renderer(Renderer::FromConfig(config));

  Scene scene;
  Camera* cam = new Camera(p, vec, vec, 0, 300, 500);
  Light* light = new PointLight(Point3(0, 0, 0), Color3(0, 0, 0));
  scene.AddLight(light);
  scene.set_camera(cam);
  scene.Init();

  BmpExporter* exporter = new BmpExporter();
  renderer->AddListener(exporter);
}

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

  // Free all memory in the protocol buffer library.
  google::protobuf::ShutdownProtobufLibrary();
  return 0;
}

Refactor main to use a test method.

Refactor main to use a test method.


#include <node.h>
#include <v8.h>
#include "helpers.h"

using namespace v8;
using namespace node;

namespace node_objc {

  // Cast a JavaScript "String" to an "NSString"
  v8::Handle<Value> Cast_NSString (const Arguments& args) {
    HandleScope scope;
    String::Utf8Value val(args[0]->ToString());
    NSString *rtn = [NSString stringWithUTF8String: *val];
    v8::Handle<Object> rtnWrap = WrapId(rtn);
    return scope.Close(rtnWrap);
  }

  void castsInit(v8::Handle<v8::Object> target) {
    HandleScope scope;
    NODE_SET_METHOD(target, "NSString", Cast_NSString);
  }

} // namespace node_objc

#import <Foundation/Foundation.h>
#include <node.h>
#include <v8.h>
#include "helpers.h"

using namespace v8;
using namespace node;

namespace node_objc {

  // Cast a JavaScript "String" to an "NSString"
  v8::Handle<Value> Cast_NSString (const Arguments& args) {
    HandleScope scope;
    String::Utf8Value val(args[0]->ToString());
    NSString *rtn = [NSString stringWithUTF8String: *val];
    v8::Handle<Object> rtnWrap = WrapId(rtn);
    return scope.Close(rtnWrap);
  }

  // Cast a JavaScript "Number" to an "NSNumber"
  v8::Handle<Value> Cast_NSNumber (const Arguments& args) {
    HandleScope scope;
    double val = args[0]->NumberValue();
    NSNumber *rtn = [NSNumber numberWithDouble: val];
    v8::Handle<Object> rtnWrap = WrapId(rtn);
    return scope.Close(rtnWrap);
  }

  void castsInit(v8::Handle<v8::Object> target) {
    HandleScope scope;
    NODE_SET_METHOD(target, "NSString", Cast_NSString);
    NODE_SET_METHOD(target, "NSNumber", Cast_NSNumber);
  }

} // namespace node_objc

Add NSNumber cast from JavaScript function


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

#include "experimental/graphite/src/ResourceCache.h"

#include "experimental/graphite/src/Resource.h"
#include "include/private/SingleOwner.h"

namespace skgpu {

#define ASSERT_SINGLE_OWNER SKGPU_ASSERT_SINGLE_OWNER(fSingleOwner)

ResourceCache::ResourceCache(SingleOwner* singleOwner) : fSingleOwner(singleOwner) {}

void ResourceCache::insertResource(Resource* resource) {
    ASSERT_SINGLE_OWNER
    SkASSERT(resource);
}

} // namespace skgpu

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

#include "experimental/graphite/src/ResourceCache.h"

#include "experimental/graphite/src/Resource.h"
#include "include/private/SingleOwner.h"

namespace skgpu {

#define ASSERT_SINGLE_OWNER SKGPU_ASSERT_SINGLE_OWNER(fSingleOwner)

ResourceCache::ResourceCache(SingleOwner* singleOwner) : fSingleOwner(singleOwner) {
// TODO: Maybe when things start using ResourceCache, then like Ganesh the compiler won't complain
// about not using fSingleOwner in Release builds and we can delete this.
#ifndef SK_DEBUG
    (void)fSingleOwner;
#endif
}

void ResourceCache::insertResource(Resource* resource) {
    ASSERT_SINGLE_OWNER
    SkASSERT(resource);
}

} // namespace skgpu

[graphite] Fix unused member warning in Release build.

Change-Id: Ib995ebae0ad54d6ce672ce4afe61f67c4247bd9d
Reviewed-on: https://skia-review.googlesource.com/c/skia/+/504540
Commit-Queue: Greg Daniel <39df0a804564ccb6cf75f18db79653821f37c1c5@google.com>
Auto-Submit: Greg Daniel <39df0a804564ccb6cf75f18db79653821f37c1c5@google.com>
Reviewed-by: Robert Phillips <95e8ac5504948c7bf91b22c16a8dbb7ae7c66bfd@google.com>
Commit-Queue: Robert Phillips <95e8ac5504948c7bf91b22c16a8dbb7ae7c66bfd@google.com>


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

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  MainWindow w;
  w.show();

  return a.exec();
}

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

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  a.setStyle(QStyleFactory::create("Fusion"));

  QPalette dark;
  dark.setColor(QPalette::Window, QColor(53, 53, 53));
  dark.setColor(QPalette::WindowText, Qt::white);
  dark.setColor(QPalette::Base, QColor(25, 25, 25));
  dark.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
  dark.setColor(QPalette::ToolTipBase, Qt::white);
  dark.setColor(QPalette::ToolTipText, Qt::white);
  dark.setColor(QPalette::Text, Qt::white);
  dark.setColor(QPalette::Button, QColor(53, 53, 53));
  dark.setColor(QPalette::ButtonText, Qt::white);
  dark.setColor(QPalette::BrightText, Qt::red);
  dark.setColor(QPalette::Link, QColor(42, 130, 218));
  dark.setColor(QPalette::Highlight, QColor(254,165,0));
  dark.setColor(QPalette::HighlightedText, Qt::black);
  a.setPalette(dark);

  Main_window w;
  w.show();

  return a.exec();
}

Change UI to dark style

Change UI to dark style


#include "utils/connection.h"

namespace utils {

Connection::Connection(const std::string& host, const std::string& port)
  : socket(io_service) {
  tcp::resolver resolver(io_service);
  tcp::resolver::query query(host, port);
  boost::asio::connect(socket, resolver.resolve(query));
  response_buf.prepare(8192);
}

Connection::~Connection() {
  socket.close();
}

jsoncons::json Connection::receive_response(boost::system::error_code* error) {
  auto len = boost::asio::read_until(socket, response_buf, "\n", *error);
  if (*error) {
    return jsoncons::json();
  }
  auto buf = response_buf.data();
  std::string reply(boost::asio::buffers_begin(buf), boost::asio::buffers_begin(buf) + len);
  response_buf.consume(len);
  return jsoncons::json::parse_string(reply);
}

void Connection::send_requests(const std::vector<jsoncons::json>& msgs) {
  jsoncons::output_format format;
  format.escape_all_non_ascii(true);
  boost::asio::streambuf request_buf;
  std::ostream s(&request_buf);
  for (const auto& m : msgs) {
    // std::cout << "Responded with: " << pretty_print(m) << std::endl;
    m.to_stream(s, format);
    s << std::endl;
  }
  socket.send(request_buf.data());
}

}  // namespace utils

#include "utils/connection.h"

namespace utils {

Connection::Connection(const std::string& host, const std::string& port)
  : socket(io_service) {
  tcp::resolver resolver(io_service);
  tcp::resolver::query query(host, port);
  boost::asio::connect(socket, resolver.resolve(query));
  response_buf.prepare(8192);
}

Connection::~Connection() {
  socket.close();
}

jsoncons::json Connection::receive_response(boost::system::error_code* error) {
  auto len = boost::asio::read_until(socket, response_buf, "\n", *error);
  if (*error) {
    return jsoncons::json();
  }
  auto buf = response_buf.data();
  std::string reply(boost::asio::buffers_begin(buf), boost::asio::buffers_begin(buf) + len);
  response_buf.consume(len);
  return jsoncons::json::parse_string(reply);
}

void Connection::send_requests(const std::vector<jsoncons::json>& msgs) {
  jsoncons::output_format format;
  format.escape_all_non_ascii(true);
  boost::asio::streambuf request_buf;
  std::ostream s(&request_buf);
  for (const auto& m : msgs) {
    std::cout << "Responded with: " << pretty_print(m) << std::endl;
    m.to_stream(s, format);
    s << std::endl;
  }
  socket.send(request_buf.data());
}

}  // namespace utils

Add debug for server responses

Add debug for server responses


// Test reading of PCH without original input files.

// Generate the PCH, removing the original file:
// RUN: echo 'struct S{char c; int i; }; void foo() {}' > %t.h
// RUN: echo 'template <typename T> void tf() { T::foo(); }' >> %t.h
// RUN: echo '#define RETURN return &i' >> %t.h
// RUN: %clang_cc1 -x c++ -emit-pch -o %t.h.pch %t.h
// RUN: rm %t.h

// Check diagnostic with location in original source:
// RUN: %clang_cc1 -include-pch %t.h.pch -Wpadded -emit-obj %s 2> %t.stderr
// RUN: grep 'bytes to align' %t.stderr

// Check diagnostic with 2nd location in original source:
// RUN: not %clang_cc1 -DREDECL -include-pch %t.h.pch -emit-obj %s 2> %t.stderr
// RUN: grep 'previous definition is here' %t.stderr

// Check diagnostic with instantiation location in original source:
// RUN: not %clang_cc1 -DINSTANTIATION -include-pch %t.h.pch -emit-obj %s 2> %t.stderr
// RUN: grep 'cannot be used prior to' %t.stderr

void qq(S*) {}

#ifdef REDECL
float foo() {return 0f;}
#endif

#ifdef INSTANTIATION
void f() {
  tf<int>();
}
#endif

// Test reading of PCH without original input files.

// Generate the PCH, removing the original file:
// RUN: echo 'struct S{char c; int i; }; void foo() {}' > %t.h
// RUN: echo 'template <typename T> void tf() { T::foo(); }' >> %t.h
// RUN: echo '#define RETURN return &i' >> %t.h
// RUN: %clang_cc1 -x c++ -emit-pch -o %t.h.pch %t.h
// RUN: rm %t.h

// Check diagnostic with location in original source:
// RUN: %clang_cc1 -include-pch %t.h.pch -Wpadded -emit-obj -o %t.o %s 2> %t.stderr
// RUN: grep 'bytes to align' %t.stderr

// Check diagnostic with 2nd location in original source:
// RUN: not %clang_cc1 -DREDECL -include-pch %t.h.pch -emit-obj -o %t.o %s 2> %t.stderr
// RUN: grep 'previous definition is here' %t.stderr

// Check diagnostic with instantiation location in original source:
// RUN: not %clang_cc1 -DINSTANTIATION -include-pch %t.h.pch -emit-obj -o %t.o %s 2> %t.stderr
// RUN: grep 'cannot be used prior to' %t.stderr

void qq(S*) {}

#ifdef REDECL
float foo() {return 0f;}
#endif

#ifdef INSTANTIATION
void f() {
  tf<int>();
}
#endif

Use tempfiles for the .o outputs.

Use tempfiles for the .o outputs.

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


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

#include "chrome/browser/metrics/metrics_service.h"

#include <string>

#include "base/base64.h"

#include "testing/gtest/include/gtest/gtest.h"

class MetricsServiceTest : public ::testing::Test {
};

// Ensure the ClientId is formatted as expected.
TEST(MetricsServiceTest, ClientIdCorrectlyFormatted) {
  std::string clientid = MetricsService::GenerateClientID();
  EXPECT_EQ(36U, clientid.length());
  std::string hexchars = "0123456789ABCDEF";
  for (uint32 i = 0; i < clientid.length(); i++) {
    char current = clientid.at(i);
    if (i == 8 || i == 13 || i == 18 || i == 23) {
      EXPECT_EQ('-', current);
    } else {
      EXPECT_TRUE(std::string::npos != hexchars.find(current));
    }
  }
}

TEST(MetricsServiceTest, IsPluginProcess) {
  EXPECT_TRUE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_PLUGIN));
  EXPECT_TRUE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_PPAPI_PLUGIN));
  EXPECT_FALSE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_GPU));
}

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

#include <ctype.h>
#include <string>

#include "chrome/browser/metrics/metrics_service.h"
#include "testing/gtest/include/gtest/gtest.h"

// Ensure the ClientId is formatted as expected.
TEST(MetricsServiceTest, ClientIdCorrectlyFormatted) {
  std::string clientid = MetricsService::GenerateClientID();
  EXPECT_EQ(36U, clientid.length());

  for (size_t i = 0; i < clientid.length(); ++i) {
    char current = clientid[i];
    if (i == 8 || i == 13 || i == 18 || i == 23)
      EXPECT_EQ('-', current);
    else
      EXPECT_TRUE(isxdigit(current));
  }
}

TEST(MetricsServiceTest, IsPluginProcess) {
  EXPECT_TRUE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_PLUGIN));
  EXPECT_TRUE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_PPAPI_PLUGIN));
  EXPECT_FALSE(
      MetricsService::IsPluginProcess(content::PROCESS_TYPE_GPU));
}

Clean up MetricsService unit test.

Clean up MetricsService unit test.

BUG=none
TEST=none

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

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


// RUN: %clang_cc1 -std=c++2a %s -verify

struct X {
  void ref() & {}
  void cref() const& {}
};

void test() {
  X{}.ref(); // expected-error{{cannot initialize object parameter of type 'X' with an expression of type 'X'}}
  X{}.cref(); // expected-no-error

  (X{}.*&X::ref)(); // expected-error{{pointer-to-member function type 'void (X::*)() &' can only be called on an lvalue}}
  (X{}.*&X::cref)(); // expected-no-error
}

// RUN: %clang_cc1 -std=c++2a %s -verify

struct X {
  void ref() & {}
  void cref() const& {}
};

void test() {
  X{}.ref(); // expected-error{{cannot initialize object parameter of type 'X' with an expression of type 'X'}}
  X{}.cref(); // expected-no-error

  (X{}.*&X::ref)(); // expected-error-re{{pointer-to-member function type 'void (X::*)() {{.*}}&' can only be called on an lvalue}}
  (X{}.*&X::cref)(); // expected-no-error
}

Fix MSVC bots which include '__attribute__((thiscall))' in pretty-printed member function types.

We really shouldn't be including inferred calling conventions here, but let's get the bots green first...

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


#include "Thread/ScopedLock.hh"

namespace LilWrapper
{
  ScopedLock::ScopedLock(Mutex *mutex)
    : _mutex(mutex)
  {
    this->_mutex->lock();
  }

  ScopedLock::~ScopedLock()
  {
    this->_mutex->unlock();
  }
}

#include "Thread/ScopedLock.hh"

namespace LilWrapper
{
  ScopedLock::ScopedLock(Mutex *mutex)
    : _mutex(mutex)
  {
    if (this->_mutex)
      this->_mutex->lock();
  }

  ScopedLock::~ScopedLock()
  {
    if (this->_mutex)
      this->_mutex->unlock();
  }
}

Make sure the Mutex exists before using it.


#include <bits/stdc++.h>
#define pb push_back
using namespace std;
typedef vector <string> vs;
int toNum(string a){
	stringstream toNum(a);
	int num;
	toNum >> num;
	return num;
}
vs split(string line, char d){
	vector < string > elements;
	stringstream ss(line);
	string item;
	while(getline(ss, item, d))	elements.pb(item);
	return elements;
}

int main(){
  vs d1 = split("1990/10/5", '/');
  for (string s: d1){
    cout << toNum(s) << endl;
  }

  char a = 'a';
  cout << (isalnum(a)?"true":"false")  << endl;
  cout <<( isalpha(a)?"true":"false") << endl;
  cout << (isblank(a)?"true":"false")  << endl;
  cout << (isdigit(a)?"true":"false")  << endl;
  cout << (islower(a)?"true":"false")  << endl;
  cout << (ispunct(a)?"true":"false")  << endl;
  cout << (isupper(a)?"true":"false")  << endl;
  cout << (isxdigit(a) ?"true":"false") << endl;
  cout << (char)tolower(a) << endl;
  cout << (char)toupper(a) << endl;
  return 0;
}

#include <bits/stdc++.h>
#define pb push_back
using namespace std;
typedef vector <string> vs;
int toNum(string a){
	stringstream toNum(a);
	int num;
	toNum >> num;
	return num;
}

string toString(double d){
  stringstream ss;
	ss << fixed << setprecision(10) << fl;
	string num = ss.str();
	return num;
}

vs split(string line, char d){
	vector < string > elements;
	stringstream ss(line);
	string item;
	while(getline(ss, item, d))	elements.pb(item);
	return elements;
}

int main(){
  vs d1 = split("1990/10/5", '/');
  for (string s: d1){
    cout << toNum(s) << endl;
  }

  char a = 'a';
  cout << (isalnum(a)?"true":"false")  << endl;
  cout <<( isalpha(a)?"true":"false") << endl;
  cout << (isblank(a)?"true":"false")  << endl;
  cout << (isdigit(a)?"true":"false")  << endl;
  cout << (islower(a)?"true":"false")  << endl;
  cout << (ispunct(a)?"true":"false")  << endl;
  cout << (isupper(a)?"true":"false")  << endl;
  cout << (isxdigit(a) ?"true":"false") << endl;
  cout << (char)tolower(a) << endl;
  cout << (char)toupper(a) << endl;
  return 0;
}

Create useful function to convert a number to string.


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

#include "logaction.h"

LogAction::LogAction(Application *application)
    : mDialog(application)
{
}

QString LogAction::name() const
{
    return "log";
}

bool LogAction::ui() const
{
    return true;
}

QString LogAction::title() const
{
    return tr("View Log");
}

bool LogAction::invoke(const QVariantMap &)
{
    mDialog.show();
}

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

#include "logaction.h"

LogAction::LogAction(Application *application)
    : mDialog(application)
{
}

QString LogAction::name() const
{
    return "log";
}

bool LogAction::ui() const
{
    return true;
}

QString LogAction::title() const
{
    return tr("View Log");
}

bool LogAction::invoke(const QVariantMap &)
{
    mDialog.show();
    return true;
}

Fix compilation error on MSVC++.

Fix compilation error on MSVC++.


#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


#include <ncurses.h>

#include "print.hpp"
#include "lightsout.hpp"
#include "keybindings.hpp"
using namespace roadagain;

int main()
{
    initscr();
    cbreak();
    noecho();
    curs_set(0);
    start_color();
    init_colors();

    board b(5, 5);
    keybindings k("emacs");
    while (!b.is_perfect()){
        char c = getch();
        const char* key = keyname(c);

        b.move_board(k.dy(key), k.dx(key));
    }

    endwin();
    return 0;
}

#include <ncurses.h>
#include <cstring>

#include <string>

#include "print.hpp"
#include "lightsout.hpp"
#include "keybindings.hpp"
using namespace roadagain;

int main(int argc, char** argv)
{
    initscr();
    cbreak();
    noecho();
    curs_set(0);
    start_color();
    init_colors();

    std::string key = "vim";
    for (int i = 1; i < argc; i++){
        if (std::strncmp("--key=", argv[i], 6) == 0){
            key = argv[i] + 6;
        }
    }

    board b(5, 5);
    keybindings k(key.c_str());
    while (!b.is_perfect()){
        char c = getch();
        const char* key = keyname(c);

        b.move_board(k.dy(key), k.dx(key));
    }

    endwin();
    return 0;
}

Add getting keybindings from argv

Add getting keybindings from argv


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

#include "base/system_monitor.h"

namespace base {

void SystemMonitor::ProcessWmPowerBroadcastMessage(int event_id) {
  PowerEvent power_event;
  switch (event_id) {
    case PBT_APMPOWERSTATUSCHANGE:
      power_event = POWER_STATE_EVENT;
      break;
    case PBT_APMRESUMEAUTOMATIC:
      power_event = RESUME_EVENT;
      break;
    case PBT_APMSUSPEND:
      power_event = SUSPEND_EVENT;
      break;
    default:
      DCHECK(false);
  }
  ProcessPowerMessage(power_event);
}

// Function to query the system to see if it is currently running on
// battery power.  Returns true if running on battery.
bool SystemMonitor::IsBatteryPower() {
  SYSTEM_POWER_STATUS status;
  if (!GetSystemPowerStatus(&status)) {
    LOG(ERROR) << "GetSystemPowerStatus failed: " << GetLastError();
    return false;
  }
  return (status.ACLineStatus == 0);
}

} // namespace base

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

#include "base/system_monitor.h"

namespace base {

void SystemMonitor::ProcessWmPowerBroadcastMessage(int event_id) {
  PowerEvent power_event;
  switch (event_id) {
    case PBT_APMPOWERSTATUSCHANGE:  // The power status changed.
      power_event = POWER_STATE_EVENT;
      break;
    case PBT_APMRESUMEAUTOMATIC:  // Non-user initiated resume from suspend.
    case PBT_APMRESUMESUSPEND:    // User initiated resume from suspend.
      power_event = RESUME_EVENT;
      break;
    case PBT_APMSUSPEND:  // System has been suspended.
      power_event = SUSPEND_EVENT;
      break;
    default:
      return;

    // Other Power Events:
    // PBT_APMBATTERYLOW - removed in Vista.
    // PBT_APMOEMEVENT - removed in Vista.
    // PBT_APMQUERYSUSPEND - removed in Vista.
    // PBT_APMQUERYSUSPENDFAILED - removed in Vista.
    // PBT_APMRESUMECRITICAL - removed in Vista.
    // PBT_POWERSETTINGCHANGE - user changed the power settings.
  }
  ProcessPowerMessage(power_event);
}

// Function to query the system to see if it is currently running on
// battery power.  Returns true if running on battery.
bool SystemMonitor::IsBatteryPower() {
  SYSTEM_POWER_STATUS status;
  if (!GetSystemPowerStatus(&status)) {
    LOG(ERROR) << "GetSystemPowerStatus failed: " << GetLastError();
    return false;
  }
  return (status.ACLineStatus == 0);
}

} // namespace base

Update comments and remove bogus DCHECK in windows-specific broadcasted power message status.

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

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


Add dummy test for memory allocator.

Add dummy test for memory allocator.


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

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/op.h"

namespace tensorflow {

REGISTER_OP("BytesLimit").Output("out: int64").SetIsStateful();
REGISTER_OP("MaxBytesInUse").Output("out: int64").SetIsStateful();

}  // namespace tensorflow

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

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"

namespace tensorflow {

REGISTER_OP("BytesLimit")
    .Output("out: int64")
    .SetIsStateful()
    .SetShapeFn(shape_inference::ScalarShape);
REGISTER_OP("MaxBytesInUse")
    .Output("out: int64")
    .SetIsStateful()
    .SetShapeFn(shape_inference::ScalarShape);

}  // namespace tensorflow

Add static shape inference to BytesLimit and MaxBytesInUse.

PiperOrigin-RevId: 158540875


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

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"

namespace tensorflow {
namespace {

class XlaReplicaIdOp : public XlaOpKernel {
 public:
  explicit XlaReplicaIdOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
  void Compile(XlaOpKernelContext* ctx) override;

 private:
  TF_DISALLOW_COPY_AND_ASSIGN(XlaReplicaIdOp);
};

void XlaReplicaIdOp::Compile(XlaOpKernelContext* ctx) {
  ctx->SetOutput(0, xla::ReplicaId(ctx->builder()));
}

REGISTER_XLA_OP(Name("XlaReplicaId"), XlaReplicaIdOp);

}  // namespace
}  // namespace tensorflow

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

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"

namespace tensorflow {
namespace {

class XlaReplicaIdOp : public XlaOpKernel {
 public:
  explicit XlaReplicaIdOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {}
  void Compile(XlaOpKernelContext* ctx) override;

 private:
  TF_DISALLOW_COPY_AND_ASSIGN(XlaReplicaIdOp);
};

void XlaReplicaIdOp::Compile(XlaOpKernelContext* ctx) {
  ctx->SetOutput(
      0, xla::ConvertElementType(xla::ReplicaId(ctx->builder()), xla::S32));
}

REGISTER_XLA_OP(Name("XlaReplicaId"), XlaReplicaIdOp);

}  // namespace
}  // namespace tensorflow

[tf2xla] Convert the result of xla::ReplicaId to S32

PiperOrigin-RevId: 327455603
Change-Id: Ic5efe1f80fc7a92debbc4f08853f824f8cdfb937