#include <iostream>

using namespace std;

const int MAX = 100;

struct Person {
  string firstName;
  string lastName;

  void input() {
    cout << "Enter person's first and last names separated by a space: ";
    cin >> firstName >> lastName;
  }

  void print() {
    cout << firstName << ' ' << lastName << '\n';
  }
};

struct Client {
  Person person;
  double account;

  void input() {
    person.input();

    cout << "Enter account: ";
    cin >> account;
  }

  void print() {
    person.print();
    cout << "Account: " << account << '\n';
  };
};

void inputClients(int n) {
  Client clients[MAX];

  for (int i = 0; i < n; ++i) {
    clients[i].input();
  }
}

void printClients(Client clients[], int n) {
  for (int i = 0; i < n; ++i) {
    clients[i].print();
  }
}

double sumAccounts(Client clients[], int n) {
  double sum = 0;

  for (int i = 0; i < n; ++i) {
    sum += clients[i].account;
  }

  return sum;
}

int main() {
  return 0;
}

#include <iostream>

using namespace std;

const int MAX = 100;

struct Person {
  string firstName;
  string lastName;

  void input() {
    cout << "Enter person's first and last names separated by a space: ";
    cin >> firstName >> lastName;
  }

  void print() {
    cout << firstName << ' ' << lastName << '\n';
  }
};

struct Client {
  Person person;
  double account;

  void input() {
    person.input();

    cout << "Enter account: ";
    cin >> account;
  }

  void print() {
    person.print();
    cout << "Account: " << account << '\n';
  };
};

void inputClients(Client clients[], int n) {
  for (int i = 0; i < n; ++i) {
    clients[i].input();
  }
}

void printClients(Client clients[], int n) {
  for (int i = 0; i < n; ++i) {
    clients[i].print();
  }
}

double sumAccounts(Client clients[], int n) {
  double sum = 0;

  for (int i = 0; i < n; ++i) {
    sum += clients[i].account;
  }

  return sum;
}

int main() {
  Client clients[MAX];
  int clientsCount = 3;

  inputClients(clients, clientsCount);
  printClients(clients, clientsCount);
  cout << sumAccounts(clients, clientsCount) << '\n';

  return 0;
}

Add test for first problem solution


//
// Created by dar on 2/21/16.
//

#include "EntityFather.h"

EntityFather::EntityFather(Map *map) : EntityMoving(map, 0.25, 0.25) {
    b2PolygonShape shape;
    shape.SetAsBox(0.25, 0.25);
    b2FixtureDef fixDef;
    fixDef.shape = &shape;
    fixDef.density = 6.0f;
    fixDef.friction = 0.1f;
    this->body->CreateFixture(&fixDef);
}

void EntityFather::update() {
    EntityMoving::update();
    this->applyImpulse(1.0f * this->getSpeed(), 0.0f);
}

double EntityFather::getSpeed() {
    return 0.5f;
}

//
// Created by dar on 2/21/16.
//

#include "EntityFather.h"

EntityFather::EntityFather(Map *map) : EntityMoving(map, 0.25, 0.25) {
    b2PolygonShape shape;
    shape.SetAsBox(0.25, 0.25);
    b2FixtureDef fixDef;
    fixDef.shape = &shape;
    fixDef.density = 6.0f;
    fixDef.friction = 0.1f;
    this->body->CreateFixture(&fixDef);
}

void EntityFather::update() {
    EntityMoving::update();
    this->applyImpulse(1.0f * this->getSpeed() * cos(this->getAngle()), 1.0f * this->getSpeed() * sin(this->getAngle()));
}

double EntityFather::getSpeed() {
    return 0.5f;
}

Make the father walk straight


/*
 * main.cc
 *
 *  Copyright (c) 2015 Masatoshi Hanai
 *
 *  This software is released under MIT License.
 *  See LICENSE.
 *
 */
#include "glog/logging.h"
#include "gflags/gflags.h"
#include "gtest/gtest.h"
#include "leveldb/db.h"
#include "leveldb/options.h"

/* test files */
#include "medium/com_test.cc"
#include "medium/db_via_lp_test.cc"
#include "medium/gvt_test.cc"
#include "medium/logical_process_test.cc"
#include "small/db_test.cc"
#include "small/io_test.cc"
#include "small/thread_test.cc"
#include "small/util_test.cc"

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

  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

/*
 * main.cc
 *
 *  Copyright (c) 2015 Masatoshi Hanai
 *
 *  This software is released under MIT License.
 *  See LICENSE.
 *
 */
#include "glog/logging.h"
#include "gflags/gflags.h"
#include "gtest/gtest.h"
#include "leveldb/db.h"
#include "leveldb/options.h"

/* test files */
#include "medium/com_test.cc"
#include "medium/db_via_lp_test.cc"
#include "medium/gvt_test.cc"
#include "medium/logical_process_test.cc"
#include "small/db_test.cc"
#include "small/io_test.cc"
#include "small/thread_test.cc"
#include "small/util_test.cc"

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

  gflags::ParseCommandLineFlags(&argc, &argv, true);
  google::InitGoogleLogging(*argv);
  google::InstallFailureSignalHandler();

  return RUN_ALL_TESTS();
}

Fix bug for parsing google test flags


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

#include "perfetto/base/watchdog.h"

#include "gtest/gtest.h"

#include <time.h>

namespace perfetto {
namespace base {
namespace {

TEST(WatchDogTest, Crash) {
  EXPECT_DEATH(
      {
        WatchDog watchdog(1);
        usleep(2000000);
      },
      "");
}

TEST(WatchDogTest, NoCrash) {
  WatchDog watchdog(100000);
  usleep(5000);
}

}  // namespace
}  // namespace base
}  // namespace perfetto

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

#include "perfetto/base/watchdog.h"

#include "perfetto/base/logging.h"

#include "gtest/gtest.h"

#include <time.h>

namespace perfetto {
namespace base {
namespace {

TEST(WatchDogTest, Crash) {
  EXPECT_DEATH(
      {
        WatchDog watchdog(1);
        int sleep_s = 20;
        while (sleep_s != 0) {
          sleep_s = sleep(sleep_s);
        }
      },
      "");
}

TEST(WatchDogTest, NoCrash) {
  WatchDog watchdog(100000);
  PERFETTO_CHECK(usleep(5000) != -1);
}

}  // namespace
}  // namespace base
}  // namespace perfetto

Increase timeout of Crash test.


// RUN: %clang_cc1 -verify -triple x86_64-apple-darwin -emit-llvm -o - %s | FileCheck %s

// CHECK: @a = global i32 10
int a = 10;
// CHECK: @ar = constant i32* @a
int &ar = a;

void f();
// CHECK: @fr = constant void ()* @_Z1fv
void (&fr)() = f;

struct S { int& a; };
// CHECK: @s = global %0 { i32* @a }
S s = { a };

// PR5581
namespace PR5581 {
class C {
public:
  enum { e0, e1 };
  unsigned f;
};

// CHECK: @_ZN6PR55812g0E = global %1 { i32 1 }
C g0 = { C::e1 };
}

namespace test2 {
  struct A {
    static const double d = 1.0;
    static const float f = d / 2;
  };

  // CHECK: @_ZN5test22t0E = global double 1.000000e+00, align 8
  // CHECK: @_ZN5test22t1E = global [2 x double] [double 1.000000e+00, double 5.000000e-01], align 16
  double t0 = A::d;
  double t1[] = { A::d, A::f };
}

// RUN: %clang_cc1 -verify -triple x86_64-apple-darwin -emit-llvm -o - %s | FileCheck %s

// CHECK: @a = global i32 10
int a = 10;
// CHECK: @ar = constant i32* @a
int &ar = a;

void f();
// CHECK: @fr = constant void ()* @_Z1fv
void (&fr)() = f;

struct S { int& a; };
// CHECK: @s = global %0 { i32* @a }
S s = { a };

// PR5581
namespace PR5581 {
class C {
public:
  enum { e0, e1 };
  unsigned f;
};

// CHECK: @_ZN6PR55812g0E = global %1 { i32 1 }
C g0 = { C::e1 };
}

namespace test2 {
  struct A {
    static const double d = 1.0;
    static const float f = d / 2;
  };

  // CHECK: @_ZN5test22t0E = global double {{1\.0+e\+0+}}, align 8
  // CHECK: @_ZN5test22t1E = global [2 x double] [double {{1\.0+e\+0+}}, double {{5\.0+e-0*}}1], align 16
  double t0 = A::d;
  double t1[] = { A::d, A::f };
}

Secure this test against slightly different number formatters.


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

#include <jni.h>

#include "AndroidAppThreadAssertionMacros.h"
#include "IndoorAtlasLocationManager.h"
#include "IndoorAtlasLocationManagerJni.h"

extern "C"
{
JNIEXPORT void JNICALL Java_com_eegeo_interiorsposition_indooratlas_IndoorAtlasLocationManagerJniMethods_DidUpdateLocation(
        JNIEnv *jenv, jclass jobj,
        jlong nativeObjectPtr,
        jdouble latitude,
        jdouble longitude,
        jstring floorId)
{
	const char* chars = jenv->GetStringUTFChars(floorId, 0);
	std::string floorIdString = chars;
	jenv->ReleaseStringUTFChars(floorId, chars);

    using ExampleApp::InteriorsPosition::SdkModel::IndoorAtlas::IndoorAtlasLocationManager;
    reinterpret_cast<IndoorAtlasLocationManager *>(nativeObjectPtr)->DidUpdateLocation(latitude,
                                                                                longitude,
                                                                                floorIdString);
}

JNIEXPORT void JNICALL Java_com_eegeo_interiorsposition_indooratlas_IndoorAtlasLocationManagerJniMethods_SetIsAuthorized(
        JNIEnv *jenv, jclass obj,
        jlong nativeObjectPtr,
        jboolean isAuthorized)
{
    using ExampleApp::InteriorsPosition::SdkModel::IndoorAtlas::IndoorAtlasLocationManager;
    reinterpret_cast<IndoorAtlasLocationManager *>(nativeObjectPtr)->SetIsAuthorized(isAuthorized);
}
}

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

#include <jni.h>

#include "AndroidAppThreadAssertionMacros.h"
#include "IndoorAtlasLocationManager.h"
#include "IndoorAtlasLocationManagerJni.h"

extern "C"
{
JNIEXPORT void JNICALL Java_com_eegeo_interiorsposition_indooratlas_IndoorAtlasLocationManagerJniMethods_DidUpdateLocation(
        JNIEnv *jenv, jclass jobj,
        jlong nativeObjectPtr,
        jdouble latitude,
        jdouble longitude,
        jstring floorId)
{
    std::string floorIdString = "";
    if(floorId != NULL)
    {
        const char *chars = jenv->GetStringUTFChars(floorId, 0);
        floorIdString = chars;
        jenv->ReleaseStringUTFChars(floorId, chars);
    }

    using ExampleApp::InteriorsPosition::SdkModel::IndoorAtlas::IndoorAtlasLocationManager;
    reinterpret_cast<IndoorAtlasLocationManager *>(nativeObjectPtr)->DidUpdateLocation(latitude,
                                                                                longitude,
                                                                                floorIdString);
}

JNIEXPORT void JNICALL Java_com_eegeo_interiorsposition_indooratlas_IndoorAtlasLocationManagerJniMethods_SetIsAuthorized(
        JNIEnv *jenv, jclass obj,
        jlong nativeObjectPtr,
        jboolean isAuthorized)
{
    using ExampleApp::InteriorsPosition::SdkModel::IndoorAtlas::IndoorAtlasLocationManager;
    reinterpret_cast<IndoorAtlasLocationManager *>(nativeObjectPtr)->SetIsAuthorized(isAuthorized);
}
}

Fix for MPLY-9036. Guard against null region values from IA. Buddy: Jordan


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

#include "voice_engine/test/auto_test/fixtures/before_initialization_fixture.h"

#include <cstdlib>

class VoeBaseMiscTest : public BeforeInitializationFixture {
};

using namespace testing;

TEST_F(VoeBaseMiscTest, MaxNumChannelsIs32) {
  EXPECT_EQ(32, voe_base_->MaxNumOfChannels());
}

TEST_F(VoeBaseMiscTest, GetVersionPrintsSomeUsefulInformation) {
  char char_buffer[1024];
  memset(char_buffer, 0, sizeof(char_buffer));
  EXPECT_EQ(0, voe_base_->GetVersion(char_buffer));
  EXPECT_THAT(char_buffer, ContainsRegex("VoiceEngine"));
}

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

#include "voice_engine/test/auto_test/fixtures/before_initialization_fixture.h"

#include <cstdlib>

class VoeBaseMiscTest : public BeforeInitializationFixture {
};

using namespace testing;

TEST_F(VoeBaseMiscTest, MaxNumChannelsIs100) {
  EXPECT_EQ(100, voe_base_->MaxNumOfChannels());
}

TEST_F(VoeBaseMiscTest, GetVersionPrintsSomeUsefulInformation) {
  char char_buffer[1024];
  memset(char_buffer, 0, sizeof(char_buffer));
  EXPECT_EQ(0, voe_base_->GetVersion(char_buffer));
  EXPECT_THAT(char_buffer, ContainsRegex("VoiceEngine"));
}

Fix MaxChannels test; 32 -> 100.


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

#include "rand.h"

using namespace std;

int main() {
  string cipher;

  getline(cin, cipher);
  cout << cipher << endl;

}

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

#include "rand.h"

using namespace std;

int main() {
  string cipher, tmp;

  while( getline( cin, tmp ) )
    {
      cipher.append( tmp );
    }
  //  cout << cipher << endl;

  ifstream freq;
  freq.open( "freq.txt", ios::in );

  string freqletter[488];
  int freqnumber[488];

  if( freq.is_open() ) {
    for(int i = 0; i < 488; i++ ) {
      freq >> freqletter[i];
      freq >> freqnumber[i];
    }
  }

  freq.close();

  // for(int i = 0; i < 488; i++ ) {
  //   cout << freqletter[i] << " " << freqnumber[i] << endl;
  // }

}

Read in input and freq.txt


//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/Runtime/Config.h"
#include "swift/Runtime/Metadata.h"

using namespace swift;

SWIFT_CC(swift) LLVM_LIBRARY_VISIBILITY extern "C"
uint32_t getMetadataKindOf(
    OpaqueValue *value,
    const Metadata *type
) {
  auto result = uint32_t(type->getKind());
  type->vw_destroy(value);
  return result;
}

//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/Runtime/Config.h"
#include "swift/Runtime/Metadata.h"

using namespace swift;

SWIFT_CC(swift) LLVM_LIBRARY_VISIBILITY extern "C"
uint32_t getMetadataKindOf(
    OpaqueValue *value,
    const Metadata *type
) {
  auto result = uint32_t(type->getKind());
  SWIFT_CC_PLUSONE_GUARD(type->vw_destroy(value));
  return result;
}

Update getMetadataKindOf for +0 parameters.


#include <iostream>

using std::cin;
using std::cout;

int main() {
  char operation;
  cout << "Choose an operation (+, -, *, /): ";
  cin >> operation;

  double first_operand;
  double second_operand;
  cout << "Enter your operands: ";
  cin >> first_operand >> second_operand;

  double result;

  switch(operation) {
    case '+':
      result = first_operand + second_operand;
      break;
    case '-':
      result = first_operand - second_operand;
      break;
    case '*':
      result = first_operand * second_operand;
      break;
    case '/':
      result = first_operand / second_operand;
      break;
    default:
      cout << "Unknown operation " << operation << '\n';
      return 1;
  }

  cout << first_operand << ' '
       << operation << ' '
       << second_operand << " = "
       << result << '\n';

  return 0;
}

#include <iostream>

using std::cin;
using std::cout;

int main() {
  char operation;
  cout << "Choose an operation (+, -, *, /): ";
  cin >> operation;

  double first_operand;
  double second_operand;
  cout << "Enter your operands: ";
  cin >> first_operand >> second_operand;

  double result;

  switch (operation) {
    case '+':
      result = first_operand + second_operand;
      break;
    case '-':
      result = first_operand - second_operand;
      break;
    case '*':
      result = first_operand * second_operand;
      break;
    case '/':
      result = first_operand / second_operand;
      break;
    default:
      cout << "Unknown operation " << operation << '\n';
      return 1;
  }

  cout << first_operand << ' '
       << operation << ' '
       << second_operand << " = "
       << result << '\n';

  return 0;
}

Add space after switch keyword


#include <boxer/boxer.h>
#include <gtk/gtk.h>

namespace boxer {

void show(const char *message, const char *title) {
  gtk_init(0, NULL);

  GtkWidget *dialog = gtk_message_dialog_new(NULL,
            GTK_DIALOG_MODAL,
            GTK_MESSAGE_INFO,
            GTK_BUTTONS_OK,
            message);
  gtk_window_set_title(GTK_WINDOW(dialog), title);
  gtk_dialog_run(GTK_DIALOG(dialog));

  gtk_widget_destroy(GTK_WIDGET(dialog));
  while (g_main_context_iteration(NULL, false));
}

} // namespace boxer

#include <boxer/boxer.h>
#include <gtk/gtk.h>

namespace boxer {

void show(const char *message, const char *title) {
  gtk_init(0, NULL);

  GtkWidget *dialog = gtk_message_dialog_new(NULL,
            GTK_DIALOG_MODAL,
            GTK_MESSAGE_INFO,
            GTK_BUTTONS_OK,
            "%s",
            message);
  gtk_window_set_title(GTK_WINDOW(dialog), title);
  gtk_dialog_run(GTK_DIALOG(dialog));

  gtk_widget_destroy(GTK_WIDGET(dialog));
  while (g_main_context_iteration(NULL, false));
}

} // namespace boxer

Add format string to gtk_message_dialog_new()


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

// The fixture for testing class Foo.
class CpuTest : public ::testing::Test
{
protected:
  CpuTest()
  {
  }

  ~CpuTest() override
  {
  }

  void SetUp() override
  {
  }

  void TearDown() override
  {
  }

  Cpu cpu;
};

TEST_F(CpuTest, instruction1test)
{
}

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

// The fixture for testing class Foo.
class CpuTest : public Cpu, public ::testing::Test
{
protected:
  CpuTest()
  {
  }

  ~CpuTest() override
  {
  }

  void SetUp() override
  {
  }

  void TearDown() override
  {
  }
};

TEST_F(CpuTest, pcNop)
{
  runOpcode(0x01);
  EXPECT_EQ(getPC(), 3);
}

Add first cpu unit test


extern "C"
{
    #include "packet_queue.h"
    #include "error.h"
    #include "nrf51.h"
    #include "nrf51_bitfields.h"
}

#include "CppUTest/TestHarness.h"

TEST_GROUP(packet_queue)
{
    packet_queue_t queue;

    void setup(void)
    {
        packet_queue_init(&queue);
    }

    void teardown(void)
    {
    }
};

TEST(packet_queue, test_queue_init_succeed)
{
    packet_queue_t queue;
    LONGS_EQUAL(SUCCESS, packet_queue_init(&queue));
}

TEST(packet_queue, test_queue_new_queue_is_empty)
{
    LONGS_EQUAL(true, packet_queue_is_empty(&queue));
}

TEST(packet_queue, test_queue_add_queue_is_not_empty)
{
    radio_packet_t packet;
    packet_queue_add(&queue, &packet);

    LONGS_EQUAL(false, packet_queue_is_empty(&queue));
}

extern "C"
{
    #include "packet_queue.h"
    #include "error.h"
    #include "nrf51.h"
    #include "nrf51_bitfields.h"
}

#include "CppUTest/TestHarness.h"

#include <limits.h>
#include <string.h>

TEST_GROUP(packet_queue)
{
    packet_queue_t queue;

    void setup(void)
    {
        packet_queue_init(&queue);
    }

    void teardown(void)
    {
    }
};

TEST(packet_queue, test_queue_init_succeed)
{
    packet_queue_t queue;
    LONGS_EQUAL(SUCCESS, packet_queue_init(&queue));
}

TEST(packet_queue, test_queue_new_queue_is_empty)
{
    LONGS_EQUAL(true, packet_queue_is_empty(&queue));

    radio_packet_t packet;
    packet_queue_add(&queue, &packet);

    LONGS_EQUAL(false, packet_queue_is_empty(&queue));
}

TEST(packet_queue, test_queue_full_queue_is_full)
{
    LONGS_EQUAL(false, packet_queue_is_full(&queue));

    for (int i = 0; i < PACKET_QUEUE_SIZE; i++)
    {
        radio_packet_t packet;
        packet_queue_add(&queue, &packet);
    }
    LONGS_EQUAL(true, packet_queue_is_full(&queue));
}

Reorganize empty and full tests.


#include <assert.h>

#include <leveldb/iterator.h>
#include <node.h>
#include <v8.h>

#include "iterator.h"

namespace node_leveldb {

async_rtn JIterator::After(uv_work_t* req) {
  Params *data = (Params*) req->data;
  data->callback->Call(data->self->handle_, 0, NULL);
  delete data;
  RETURN_ASYNC_AFTER;
}

async_rtn JIterator::Seek(uv_work_t* req) {
  SeekParams *data = (SeekParams*) req->data;
  data->self->it_->Seek(data->key);
  RETURN_ASYNC;
}

async_rtn JIterator::First(uv_work_t* req) {
  SeekParams *data = (SeekParams*) req->data;
  data->self->it_->SeekToFirst();
  RETURN_ASYNC;
}

async_rtn JIterator::Last(uv_work_t* req) {
  SeekParams *data = (SeekParams*) req->data;
  data->self->it_->SeekToLast();
  RETURN_ASYNC;
}

async_rtn JIterator::Next(uv_work_t* req) {
  SeekParams *data = (SeekParams*) req->data;
  data->self->it_->Next();
  RETURN_ASYNC;
}

async_rtn JIterator::Prev(uv_work_t* req) {
  SeekParams *data = (SeekParams*) req->data;
  data->self->it_->Prev();
  RETURN_ASYNC;
}

} // node_leveldb

#include <assert.h>

#include <leveldb/iterator.h>
#include <node.h>
#include <v8.h>

#include "iterator.h"

namespace node_leveldb {

async_rtn JIterator::After(uv_work_t* req) {
  Params *data = (Params*) req->data;
  data->callback->Call(data->self->handle_, 0, NULL);
  delete data;
  RETURN_ASYNC_AFTER;
}

async_rtn JIterator::Seek(uv_work_t* req) {
  SeekParams *data = (SeekParams*) req->data;
  data->self->it_->Seek(data->key);
  RETURN_ASYNC;
}

async_rtn JIterator::First(uv_work_t* req) {
  Params *data = (Params*) req->data;
  data->self->it_->SeekToFirst();
  RETURN_ASYNC;
}

async_rtn JIterator::Last(uv_work_t* req) {
  Params *data = (Params*) req->data;
  data->self->it_->SeekToLast();
  RETURN_ASYNC;
}

async_rtn JIterator::Next(uv_work_t* req) {
  Params *data = (Params*) req->data;
  data->self->it_->Next();
  RETURN_ASYNC;
}

async_rtn JIterator::Prev(uv_work_t* req) {
  Params *data = (Params*) req->data;
  data->self->it_->Prev();
  RETURN_ASYNC;
}

} // node_leveldb

Fix types in iterator async


// Qt includes
//#include <QHash>
//#include <QVariant>

// Visomics includes
#include "voLog2.h"

// VTK includes
#include <vtkDoubleArray.h>
#include <vtkMath.h>
#include <vtkTable.h>

namespace Normalization
{

//------------------------------------------------------------------------------
bool applyLog2(vtkTable * dataTable, const QHash<int, QVariant>& settings)
{
  Q_UNUSED(settings);
  if (!dataTable)
    {
    return false;
    }

  for (int cid = 0; cid < dataTable->GetNumberOfColumns(); ++cid)
    {
    vtkDoubleArray * column = vtkDoubleArray::SafeDownCast(dataTable->GetColumn(cid));
    if (!column)
      {
      continue;
      }
    for (int rid = 0; rid < column->GetNumberOfTuples() * column->GetNumberOfComponents(); ++rid)
      {
      column->SetValue(rid, log2(column->GetValue(rid)));
      }
    }
  dataTable->Modified();

  return true;
}

} // end of Normalization namespace

// Qt includes
//#include <QHash>
//#include <QVariant>

// Visomics includes
#include "voLog2.h"

// VTK includes
#include <vtkDoubleArray.h>
#include <vtkTable.h>

// STD includes
#include <cmath>

namespace Normalization
{

//------------------------------------------------------------------------------
bool applyLog2(vtkTable * dataTable, const QHash<int, QVariant>& settings)
{
  Q_UNUSED(settings);
  if (!dataTable)
    {
    return false;
    }

  for (int cid = 0; cid < dataTable->GetNumberOfColumns(); ++cid)
    {
    vtkDoubleArray * column = vtkDoubleArray::SafeDownCast(dataTable->GetColumn(cid));
    if (!column)
      {
      continue;
      }
    for (int rid = 0; rid < column->GetNumberOfTuples() * column->GetNumberOfComponents(); ++rid)
      {
      column->SetValue(rid, std::log(column->GetValue(rid)) / log(2.0));
      }
    }
  dataTable->Modified();

  return true;
}

} // end of Normalization namespace

Use log(X)/log(2.0) instead of log2() function


#include "mainwindowcontroller.h"
#include "ui_mainwindowcontroller.h"

#include <QErrorMessage>
#include <QStandardPaths>
#include <QDir>
#include <QCoreApplication>

#include "kopsik_api.h"

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

    QString version = QCoreApplication::applicationVersion();
    ctx_ = kopsik_context_init("linux_native_app", version.toUtf8().constData());

    QString appDirPath =
            QStandardPaths::writableLocation(QStandardPaths::DataLocation);
    QDir appDir = QDir(appDirPath);

    QString logPath = appDir.filePath("kopsik.log");
    kopsik_set_log_path(logPath.toUtf8().constData());

    QString dbPath = appDir.filePath("kopsik.db");
    kopsik_set_db_path(ctx_, dbPath.toUtf8().constData());

    QString executablePath = QCoreApplication::applicationDirPath();
    QDir executableDir = QDir(executablePath);
    QString cacertPath = executableDir.filePath("cacert.pem");
    kopsik_set_cacert_path(ctx_, cacertPath.toUtf8().constData());

    if (!kopsik_context_start_events(ctx_)) {
    }
}

MainWindowController::~MainWindowController()
{
    kopsik_context_clear(ctx_);
    delete ui;
}

#include "mainwindowcontroller.h"
#include "ui_mainwindowcontroller.h"

#include <QErrorMessage>
#include <QStandardPaths>
#include <QDir>
#include <QCoreApplication>

#include "kopsik_api.h"

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

    QString version = QCoreApplication::applicationVersion();
    ctx_ = kopsik_context_init("linux_native_app", version.toUtf8().constData());

    QString appDirPath =
            QStandardPaths::writableLocation(QStandardPaths::DataLocation);
    QDir appDir = QDir(appDirPath);
    if (!appDir.exists()) {
        appDir.mkpath(".");
    }

    QString logPath = appDir.filePath("kopsik.log");
    kopsik_set_log_path(logPath.toUtf8().constData());

    QString dbPath = appDir.filePath("kopsik.db");
    kopsik_set_db_path(ctx_, dbPath.toUtf8().constData());

    QString executablePath = QCoreApplication::applicationDirPath();
    QDir executableDir = QDir(executablePath);
    QString cacertPath = executableDir.filePath("cacert.pem");
    kopsik_set_cacert_path(ctx_, cacertPath.toUtf8().constData());

    if (!kopsik_context_start_events(ctx_)) {
    }
}

MainWindowController::~MainWindowController()
{
    kopsik_context_clear(ctx_);
    delete ui;
}

Create app dir if not exists (linux)


#include "Ball.h"

void Ball::reset()
{
    float resetX, resetY;

    resetX = displayW / 2.0;
    resetY = rand() % displayH;

    randomDirection();

    setPosition(resetX, resetY);
}

void Ball::update()
{
    checkForCollisions();

    x += accelX;
    y += accelY;

    if (testBit(DEAD))
    {
        reset();
        clearBit(DEAD);
    }

    calcCenter();
}

void Ball::randomDirection()
{
    if (rand() % 2)
    {
        accelX *= -1;
    }
    if (rand() % 2)
    {
        accelY *= -1;
    }
}

void Ball::getDisplayData()
{
    ALLEGRO_DISPLAY *display = al_get_current_display();

    displayW = al_get_display_width(display);
    displayH = al_get_display_height(display);
}

void Ball::checkForCollisions()
{
    if (x < 0 || x > displayW)
    {
        accelX *= -1;
    }
    if (y < 0 || y > displayH)
    {
        accelY *= -1;
    }
}

#include "Ball.h"

void Ball::reset()
{
    float resetX, resetY;

    resetX = displayW / 2.0;
    resetY = rand() % displayH;

    randomDirection();

    setPosition(resetX, resetY);
}

void Ball::update()
{
    checkForCollisions();

    x += accelX;
    y += accelY;

    if (testBit(DEAD))
    {
        reset();
        clearBit(DEAD);
    }

    calcCenter();
}

void Ball::randomDirection()
{
    if (rand() % 2)
    {
        accelX *= -1;
    }
    if (rand() % 2)
    {
        accelY *= -1;
    }
}

void Ball::getDisplayData()
{
    ALLEGRO_DISPLAY *display = al_get_current_display();

    displayW = al_get_display_width(display);
    displayH = al_get_display_height(display);
}

void Ball::checkForCollisions()
{
    if (x - w / 2.0 < 0 || x + w / 2.0 > displayW)
    {
        accelX *= -1;
    }
    if (y - h / 2.0 < 0 || y + h / 2.0> displayH)
    {
        accelY *= -1;
    }
}

Fix ball bouncing before graphic touched borders.


#include <kernel/config.h>
#include <kernel/kernconf.hh>

USDK_API kernconf_type kernconf = {
  // Default is large enough until we enable a mechanism to dynamically
  // reallocate task space on demand.
  /* .default_stack_size = */         URBI_KERNEL_STACK_SIZE * 1024,
  /* .minimum_stack_size = */         4 * 1024
};

#include <kernel/config.h>
#include <kernel/kernconf.hh>

USDK_API kernconf_type kernconf = {
  // Default is large enough until we enable a mechanism to dynamically
  // reallocate task space on demand.
  /* .default_stack_size = */         URBI_KERNEL_STACK_SIZE * 1024,
  /* .minimum_stack_size = */         URBI_KERNEL_STACK_SIZE * 1024 / 8
};

Make the minimum stack size depend on the default stack size.


#include "config.h"

#include <stdint.h>
#include <stdlib.h>
#include <sys/types.h>
#ifdef RBX_WINDOWS
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netdb.h>
#endif
#include <sys/stat.h>
#include <errno.h>
#include <time.h>
#include <math.h>

#include "windows_compat.h"
#include "ffi_util.hpp"

#ifdef __APPLE__
#include <crt_externs.h>
#endif

extern "C" {

extern char** environ;

int ffi_errno() { return errno; }

char** ffi_environ() {
#ifdef __APPLE__
  return *_NSGetEnviron();
#else
  return environ;
#endif
}

void ffi_set_errno(int n) {
  errno = n;
}

#ifndef major
#define major(x) x
#endif

#ifndef minor
#define minor(x) 0
#endif

long ffi_major(dev_t n) {
  return major(n);
}

long ffi_minor(dev_t n) {
  return minor(n);
}

}

#include "config.h"

#include <stdint.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/sysmacros.h>
#ifdef RBX_WINDOWS
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netdb.h>
#endif
#include <sys/stat.h>
#include <errno.h>
#include <time.h>
#include <math.h>

#include "windows_compat.h"
#include "ffi_util.hpp"

#ifdef __APPLE__
#include <crt_externs.h>
#endif

extern "C" {

extern char** environ;

int ffi_errno() { return errno; }

char** ffi_environ() {
#ifdef __APPLE__
  return *_NSGetEnviron();
#else
  return environ;
#endif
}

void ffi_set_errno(int n) {
  errno = n;
}

#ifndef major
#define major(x) x
#endif

#ifndef minor
#define minor(x) 0
#endif

long ffi_major(dev_t n) {
  return major(n);
}

long ffi_minor(dev_t n) {
  return minor(n);
}

}

Fix warning on Ubuntu Bionic.


// Native C++ Libraries
#include <iostream>
#include <string>

// C++ Interpreter Libraries
#include <Console.h>

using namespace std;

int main()
{
	RESTART:
	string input = "";
	getline(cin, input);
	cin.ignore();
	goto RESTART;
}

// Native C++ Libraries
#include <iostream>
#include <string>

// C++ Interpreter Libraries
#include <Console.h>

using namespace std;

int main()
{
	RESTART:
	string input = "";
	getline(cin, input);
	goto RESTART;
}

Remove console-in ignore in main source.


#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QtQml>
#include "applications.h"
#include "iconprovider.h"
#include "process.h"

/**
 * @todo: Config file in ~/.config/qmldmenu/
 * @todo: SHIFT(ENTER) for sudo
 * @todo: TAB For command (term /{usr}/bin/) / app (.desktop) mode
 */
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QLoggingCategory::setFilterRules("qt.svg.warning=false"); // Hide buggy SVG icon warnings

    QQmlApplicationEngine engine;

    qmlRegisterType<Process>("Process", 1, 0, "Process");
    qmlRegisterType<Applications>("Applications", 1, 0, "Applications");
    engine.addImageProvider(QLatin1String("appicon"), new IconProvider);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QtQml>
#include "applications.h"
#include "iconprovider.h"
#include "process.h"

/**
 * @todo: Config file in ~/.config/qmldmenu/
 * @todo: SHIFT(ENTER) for sudo
 * @todo: TAB For command (term /{usr}/bin/) / app (.desktop) mode
 */
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QLoggingCategory::setFilterRules("qt.svg.warning=false"); // Hide buggy SVG icon warnings
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QQmlApplicationEngine engine;

    qmlRegisterType<Process>("Process", 1, 0, "Process");
    qmlRegisterType<Applications>("Applications", 1, 0, "Applications");
    engine.addImageProvider(QLatin1String("appicon"), new IconProvider);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

Fix high dpi icon sizes


/*
 * Copyright (C) 2008-2010, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

// This file *must* remain with absolutely no run-time dependency.

#include <urbi/urbi-root.hh>

#include <sdk/config.hh>

int main(int argc, char* argv[])
{
  UrbiRoot urbi_root(argv[0],
#ifdef STATIC_BUILD
                     true
#else
                     false
#endif
                     );
  return urbi_root.urbi_launch(argc, argv);
}

/*
 * Copyright (C) 2008-2010, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

// This file *must* remain with absolutely no run-time dependency.

#include <urbi/urbi-root.hh>

#include <sdk/config.h>

int main(int argc, char* argv[])
{
  UrbiRoot urbi_root(argv[0],
#ifdef STATIC_BUILD
                     true
#else
                     false
#endif
                     );
  return urbi_root.urbi_launch(argc, argv);
}

Fix typo in previous patch.


/*
* Arduino JSON library
* Benoit Blanchon 2014 - MIT License
*/

#include "CppUnitTest.h"
#include "IndentedPrintDecorator.h"
#include "StringBuilder.h"

using namespace ArduinoJson::Internals;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace JsonGeneratorTests
{
    TEST_CLASS(Indented_Array_Tests)
    {
        char buffer[1024];
        size_t returnValue;

    public:

        TEST_METHOD(EmptyArray)
        {
            whenInputIs("[]");
            outputMustBe("[]");
        }

        TEST_METHOD(OneElement)
        {
            whenInputIs("[1]");
            outputMustBe(
                "[\n"
                " 1\n"
                "]");
        }

    private:

        void whenInputIs(const char input[])
        {
            StringBuilder sb(buffer, sizeof(buffer));
            IndentedPrintDecorator decorator(sb);

            returnValue = decorator.print(input);
        }

        void outputMustBe(const char* expected)
        {
            Assert::AreEqual(expected, buffer);
            Assert::AreEqual(strlen(expected), returnValue);
        }
    };
}

/*
* Arduino JSON library
* Benoit Blanchon 2014 - MIT License
*/

#include "CppUnitTest.h"
#include "IndentedPrintDecorator.h"
#include "StringBuilder.h"

using namespace ArduinoJson::Internals;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace JsonGeneratorTests
{
    TEST_CLASS(Indented_Array_Tests)
    {
        char buffer[1024];
        size_t returnValue;

    public:

        TEST_METHOD(EmptyArray)
        {
            whenInputIs("[]");
            outputMustBe("[]");
        }

        TEST_METHOD(OneElement)
        {
            whenInputIs("[1]");
            outputMustBe(
                "[\n"
                " 1\n"
                "]");
        }

        TEST_METHOD(TwoElements)
        {
            whenInputIs("[1,2]");
            outputMustBe(
                "[\n"
                " 1,\n"
                " 2\n"
                "]");
        }

    private:

        void whenInputIs(const char input[])
        {
            StringBuilder sb(buffer, sizeof(buffer));
            IndentedPrintDecorator decorator(sb);

            returnValue = decorator.print(input);
        }

        void outputMustBe(const char* expected)
        {
            Assert::AreEqual(expected, buffer);
            Assert::AreEqual(strlen(expected), returnValue);
        }
    };
}

Test array with 2 elements


#include "cardreader-t.h"
#include <QSignalSpy>

const QString TEST_CARDNUMBER = "1234_testcard";

void CardReaderTest::initTestCase()
{
	widget.installEventFilter(&cardReader);
}

void CardReaderTest::simulateRFIDReader()
{
	QSignalSpy spy(&cardReader, SIGNAL(newCardNumber(QString)));
	QVERIFY(spy.isValid());

	QTest::keyClicks(&widget, TEST_CARDNUMBER);
	QTest::keyClick(&widget, Qt::Key_Return);

	QCOMPARE(spy.count(), 1);

	QList<QVariant> arguments = spy.takeFirst();
	QCOMPARE(arguments.at(0).toString(), TEST_CARDNUMBER);
}

void CardReaderTest::simulateKeyboardInput()
{
	QSignalSpy spy(&cardReader, SIGNAL(newCardNumber(QString)));
	QVERIFY(spy.isValid());

	int keyTypingTime = CARDREADER_TIME_LIMIT_MS*1.0/((TEST_CARDNUMBER.size())*1.0);
	QTest::keyClicks(&widget, TEST_CARDNUMBER, Qt::NoModifier, keyTypingTime);
	QTest::keyClick(&widget, Qt::Key_Return);

	QCOMPARE(spy.count(), 0);
}

void CardReaderTest::simulateSecondRFIDReader()
{
	simulateRFIDReader();
}

QTEST_MAIN(CardReaderTest)

#include "cardreader-t.h"
#include <QSignalSpy>

const QString TEST_CARDNUMBER = "1234_testcard";

void CardReaderTest::initTestCase()
{
	widget.installEventFilter(&cardReader);
}

void CardReaderTest::simulateRFIDReader()
{
	QSignalSpy spy(&cardReader, SIGNAL(newCardNumber(QString)));
	QVERIFY(spy.isValid());

	QTest::keyClicks(&widget, TEST_CARDNUMBER);
	QTest::keyClick(&widget, Qt::Key_Return);

	QCOMPARE(spy.count(), 1);

	QList<QVariant> arguments = spy.takeFirst();
	QCOMPARE(arguments.at(0).toString(), TEST_CARDNUMBER);
}

void CardReaderTest::simulateKeyboardInput()
{
	QSignalSpy spy(&cardReader, SIGNAL(newCardNumber(QString)));
	QVERIFY(spy.isValid());

	int keyTypingTime = 50;
	QTest::keyClicks(&widget, TEST_CARDNUMBER, Qt::NoModifier, keyTypingTime);
	QTest::keyClick(&widget, Qt::Key_Return);

	QCOMPARE(spy.count(), 0);
}

void CardReaderTest::simulateSecondRFIDReader()
{
	simulateRFIDReader();
}

QTEST_MAIN(CardReaderTest)

Use 50 ms for key typing time in the card reader test instead of something based on the card reader limit constant, in order to detect that the card reader constant is mis-set.


// Return multiple values

#include <tuple>
#include <string>

std::tuple<int, bool, std::string> foo()
{
	return {128, true, "hello"};
}

int main()
{
	int obj1;
	bool obj2;
	std::string obj3;

	std::tie(obj1, obj2, obj3) = foo();
}

// Return multiple values of different types from a function.
//
// The `foo` function on [6-9] returns a
// [`std::tuple`](cpp/utility/tuple) representing multiple values
// of different types.
//
// On [17], the [`std::tie`](cpp/utility/tuple/tie) helper function
// ensures that each of the return values is assigned to each of the
// given objects. This approach only works if it is reasonable to
// declare the objects earlier.
//
// When we cannot use `std::tie`, we can simply
// store the resulting `std::tuple` object and use
// [`std::get`](cpp/utility/tuple/get) to get the values from it.

// Return multiple values

#include <tuple>

std::tuple<int, bool, float> foo()
{
	return {128, true, 1.5f};
}

int main()
{
	int obj1;
	bool obj2;
	float obj3;

	std::tie(obj1, obj2, obj3) = foo();
}

// Return multiple values of different types from a function.
//
// The `foo` function on [5-8] returns a
// [`std::tuple`](cpp/utility/tuple) representing multiple values
// of different types.
//
// On [16], we call this function and use [`std::tie`](cpp/utility/tuple/tie)
// to assign the return values to each of the given objects.
// If we cannot create the objects prior to this call, we can
// alternatively store the resulting `std::tuple` object and use
// [`std::get`](cpp/utility/tuple/get) to get the values from it.
//
// If the values are closely and logically related, consider composing
// them into a `struct` or `class`.

Rewrite return multiple values sample


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

#include "../lib/CodeGen/AsmPrinter/DIE.h"
#include "../lib/CodeGen/AsmPrinter/DIEHash.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Format.h"
#include "gtest/gtest.h"

namespace {

using namespace llvm;
TEST(DIEHashData1Test, DIEHash) {
  DIEHash Hash;
  DIE Die(dwarf::DW_TAG_base_type);
  DIEInteger Size(4);
  Die.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Size);
  uint64_t MD5Res = Hash.computeTypeSignature(&Die);
  ASSERT_TRUE(MD5Res == 0x540e9ff30ade3e4aULL);
}
}

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

#include "../lib/CodeGen/AsmPrinter/DIE.h"
#include "../lib/CodeGen/AsmPrinter/DIEHash.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Format.h"
#include "gtest/gtest.h"

using namespace llvm;

namespace {
TEST(DIEHashData1Test, DIEHash) {
  DIEHash Hash;
  DIE Die(dwarf::DW_TAG_base_type);
  DIEInteger Size(4);
  Die.addValue(dwarf::DW_AT_byte_size, dwarf::DW_FORM_data1, &Size);
  uint64_t MD5Res = Hash.computeTypeSignature(&Die);
  ASSERT_EQ(MD5Res, 0x540e9ff30ade3e4aULL);
}
}

Use ASSERT_EQ rather than ASSERT_TRUE for better unit test failures.


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

#include "chrome/common/default_plugin.h"

#include "chrome/default_plugin/plugin_main.h"
#include "webkit/plugins/npapi/plugin_list.h"

namespace chrome {

void RegisterInternalDefaultPlugin() {
#if defined(OS_WIN)
  // TODO(bauerb): On Windows the default plug-in can download and install
  // missing plug-ins, which we don't support in the browser yet, so keep
  // using the default plug-in on Windows until we do.
  const webkit::npapi::PluginEntryPoints entry_points = {
#if !defined(OS_POSIX) || defined(OS_MACOSX)
    default_plugin::NP_GetEntryPoints,
#endif
    default_plugin::NP_Initialize,
    default_plugin::NP_Shutdown
  };

  webkit::npapi::PluginList::Singleton()->RegisterInternalPlugin(
      FilePath(webkit::npapi::kDefaultPluginLibraryName),
      "Default Plug-in",
      "Provides functionality for installing third-party plug-ins",
      "*",
      entry_points);
#endif  // defined OS(WIN)
}

}  // namespace chrome

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

#include "chrome/common/default_plugin.h"

#include "chrome/default_plugin/plugin_main.h"
#include "webkit/plugins/npapi/plugin_list.h"

namespace chrome {

void RegisterInternalDefaultPlugin() {
#if defined(OS_WIN) && !defined(USE_AURA)
  // TODO(bauerb): On Windows the default plug-in can download and install
  // missing plug-ins, which we don't support in the browser yet, so keep
  // using the default plug-in on Windows until we do.
  // Aura isn't going to support NPAPI plugins.
  const webkit::npapi::PluginEntryPoints entry_points = {
#if !defined(OS_POSIX) || defined(OS_MACOSX)
    default_plugin::NP_GetEntryPoints,
#endif
    default_plugin::NP_Initialize,
    default_plugin::NP_Shutdown
  };

  webkit::npapi::PluginList::Singleton()->RegisterInternalPlugin(
      FilePath(webkit::npapi::kDefaultPluginLibraryName),
      "Default Plug-in",
      "Provides functionality for installing third-party plug-ins",
      "*",
      entry_points);
#endif
}

}  // namespace chrome

Disable the default plugin for aura


// Copyright 2017-2020 The Verible 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 "common/strings/display_utils.h"

#include <iostream>

namespace verible {

static constexpr absl::string_view kEllipses = "...";

std::ostream& operator<<(std::ostream& stream, const AutoTruncate& trunc) {
  const auto text = trunc.text;
  const auto length = text.length();
  if (length <= trunc.max_chars) return stream << text;
  const auto context_length = trunc.max_chars - kEllipses.length();
  const auto tail_length = context_length / 2;
  const auto head_length = context_length - tail_length;
  const auto tail_start = length - tail_length;
  return stream << text.substr(0, head_length) << kEllipses
                << text.substr(tail_start, tail_length);
}

}  // namespace verible

// Copyright 2017-2020 The Verible 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 "common/strings/display_utils.h"

#include <iostream>

namespace verible {

static constexpr absl::string_view kEllipses = "...";

std::ostream& operator<<(std::ostream& stream, const AutoTruncate& trunc) {
  const auto text = trunc.text;
  const int length = text.length();
  if (length <= trunc.max_chars) return stream << text;
  const auto context_length = trunc.max_chars - kEllipses.length();
  const auto tail_length = context_length / 2;
  const auto head_length = context_length - tail_length;
  const auto tail_start = length - tail_length;
  return stream << text.substr(0, head_length) << kEllipses
                << text.substr(tail_start, tail_length);
}

}  // namespace verible

Make sure to not compare signed with unsigned.


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

#include "views/focus/focus_manager.h"

#include "base/logging.h"

namespace views {

void FocusManager::ClearNativeFocus() {
  NOTIMPLEMENTED();
}

void FocusManager::FocusNativeView(gfx::NativeView native_view) {
  NOTIMPLEMENTED();
}

 // static
FocusManager* FocusManager::GetFocusManagerForNativeView(
    gfx::NativeView native_view) {
  NOTIMPLEMENTED();
}

}  // namespace views

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

#include "views/focus/focus_manager.h"

#include "base/logging.h"

namespace views {

void FocusManager::ClearNativeFocus() {
  NOTIMPLEMENTED();
}

void FocusManager::FocusNativeView(gfx::NativeView native_view) {
  NOTIMPLEMENTED();
}

 // static
FocusManager* FocusManager::GetFocusManagerForNativeView(
    gfx::NativeView native_view) {
  NOTIMPLEMENTED();
  return NULL;
}

}  // namespace views

Fix compilation error in the focus manager by returning NULL from unimplemented function.


// Copyright 2020 The XLS 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 "xls/common/init_xls.h"

#include "absl/flags/parse.h"
#include "xls/common/file/get_runfile_path.h"
#include "xls/common/logging/logging.h"

namespace xls {

std::vector<absl::string_view> InitXls(absl::string_view usage, int argc,
                                       char* argv[]) {
  // Copy the argv array to ensure this method doesn't clobber argv.
  std::vector<char*> arguments(argv, argv + argc);
  std::vector<char*> remaining = absl::ParseCommandLine(argc, argv);
  XLS_CHECK_GE(argc, 1);

  XLS_CHECK_OK(InitRunfilesDir(argv[0]));

  return std::vector<absl::string_view>(remaining.begin() + 1, remaining.end());
}

}  // namespace xls

// Copyright 2020 The XLS 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 "xls/common/init_xls.h"

#include "absl/flags/parse.h"
#include "xls/common/file/get_runfile_path.h"
#include "xls/common/logging/logging.h"

namespace xls {

std::vector<absl::string_view> InitXls(absl::string_view usage, int argc,
                                       char* argv[]) {
  // Copy the argv array to ensure this method doesn't clobber argv.
  std::vector<char*> arguments(argv, argv + argc);
  std::vector<char*> remaining = absl::ParseCommandLine(argc, argv);
  XLS_CHECK_GE(argc, 1);

  return std::vector<absl::string_view>(remaining.begin() + 1, remaining.end());
}

}  // namespace xls

Remove the execution of InitRunfilesDir from InitXls. The InitXLS assumes that an executable has Runfiles and is a Runfile marker. Moreover, as XLS moves to a bazel toolchain implementation, toolchain executables are not a runfile or a runfile marker.


#########################################################
#		Local Compiler Rules			#
#########################################################

#--objectrule--#	$(CXX) $(CFLAGS) $(CDEFS) $(CINCS) -o $@ -c
#--objectsuffix--#	$B
#--targetsuffix--#	$B
#--tarulesuffix--#	$B
#--buildtargets--#	targets

.SUFFIXES :

B	=
%-dbg 	: B = -dbg

D	=
%-dbg 	: D = /dbg

CDEFS	=  -DVisionBuild
CINCS	=
CBASE	= -fexceptions -frtti -Wno-trigraphs -Wno-undefined-bool-conversion
CDBG	= -g
CREL	= -O2
CVER	= ${CREL}

CFLAGS	= ${CVER} ${CBASE}

LINKER	= VLINK-CC
LBASE	=
LIBASE	= ${LOCALLIBS} -lpthread
LIBS	= ${LBASE} -c -L../lib$D ${LIBASE}

release : targets

debug : targets-dbg

targets-dbg :
	@$(MAKE) B=-dbg D=/dbg CVER=${CDBG} targets

clean-dbg :
	@$(MAKE) B=-dbg D=/dbg clean

clean-all : clean clean-dbg

#########################################################
#		Local Compiler Rules			#
#########################################################

#--objectrule--#	$(CXX) $(CFLAGS) $(CDEFS) $(CINCS) -o $@ -c
#--objectsuffix--#	$B
#--targetsuffix--#	$B
#--tarulesuffix--#	$B
#--buildtargets--#	targets

.SUFFIXES :

B	=
%-dbg 	: B = -dbg

D	=
%-dbg 	: D = /dbg

CDEFS	=  -DVisionBuild
CINCS	=
CBASE	= -fexceptions -frtti -Wno-trigraphs -Wno-undefined-bool-conversion -Wno-format -Wno-logical-op-parentheses -Wno-switch -Wno-shift-op-parentheses -Wno-shift-negative-value -Wno-parentheses
CDBG	= -g
CREL	= -O2
CVER	= ${CREL}

CFLAGS	= ${CVER} ${CBASE}

LINKER	= VLINK-CC
LBASE	=
LIBASE	= ${LOCALLIBS} -lpthread
LIBS	= ${LBASE} -L../lib$D ${LIBASE}

release : targets

debug : targets-dbg

targets-dbg :
	@$(MAKE) B=-dbg D=/dbg CVER=${CDBG} targets

clean-dbg :
	@$(MAKE) B=-dbg D=/dbg clean

clean-all : clean clean-dbg

Adjust compiler options used to build Mac executables.


#include "AppViewController.h"

namespace mural
{

AppViewController::~AppViewController()
{
    delete this->view;
}

void AppViewController::initWithScriptAtPath(const char *path, int width, int height, const char *title)
{
    this->view = new JavaScriptView(width, height, title);
    this->view->loadScriptAtPath(path);
    this->view->startRunning();
}

}

#include "AppViewController.h"

// #include <thread>

namespace mural
{

AppViewController::~AppViewController()
{
    delete this->view;
}

void AppViewController::initWithScriptAtPath(const char *path, int width, int height, const char *title)
{
    this->view = new JavaScriptView(width, height, title);
    this->view->loadScriptAtPath(path);
    // Test MuOperationQueue
    // this->view->backgroundQueue.addOperation([] {
    //     printf("[Test]: Operation 'A' starts running, this should be long (1000ms)\n");
    //     std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    //     printf("[Test]: Operation 'A' finished\n");
    // });
    // this->view->backgroundQueue.addOperation([] {
    //     printf("[Test]: Operation 'B' just fired\n");
    // });
    this->view->startRunning();
}

}

Add some simple tests to check whether the operation-queue works


// REQUIRES: x86-registered-target,x86-64-registered-target
// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -S %s -o %t-64.s
// RUN: FileCheck -check-prefix CHECK-LP64 --input-file=%t-64.s %s
// RUN: %clang_cc1 -triple i386-apple-darwin -std=c++11 -S %s -o %t-32.s
// RUN: FileCheck -check-prefix CHECK-LP32 --input-file=%t-32.s %s

struct A {
  A(int);
};

struct B {
  B(A);
};

int main () {
  (B)10;
  B(10);
  static_cast<B>(10);
}

// CHECK-LP64: callq    __ZN1AC1Ei
// CHECK-LP64: callq    __ZN1BC1E1A
// CHECK-LP64: callq    __ZN1AC1Ei
// CHECK-LP64: callq    __ZN1BC1E1A
// CHECK-LP64: callq    __ZN1AC1Ei
// CHECK-LP64: callq    __ZN1BC1E1A

// CHECK-LP32: calll     L__ZN1AC1Ei
// CHECK-LP32: calll     L__ZN1BC1E1A
// CHECK-LP32: calll     L__ZN1AC1Ei
// CHECK-LP32: calll     L__ZN1BC1E1A
// CHECK-LP32: calll     L__ZN1AC1Ei
// CHECK-LP32: calll     L__ZN1BC1E1A

// RUN: %clang_cc1 -triple x86_64-apple-darwin -std=c++11 -emit-llvm %s -o - | \
// RUN: FileCheck %s
// RUN: %clang_cc1 -triple i386-apple-darwin -std=c++11 -emit-llvm %s -o - |   \
// RUN: FileCheck %s

struct A {
  A(int);
};

struct B {
  B(A);
};

int main () {
  (B)10;
  B(10);
  static_cast<B>(10);
}

// CHECK: call void @_ZN1AC1Ei
// CHECK: call void @_ZN1BC1E1A
// CHECK: call void @_ZN1AC1Ei
// CHECK: call void @_ZN1BC1E1A
// CHECK: call void @_ZN1AC1Ei
// CHECK: call void @_ZN1BC1E1A

Check IR in this test.


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

#include "Game.h"
#include "Shell.h"

#if (defined(_MSC_VER) && _MSC_VER < 1900 /*vs2015*/) ||                       \
    defined MINGW_HAS_SECURE_API
#include <basetsd.h>
#define snprintf sprintf_s
#endif

void Game::print_stats() {
    // Output frame count and measured elapsed time
    auto now = std::chrono::system_clock::now();
    auto elapsed = now - start_time;
    auto elapsed_millis =
        std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
    char msg[256];
    snprintf(msg, 255, "frames:%d, elapsedms:%ld", frame_count, elapsed_millis);
    shell_->log(Shell::LogPriority::LOG_INFO, msg);
}

void Game::quit() {
    print_stats();
    shell_->quit();
}

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

#include <sstream>

#include "Game.h"
#include "Shell.h"

void Game::print_stats() {
    // Output frame count and measured elapsed time
    auto now = std::chrono::system_clock::now();
    auto elapsed = now - start_time;
    auto elapsed_millis =
        std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
    std::stringstream ss;
    ss << "frames:" << frame_count << ", elapsedms:" << elapsed_millis;
    shell_->log(Shell::LogPriority::LOG_INFO, ss.str().c_str());
}

void Game::quit() {
    print_stats();
    shell_->quit();
}

Fix compiler warning in smoketest


// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Rosetta/Commons/Constants.hpp>
#include <Rosetta/Models/Graveyard.hpp>

namespace RosettaStone
{
Graveyard::Graveyard()
{
    m_cards.reserve(START_DECK_SIZE);
}

Player& Graveyard::GetOwner() const
{
    return *m_owner;
}

void Graveyard::SetOwner(Player& owner)
{
    m_owner = &owner;
}

void Graveyard::AddCard(Entity& card)
{
    m_cards.emplace_back(&card);
}
}  // namespace RosettaStone

// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Rosetta/Commons/Constants.hpp>
#include <Rosetta/Models/Enchantment.hpp>
#include <Rosetta/Models/Graveyard.hpp>

namespace RosettaStone
{
Graveyard::Graveyard()
{
    m_cards.reserve(START_DECK_SIZE);
}

Player& Graveyard::GetOwner() const
{
    return *m_owner;
}

void Graveyard::SetOwner(Player& owner)
{
    m_owner = &owner;
}

void Graveyard::AddCard(Entity& card)
{
    m_cards.emplace_back(&card);

    int enchantSize = static_cast<int>(card.appliedEnchantments.size());
    for (int i = enchantSize - 1; i >= 0; --i)
    {
        card.appliedEnchantments[i]->Remove();
    }
}
}  // namespace RosettaStone

Add code to remove applied enchantments


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

#define MAX_INPUT_SIZE 100

bool is_palindrome(const char *string, const int begin = 0, int end = -1)
{
    /* initialise parameter */
    if(end == -1) end = strlen(string) - 1;

    /* base case */
    if(string[begin] != string[end]) return false;
    if(begin >= end) return true;

    /* recursive case */
    return is_palindrome(string, begin + 1, end - 1);
}

int main(void)
{
    printf("palindrome checker\n");

    char word[MAX_INPUT_SIZE];
    printf("Enter word= "); scanf("%s", word);

    printf("%s is %spalindrome.\n", word, is_palindrome(word) ? "" : "not " );
    return 0;
}

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

#define MAX_INPUT_SIZE 100

bool is_palindrome(const char *word)
{
    int length = strlen(word);
    char string[length]; /* Should not modify the value of ptr arg. */
    strcpy(string, word);

    /* base case */
    if(length <= 1) return true;
    if(string[0] != string[length - 1]) return false;

    /* recursive case */
    string[length - 1] = '\0';
    return is_palindrome(string + 1);
}

int main(void)
{
    printf("palindrome checker\n");

    char word[MAX_INPUT_SIZE];
    printf("Enter word= "); scanf("%s", word);

    printf("%s is %spalindrome.\n", word, is_palindrome(word) ? "" : "not " );
    return 0;
}

Adjust string directly instead of using index of the array


// RUN: CINDEXTEST_EDITING=1 c-index-test -test-load-source local %s -Wuninitialized -Werror=unused 2>&1 | FileCheck -check-prefix=DIAGS %s

// Make sure -Wuninitialized works even though the header had a warn-as-error occurrence.

// DIAGS: error: unused variable 'x'
// DIAGS: warning: variable 'x1' is uninitialized
// DIAGS-NOT: error: use of undeclared identifier
// DIAGS: warning: variable 'x1' is uninitialized

#include "pch-warn-as-error-code-split.h"

void test() {
  int x1; // expected-note {{initialize}}
  int x2 = x1; // expected-warning {{uninitialized}}
  (void)x2;
  foo_head();
}

// RUN: env CINDEXTEST_EDITING=1 c-index-test -test-load-source local %s -Wuninitialized -Werror=unused 2>&1 | FileCheck -check-prefix=DIAGS %s

// Make sure -Wuninitialized works even though the header had a warn-as-error occurrence.

// DIAGS: error: unused variable 'x'
// DIAGS: warning: variable 'x1' is uninitialized
// DIAGS-NOT: error: use of undeclared identifier
// DIAGS: warning: variable 'x1' is uninitialized

#include "pch-warn-as-error-code-split.h"

void test() {
  int x1; // expected-note {{initialize}}
  int x2 = x1; // expected-warning {{uninitialized}}
  (void)x2;
  foo_head();
}

Add 'env' to fix test failures in windows bots.


#include "host-interface.hpp"

namespace phosphor
{
namespace host
{

void Host::execute(Command command)
{
    // Future commits to build on
    return;
}

} // namespace host
} // namepsace phosphor

#include <queue>
#include <phosphor-logging/log.hpp>
#include "host-interface.hpp"

namespace phosphor
{
namespace host
{

using namespace phosphor::logging;

// When you see base:: you know we're referencing our base class
namespace base = sdbusplus::xyz::openbmc_project::Control::server;

std::queue<base::Host::Command> workQueue{};

void Host::execute(base::Host::Command command)
{
    log<level::INFO>("Pushing cmd on to queue",
            entry("CONTROL_HOST_CMD=%s",
                  convertForMessage(command)));
    workQueue.push(command);
    return;
}

} // namespace host
} // namepsace phosphor

Support for putting entries onto queue


// RUN: %clang_cc1 -fsyntax-only -Wno-dangling -Wreturn-stack-address -verify %s

struct [[gsl::Owner(int)]] MyIntOwner {
  MyIntOwner();
  int &operator*();
};

struct [[gsl::Pointer(int)]] MyIntPointer {
  MyIntPointer(int *p = nullptr);
  MyIntPointer(const MyIntOwner &);
  int &operator*();
  MyIntOwner toOwner();
};

int &f() {
  int i;
  return i; // expected-warning {{reference to stack memory associated with local variable 'i' returned}}
}

MyIntPointer g() {
  MyIntOwner o;
  return o; // No warning, it is disabled.
}

// RUN: %clang_cc1 -fsyntax-only -Wno-dangling-gsl -Wreturn-stack-address -verify %s

struct [[gsl::Owner(int)]] MyIntOwner {
  MyIntOwner();
  int &operator*();
};

struct [[gsl::Pointer(int)]] MyIntPointer {
  MyIntPointer(int *p = nullptr);
  MyIntPointer(const MyIntOwner &);
  int &operator*();
  MyIntOwner toOwner();
};

int &f() {
  int i;
  return i; // expected-warning {{reference to stack memory associated with local variable 'i' returned}}
}

MyIntPointer g() {
  MyIntOwner o;
  return o; // No warning, it is disabled.
}

Fix a test to test what the name suggest.


/**
 ** \file libport/perror.cc
 ** \brief perror: implements file libport/perror.hh
 */

#include <stdio.h>

#include "libport/cstring"

namespace libport
{

  void
  perror (const char* s)
  {
#ifndef WIN32
    ::perror(s);
#else
    int errnum;
    const char* errstring;
    const char* colon;

    errnum = WSAGetLastError();
    errstring = strerror(errnum);

    if (s == NULL || *s == '\0')
      s = colon = "";
    else
      colon = ": ";

    std::cerr << s << colon << errstring << std::endl;
#endif
  }

}

/**
 ** \file libport/perror.cc
 ** \brief perror: implements file libport/perror.hh
 */

#include <cstdio>
#include <iostream>

#include "libport/cstring"

namespace libport
{

  void
  perror (const char* s)
  {
#ifndef WIN32
    ::perror(s);
#else
    int errnum;
    const char* errstring;
    const char* colon;

    errnum = WSAGetLastError();
    errstring = strerror(errnum);

    if (s == NULL || *s == '\0')
      s = colon = "";
    else
      colon = ": ";

    std::cerr << s << colon << errstring << std::endl;
#endif
  }

}

Add missing include and change existing include


#include "Timer.h"

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

#include <string>
#include <iostream>

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

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

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

#include "Timer.h"

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

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

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

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

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

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

Fix failure of the Timer unit test.


#include <iostream>
#include "../src/tisys.hpp"

int main(int argc, char** argv){
	cout << "Example" <<endl;
	Filesystem fs;

	if ( argc == 1 )
		fs.listdir(".");
	else
		fs.listdir( argv[1] );

	cout << fs;
	return 0;
}

#include <iostream>
#include "../src/tisys.hpp"

using namespace std;

int main(int argc, char** argv){
	cout << "Example" <<endl;
	Filesystem fs;

	if ( argc == 1 )
		fs.listdir(".");
	else
		fs.listdir( argv[1] );

	cout << fs;
	return 0;
}

Put the using namespace std in the cpp files


/// \file Connector_RAW/main.cpp
/// Contains the main code for the RAW connector.

#include <iostream>
#include "../util/socket.h"

/// Contains the main code for the RAW connector.
/// Expects a single commandline argument telling it which stream to connect to,
/// then outputs the raw stream to stdout.
int main(int argc, char  ** argv) {
  if (argc < 2){
    std::cout << "Usage: " << argv[0] << " stream_name" << std::endl;
    return 1;
  }
  std::string input = "/tmp/shared_socket_";
  input += argv[1];
  //connect to the proper stream
  Socket::Connection S(input);
  if (!S.connected()){
    std::cout << "Could not open stream " << argv[1] << std::endl;
    return 1;
  }
  //transport ~50kb at a time
  //this is a nice tradeoff between CPU usage and speed
  char buffer[50000];
  while(std::cout.good() && S.read(buffer,50000)){std::cout.write(buffer,50000);}
  S.close();
  return 0;
}

/// \file Connector_RAW/main.cpp
/// Contains the main code for the RAW connector.

#include <iostream>
#include "../util/socket.h"

/// Contains the main code for the RAW connector.
/// Expects a single commandline argument telling it which stream to connect to,
/// then outputs the raw stream to stdout.
int main(int argc, char  ** argv) {
  if (argc < 2){
    std::cout << "Usage: " << argv[0] << " stream_name" << std::endl;
    return 1;
  }
  std::string input = "/tmp/shared_socket_";
  input += argv[1];
  //connect to the proper stream
  Socket::Connection S(input);
  if (!S.connected()){
    std::cout << "Could not open stream " << argv[1] << std::endl;
    return 1;
  }
  //transport ~50kb at a time
  //this is a nice tradeoff between CPU usage and speed
  const char buffer[50000] = {0};
  while(std::cout.good() && S.read(buffer,50000)){std::cout.write(buffer,50000);}
  S.close();
  return 0;
}

Fix compiling of DTSC version branch.


// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"

#include "App/Factories/AdditionNFDelegate.h"
#include "App/Factories/ConstantNFDelegate.h"
#include "App/Factories/PrinterNFDelegate.h"
#include "App/Factories/TextFileNFDelegate.h"

// Qt.
#include <QApplication>

QString titleString()
{
    QString name = QString::fromStdString(App::appName());
    QString version = QString::fromStdString(App::appVersion());
    return QString("%1 - v%2").arg(name).arg(version);
}

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

    App app;
    app.addNodeFactory(new AdditionNFDelegate);
    app.addNodeFactory(new ConstantNFDelegate);
    app.addNodeFactory(new PrinterNFDelegate);
    app.addNodeFactory(new TextFileNFDelegate);

    MainWindow w(&app);
    w.setWindowTitle(titleString());
    w.setMinimumSize(800, 600);
    w.show();

    app.setUI(&w);
    app.setDelegate(&w);

    return a.exec();
}

// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"

#include "App/Factories/AdditionNFDelegate.h"
#include "App/Factories/ConstantNFDelegate.h"
#include "App/Factories/PrinterNFDelegate.h"
#include "App/Factories/TextFileNFDelegate.h"

#include "System/QtBasedFileSystem.h"

// Qt.
#include <QApplication>

QString titleString()
{
    QString name = QString::fromStdString(App::appName());
    QString version = QString::fromStdString(App::appVersion());
    return QString("%1 - v%2").arg(name).arg(version);
}

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

    QtBasedFileSystem file_system;

    App app(&file_system);
    app.addNodeFactory(new AdditionNFDelegate);
    app.addNodeFactory(new ConstantNFDelegate);
    app.addNodeFactory(new PrinterNFDelegate);
    app.addNodeFactory(new TextFileNFDelegate);

    MainWindow w(&app);
    w.setWindowTitle(titleString());
    w.setMinimumSize(800, 600);
    w.show();

    app.setUI(&w);
    app.setDelegate(&w);

    return a.exec();
}

Use Qt based file system in App.


#include <QApplication>
#include <QTranslator>

#include <qtsingleapplication.h>

#include <Manager.h>
#include <Settings.h>

int main (int argc, char *argv[]) {
  QtSingleApplication a (argc, argv);
  if (a.sendMessage (QString ())) {
    return 0;
  }
  a.setQuitOnLastWindowClosed (false);
  a.setApplicationName (settings_values::appName);
  a.setOrganizationName (settings_values::companyName);

  QTranslator translator;
  // Set default to english.
  if (translator.load (QLocale::system (), "translation", "_", ":/translations") ||
      translator.load (":/translations/translation_en")) {
    a.installTranslator (&translator);
  }

  Manager manager;

  return a.exec ();
}

#ifdef Q_OS_LINUX
#  include <locale.h>
#endif

#include <QApplication>
#include <QTranslator>

#include <qtsingleapplication.h>

#include <Manager.h>
#include <Settings.h>

int main (int argc, char *argv[]) {
  QtSingleApplication a (argc, argv);
  if (a.sendMessage (QString ())) {
    return 0;
  }
#ifdef Q_OS_LINUX
  setlocale (LC_NUMERIC, "C");
#endif
  a.setQuitOnLastWindowClosed (false);
  a.setApplicationName (settings_values::appName);
  a.setOrganizationName (settings_values::companyName);

  QTranslator translator;
  // Set default to english.
  if (translator.load (QLocale::system (), "translation", "_", ":/translations") ||
      translator.load (":/translations/translation_en")) {
    a.installTranslator (&translator);
  }

  Manager manager;

  return a.exec ();
}

Set numeric locale to C for proper tesseract-orc-* packages work on linux.


// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"

#include "App/Factories/PrinterNFDelegate.h"
#include "App/Factories/TextFileNFDelegate.h"

#include "System/QtBasedFileSystem.h"

// Qt.
#include <QApplication>

QString titleString()
{
    QString name = QString::fromStdString(App::appName());
    QString version = QString::fromStdString(App::appVersion());
    return QString("%1 - v%2").arg(name).arg(version);
}

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

    QtBasedFileSystem file_system;

    App app(&file_system);
    app.addNodeFactory(new PrinterNFDelegate);
    app.addNodeFactory(new TextFileNFDelegate);
    app.loadScriptNodes("Nodin/NodeScripts/Lua");

    MainWindow w(&app);
    w.setWindowTitle(titleString());
    w.setMinimumSize(800, 600);
    w.show();

    app.setUI(&w);
    app.setDelegate(&w);

    return a.exec();
}

// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"

#include "App/Factories/TextFileNFDelegate.h"

#include "System/QtBasedFileSystem.h"

// Qt.
#include <QApplication>

QString titleString()
{
    QString name = QString::fromStdString(App::appName());
    QString version = QString::fromStdString(App::appVersion());
    return QString("%1 - v%2").arg(name).arg(version);
}

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

    QtBasedFileSystem file_system;

    App app(&file_system);
    app.addNodeFactory(new TextFileNFDelegate);
    app.loadScriptNodes("Nodin/NodeScripts/Lua");

    MainWindow w(&app);
    w.setWindowTitle(titleString());
    w.setMinimumSize(800, 600);
    w.show();

    app.setUI(&w);
    app.setDelegate(&w);

    return a.exec();
}

Remove PrinterNFDelegate, has become redundant due to logger Lua node.


#include <ncurses.h>
#include "ev3dev.h"

using namespace ev3dev;

int main() {
	int inputKey;

	const int KEY_A = 97;
	const int KEY_S = 115;
	const int KEY_D = 100;
	const int KEY_F = 102;
	const int KEY_Q = 113;
	const int KEY_R = 114;

	initscr();
	raw();
	mvprintw(1,2,"Hello world :) Press Q to quit. ");

	noecho();
	inputKey = getch();

	while(inputKey != KEY_Q) {
		printw("[KEY #%i PRESSED] ", inputKey);

		if (inputKey == KEY_R) {
			sound::beep();

		}else if (inputKey == KEY_A) {
			sound::tone(262,180);
		}else if (inputKey == KEY_S) {
			sound::tone(392,180);
		}else if (inputKey == KEY_D) {
			sound::tone(440,180);
		}else if (inputKey == KEY_F) {
			sound::tone(262,400);
		}

		inputKey = getch();
	}

	endwin();
	return 0;
}

#include <ncurses.h>
#include "ev3dev.h"

using namespace ev3dev;

int main() {
	int inputKey;

	const int KEY_A = 97;
	const int KEY_S = 115;
	const int KEY_D = 100;
	const int KEY_F = 102;
	const int KEY_Q = 113;
	const int KEY_R = 114;

	initscr();
	raw();
	keypad(stdscr, TRUE);
	mvprintw(1,2,"Hello world :) Press Q to quit. ");

	noecho();
	inputKey = getch();

	while(inputKey != KEY_Q) {
		printw("[KEY #%i PRESSED] ", inputKey);

		if (inputKey == KEY_R) {
			sound::beep();

		}else if (inputKey == KEY_A) {
			sound::tone(262,180);
		}else if (inputKey == KEY_S) {
			sound::tone(392,180);
		}else if (inputKey == KEY_D) {
			sound::tone(440,180);
		}else if (inputKey == KEY_F) {
			sound::tone(262,400);
		}

		inputKey = getch();
	}

	endwin();
	return 0;
}

Enable function and arrow keys


/*
 * Copyright 2013 Kamil Michalak <kmichalak8@gmail.com>
 *
 * 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 <stdlib.h>
#include <iostream>

using namespace std;

int main(int argc, char **argv)
{
	char* home_dir = getenv("HOME");
	cout << home_dir << endl;
	return 0;
}

/*
 * Copyright 2013 Kamil Michalak <kmichalak8@gmail.com>
 *
 * 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 <iostream>
#include <getopt.h>

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

 	static struct option long_options[] = {
 		{"config", 1, 0, 'c'},
		{"query", 0, 0, 'q'},
 		{NULL, 0, NULL, 0}
 	};

	int option_index = 0;
	while ((arg_char = getopt_long(argc, argv, "c:", long_options, &option_index)) != -1)
		switch (arg_char)
		{
			case 0:
				std::cout << long_options[option_index].name << std::endl;
			case 'c':
				std::cout << "configuration" << std::endl;
				if (optarg)
					std::cout << " with arguments: " << optarg << std::endl;
				std::cout << argv[optind] << std::endl;
				break;
			case 'q':
				std::cout << "query" << std::endl;
				break;
			default:
				std::cout << arg_char << std::endl;
				if (optarg)
					std::cout << " with arguments: " << optarg << std::endl;
		}

	return 0;
}

Add basic skeleton for command line arguments parsing mechanism


/* * This file is part of meego-im-framework *
 *
 * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * Contact: Nokia Corporation (directui@nokia.com)
 *
 * If you have questions regarding the use of this file, please contact
 * Nokia at directui@nokia.com.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "mainwindow.h"

#include <QtCore>
#include <QtGui>

#include <cstdlib>

int main(int argc, char** argv)
{
    // Set input method to MInputContext
#ifdef HAVE_LEGACY_NAMES
    setenv("QT_IM_MODULE", "MInputContext", 1);
#else
    setenv("QT_IM_MODULE", "Maliit", 1);
#endif

    QApplication kit(argc, argv);

    MainWindow window;
    return kit.exec();
}

/* * This file is part of meego-im-framework *
 *
 * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * Contact: Nokia Corporation (directui@nokia.com)
 *
 * If you have questions regarding the use of this file, please contact
 * Nokia at directui@nokia.com.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "mainwindow.h"

#include <QtCore>
#include <QtGui>

#include <cstdlib>

int main(int argc, char** argv)
{
    // Set input method to MInputContext
#ifdef HAVE_LEGACY_NAMES
    setenv("QT_IM_MODULE", "MInputContext", 1);
#else
    setenv("QT_IM_MODULE", "Maliit", 1);
#endif

    QApplication kit(argc, argv);

#ifdef Q_WS_QPA
    // Workaround for lighthouse Qt
    kit.setInputContext(QInputContextFactory::create("Maliit", &kit));
#endif

    MainWindow window;
    return kit.exec();
}

Add workaround for QT Lighthouse to example.


# include "broker2broker.hpp"
# include <sstream>
#include <sys/socket.h>

/**
 * @brief Initialize an outgoing message of SNDMSG type.
 */
MessageForB2B::MessageForB2B(const chattp::ChattpMessage& mesg, const string& channel_id)
{
    message_buffer.set_sequence_number(b2b_counter.get());
    *(message_buffer.mutable_mesg()) = mesg;
    message_buffer.set_channel_id(channel_id);
    message_buffer.set_type(B2BMessage::SENDMESSAGE);
}

/**
 * @brief Initialize an outgoing message of MSGSNT type.
 */
MessageForB2B::MessageForB2B(sequence_t seq_num, bool status)
{
    message_buffer.set_type(B2BMessage::MESSAGESENT);
    message_buffer.set_status(status);
}

B2BIncoming::B2BIncoming(const char* buffer, size_t length, const string& origin_b)
    : origin_broker(origin_b)
{
    message_buffer.ParseFromArray(buffer,length);
}

# include "broker2broker.hpp"
# include <sstream>
#include <sys/socket.h>

/**
 * @brief Initialize an outgoing message of SNDMSG type.
 */
MessageForB2B::MessageForB2B(const chattp::ChattpMessage& mesg, const string& channel_id)
{
    message_buffer.set_sequence_number(b2b_counter.get());
    *(message_buffer.mutable_mesg()) = mesg;
    message_buffer.set_channel_id(channel_id);
    message_buffer.set_type(B2BMessage::SENDMESSAGE);
}

/**
 * @brief Initialize an outgoing message of MSGSNT type.
 */
MessageForB2B::MessageForB2B(sequence_t seq_num, bool status)
{
    message_buffer.set_sequence_number(seq_num);
    message_buffer.set_type(B2BMessage::MESSAGESENT);
    message_buffer.set_status(status);
}

B2BIncoming::B2BIncoming(const char* buffer, size_t length, const string& origin_b)
    : origin_broker(origin_b)
{
    message_buffer.ParseFromArray(buffer,length);
}

Initialize sequence_number field for MESSAGESENT messages!


#include <QApplication>
#include <QSettings>
#include <QLocale>
#include <QTranslator>
#include <QLibraryInfo>

#include "trayicon.h"

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QApplication::setOrganizationName("Restnotifier");
    app.setQuitOnLastWindowClosed(false);

    // Set language
    QSettings settings;
    QString lang;
    QTranslator translator, qtTranslator;
    if (settings.contains("lang"))
        lang = settings.value("lang").toString();
    else
        lang = QLocale::languageToString(QLocale::system().language());
    if (lang == "ru")
    {
        QLocale::setDefault(QLocale("ru_RU"));

        // install qt translator
        qtTranslator.load("qt_" + QLocale().name(),
            QLibraryInfo::location(QLibraryInfo::TranslationsPath));
        app.installTranslator(&qtTranslator);

        // install app translator
        translator.load("restnotifier_ru_RU");
        app.installTranslator(&translator);
    }

    TrayIcon *trayIcon = new TrayIcon();
    trayIcon->show();
    QObject::connect(trayIcon, SIGNAL(quitScheduled()), &app, SLOT(quit()));
    int code = app.exec();
    delete trayIcon;
    return code;
}

#include <QApplication>
#include <QSettings>
#include <QLocale>
#include <QTranslator>
#include <QLibraryInfo>

#include "trayicon.h"

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QApplication::setOrganizationName("Restnotifier");
    app.setQuitOnLastWindowClosed(false);

    // Set language
    QSettings settings;
    QString lang;
    QTranslator translator, qtTranslator;
    if (settings.contains("lang"))
        lang = settings.value("lang").toString();
    else
        lang = QLocale::languageToString(QLocale::system().language());
    if (lang == "ru")
    {
        QLocale::setDefault(QLocale("ru_RU"));

        // install qt translator
#if defined Q_WS_X11
        const QString loc = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
#elif defined Q_WS_WIN
        const QString loc();
#endif
        qtTranslator.load("qt_" + QLocale().name(), loc);
        app.installTranslator(&qtTranslator);

        // install app translator
        translator.load("restnotifier_ru_RU");
        app.installTranslator(&translator);
    }

    TrayIcon *trayIcon = new TrayIcon();
    trayIcon->show();
    QObject::connect(trayIcon, SIGNAL(quitScheduled()), &app, SLOT(quit()));
    int code = app.exec();
    delete trayIcon;
    return code;
}

Fix qt translation files path on Windows


#include "./transfer_function.h"
#include <QLoggingCategory>
#include <stdexcept>
#include "./texture_manager.h"
#include "../utils/gradient_utils.h"

namespace Graphics
{

// QLoggingCategory tfChan("Graphics.TransferFunction");

TransferFunction::TransferFunction(
    std::shared_ptr<TextureManager> textureManager, std::string path)
  : textureManager(textureManager)
{

  auto image =
      GradientUtils::loadGradientAsImage(QString(path.c_str()), QSize(512, 1));
  texture = textureManager->addTexture(&image);
}

TransferFunction::~TransferFunction()
{
}

}  // namespace Graphics

#include "./transfer_function.h"
#include <QLoggingCategory>
#include <stdexcept>
#include "./texture_manager.h"
#include "../utils/gradient_utils.h"

namespace Graphics
{

// QLoggingCategory tfChan("Graphics.TransferFunction");

TransferFunction::TransferFunction(
    std::shared_ptr<TextureManager> textureManager, std::string path)
  : textureManager(textureManager)
{

  auto vector = GradientUtils::loadGradientAsFloats(QString(path.c_str()), 512);
  texture = textureManager->addTexture(vector.data(), 512, 1);
}

TransferFunction::~TransferFunction()
{
}

}  // namespace Graphics

Load gradient as floats and create float texture.


#include <strong_types.hpp>

namespace st = strong_types;

// Create a type that counts number of cycles
struct cycle_count : st::type<cycle_count, int> {
  // inherit the base class's constructors
  using type::type;
};

// Create a type that counts number of instructions
struct instruction_count : st::type<instruction_count, int> {
  using type::type;
};

// Create a type for frequencies (hertz)
struct frequency : st::type<frequency, double> {
  using type::type;
};

int main() {
  cycle_count cycles(50);
  instruction_count instructions(10000);
  frequency clock_rate(2.6);

  return 0;
}

#include <strong_types.hpp>

namespace st = strong_types;

// Create a type that counts number of cycles
struct cycle_count : st::type<cycle_count, int> {
  // inherit the base class's constructors
  using type::type;
};

// Create a type that counts number of instructions
struct instruction_count : st::type<instruction_count, int> {
  using type::type;
};

// Create a type for frequencies (hertz)
struct frequency : st::type<frequency, double> {
  using type::type;
};

// Create a type for periods (inverse of frequency)
struct period : st::type<period, double> {
  using type::type;
};

// Calculate the period given a frequency
constexpr period inverse(frequency const & hertz)
{
  return period(1.0 / static_cast<double>(hertz));
}

int main() {
  cycle_count cycles(50);
  instruction_count instructions(10000);
  frequency clock_rate(2.6);
  period p = inverse(clock_rate);

  return 0;
}

Add inverse of frequency type


#include "fisx_detector.h"
#include <math.h>
#include <stdexcept>

Detector::Detector(const std::string & name, const double & density, const double & thickness, \
                  const double & funnyFactor): Layer(name, density, thickness, funnyFactor)
{
    this->diameter =  0.0;
    this->distance = 10.0;
}

double Detector::getActiveArea() const
{
    double pi;
    pi = acos(-1.0);
    return (0.5 * pi) * (this->diameter * this->diameter);
}

void Detector::setActiveArea(const double & area)
{
    double pi;
    pi = acos(-1.0);
    if (area < 0)
    {
        throw std::invalid_argument("Negative detector area");
    }
    this->diameter = sqrt(area/(0.5 * pi));
}

void Detector::setDiameter(const double & diameter)
{
    if (diameter < 0)
    {
        throw std::invalid_argument("Negative detector diameter");
    }
    this->diameter = diameter;
}

void Detector::setDistance(const double & distance)
{
    if (distance <= 0)
    {
        throw std::invalid_argument("Negative detector distance");
    }
    this->distance = distance;
}

const double & Detector::getDiameter() const
{
    return this->diameter;
}

const double & Detector::getDistance() const
{
    return this->distance;
}

#include "fisx_detector.h"
#include <math.h>
#include <stdexcept>

Detector::Detector(const std::string & name, const double & density, const double & thickness, \
                  const double & funnyFactor): Layer(name, density, thickness, funnyFactor)
{
    this->diameter =  0.0;
    this->distance = 10.0;
}

double Detector::getActiveArea() const
{
    double pi;
    pi = acos(-1.0);
    return (0.25 * pi) * (this->diameter * this->diameter);
}

void Detector::setActiveArea(const double & area)
{
    double pi;
    pi = acos(-1.0);
    if (area < 0)
    {
        throw std::invalid_argument("Negative detector area");
    }
    this->diameter = 2.0 * sqrt(area/pi);
}

void Detector::setDiameter(const double & diameter)
{
    if (diameter < 0)
    {
        throw std::invalid_argument("Negative detector diameter");
    }
    this->diameter = diameter;
}

void Detector::setDistance(const double & distance)
{
    if (distance <= 0)
    {
        throw std::invalid_argument("Negative detector distance");
    }
    this->distance = distance;
}

const double & Detector::getDiameter() const
{
    return this->diameter;
}

const double & Detector::getDistance() const
{
    return this->distance;
}

Correct area and diameter calculations.


#include <mantella_bits/helper/unorderedContainer.hpp>

// C++ standard library
#include <functional>

namespace mant {
  arma::uword Hash::operator()(
      const arma::Col<double>& key) const {
    // Start with the hash of the first value ...
    arma::uword hashedKey = std::hash<double>()(key(0));

    // ... and add the hash value of all following values to it.
    // Note: This is adapted from the Boost library (boost::hash_combine).
    for (const auto& value : key) {
      hashedKey ^= std::hash<double>()(value) + 0x9e3779b9 + (hashedKey << 6) + (hashedKey >> 2);
    }

    return hashedKey;
  }

  bool IsEqual::operator()(
      const arma::Col<double>& firstKey,
      const arma::Col<double>& secondKey) const {
    // TODO Add exception

    return arma::all(firstKey == secondKey);
  }
}

#include <mantella_bits/helper/unorderedContainer.hpp>

// C++ standard library
#include <functional>

namespace mant {
  arma::uword Hash::operator()(
      const arma::Col<double>& key) const {
    // Start with the hash of the first value ...
    arma::uword hashedKey = std::hash<double>()(key(0));

    // ... and add the hash value of all following values to it.
    // Note: This is adapted from the Boost library (boost::hash_combine).
    for (const auto& value : key) {
      hashedKey ^= std::hash<double>()(value) + 0x9e3779b9 + (hashedKey << 6) + (hashedKey >> 2);
    }

    return hashedKey;
  }

  bool IsEqual::operator()(
      const arma::Col<double>& firstKey,
      const arma::Col<double>& secondKey) const {
    if (firstKey.n_elem != secondKey.n_elem) {
      return false;
    }

    return arma::all(firstKey == secondKey);
  }
}

Return false if the size does not match


/*
C++ working draft
7.9.1
If the source value is between two adjacent destination values, the result
of the conversion is an implementation-defined choice of either of those
values. Otherwise, the behavior is undefined.
*/
#include <cstdlib>
#include <iostream>

int main() {
  static constexpr double kLargeDouble = 1e100;
  std::cout << static_cast<float>(kLargeDouble) << std::endl;
  return 0;
}

/*
http://eel.is/c++draft/conv.double#1
7 Expressions [expr]
7.3 Standard conversions [conv]
7.3.9 Floating-point conversions [conv.double]
1 A prvalue of floating-point type can be converted to a prvalue of another floating-point type.
  If the source value can be exactly represented in the destination type, the result of the conversion is that exact representation.
  If the source value is between two adjacent destination values, the result of the conversion is an implementation-defined choice of either of those values.
  Otherwise, the behavior is undefined.

https://docs.microsoft.com/en-us/cpp/c-language/conversions-from-floating-point-types?view=vs-2019
Represent as a float. If double value can't be represented exactly as float, loss of precision occurs. If value is too large to be represented as float, the result is undefined.
*/
#include <cstdlib>
#include <iostream>

int main() {
  static constexpr double kLargeDouble = 1e100;
  std::cout << static_cast<float>(kLargeDouble) << std::endl;
  return 0;
}

Update docs on double to float


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

#include "net/disk_cache/cache_util.h"

#include "base/file_util.h"
#include "base/logging.h"
#include "base/string_util.h"

namespace disk_cache {

bool MoveCache(const std::wstring& from_path, const std::wstring& to_path) {
  // Just use the version from base.
  return file_util::Move(from_path.c_str(), to_path.c_str());
}

void DeleteCache(const std::wstring& path, bool remove_folder) {
  if (remove_folder) {
    file_util::Delete(path, false);
  } else {
    std::wstring name(path);
    // TODO(rvargas): Fix this after file_util::delete is fixed.
    // file_util::AppendToPath(&name, L"*");
    file_util::Delete(name, true);
  }
}

bool DeleteCacheFile(const std::wstring& name) {
  return file_util::Delete(name, false);
}

void WaitForPendingIO(int* num_pending_io) {
  if (*num_pending_io) {
    NOTIMPLEMENTED();
  }
}

}  // namespace disk_cache

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

#include "net/disk_cache/cache_util.h"

#include "base/file_util.h"
#include "base/logging.h"
#include "base/string_util.h"

namespace disk_cache {

bool MoveCache(const std::wstring& from_path, const std::wstring& to_path) {
  // Just use the version from base.
  return file_util::Move(from_path.c_str(), to_path.c_str());
}

void DeleteCache(const std::wstring& path, bool remove_folder) {
  file_util::FileEnumerator iter(path, /* recursive */ false,
                                 file_util::FileEnumerator::FILES);
  for (std::wstring file = iter.Next(); !file.empty(); file = iter.Next()) {
    if (!file_util::Delete(file, /* recursive */ false))
      NOTREACHED();
  }

  if (remove_folder) {
    if (!file_util::Delete(path, /* recursive */ false))
      NOTREACHED();
  }
}

bool DeleteCacheFile(const std::wstring& name) {
  return file_util::Delete(name, false);
}

void WaitForPendingIO(int* num_pending_io) {
  if (*num_pending_io) {
    NOTIMPLEMENTED();
  }
}

}  // namespace disk_cache

Fix DeleteCache on POSIX. It wasn't successfully deleting before.