class Solution {
public:
     bool canTransform(string start, string end) {
        int i = 0, j = 0, n = start.length();
        while(j < n && i < n){
            while(j < n && end[j] == 'X') j++;
            while(i < n && start[i] == 'X') i++l
            if(i == n && j == n) break;
            if(i == n || j == n) return false;
            if(start[i] != end[j]) return false;
            if(start[i] == 'R' && i > j) return false;
            if(start[i] == 'L' && i < j) return false;
            i++;
            j++;
        }

        return true;
    }
};

Swap Adjacent in LR String


#include <stan/math/matrix/inverse_spd.hpp>
#include <stan/math/matrix/multiply.hpp>
#include <gtest/gtest.h>
#include <test/agrad/util.hpp>
#include <stan/agrad/agrad.hpp>
#include <stan/agrad/matrix.hpp>
#include <stan/agrad/rev/print_stack.hpp>

TEST(AgradRevMatrix,inverse_spd_val) {
  using stan::math::inverse_spd;
  using stan::agrad::matrix_v;

  matrix_v a(2,2);
  a << 2.0, 3.0,
    3.0, 7.0;

  matrix_v a_inv = inverse_spd(a);

  matrix_v I = multiply(a,a_inv);

  EXPECT_NEAR(1.0,I(0,0).val(),1.0E-12);
  EXPECT_NEAR(0.0,I(0,1).val(),1.0E-12);
  EXPECT_NEAR(0.0,I(1,0).val(),1.0E-12);
  EXPECT_NEAR(1.0,I(1,1).val(),1.0e-12);

  EXPECT_THROW(inverse_spd(matrix_v(2,3)), std::domain_error);

  a << 2.0, 3.0,
  1.0, 7.0;
  EXPECT_THROW(inverse_spd(a), std::domain_error);
  a << 1.0, -1.0,
  -1.0, -1.0;
  EXPECT_THROW(inverse_spd(a), std::domain_error);
}

TEST(AgradRevMatrix,inverse_spd_inverse_spd_sum) {
  using stan::math::sum;
  using stan::math::inverse_spd;
  using stan::agrad::matrix_v;

  matrix_v a(4,4);
  a << 1.0, 0.0, 0.0, 0.0,
  0.0, 1.0, 0.0, 0.0,
  0.0, 0.0, 1.0, 0.0,
  0.0, 0.0, 0.0, 1.0;

  AVEC x;
  for (int i = 0; i < 4; ++i)
    for (int j = 0; j < 4; ++j)
      x.push_back(a(i,j));

  AVAR a_inv_inv_sum = sum(inverse_spd(inverse_spd(a)));

  VEC g;
  a_inv_inv_sum.grad(x,g);

  size_t k = 0;
  for (int i = 0; i < 4; ++i) {
    for (int j = 0; j < 4; ++j) {
      if (i == j)
        EXPECT_FLOAT_EQ(1.0,g[k]);
      else if (i > j)
        EXPECT_FLOAT_EQ(2.0,g[k]);
      else
        EXPECT_FLOAT_EQ(0.0,g[k]);
      k++;
    }
  }
}

Add unit test for inverse_spd.


// RUN: %clang_cc1 -std=c++1y %s -verify

// expected-no-diagnostics
namespace variadic_expansion {
  void f(int &, char &);

  template <typename ... T> void g(T &... t) {
    f([&a(t)]()->decltype(auto) {
      return a;
    }() ...);
  }

  void h(int i, char c) { g(i, c); }
}

Add extra testing for init-captures.


// RUN: %clang_cc1 -fsyntax-only -verify %s

// This is not well-formed C++ but used to crash in sema.

template <class T>
struct X {
  template <class U>
  struct A { // expected-note {{not-yet-instantiated member is declared here}}
    template <class V>
    struct B {
      template <class W>
      struct C {
        template <class X>
        struct D {
          template <class Y>
          struct E {
            template <class Z>
            void operator+=(Z);
          };
        };
      };
    };
  };

  template <class U>
  template <class V>
  template <class W>
  template <class X>
  template <class Y>
  template <class Z>
  friend void A<U>::template B<V>::template C<W>::template D<X>::template E<Y>::operator+=(Z); // expected-warning {{not supported}} expected-error {{no member 'A' in 'X<int>'; it has not yet been instantiated}}
};

void test() {
  X<int>::A<int>::B<int>::C<int>::D<int>::E<int>() += 1.0; // expected-note {{in instantiation of template class 'X<int>' requested here}}
}

Add a crazy test case for r243987


/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

#include "catch.hpp"

#include "hooks.hh"

static int i;
void inc_i(vick::contents&) { ++i; }

TEST_CASE("hook proc", "[hook]") {
    vick::hook h;
    vick::contents c;
    h.add(inc_i);
    int li = i;
    h.proc(c);
    REQUIRE(li + 1 == i);
}

TEST_CASE("hook remove", "[hook]") {
    vick::hook h;
    vick::contents c;
    int li = i;
    h.add(inc_i);
    REQUIRE(li == i);
    h.proc(c);
    REQUIRE(li + 1 == i);
    REQUIRE(h.remove(inc_i));
    REQUIRE_FALSE(h.remove(inc_i));
    REQUIRE(li + 1 == i);
    h.proc(c);
    REQUIRE(li + 1 == i);
}

TEST_CASE("hook add multiple", "[hook]") {
    vick::hook h;
    vick::contents c;
    int li = i;
    h.add(inc_i);
    h.add(inc_i);
    REQUIRE(li == i);
    h.proc(c);
    REQUIRE(li + 2 == i);
    REQUIRE(h.remove(inc_i));
    REQUIRE_FALSE(h.remove(inc_i));
    REQUIRE(li + 2 == i);
    h.proc(c);
    REQUIRE(li + 2 == i);
}

Add tests for hook class


#include "mock_player.hpp"

#include <ctime>

#include <boost/random/discrete_distribution.hpp>

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

static boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;

namespace Quoridor {

MockPlayer::MockPlayer(std::shared_ptr<Game> game,
        std::shared_ptr<Pawn> pawn)
    : game_(game), pawn_(pawn), goal_nodes_(), moves_()
{
    lg.add_attribute("Tag", blattrs::constant<std::string>("mock player"));

    goal_nodes_ = game_->pawn_data(pawn_).goal_nodes;

    BOOST_LOG_DEBUG(lg) << "created new MockPlayer (" << pawn_->color() << ")";
    for (auto node : goal_nodes_) {
        BOOST_LOG_DEBUG(lg) << "goal node: " << node.row() << ":" << node.col();
    }
}

MockPlayer::~MockPlayer()
{
}

IMove *MockPlayer::get_move()
{
    IMove *move = moves_.front();
    moves_.pop_front();
    return move;
}

void MockPlayer::push_move(IMove *move)
{
    moves_.push_back(move);
}

}  /* namespace Quoridor */

#include "mock_player.hpp"

#include <ctime>

#include <boost/random/discrete_distribution.hpp>

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

static boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;

namespace Quoridor {

MockPlayer::MockPlayer(std::shared_ptr<Game> game,
        std::shared_ptr<Pawn> pawn)
    : game_(game), pawn_(pawn), goal_nodes_(), moves_()
{
    lg.add_attribute("Tag", blattrs::constant<std::string>("mock player"));

    goal_nodes_ = game_->pawn_data(pawn_).goal_nodes;

    BOOST_LOG_DEBUG(lg) << "created new MockPlayer (" << pawn_->color() << ")";
    for (auto node : goal_nodes_) {
        BOOST_LOG_DEBUG(lg) << "goal node: " << node.row() << ":" << node.col();
    }
}

MockPlayer::~MockPlayer()
{
}

IMove *MockPlayer::get_move()
{
    if (moves_.size() == 0) {
        throw Exception("no more moves");
    }
    IMove *move = moves_.front();
    moves_.pop_front();
    return move;
}

void MockPlayer::push_move(IMove *move)
{
    moves_.push_back(move);
}

}  /* namespace Quoridor */

Check available moves in MockPlayer


#include <iostream>

//Function to calculate number of integers in a given number.
int integer_length(long long int n){
    int length = 0;
    while (n!=0){
        length++;
        n=n/10;
    }
    return length;
}

//Driver function.
int main(){
    std::cout << integer_length(34) << std::endl;
    std::cout << integer_length(6) << std::endl;
    std::cout << integer_length(785416931) << std::endl;
}

Add C++ solution to the interger-length problem.


// 17. Letter Combinations of a Phone Number
/**
 * Given a digit string, return all possible letter combinations that the number could represent.
 *
 * A mapping of digit to letters (just like on the telephone buttons) is given below.
 *
 * 1()     2(abc)  3(def)
 * 4(ghi)  5(jkl)  6(mno)
 * 7(pqrs) 8(tuv)  9(wxyz)
 * *()     0()     #()
 *
 * Input:Digit string "23"
 * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
 *
 * Note:
 * Although the above answer is in lexicographical order, your answer could be in any order you want.
 *
 * Tags: Backtracking, String
 *
 * Similar Problems: (M) Generate Parentheses, (M) Combination Sum
 *
 * Author: Kuang Qin
 */

#include "stdafx.h"
#include <vector>
#include <string>
#include <unordered_map>
#include <iostream>

using namespace std;

class Solution {
    unordered_map<char, string> tel;
    void backtrack(string& digits, vector<string>& res, string& str, int index) {
        int n = digits.size();

        // record current result at the last button
        if (index == n && !str.empty())
        {
            res.push_back(str);
            return;
        }

        // invalid string, return
        if (tel.find(digits[index]) == tel.end())
        {
            res.clear();
            return;
        }

        // start to backtrack corresponding string on each button
        string s = tel[digits[index]];
        int len = s.size();
        for (int i = 0; i < len; i++)
        {
            str += s[i];
            backtrack(digits, res, str, index + 1);
            str.pop_back();
        }

        return;
    }
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        int n = digits.size();
        if (n == 0)
        {
            return res;
        }

        // initialize hash map
        tel['2'] = "abc";
        tel['3'] = "def";
        tel['4'] = "ghi";
        tel['5'] = "jkl";
        tel['6'] = "mno";
        tel['7'] = "pqrs";
        tel['8'] = "tuv";
        tel['9'] = "wxyz";

        string str;

        backtrack(digits, res, str, 0);
        return res;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    string digits("731");
    Solution mySolution;
    vector<string> res = mySolution.letterCombinations(digits);

    for (int i = 0; i < res.size(); i++)
    {
        cout << res[i] << endl;
    }
    system("pause");
    return 0;
}

Add Solution for Problem 017


#include <iostream>
#include <iterator>
#include <vector>
#include <list>
#include <algorithm>

#include "../utility.h"
#include "../random.h"

template<typename IteratorT>
void print(const range<IteratorT>& r)
{
    for (auto x : r)
        std::cout << x << " ";
    std::cout << std::endl;
}

template<typename IteratorT>
size_t size(const range<IteratorT>& r)
{
    return std::distance(r.begin(), r.end());
}

int main()
{
    std::list<int> v{ 3, 1, 4, 22, 31 };

    auto range = make_range(v.begin(), v.end());

    print(range);
    std::cout << "Size : " << size(range) << std::endl;

    std::vector<int> w;
    std::copy(v.begin(), v.end(), std::back_inserter(w));

    auto range2 = make_range(w.begin(), std::next(w.begin(), 4));

    print(range2);
    std::cout << "Size : " << size(range2) << std::endl;

    randomize();
    std::shuffle(range2.begin(), range2.end(), global_urng());

    std::copy(range2.begin(), range2.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;

    std::copy(range.begin(), range.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;

    return 0;
}

Add examples on the use of class range


// Chapter 23, Try This 1: replace 333 in example with 10

#include<iostream>
#include<iomanip>

int main()
{
    float x = 1.0/10;
    float sum = 0;
    for (int i = 0; i<10; ++i) sum += x;
    std::cout << std::setprecision(15) << sum << '\n';
}

Add Chapter 24, Try This 1


/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 */

#include <boost/test/unit_test.hpp>
#include <eosio/testing/tester.hpp>

using namespace eosio;
using namespace testing;
using namespace chain;

BOOST_AUTO_TEST_SUITE(block_tests)

BOOST_AUTO_TEST_CASE(block_with_invalid_tx_test)
{
   tester main;

   // First we create a valid block with valid transaction
   main.create_account(N(newacc));
   auto b = main.produce_block();

   // Make a copy of the valid block and corrupt the transaction
   auto copy_b = std::make_shared<signed_block>(*b);
   auto signed_tx = copy_b->transactions.back().trx.get<packed_transaction>().get_signed_transaction();
   auto& act = signed_tx.actions.back();
   auto act_data = act.data_as<newaccount>();
   // Make the transaction invalid by having the new account name the same as the creator name
   act_data.name = act_data.creator;
   act.data = fc::raw::pack(act_data);
   // Re-sign the transaction
   signed_tx.signatures.clear();
   signed_tx.sign(main.get_private_key(N(eosio), "active"), main.control->get_chain_id());
   // Replace the valid transaction with the invalid transaction
   auto invalid_packed_tx = packed_transaction(signed_tx);
   copy_b->transactions.back().trx = invalid_packed_tx;

   // Re-sign the block
   auto header_bmroot = digest_type::hash( std::make_pair( copy_b->digest(), main.control->head_block_state()->blockroot_merkle.get_root() ) );
   auto sig_digest = digest_type::hash( std::make_pair(header_bmroot, main.control->head_block_state()->pending_schedule_hash) );
   copy_b->producer_signature = main.get_private_key(N(eosio), "active").sign(sig_digest);

   // Push block with invalid transaction to other chain
   tester validator;
   validator.control->abort_block();
   BOOST_REQUIRE_EXCEPTION(validator.control->push_block( copy_b ), fc::exception ,
   [] (const fc::exception &e)->bool {
      return e.code() == action_validate_exception::code_value ;
   }) ;

}

BOOST_AUTO_TEST_SUITE_END()

Add push block with invalid transaction test


//===-------------- lib/Support/Hashing.cpp -------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides implementation bits for the LLVM common hashing
// infrastructure. Documentation and most of the other information is in the
// header file.
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/Hashing.h"

using namespace llvm;

// Provide a definition and static initializer for the fixed seed. This
// initializer should always be zero to ensure its value can never appear to be
// non-zero, even during dynamic initialization.
size_t llvm::hashing::detail::fixed_seed_override = 0;

// Implement the function for forced setting of the fixed seed.
// FIXME: Use atomic operations here so that there is no data race.
void llvm::set_fixed_execution_hash_seed(size_t fixed_value) {
  hashing::detail::fixed_seed_override = fixed_value;
}

Add the source file with trivial definitions in it that was missing from r151822, sorry sorry. =[


// RUN: %clang -### %s 2>&1 | FileCheck %s -check-prefix=DEFAULT
// DEFAULT: "-cc1" {{.*}} "-fcxx-exceptions" "-fexceptions"
//
// RUN: %clang -### -fexceptions %s 2>&1 | FileCheck %s -check-prefix=ON1
// ON1: "-cc1" {{.*}} "-fcxx-exceptions" "-fexceptions"
//
// RUN: %clang -### -fno-exceptions -fcxx-exceptions %s 2>&1 | FileCheck %s -check-prefix=ON2
// ON2: "-cc1" {{.*}} "-fcxx-exceptions" "-fexceptions"
//
// RUN: %clang -### -fno-cxx-exceptions -fexceptions %s 2>&1 | FileCheck %s -check-prefix=ON3
// ON3: "-cc1" {{.*}} "-fcxx-exceptions" "-fexceptions"
//
// RUN: %clang -### -fno-exceptions %s 2>&1 | FileCheck %s -check-prefix=OFF1
// OFF1-NOT: "-cc1" {{.*}} "-fcxx-exceptions"
//
// RUN: %clang -### -fno-cxx-exceptions %s 2>&1 | FileCheck %s -check-prefix=OFF2
// OFF2-NOT: "-cc1" {{.*}} "-fcxx-exceptions"
//
// RUN: %clang -### -fcxx-exceptions -fno-exceptions %s 2>&1 | FileCheck %s -check-prefix=OFF3
// OFF3-NOT: "-cc1" {{.*}} "-fcxx-exceptions"
//
// RUN: %clang -### -fexceptions -fno-cxx-exceptions %s 2>&1 | FileCheck %s -check-prefix=OFF4
// OFF4-NOT: "-cc1" {{.*}} "-fcxx-exceptions"

Add a test case that would have caught the bug fixed in r126640.


/*
Allocore Example: Lévy flight

Description:
A Lévy flight is a random walk where the step size is determined by a function
that is heavy-tailed. This example uses a Cauchy distribution.

Author:
Lance Putnam, 9/2011
*/

#include "allocore/io/al_App.hpp"
using namespace al;

class MyApp : public App{
public:

	RingBuffer<Vec3f> A;
	Mesh vert;

	MyApp(): A(8000)
	{
		nav().pos(0,0,4);
		initWindow();
		window().displayMode(window().displayMode() | Window::MULTISAMPLE);
	}

	virtual void onAnimate(double dt){

		for(int i=0; i<4; ++i){
			Vec3f p;
			rnd::ball<3>(p.elems());

			float r = p.magSqr();
			float l = 0.04;				// spread of steps; lower is more flighty
			float v = l/(r+l*l) * 0.1;	// map uniform to Cauchy distribution

			p = p.sgn() * v;
			p += A.newest();
			A.write(p);
		}

		vert.primitive(Graphics::LINE_STRIP);
		vert.reset();
		for(int i=0; i<A.fill(); ++i){
			float f = float(i)/A.size();
			vert.vertex(A.read(i));

			Vec3f dr = A.read(i+1) - A.read(i-1);

			vert.color(HSV((1-f)*0.2, al::clip(dr.mag()*4 + 0.2), 1-f));
		}
	}

	virtual void onDraw(Graphics& g, const Viewpoint& v){
		g.draw(vert);
	}
};

int main(){
	MyApp().start();
}

Add Levy flight example back; updated to use al::RingBuffer


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

double integrate(double (*f)(double x), double a, double b)
{
	int    N = 10;
	double h = (b-a)/N;
	double integral = 0.0;
	for(int i=0; i<N; i++)
	{
		double x = a + (i+0.5)*h;
		integral += (*f)(x)*h;
	}
	return integral;
}

int main()
{
	cout << integrate(exp, 0.0, 1.0) << endl;
	cout << integrate(sin, 0.0, M_PI/4.0) << endl;
}

Add file to demonstrate use of function pointer.


/**
 * Copyright 2014 Open Connectome Project (http://openconnecto.me)
 * Written by Disa Mhembere (disa)
 *
 * This file is part of FlashGraph.
 *
 * 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 "matrix/kmeans_coordinator.h"

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

    if (argc < 6) {
        fprintf(stderr, "usage: ./test_kmeans_coordinator nthreads "
                "nrow ncol k datafile\n");
        exit(911);
    }

    unsigned nthreads = atoi(argv[1]);
    unsigned nrow = atoi(argv[2]);
    unsigned ncol = atoi(argv[3]);
    unsigned k = atoi(argv[4]);
    std::string fn = argv[5];

    printf("nthreads: %u\n", nthreads);
    printf("nrow: %u\n", nrow);
    printf("ncol: %u\n", ncol);

    unsigned nnodes = numa_num_task_nodes();
    std::cout << "We have " << nnodes << " NUMA nodes\n";

    kmeans_coordinator::ptr kc = kmeans_coordinator::create(
            nthreads, nnodes, nrow, ncol, k, fn);
    return(EXIT_SUCCESS);
}

Test for kmeans coordinator added


// Test if message passing works
// Should on x86, not on arm
// Basically always just doesn't see the write at all.
// Probably need to loop.

#include <atomic>
#include <stdio.h>

// Note that writing the test in C++ is kind of bogus, since
// the *compiler* can reorder.
std::atomic<long> data = {0};
std::atomic<long> ready = {0};

int thread0()
{
    data.store(1, std::memory_order_relaxed);
    ready.store(1, std::memory_order_relaxed);
    return 0;
}

int thread1()
{
    int rready = ready.load(std::memory_order_relaxed);
    int rdata = data.load(std::memory_order_relaxed);
    return (rdata<<1) | rready;
}

void reset()
{
    data.store(0, std::memory_order_relaxed);
    ready.store(0, std::memory_order_relaxed);
}

// Formatting results
int result_counts[4];

void process_results(int *r)
{
    int idx = r[1];
    result_counts[idx]++;
}

void summarize_results()
{
    for (int r0 = 0; r0 <= 1; r0++) {
        for (int r1 = 0; r1 <= 1; r1++) {
            int idx = (r1<<1) | r0;
            printf("ready=%d data=%d: %d\n", r0, r1, result_counts[idx]);
        }
    }
}

typedef int (test_fn)();
test_fn *test_fns[] = {thread0, thread1};

int thread_count = 2;

Add a test for message passing.


/// \file stream.cpp
///
/// Unit tests for stream functions

#include "../stream.hpp"

#include "vg.pb.h"

#include "catch.hpp"

#include <sstream>
#include <iostream>

namespace vg {
namespace unittest {
using namespace std;

TEST_CASE("Protobuf messages that are all default can be stored and retrieved", "[stream]") {
    stringstream datastream;

    // Write one empty message
    REQUIRE(stream::write<Graph>(datastream, 1, [](size_t i) {
       return Graph();
    }));

    // Look for it
    int seen = 0;
    stream::for_each<Graph>(datastream, [&](const Graph& item) {
        seen++;
    });

    // Make sure it comes back
    REQUIRE(seen == 1);
}

TEST_CASE("Protobuf messages can be written and read back", "[stream]") {
    stringstream datastream;

    // Define some functions to make and check fake Protobuf objects
    using message_t = Position;

    auto get_message = [&](size_t index) {
        message_t item;
        item.set_node_id(index);
        cerr << "Made item " << index << endl;
        return item;
    };

    size_t index_expected = 0;
    auto check_message = [&](const message_t& item) {
        cerr << "Read item " << item.node_id() << endl;
        REQUIRE(item.node_id() == index_expected);
        index_expected++;
    };

    // Serialize some objects
    REQUIRE(stream::write<message_t>(datastream, 10, get_message));

    auto data = datastream.str();
    for (size_t i = 0; i < data.size(); i++) {
        ios state(nullptr);
        state.copyfmt(cerr);
        cerr << setfill('0') << setw(2) << hex << (int)(uint8_t)data[i] << " ";
        if (i % 8 == 7) {
            cerr << endl;
        }
        cerr.copyfmt(state);
    }
    cerr << endl;

    // Read them back
    stream::for_each<message_t>(datastream, check_message);

}

}

}

Add tests showing we discard all-default messages


// RUN: %clang_cc1 -Wpedantic -fsyntax-only %s -verify

void foo() __attribute__((diagnose_if(1, "", "error"))); // expected-warning{{'diagnose_if' is a clang extension}}
void foo(int a) __attribute__((diagnose_if(a, "", "error"))); // expected-warning{{'diagnose_if' is a clang extension}}
// FIXME: When diagnose_if gets a CXX11 spelling, this should be enabled.
#if 0
[[clang::diagnose_if(a, "", "error")]] void foo(double a);
#endif

Add a test for diagnose_if.


#include <ctime>
#include <iostream>
#include "PremModel.h"
#include "PMNS_Fast.h"

using namespace std;

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

  int minM = 0;
  int maxM = 2;

  if(argc>1){
    string test = argv[1];
    if(test=="new") maxM = 1;
    if(test=="old") minM = 1;
  }

  int ntries = 1e4;
  if(maxM-minM<2) ntries = 1e3;

  OscProb::PMNS_Fast p;

  // PREM Model
  OscProb::PremModel prem;

  // Fill path for cosT
  prem.FillPath(-1);

  // Give path to calculator
  p.SetPath(prem.GetNuPath());

  double oldTime = 0;
  double newTime = 0;

  for(int m=minM; m<maxM; m++){

    int myTime = clock();

    for(int i=0; i<ntries; i++){

      //p.SetDm(3, (1 -2*(i%2)) * 2.5e-3);
      //p.SetEnergy(2 + (i%2));
      p.SetOldProp(m);

      p.Prob(1,0);

    }

    double timeSec = double(clock() - myTime) / CLOCKS_PER_SEC;
    if(m) oldTime = timeSec;
    else  newTime = timeSec;

  }

  cout << "Old time = " << oldTime << endl;
  cout << "New time = " << newTime << endl;
  if(maxM-minM==2) cout << "Speedup  = " << oldTime/newTime << " times" << endl;

}

Add macro to compare old and new propagation methods


// RUN: %clang_cc1 -verify -chain-include %s %s

// PR 14044
#ifndef PASS1
#define PASS1
class S {
  void f(struct Test);
};
#else
::Tesy *p;  // expected-error {{did you mean 'Test'}}
            // expected-note@-4 {{'Test' declared here}}
#endif

Add the test case from PR 14044 to ensure it doesn't regress.


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

#include "chromeos/dbus/ibus/mock_ibus_engine_service.h"

namespace chromeos {

MockIBusEngineService::MockIBusEngineService() {
}

MockIBusEngineService::~MockIBusEngineService() {
}

void MockIBusEngineService::SetEngine(IBusEngineHandlerInterface* handler) {
}

void MockIBusEngineService::UnsetEngine() {
}

void MockIBusEngineService::RegisterProperties(
      const IBusPropertyList& property_list) {
}

void MockIBusEngineService::UpdatePreedit(const IBusText& ibus_text,
                                          uint32 cursor_pos,
                                          bool is_visible,
                                          IBusEnginePreeditFocusOutMode mode) {
}

void MockIBusEngineService::UpdateAuxiliaryText(const IBusText& ibus_text,
                                                bool is_visible) {
}

void MockIBusEngineService::UpdateLookupTable(
    const IBusLookupTable& lookup_table,
    bool is_visible) {
}

void MockIBusEngineService::UpdateProperty(const IBusProperty& property) {
}

void MockIBusEngineService::ForwardKeyEvent(uint32 keyval,
                                            uint32 keycode,
                                            uint32 state) {
}

void MockIBusEngineService::RequireSurroundingText() {
}

}  // namespace chromeos

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

#include "chromeos/dbus/ibus/mock_ibus_engine_service.h"

namespace chromeos {

MockIBusEngineService::MockIBusEngineService() {
}

MockIBusEngineService::~MockIBusEngineService() {
}

void MockIBusEngineService::SetEngine(IBusEngineHandlerInterface* handler) {
}

void MockIBusEngineService::UnsetEngine() {
}

void MockIBusEngineService::RegisterProperties(
      const IBusPropertyList& property_list) {
}

void MockIBusEngineService::UpdatePreedit(const IBusText& ibus_text,
                                          uint32 cursor_pos,
                                          bool is_visible,
                                          IBusEnginePreeditFocusOutMode mode) {
}

void MockIBusEngineService::UpdateAuxiliaryText(const IBusText& ibus_text,
                                                bool is_visible) {
}

void MockIBusEngineService::UpdateLookupTable(
    const IBusLookupTable& lookup_table,
    bool is_visible) {
}

void MockIBusEngineService::UpdateProperty(const IBusProperty& property) {
}

void MockIBusEngineService::ForwardKeyEvent(uint32 keyval,
                                            uint32 keycode,
                                            uint32 state) {
}

void MockIBusEngineService::RequireSurroundingText() {
}

void MockIBusEngineService::CommitText(const std::string& text) {
}

}  // namespace chromeos

Add a missing implementation of CommitText in MockIBusEngineService.


#include "test.h"
#include "lcg.h"

// By central limiting theorem,
// U ~ [0, 1]
// S = sum U_i for i = 1 to M
// S ~ N(M / 2, M / 12)
// Z = (S - M / 2) / sqrt(M / 12)
// Z ~ N(0, 1)

template <class T, class RNG, int M>
static inline T clt(RNG& r) {
	static T inv = 1 / std::sqrt(T(M) / 12);

	T sum = 0;
	for (int i = 0; i < M; i++)
		sum += r();

	return (sum - M / T(2)) * inv;
}

template <class T, int M>
static void clt(T* data, size_t count) {
	LCG r;
	for (size_t i = 0; i < count; i++)
		data[i] = clt<T, LCG, M>(r);
}

#define CLT_TEST(M)\
static void normaldistf_clt##M(float* data, size_t count) {\
    clt<float, M>(data, count);\
}\
static void normaldist_clt##M(double* data, size_t count) {\
    clt<double, M>(data, count);\
}\
REGISTER_TEST(clt##M)

CLT_TEST(4);
CLT_TEST(8);
CLT_TEST(16);

Add central limiting theorem method


#include <iostream>

template <int N>
int fat() {
  return N * fat<N-1>();
}

template <>
int fat<1>() {
  return 1;
}

int main() {
  const int fat5 = fat<5>();
  std::cout << fat5 << std::endl;
}

Add c++ fatorial template meta programming example


//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <deque>

#include "catch.hpp"

#include "dll/neural/dense_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/trainer/stochastic_gradient_descent.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

// This test case is done to benchmark the performance of SGD
TEST_CASE("dbn/sgd/perf/1", "[dbn][mnist][sgd][perf]") {
    using dbn_t = dll::dbn_desc<
        dll::dbn_layers<
            dll::dense_desc<28 * 28, 500>::layer_t,
            dll::dense_desc<500, 250>::layer_t,
            dll::dense_desc<250, 10, dll::activation<dll::function::SOFTMAX>>::layer_t>,
        dll::momentum, dll::batch_size<100>, dll::trainer<dll::sgd_trainer>>::dbn_t;

    auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(2000);
    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>();

    auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 50);
    std::cout << "ft_error:" << ft_error << std::endl;
    CHECK(ft_error < 5e-2);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.2);
}

Prepare test case for performance test of SGD


#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <queue>
#include <stack>
#include <algorithm>
#include <functional>
#include <utility>
#include <cstdio>
#include <cstdlib>
using namespace std;

// dist[i][j] = the dist between word1[0...i-1] and word2[0...j-1]
// Recursion:
// dist[i][j] = dist[i-1][j-1] + 0 / 1   word1[i-1] == word2[j-1] or not
//            = dist[i-1][j] + 1
//            = dist[i][j-1] + 1
// Init:
// dist[0][j] = j;
// dist[i][0] = i;
// Complexity: O(n1*n2) time & space overhead
int minDistance(string word1, string word2)
{
	int n1 = word1.size();
	int n2 = word2.size();
	vector<vector<int> > dist(n1 + 1, vector<int>(n2 + 1, 0));
	// init
	for (int i = 0; i <= n1; ++i) dist[i][0] = i;
	for (int j = 0; j <= n2; ++j) dist[0][j] = j;

	// bottom to up
	for (int i = 1; i <= n1; ++i)
	{
		for (int j = 1; j <= n2; ++j)
		{
			int tmp = 0;
			if (word1[i-1] == word2[j-1]) tmp = dist[i-1][j-1];
			else tmp = dist[i-1][j-1] + 1;

			tmp = min(tmp, dist[i-1][j] + 1);
			tmp = min(tmp, dist[i][j-1] + 1);

			dist[i][j] = tmp;
		}
	}

	return dist[n1][n2];
}

Edit distance, classic problem, need to recheck


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

#include "ui/base/win/dpi_setup.h"

#include "ui/base/layout.h"
#include "ui/gfx/display.h"
#include "ui/gfx/win/dpi.h"

namespace ui {
namespace win {

void InitDeviceScaleFactor() {
  float scale = 1.0f;
  if (gfx::IsHighDPIEnabled()) {
    float scale = gfx::Display::HasForceDeviceScaleFactor() ?
        gfx::Display::GetForcedDeviceScaleFactor() : gfx::GetDPIScale();
    // Quantize to nearest supported scale factor.
    scale = ui::GetImageScale(ui::GetSupportedScaleFactor(scale));
  }
  gfx::InitDeviceScaleFactor(scale);
}

}  // namespace win
}  // namespace ui

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

#include "ui/base/win/dpi_setup.h"

#include "ui/base/layout.h"
#include "ui/gfx/display.h"
#include "ui/gfx/win/dpi.h"

namespace ui {
namespace win {

void InitDeviceScaleFactor() {
  float scale = 1.0f;
  if (gfx::IsHighDPIEnabled()) {
    scale = gfx::Display::HasForceDeviceScaleFactor() ?
        gfx::Display::GetForcedDeviceScaleFactor() : gfx::GetDPIScale();
    // Quantize to nearest supported scale factor.
    scale = ui::GetImageScale(ui::GetSupportedScaleFactor(scale));
  }
  gfx::InitDeviceScaleFactor(scale);
}

}  // namespace win
}  // namespace ui

Correct bug in InitDeviceScaleFactor - hidden variable.


/*
* (C) 2017 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "tests.h"

#if defined(BOTAN_HAS_ASN1)
   #include <botan/der_enc.h>
   #include <botan/ber_dec.h>
#endif

namespace Botan_Tests {

#if defined(BOTAN_HAS_ASN1)

namespace {

Test::Result test_ber_stack_recursion()
   {
   Test::Result result("BER stack recursion");

   // OSS-Fuzz #813 GitHub #989

   try
      {
      const std::vector<uint8_t> in(10000000, 0);
      Botan::DataSource_Memory input(in.data(), in.size());
      Botan::BER_Decoder dec(input);

      while(dec.more_items())
         {
         Botan::BER_Object obj;
         dec.get_next(obj);
         }
      }
   catch(Botan::Decoding_Error&)
      {
      }

   result.test_success("No crash");

   return result;
   }

}

class ASN1_Tests : public Test
   {
   public:
      std::vector<Test::Result> run() override
         {
         std::vector<Test::Result> results;

         results.push_back(test_ber_stack_recursion());

         return results;
         }
   };

BOTAN_REGISTER_TEST("asn1", ASN1_Tests);

#endif

}

Add test for OSS-Fuzz 813


#include <stdio.h>
#include <math.h>

#include <string>
#include <sstream>

template <class T> T from_str(const std::string & str){
	std::istringstream sin(str);
	T ret;
	sin >> ret;
	return ret;
}

void print(double a){
	printf("%.20f, %llX\n", a, *((unsigned long long *) &a));
}

int main(int argc, char **argv){
	double i = from_str<double>(argv[1]);

	print(sqrt(-1));
	print(1.0/i);
	print(-1.0/i);
	print(0.0/i);
	print(-0.0/i);
	print((1.0/i)/(-1.0/i));

	print((1.0/i) + 3.0);
	print((-1.0/i) + 3.0);

	print(3.0/(1.0/i));

	return 0;
}

Add some code to output the bit patterns for various ways of generating NaN and Inf, compile with -lm


#include <catch.hpp>

#include "Chip8.hpp"
#include "CPU.hpp"

namespace {

using namespace Core8;

SCENARIO("CPUs can assign the value of one register to another", "[assign]") {
  GIVEN("A CPU with some initialized registers") {
    CPU cpu{};
    cpu.writeRegister(Chip8::REGISTER::V0, 0x01);
    cpu.writeRegister(Chip8::REGISTER::VC, 0xCB);
    cpu.writeRegister(Chip8::REGISTER::VF, 0xFF);

    WHEN("the CPU assigns one register to another") {
      cpu.setInstruction(0x8100);
      cpu.decode();
      cpu.execute();
      cpu.setInstruction(0x8DC0);
      cpu.decode();
      cpu.execute();
      cpu.setInstruction(0x8EF0);
      cpu.decode();
      cpu.execute();

      THEN("the target register holds a copy of the source register") {
        REQUIRE(cpu.readRegister(Chip8::REGISTER::V1) == 0x01);
        REQUIRE(cpu.readRegister(Chip8::REGISTER::VD) == 0xCB);
        REQUIRE(cpu.readRegister(Chip8::REGISTER::VE) == 0xFF);
      }
      AND_THEN("the source register remains unchanged") {
        REQUIRE(cpu.readRegister(Chip8::REGISTER::V0) == 0x01);
        REQUIRE(cpu.readRegister(Chip8::REGISTER::VC) == 0xCB);
        REQUIRE(cpu.readRegister(Chip8::REGISTER::VF) == 0xFF);
      }
    }
  }
}

} // unnamed namespace

Add unit tests to assign operation


// ========================================================================== //
// This file is part of DO++, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2014 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

#include <limits>
#include <stdint.h>
#include <vector>

#include <gtest/gtest.h>

#include "pixel.hpp"
#include "color_conversion.hpp"

using namespace std;
using namespace DO;

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

Add stub for unit-testing the color conversion.


#include <mach/mach_time.h>
#include <string>
#include <stdio.h>

#define LAPS 10000000

std::wstring s = L"siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig";

int
main(void) {
  uint64_t count = 0;
  uint64_t start = mach_absolute_time();
  for (auto i = 0; i < LAPS; i++) {
    for (auto c : s) {
      count++;
      asm volatile("" : "+r" (count));
    }
  }
  uint64_t delta = mach_absolute_time() - start;
  printf("%f ns/lap\n", (double)delta / (double)LAPS);

  return 0;
}

#include <mach/mach_time.h>
#include <string>
#include <stdio.h>

#define LAPS 10000000

std::wstring s = L"siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig";

int
main(void) {
  uint64_t count = 0;
  uint64_t start = mach_absolute_time();
  for (auto i = 0; i < LAPS; i++) {
    for (auto c : s) {
      count++;
      asm volatile("" : "+r" (count));
    }
  }
  uint64_t delta = mach_absolute_time() - start;
  printf("%f nanoseconds\n", (double)delta);
  printf("%f ns/lap\n", (double)delta / (double)LAPS);

  return 0;
}

Print the total execution time.


/**
 * Remove Duplicates from Sorted Array
 *
 * cpselvis (cpselvis@gmail.com)
 * August 23th, 2016
 */
#include<iostream>
#include<vector>

using namespace std;

class Solution {
public:
  int removeDuplicates(vector<int>& nums) {
    int prev, len = 0;

    for (int i = 0; i < nums.size(); ) {
      if (nums[i] != prev) {
	len ++;
	prev = nums[i];
	i ++;
      } else {
	nums.erase(nums.begin() + i);
      }
    }
    return len;
  }
};

int main(int argc, char **argv)
{
  int arr[3] = {1, 1, 2};
  vector<int> nums(arr + 0, arr + 3);

  Solution s;
  cout << s.removeDuplicates(nums) << endl;
}

Remove duplicate elements of an array.


#include <iostream>

using namespace std;

class DynamicArray {
  int* elements;
  int size;
  int capacity;

  void resize() {
    // increase capacity
    capacity *= 2;

    // allocate new memory
    int* newElements = new int[capacity];

    // copy old array
    for (int i = 0; i < size; ++i) {
      newElements[i] = elements[i];
    }

    // free old memory
    delete[] elements;

    // assign new memory to elements
    elements = newElements;
  }

  void copy(const DynamicArray& other) {
    elements = new int[other.capacity];

    for (int i = 0; i < other.size; ++i) {
      elements[i] = other.elements[i];
    }

    size = other.size;
    capacity = other.capacity;
  }

public:

  DynamicArray(int _capacity = 8): size(0), capacity(_capacity) {
    elements = new int[capacity];
  }

  DynamicArray(const DynamicArray& other) {
    copy(other);
  }

  DynamicArray& operator=(const DynamicArray& other) {
    if (this != &other) {
      delete[] elements;
      copy(other);
    }

    return *this;
  }

  ~DynamicArray() {
    delete[] elements;
  }

  int getSize() const {
    return size;
  }

  int getAt(int index) const {
    return elements[index];
  }

  void addAtEnd(int element) {
    if (size == capacity) {
      resize();
    }

    elements[size] = element;
    size++;
  }

  void removeLast() {
    size--;
  }

  void addAt(int element, int index) {
    if (size == capacity) {
      resize();
    }

    for (int i = size; i > index; --i) {
      elements[i] = elements[i - 1];
    }

    elements[index] = element;
    size++;
  }

  void removeAt(int index) {
    for (int i = index; i < size - 1; ++i) {
      elements[i] = elements[i + 1];
    }

    size--;
  }
};

int main() {
  DynamicArray d1;
  d1.addAtEnd(1);
  d1.addAtEnd(2);
  d1.addAtEnd(3);

  DynamicArray d2;
  d2.addAtEnd(2);

  d2 = d1;

  d1.addAt(10, 0);

  cout << d1.getAt(0) << '\n';
  cout << d2.getAt(0) << '\n';

  return 0;
}

Add solution to the dynamic array problem


/*
    This file is part of libkcal.

    Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
    Copyright (C) 2005 Reinhold Kainhofer <reinhold@kainhofer.com>

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include "calendarlocal.h"
#include "vcalformat.h"
#include "filestorage.h"

#include <kaboutdata.h>
#include <kapplication.h>
#include <kdebug.h>
#include <klocale.h>
#include <kcmdlineargs.h>

#include <qfile.h>
#include <qfileinfo.h>

using namespace KCal;

static const KCmdLineOptions options[] =
{
  { "verbose", "Verbose output", 0 },
  { "+input", "Name of input file", 0 },
  { "+output", "Name of output file", 0 },
  KCmdLineLastOption
};

int main( int argc, char **argv )
{
  KAboutData aboutData("testvcalexport", "Part of LibKCal's test suite. Checks if export to vCalendar still works correctly.", "0.1");
  KCmdLineArgs::init( argc, argv, &aboutData );
  KCmdLineArgs::addCmdLineOptions( options );

  KApplication app/*( false, false )*/;

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  if ( args->count() != 2 ) {
    args->usage( "Wrong number of arguments." );
  }

  QString input = QFile::decodeName( args->arg( 0 ) );
  QString output = QFile::decodeName( args->arg( 1 ) );

  QFileInfo outputFileInfo( output );
  output = outputFileInfo.absFilePath();

  kdDebug(5800) << "Input file: " << input << endl;
  kdDebug(5800) << "Output file: " << output << endl;

  CalendarLocal cal( QString::fromLatin1("UTC") );

  if ( !cal.load( input ) ) return 1;
  FileStorage storage( &cal, output, new VCalFormat );
  if ( !storage.save() ) return 1;

  return 0;
}

Test application to read in an .ics file and export it to .vcs.


#include "greentea-client/greentea_serial.h"

SingletonPtr<GreenteaSerial> greentea_serial;

GreenteaSerial::GreenteaSerial() : mbed::RawSerial(USBTX, USBRX) {};

#include "greentea-client/greentea_serial.h"

SingletonPtr<GreenteaSerial> greentea_serial;

GreenteaSerial::GreenteaSerial() : mbed::RawSerial(USBTX, USBRX, MBED_CONF_PLATFORM_STDIO_BAUD_RATE) {};

Make GreenTea respect STDIO baud rate


// Chapter 25, exercise 3: initialize a 32-bit signed int with the bit patterns
// and print the result:
// - all zeros
// - all ones
// - alternating ones and zeros (starting with leftmost one)
// - alternating zeros and ones (starting with leftomst zero)
// - 110011001100...
// - 001100110011...
// - all-one bytes and all-zero bytes starting with all-one byte
// - all-one bytes and all-zero bytes starting with all-zero byte
//
// Repeat with unsigned int.

#include<iostream>
#include<iomanip>
#include<bitset>

using namespace std;

template<class T>
void print(T s) { cout << bitset<32>(s) << " is " << s << '\n'; }

int main()
try
{
    cout << "Signed integer:\n";
    int s = 0x0;
    print(s);
    s = ~s;
    print(s);
    s = 0xaaaaaaaa;
    print(s);
    s = ~s;
    print(s);
    s = 0xcccccccc;
    print(s);
    s = ~s;
    print(s);
    s = 0xff00ff00;
    print(s);
    s = ~s;
    print(s);

    cout << "\nUnsigned integer:\n";
    unsigned int u = 0x0;
    print(u);
    u = ~u;
    print(u);
    u = 0xaaaaaaaa;
    print(u);
    u = ~u;
    print(u);
    u = 0xcccccccc;
    print(u);
    u = ~u;
    print(u);
    u = 0xff00ff00;
    print(u);
    u = ~u;
    print(u);
}
catch (exception& e) {
    cerr << "Exception: " << e.what() << '\n';
}
catch (...) {
    cerr << "Exception\n";
}

Add Chapter 25, exercise 3


#include "../test.h"
#include "../../src/forces/label_collision_force.h"
#include "../../src/forces/label_state.h"

namespace Forces
{

TEST(Test_LabelCollisionForce, NoForceIfLabelsDontCollide)
{
  LabelCollisionForce force;

  Eigen::Vector2f size(0.1f, 0.1f);
  LabelState label(1, "Tested label", Eigen::Vector3f(0, 0, 0), size);
  label.labelPosition2D = Eigen::Vector2f(0, 0);

  LabelState other(2, "Other label", Eigen::Vector3f(1, 1, 0), size);
  label.labelPosition2D = Eigen::Vector2f(1, 1);

  LabellerFrameData frameData(1.0f, Eigen::Matrix4f::Identity(),
                              Eigen::Matrix4f::Identity());
  auto labels = std::vector<LabelState>{ label, other };
  auto result = force.calculateForce(label, labels, frameData);

  EXPECT_Vector2f_NEAR(Eigen::Vector2f(0, 0), result, 0.0001f);
}

}  // namespace Forces

Add first test for LabelCollisionForce.


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

#include "SkTypes.h"

#include "mozilla/mozalloc.h"
#include "mozilla/mozalloc_abort.h"
#include "mozilla/mozalloc_oom.h"

void sk_throw() {
    SkDEBUGFAIL("sk_throw");
    mozalloc_abort("Abort from sk_throw");
}

void sk_out_of_memory(void) {
    SkDEBUGFAIL("sk_out_of_memory");
    mozalloc_handle_oom(0);
}

void* sk_malloc_throw(size_t size) {
    return sk_malloc_flags(size, SK_MALLOC_THROW);
}

void* sk_realloc_throw(void* addr, size_t size) {
    return moz_xrealloc(addr, size);
}

void sk_free(void* p) {
    moz_free(p);
}

void* sk_malloc_flags(size_t size, unsigned flags) {
    return (flags & SK_MALLOC_THROW) ? moz_xmalloc(size) : moz_malloc(size);
}

Add a new SkMemory implementation that uses mozalloc instead of malloc


/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

#include "contents.hh"
#include "catch.hpp"

using namespace vick;

TEST_CASE("contents construction coordinates", "[contents]") {
#define TESTS                                                        \
    /* always start at `y = 0`, `x = 0` */                           \
    do {                                                             \
        REQUIRE(c.y == 0);                                           \
        REQUIRE(c.x == 0);                                           \
    } while (0)

    SECTION("contents()") {
        contents c;
        TESTS;
    }
    SECTION("contents({})") {
        contents c({});
        TESTS;
    }
    SECTION("contents({\"hi\", \"bye\"})") {
        contents c({"hi", "bye"});
        TESTS;
    }

#undef TESTS
}

TEST_CASE("contents::push_back", "[contents]") {
    contents c;
    REQUIRE(c.cont.size() == 0);
    c.push_back("hello");
    c.push_back("world");
    REQUIRE(c.cont.size() == 2);
    REQUIRE(c.cont[0] == "hello");
    REQUIRE(c.cont[1] == "world");
}

TEST_CASE("contents::yx", "[contents]") {
    contents c;

    c.waiting_for_desired = false;
    // require that it moves out of bounds without checking
    c.yx(3, 1);
    REQUIRE(c.y == 3);
    REQUIRE(c.x == 1);
    REQUIRE_FALSE(c.waiting_for_desired);

    // ensure it doesn't modify waiting_for_desired
    c.waiting_for_desired = true;
    c.yx(0, 5);
    REQUIRE(c.y == 0);
    REQUIRE(c.x == 5);
    REQUIRE(c.waiting_for_desired);
}

TEST_CASE("contents `copy/move` `assignment/construction`",
          "[contents]") {
    contents n({"asdf", "jkl;"});
    n.yx(1, 1);

#define TESTS                                                        \
    do {                                                             \
        REQUIRE(c.y == 1);                                           \
        REQUIRE(c.x == 1);                                           \
        REQUIRE(c.cont.size() == 2);                                 \
        REQUIRE(c.cont[0] == "asdf");                                \
        REQUIRE(c.cont[1] == "jkl;");                                \
    } while (0)

    SECTION("copy assignment") {
        contents c;
        c = n;
        TESTS;
    }
    SECTION("move assignment") {
        contents c;
        c = std::move(n);
        TESTS;
    }
    SECTION("copy construction") {
        contents c(n);
        TESTS;
    }
    SECTION("move construction") {
        contents c(std::move(n));
        TESTS;
    }

#undef TESTS
}

Add tests for `class contents`


#include <test.hpp>

TEST_CASE("varint") {

    std::string buffer;
    mapbox::util::pbf_writer pw(buffer);

    SECTION("encode/decode int32") {
        pw.add_int32(1, 17);
        mapbox::util::pbf item(buffer.data(), buffer.size());
        REQUIRE(item.next());
        REQUIRE(17 == item.get_int32());
    }

    SECTION("encode/decode uint32") {
        pw.add_uint32(1, 17U);
        mapbox::util::pbf item(buffer.data(), buffer.size());
        REQUIRE(item.next());
        REQUIRE(17U == item.get_uint32());
    }

    SECTION("encode/decode uint64") {
        pw.add_uint64(1, (1ULL << 40));
        mapbox::util::pbf item(buffer.data(), buffer.size());
        REQUIRE(item.next());
        REQUIRE((1ULL << 40) == item.get_uint64());
    }

    SECTION("short buffer while parsing varint") {
        pw.add_uint64(1, (1ULL << 40));
        buffer.resize(buffer.size() - 1); // "remove" last byte from buffer
        mapbox::util::pbf item(buffer.data(), buffer.size());
        REQUIRE(item.next());
        REQUIRE_THROWS_AS(item.get_uint64(), mapbox::util::pbf::end_of_buffer_exception);
    }

    SECTION("data corruption in buffer while parsing varint)") {
        pw.add_uint64(1, (1ULL << 20));
        buffer[buffer.size() - 1] += 0x80; // pretend the varint goes on
        mapbox::util::pbf item(buffer.data(), buffer.size());
        REQUIRE(item.next());
        REQUIRE_THROWS_AS(item.get_uint64(), mapbox::util::pbf::end_of_buffer_exception);
    }

    SECTION("data corruption in buffer while parsing varint (max length varint)") {
        pw.add_uint64(1, std::numeric_limits<uint64_t>::max());
        buffer[buffer.size() - 1] += 0x80; // pretend the varint goes on
        mapbox::util::pbf item(buffer.data(), buffer.size());
        REQUIRE(item.next());
        REQUIRE_THROWS_AS(item.get_uint64(), mapbox::util::pbf::varint_too_long_exception);
    }

}

Test various varint encoding/decoding cases with failure modes.


#include "option_types.hh"
#include "unit_tests.hh"

namespace Kakoune
{

UnitTest test_option_parsing{[]{
    auto check = [](auto&& value, StringView str)
    {
        auto repr = option_to_string(value);
        kak_assert(repr == str);
        std::decay_t<decltype(value)> parsed;
        option_from_string(str, parsed);
        kak_assert(parsed == value);
    };

    check(123, "123");
    check(true, "true");
    check(Vector<String>{"foo", "bar:", "baz"}, "foo:bar\\::baz");
    check(HashMap<String, int>{{"foo", 10}, {"b=r", 20}, {"b:z", 30}}, "foo=10:b\\=r=20:b\\:z=30");
    check(DebugFlags::Keys | DebugFlags::Hooks, "hooks|keys");
}};

}

Add unit test for option parsing


#include <cstdlib>
#include <iostream>
#include <cmath>

using namespace std;

void pow2(int& x) {
    x = pow(x, 2);
}

int pow3(int x) {
    return pow(x, 3);
}

int main() {
    int x, y;

    cin >> x >> y;

    pow2(x);
    y = pow3(y);

    cout << x << " " << y << endl;
    return 0;
}

Add wshop form 05 Oct 2015


// Copyright 2021 DeepMind Technologies Limited
//
// 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.

// A benchmark for comparing different implementations of engine_util_spatial methods.

#include <benchmark/benchmark.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <absl/base/attributes.h>
#include <mujoco/mjdata.h>
#include <mujoco/mujoco.h>
#include "src/engine/engine_util_blas.h"
#include "src/engine/engine_util_spatial.h"
#include "test/fixture.h"

namespace mujoco {
namespace {

// ------------- quaternion-vector rotation ----------------------------

void BM_RotVecQuat(benchmark::State& state) {
  MujocoErrorTestGuard guard;

  // Create axis-angle and convert to a quaternion
  mjtNum quat[4];
  const mjtNum angle = 33 * M_PI / 180;
  mjtNum vec[] = {0.2672612419124244, 0.5345224838248488, 0.8017837257372732};
  mju_axisAngle2Quat(quat, vec, angle);

  for (auto s : state) {
    mjtNum result[3];
    mju_rotVecQuat(result, vec, quat);
    benchmark::DoNotOptimize(result);
  }
  state.SetItemsProcessed(state.iterations());
}
BENCHMARK(BM_RotVecQuat);

}  // namespace
}  // namespace mujoco

Add an example benchmark for methods in `engine_util_spatial`.


#include <utility>

template <std::size_t I, typename T> struct holder { T t; };

template <typename Sequence, typename... Ts> struct tuple_impl;

template <std::size_t... I, typename... Ts>
struct tuple_impl<std::index_sequence<I...>, Ts...> : holder<I, Ts>... {};

template <typename... Ts>
using tuple = tuple_impl<std::make_index_sequence<sizeof...(Ts)>, Ts...>;

template <std::size_t I, typename T> T &get(holder<I, T> &h) { return h.t; }

template <typename T, std::size_t I> T &get(holder<I, T> &h) { return h.t; }

#include <iostream>
#include <string>

void test_tuple() {
  tuple<int, std::string> t{1, "hello"};
  std::cout << get<1>(t) << "\n";
  std::cout << get<0>(t) << "\n";

  get<int>(t) = 5;
  get<std::string>(t) = "world";

  std::cout << get<1>(t) << "\n";
  std::cout << get<0>(t) << "\n";
}

#include <variant>

template <typename... F> struct overload : F... { using F::operator()...; };

template <typename... F> overload(F...)->overload<F...>;

void test_overload() {
  std::variant<int, std::string> v;
  v = std::string("hello");

  std::visit(
      overload{[](int i) { std::cout << i << " int \n"; },
               [](const std::string &s) { std::cout << s << " string \n"; }},
      v);
}

int main() {
  test_tuple();
  test_overload();
}

Add some short metaprogramming examples


// RUN: %clang_cc1 -std=c++0x -fsyntax-only -verify %s

// PR5290
int const f0();
void f0_test() {
  decltype(0, f0()) i = 0; // expected-warning{{expression result unused}}
  i = 0;
}

struct A { int a[1]; A() { } };
typedef A const AC;
int &f1(int*);
float &f2(int const*);

void test_f2() {
  float &fr = f2(AC().a);
}

Add test case for PR5290; this bug was fixed with the non-class rvalue de-cv-qualification fixes.


// RUN: %clangxx_msan -m64 -O2 %s -o %t && %run %t

#include <sanitizer/msan_interface.h>

struct S {
  S(int a0) : a(a0) {}
  int a;
  int b;
};

// Here S is passed to FooRun as a 64-bit integer.
// This triggers an optimization where 10000 * s.a is transformed into
// ((*(uint64_t *)&s) * (10000 * 2**32)) >> 32
// Test that MSan understands that this kills the uninitialized high half of S
// (i.e. S::b).
void FooRun(S s) {
  int64_t x = 10000 * s.a;
  __msan_check_mem_is_initialized(&x, sizeof(x));
}

int main(void) {
  S z(1);
  // Take &z to ensure that it is built on stack.
  S *volatile p = &z;
  FooRun(z);
  return 0;
}

Fix handling of multiplication by a constant with a number of trailing zeroes.


#include <stdio.h>
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string.h>

/*
1000 in 9 seconds

so each one takes ~0.01s - fine
10x faster than haskell
*/

std::string readFile(const char* file)
{
        std::ifstream f;
        std::stringstream ss;

        f.open(file, std::ios::in | std::ios::binary);

        if (f.fail()) printf("doh\n");
        ss << f.rdbuf();
        if (!f && !f.eof()) printf("doh\n");
        f.close();

        return ss.str();
}

int main()
{
    std::string x = readFile("output/bullet.ids");
    const char* s = x.c_str();
    std::cout << "Paused, press enter to continue...";
    std::cin.get();
    for (int i = 1; i <= 1000; i++)
    {
        char buf[3];
        buf[0] = '?';
        buf[1] = i;
        buf[2] = 0;

        char* c = strstr(s, buf);
        printf("%i %i\n", i, c == 0 ? -1 : c - s);
    }
    std::cout << "Done";
    return 0;
}

Add a test of searching in order


// Chapter 25, exercise 9: without using standard headers such as <limits>,
// compute the number of bits in an int and determine wether char is signed or
// unsigned

#include<iostream>

using namespace std;

int main()
{
    int n = 0;
    int i = 1;
    while (true) {
        cout << "1 at bit " << n << ": " << (i<<n) << '\n';
        if ((i<<n) < (i<<(n-1))) break;
        ++n;
    }
    cout << "int has " << n+1 << " bits (hitting the sign bit when shifting "
        << "by " << n << " positions).\n\n";
    char ch = -1;
    if (ch==-1)
        cout << "char is signed\n";
    else    // ch becomes 255
        cout << "char is unsigned\n";
}

Add Chapter 25, exercise 9


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

#include "chrome/browser/extensions/extension_apitest.h"
#include "net/dns/mock_host_resolver.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Wallpaper) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  ASSERT_TRUE(StartEmbeddedTestServer());
  ASSERT_TRUE(RunExtensionTest("wallpaper")) << message_;
}

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

#include "chrome/browser/extensions/extension_apitest.h"
#include "net/dns/mock_host_resolver.h"

// Disabled due to flakiness. See http://crbug.com/468632.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Wallpaper) {
  host_resolver()->AddRule("a.com", "127.0.0.1");
  ASSERT_TRUE(StartEmbeddedTestServer());
  ASSERT_TRUE(RunExtensionTest("wallpaper")) << message_;
}

Disable ExtensionApiTest.Wallpaper as it's flaky.


// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: echo "42" | %run %t 2>&1 | FileCheck %s

#include <iostream>

int main() {
  int i;
  std::cout << "Type i: ";
  std::cin >> i;
  return 0;
// CHECK: Type i:
// CHECK-NOT: AddressSanitizer: stack-buffer-overflow on address [[ADDR:0x[0-9a-f]+]]
}

Add a test case for r208215 [stack buffer overflow in <iostream>]


#include <bits/stdc++.h>

using namespace std;

vector<int> G[MAX];

/* this visited array should be initialized with false
    eg.: memset(visited, false, sizeof visited) */
bool visited[MAX];

void BFS(int first) {
    queue<int>Q;
    Q.push(first);
    while (!Q.empty()) {
        int act = Q.front();
        visited[act] = true;
        Q.pop();
        for (int i= 0; i< G[act].size(); i++)
            if (!visited[G[act][i]])
                Q.push(G[act][i]);
    }
}

Add bfs source code in c++


#include "catch.hpp"

#include "dll/rbm.hpp"
#include "dll/dbn.hpp"
#include "dll/vector.hpp"
#include "dll/labels.hpp"
#include "dll/test.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

TEST_CASE( "dbn/mnist_1", "rbm::simple" ) {
    typedef dll::dbn<
        dll::layer<28 * 28, 100, dll::in_dbn, dll::momentum, dll::batch_size<25>, dll::init_weights>,
        dll::layer<100, 200, dll::in_dbn, dll::momentum, dll::batch_size<25>>,
        dll::layer<200, 10, dll::in_dbn, dll::momentum, dll::batch_size<25>, dll::hidden<dll::unit_type::SOFTMAX>>> dbn_t;

    auto dataset = mnist::read_dataset<std::vector, vector, double>();

    REQUIRE(!dataset.training_images.empty());
    dataset.training_images.resize(200);
    dataset.training_labels.resize(200);

    mnist::binarize_dataset(dataset);

    auto labels = dll::make_fake(dataset.training_labels);

    auto dbn = make_unique<dbn_t>();

    dbn->pretrain(dataset.training_images, 5);
    dbn->fine_tune(dataset.training_images, labels, 5, 50);

    auto error = test_set(dbn, dataset.training_images, dataset.training_labels, dll::predictor());

    REQUIRE(error < 1e-2);
}

Add test case for DBN


// RUN: %llvmgxx -S %s -o /dev/null

#include <locale>

namespace std
{
  codecvt<char, char, mbstate_t>::
  codecvt(size_t __refs)
  : __codecvt_abstract_base<char, char, mbstate_t>(__refs),
  _M_c_locale_codecvt(_S_get_c_locale())
  { }
}

Test handling of TRY_CATCH_EXPRs for which the handler is a sequence of ordinary statements, rather than a list of CATCH_EXPRs or an EH_FILTER_EXPR.


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

// CHECK: DW_TAG_subrange_type

struct StructName {
  int member[];
};

struct StructName SN;

Test that we emit a subrange type for vlas.


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

template<int N, int M>
struct A0 {
  void g0();
};

template<int X, int Y> void f0(A0<X, Y>) { } // expected-note{{previous}}
template<int N, int M> void f0(A0<M, N>) { }
template<int V1, int V2> void f0(A0<V1, V2>) { } // expected-error{{redefinition}}

template<int X, int Y> void f1(A0<0, (X + Y)>) { } // expected-note{{previous}}
template<int X, int Y> void f1(A0<0, (X - Y)>) { }
template<int A, int B> void f1(A0<0, (A + B)>) { } // expected-error{{redefinition}}

template<int X, int Y> void A0<X, Y>::g0() { }

Add a template test that requires canonical expression comparison


#include "backtrace_formatter.h"
#include <iostream>

namespace lms {
namespace extra {

void BacktraceFormatter::print(){
    std::cerr << "BacktraceFormatter::print not implemented on Win32" << std::endl;
}

}  // namespace extra
}  // namespace lms

#include "lms/extra/backtrace_formatter.h"
#include <iostream>
#include <Windows.h>

namespace lms {
namespace extra {

void printStacktrace() {
    // http://stackoverflow.com/questions/5693192/win32-backtrace-from-c-code
    // https://msdn.microsoft.com/en-us/library/windows/desktop/bb204633(v=vs.85).aspx

    unsigned int   i;
    void         * stack[ 100 ];
    unsigned short frames;
    SYMBOL_INFO  * symbol;
    HANDLE         process;

    process = GetCurrentProcess();

    SymInitialize( process, NULL, TRUE );

    frames               = CaptureStackBackTrace( 0, 100, stack, NULL );
    symbol               = ( SYMBOL_INFO * )calloc( sizeof( SYMBOL_INFO ) + 256 * sizeof( char ), 1 );
    symbol->MaxNameLen   = 255;
    symbol->SizeOfStruct = sizeof( SYMBOL_INFO );

    printf("\nStacktrace\n");

    for( i = 0; i < frames; i++ ) {
        SymFromAddr( process, ( DWORD64 )( stack[ i ] ), 0, symbol );

        printf( "%i: %s - 0x%0X\n", frames - i - 1, symbol->Name, symbol->Address );
    }

    free( symbol );
}

}  // namespace extra
}  // namespace lms

Implement BacktraceFormatter for Win32 (NOT tested)


class Solution {
public:
    bool findRotation(vector<vector<int>>& mat, vector<vector<int>>& target) {
        if (check(mat, target))
            return true;
        rotate(mat);
        if (check(mat, target))
            return true;
        rotate(mat);
        if (check(mat, target))
            return true;
        rotate(mat);
        if (check(mat, target))
            return true;
        return false;
    }
private:
    void rotate(std::vector<std::vector<int>>& matrix) {
        int length = matrix.size();
        for(int i=0; i<=length/2; ++i) {
            for(int j=i; j<length-i-1; ++j) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[length-1-j][i];
                matrix[length-1-j][i] = matrix[length-1-i][length-1-j];
                matrix[length-1-i][length-1-j] = matrix[j][length-1-i];
                matrix[j][length-1-i] = temp;
            }
        }
    }

    bool check(std::vector<std::vector<int>>& matrix, std::vector<std::vector<int>>& target) {
        int length = matrix.size();
        for (int i = 0; i < length; ++i) {
            for (int j = 0; j < length; ++j) {
                if (matrix[i][j] != target[i][j])
                    return false;
            }
        }
        return true;
    }
};

Determine Whether Matrix Can Be Obtained By Rotation


#include <iostream>
#include <tuple>
#include <vector>
#include <utility>

using namespace std;

int main() {
    //test 17.1
    auto ituple = make_tuple(10, 20, 30);
    size_t sz = tuple_size<decltype(ituple)>::value;
    cout << sz << endl;
//    for(size_t i = 0; i != sz; ++ i) {
//            const size_t ii = i;
//        cout << get<ii>(ituple) << ends;
//    }
    cout << endl;

    //test 17.2
    tuple<string, vector<string>, pair<string, int>> t("string", {"string", "in", "vector"}, {"string in pair", 0});
    cout << get<0>(t) << endl;
    cout << get<1>(t)[0] << endl;
    cout << get<2>(t).first << endl;
    return 0;
}

Add solution for chapter 17 test 1, test 2


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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

class WindowOpenPanelTest : public ExtensionApiTest {
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnablePanels);
  }
};

#if defined(OS_MACOSX)  // http://crbug.com/162912 || defined(OS_WIN)
// Focus test fails if there is no window manager on Linux.
IN_PROC_BROWSER_TEST_F(WindowOpenPanelTest, WindowOpenFocus) {
  ASSERT_TRUE(RunExtensionTest("window_open/focus")) << message_;
}
#endif

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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

class WindowOpenPanelTest : public ExtensionApiTest {
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnablePanels);
  }
};

// http://crbug.com/162912 || defined(OS_WIN)
// http://crbug.com/253417 for NDEBUG
#if defined(OS_MACOSX) && defined(NDEBUG)
// Focus test fails if there is no window manager on Linux.
IN_PROC_BROWSER_TEST_F(WindowOpenPanelTest, WindowOpenFocus) {
  ASSERT_TRUE(RunExtensionTest("window_open/focus")) << message_;
}
#endif

Disable WindowOpenPanelTest.WindowOpenFocus on Mac debug builds.


// 9. Palindrome Number
/**
 * Determine whether an integer is a palindrome. Do this without extra space.
 *
 * Some hints:
 * Could negative integers be palindromes? (ie, -1)
 *
 * If you are thinking of converting the integer to string, note the restriction of using extra space.
 *
 * You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow.
 * How would you handle such case?
 *
 * There is a more generic way of solving this problem.
 *
 * Tags: Math
 *
 * Similar Problems: (E) Palindrome Linked List
 *
 * Author: Kuang Qin
 */

#include <iostream>
#include <string>

using namespace std;

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0 || (x != 0 && x % 10 == 0)) {
            // negative integers and integers that end with 0 are not palindrome
            return false;
        }

        int rev = 0;
        while (x > rev) {   // reverse the integer till half then compare, no overflow risk
            rev *= 10;
            rev += x % 10;
            x /= 10;
        }

        // even digits: x == rev if palindrome
        // odd digits: x == rev / 10 if padlindrome
        return (x == rev || x == rev / 10);
    }
};

int main() {
    int x = 1221;
    Solution sol;
    bool ans = sol.isPalindrome(x);
    cout << ans << endl;
    cin.get();

    return 0;
}

Add Solution for 009 Palindrome Number


// Verified: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_1_A
struct union_find {
  vector<int> par;
  vector<int> rank;

  union_find (int n) : par(n), rank(n, 0) {
    REP(i,n)par[i]=i;
  }

  int find (int x) {
    if (par[x] == x)
      return x;
    else
      return par[x] = find(par[x]);
  }

  bool same (int x, int y) {
    return find(x) == find(y);
  }

  void unite (int x, int y) {
    x = find(x);
    y = find(y);

    if (x == y)
      return;

    if (rank[x] < rank[y])
      par[x] = y;
    else {
      par[y] = x;
      if (rank[x] == rank[y])
        rank[x]++;
    }
  }
};

Add library (Union find tree)


#include "variant/indicator_platform.hpp"

#include <hal.h>

IndicatorPlatform::IndicatorPlatform() {
}

void IndicatorPlatform::set(IndicatorIntent intent, bool value) {
  switch(intent) {
    case HEARTBEAT:
      //palWritePad(GPIOE, GPIOE_LED3_RED, value);
      break;
    case VEHICLE_ARMED:
      //palWritePad(GPIOE, GPIOE_LED4_BLUE, value);
      break;
  }
}

Add indicator platform to icarus.


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

#define SIZE 10

void generate_function(std::string f_name, int size, int pos, int val)
{
	std::string buff_name = "myOutBuff";

        halide_dimension_t *shape = new halide_dimension_t[1];
        shape[0].min = 0;
        shape[0].extent = 10;
        shape[0].stride = 1;
	Halide::Buffer<> buffer = Halide::Buffer<>(Halide::UInt(8), NULL, 1, shape, buff_name);

	Halide::Internal::Parameter p = Halide::Internal::Parameter(Halide::UInt(8), true, 1, buff_name);
	p.set_buffer(buffer);

	Halide::Expr halideTrue = Halide::Internal::const_true();
	Halide::Internal::Stmt s = Halide::Internal::Store::make(buff_name, Halide::Expr(val), Halide::Expr(pos), p, halideTrue);

	std::cout << s << std::endl;
	s = unpack_buffers(s);

	std::vector<Halide::Argument> args_vect;
	Halide::Argument arg(buff_name, Halide::Argument::Kind::OutputBuffer, Halide::UInt(8), 1);
       	args_vect.push_back(arg);

	Halide::Target target = Halide::get_host_target();

	Halide::Module m(f_name, target);
        Halide::Internal::LoweredFunc ss = Halide::Internal::LoweredFunc(f_name, args_vect, s, Halide::Internal::LoweredFunc::External);
        std::cout << ss << std::endl;

	m.append(ss);
        Halide::Outputs output = Halide::Outputs().object(f_name + ".o");
  	m.compile(output);
  	m.compile(Halide::Outputs().c_header(f_name + ".h"));
}

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

	int pos = 5;
	int val = 3;

	generate_function("my_func", SIZE, pos, val);

	return 0;

}

Add a simple halide file that starts from the low level IR and generates an object file


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

#include "content/renderer/gpu/delegated_compositor_output_surface.h"

namespace content {

DelegatedCompositorOutputSurface::DelegatedCompositorOutputSurface(
    int32 routing_id,
    uint32 output_surface_id,
    const scoped_refptr<ContextProviderCommandBuffer>& context_provider,
    scoped_ptr<cc::SoftwareOutputDevice> software)
    : CompositorOutputSurface(routing_id,
                              output_surface_id,
                              context_provider,
                              software.Pass(),
                              true) {
  capabilities_.delegated_rendering = true;
}

}  // namespace content

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

#include "content/renderer/gpu/delegated_compositor_output_surface.h"

namespace content {

DelegatedCompositorOutputSurface::DelegatedCompositorOutputSurface(
    int32 routing_id,
    uint32 output_surface_id,
    const scoped_refptr<ContextProviderCommandBuffer>& context_provider,
    scoped_ptr<cc::SoftwareOutputDevice> software)
    : CompositorOutputSurface(routing_id,
                              output_surface_id,
                              context_provider,
                              software.Pass(),
                              true) {
  capabilities_.delegated_rendering = true;
  capabilities_.max_frames_pending = 1;
}

}  // namespace content

Revert r227195 - aura: Set max pending frames to the default instead of 1 with ubercomp.


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

using namespace std;

//solution for test 16.63 16.64

template <typename T>
typename vector<T>::size_type countTimes(const vector<T> &vec, const T &target) {
    typename vector<T>::size_type time = 0;
    for(auto elem : vec) {
        if(elem == target) {
            ++ time;
        }
    }
    return time;
}

template <>
vector<const char*>::size_type countTimes(const vector<const char*> &vec, const char* const &target) {
    cout << "specialization  " << ends;
    vector<const char*>::size_type time = 0;
    for(auto elem : vec) {
        if(strcmp(elem, target) == 0) {
            ++ time;
        }
    }
    return time;
}

int main() {
    vector<int> ivec = {1, 2, 2, 3, 4, 1, 2, 4, 6};
    cout << countTimes(ivec, 2) << endl;
    vector<double> dvec = {1.0, 2.0, 3.0, 2.0, 4.0, 1.0, 2.0};
    cout << countTimes(dvec, 1.0) << endl;
    vector<const char*> cvec = {"a", "b", "a", "c"};
    const char* c = "f";
    cout << countTimes(cvec, c) << endl;
    vector<string> svec = {"a", "b", "a", "c"};
    string s = "f";
    cout << countTimes(svec, s) << endl;
}

Add solution for chapter 16 test 63 64


#include <iostream>
#define isOdd(x) (x & 0x01)

using namespace std;

int main (){
    int a =57;
    int b= 32;
    cout << isOdd(a) << endl;
    cout << isOdd(b) << endl;
    return 0;
}

Add useful function to know if a number is even or odd.


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

#include "distortos/board/lowLevelInitialization.hpp"

namespace distortos
{

namespace board
{

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

void lowLevelInitialization()
{

}

}	// namespace board

}	// namespace distortos

Add empty board::lowLevelInitialization() for NUCLEO-F103RB


#include <iostream>

using namespace std;

template <typename T>
void f(T t) {
    cout << "f(T)" << endl;
}

template <typename T>
void f(const T* t) {
    cout << "f(const T*)" << endl;
}

template <typename T>
void g(T t) {
    cout << "g(T)" << endl;
}

template <typename T>
void g(T* t) {
    cout << "g(T*)" << endl;
}

int main() {
    int i = 42, *p = &i;
    const int ci = 0, *p2 = &ci;

    g(42);//g(T)
    g(p);//g(T*)
    g(ci);//g(T)
    g(p2);//g(T*)
    f(42);//f(T)
    f(p);//f(T)
    f(ci);//f(T)
    f(p2);//f(const T*)
}

Add solution for chapter 16 test 49.


#include "chunked-vector.hh"

#include <gtest/gtest.h>

namespace nix {
    TEST(ChunkedVector, InitEmpty) {
        auto v = ChunkedVector<int, 2>(100);
        ASSERT_EQ(v.size(), 0);
    }

    TEST(ChunkedVector, GrowsCorrectly) {
        auto v = ChunkedVector<int, 2>(100);
        for (auto i = 1; i < 20; i++) {
            v.add(i);
            ASSERT_EQ(v.size(), i);
        }
    }

    TEST(ChunkedVector, AddAndGet) {
        auto v = ChunkedVector<int, 2>(100);
        for (auto i = 1; i < 20; i++) {
            auto [i2, idx] = v.add(i);
            auto & i3 = v[idx];
            ASSERT_EQ(i, i2);
            ASSERT_EQ(&i2, &i3);
        }
    }

    TEST(ChunkedVector, ForEach) {
        auto v = ChunkedVector<int, 2>(100);
        for (auto i = 1; i < 20; i++) {
            v.add(i);
        }
        int count = 0;
        v.forEach([&count](int elt) {
            count++;
        });
        ASSERT_EQ(count, v.size());
    }

    TEST(ChunkedVector, OverflowOK) {
        // Similar to the AddAndGet, but intentionnally use a small
        // initial ChunkedVector to force it to overflow
        auto v = ChunkedVector<int, 2>(2);
        for (auto i = 1; i < 20; i++) {
            auto [i2, idx] = v.add(i);
            auto & i3 = v[idx];
            ASSERT_EQ(i, i2);
            ASSERT_EQ(&i2, &i3);
        }
    }

}

Add some tests for ChunkedVector


// TODO: retest this code. It was tested once, but had to be pushed for backup purposes.
// DO TEST IT BEFORE PROPER USE.

// Tarjan for SCC and Edge Biconnected Componentes - O(n + m)
#include <bits/stdc++.h>
using namespace std;

const int N = 1e5+5;

vector<int> adj[N], st;
int num[N], low[N], vis[N], cnt, scc[N], sccn=1;

void dfs(int u, int p) {
  num[u] = low[u] = ++cnt;
  int ch = 0;
  st.push_back(u), vis[u] = 1;

  for(int v : adj[u]) {
    if (!num[v]) dfs(v, u);
    // Uncomment below for biconnected components.
    if (vis[v]/* and v != p*/) low[u] = min(low[u], low[v]);
  }

  if (low[u] == num[u]) while(1) {
      int v = st.back(); st.pop_back();
      scc[v] = sccn, vis[v] = 0;
      if (v == u) { sccn++; break; }
  }
}

void tarjan(int n) { for(int i=1; i<=n; ++i) if (!num[i]) dfs(i, -1); }

Add Tarjan for SCC + binconnected components. Needs further testing.


#include <stdio.h>
#include <algorithm>
#include <iterator>
#include <vector>

using namespace std;

typedef vector <int > vi;

inline void show(vi &data, int &size){
    for (int i=0; i<size; i++)
            printf("%d \t", data[i]);
        printf("\n");
}
inline void permutation(vi data, int size){
    sort(data.begin(), data.end());
    do {
        show(data, size);
    }while(next_permutation(data.begin(), data.end()));
    show(data, size);
}

int main(){
    int size = 3 ;
    int data[] = {1,4,-1};
    vi vals(begin(data), end(data));
    permutation(vals, size);
    return 0;
}

Add simple algorithm over c++ to get the permutations.


/*
 *  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.


// 16. 3Sum Closest
/**
 * Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
 *
 *     For example, given array S = {-1 2 1 -4}, and target = 1.
 *
 *     The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
 *
 * Tags: Array, Two Pointers
 *
 * Similar Problems: (M) 3Sum, (M) 3Sum Smaller
 *
 * Author: Kuang Qin
 */

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

using namespace std;

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int n = nums.size();
        if (n < 3)
            return 0;

        // sort the array
        sort(nums.begin(), nums.end());

        // possible maximum
        int res = nums[n - 3] + nums[n - 2] + nums[n - 1];
        if (res <= target)
            return res;

        // possible minimum
        res = nums[0] + nums[1] + nums[2];
        if (res >= target)
            return res;

        for (int i = 0; i < n - 2; i++)
        {
            // use two pointers to search the closest
            int left = i + 1, right = n - 1;

            while (left < right)
            {
                int sum = nums[i] + nums[left] + nums[right];
                if (abs(sum - target) < abs(res - target))  // res starts from possible minimum
                {
                    res = sum;  // sum is closer, record result
                }

                if (sum < target)
                    while (++left < right && nums[left] == nums[left - 1]) {}   // skip duplicates from left
                else if (sum > target)
                    while (left < --right && nums[right] == nums[right + 1]) {} // skip duplicates from right
                else
                    return sum;
            }
        }

        return res;
    }
};

int main()
{
    vector<int> nums = {-1, 2, 1, -4};
    int target = 1;
    Solution sol;
    int res = sol.threeSumClosest(nums, target);
    cout << res << endl;
    cin.get();

    return 0;
}

Add Solution for 016 3Sum Closest


// RUN: %clang_cc1 -std=c++11 -emit-llvm -g -o - %s | FileCheck %s
// Test that we are emitting debug info and base types for scoped enums.

// CHECK: [ DW_TAG_enumeration_type ] [Color] {{.*}} [from int]
enum class Color { gray };

void f(Color);
void g() {
  f(Color::gray);
}

// CHECK: [ DW_TAG_enumeration_type ] [Colour] {{.*}} [from int]
enum struct Colour { grey };

void h(Colour);
void i() {
  h(Colour::grey);
}

// CHECK: [ DW_TAG_enumeration_type ] [Couleur] {{.*}} [from unsigned char]
enum class Couleur : unsigned char { gris };

void j(Couleur);
void k() {
  j(Couleur::gris);
}

Move debug info tests for scoped enums into a separate file.


////////////////////////////////////////////////////////////////////////////////
/// @brief fundamental types for the optimisation and execution of AQL
///
/// @file arangod/Aql/Types.cpp
///
/// DISCLAIMER
///
/// Copyright 2010-2014 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Max Neunhoeffer
/// @author Copyright 2014, triagens GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "Aql/Types.h"

using namespace triagens::aql;
using Json = triagens::basics::Json;

AqlValue::~AqlValue () {
  switch (_type) {
    case JSON: {
      delete _json;
      return;
    }
    case DOCVEC: {
      for (auto it = _vector->begin(); it != _vector->end(); ++it) {
        delete *it;
      }
      delete _vector;
      return;
    }
    case RANGE: {
      return;
    }
    default:
      return;
  }
}

AqlValue* AqlValue::clone () const {
  switch (_type) {
    case JSON: {
      return new AqlValue(new Json(_json->copy()));
    }
    case DOCVEC: {
      auto c = new vector<AqlItemBlock*>;
      c->reserve(_vector->size());
      for (auto it = _vector->begin(); it != _vector->end(); ++it) {
        c->push_back((*it)->slice(0, (*it)->size()));
      }
      return new AqlValue(c);
    }
    case RANGE: {
      return new AqlValue(_range._low, _range._high);
    }
    default:
      return nullptr;
  }

}

////////////////////////////////////////////////////////////////////////////////
/// @brief splice multiple blocks, note that the new block now owns all
/// AqlValue pointers in the old blocks, therefore, the latter are all
/// set to nullptr, just to be sure.
////////////////////////////////////////////////////////////////////////////////

AqlItemBlock* AqlItemBlock::splice(std::vector<AqlItemBlock*>& blocks)
{
  return nullptr;
}

Add the forgotten file. splice is only a stub.


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

typedef struct _NODE {
  int data;
  _NODE* next;
  _NODE* prev;
} NODE;

void push(NODE** head_ref, int data) {
  NODE* node = new NODE();
  node->data = data;
  node->next = *head_ref;
  node->prev = NULL;

  if (*head_ref != nullptr) {
    (*head_ref)->prev = node;
  }

  *head_ref = node;
}

void printList(NODE* node) {
  while (node) {
    printf("%d ", node->data);
    node = node->next;
  }
}

void deleteNode(NODE** head_ref, NODE* dNode) {
  if (*head_ref == nullptr || dNode == nullptr) {
    return;
  }

  if (*head_ref == dNode) {
    *head_ref = dNode->next;
  }

  if (dNode->next != nullptr) {
    dNode->next->prev = dNode->prev;
  }

  if (dNode->prev != nullptr) {
    dNode->prev->next = dNode->next;
  }

  free(dNode);
}

int main(int argc, char const* argv[]) {
  /* Start with the empty list */
  NODE* head = nullptr;

  /* Let us create the doubly linked list 10<->8<->4<->2 */
  push(&head, 2);
  push(&head, 4);
  push(&head, 8);
  push(&head, 10);

  printf("\n Original Linked list ");
  printList(head);

  /* delete nodes from the doubly linked list */
  deleteNode(&head, head);       /*delete first node*/
  deleteNode(&head, head->next); /*delete middle node*/
  deleteNode(&head, head->next); /*delete last node*/

  /* Modified linked list will be NULL<-8->NULL */
  printf("\n Modified Linked list ");
  printList(head);
  return 0;
}

Delete Doubly Linked List Node.


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(NULL == head || NULL == head->next) return head;
        ListNode *prev = head, *current = head->next;
        int v = head->val;
        while(current){
            bool dup = false;
            while(current && current->val == v){
                dup = true;
                current = current->next;
            }
            if(dup){
                if(head->val == v){
                    head = prev = current;
                }else{
                    prev->next = current;
                }
            }else if(prev && prev->next != current){
                prev = prev->next;
            }
            if(current){
                v = current->val;
                current = current->next;
            }
        }
        return head;
    }
};

Remove Duplicates from Sorted List II


// RUN: %llvmgxx %s -S -o - | FileCheck %s
// Make sure pointers are passed as pointers, not converted to int.
// The first load should be of type i8** in either 32 or 64 bit mode.
// This formerly happened on x86-64, 7375899.

class StringRef {
public:
  const char *Data;
  long Len;
};
void foo(StringRef X);
void bar(StringRef &A) {
// CHECK: @_Z3barR9StringRef
// CHECK: load i8**
  foo(A);
// CHECK: ret void
}

Test for llvm-gcc checkin 89898.


#include <gpio.h> // gpio pin controllling

int main()
{
    // defines the variable ledPin and refers it to an GPIO-Pin
    auto ledPin = gpio::output_pin(15);

    // loop 10 times
    for (int i = 0; i < 10; i++) {
        // pin is set true, pin is HIGH, LED is on
        ledPin.set_state(true);
        // pause for 500ms, status is on hold and stays true
        delay(500);

        // pin set false again, pin is LOW, LED is off
        ledPin.set_state(false);
        // 500ms pause
        delay(500);
    }

    return EXIT_SUCCESS;
}

Add simple led tutorial code


#include <iostream>
#include <string>
#include <regex>

using namespace std;

int main() {
    string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})";
    regex r(phone);
    string s;
    string fmt = "$2.$5.$7";
    while(getline(cin, s)) {
        cout << regex_replace(s, r, fmt) << endl;
    }
    return 0;
}

Add solution for chapter 17 test 24


//
// Copyright (c) 2002-2010 The ANGLE 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.
//

// debug.cpp: Debugging utilities.

#include "common/debug.h"

#include <stdio.h>
#include <stdarg.h>

namespace gl
{
void trace(const char *format, ...)
{
    if (true)
    {
        if (format)
        {
            FILE *file = fopen("debug.txt", "a");

            if (file)
            {
                va_list vararg;
                va_start(vararg, format);
                vfprintf(file, format, vararg);
                va_end(vararg);

                fclose(file);
            }
        }
    }
}
}

//
// Copyright (c) 2002-2010 The ANGLE 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.
//

// debug.cpp: Debugging utilities.

#include "common/debug.h"

#include <stdio.h>
#include <stdarg.h>

static bool trace_on = true;

namespace gl
{
void trace(const char *format, ...)
{
    if (trace_on)
    {
        if (format)
        {
            FILE *file = fopen("debug.txt", "a");

            if (file)
            {
                va_list vararg;
                va_start(vararg, format);
                vfprintf(file, format, vararg);
                va_end(vararg);

                fclose(file);
            }
        }
    }
}
}

Make it easier to disable tracing


// 371. Sum of Two Integers
/**
 * Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
 *
 * Example:
 * Given a = 1 and b = 2, return 3.
 *
 * Tags: Bit Manipulation
 *
 * Similar Problems:  (M) Add Two Numbers
 *
 * Author: Kuang Qin
 */

#include <iostream>

using namespace std;

class Solution {
public:
    int getSum(int a, int b) {
        return b == 0 ? a : getSum(a ^ b, (a & b) << 1);
    }
};

int main() {
    Solution sol;
    cout << sol.getSum(1, 2) << endl;
    cin.get();
    return 0;
}

Add Solution for 371 Sum of Two Integers


#include <bits/stdc++.h>

using namespace std;
// Constants
const double PI = acos(-1);
struct point {
    double x;
    double y;
    point (){}
    point (double _x, double _y){
        x = _x;
        y = _y;
    }
};

inline point get_center(point A, point B, point C){

    float yDelta_a = B.y - A.y;
    float xDelta_a = B.x - A.x;
    float yDelta_b = C.y - B.y;
    float xDelta_b = C.x - B.x;

    point center;

    float aSlope = yDelta_a/xDelta_a;
    float bSlope = yDelta_b/xDelta_b;

    center.x = (aSlope*bSlope*(A.y - C.y) + bSlope*(A.x + B.x)
                - aSlope*(B.x+C.x) )/(2* (bSlope-aSlope) );
    center.y = -1*(center.x - (A.x+B.x)/2)/aSlope +  (A.y+B.y)/2;

    return center;
}

Add algorithm for computing the center of a circle based on three points.


// 8.exercise.04.cpp
//
//  An int can hold integers only up to a maximum number. Find an approximation
//  of that maximum number by using fibonacci().
//
//  COMMENTS

#include "std_lib_facilities.h"

void print(const string& label, const vector<int>& data)
// Only read arguments, so it safe to pass them by const-reference
{
    cout << label << ": { ";
    for (int i : data)
        cout << i << ' ';
    cout << "}\n";
}

int check_add(int a, int b)
// Adds two integers performing overflow control to avoid undefined behavior.
// (Search for INT32-C on https://www.securecoding.cert.org)
{
    if (((b > 0) && (a > (numeric_limits<int>::max() - b))) ||
        ((b < 0) && (a < (numeric_limits<int>::min() - b))))
            error("check_add(): integer add overflows.");
    else
        return a+b;
}

void fibonacci(int x, int y, vector<int>& v, int n)
// Generates a Fibonacci sequence of n values into v, starting with values x
// and y (integers passed by value, and we are modifying v, so it is passed by
// reference).
// Preconditions:
//  Vector must be empty
//  To simplify, n must be equal or greater than two.
{
    if (v.size() != 0)
        error("fibonacci(): Non empty vector passed as argument.");
    if (n < 2)
        error("fibonacci(): n must be al least 2.");

    v.push_back(x);
    v.push_back(y);

    for (int i = 2; i < n; ++i)
        //v.push_back(v[i-2] + v[i-1]);
        v.push_back(check_add(v[i-2],v[i-1]));
}

int main()
// Test the fibonacci function
try {
    return 0;
}
catch(exception& e)
{
    cerr << e.what() << '\n';
    return 1;
}
catch(...)
{
    cerr << "Unknwon exception!!\n";
    return 2;
}

Prepare exercise 4 from chapter 8.


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

#include "chrome/browser/download/download_completion_blocker.h"

#include "base/logging.h"

DownloadCompletionBlocker::DownloadCompletionBlocker()
  : is_complete_(false) {
}

DownloadCompletionBlocker::~DownloadCompletionBlocker() {
}

void DownloadCompletionBlocker::CompleteDownload() {
  DCHECK(!is_complete_);
  is_complete_ = true;
  if (callback_.is_null())
    return;
  callback_.Run();
  callback_.Reset();
}

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

#include "chrome/browser/download/download_completion_blocker.h"

#include "base/logging.h"

DownloadCompletionBlocker::DownloadCompletionBlocker()
  : is_complete_(false) {
}

DownloadCompletionBlocker::~DownloadCompletionBlocker() {
}

void DownloadCompletionBlocker::CompleteDownload() {
  // Do not run |callback_| more than once.
  if (is_complete_)
    return;
  is_complete_ = true;

  if (callback_.is_null())
    return;
  callback_.Run();
  // |callback_| may delete |this|, so do not rely on |this| after running
  // |callback_|!
}

Fix crasher in DownloadCompletionBlocker BUG=130324


// RUN: %clang_cc1 %s -verify -fsyntax-only
// Note: most of the 'nodebug' tests are in attr-nodebug.c.

// expected-no-diagnostics
class c {
  void t3() __attribute__((nodebug));
};

Add a test showing that nodebug is accepted in methods too. Patch by Paul Robinson.


#include "PackageDatagram.h"

// Constructors

PackageDatagram::PackageDatagram(char* data, unsigned int length, char* ip, int port)
{
	this->data = new char[length];
	memcpy(this->data, data, length);

	this->length = length;
	memcpy(this->ip, ip, sizeof this->ip);
	this->port = port;
}

PackageDatagram::PackageDatagram(unsigned int length)
{
	this->length = length;
}

PackageDatagram::~PackageDatagram(){

}

// Public Methods

char* PackageDatagram::getIp(){
	return ip;
}
unsigned int PackageDatagram::getLength(){
	return length;
}
int PackageDatagram::getPort(){
	return port;
}
char* PackageDatagram::getData(){
	return data;
}

void PackageDatagram::setPort(int port)
{
	this->port = port;
}
void PackageDatagram::setIp(char* ip)
{
	for(int i=0; i < 16; i++){
		this->ip[i] = ip[i];
	}
}
void PackageDatagram::setData(char* data){

	this->data = data;
}

Package Datagram Class Behaviour defined


// RUN: %clang_cc1 %s -emit-llvm-only
// CHECK that we don't crash.

int main(void){
	int x = 12;
	// Make sure we don't crash when constant folding the case 4
	// statement due to the case 5 statement contained in the do loop
	switch (4) {
		case 4: do { case 5: x++;} while (x < 100);
	}
	return x;
}

Patch for r148243 which was left behind.


// Copyright (c) 2013 Stanislas Polu.
// Copyright (c) 2012 The Chromium Authors.
// See the LICENSE file.

#include "exo/exo_browser/common/switches.h"

namespace switches {

// Makes ExoBrowser use the given path for its data directory.
const char kExoBrowserDataPath[] = "data-path";
// Prevents the launch of Exo and runs the ExoBrowser in "raw" mode
const char kExoBrowserRaw[] = "exo-browser";

// Allow access to external pages during layout tests.
const char kAllowExternalPages[] = "allow-external-pages";

// Enable accelerated 2D canvas.
const char kEnableAccelerated2DCanvas[] = "enable-accelerated-2d-canvas";

// Encode binary layout test results (images, audio) using base64.
const char kEncodeBinary[] = "encode-binary";

}  // namespace switches

// Copyright (c) 2013 Stanislas Polu.
// Copyright (c) 2012 The Chromium Authors.
// See the LICENSE file.

#include "exo/exo_browser/common/switches.h"

namespace switches {

// Makes ExoBrowser use the given path for its data directory.
const char kExoBrowserDataPath[] = "data-path";
// Prevents the launch of Exo and runs the ExoBrowser in "raw" mode
const char kExoBrowserRaw[] = "raw";

// Allow access to external pages during layout tests.
const char kAllowExternalPages[] = "allow-external-pages";

// Enable accelerated 2D canvas.
const char kEnableAccelerated2DCanvas[] = "enable-accelerated-2d-canvas";

// Encode binary layout test results (images, audio) using base64.
const char kEncodeBinary[] = "encode-binary";

}  // namespace switches

Change switch name to "--raw"


// RUN: clang-cc -fsyntax-only -verify %s
template<class T1>
class A {
  template<class T2> class B {
    void mf();
  };
};

template<> template<> class A<int>::B<double>;
template<> template<> void A<char>::B<char>::mf();

template<> void A<char>::B<int>::mf(); // expected-error{{requires 'template<>'}}

Test explicit specialization involving multiple template<> headers