#include <Spark/SparseLinearSolvers.hpp>
#include <iostream>

Eigen::VectorXd spark::sparse_linear_solvers::DfeBiCgSolver::solve(
            const Eigen::SparseMatrix<double>& A,
            const Eigen::VectorXd& b)
{
  Eigen::VectorXd vd(b.size());
  return vd;
}

#include <Spark/SparseLinearSolvers.hpp>
#include <iostream>
#include <stdexcept>

using Vd = Eigen::VectorXd;

Eigen::VectorXd spark::sparse_linear_solvers::DfeBiCgSolver::solve(
            const Eigen::SparseMatrix<double>& A,
            const Eigen::VectorXd& b)
{

  std::cout << "Running bicgstab!!!" << std::endl;
  Vd x(b.size());
  Vd p(b.size());
  Vd v(b.size());

  double rho, alpha, omega, beta;
  double rho_prev, omega_prev;

  Vd r =  b - A * x;
  Vd rhat = r;
  rho = rho_prev = alpha = omega = omega_prev = 1;
  x.setZero();
  v.setZero();
  p.setZero();

  int maxIter = 2000000;
  double normErr = 1E-15;

  Vd precon(b.size());
  for (int i = 0; i < b.size(); i++) {
    if (A.diagonal()(i) == 0)
      throw std::invalid_argument("Main diagonal contains zero elements");
    precon[i] = 1/A.diagonal()(i);
  }

  for (int i = 0; i < maxIter; i++) {
    std::cout << "Iteration " << i << std::endl;
    rho = rhat.dot(r);
    beta = rho / rho_prev * alpha / omega_prev;
    p = r + beta * (p - omega_prev * v);
    Vd y = precon.cwiseProduct(p);
    v = A * y;
    alpha = rho / rhat.dot(v);
    Vd s = r - alpha * v;
    if (s.norm() < normErr) {
      return x + alpha * p;
    }
    Vd z = precon.cwiseProduct(s);
    Vd t = A * z;
    Vd tmp = precon.cwiseProduct(t);
    omega = tmp.dot(z) / tmp.dot(tmp);
    x = x + alpha * y + omega * z;
    r = s - omega * t;
    omega_prev = omega;
    rho_prev = rho;
  }

  return x;
}

Add hand written preconditioned bicgstab


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

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

namespace RosettaStone::SimpleTasks
{
SetGameTagTask::SetGameTagTask(EntityType entityType, GameTag tag, int amount)
    : ITask(entityType), m_gameTag(tag), m_amount(amount)
{
    // Do nothing
}

TaskID SetGameTagTask::GetTaskID() const
{
    return TaskID::SET_GAME_TAG;
}

TaskStatus SetGameTagTask::Impl(Player& player)
{
    auto entities =
        IncludeTask::GetEntities(m_entityType, player, m_source, m_target);

    for (auto& entity : entities)
    {
        entity->SetGameTag(m_gameTag, m_amount);
    }

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

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

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

namespace RosettaStone::SimpleTasks
{
SetGameTagTask::SetGameTagTask(EntityType entityType, GameTag tag, int amount)
    : ITask(entityType), m_gameTag(tag), m_amount(amount)
{
    // Do nothing
}

TaskID SetGameTagTask::GetTaskID() const
{
    return TaskID::SET_GAME_TAG;
}

TaskStatus SetGameTagTask::Impl(Player& player)
{
    auto entities =
        IncludeTask::GetEntities(m_entityType, player, m_source, m_target);

    for (auto& entity : entities)
    {
        entity->SetGameTag(m_gameTag, m_amount);

        // Process windfury
        if (m_gameTag == GameTag::WINDFURY && m_amount == 1)
        {
            auto m = dynamic_cast<Minion*>(entity);
            if (m != nullptr && m->numAttacked == 1 &&
                m->GetGameTag(GameTag::EXHAUSTED) == 1)
            {
                m->SetGameTag(GameTag::EXHAUSTED, 0);
            }
        }
    }

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

Add code to process windfury game tag

feat(card-impl): Add code to process windfury game tag


#ifndef WARGEN_CPP
#define WARGEN_CPP

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

int main() {

std::vector<char> cards = {'1','1','1','1','2','2','2','2','3','3','3','3','4','4','4','4','5','5','5','5','6','6','6','6','7','7','7','7','8','8','8','8','9','9','9','9','T','T','T','T','J','J','J','J','Q','Q','Q','Q','K','K','K','K'};
std::vector<int> thresholds = {6,7,8,9,10,11,12};
std::ofstream myFile;
myFile.open("input1.txt");

std::random_shuffle(cards.begin(), cards.end());
std::random_shuffle(thresholds.begin(), thresholds.end());

for(int i = 0; i < 52; i++) {
  myFile << cards[i];
  if(i==25) {
    myFile << "\n";
  }
}
myFile << "\n";
for(int i = 0; i < 7; i++) {
  myFile << thresholds[i];
}
std::random_shuffle(thresholds.begin(), thresholds.end());
myFile << "\n";
for(int i = 0; i < 7; i++) {
  myFile << thresholds[i];
}

myFile.close9);
};

#endif

Update input generator to be in line with description


#include "params.hpp"

#include "../coding/multilang_utf8_string.hpp"

namespace search
{

SearchParams::SearchParams()
: m_inputLanguageCode(StringUtf8Multilang::UNSUPPORTED_LANGUAGE_CODE),
  m_searchMode(ALL), m_validPos(false)
{
}

void SearchParams::SetPosition(double lat, double lon)
{
  m_lat = lat;
  m_lon = lon;
  m_validPos = true;
}

void SearchParams::SetInputLanguage(string const & language)
{
  /// @todo take into an account zh_pinyin, ko_rm and ja_rm
  size_t const delimPos = language.find_first_of("-_");

  m_inputLanguageCode = StringUtf8Multilang::GetLangIndex(
        delimPos == string::npos ? language : language.substr(0, delimPos));
}

bool SearchParams::IsLanguageValid() const
{
  return (m_inputLanguageCode != StringUtf8Multilang::UNSUPPORTED_LANGUAGE_CODE);
}

bool SearchParams::IsEqualCommon(SearchParams const & rhs) const
{
  // do not compare m_mode
  return (m_query == rhs.m_query &&
          m_inputLanguageCode == rhs.m_inputLanguageCode &&
          m_validPos == rhs.m_validPos &&
          m_searchMode == rhs.m_searchMode);
}

string DebugPrint(SearchParams const & params)
{
  string s("search::SearchParams: ");
  s = s + "Query = " + params.m_query;
  return s;
}

} // namespace search

#include "params.hpp"

#include "../coding/multilang_utf8_string.hpp"

namespace search
{

SearchParams::SearchParams()
: m_inputLanguageCode(StringUtf8Multilang::UNSUPPORTED_LANGUAGE_CODE),
  m_searchMode(ALL), m_validPos(false)
{
}

void SearchParams::SetPosition(double lat, double lon)
{
  m_lat = lat;
  m_lon = lon;
  m_validPos = true;
}

void SearchParams::SetInputLanguage(string const & language)
{
  /// @todo take into an account zh_pinyin, ko_rm and ja_rm
  size_t const delimPos = language.find_first_of("-_");

  m_inputLanguageCode = StringUtf8Multilang::GetLangIndex(
        delimPos == string::npos ? language : language.substr(0, delimPos));
}

bool SearchParams::IsLanguageValid() const
{
  return (m_inputLanguageCode != StringUtf8Multilang::UNSUPPORTED_LANGUAGE_CODE);
}

bool SearchParams::IsEqualCommon(SearchParams const & rhs) const
{
  return (m_query == rhs.m_query &&
          m_inputLanguageCode == rhs.m_inputLanguageCode &&
          m_validPos == rhs.m_validPos &&
          m_searchMode == rhs.m_searchMode);
}

string DebugPrint(SearchParams const & params)
{
  string s("search::SearchParams: ");
  s = s + "Query = " + params.m_query;
  return s;
}

} // namespace search

Fix bug with comparing SearchParams.

Fix bug with comparing SearchParams.


#include "grune/all.hpp"

#include <boost/filesystem.hpp>
#include <fstream>

#define ADD_TEST(name) \
    extern void name(std::ostream&);

ADD_TEST(test_anbncn);
ADD_TEST(test_numbers);
ADD_TEST(test_numbers_simple);
ADD_TEST(test_tdh);
ADD_TEST(test_turtle);

typedef void (*test_fcn_t)(std::ostream&);
void run_test(test_fcn_t test, const std::string& name)
{
    std::cout << "Running test " << name << "..." << std::endl;
    std::ofstream results("./results/" + name + ".results");
    test(results);
}

#define RUN_TEST(name) run_test(name, #name)

int main()
{
    RUN_TEST(test_anbncn);
    RUN_TEST(test_numbers_simple);
    RUN_TEST(test_numbers);
    RUN_TEST(test_turtle);
    RUN_TEST(test_tdh);

    return 0;
}

#include "grune/all.hpp"

#include <boost/filesystem.hpp>
#include <fstream>

#define ADD_TEST(name) \
    extern void name(std::ostream&);

ADD_TEST(test_anbncn);
ADD_TEST(test_numbers);
ADD_TEST(test_numbers_simple);
ADD_TEST(test_tdh);
ADD_TEST(test_turtle);

typedef void (*test_fcn_t)(std::ostream&);
void run_test(test_fcn_t test, const std::string& name)
{
    std::cout << "Running test " << name << "..." << std::endl;
    std::ofstream results("./results/" + name + ".results");
    test(results);
}

#ifndef COVERITY_BUILD
#define RUN_TEST(name) run_test(name, #name)
#else
#include <coverity-test-separation.h>
#define RUN_TEST(name) \
    do { \
        COVERITY_TS_START_TEST(#name); \
        run_test(name, #name); \
        COVERITY_TS_END_TEST(); \
    } while (0)
#endif

int main()
{
#ifdef COVERITY_BUILD
    COVERITY_TS_SET_SUITE_NAME("generation_tests");
#endif
    RUN_TEST(test_anbncn);
    RUN_TEST(test_numbers_simple);
    RUN_TEST(test_numbers);
    RUN_TEST(test_turtle);
    RUN_TEST(test_tdh);

    return 0;
}

Add test separation for generation tests.


//
//  Gyroid.cpp
//  VolumeRenderer
//
//  Created by Calvin Loncaric on 6/26/11.
//

#include "Gyroid.h"
#include <cmath>

float Gyroid::valueAt(float x, float y, float z) const
{
    return (cosf(x) * sinf(y) + cosf(y) * sinf(z) + cosf(z) * sinf(x));
}

vector Gyroid::gradientAt(float x, float y, float z) const
{
    return Isosurface::gradientAt(x, y, z);
    float gx = cosf(x) * cosf(z) - sinf(x) * sinf(y);
    float gy = cosf(x) * cosf(y) - sinf(y) * sinf(z);
    float gz = cosf(y) * cosf(z) - sinf(x) * sinf(z);

    vector result = { gx, gy, gz };
    normalize(result);

    return result;
}

//
//  Gyroid.cpp
//  VolumeRenderer
//
//  Created by Calvin Loncaric on 6/26/11.
//

#include "Gyroid.h"
#include <cmath>

float Gyroid::valueAt(float x, float y, float z) const
{
    return (cosf(x) * sinf(y) + cosf(y) * sinf(z) + cosf(z) * sinf(x));
}

vector Gyroid::gradientAt(float x, float y, float z) const
{
    float gx = cosf(x) * cosf(z) - sinf(x) * sinf(y);
    float gy = cosf(x) * cosf(y) - sinf(y) * sinf(z);
    float gz = cosf(y) * cosf(z) - sinf(x) * sinf(z);

    vector result = { gx, gy, gz };
    normalize(result);

    return result;
}

Remove a stray debug line

Remove a stray debug line


#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <string.h>
#include <stdio.h>
#include <excpt.h>

#include "sapi4.hpp"

int main(int argc, char** argv)
{
	VOICE_INFO VoiceInfo;
	if (!InitializeForVoice(argv[1], &VoiceInfo)) {
		return 0;
	}

	UINT64 Len;

	LPSTR outFile = (LPSTR)malloc(17);
	GetTTS(&VoiceInfo, atoi(argv[2]), atoi(argv[3]), argv[4], &Len, &outFile);

	printf("%s\n", outFile);
	free(outFile);
}

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <string.h>
#include <stdio.h>
#include <excpt.h>

#include "sapi4.hpp"

int main(int argc, char** argv)
{
	VOICE_INFO VoiceInfo;
	if (!InitializeForVoice(argv[1], &VoiceInfo)) {
		return 0;
	}

	UINT64 Len;

	LPSTR outFile[17];
	GetTTS(&VoiceInfo, atoi(argv[2]), atoi(argv[3]), argv[4], &Len, &outFile);

	printf("%s\n", outFile);
}

Use stack instead of malloc

Use stack instead of malloc


#pragma warning( disable : 4350 )
#pragma warning(push, 3)
#include <iostream>
#pragma warning(pop)

int main(int , char **) {
    std::cout << "Hello CI!" << std::endl;
    return 0;
}

#pragma warning( disable : 4710 4514)

#pragma warning( disable : 4350 4710 )
#pragma warning(push, 3)
#include <iostream>
#pragma warning(pop)

int main(int , char **) {
    std::cout << "Hello CI!" << std::endl;
    return 0;
}

#pragma warning( disable : 4514)

Make MSVC release build actually work

Make MSVC release build actually work


#include <spdlog/spdlog.h>

int main(int argc, char* argv[]) {
  auto console = spdlog::stdout_logger_mt("console");
  console->info("Hello from INFO");
}

#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_sinks.h>

int main(int argc, char* argv[]) {
  auto console = spdlog::stdout_logger_mt("console");
  console->info("Hello from INFO");
  return 0;
}

Fix missing include in the example

Fix missing include in the example


//
// Created by Jan de Visser on 2021-09-22.
//

#include <core/Format.h>
#include <core/StringUtil.h>
#include <gtest/gtest.h>

TEST(Format, format_int) {
    std::string formatted = Obelix::format("{}", 42);
    EXPECT_EQ(formatted, "42");
}

TEST(Format, format_string) {
    std::string formatted = Obelix::format("{}", std::string("Hello World!"));
    EXPECT_EQ(formatted, "Hello World!");
}

TEST(Format, format_char)
{
    std::string formatted = Obelix::format("{}","Hello World!");
    EXPECT_EQ(formatted, "Hello World!");
}

TEST(Format, format_char_and_int)
{
    std::string formatted = Obelix::format("String: '{}' int: {}-", "Hello World!", 42);
    EXPECT_EQ(formatted, "String: 'Hello World!' int: 42-");
}

//
// Created by Jan de Visser on 2021-09-22.
//

#include <core/Format.h>
#include <core/StringUtil.h>
#include <gtest/gtest.h>

TEST(Format, format_int) {
    std::string formatted = Obelix::format("{}", 42);
    EXPECT_EQ(formatted, "42");
}

TEST(Format, format_string) {
    std::string formatted = Obelix::format("{}", std::string("Hello World!"));
    EXPECT_EQ(formatted, "Hello World!");
}

TEST(Format, format_char)
{
    std::string formatted = Obelix::format("{}", "Hello World!");
    EXPECT_EQ(formatted, "Hello World!");
}

TEST(Format, format_char_and_int)
{
    std::string formatted = Obelix::format("String: '{}' int: {}-", "Hello World!", 42);
    EXPECT_EQ(formatted, "String: 'Hello World!' int: 42-");
}

TEST(Format, format_escape)
{
    std::string formatted = Obelix::format("String: '{}' Escaped brace: {{ and a close } int: {}-", "Hello World!", 42);
    EXPECT_EQ(formatted, "String: 'Hello World!' Escaped brace: { and a close } int: 42-");
}

Test for { escaping in format()

Test for { escaping in format()


/**
 * \file
 * \brief chip::lowLevelInitialization() implementation for STM32F0
 *
 * \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/chip/lowLevelInitialization.hpp"

namespace distortos
{

namespace chip
{

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

void lowLevelInitialization()
{

}

}	// namespace chip

}	// namespace distortos

/**
 * \file
 * \brief chip::lowLevelInitialization() implementation for STM32F0
 *
 * \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/chip/lowLevelInitialization.hpp"

#include "distortos/chip/STM32F0-FLASH.hpp"

#include "distortos/distortosConfiguration.h"

namespace distortos
{

namespace chip
{

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

void lowLevelInitialization()
{
#ifdef CONFIG_CHIP_STM32F0_FLASH_PREFETCH_ENABLE
	configurePrefetchBuffer(true);
#else	// !def CONFIG_CHIP_STM32F0_FLASH_PREFETCH_ENABLE
	configurePrefetchBuffer(false);
#endif	// !def CONFIG_CHIP_STM32F0_FLASH_PREFETCH_ENABLE
}

}	// namespace chip

}	// namespace distortos

Enable flash prefetch in low-level initialization for STM32F0

Flash prefetch is enabled or disabled depending on whether
CONFIG_CHIP_STM32F0_FLASH_PREFETCH_ENABLE is defined or not.


#include "sn_sweeper_dd.hpp"

namespace mocc { namespace sn {
    void SnSweeper_DD::sweep( int group ) {
        // Store the transport cross section somewhere useful
        for( auto &xsr: *xs_mesh_ ) {
            real_t xstr = xsr.xsmactr()[group];
            for( auto &ireg: xsr.reg() ) {
                xstr_[ireg] = xstr;
            }
        }

        flux_1g_ = flux_[ std::slice(n_reg_*group, n_reg_, 1) ];

        // Perform inner iterations
        for( size_t inner=0; inner<n_inner_; inner++ ) {
            // Set the source (add upscatter and divide by 4PI)
            source_->self_scatter( group, flux_1g_, q_ );
            if( inner == n_inner_-1 && coarse_data_ ) {
                // Wipe out the existing currents
                coarse_data_->current.col( group ) = 0.0;
                this->sweep_1g<sn::Current, CellWorker_DD>( group,
                        cell_worker_ );
std::cout << coarse_data_->current.col( group ) << std::endl << std::endl;
            } else {
                this->sweep_1g<sn::NoCurrent, CellWorker_DD>( group,
                        cell_worker_ );
            }
        }
        flux_[ std::slice(n_reg_*group, n_reg_, 1) ] = flux_1g_;

        return;
    }
} }

#include "sn_sweeper_dd.hpp"

namespace mocc { namespace sn {
    void SnSweeper_DD::sweep( int group ) {
        // Store the transport cross section somewhere useful
        for( auto &xsr: *xs_mesh_ ) {
            real_t xstr = xsr.xsmactr()[group];
            for( auto &ireg: xsr.reg() ) {
                xstr_[ireg] = xstr;
            }
        }

        flux_1g_ = flux_[ std::slice(n_reg_*group, n_reg_, 1) ];

        // Perform inner iterations
        for( size_t inner=0; inner<n_inner_; inner++ ) {
            // Set the source (add upscatter and divide by 4PI)
            source_->self_scatter( group, flux_1g_, q_ );
            if( inner == n_inner_-1 && coarse_data_ ) {
                // Wipe out the existing currents
                coarse_data_->current.col( group ) = 0.0;
                this->sweep_1g<sn::Current, CellWorker_DD>( group,
                        cell_worker_ );
            } else {
                this->sweep_1g<sn::NoCurrent, CellWorker_DD>( group,
                        cell_worker_ );
            }
        }
        flux_[ std::slice(n_reg_*group, n_reg_, 1) ] = flux_1g_;

        return;
    }
} }

Remove print statement for DD currents

Remove print statement for DD currents


// Licensed under the Apache License, Version 2.0.

#include "support.h"

#include <clocale>
#include <cstdio>
#include <cwchar>

#include <sys/ioctl.h>
#include <unistd.h>

void setup() { setlocale(LC_ALL, "en_US.UTF-8"); }

void clear_screen() { fputws(L"\033[2J\033[1;1H", stdout); }

std::pair<size_t, size_t> screen_size() {
  winsize size;
  ioctl(STDOUT_FILENO, TIOCGWINSZ, &size);
  return {size.ws_row, size.ws_col};
}

// Licensed under the Apache License, Version 2.0.

#include "support.h"

#include <clocale>
#include <cstdio>
#include <cwchar>

#include <sys/ioctl.h>
#include <unistd.h>

void setup() { setlocale(LC_ALL, "C.UTF-8"); }

void clear_screen() { fputws(L"\033[2J\033[1;1H", stdout); }

std::pair<size_t, size_t> screen_size() {
  winsize size;
  ioctl(STDOUT_FILENO, TIOCGWINSZ, &size);
  return {size.ws_row, size.ws_col};
}

Use C.UTF-8 instead of en_US.UTF-8

Use C.UTF-8 instead of en_US.UTF-8

Should be more portable.


#include "partition.hpp"

namespace SorterThreadedHelper {

  Partition::Partition(const std::set<double>::iterator pivotsBegin,
                       const std::set<double>::iterator pivotsEnd,
                       const std::vector<double>::iterator chunkBegin,
                       const std::vector<double>::iterator chunkEnd) :
    chunkBegin_(chunkBegin), chunkEnd_(chunkEnd) {

    for (std::set<double>::iterator it = pivotsBegin; it != pivotsEnd; ++it) {
      partition_.insert(new PartitionWall(*it, false));
    }
    partition_.insert(new PartitionWall(*pivotsBegin, true));
  }
  Partition::~Partition() {
    for (std::set<PartitionWall*>::iterator it = partition_.begin(); it != partition_.end(); ++it) {
      delete *it;
    }
  }

}

Put the iterator construction inside the for loop


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

#ifdef _WIN32
#include "notificationstate-query.h"
#endif

using namespace v8;

void Method(const v8::FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
  int returnValue = -1;

  #ifdef _WIN32
    returnValue = queryUserNotificationState();
  #endif

  args.GetReturnValue().Set(Int32::New(isolate, returnValue));
}

void Init(Handle<Object> exports) {
  Isolate* isolate = Isolate::GetCurrent();
  exports->Set(String::NewFromUtf8(isolate, "getNotificationState"),
      FunctionTemplate::New(isolate, Method)->GetFunction());
}

NODE_MODULE(quiethours, Init)

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

#ifdef _WIN32
#include "notificationstate-query.h"
#endif

using namespace v8;

void Method(const v8::FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
  int returnValue = -1;

  #ifdef _WIN32
    returnValue = queryUserNotificationState();
  #endif

  args.GetReturnValue().Set(Int32::New(isolate, returnValue));
}

void Init(Local<Object> exports) {
  Isolate* isolate = Isolate::GetCurrent();
  exports->Set(String::NewFromUtf8(isolate, "getNotificationState"),
      FunctionTemplate::New(isolate, Method)->GetFunction());
}

NODE_MODULE(quiethours, Init)

Handle -> Local for node 12 compat

fix: Handle -> Local for node 12 compat

See https://electronjs.org/blog/nodejs-native-addons-and-electron-5 for details.


// NoteTrainer (c) 2016 Andrey Fidrya. MIT license. See LICENSE for more information.

#include "Note.h"

QString noteName(Note note)
{
    switch (note) {
    case Note::C:   return "do";
    case Note::Cis: return "di";
    case Note::D:   return "re";
    case Note::Ees: return "me";
    case Note::E:   return "mi";
    case Note::F:   return "fa";
    case Note::Fis: return "fi";
    case Note::G:   return "so";
    case Note::Aes: return "lu";
    case Note::A:   return "la";
    case Note::Bes: return "se";
    case Note::B:   return "si";
    default: break;
    }
    return "?";
}

bool isFilled(Note note)
{
    switch (note) {
    case Note::C:
    case Note::D:
    case Note::E:
    case Note::Fis:
    case Note::Aes:
    case Note::Bes:
        return true;
    default:
        break;
    }
    return false;
}

Note noteFromKey(int key)
{
    int c4key = 60;
    int deltaKey = key - c4key;
    int note = 0;
    if (deltaKey >= 0) {
        note = deltaKey % 12;
    } else {
        note = 12 + deltaKey % 12;
    }
    //int octave = 4 + deltaKey / 12;

    return (Note)note;
}

// NoteTrainer (c) 2016 Andrey Fidrya. MIT license. See LICENSE for more information.

#include "Note.h"
#include "Utils/Utils.h"

QString noteName(Note note)
{
    switch (note) {
    case Note::C:   return "do";
    case Note::Cis: return "di";
    case Note::D:   return "re";
    case Note::Ees: return "me";
    case Note::E:   return "mi";
    case Note::F:   return "fa";
    case Note::Fis: return "fi";
    case Note::G:   return "so";
    case Note::Aes: return "lu";
    case Note::A:   return "la";
    case Note::Bes: return "se";
    case Note::B:   return "si";
    default: break;
    }
    return "?";
}

bool isFilled(Note note)
{
    switch (note) {
    case Note::C:
    case Note::D:
    case Note::E:
    case Note::Fis:
    case Note::Aes:
    case Note::Bes:
        return true;
    default:
        break;
    }
    return false;
}

Note noteFromKey(int key)
{
    int c4key = 60;
    int deltaKey = key - c4key;
    int note = 0;
    if (deltaKey >= 0) {
        note = deltaKey % 12;
    } else {
        note = 12 + deltaKey % 12;
        note %= 12;
    }
    //int octave = 4 + deltaKey / 12;

    return (Note)note;
}

Fix incorrect display of note C in octaves 1-3


// This is the starting point
//
#include <iostream>
#include <fstream>
#include <sstream>

int main() {
    std::string firstInputString;
    std::string secondInputString;

    std::cout << "Enter the first string" << std::endl;
    std::cin >> firstInputString;
    std::cout << "Enter the second string" << std::endl;
    std::cin >> secondInputString;

    if (firstInputString == secondInputString) {
        std::cout << "Match!" << std::endl;
    }

    std::string fileName;
    std::cout << "Enter a filename in which to look for the string" << std::endl;
    std::cin >> fileName;

    std::ifstream fileInputStream(fileName);
    std::string line;
    if (fileInputStream.is_open()) {
        std::cout << "Successfully opened " << fileName << std::endl;
        while(true) {
            if (fileInputStream.fail()) {
                std::cout << "The file input stream went into an error state" << std::endl;
                break;
            }
            getline(fileInputStream, line);
            std::cout << line << std::endl;
            if (firstInputString == line) {
                std::cout << "Match!" << std::endl;
            }
        }
    } else {
        std::cout << "Could not open file for reading" << std::endl;
    }

    return 0;
}

// This is the starting point
//
#include <iostream>
#include <fstream>
#include <sstream>

int main() {
    std::string first_input;
    std::string second_input;

    std::cout << "Enter the first string" << std::endl;
    std::cin >> first_input;
    std::cout << "Enter the second string" << std::endl;
    std::cin >> second_input;

    if (first_input == second_input) {
        std::cout << "Match!" << std::endl;
    }

    std::string fileName;
    std::cout << "Enter a filename in which to look for the string" << std::endl;
    std::cin >> fileName;

    std::ifstream file_input_stream(fileName);
    std::string line;
    if (file_input_stream.is_open()) {
        std::cout << "Successfully opened " << fileName << std::endl;
        while(true) {
            if (file_input_stream.fail()) {
                std::cout << "The file input stream went into an error state" << std::endl;
                break;
            }
            getline(file_input_stream, line);
            std::cout << line << std::endl;
            if (first_input == line) {
                std::cout << "Match!" << std::endl;
            }
        }
    } else {
        std::cout << "Could not open file for reading" << std::endl;
    }

    return 0;
}

Update identifiers to reflect consistent casing


#include <string>
#include <benchmark/benchmark.h>
#include "farmhash.h"

static void BM_Farmhash(benchmark::State& state) {
  auto payload = std::string(state.range(0), '.');
  while (state.KeepRunning())
    util::Hash64(payload);
  state.SetBytesProcessed(int64_t(state.iterations()) * int64_t(state.range(0)));
}

// Register the function as a benchmark
BENCHMARK(BM_Farmhash)->Arg(4)->Arg(11)->Arg(25)->Arg(100)->Arg(1000)->Arg(10000);

BENCHMARK_MAIN();

#include <string>
#include <benchmark/benchmark.h>
#include "farmhash.h"

static void BM_Farmhash(benchmark::State& state) {
  auto payload = std::string(state.range(0), '.');
  for (auto _ : state)
    util::Hash64(payload);
  state.SetBytesProcessed(int64_t(state.iterations()) * int64_t(state.range(0)));
}

// Register the function as a benchmark
BENCHMARK(BM_Farmhash)->Arg(4)->Arg(11)->Arg(25)->Arg(100)->Arg(1000)->Arg(10000);

BENCHMARK_MAIN();

Use recommended c++11 benchmark loop

Use recommended c++11 benchmark loop


#include "htmlsnap.h"
#include <QPainter>
#include <QDebug>
#include <QWebFrame>
#include <QTimer>
#include <iostream>
#include <QBuffer>

HtmlSnap::HtmlSnap()
{
    connect(&page, SIGNAL(loadFinished(bool)), this, SLOT(render()));
}

void HtmlSnap::loadHtml(char* html)
{
    page.mainFrame()->setHtml(QString(html), QUrl());
}

void HtmlSnap::render()
{
    page.setViewportSize(page.mainFrame()->contentsSize());
    QImage image(page.viewportSize(), QImage::Format_ARGB32);
    QPainter painter(&image);

    page.mainFrame()->render(&painter);
    painter.end();

    QByteArray data;
    QBuffer buffer(&data);
    buffer.open(QBuffer::WriteOnly);

    if(!image.save(&buffer, "PNG"))
    {
        std::cerr << "could not save data to buffer";
        return;
    }

    std::cout << data.toBase64().data();

    QTimer::singleShot(0, this, SIGNAL(finished()));
}

#include "htmlsnap.h"
#include <QPainter>
#include <QDebug>
#include <QWebFrame>
#include <QTimer>
#include <iostream>
#include <QBuffer>

HtmlSnap::HtmlSnap()
{
    connect(&page, SIGNAL(loadFinished(bool)), this, SLOT(render()));
}

void HtmlSnap::loadHtml(char* html)
{
    page.mainFrame()->setHtml(QString(html), QUrl());
}

void HtmlSnap::render()
{
    page.setViewportSize(page.mainFrame()->contentsSize());
    QImage image(page.viewportSize(), QImage::Format_ARGB32);
    QPainter painter(&image);

    page.mainFrame()->render(&painter);
    painter.end();

    QByteArray data;
    QBuffer buffer(&data);
    buffer.open(QBuffer::WriteOnly);

    if(!image.save(&buffer, "PNG"))
        std::cerr << "could not save data to buffer";
    else
        std::cout << data.toBase64().data();

    QTimer::singleShot(0, this, SIGNAL(finished()));
}

Make sure the app closes on error

Make sure the app closes on error


#include "executor.h"
#include <chrono>

const std::time_t Executor::waitOnNullTask;
const std::time_t Executor::waitOnEndTask;

Executor::Executor(int id) : Thread(id), cLog("Executor #" + std::to_string(id)) {
}

Executor::~Executor() {
}

void Executor::SetTasksPool(TasksPool& p) {
        tasksPool = &p;
}

void Executor::Run() {
        Thread::Run();
        D_LOG("Run");
        while (!interrupted){
                auto task = tasksPool->GetTask();
                if (task){
			// cppcheck-suppress constStatement
			log(logxx::notice) << "Starting task #" << task->id << logxx::endl;
                        bool res = RunTask(task);
                        auto &s = log(logxx::notice) << "Task #" << task->id << " ";
                        if (res)
                                s << "successfully done";
                        else
                                s << "failed";
                        s << logxx::endl;
                        std::this_thread::sleep_for(std::chrono::seconds(waitOnEndTask));
                } else
                        std::this_thread::sleep_for(std::chrono::seconds(waitOnNullTask));
        }
}

#include "executor.h"
#include <chrono>

const std::time_t Executor::waitOnNullTask;
const std::time_t Executor::waitOnEndTask;

Executor::Executor(int id) : Thread(id), cLog("Executor #" + std::to_string(id)) {
}

Executor::~Executor() {
}

void Executor::SetTasksPool(TasksPool& p) {
        tasksPool = &p;
}

void Executor::Run() {
        Thread::Run();
        D_LOG("Run");
        if (tasksPool){
                while (!interrupted){
                        auto task = tasksPool->GetTask();
                        if (task){
                                // cppcheck-suppress constStatement
                                log(logxx::notice) << "Starting task #" << task->id << logxx::endl;
                                bool res = RunTask(task);
                                auto &s = log(logxx::notice) << "Task #" << task->id << " ";
                                if (res)
                                        s << "successfully done";
                                else
                                        s << "failed";
                                s << logxx::endl;
                                std::this_thread::sleep_for(std::chrono::seconds(waitOnEndTask));
                        } else
                                std::this_thread::sleep_for(std::chrono::seconds(waitOnNullTask));
                }
        } else
                log(logxx::error) << "No tasks pool provided" << logxx::endl;
}

Check if tasks pool is set

Check if tasks pool is set


#include "Data.hpp"

#include <stdexcept>
#include <string>

namespace Tools {
  Data::BitsType getBitsFromString(const std::string& buf) {

    Data::BitsType bits(buf.size());
    for (size_t i = 0; i < buf.size(); ++i) {
      if (buf[i] == '0')
	bits[i] = 0;
      else if (buf[i] == '1')
	bits[i] = 1;
      else
	throw std::logic_error("Wrong data");
    }

    return bits;
  }
}

Data Data::parseUniqueDataFromStream(std::istream& stream) {

  std::string buf;
  Data data;

  // I. get first line
  if (not (stream >> buf))
    throw std::logic_error("Error reading stream");

  data.sizeOfDimension = buf.size();
  data.numOfTransactions = 0;

  // increment occurrence of transaction`s elements
  data.data[Tools::getBitsFromString(buf)]++;

  // II. process rest of the file content:
  while (stream >> buf) {
    if (data.sizeOfDimension != buf.size())
      throw std::logic_error("Data inconsistent");

    data.data[Tools::getBitsFromString(buf)]++;
    data.numOfTransactions++;
  }

  return data;
}

#include "Data.hpp"

#include <stdexcept>
#include <string>

namespace Tools {
  Data::BitsType getBitsFromString(const std::string& buf) {

    Data::BitsType bits(buf.size());
    for (size_t i = 0; i < buf.size(); ++i) {
      if (buf[i] == '0')
	bits[i] = 0;
      else if (buf[i] == '1')
	bits[i] = 1;
      else
	throw std::logic_error("Wrong data");
    }

    return bits;
  }
}

Data Data::parseUniqueDataFromStream(std::istream& stream) {

  std::string buf;
  Data data;

  // I. get first line
  if (not (stream >> buf))
    throw std::logic_error("Error reading stream");

  data.sizeOfDimension = buf.size();
  data.numOfTransactions = 0;

  // increment occurrence of transaction`s elements
  data.data[Tools::getBitsFromString(buf)]++;
  data.numOfTransactions++;

  // II. process rest of the file content:
  while (stream >> buf) {
    if (data.sizeOfDimension != buf.size())
      throw std::logic_error("Data inconsistent");

    data.data[Tools::getBitsFromString(buf)]++;
    data.numOfTransactions++;
  }

  return data;
}

Correct transaction count when reading a first line


// 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/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

#if defined(TOOLKIT_VIEWS)
// Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms.
// See http://crbug.com/39916 for details.
#define MAYBE_Infobars Infobars
#else
#define MAYBE_Infobars DISABLED_Infobars
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
  // TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

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

// 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/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

#if defined(TOOLKIT_VIEWS)
#if defined (OS_WIN)
#define MAYBE_Infobars Infobars
#else
// Flaky on ChromeOS, see http://crbug.com/40141.
#define MAYBE_Infobars FLAKY_Infobars
#endif

#else
// Need to port ExtensionInfoBarDelegate::CreateInfoBar() to other platforms.
// See http://crbug.com/39916 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
  // TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

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

Mark a test as flaky on ChromeOS.

Mark a test as flaky on ChromeOS.

BUG=40141
TEST=None

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

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


// Copyright 2015-2017 Directive Games Limited - All Rights Reserved

#include "DriftPrivatePCH.h"

#include "AndroidSecureStorage.h"
#include "FileHelper.h"

#if PLATFORM_ANDROID

AndroidSecureStorage::AndroidSecureStorage(const FString& productName, const FString& serviceName)
: productName_{ productName }
, serviceName_{ serviceName }
{
}

bool AndroidSecureStorage::SaveValue(const FString& key, const FString& value, bool overwrite)
{
    auto fullPath = key + TEXT(".dat");
    uint32 flags = overwrite ? 0 : FILEWRITE_NoReplaceExisting;
    return FFileHelper::SaveStringToFile(value, *fullPath, EEncodingOptions::AutoDetect, &IFileManager::Get(), flags);
}

bool AndroidSecureStorage::GetValue(const FString& key, FString& value)
{
    auto fullPath = key + TEXT(".dat");
    FString fileContent;
    if (FFileHelper::LoadFileToString(fileContent, *fullPath))
    {
        value = fileContent;
        return true;
    }
    return false;
}

#endif // PLATFORM_ANDROID

// Copyright 2015-2017 Directive Games Limited - All Rights Reserved

#include "DriftPrivatePCH.h"

#include "AndroidSecureStorage.h"
#include "FileHelper.h"

#if PLATFORM_ANDROID

AndroidSecureStorage::AndroidSecureStorage(const FString& productName, const FString& serviceName)
: productName_{ productName }
, serviceName_{ serviceName }
{
}

bool AndroidSecureStorage::SaveValue(const FString& key, const FString& value, bool overwrite)
{
    auto fullPath = key + TEXT(".dat");
    uint32 flags = overwrite ? 0 : FILEWRITE_NoReplaceExisting;
    return FFileHelper::SaveStringToFile(value, *fullPath, FFileHelper::EEncodingOptions::AutoDetect, &IFileManager::Get(), flags);
}

bool AndroidSecureStorage::GetValue(const FString& key, FString& value)
{
    auto fullPath = key + TEXT(".dat");
    FString fileContent;
    if (FFileHelper::LoadFileToString(fileContent, *fullPath))
    {
        value = fileContent;
        return true;
    }
    return false;
}

#endif // PLATFORM_ANDROID

Fix build error on Android

Fix build error on Android


#include <cassert>
#include <cmath>
#include <limits>
#include <serializer.h>

void test(const double in) {
  Serializer s;
  writer<decltype(+in)>::write(s, in);
  const auto buf = s.data();
  Deserializer d(s.buffer, s.buffer.size() - buf.second);
  const auto out = reader<decltype(+in)>::read(d);
  assert(in == out || (std::isnan(in) && std::isnan(out)));
}

int main() {
  test(std::numeric_limits<double>::infinity());
  test(-std::numeric_limits<double>::infinity());
  test(std::numeric_limits<double>::quiet_NaN());
  test(1.0);
  test(-1.0);
  test(2.0);
  test(-2.0);
  test(M_PI);
  test(-M_PI);
  test(std::numeric_limits<double>::epsilon());
  test(std::numeric_limits<double>::min());
  test(std::numeric_limits<double>::max());
  test(std::numeric_limits<double>::denorm_min());
}

#include <cassert>
#include <cmath>
#include <limits>
#include <serializer.h>

void test(const double in) {
  Serializer s;
  writer<decltype(+in)>::write(s, in);
  const auto buf = s.data();
  Deserializer d(s.buffer, s.buffer.size() - buf.second);
  const auto out = reader<decltype(+in)>::read(d);
  assert(in == out || (std::isnan(in) && std::isnan(out)));
}

int main() {
  test(std::numeric_limits<double>::infinity());
  test(-std::numeric_limits<double>::infinity());
  test(std::numeric_limits<double>::quiet_NaN());
  test(0.0);
  test(-0.0);
  test(1.0);
  test(-1.0);
  test(2.0);
  test(-2.0);
  test(M_PI);
  test(-M_PI);
  test(std::numeric_limits<double>::epsilon());
  test(std::numeric_limits<double>::min());
  test(std::numeric_limits<double>::max());
  test(std::numeric_limits<double>::denorm_min());
}

Test serialization of zero too

Test serialization of zero too


#include "queryconfig.h"

#include <thread>

annis::QueryConfig::QueryConfig()
  : optimize(true), forceFallback(false), avoidNestedBySwitch(true),
    numOfParallelTasks(std::thread::hardware_concurrency())

{

}

#include "queryconfig.h"

#include <thread>

annis::QueryConfig::QueryConfig()
  : optimize(true), forceFallback(false), avoidNestedBySwitch(true),
    numOfParallelTasks(std::thread::hardware_concurrency()-1)

{

}

Change default config to use one thread less that CPUS available for the thread pool. Since there is a thread which calles next() it makes sense to not use all CPUs for the thread pool.


#include <QApplication>
#include <QDeclarativeView>
#include <QUrl>
#include <MDeclarativeCache>

Q_DECL_EXPORT int main(int argc, char** argv)
{
    QApplication* app = MDeclarativeCache::qApplication(argc, argv);

    QDeclarativeView viewer;
    viewer.setSource(QUrl("qrc:/qml/main.qml"));
    viewer.showFullScreen();

    return app->exec();
}

#include <QApplication>
#include <QDeclarativeView>
#include <QUrl>
#include <qplatformdefs.h>

#if defined(MEEGO_EDITION_HARMATTAN)
    #include <MDeclarativeCache>
    #define NEW_QAPPLICATION(x, y) MDeclarativeCache::qApplication((x), (y))
    Q_DECL_EXPORT
#else
    #define NEW_QAPPLICATION(x, y) new QApplication((x), (y))
#endif

int main(int argc, char** argv)
{
    QApplication* app = NEW_QAPPLICATION(argc, argv);

    QDeclarativeView viewer;
    viewer.setSource(QUrl("qrc:/qml/main.qml"));
    viewer.showFullScreen();

    return app->exec();
}

Use QML booster only when compiling to Harmattan target.


#include "gtest/gtest.h"

//#include <nr.h>
//#include <nrutil.h>
#include "packages/transformation/src/newt2.cc"
#include <irtkTransformation.h>

const double EPSILON = 0.001;

TEST(Packages_Transformation_newt2, irtkMultiLevelFreeFormTransformation_Inverse)
{
   irtkCifstream iStream;
   iStream.Open("/vol/medic02/users/sp2010/PhD/Tumor/dofs/gradientnreg2-NGP-HG01.dof.gz");
   irtkMultiLevelFreeFormTransformation transformation;
   transformation.Read(iStream);

   double x = 10, y = 10, z = 10;
   transformation.Inverse(x, y, z);

   ASSERT_NEAR(1.16573, x, EPSILON);
   ASSERT_NEAR(23.9054, y, EPSILON);
   ASSERT_NEAR(-17.255, z, EPSILON);
}

#include "gtest/gtest.h"

#include <irtkTransformation.h>

const double EPSILON = 0.001;

TEST(Packages_Transformation_newt2, irtkMultiLevelFreeFormTransformation_Inverse)
{
   irtkCifstream iStream;
   iStream.Open("/vol/medic02/users/sp2010/PhD/Tumor/dofs/gradientnreg2-NGP-HG01.dof.gz");
   irtkMultiLevelFreeFormTransformation transformation;
   transformation.Read(iStream);

   double x = 10, y = 10, z = 10;
   transformation.Inverse(x, y, z);

   ASSERT_NEAR(1.16573, x, EPSILON);
   ASSERT_NEAR(23.9054, y, EPSILON);
   ASSERT_NEAR(-17.255, z, EPSILON);
}

Remove redundant inclusions from newt_test.cc


#include "rubybasic/BindApplication.hpp"

#include "mruby.h"
#include "mrubybind.h"
#include "ofAppRunner.h"

namespace {
    static float get_frame_rate() { return ofGetFrameRate(); }
    static void set_window_pos(int x, int y) { ofSetWindowPosition(x, y); }
    static void set_window_size(int width, int height) { ofSetWindowShape(width, height); }
    static int window_pos_x() { return ofGetWindowPositionX(); }
    static int window_pos_y() { return ofGetWindowPositionY(); }
    static int window_width() { return ofGetWidth(); }
    static int window_height() { return ofGetHeight(); }
}

//--------------------------------------------------------------------------------
void BindApplication::Bind(mrb_state* mrb)
{
    mrubybind::MrubyBind b(mrb);

    b.bind("get_frame_rate", get_frame_rate);
    b.bind("set_window_pos", set_window_pos);
    b.bind("set_window_size", set_window_size);
    b.bind("window_pos_x", window_pos_x);
    b.bind("window_pos_y", window_pos_y);
    b.bind("window_width", window_width);
    b.bind("window_height", window_height);
}

//EOF

#include "rubybasic/BindApplication.hpp"

#include "mruby.h"
#include "mrubybind.h"
#include "ofAppRunner.h"

namespace {
    static float get_frame_rate() { return ofGetFrameRate(); }
    static void set_window_pos(int x, int y) { ofSetWindowPosition(x, y); }
    static void set_window_size(int width, int height) { ofSetWindowShape(width, height); }
    static int window_pos_x() { return ofGetWindowPositionX(); }
    static int window_pos_y() { return ofGetWindowPositionY(); }
    // static int window_width() { return ofGetWidth(); }
    // static int window_height() { return ofGetHeight(); }
    static int window_width() { return ofGetWindowWidth(); }
    static int window_height() { return ofGetWindowHeight(); }
    static int screen_width() { return ofGetScreenWidth(); }
    static int screen_height() { return ofGetScreenHeight(); }
}

//--------------------------------------------------------------------------------
void BindApplication::Bind(mrb_state* mrb)
{
    mrubybind::MrubyBind b(mrb);

    b.bind("get_frame_rate", get_frame_rate);
    b.bind("set_window_pos", set_window_pos);
    b.bind("set_window_size", set_window_size);
    b.bind("window_pos_x", window_pos_x);
    b.bind("window_pos_y", window_pos_y);
    b.bind("window_width", window_width);
    b.bind("window_height", window_height);
    b.bind("screen_width", screen_width);
    b.bind("screen_height", screen_height);
}

//EOF

Add screen_witdh, height. Change window_height, width base function.


MATCH_TEST("x", UNANCHORED, "x");
MATCH_TEST("x", UNANCHORED, "xyz");
MATCH_TEST("x", UNANCHORED, "uvwx");
MATCH_TEST("x", UNANCHORED, "uvwxyz");

MATCH_TEST("x", ANCHOR_START, "x");
MATCH_TEST("x", ANCHOR_START, "xyz");
MATCH_TEST("x", ANCHOR_START, "uvwx");
MATCH_TEST("x", ANCHOR_START, "uvwxyz");

MATCH_TEST("x", ANCHOR_BOTH, "x");
MATCH_TEST("x", ANCHOR_BOTH, "xyz");
MATCH_TEST("x", ANCHOR_BOTH, "uvwx");
MATCH_TEST("x", ANCHOR_BOTH, "uvwxyz");

MATCH_TEST("^x", UNANCHORED, "x");
MATCH_TEST("^x", UNANCHORED, "xyz");
MATCH_TEST("^x", UNANCHORED, "uvwx");
MATCH_TEST("^x", UNANCHORED, "uvwxyz");

MATCH_TEST("x$", UNANCHORED, "x");
MATCH_TEST("x$", UNANCHORED, "xyz");
MATCH_TEST("x$", UNANCHORED, "uvwx");
MATCH_TEST("x$", UNANCHORED, "uvwxyz");

MATCH_TEST("^x$", UNANCHORED, "x");
MATCH_TEST("^x$", UNANCHORED, "xyz");
MATCH_TEST("^x$", UNANCHORED, "uvwx");
MATCH_TEST("^x$", UNANCHORED, "uvwxyz");

Add some explicit anchoring tests.

Add some explicit anchoring tests.

Those are not implemented as empty-width instructions in re2,
but as flags telling it to use an appropriate anchor mode even though
the caller might disagree. Forgetting to check `Prog::anchor_start`
or `Prog::anchor_end` is a good way to fail these tests.


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

#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "gtest/gtest.h"

#include <string>
using namespace llvm;

TEST(DebugTest, Basic) {
  std::string s1, s2;
  raw_string_ostream os1(s1), os2(s2);
  static const char *DT[] = {"A", "B"};

  llvm::DebugFlag = true;
  setCurrentDebugTypes(DT, 2);
  DEBUG_WITH_TYPE("A", os1 << "A");
  DEBUG_WITH_TYPE("B", os1 << "B");
  EXPECT_EQ("AB", os1.str());

  setCurrentDebugType("A");
  DEBUG_WITH_TYPE("A", os2 << "A");
  DEBUG_WITH_TYPE("B", os2 << "B");
  EXPECT_EQ("A", os2.str());
}

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

#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "gtest/gtest.h"

#include <string>
using namespace llvm;

#ifndef NDEBUG
TEST(DebugTest, Basic) {
  std::string s1, s2;
  raw_string_ostream os1(s1), os2(s2);
  static const char *DT[] = {"A", "B"};

  llvm::DebugFlag = true;
  setCurrentDebugTypes(DT, 2);
  DEBUG_WITH_TYPE("A", os1 << "A");
  DEBUG_WITH_TYPE("B", os1 << "B");
  EXPECT_EQ("AB", os1.str());

  setCurrentDebugType("A");
  DEBUG_WITH_TYPE("A", os2 << "A");
  DEBUG_WITH_TYPE("B", os2 << "B");
  EXPECT_EQ("A", os2.str());
}
#endif

Fix unit test in NDEBUG build

Fix unit test in NDEBUG build

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


//===--------------------- LLDBAssert.cpp ------------------------*- C++-*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "lldb/Utility/LLDBAssert.h"

#include "llvm/Support/Format.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;
using namespace lldb_private;

void lldb_private::lldb_assert(bool expression, const char *expr_text,
                               const char *func, const char *file,
                               unsigned int line) {
  if (LLVM_LIKELY(expression))
    return;

  errs() << format("Assertion failed: (%s), function %s, file %s, line %u\n",
                   expr_text, func, file, line);
  errs() << "backtrace leading to the failure:\n";
  llvm::sys::PrintStackTrace(errs());
  errs() << "please file a bug report against lldb reporting this failure "
            "log, and as many details as possible\n";
  abort();
}

//===--------------------- LLDBAssert.cpp ------------------------*- C++-*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "lldb/Utility/LLDBAssert.h"

#include "llvm/Support/Format.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;
using namespace lldb_private;

void lldb_private::lldb_assert(bool expression, const char *expr_text,
                               const char *func, const char *file,
                               unsigned int line) {
  if (LLVM_LIKELY(expression))
    return;

  errs() << format("Assertion failed: (%s), function %s, file %s, line %u\n",
                   expr_text, func, file, line);
  errs() << "backtrace leading to the failure:\n";
  llvm::sys::PrintStackTrace(errs());
  errs() << "please file a bug report against lldb reporting this failure "
            "log, and as many details as possible\n";
}

Revert r341387. (Calling abort() from lldb_assert()).

rdar://problem/49356014


/**
 * @file nmf_test.cpp
 * @author Mohan Rajendran
 *
 * Test file for NMF class.
 */
#include <mlpack/core.hpp>
#include <mlpack/methods/nmf/nmf.hpp>

#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"

BOOST_AUTO_TEST_SUITE(NMFTest);

using namespace std;
using namespace arma;
using namespace mlpack;
using namespace mlpack::nmf;

/**
 * Check the if the product of the calculated factorization is close to the
 * input matrix.
 */
BOOST_AUTO_TEST_CASE(NMFTest)
{
  mat v = randu<mat>(5, 5);
  size_t r = 4;
  mat w, h;

  NMF<> nmf(0);
  nmf.Apply(v, w, h, r);

  mat wh = w * h;

  v.print("v");
  wh.print("wh");

  for (size_t row = 0; row < 5; row++)
    for (size_t col = 0; col < 5; col++)
      BOOST_REQUIRE_CLOSE(v(row, col), wh(row, col), 5.0);
}

BOOST_AUTO_TEST_SUITE_END();

/**
 * @file nmf_test.cpp
 * @author Mohan Rajendran
 *
 * Test file for NMF class.
 */
#include <mlpack/core.hpp>
#include <mlpack/methods/nmf/nmf.hpp>

#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"

BOOST_AUTO_TEST_SUITE(NMFTest);

using namespace std;
using namespace arma;
using namespace mlpack;
using namespace mlpack::nmf;

/**
 * Check the if the product of the calculated factorization is close to the
 * input matrix.
 */
BOOST_AUTO_TEST_CASE(NMFTest)
{
  mat v = randu<mat>(5, 5);
  size_t r = 4;
  mat w, h;

  NMF<> nmf(0);
  nmf.Apply(v, w, h, r);

  mat wh = w * h;

  v.print("v");
  wh.print("wh");

//  for (size_t row = 0; row < 5; row++)
//    for (size_t col = 0; col < 5; col++)
//      BOOST_REQUIRE_CLOSE(v(row, col), wh(row, col), 5.0);
}

BOOST_AUTO_TEST_SUITE_END();

Comment out testing procedure for now because it doesn't work (yet).


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

#include <common/err_common.hpp>
#include <af/device.h>
#include <af/exception.h>

#include <algorithm>
#include <string>

void af_get_last_error(char **str, dim_t *len) {
    std::string &global_error_string = get_global_error_string();
    dim_t slen =
        std::min(MAX_ERR_SIZE, static_cast<int>(global_error_string.size()));

    if (len && slen == 0) {
        *len = 0;
        *str = NULL;
        return;
    }

    af_alloc_host(reinterpret_cast<void **>(str), sizeof(char) * (slen + 1));
    global_error_string.copy(*str, slen);

    (*str)[slen]        = '\0';
    global_error_string = std::string("");

    if (len) { *len = slen; }
}

af_err af_set_enable_stacktrace(int is_enabled) {
    common::is_stacktrace_enabled() = is_enabled;

    return AF_SUCCESS;
}

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

#include <common/err_common.hpp>
#include <af/device.h>
#include <af/exception.h>
#include <af/util.h>

#include <algorithm>
#include <string>

void af_get_last_error(char **str, dim_t *len) {
    std::string &global_error_string = get_global_error_string();
    dim_t slen =
        std::min(MAX_ERR_SIZE, static_cast<int>(global_error_string.size()));

    if (len && slen == 0) {
        *len = 0;
        *str = NULL;
        return;
    }

    af_alloc_host(reinterpret_cast<void **>(str), sizeof(char) * (slen + 1));
    global_error_string.copy(*str, slen);

    (*str)[slen]        = '\0';
    global_error_string = std::string("");

    if (len) { *len = slen; }
}

af_err af_set_enable_stacktrace(int is_enabled) {
    common::is_stacktrace_enabled() = is_enabled;

    return AF_SUCCESS;
}

Fix undefined set_stacktrace symbol by adding missing header in source


#include <iostream>
#include <cstdlib>

#include <Eigen/Dense>

#include "problem.hpp"

using namespace integrator_chains;

int main()
{
    Eigen::Vector2i numdim_output_bounds( 2, 2 );
    Eigen::Vector2i num_integrators_bounds( 2, 2 );

    Eigen::Vector4d Y_box;
    Y_box << -1, 10, -2, 10;

    Eigen::Vector4d U_box;
    U_box << -1, 1, -1, 1;

    Eigen::Vector2d period_bounds( 0.05, 0.1 );

    Eigen::Vector2i number_goals_bounds( 1, 2 );
    Eigen::Vector2i number_obstacles_bounds( 0, 1 );

    srand(time(0));
    Problem *prob = Problem::random( numdim_output_bounds,
                                     num_integrators_bounds,
                                     Y_box, U_box,
                                     number_goals_bounds,
                                     number_obstacles_bounds,
                                     period_bounds );
    std::cout << *prob << std::endl;

    prob->to_formula( std::cerr );
    std::cerr << std::endl;

    delete prob;
    return 0;
}

#include <iostream>
#include <cstdlib>
#include <ctime>

#include <Eigen/Dense>

#include "problem.hpp"

using namespace integrator_chains;

int main()
{
    Eigen::Vector2i numdim_output_bounds( 2, 2 );
    Eigen::Vector2i num_integrators_bounds( 2, 2 );

    Eigen::Vector4d Y_box;
    Y_box << -1, 10, -2, 10;

    Eigen::Vector4d U_box;
    U_box << -1, 1, -1, 1;

    Eigen::Vector2d period_bounds( 0.05, 0.1 );

    Eigen::Vector2i number_goals_bounds( 1, 2 );
    Eigen::Vector2i number_obstacles_bounds( 0, 1 );

    std::srand( std::time( 0 ) );
    Problem *prob = Problem::random( numdim_output_bounds,
                                     num_integrators_bounds,
                                     Y_box, U_box,
                                     number_goals_bounds,
                                     number_obstacles_bounds,
                                     period_bounds );
    std::cout << *prob << std::endl;

    prob->to_formula( std::cerr );
    std::cerr << std::endl;

    delete prob;
    return 0;
}

Resolve C standard library functions in std::


#include "ToJsonWriter.h"

#include <json/json.h>

std::string ToJsonWriter::convertToJson(const Article* a)
{
    Json::Value val;

    Json::Value array(Json::ValueType::arrayValue);

    for(auto ali = a->linkBegin(); ali != a->linkEnd(); ali++) {
        std::string tit = (*ali)->getTitle();
        array.append(Json::Value(tit));
    }

    val[a->getTitle()] = array;

    Json::FastWriter jsw;
    jsw.omitEndingLineFeed();

    return jsw.write(val);
}

std::string ToJsonWriter::convertToJson(const ArticleCollection&)
{
    return "";
}

void ToJsonWriter::output(const Article* article, std::ostream& outstream)
{
    outstream << convertToJson(article);
}

void ToJsonWriter::output(const ArticleCollection& collection, std::ostream& outstream)
{
    outstream << convertToJson(collection);
}

#include "ToJsonWriter.h"

#include <json/json.h>

Json::Value getArticleLinks(const Article* a)
{
    Json::Value array(Json::ValueType::arrayValue);

    for(auto ali = a->linkBegin(); ali != a->linkEnd(); ali++) {
        std::string tit = (*ali)->getTitle();
        array.append(Json::Value(tit));
    }

    return array;
}

std::string ToJsonWriter::convertToJson(const Article* a)
{
    Json::Value val;

    val[a->getTitle()] = getArticleLinks(a);

    Json::FastWriter jsw;
    jsw.omitEndingLineFeed();

    return jsw.write(val);
}

std::string ToJsonWriter::convertToJson(const ArticleCollection& ac)
{
    Json::Value val(Json::ValueType::objectValue);

    for(auto ar : ac) {
        val[ar.first] = getArticleLinks(ar.second);
    }

    Json::FastWriter jsw;
    jsw.omitEndingLineFeed();

    return jsw.write(val);
}

void ToJsonWriter::output(const Article* article, std::ostream& outstream)
{
    outstream << convertToJson(article);
}

void ToJsonWriter::output(const ArticleCollection& collection, std::ostream& outstream)
{
    outstream << convertToJson(collection);
}

Add conversion method for ArticleCollection


// Copyright (C) 2012, All Rights Reserved.
// Author: Cory Maccarrone <darkstar6262@gmail.com>

#include "client/ui/cli/cli_client.h"
#include "gflags/gflags.h"
#include "glog/logging.h"

using backup::CliMain;

int main(int argc, char* argv[]) {
  google::ParseCommandLineFlags(&argc, &argv, true);
  google::InitGoogleLogging(argv[0]);
  google::InstallFailureSignalHandler();

  CHECK_LT(1, argc) << "Must specify a command";

  // Construct the command handler.
  CliMain cli(argc, argv);
  if (!cli.Init()) {
    LOG(FATAL) << "Error initializing backend";
  }

  return cli.RunCommand();
}

// Copyright (C) 2012, All Rights Reserved.
// Author: Cory Maccarrone <darkstar6262@gmail.com>

#include "client/ui/cli/cli_client.h"
#include "gflags/gflags.h"
#include "glog/logging.h"

using backup::CliMain;

int main(int argc, char* argv[]) {
  google::SetUsageMessage(
      "Usage: cli_client <options> <command>\n\n"
      "Commands:\n"
      "    list_backup_sets\n"
      "        List the available backup sets.\n\n"
      "    create_backup_set <backup set name>\n"
      "        Create a backup set with the given name.\n\n"
      "    create_incremental_backup <backup set> <backup name> <size_in_mb>\n"
      "        Create an incremental backup in the given backup set with at most\n"
      "        <size_in_mb> megabytes.");

  google::ParseCommandLineFlags(&argc, &argv, true);
  google::InitGoogleLogging(argv[0]);
  google::InstallFailureSignalHandler();

  CHECK_LT(1, argc) << "Must specify a command";

  // Construct the command handler.
  CliMain cli(argc, argv);
  if (!cli.Init()) {
    LOG(FATAL) << "Error initializing backend";
  }

  return cli.RunCommand();
}

Add simple help to the CLI client.

Add simple help to the CLI client.

This should really be auto-generated by the commands themselves in
CliMain() as a static function.


#include <fstream>
#include <iostream>
#include <utility>
#include <map>
#include <set>
#include <queue>
#include <bitset>

using namespace std;

int main() {
	ifstream fin("highcard.in");
	ofstream fout("highcard.out");

	int num_sing_cards;
	fin >> num_sing_cards;

	bitset<100000> cards;
	for (int i = 0; i < num_sing_cards; i++) {
		int card;
		fin >> card;
		cards[card - 1] = true;
		cout << "? " << card << endl;
	}

	int elsie = 0, score = 0;
	for (int i = 0; i < 2 * num_sing_cards; i++) {
		cout << "C " << i << ' ' << cards[i] << endl;
		if (cards[i]) {
			elsie++;
		} else if (elsie) {
			elsie--;
			score++;
		}
	}

	fout << score << endl;
}

#include <fstream>
#include <bitset>

using namespace std;

int main() {
	ifstream fin("highcard.in");
	ofstream fout("highcard.out");

	int num_sing_cards;
	fin >> num_sing_cards;

	bitset<100000> cards;
	for (int i = 0; i < num_sing_cards; i++) {
		int card;
		fin >> card;
		cards[card - 1] = true;
	}

	int elsie = 0, score = 0;
	for (int i = 0; i < 2 * num_sing_cards; i++) {
		if (cards[i]) {
			elsie++;
		} else if (elsie) {
			elsie--;
			score++;
		}
	}

	fout << score << endl;
}

Remove debug and unused headers

2015-dec-silver/2-highcard/cpp11: Remove debug and unused headers


#include <gtest/gtest.h>

#include "distance.h"
using namespace testing;
using namespace std::literals::distance_literals;

namespace TestDistanceUnits
{
    class DistanceTest : public Test
    {
    protected:
        std::units::si::distance<long int> distance{0};
    };

    TEST_F(DistanceTest, Constructor_WhenInvoked_WillInitialise)
    {
        EXPECT_EQ(0, distance.count());
    }

    class LiteralsTest : public Test
    {
    };

    TEST_F(LiteralsTest, MetresLiteral_WhenUsed_WillReturnMetresType)
    {
        static_assert(std::is_same<std::units::si::metres, decltype(1_m)>::value,
                      "Incompatible types");
        EXPECT_TRUE(true);
    }
}

#include <gtest/gtest.h>

#include "distance.h"
using namespace testing;
using namespace std::literals::distance_literals;

namespace TestDistanceUnits
{
    class DistanceTest : public Test
    {
    protected:
        std::units::si::distance<long int> distance{0};
    };

    TEST_F(DistanceTest, Constructor_WhenInvoked_WillInitialise)
    {
        EXPECT_EQ(0, distance.count());
    }

    class LiteralsTest : public Test
    {
    };

    TEST_F(LiteralsTest, MetresLiteral_WhenUsed_WillReturnMetresType)
    {
        constexpr auto is_same = std::is_same<std::units::si::metres, decltype(1_m)>::value;
        EXPECT_TRUE(is_same) << "Incompatible types";
    }
}

Check type similarity at runtim instead

Check type similarity at runtim instead

Signed-off-by: Dave Brown <3eb4035e47bf510ef54544ee63f7ff38b3c2887e@bigdavedev.com>


#include <iostream>
#include <string>

#include <proxc/config.hpp>

#include <proxc/context.hpp>
#include <proxc/scheduler.hpp>

#include "setup.hpp"

using Context = proxc::Context;

void printer(int x, int y)
{
    SafeCout::print(x, ", ", y);
}

void test_context()
{
     auto main_ctx = Context::running();
     auto scheduler = main_ctx->get_scheduler();
     auto func1_ctx = Context::make_work_context(
         printer,
         42, 1337
     );
     auto func2_ctx = Context::make_work_context(
         [](){
            SafeCout::print("no arguments!");
         }
     );
     scheduler->attach_work_context(func1_ctx);
     scheduler->attach_work_context(func2_ctx);

     scheduler->schedule(func1_ctx);
     func2_ctx->resume();
     std::cout << "done" << std::endl;
}

int main()
{
    test_context();

    return 0;
}

#include <iostream>
#include <string>

#include <proxc/config.hpp>

#include <proxc/context.hpp>
#include <proxc/scheduler.hpp>

#include "setup.hpp"

using Context = proxc::Context;

void printer(int x, int y)
{
    SafeCout::print(x, ", ", y);
}

void test_context()
{
    // TODO
}

int main()
{
    test_context();

    return 0;
}

Remove context test, context is to be reimpleemnted.


// Copyright (c) 2020 Sony Corporation. 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 <nbla/array/cpu_array.hpp>
#include <nbla/array/cpu_dlpack_array.hpp>

namespace nbla {

CpuDlpackArray::CpuDlpackArray(const Size_t size, dtypes dtype,
                               const Context &ctx)
    : DlpackArray(size, dtype, ctx) {}

CpuDlpackArray::~CpuDlpackArray() {}

Context CpuDlpackArray::filter_context(const Context &ctx) {
  return Context({}, "CpuDlpackArray", "");
}

void CpuDlpackArray::zero() {
  std::memset(this->pointer<void>(), 0,
              this->size() * sizeof_dtype(this->dtype_));
}

NBLA_DEFINE_FUNC_COPY_FROM(CpuDlpackArray, cpu_array_copy, cpu);
NBLA_DEFINE_FUNC_FILL(CpuDlpackArray, cpu_fill, cpu);
}

// Copyright (c) 2020 Sony Corporation. 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 <nbla/array/cpu_array.hpp>
#include <nbla/array/cpu_dlpack_array.hpp>

#include <cstring>

namespace nbla {

CpuDlpackArray::CpuDlpackArray(const Size_t size, dtypes dtype,
                               const Context &ctx)
    : DlpackArray(size, dtype, ctx) {}

CpuDlpackArray::~CpuDlpackArray() {}

Context CpuDlpackArray::filter_context(const Context &ctx) {
  return Context({}, "CpuDlpackArray", "");
}

void CpuDlpackArray::zero() {
  std::memset(this->pointer<void>(), 0,
              this->size() * sizeof_dtype(this->dtype_));
}

NBLA_DEFINE_FUNC_COPY_FROM(CpuDlpackArray, cpu_array_copy, cpu);
NBLA_DEFINE_FUNC_FILL(CpuDlpackArray, cpu_fill, cpu);
}

[c++] Fix missing std::memset for DLPack utils


#include "logging.h"

XPLogAggregator xplog_aggregator;
XPLogAggregator xplog_debug_aggregator;

thread_local XPLogger xplog(xplog_aggregator);
thread_local XPLogger xplog_debug(xplog_debug_aggregator);

XPLogAggregator::XPLogAggregator() {
    XPLMCreateFlightLoop_t callback_info{
        .structSize = sizeof(XPLMCreateFlightLoop_t),
        .callbackFunc = &XPLogAggregator::logging_callback,
        .phase = xplm_FlightLoop_Phase_BeforeFlightModel,
        .refcon = this,
    };

    callback_id = XPLMCreateFlightLoop(&callback_info);

    XPLMScheduleFlightLoop(callback_id, -1, 0);
}

XPLogAggregator::~XPLogAggregator() {
    XPLMDestroyFlightLoop(callback_id);

}

float XPLogAggregator::logging_callback(float /* inElapsedSinceLastCall */, float /* inElapsedTimeSinceLastFlightLoop */, int /* inCounter */, void * refcon) {
    XPLogAggregator * xpl = static_cast<XPLogAggregator *>(refcon);

    while(true) {
        std::optional<std::string> opt_message = xpl->message_queue.get();

        if(opt_message) {
            XPLMDebugString(xpl->prefix_.c_str());
            XPLMDebugString(opt_message->c_str());
        } else {
            return -1;
        }
    }
}

#include "logging.h"

XPLogAggregator xplog_aggregator;
XPLogAggregator xplog_debug_aggregator;

thread_local XPLogger xplog(xplog_aggregator);
thread_local XPLogger xplog_debug(xplog_debug_aggregator);

XPLogAggregator::XPLogAggregator() {
    XPLMCreateFlightLoop_t callback_info{
        .structSize = sizeof(XPLMCreateFlightLoop_t),
        .phase = xplm_FlightLoop_Phase_BeforeFlightModel,
        .callbackFunc = &XPLogAggregator::logging_callback,
        .refcon = this,
    };

    callback_id = XPLMCreateFlightLoop(&callback_info);

    XPLMScheduleFlightLoop(callback_id, -1, 0);
}

XPLogAggregator::~XPLogAggregator() {
    XPLMDestroyFlightLoop(callback_id);

}

float XPLogAggregator::logging_callback(float /* inElapsedSinceLastCall */, float /* inElapsedTimeSinceLastFlightLoop */, int /* inCounter */, void * refcon) {
    XPLogAggregator * xpl = static_cast<XPLogAggregator *>(refcon);

    while(true) {
        std::optional<std::string> opt_message = xpl->message_queue.get();

        if(opt_message) {
            XPLMDebugString(xpl->prefix_.c_str());
            XPLMDebugString(opt_message->c_str());
        } else {
            return -1;
        }
    }
}

Reorder struct initializer to try to fix build on non-mac platforms.


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

#include <signal.h>

#include <gmock/gmock.h>
#include <gtest/gtest.h>

namespace asylo {
namespace {

static bool signal_handled = false;

void HandleSignal(int signum) {
  if (signum == SIGUSR1) {
    signal_handled = true;
  }
}

// Registers a signal handler for SIGUSR1, raises it, and checks whether it's
// handled.
TEST(SignalTest, RaiseSignal) {
  struct sigaction act;
  act.sa_handler = &HandleSignal;
  struct sigaction oldact;
  sigaction(SIGUSR1, &act, &oldact);
  raise(SIGUSR1);
  EXPECT_TRUE(signal_handled);
}

}  // namespace
}  // namespace asylo

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

#include <signal.h>

#include <gmock/gmock.h>
#include <gtest/gtest.h>

namespace asylo {
namespace {

static bool signal_handled = false;

void HandleSignal(int signum) {
  if (signum == SIGUSR1) {
    signal_handled = true;
  }
}

// Registers a signal handler for SIGUSR1, raises it, and checks whether it's
// handled.
TEST(SignalTest, RaiseSignal) {
  struct sigaction act;
  memset(&act, 0, sizeof(struct sigaction));
  act.sa_handler = &HandleSignal;
  struct sigaction oldact;
  sigaction(SIGUSR1, &act, &oldact);
  raise(SIGUSR1);
  EXPECT_TRUE(signal_handled);
}

}  // namespace
}  // namespace asylo

Initialize whole sigaction before use

Initialize whole sigaction before use

PiperOrigin-RevId: 225025999


#include "main.h"

#include <boost/program_options.hpp>
#include <iostream>

#include "application.h"

namespace po = boost::program_options;

using namespace simplicity;
using namespace std;

void print_version(void);

int main(int argc, char **argv)
{
	po::options_description program_desc("Simplicity window manager");

	program_desc.add_options()
		("help",    "Display usage")
		("version", "Print simplicity version")
	;

	po::variables_map args;
	po::store(po::parse_command_line(argc, argv, program_desc), args);
	po::notify(args);

	if (args.count("help"))
	{
		cerr << program_desc << endl;
		return 1;
	}

	if (args.count("version"))
	{
		print_version();
		return 1;
	}

	SimplicityApplication::get_instance().run();

	return 0;
}

void print_version(void)
{
	cout << PACKAGE_STRING << endl;
	cout << "Copyright (C) 2014 James Durand\n"
			"This is free software; see the source for copying conditions.\n"
			"There is NO warranty." << endl;
}

#include "main.h"

#include <boost/program_options.hpp>
#include <iostream>

#include "application.h"

namespace po = boost::program_options;

using namespace simplicity;
using namespace std;

void print_version(void);

int main(int argc, char **argv)
{
	po::options_description program_desc("Simplicity window manager");

	program_desc.add_options()
		("help",    "Display usage")
		("version", "Print simplicity version")
	;

	po::variables_map args;
	po::store(po::parse_command_line(argc, argv, program_desc), args);
	po::notify(args);

	if (args.count("help"))
	{
		cerr << program_desc << endl;
		return 1;
	}

	if (args.count("version"))
	{
		print_version();
		return 1;
	}

	SimplicityApplication::get_instance().run();

	return 0;
}

void print_version(void)
{
	cerr << PACKAGE_STRING << endl;
	cerr << "Copyright (C) 2014 James Durand\n"
			"This is free software; see the source for copying conditions.\n"
			"There is NO warranty." << endl;
}

Use stderr to be consistent

Use stderr to be consistent


/*
 * *****************************************************************************
 *   Copyright 2014 Spectra Logic Corporation. 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. A copy of the License
 *   is located at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   or in the "license" file accompanying this file.
 *   This file 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 <QTest>

#include "test.h"

int
main(int /*argc*/, char** /*argv[]*/)
{
	int failed = 0;

	for (int i = 0; i < Test::s_tests.size(); i++) {
		int result = QTest::qExec(Test::s_tests.at(i));
		if (result != 0) {
			failed++;
		}
	}

	return failed;
}

/*
 * *****************************************************************************
 *   Copyright 2014 Spectra Logic Corporation. 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. A copy of the License
 *   is located at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   or in the "license" file accompanying this file.
 *   This file 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 <qDebug>
#include <QTest>

#include "test.h"

int
main(int /*argc*/, char** /*argv[]*/)
{
	int failed = 0;

	for (int i = 0; i < Test::s_tests.size(); i++) {
		int result = QTest::qExec(Test::s_tests.at(i));
		if (result != 0) {
			failed++;
		}
	}

	qDebug();
	if (failed == 0) {
		qDebug() << "All Tests Passed";
	} else {
		qDebug() << failed << "Test Suite(s) Contained Failures";
	}

	return failed;
}

Print a message at the end of the test run so it's easier to determine if any of the tests failed.


#include "RegExp.h"

namespace tinygrep {

namespace resyntax {

RegExp::RegExp() : RegExp::RegExp(RegExpEnum::kEmpty) {}

RegExp::RegExp(RegExpEnum type) : type_(type), r1_(nullptr), r2_(nullptr), literal_('\0') {}

RegExp::RegExp(RegExpEnum type, literalType literal) : RegExp::RegExp(type) {
  literal_ = literal;
}

RegExp::RegExp(RegExpEnum type, const RegExp& r1) : RegExp::RegExp(type) {
  r1_ = SPtr(new RegExp(r1));
}

RegExp::RegExp(RegExpEnum type, const RegExp& r1, const RegExp& r2) : RegExp::RegExp(type, r1) {
  r2_ = SPtr(new RegExp(r2));
}

RegExpEnum RegExp::getType() const {
  return type_;
}

const RegExp& RegExp::getR1() const {
  return *r1_;
}

const RegExp& RegExp::getR2() const {
  return *r2_;
}

RegExp::literalType RegExp::getLiteral() const {
  return literal_;
}

}  // namespace resyntax

}  // namespace tinygrep

#include "RegExp.h"

namespace tinygrep {

namespace resyntax {

RegExp::RegExp() : RegExp::RegExp(RegExpEnum::kEmpty) {}

RegExp::RegExp(RegExpEnum type) : type_(type), r1_(nullptr), r2_(nullptr), literal_('\0') {}

RegExp::RegExp(RegExpEnum type, literalType literal) : RegExp::RegExp(type) {
  literal_ = literal;
}

RegExp::RegExp(RegExpEnum type, const RegExp& r1) : RegExp::RegExp(type) {
  r1_ = std::make_shared<RegExp>(r1);
}

RegExp::RegExp(RegExpEnum type, const RegExp& r1, const RegExp& r2) : RegExp::RegExp(type, r1) {
  r2_ = std::make_shared<RegExp>(r2);
}

RegExpEnum RegExp::getType() const {
  return type_;
}

const RegExp& RegExp::getR1() const {
  return *r1_;
}

const RegExp& RegExp::getR2() const {
  return *r2_;
}

RegExp::literalType RegExp::getLiteral() const {
  return literal_;
}

}  // namespace resyntax

}  // namespace tinygrep

Use make_shared instead of raw smart pointer constructor.


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

#include "ToolBar.h"
#include <Gui/Widgets/MainWindow.h>

QUML_BEGIN_NAMESPACE_GW

#ifdef Q_OS_MAC_disabled
ToolBar::ToolBar(QObject* parent) : QObject(parent),
        mToolBar(new QMacNativeToolBar()) {
}
#else
ToolBar::ToolBar(QObject* parent) : QObject(parent),
        mToolBar(new QToolBar()) {
}
#endif

void ToolBar::showInWindow(MainWindow* w) {
    mWindow = w;
#ifdef Q_OS_MAC_disabled
    mToolBar->showInWindowForWidget(w);
    mToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
#else
    w->addToolBar(mToolBar.get());
    mToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
#endif
}

QuGW::MainWindow* ToolBar::window() {
    return mWindow;
}

// #ifndef Q_OS_MAC
void ToolBar::addWidget(ToolBarItem* item) {
    mToolBar->addWidget(item);
}
// #endif

void ToolBar::addSeparator() {
    mToolBar->addSeparator();
}

#ifdef Q_OS_MAC_disabled
void ToolBar::addFlexibleSpace() {
    mToolBar->addStandardItem(QMacToolButton::FlexibleSpace);
}
#endif

QUML_END_NAMESPACE_GW

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

#include "ToolBar.h"
#include <Gui/Widgets/MainWindow.h>

QUML_BEGIN_NAMESPACE_GW

#ifdef Q_OS_MAC_disabled
ToolBar::ToolBar(QObject* parent) : QObject(parent),
        mToolBar(new QMacNativeToolBar()) {
}
#else
ToolBar::ToolBar(QObject* parent) : QObject(parent),
        mToolBar(new QToolBar()) {
    mToolBar->setFloatable(false);
    mToolBar->setMovable(false);
}
#endif

void ToolBar::showInWindow(MainWindow* w) {
    mWindow = w;
#ifdef Q_OS_MAC_disabled
    mToolBar->showInWindowForWidget(w);
    mToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
#else
    w->addToolBar(mToolBar.get());
    mToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
#endif
}

QuGW::MainWindow* ToolBar::window() {
    return mWindow;
}

// #ifndef Q_OS_MAC
void ToolBar::addWidget(ToolBarItem* item) {
    mToolBar->addWidget(item);
}
// #endif

void ToolBar::addSeparator() {
    mToolBar->addSeparator();
}

#ifdef Q_OS_MAC_disabled
void ToolBar::addFlexibleSpace() {
    mToolBar->addStandardItem(QMacToolButton::FlexibleSpace);
}
#endif

QUML_END_NAMESPACE_GW

Set the toolbar to be static in its location. It looks ugly otherwise.


#include "counter_application.hpp"
#include <lib-tmsp/server.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/log/trivial.hpp>

int main(int argc, char const* argv[])
{
	if(argc < 3)
	{
		BOOST_LOG_TRIVIAL(info) << "Provide TMSP listening endpoint on command line. Example: 0.0.0.0 46658";
		return 1;
	}

	try
	{
		boost::asio::io_service io_service;
		tmsp::server_type const server(
			io_service,
			boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(argv[1]), std::atoi(argv[2])),
			std::make_shared<counter::application_type>()
			);

		// In this simple application, all work is scheduled on the main thread using boost asio (just below).
		// Since the application is thus protected from being re-entered, there is no need for a mutex
		// inside the application. However it was left in in as a kind reminder that application
		// state must be synchronized if the thread count ever increased.
		io_service.run();
	}

	catch(...)
	{
		BOOST_LOG_TRIVIAL(error) << boost::current_exception_diagnostic_information();
		return 2;
	}

	return 0;
}

#include "counter_application.hpp"
#include <lib-tmsp/server.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/log/trivial.hpp>

int main(int argc, char const* argv[])
{
	if(argc < 3)
	{
		BOOST_LOG_TRIVIAL(info) << "Provide TMSP listening endpoint on command line. Example: 0.0.0.0 46658";
		return 1;
	}

	try
	{
		boost::asio::io_service io_service;
		tmsp::server_type const server(
			io_service,
			boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(argv[1]), std::atoi(argv[2])),
			std::make_shared<counter::application_type>()
			);

		// In this simple application, all work is scheduled on the main thread using boost asio (just below).
		// Since the application is thus protected from being re-entered, there is no need for a mutex to synchronize access.
		// It was left there as a kind reminder that synchronization must be used if the thread count ever increases.
		io_service.run();
	}

	catch(...)
	{
		BOOST_LOG_TRIVIAL(error) << boost::current_exception_diagnostic_information();
		return 2;
	}

	return 0;
}

Change wording on thread synchronization


/**
 * \file
 * \brief chip::lowLevelInitialization() implementation for STM32L4
 *
 * \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/chip/lowLevelInitialization.hpp"

namespace distortos
{

namespace chip
{

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

void lowLevelInitialization()
{

}

}	// namespace chip

}	// namespace distortos

/**
 * \file
 * \brief chip::lowLevelInitialization() implementation for STM32L4
 *
 * \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/chip/lowLevelInitialization.hpp"

#include "distortos/chip/STM32L4-FLASH.hpp"

#include "distortos/distortosConfiguration.h"

namespace distortos
{

namespace chip
{

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

void lowLevelInitialization()
{
#ifdef CONFIG_CHIP_STM32L4_FLASH_PREFETCH_ENABLE
	configureInstructionPrefetch(true);
#else	// !def CONFIG_CHIP_STM32L4_FLASH_PREFETCH_ENABLE
	configureInstructionPrefetch(false);
#endif	// !def CONFIG_CHIP_STM32L4_FLASH_PREFETCH_ENABLE

#ifdef CONFIG_CHIP_STM32L4_FLASH_DATA_CACHE_ENABLE
	enableDataCache();
#else	// !def CONFIG_CHIP_STM32L4_FLASH_DATA_CACHE_ENABLE
	disableDataCache();
#endif	// !def CONFIG_CHIP_STM32L4_FLASH_DATA_CACHE_ENABLE

#ifdef CONFIG_CHIP_STM32L4_FLASH_INSTRUCTION_CACHE_ENABLE
	enableInstructionCache();
#else	// !def CONFIG_CHIP_STM32L4_FLASH_INSTRUCTION_CACHE_ENABLE
	disableInstructionCache();
#endif	// !def CONFIG_CHIP_STM32L4_FLASH_INSTRUCTION_CACHE_ENABLE
}

}	// namespace chip

}	// namespace distortos

Extend STM32L4's lowLevelInitialization() with flash initialization


#include <windows.h>
#include "system/thread.hh"

using System::Thread;

DWORD WINAPI startThread(LPVOID args);

class Implementation : public Thread::ThreadImplementation
{
public:
    Implementation(Thread::Callable function) : _function(function) { }

    void start()
    {
        _threadHandle = CreateThread(NULL, 0, ::startThread, this, 0, NULL);
    }

    void join()
    {
        WaitForSingleObject(_threadHandle, INFINITE);
    }

    void run()
    {
        _function();
    }

private:
    Thread::Callable _function;
    HANDLE _threadHandle;
};

DWORD WINAPI startThread(LPVOID args)
{
    Implementation *self = (Implementation *)args;
    self->run();
    return NULL;
}

Thread::ThreadImplementation *Thread::createImplementation(Thread::Callable function)
{
    return new Implementation(function);
}

Thread::Thread(Callable function)
{
    _implementation = createImplementation(function);
    _implementation->start();
}

void Thread::join()
{
    _implementation->join();
}

#include <windows.h>
#include "system/thread.hh"

using System::Thread;

DWORD WINAPI startThread(LPVOID args);

class Implementation : public Thread::ThreadImplementation
{
public:
    Implementation(Thread::Callable function) : _function(function) { }

    void start()
    {
        _threadHandle = CreateThread(NULL, 0, ::startThread, this, 0, NULL);
    }

    void join()
    {
        WaitForSingleObject(_threadHandle, INFINITE);
    }

    void run()
    {
        _function();
    }

private:
    Thread::Callable _function;
    HANDLE _threadHandle;
};

DWORD WINAPI startThread(LPVOID args)
{
    Implementation *self = (Implementation *)args;
    self->run();
    return 1;
}

Thread::ThreadImplementation *Thread::createImplementation(Thread::Callable function)
{
    return new Implementation(function);
}

Thread::Thread(Callable function)
{
    _implementation = createImplementation(function);
    _implementation->start();
}

void Thread::join()
{
    _implementation->join();
}

Fix type warning (and success value)

Fix type warning (and success value)


Add triples to keep make test work on Windows, where wchar_t is only 16
bits wide.

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


// RUN: %clang -march=x86_64-apple-darwin10 -emit-llvm -g -S %s -o - | FileCheck %s

struct X {
  X(int v);

  int value;
};

X::X(int v) {
  // CHECK: call void @_ZN1XC2Ei(%struct.X* %this1, i32 %tmp), !dbg
  value = v;
}

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

struct X {
  X(int v);

  int value;
};

X::X(int v) {
  // CHECK_TEMPORARILY_DISABLED: call void @_ZN1XC2Ei(%struct.X* %this1, i32 %tmp), !dbg
  // TEMPORARY CHECK: X
  value = v;
}

Revert r110936; this fails on clang-i686-darwin10 too.

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


#if defined(__unix__) || defined(__APPLE__)

#include <iostream>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>

#include "Types.h"

#include "Tools.h"

void StartBotProcess(const BotConfig &Agent, const std::string& CommandLine, void **ProcessId)
{
    FILE* pipe = popen(CommandLine.c_str(), "r");
    if (!pipe)
    {
        std::cerr << "Can't launch command '" <<
            CommandLine << "'" << std::endl;
        return;
    }
	*ProcessId = pipe;
    int returnCode = pclose(pipe);
    if (returnCode != 0)
    {
        std::cerr << "Failed to finish command '" <<
            CommandLine << "', code: " << returnCode << std::endl;
    }
}

void SleepFor(int seconds)
{
    sleep(seconds);
}

void KillSc2Process(unsigned long pid)
{
    kill(pid, SIGKILL);
}

bool MoveReplayFile(const char* lpExistingFileName, const  char* lpNewFileName)
{
	// todo
	throw "MoveFile is not implemented for linux yet.";
}

void KillBotProcess(void *ProcessStruct);
{
	// This needs to be implemented
}

#endif

#if defined(__unix__) || defined(__APPLE__)

#include <iostream>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>

#include "Types.h"

#include "Tools.h"

void StartBotProcess(const BotConfig &Agent, const std::string& CommandLine, void **ProcessId)
{
    FILE* pipe = popen(CommandLine.c_str(), "r");
    if (!pipe)
    {
        std::cerr << "Can't launch command '" <<
            CommandLine << "'" << std::endl;
        return;
    }
	*ProcessId = pipe;
    int returnCode = pclose(pipe);
    if (returnCode != 0)
    {
        std::cerr << "Failed to finish command '" <<
            CommandLine << "', code: " << returnCode << std::endl;
    }
}

void SleepFor(int seconds)
{
    sleep(seconds);
}

void KillSc2Process(unsigned long pid)
{
    kill(pid, SIGKILL);
}

bool MoveReplayFile(const char* lpExistingFileName, const  char* lpNewFileName)
{
	// todo
	throw "MoveFile is not implemented for linux yet.";
}

void KillBotProcess(void *ProcessStruct)
{
	// This needs to be implemented
}

#endif

Fix broken compilation on Linux/OS X

Fix broken compilation on Linux/OS X


#include "mips_memory.h"
#include "mips_instr.h"

#include <infra/instrcache/instr_cache.h>

FuncInstr MIPSMemory::fetch_instr( Addr PC)
{
    const auto [found, value] = instr_cache.find( PC);

    FuncInstr instr = found ? value : FuncInstr( fetch( PC), PC);

    instr_cache.update( PC, instr);

    return instr;
}

#include "mips_memory.h"
#include "mips_instr.h"

#include <infra/instrcache/instr_cache.h>

FuncInstr MIPSMemory::fetch_instr( Addr PC)
{
    const auto [found, value] = instr_cache.find( PC); // NOLINT https://bugs.llvm.org/show_bug.cgi?id=36283

    FuncInstr instr = found ? value : FuncInstr( fetch( PC), PC);

    instr_cache.update( PC, instr);

    return instr;
}

Add NOLINT to C++17 structured binding code


#include "include/matchercreationdialog.h"
#include "ui_matchercreationdialog.h"

MatcherCreationDialog::MatcherCreationDialog(QWidget *parent) :
	QDialog(parent),
	ui(new Ui::MatcherCreationDialog)
{
	ui->setupUi(this);
}

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

int MatcherCreationDialog::xblocks()
{
	return ui->xblocks->value();
}

int MatcherCreationDialog::yblocks()
{
	return ui->yblocks->value();
}

int MatcherCreationDialog::windowSize()
{
	return ui->window_size->value();
}

CharacterSets MatcherCreationDialog::set()
{
	switch(ui->set->currentIndex()) {
	case 1:
		return CharacterSets::CHINESE;
	case 2:
		return CharacterSets::LATIN;
	case 0:
	default:
		return CharacterSets::CHINESE_REDUCED;
	}
}

#include "include/matchercreationdialog.h"
#include "ui_matchercreationdialog.h"

#include <QSettings>

MatcherCreationDialog::MatcherCreationDialog(QWidget *parent) :
	QDialog(parent),
	ui(new Ui::MatcherCreationDialog)
{
	ui->setupUi(this);
	QSettings settings;
	ui->xblocks->setValue(settings.value("xblocks").toInt());
	ui->yblocks->setValue(settings.value("yblocks").toInt());
	ui->window_size->setValue(settings.value("windowSize").toInt());

	switch(settings.value("characterSet").value<CharacterSets>()) {
	case CharacterSets::CHINESE:
		ui->set->setCurrentIndex(1);
		break;
	case CharacterSets::LATIN:
		ui->set->setCurrentIndex(2);
		break;
	case CharacterSets::CHINESE_REDUCED:
	default:
		ui->set->setCurrentIndex(0);
		break;
	}
}

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

int MatcherCreationDialog::xblocks()
{
	return ui->xblocks->value();
}

int MatcherCreationDialog::yblocks()
{
	return ui->yblocks->value();
}

int MatcherCreationDialog::windowSize()
{
	return ui->window_size->value();
}

CharacterSets MatcherCreationDialog::set()
{
	switch(ui->set->currentIndex()) {
	case 1:
		return CharacterSets::CHINESE;
	case 2:
		return CharacterSets::LATIN;
	case 0:
	default:
		return CharacterSets::CHINESE_REDUCED;
	}
}

Load values in MatcherCreationDialog from settings


#include <Halide.h>
#include "vzero.h"
#include <stdio.h>
using namespace Halide;

// RUN: rm -f vzero.stdout; ./vzero.out; llvm-dis -o vzero.stdout vzero.bc; FileCheck %s < vzero.stdout

int main(int argc, char **argv) {
  Target target;
  setupHexagonTarget(target);
  target.set_feature(Target::HVX_64);
  //CHECK: call{{.*}}@llvm.hexagon.V6.vd0
  testBzero<uint32_t>(target);

  printf ("Done\n");

  return 0;
}

#include <Halide.h>
#include "vzero.h"
#include <stdio.h>
using namespace Halide;

// RUN: rm -f vzero.stdout; ./vzero.out; llvm-dis -o vzero.stdout vzero.bc; FileCheck %s < vzero.stdout

int main(int argc, char **argv) {
  Target target;
  setupHexagonTarget(target, Target::HVX_64);
  //CHECK: call{{.*}}@llvm.hexagon.V6.vd0
  testBzero<uint32_t>(target);

  printf ("Done\n");

  return 0;
}

Fix error in setting both HVX_64 and HVX_128 at same time

Former-commit-id: 702e785ff0c32457d741a46c15fa48b650cf9227


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

#include "SkFontConfigInterface.h"
#include "SkFontMgr.h"
#include "SkMutex.h"
#include "SkRefCnt.h"

SK_DECLARE_STATIC_MUTEX(gFontConfigInterfaceMutex);
static sk_sp<SkFontConfigInterface> gFontConfigInterface(nullptr);

sk_sp<SkFontConfigInterface> SkFontConfigInterface::RefGlobal() {
    SkAutoMutexAcquire ac(gFontConfigInterfaceMutex);

    if (gFontConfigInterface) {
        return gFontConfigInterface;
    }
    return sk_ref_sp(SkFontConfigInterface::GetSingletonDirectInterface());
}

void SkFontConfigInterface::SetGlobal(sk_sp<SkFontConfigInterface> fc) {
    SkAutoMutexAcquire ac(gFontConfigInterfaceMutex);

    gFontConfigInterface = std::move(fc);
}

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

#include "SkFontConfigInterface.h"
#include "SkFontMgr.h"
#include "SkMutex.h"
#include "SkRefCnt.h"

SK_DECLARE_STATIC_MUTEX(gFontConfigInterfaceMutex);
static SkFontConfigInterface* gFontConfigInterface;

sk_sp<SkFontConfigInterface> SkFontConfigInterface::RefGlobal() {
    SkAutoMutexAcquire ac(gFontConfigInterfaceMutex);

    if (gFontConfigInterface) {
        return sk_ref_sp(gFontConfigInterface);
    }
    return sk_ref_sp(SkFontConfigInterface::GetSingletonDirectInterface());
}

void SkFontConfigInterface::SetGlobal(sk_sp<SkFontConfigInterface> fc) {
    SkAutoMutexAcquire ac(gFontConfigInterfaceMutex);

    SkSafeUnref(gFontConfigInterface);
    gFontConfigInterface = fc.release();
}

Remove static initializer to register destructor.

Skia cannot have global sk_sp objects because they will register an exit
time destructor which will be done through a static initializer.

BUG=chromium:843858

Change-Id: I43e3d18c9d8b50ff067414148c7524bffd3523da
Reviewed-on: https://skia-review.googlesource.com/128843
Auto-Submit: Ben Wagner <53965154ffeecc4a10886eab9259e95965f2979a@google.com>
Commit-Queue: Herb Derby <9e12a3d2bbf73546e47cc9958f6ba8f3215b7eaf@google.com>
Reviewed-by: Herb Derby <9e12a3d2bbf73546e47cc9958f6ba8f3215b7eaf@google.com>


#include <kontsevich_graph_sum.hpp>

template <class T>
void KontsevichGraphSum<T>::reduce()
{
    auto current_term = this->begin();
    current_term->first *= current_term->second.sign();
    current_term->second.sign(1);
    while (current_term < this->end())
    {
        auto subsequent_term = current_term + 1;
        while (subsequent_term < this->end())
        {
            if (subsequent_term->second.abs() == current_term->second.abs())
            {
                current_term->first += subsequent_term->first * subsequent_term->second.sign();
                subsequent_term = this->erase(subsequent_term);
            }
            else
                subsequent_term++;
        }
        current_term++;
    }
}

template <class T>
std::ostream& operator<<(std::ostream& os, const KontsevichGraphSum<T>& gs)
{
    if (gs.size() == 0)
        return os << "0";
    for (auto &term : gs)
    {
        os << term.first << "*(" << term.second << ")";
        if (&term != &gs.back())
            os << " + ";
    }
    return os;
}

template class KontsevichGraphSum<int>;
template std::ostream& operator<<(std::ostream& os, const KontsevichGraphSum<int>& gs);

#include "kontsevich_graph_sum.hpp"

template <class T>
void KontsevichGraphSum<T>::reduce()
{
    auto current_term = this->begin();
    while (current_term < this->end())
    {
        current_term->first *= current_term->second.sign();
        current_term->second.sign(1);
        auto subsequent_term = current_term + 1;
        while (subsequent_term < this->end())
        {
            if (subsequent_term->second.abs() == current_term->second.abs())
            {
                current_term->first += subsequent_term->first * subsequent_term->second.sign();
                subsequent_term = this->erase(subsequent_term);
            }
            else
                subsequent_term++;
        }
        current_term++;
    }
}

template <class T>
std::ostream& operator<<(std::ostream& os, const KontsevichGraphSum<T>& gs)
{
    if (gs.size() == 0)
        return os << "0";
    for (auto &term : gs)
    {
        os << term.first << "*(" << term.second << ")";
        if (&term != &gs.back())
            os << " + ";
    }
    return os;
}

template class KontsevichGraphSum<int>;
template std::ostream& operator<<(std::ostream& os, const KontsevichGraphSum<int>& gs);

Fix unintended behavior in KontsevichGraphSum's reduce() method: now all signs of graphs are properly set to 1.