// Makes sure it doesn't crash.

// XFAIL: linux

// RUN: rm -rf %t
// RUN: not %clang_cc1 %s -index-store-path %t/idx -std=c++14
// RUN: c-index-test core -print-record %t/idx | FileCheck %s

namespace rdar32474406 {
void foo();
typedef void (*Func_t)();
// CHECK: [[@LINE+4]]:1 | type-alias/C | c:record-hash-crash-invalid-name.cpp@N@rdar32474406@T@Func_t | Ref,RelCont | rel: 1
// CHECK-NEXT: RelCont | c:@N@rdar32474406
// CHECK: [[@LINE+2]]:14 | function/C | c:@N@rdar32474406@F@foo# | Ref,RelCont | rel: 1
// CHECK-NEXT: RelCont | c:@N@rdar32474406
Func_t[] = { foo }; // invalid decomposition
}

Add a test for a crash with unnamed NamedDecls


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

// Enunciado: https://www.hackerrank.com/challenges/flipping-the-matrix

int main() {
    unsigned q, n;
    cin >> q;
    for (int cq = 0; cq < q; ++cq) {
        cin >> n;

        // Cada elemento tiene 4 posiciones posibles mediante las operaciones dadas
        // Idea 3 (la buena): basta tomar el máximo de las 4 posiciones posibles para cada elemento del cuadrante

        vector<vector<unsigned>> m(2*n, vector<unsigned>(2*n));

        for (auto& v : m) {
            for (unsigned& e : v) {
                cin >> e;
            }
        }

        long long unsigned sum = 0;

        for (unsigned i = 0; i < n; ++i) {
            for (unsigned j = 0; j < n; ++j) {
                // calcular las 4 posiciones simétricas respecto de los ejes centrales
                sum += max(
                    m[i][j], max(
                    m[2*n-i-1][j], max(
                    m[i][2*n-j-1],
                    m[2*n-i-1][2*n-j-1])));
            }
        }

        cout << sum << endl;
    }

    return 0;
}

Add problem: Flipping the matrix


#include <memory>
#include <string>

#include <SFCGAL/all.h>
#include <SFCGAL/Kernel.h>
#include <SFCGAL/io/Serialization.h>

#include <boost/test/unit_test.hpp>
using namespace boost::unit_test ;

using namespace SFCGAL ;

BOOST_AUTO_TEST_SUITE( SFCGAL_io_WktReaderTest )

BOOST_AUTO_TEST_CASE( textTest )
{
	Kernel::Point_2 pt( 2.3, 4.5 );
	Kernel::Point_2 rpt;

	std::ostringstream ostr;
	boost::archive::text_oarchive arc( ostr );
	arc << pt;

	std::string str = ostr.str();

	std::istringstream istr( str );
	boost::archive::text_iarchive iarc( istr );
	iarc >> rpt;

	BOOST_CHECK( pt == rpt );
}

BOOST_AUTO_TEST_CASE( binaryTest )
{
	Kernel::Point_2 pt( 2.3, 4.5 );
	Kernel::Point_2 rpt;

	std::ostringstream ostr;
	boost::archive::binary_oarchive arc( ostr );
	arc << pt;

	std::string str = ostr.str();

	std::istringstream istr( str );
	boost::archive::binary_iarchive iarc( istr );
	iarc >> rpt;

	BOOST_CHECK( pt == rpt );
}

BOOST_AUTO_TEST_SUITE_END()

Add a unit test for serialization


#include "HaxeRuntime.h"
#include "VariantPtr.h"
#include "CoreMinimal.h"
#include "HaxeInit.h"

void unreal::VariantPtr::badAlignmentAssert(UIntPtr value)
{
  UE_LOG(HaxeLog, Fatal, TEXT("The pointer %llx was not aligned and is not supported by Unreal.hx"), value);
}

Update to latest perforce change Change 21906 by waneck@wnk-razer on 2018/07/20 09:33:21


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

#include "mojo/common/user_agent.h"

namespace mojo {
namespace common {

std::string GetUserAgent() {
  // TODO(jam): change depending on OS
  return "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like "
         "Gecko) Chrome/42.0.2311.68 Safari/537.36";
}

}  // namespace common
}  // namespace mojo

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

#include "mojo/common/user_agent.h"

#include "build/build_config.h"

namespace mojo {
namespace common {

std::string GetUserAgent() {
  // TODO(jam): change depending on OS
#if defined(OS_ANDROID)
  return "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 7 Build/LMY48G) "
         "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.68 "
         "Safari/537.36";
#else
  return "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like "
         "Gecko) Chrome/42.0.2311.68 Safari/537.36";
#endif
}

}  // namespace common
}  // namespace mojo

Use a different User-Agent for Android build.


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

#include "Benchmark.h"
#include "Resources.h"
#include "SkBitmap.h"
#include "SkData.h"
#include "SkImageEncoder.h"

class EncodeBench : public Benchmark {
public:
    EncodeBench(const char* filename, SkImageEncoder::Type type, int quality)
        : fFilename(filename)
        , fType(type)
        , fQuality(quality)
    {
        // Set the name of the bench
        SkString name("Encode_");
        name.append(filename);
        name.append("_");
        switch (type) {
            case SkImageEncoder::kJPEG_Type:
                name.append("JPEG");
                break;
            case SkImageEncoder::kPNG_Type:
                name.append("PNG");
                break;
            case SkImageEncoder::kWEBP_Type:
                name.append("WEBP");
                break;
            default:
                name.append("Unknown");
                break;
        }

        fName = name;
    }

    bool isSuitableFor(Backend backend) override { return backend == kNonRendering_Backend; }

    const char* onGetName() override { return fName.c_str(); }

    void onPreDraw(SkCanvas*) override {
#ifdef SK_DEBUG
        bool result =
#endif
        GetResourceAsBitmap(fFilename, &fBitmap);
        SkASSERT(result);
    }

    void onDraw(int loops, SkCanvas*) override {
        for (int i = 0; i < loops; i++) {
            SkAutoTUnref<SkData> data(SkImageEncoder::EncodeData(fBitmap, fType, fQuality));
            SkASSERT(data);
        }
    }

private:
    const char*                fFilename;
    const SkImageEncoder::Type fType;
    const int                  fQuality;
    SkString                   fName;
    SkBitmap                   fBitmap;
};

// The Android Photos app uses a quality of 90 on JPEG encodes
DEF_BENCH(return new EncodeBench("mandrill_512.png", SkImageEncoder::kJPEG_Type, 90));
DEF_BENCH(return new EncodeBench("color_wheel.jpg", SkImageEncoder::kJPEG_Type, 90));

// PNG encodes are lossless so quality should be ignored
DEF_BENCH(return new EncodeBench("mandrill_512.png", SkImageEncoder::kPNG_Type, 90));
DEF_BENCH(return new EncodeBench("color_wheel.jpg", SkImageEncoder::kPNG_Type, 90));

// TODO: What is the appropriate quality to use to benchmark WEBP encodes?
DEF_BENCH(return new EncodeBench("mandrill_512.png", SkImageEncoder::kWEBP_Type, 90));
DEF_BENCH(return new EncodeBench("color_wheel.jpg", SkImageEncoder::kWEBP_Type, 90));

Add bench for image encodes


#include <iostream>

using namespace std;

class Pizza {
  char name[30];
  double price;

public:

  Pizza(const char _name[] = "", double _price = 0): price(_price) {
    strcpy(name, _name);
  }

  double getPrice() {
    return price;
  }
};

class Order {
  Pizza pizzas[20];
  int pizzasCount;

public:

  Order(): pizzasCount(0) {}

  void addPizza(const Pizza& pizza) {
    pizzas[pizzasCount++] = pizza;
  }

  double getTotalPrice() {
    double total = 0;

    for (int i = 0; i < pizzasCount; ++i) {
      total += pizzas[i].getPrice();
    }

    return total;
  }
};

class Client {
  char name[30];
  Order orders[10];
  int ordersCount;

public:

  Client(const char _name[]): ordersCount(0) {
    strcpy(name, _name);
  }

  void addOrder(const Order& order) {
    orders[ordersCount++] = order;
  }

  double getOrdersPrice() {
    double ordersPrice = 0;

    for (int i = 0; i < ordersCount; ++i) {
      ordersPrice += orders[i].getTotalPrice();
    }

    return ordersPrice;
  }
};

int main() {
  Pizza capricciosa("Capricciosa", 9);
  Pizza margherita("Margherita", 6.5);
  Pizza calzone("Calzone", 8);

  Order order1;
  order1.addPizza(calzone);
  order1.addPizza(margherita);

  Order order2;
  order2.addPizza(capricciosa);
  order2.addPizza(margherita);
  order2.addPizza(capricciosa);

  Client ivan("Ivan");
  ivan.addOrder(order1);
  ivan.addOrder(order2);

  cout << ivan.getOrdersPrice() << '\n';

  return 0;
}

Add solution to the second problem of the first test


// This is a regression test on debug info to make sure we don't hit a compile unit size
// issue with gdb.
// RUN: %llvmgcc -S -O0 -g %s -o - | llvm-as | llc --disable-fp-elim -o Output/NoCompileUnit.s -f
// RUN: as Output/NoCompileUnit.s -o Output/NoCompileUnit.o
// RUN: g++ Output/NoCompileUnit.o -o Output/NoCompileUnit.exe
// RUN: ( echo "break main"; echo "run" ; echo "p NoCompileUnit::pubname" ) > Output/NoCompileUnit.gdbin
// RUN: gdb -q -batch -n -x Output/NoCompileUnit.gdbin Output/NoCompileUnit.exe | tee Output/NoCompileUnit.out | not grep '"low == high"'
// XFAIL: i[1-9]86|alpha|ia64|arm

class MamaDebugTest {
private:
  int N;

protected:
  MamaDebugTest(int n) : N(n) {}

  int getN() const { return N; }

};

class BabyDebugTest : public MamaDebugTest {
private:

public:
  BabyDebugTest(int n) : MamaDebugTest(n) {}

  static int doh;

  int  doit() {
    int N = getN();
    int Table[N];

    int sum = 0;

    for (int i = 0; i < N; ++i) {
      int j = i;
      Table[i] = j;
    }
    for (int i = 0; i < N; ++i) {
      int j = Table[i];
      sum += j;
    }

    return sum;
  }

};

int BabyDebugTest::doh;

int main(int argc, const char *argv[]) {
  BabyDebugTest BDT(20);
  return BDT.doit();
}

Add compile unit size test


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

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

#include "gtest/gtest.h"

#include <Rosetta/Actions/Generic.hpp>
#include <Rosetta/Enums/CardEnums.hpp>
#include <Rosetta/Games/Game.hpp>

using namespace RosettaStone;

TEST(Generic, GetZone)
{
    GameConfig config;
    config.player1Class = CardClass::ROGUE;
    config.player2Class = CardClass::PALADIN;
    config.startPlayer = PlayerType::PLAYER1;
    config.doFillDecks = true;
    config.autoRun = false;

    Game game(config);
    game.StartGame();
    game.ProcessUntil(Step::MAIN_START);

    Player& curPlayer = game.GetCurrentPlayer();

    EXPECT_EQ(&curPlayer.GetDeckZone(),
              Generic::GetZone(curPlayer, ZoneType::DECK));
    EXPECT_EQ(&curPlayer.GetFieldZone(),
              Generic::GetZone(curPlayer, ZoneType::PLAY));
    EXPECT_EQ(&curPlayer.GetGraveyardZone(),
              Generic::GetZone(curPlayer, ZoneType::GRAVEYARD));
    EXPECT_EQ(&curPlayer.GetHandZone(),
              Generic::GetZone(curPlayer, ZoneType::HAND));
    EXPECT_EQ(&curPlayer.GetSecretZone(),
              Generic::GetZone(curPlayer, ZoneType::SECRET));
    EXPECT_EQ(&curPlayer.GetSetasideZone(),
              Generic::GetZone(curPlayer, ZoneType::SETASIDE));
    EXPECT_EQ(nullptr, Generic::GetZone(curPlayer, ZoneType::INVALID));
    EXPECT_EQ(nullptr, Generic::GetZone(curPlayer, ZoneType::REMOVEDFROMGAME));
}

Add unit test for Generic::GetZone() function


#include <iostream>
using namespace std;

int main() {
	int N = 4;
	char items[] = {'a', 'b', 'c', 'd'};
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < N; j++) {
			cout<<items[i^j]<<" ";
		}
		cout<<endl;
	}
	return 0;
}

Implement algorithm to print symmetrix matrix


#include "Output.h"

Output output;

void varArgFunc(int numParams, ...)
{
	__builtin_va_list ap;
	__builtin_va_start(ap, numParams);

	for (int i = 0; i < numParams; i++)
		output << __builtin_va_arg(ap, int);

	__builtin_va_end(ap);
}

int main()
{
	varArgFunc(4, 0xaaaaaaaa, 0xbbbbbbbb, 0xcccccccc, 0xdddddddd);

	// CHECK: 0xaaaaaaaa
	// CHECK: 0xbbbbbbbb
	// CHECK: 0xcccccccc
	// CHECK: 0xdddddddd
}

Add test for variadic functions.


#include <osrm/coordinate.hpp>

#include <boost/test/unit_test.hpp>

// Regression test for bug captured in #1347
BOOST_AUTO_TEST_CASE(regression_test_1347)
{
    FixedPointCoordinate u(10 * COORDINATE_PRECISION, -100 * COORDINATE_PRECISION);
    FixedPointCoordinate v(10.001 * COORDINATE_PRECISION, -100.002 * COORDINATE_PRECISION);
    FixedPointCoordinate q(10.002 * COORDINATE_PRECISION, -100.001 * COORDINATE_PRECISION);

    float d1 = FixedPointCoordinate::ComputePerpendicularDistance(u, v, q);

    float ratio;
    FixedPointCoordinate nearest_location;
    float d2 = FixedPointCoordinate::ComputePerpendicularDistance(u, v, q, nearest_location, ratio);

    BOOST_CHECK_LE(std::abs(d1 - d2), 0.01);
}

Add regression test for FixedpointCoordinate


#include <iostream>

using namespace std;

class BankAccount {
  char clientName[23];
  char id[15];
  double account;

public:

  BankAccount(const char _clientName[], const char _id[], double _account) {
    strcpy(clientName, _clientName);
    strcpy(id, _id);
    account = _account;
  }

  void print() {
    cout << "Name: " << clientName << '\n' <<
            "Account ID: " << id << '\n' <<
            "Account: " << account << '\n';
  }

  void transfer(double amount) {
    account += amount;
  }

  void draw(double amount) {
    account -= amount;
  }
};

int main() {
  BankAccount bankAccount("Ivan", "1", 2000);
  bankAccount.print();

  bankAccount.transfer(300);
  bankAccount.print();

  bankAccount.draw(500);
  bankAccount.print();

  return 0;
}

Add solution to first problem


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

using namespace std;

int main (){
    freopen("data.in", "r", stdin);
    freopen("data.out", "w", stdout);

    return 0;

}

Insert useful script for windows computers, standard input output.


// RUN: %clangxx_tsan -O1 %s -o %t && %t 2>&1 | FileCheck %s
#include <pthread.h>
#include <unistd.h>

pthread_rwlock_t rwlock;
int GLOB;

void *Thread1(void *p) {
  (void)p;
  pthread_rwlock_rdlock(&rwlock);
  // Write under reader lock.
  usleep(100);
  GLOB++;
  pthread_rwlock_unlock(&rwlock);
  return 0;
}

int main(int argc, char *argv[]) {
  pthread_rwlock_init(&rwlock, NULL);
  pthread_rwlock_rdlock(&rwlock);
  pthread_t t;
  pthread_create(&t, 0, Thread1, 0);
  volatile int x = GLOB;
  (void)x;
  pthread_rwlock_unlock(&rwlock);
  pthread_join(t, 0);
  pthread_rwlock_destroy(&rwlock);
  return 0;
}

// CHECK: WARNING: ThreadSanitizer: data race
// CHECK:   Write of size 4 at {{.*}} by thread 1:
// CHECK:     #0 Thread1(void*) {{.*}}write_in_reader_lock.cc:13
// CHECK:   Previous read of size 4 at {{.*}} by main thread:
// CHECK:     #0 main {{.*}}write_in_reader_lock.cc:23

Add output test for write under reader lock


#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>

bool is_whitespace(char c) {
	return c == ' ' || c == '\t' || c == '\n';
}

void add_words(std::vector<std::string> &dest, const std::string &s) {
	char *begin, *end;
	char t;
	end = begin = (char*)s.c_str();
	while (*begin != '\0') {
		while (!is_whitespace(*end) && *end != '\0')
				end++;
		if (*end == '\0') {
			dest.push_back(std::string(begin));
			break;
		}
		t = *end;
		*end = '\0';
		dest.push_back(std::string(begin));
		*end = t;
		for (begin = ++end; is_whitespace(*begin); begin = ++end);
	}
}

void populate_iindex(std::map<std::string, std::map<std::string, int>> &iindex, const std::string &fname) {
	std::ifstream in(fname);
	if (!in)
		throw in.rdstate();
	std::stringstream txt;
	txt << in.rdbuf();
	in.close();
	std::vector<std::string> words;
	add_words(words, txt.str());
	for (auto &w : words)
		iindex[w][fname] += 1;
}

int main() {
	std::map<std::string, std::map<std::string, int>> iindex;
	std::vector<std::string> files = {"bloom.cc", "cache.go", "quicksort.c", "self-repl.py"};
	for (auto &f : files)
		populate_iindex(iindex, f);
	std::string input;
	while (std::cin.good()) {
		std::cout << "Enter your search term: ";
		if (!std::getline(std::cin, input) || !iindex.count(input))
			goto endloop;
		for (auto &it : iindex[input])
			std::cout << it.first << ": " << it.second << "\n";
		endloop:
		std::cout << "\n";
	}
	return 0;
}

Add basic inverted index implementation in C++


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

using namespace Halide;

int count = 0;
int my_trace(void *user_context, const halide_trace_event *ev) {
    if (ev->event == halide_trace_load) {
        count++;
    }
    return 0;
}

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

    Func f;
    Var x, y;

    Func in;
    in(x, y) = x + y;
    in.compute_root();

    // Set f to zero
    f(x, y) = 0;

    // Then iterate over a circle, adding in(x, y) to f.
    Expr t = cast<int>(ceil(sqrt(10*10 - y*y)));
    f(x, y) += select(x > -t && x < t, likely(in(x, y)), 0);

    in.trace_loads();
    f.set_custom_trace(my_trace);
    f.realize(20, 20);

    int c = 0;
    for (int y = 0; y < 20; y++) {
        for (int x = 0; x < 20; x++) {
            if (x*x + y*y < 10*10) c++;
        }
    }

    if (count != c) {
        printf("Func 'in' should only have been loaded from at points "
               "within the circle x*x + y*y < 10*10. It was loaded %d "
               "times, but there are %d points within that circle\n", count, c);
        return -1;
    }

    return 0;
}

Add test that uses likely intrinsic to iterate over a circlular domain!


// 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 "chrome/common/chrome_switches.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace extensions {

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

  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    ExtensionApiTest::SetUpInProcessBrowserTestFixture();
  }
};

IN_PROC_BROWSER_TEST_F(AutomationApiTest, SanityCheck) {
  ASSERT_TRUE(RunComponentExtensionTest("automation/sanity_check")) << message_;
}

}  // namespace extensions

// 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 "chrome/common/chrome_switches.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace extensions {

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

  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    ExtensionApiTest::SetUpInProcessBrowserTestFixture();
  }
};

// http://crbug.com/353039
IN_PROC_BROWSER_TEST_F(AutomationApiTest, DISABLED_SanityCheck) {
  ASSERT_TRUE(RunComponentExtensionTest("automation/sanity_check")) << message_;
}

}  // namespace extensions

Disable new flaky test. BUG=353039 TBR=dtseng


#include <silicon/api.hh>
#include <silicon/remote_api.hh>
#include <silicon/websocketpp.hh>

using websocketpp::connection_hdl;

struct session
{

  static session* instantiate(connection_hdl c)
  {
    auto it = sessions.find(c);
    if (it != sessions.end()) return &(it->second);
    else
    {
      std::unique_lock<std::mutex> l(sessions_mutex);
      return &(sessions[c]);
    }
  }

  static session* find(std::string n)
  {
    for (auto& it : sessions) if (it.second.nickname == n) return &it.second;
    return 0;
  }

  std::string nickname;

private:
  static std::mutex sessions_mutex;
  static std::map<connection_hdl, session> sessions;
};

std::mutex session::sessions_mutex;
std::map<connection_hdl, session> session::sessions;

int main(int argc, char* argv[])
{
  using namespace sl;

  // The remote client api accessible from this server.
  auto client_api = make_remote_api(   @broadcast(@from, @text), @pm(@from, @text)  );

  // The type of a client to call the remote api.
  typedef ws_client<decltype(client_api)> client;
  // The list of client.
  typedef ws_clients<decltype(client_api)> clients;

  // The server api accessible by the client.
  auto server_api = make_api(

    // Set nickname.
    @nick(@nick) = [] (auto p, session* s, client& c) {
      while(session::find(p.nick)) p.nick += "_";
      s->nickname = p.nick;
      return D(@nick = s->nickname);
    },

    // Broadcast a message to all clients.
    @broadcast(@message) = [] (auto p, session* s, clients& cs) {
      cs | [&] (client& c) { c.broadcast(s->nickname, p.message); };
    },

    // Private message.
    @pm(@to, @message) = [] (auto p, session* s, clients& cs) {
      cs | [&] (client& c2, session* s2) {
        if (s2->nickname == p.to)
          c2.pm(s->nickname, p.message);
      };
    }

    );

  websocketpp_json_serve(server_api, client_api, atoi(argv[1]));

}

Add a chat websocket test.


#include <iostream>

//Function to find the number of closed loops in a given number.
int closed_loops(int n){
    int counter = 0;
    while(n!=0){
        int r = n%10;
        if ((r==6) || (r==9) || (r==0))
            counter++;
        if (r==8)
            counter+=2;
        n=n/10;
    }
    return counter;
}

// Driver function.
int main() {
    int num1 = 2876;
    int num2 = 7589;
    int num3 = 1075;
    std::cout << closed_loops(num1) << std::endl;
    std::cout << closed_loops(num2) << std::endl;
    std::cout << closed_loops(num3) << std::endl;
}

Add a C++ solution to the closed loops problem.


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

namespace StdExample {

constexpr int f(void *) { return 0; }
constexpr int f(...) { return 1; }
constexpr int g1() { return f(0); }
constexpr int g2(int n) { return f(n); }
constexpr int g3(int n) { return f(n*0); }

namespace N {
  constexpr int c = 5;
  constexpr int h() { return c; }
}
constexpr int c = 0;
constexpr int g4() { return N::h(); }

// FIXME: constexpr calls aren't recognized as ICEs yet, just as foldable.
#define JOIN2(a, b) a ## b
#define JOIN(a, b) JOIN2(a, b)
#define CHECK(n, m) using JOIN(A, __LINE__) = int[n]; using JOIN(A, __LINE__) = int[m];
CHECK(f(0), 0)
CHECK(f('0'), 1)
CHECK(g1(), 0)
CHECK(g2(0), 1)
CHECK(g2(1), 1)
CHECK(g3(0), 1)
CHECK(g3(1), 1)
CHECK(N::h(), 5)
CHECK(g4(), 5)

}

Add test missed from r143234.


// 016. 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
 *
 * Author: Kuang Qin
 */

#include "stdafx.h"
#include <algorithm>
#include <vector>

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());

        // let the result be the possible maximum
        int result = nums[n - 1] + nums[n - 2] + nums[n - 3];
        if (result <= target)
        {
            return result;
        }

        // let the result be the possible minimum
        result = nums[0] + nums[1] + nums[2];
        if (result >= target)
        {
            return result;
        }

        for (int i = 0; i < n - 2; i++)
        {
            // use two pointers, adjust sum by moving left or right pointer
            int left = i + 1, right = n - 1;

            while (left < right)
            {
                int sum = nums[left] + nums[right] + nums[i];

                if (abs(sum - target) < abs(result - target))
                {
                    result = sum;
                }

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

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

        return result;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    vector<int> nums;
    int target = 1;

    // nums = {-1, 2, 1, -4}
    nums.push_back(-1);
    nums.push_back(2);
    nums.push_back(1);
    nums.push_back(-4);

    Solution mySolution;
    int result = mySolution.threeSumClosest(nums, target);

    return 0;
}

Add Solution for Problem 016


// Copyright 2016 Mitchell Kember. Subject to the MIT License.
// Project Euler: Problem 26
// Reciprocal cycles

#include <vector>

namespace problem_26 {

long recurring_cycle_len(const long n) {
	long dividend = 10;
	std::vector<long> remainders;
	while (dividend > 0) {
		// Check if the next remainder has ocurred before.
		const long rem = dividend % n;
		const auto end = remainders.end();
		const auto it = std::find(remainders.begin(), end, rem);
		if (it != end) {
			return std::distance(it, end);
		}

		remainders.push_back(rem);
		dividend = rem * 10;
	}
	return 0;
}

long solve() {
	long result = 1;
	long max_len = 0;
	for (long i = 1; i < 1000; ++i) {
		const long len = recurring_cycle_len(i);
		if (len > max_len) {
			result = i;
			max_len = len;
		}
	}
	return result;
}

} // namespace problem_26

Solve problem 26 in C++


/*
 * bacteria-core, core for cellular automaton
 * Copyright (C) 2016 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#include <boost/test/unit_test.hpp>

#include "CoreConstants.hpp"
#include "CoreGlobals.hpp"
#include "Creator.hpp"

BOOST_AUTO_TEST_CASE (create_model_test) {
    ModelPtr model = Creator::createModel(
        MIN_WIDTH,
        MIN_HEIGHT,
        1,
        1
    );
    BOOST_REQUIRE(model->getWidth() == MIN_WIDTH);
    BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT);
    BOOST_REQUIRE(model->getBacteriaNumber(0) == 1);
}

Add Creator's first unit test: create_model_test


#include "abstractfieldwidgetfactory.h"

using namespace KPeople;

AbstractFieldWidgetFactory::AbstractFieldWidgetFactory(QObject *parent):
    QObject(parent)
{
}

AbstractFieldWidgetFactory::~AbstractFieldWidgetFactory()
{

}

Add missing file from last commit


//   Copyright 2016 otris software AG
//
//   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 <ews/ews.hpp>
#include <ews/ews_test_support.hpp>

#include <cstdlib>
#include <exception>
#include <iostream>
#include <ostream>
#include <string>

int main()
{
    int res = EXIT_SUCCESS;
    ews::set_up();

    try
    {
        const auto env = ews::test::environment();
        auto service = ews::service(env.server_uri, env.domain, env.username,
                                    env.password);

        // First create some draft message
        ews::distinguished_folder_id drafts = ews::standard_folder::drafts;
        for (int i = 0; i < 20; i++)
        {
            auto message = ews::message();
            message.set_subject("This is an e-mail message for our paging view");
            std::vector<ews::mailbox> recipients;
            recipients.push_back(ews::mailbox("donald.duck@duckburg.com"));
            message.set_to_recipients(recipients);
            auto item_id =
                service.create_item(message, ews::message_disposition::save_only);
        }

        // Now iterate over all items in the folder
        // Starting at the end with an offset of 10
        // Returning a number of 5 items per iteration
        // Until no more items are returned
        ews::paging_view view(5, 10, ews::paging_base_point::end);
        while (true)
        {
            auto item_ids = service.find_item(drafts, view);
            if (item_ids.empty())
            {
                std::cout << "No more messages found!\n";
                break;
            }

            for (const auto& id : item_ids)
            {
                auto msg = service.get_message(id);
                std::cout << msg.get_subject() << std::endl;
            }

            view.advance();
        }
    }
    catch (std::exception& exc)
    {
        std::cout << exc.what() << std::endl;
        res = EXIT_FAILURE;
    }

    ews::tear_down();
    return res;
}

// vim:et ts=4 sw=4

Add example for paging view


#include <stdio.h>

static unsigned NumAs = 0;

struct A {
  unsigned ANum;
  A() : ANum(NumAs++) { printf("Created A #%d\n", ANum); }
  A(const A &a) : ANum(NumAs++) { printf("Copy Created A #%d\n", ANum); }
  ~A() { printf("Destroyed A #%d\n", ANum); }
};

static bool ShouldThrow = false;

int throws()
  try
{
  if (ShouldThrow) throw 7; return 123;
} catch (...) {
  printf("'throws' threw an exception: rethrowing!\n");
  throw;
}

struct B {
  A a0, a1, a2;
  int i;
  A a3, a4;

  B();
  ~B() { printf("B destructor!\n"); }
};

B::B()
try
: i(throws())
{
  printf("In B constructor!\n");
}
catch (int i) {
  printf("In B catch block with int %d: auto rethrowing\n", i);
}

int main() {
  {
    B b;   // Shouldn't throw.
  }

  try {
    ShouldThrow = true;
    B b;
  } catch (...) {
    printf("Caught exception!\n");
  }
}

Add test for the last chapter of our C++ exception handling odyssey. llvmg++ now fully supports all C++ exception handling functionality.


#include <agency/execution_policy.hpp>
#include <iostream>

void hello(agency::sequential_agent& self)
{
  std::cout << "Hello, world from agent " << self.index() << std::endl;
}

int main()
{
  // create 10 sequential_agents to execute the hello() task in bulk
  agency::bulk_invoke(agency::seq(10), hello);

  return 0;
}

Add hello world example program


// RUN: %clangxx_asan -O0 %s -o %t && not %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK
// RUN: %clangxx_asan -O1 %s -o %t && not %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK
// RUN: %clangxx_asan -O2 %s -o %t && not %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK
// RUN: %clangxx_asan -O3 %s -o %t && not %t 2>&1 | FileCheck %s --check-prefix=CHECK-%os --check-prefix=CHECK

#include <stdlib.h>
int main() {
  char * volatile x = new char[10];
  delete[] x;
  return x[5];
  // CHECK: {{.*ERROR: AddressSanitizer: heap-use-after-free on address}}
  // CHECK:   {{0x.* at pc 0x.* bp 0x.* sp 0x.*}}
  // CHECK: {{READ of size 1 at 0x.* thread T0}}
  // CHECK: {{    #0 0x.* in main .*use-after-delete.cc:10}}
  // CHECK: {{0x.* is located 5 bytes inside of 10-byte region .0x.*,0x.*}}
  // CHECK: {{freed by thread T0 here:}}

  // CHECK-Linux: {{    #0 0x.* in operator delete\[\]}}
  // CHECK-Linux: {{    #1 0x.* in main .*use-after-delete.cc:9}}

  // CHECK: {{previously allocated by thread T0 here:}}

  // CHECK-Linux: {{    #0 0x.* in operator new\[\]}}
  // CHECK-Linux: {{    #1 0x.* in main .*use-after-delete.cc:8}}

  // CHECK: Shadow byte legend (one shadow byte represents 8 application bytes):
  // CHECK: Global redzone:
  // CHECK: ASan internal:
}

Add a test for stack unwinding in new and delete.


#include <iostream>
#include <fstream>

using namespace std;

struct CarInfo {
    const char * name;
    int hp;
};

const CarInfo CARS[] = {
    { "Lambordgini Murcielago", 670 },
    { "Mercedes - AMG", 503 },
    { "Pagani Zonda R", 740},
    { "Bugatti Veyron", 1020}
};

struct CarRecord {
    char name[24];
    int carId;
    unsigned regId;
};

const int MAX_RECORDS = 1000;
CarRecord database[MAX_RECORDS];
int dbSize = 0;

void load();
void save();
void report();
void addRecord();
void menu();

int main() {
    load();
    return 0;
}

void load() {
    ifstream dbFile("db-save.dat", ios::in | ios::binary);
    if (!dbFile) {
        return;
    }

    int saveSize = 0;
    if (!dbFile.read((char*)&saveSize, sizeof(saveSize))) {
        cerr << "Failed to read save file";
        exit(1);
    }

    if (!dbFile.read((char*)database, saveSize * sizeof(CarRecord))) {
        cerr << "Failed to load records - failed to read";
        exit(1);
    }
    dbSize = saveSize;
}

void save() {
    ofstream dbFile("db-save.dat", ios::trunc | ios::binary);
    if (!dbFile) {
        cerr << "Failed to create save file";
        exit(1);
    }

    if (!dbFile.write((const char *)&dbSize, sizeof(dbSize))) {
        cerr << "Failed to write to save file";
        exit(1);
    }

    if (!dbFile.write((const char*)database, dbSize * sizeof(CarRecord))) {
        cerr << "Failed to write to save file";
        exit(1);
    }

    dbFile.close();
}

Add partial sollution to hw1 oop-inf-2015


// RUN: %clangxx_msan -m64 -O0 %s -o %t && %t

int main(void) {
  int i;
  __sync_lock_test_and_set(&i, 0);
  return i;
}

Test for atomic handling in MSan.


#include <iostream>
#include <thread>

#include <glog/logging.h>

#include "base/concurrent/wait_group.h"
#include "base/strings/string_piece.h"
#include "net/socket/socket_factory.h"
#include "net/socket/unix_domain_client_socket.h"
#include "net/socket/unix_domain_server_socket.h"

using namespace std;

const char* const UNIX_DOMAIN_SOCKET_PATH = "/tmp/uds-test.sock";

void run_server(concurrent::WaitGroup* wg)
{
    net::UnixDomainServerSocket sock = net::SocketFactory::instance()->make_unix_domain_server_socket();
    CHECK(sock.valid());

    (void)unlink(UNIX_DOMAIN_SOCKET_PATH);
    CHECK(sock.bind(UNIX_DOMAIN_SOCKET_PATH));
    CHECK(sock.listen(5));

    wg->done();

    net::UnixDomainSocket accepted = sock.accept();
    CHECK(accepted.valid());

    CHECK(sock.close());

    char buf[7];
    CHECK(accepted.read_exactly(buf, 7));

    cout << "server: " << strings::StringPiece(buf, 7) << endl;
}

void run_client()
{
    net::UnixDomainClientSocket sock = net::SocketFactory::instance()->make_unix_domain_client_socket();
    CHECK(sock.valid());

    CHECK(sock.connect(UNIX_DOMAIN_SOCKET_PATH));

    cout << "client: foobar" << endl;
    sock.write("foobar", 7);
}

int main()
{
    concurrent::WaitGroup wg;
    wg.add(1);

    thread server_thread(run_server, &wg);
    wg.wait_until_done();

    thread client_thread(run_client);

    client_thread.join();
    server_thread.join();
}

Add more unix domain socket experimental program.


#include "mbed.h"

Ticker ticker;
DigitalOut led1(LED1);
DigitalOut led2(LED2);
CAN can1(p9, p10);
CAN can2(p30, p29);
char counter = 0;

void printmsg(char *title, CANMessage *msg) {
    printf("%s [%03X]", title, msg->id);
    for(char i = 0; i < msg->len; i++) {
        printf(" %02X", msg->data[i]);
    }
    printf("\n");
}

void send() {
    printf("send()\n");
    CANMessage msg = CANMessage(1337, &counter, 1);
    if(can1.write(msg)) {
        printmsg("Tx message:", &msg);
        counter++;
    }
    led1 = !led1;
}

void read() {
    CANMessage msg;
    printf("rx()\n");
    if(can1.read(msg)) {
        printmsg("Rx message:", &msg);
        led2 = !led2;
    }
}

int main() {
    printf("main()\n");
    ticker.attach(&send, 1);
    can1.attach(&read);
    while(1) {
        printf("loop()\n");
        wait(1);
    }
}

#include "mbed.h"

Ticker ticker;
DigitalOut led1(LED1);
DigitalOut led2(LED2);
CAN can1(p9, p10);
CAN can2(p30, p29);
char counter = 0;

void printmsg(char *title, CANMessage *msg) {
    printf("%s [%03X]", title, msg->id);
    for(char i = 0; i < msg->len; i++) {
        printf(" %02X", msg->data[i]);
    }
    printf("\n");
}

void send() {
    printf("send()\n");
    CANMessage msg = CANMessage(1337, &counter, 1);
    if(can1.write(msg)) {
        printmsg("Tx message:", &msg);
        counter++;
    }
    led1 = !led1;
}

void read() {
    CANMessage msg;
    printf("rx()\n");
    if(can2.read(msg)) {
        printmsg("Rx message:", &msg);
        led2 = !led2;
    }
}

int main() {
    printf("main()\n");
    ticker.attach(&send, 1);
    can2.attach(&read);
    while(1) {
        printf("loop()\n");
        wait(1);
    }
}

Fix CAN Interrupt Test (MBED_31)


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

using namespace Halide;

int main(int argc, char **argv) {
    Var x, y;
    Image<int> full = lambda(x, y, x * y).realize(800, 600);

    buffer_t cropped = {0};
    cropped.host = (uint8_t *)(&full(40, 80));
    cropped.host_dirty = true;
    cropped.elem_size = 4;
    cropped.min[0] = 40;
    cropped.min[1] = 80;
    cropped.extent[0] = 128;
    cropped.extent[1] = 96;
    cropped.stride[0] = full.stride(0);
    cropped.stride[1] = full.stride(1);
    Buffer out(Int(32), &cropped);

    Func f;

    f(x, y) = x*y + 1;
    f.gpu_tile(x, y, 16, 16);
    f.realize(out);

    // Put something secret outside of the region that the func is
    // supposed to write to.
    full(500, 80) = 1234567;

    // Copy back the output.
    out.copy_to_host();

    if (full(500, 80) != 1234567) {
        printf("Output value outside of the range evaluated was clobbered by copy-back from gpu!\n");
        return -1;
    }

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

Add test for non-contiguous gpu copy


// 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 "base/message_loop/message_loop.h"
#include "chrome/browser/extensions/api/feedback_private/feedback_private_api.h"
#include "chrome/browser/extensions/extension_apitest.h"

namespace extensions {

class FeedbackApiTest: public ExtensionApiTest {
 public:
  FeedbackApiTest() {}
  virtual ~FeedbackApiTest() {}
};

IN_PROC_BROWSER_TEST_F(FeedbackApiTest, Basic) {
  EXPECT_TRUE(RunExtensionTest("feedback_private/basic")) << message_;
}

} // namespace extensions

// 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 "base/message_loop/message_loop.h"
#include "chrome/browser/extensions/api/feedback_private/feedback_private_api.h"
#include "chrome/browser/extensions/extension_apitest.h"

namespace extensions {

class FeedbackApiTest: public ExtensionApiTest {
 public:
  FeedbackApiTest() {}
  virtual ~FeedbackApiTest() {}
};

// Fails on Linux/Win.  http://crbug.com/408917
#if defined(OS_WIN) || defined(OS_LINUX)
#define MAYBE_Basic DISABLED_Basic
#else
#define MAYBE_Basic Basic
#endif

IN_PROC_BROWSER_TEST_F(FeedbackApiTest, MAYBE_Basic) {
  EXPECT_TRUE(RunExtensionTest("feedback_private/basic")) << message_;
}

} // namespace extensions

Disable FeedbackApiTest.Basic on Win & Linux


#include <bits/stdc++.h>

using namespace std;

void toBin(int x){
  for (int i =31; i>=0; --i){
      cout << ((x&(1LL<<i))!=0);
  }
}

int main (){
  toBin(10);
  return 0;
}

Add useful algorithm to bin in c++.


#include hand_XXX_driver.h

// No memory allocation outside init

main{
    /// This function will do all the necessary work to set up the hand:
    /// - Scan bus for slaves
    /// - If there's a hand of type XXX then

    /// - initialize hand [p0-m1]

    /// - configure hand
    /// Configurations for the hand will be read from a file, these will include:
    /// - Ethernet port to use
    /// - internal tuning and over-tension potection parameters
    /// - desired operation mode (PWM or tendon tension)
    int success = initialize_hand_XXX();

    /// buffer where the commands (PWM or torque) to the robot motors will be written
    unsigned char *command_buffer;

    /// buffer where the status (sensor data) from the robot can be read from
    unsigned char *status_buffer;

    /// From here
    while(true)
    {
        /// This will use the command_buffer data to build an etherCAT frame and send it to the hand
        /// The etherCAT frame comes back with sensor data from the hand that can be read from the status_buffer
        send_and_receive_from_hand_XXX(command_buffer, status_buffer);

        /// Do stuff with the status data (compute next commands)

        /// Wait until time for next frame

        send_and_receive_from_hand_XXX(command_buffer, status_buffer);
        /// Waiting until next iteration

    }
}

Add pseudocode for top level file


// 3.2 - design a stack with push, pop, peek and min, all in O(1)

// improvement: only push to aux stack if new value is <= current minimum; only
// pop from aux stack if value being popped is == current minimum - saves space
// if many values are not the minimum.

// alternative: define data structure to hold int plus the current minimum,
// make stack of this data structure and just return the current minimum stored
// in the top element if asked

#include<stdexcept>
#include<iostream>

using namespace std;

struct Node {
    Node* next;
    int val;
    Node(int v) :next(0), val(v) { }
};

struct Stack {
    Node* top;

    void push(int v)
    {
        Node* n = new Node(v);
        n->next = top;
        top = n;
    }

    int pop()
    {
        if (top==0)
            throw exception("can't pop empty stack");
        int v = top->val;
        Node* n = top->next;
        delete(top);
        top = n;
        return v;
    }

    int peek()
    {
        if (!top)
            throw exception("can't peek on empty stack");
        return top->val;
    }

    Stack() :top(0) { }
};

class Min_stack : public Stack {
    Stack min_stack;
public:
    Min_stack() :Stack(), min_stack() { }

    void push(int v)
    {
        if (top==0 || v < min_stack.peek())
            min_stack.push(v);
        else
            min_stack.push(min_stack.peek());
        Stack::push(v); // must be last, otherwise top!=0
    }

    int pop()
    {
        min_stack.pop();
        return Stack::pop();
    }

    int min()
    {
        return min_stack.peek();
    }
};

int main()
try
{
    Min_stack ms;
    //ms.peek();  // throws
    //ms.pop();   // throws
    ms.push(1);
    ms.push(2);
    cout << "Minimum in {1,2}: " << ms.min() << '\n';
    ms.push(3);
    ms.push(-1);
    ms.push(4);
    ms.push(5);
    cout << "Minimum in {1,2,3,-1,4,5}: " << ms.min() << '\n';
    cout << "\nPopping all:\n";
    while (ms.top)
        cout << ms.pop() << '\n';
    ms.pop();   // throws
}
catch (exception& e) {
    cerr << "Exception: " << e.what() << '\n';
}
catch (...) {
    cerr << "Exception\n";
}

Add Chapter 3, exercise 2 (using stack in stack approach)


// RUN: %clang_cc1 -std=c++11 -fsyntax-only %s
// RUN: %clang_cc1 -std=c++98 -fsyntax-only -verify %s

// expected-error@8 {{in c++98 only}}
#if 0
R"(
#else
#error in c++98 only)"
#endif

Add raw string literal versus C preprocessor test, suggested by James Dennett.


#include <stdio.h>
using namespace std;

// converts the time in millis to
// human readable format in hh:mm:ss
// I/P: 901000
// O/P: 00:15:01
void convertTime(int timeInMillis) {
    // convert millisecs into secs
    int secs = timeInMillis/1000;
    // convert secs into minutes and round off if it reaches 60
    int mins = secs/60 % 60;
    // convert secs into hrs and round off if it reaches 24
    int hrs = (secs/(60*60)) % 24;
    // print the time in the format hh:mm:ss
    printf("%02d:%02d:%02d\n", hrs, mins, secs%60);
}

int main() {
    convertTime(901000);
    convertTime(3601000);

    return 0;
}

Convert time in millisecs to hh:mm:ss


// 143. Reorder List
/**
 * Given a singly linked list L: L0->L1->...->Ln-1->Ln,
 * reorder it to: L0->Ln->L1->Ln-1->L2->Ln-2->...
 *
 * You must do this in-place without altering the nodes' values.
 *
 * For example,
 * Given {1,2,3,4}, reorder it to {1,4,2,3}.
 *
 * Tags: Linked List
 *
 * Author: Kuang Qin
 */

#include <iostream>

using namespace std;

/**
 * Definition for singly-linked list.
 */
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
    ListNode(int x, ListNode *p) : val(x), next(p) {}
};

class Solution {
public:
    void reorderList(ListNode* head) {
        if (head == NULL || head->next == NULL) {
            return;
        }

        // divide the list into two parts
        ListNode *slow = head, *fast = head->next;
        while (fast != NULL && fast->next != NULL) {
            slow = slow->next;
            fast = fast->next->next;
        }

        // reverse the second part of the list from slow->next
        ListNode *curr = slow->next, *prev = NULL;
        while (curr != NULL) {
            ListNode *next = curr->next;
            curr->next = prev;
            prev = curr;
            curr = next;
        }

        // connect two lists
        slow->next = NULL;
        while (head != NULL && prev != NULL) {
            ListNode *next = prev->next;
            prev->next = head->next;
            head->next = prev;
            head = prev->next;
            prev = next;
        }

        return;
    }
};

int main() {
    ListNode node5(5), node4(4, &node5), node3(3, &node4), node2(2, &node3), node1(1, &node2);
    Solution sol;
    ListNode *head = &node1;
    sol.reorderList(head);
    for (ListNode *p = head; p != NULL; p = p->next) {
        cout << p->val << " ";
    }
    cout << endl;
    cin.get();

    return 0;
}

Add Solution for 143 Reorder List


/* GNE - Game Networking Engine, a portable multithreaded networking library.
 * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu)
 * Project website: http://www.rit.edu/~jpw9607/
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

//this CPP file only for precompiled header
#include "../include/gnelib/gneintern.h"

Set up PCH for MSVC.NET


/*
 * Copyright (c) 2016 Kartik Kumar, Dinamica Srl (me@kartikkumar.com)
 * Distributed under the MIT License.
 * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
 */

#include <map>
#include <typeinfo>
#include <vector>

#include <catch.hpp>

#include "rvdsim/typedefs.hpp"

namespace rvdsim
{
namespace tests
{

TEST_CASE( "Test typedefs", "[typedef]" )
{
    REQUIRE( typeid( Real )             == typeid( double ) );
    REQUIRE( typeid( Vector3 )          == typeid( std::vector< Real > ) );
    REQUIRE( typeid( Vector6 )          == typeid( std::vector< Real > ) );
    REQUIRE( typeid( StateHistory )     == typeid( std::map< Real, Vector6 > ) );
    REQUIRE( typeid( ThrustHistory )    == typeid( std::map< Real, Vector3 > ) );
}

} // namespace tests
} // namespace rvdsim

Add unit tests for typedefs.


// Allow having both the no-arg and arg1 logging implementation live together,
// and be called in the correct cases.
//
// RUN: rm arg0-arg1-logging-* || true
// RUN: %clangxx_xray -std=c++11 %s -o %t
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=1 xray_logfile_base=arg0-arg1-logging-" %run %t
//
// TODO: Support these in ARM and PPC
// XFAIL: arm || aarch64 || mips
// UNSUPPORTED: powerpc64le

#include "xray/xray_interface.h"
#include <cassert>
#include <cstdio>

using namespace std;

bool arg0loggercalled = false;
void arg0logger(int32_t, XRayEntryType) { arg0loggercalled = true; }

[[clang::xray_always_instrument]] void arg0fn() { printf("hello, arg0!\n"); }

bool arg1loggercalled = false;
void arg1logger(int32_t, XRayEntryType, uint64_t) { arg1loggercalled = true; }

[[ clang::xray_always_instrument, clang::xray_log_args(1) ]] void
arg1fn(uint64_t arg1) {
  printf("hello, arg1!\n");
}

int main(int argc, char *argv[]) {
  __xray_set_handler(arg0logger);
  __xray_set_handler_arg1(arg1logger);
  arg0fn();
  arg1fn(0xcafef00d);
  __xray_remove_handler_arg1();
  __xray_remove_handler();
  assert(arg0loggercalled && arg1loggercalled);
}

Add a test for both arg1 and arg0 handling in the same binary


#include <boost/test/unit_test.hpp>
#include <ygo/deck/Format.h>
#include <ygo/deck/DB.h>

struct Format_Fixture
{
    Format_Fixture()
    {
        ygo::deck::DB::get().path("test/card.db");
    }
};

BOOST_FIXTURE_TEST_SUITE(Format, Format_Fixture)

BOOST_AUTO_TEST_CASE(Create)
{
    auto formatDates = ygo::deck::Format::formatDates();
    for (auto&& f : formatDates) {
        ygo::deck::Format formatA(ygo::data::Format::ADVANCED, f);
        BOOST_CHECK_EQUAL(formatA.formatDate(), f);
        BOOST_CHECK(formatA.format() == ygo::data::Format::ADVANCED);

        ygo::deck::Format formatT(ygo::data::Format::TRADITIONAL, f);
        BOOST_CHECK_EQUAL(formatT.formatDate(), f);
        BOOST_CHECK(formatT.format() == ygo::data::Format::TRADITIONAL);
    }
}

BOOST_AUTO_TEST_CASE(Invalid)
{
    try {
        ygo::deck::Format f(ygo::data::Format::ADVANCED, "InvalidFormat");
        BOOST_CHECK_EQUAL(0, 1);
    } catch (std::runtime_error& e) {
        BOOST_CHECK_EQUAL(1, 1);
    }
}

BOOST_AUTO_TEST_CASE(Limits)
{
    ygo::deck::Format formatA(ygo::data::Format::ADVANCED, "April 2004");
    ygo::deck::Format formatT(ygo::data::Format::TRADITIONAL, "April 2004");

    BOOST_CHECK_EQUAL(0, formatA.cardCount("Change of Heart"));
    BOOST_CHECK_EQUAL(1, formatT.cardCount("Change of Heart"));

    BOOST_CHECK_EQUAL(1, formatA.cardCount("Mage Power"));
    BOOST_CHECK_EQUAL(1, formatT.cardCount("Mage Power"));

    BOOST_CHECK_EQUAL(2, formatA.cardCount("Creature Swap"));
    BOOST_CHECK_EQUAL(2, formatT.cardCount("Creature Swap"));

    BOOST_CHECK_EQUAL(3, formatA.cardCount("Kuriboh"));
    BOOST_CHECK_EQUAL(3, formatT.cardCount("Kuriboh"));

}

BOOST_AUTO_TEST_SUITE_END()

Add unit tests for ygo::deck::Format


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

template<typename T>
struct X0 {
  void f();

  template<typename U>
  void g(U);

  struct Nested {
  };

  static T member;
};

int &use_X0_int(X0<int> x0i,  // expected-note{{implicit instantiation first required here}}
                int i) {
  x0i.f(); // expected-note{{implicit instantiation first required here}}
  x0i.g(i); // expected-note{{implicit instantiation first required here}}
  X0<int>::Nested nested; // expected-note{{implicit instantiation first required here}}
  return X0<int>::member; // expected-note{{implicit instantiation first required here}}
}

template<>
void X0<int>::f() { // expected-error{{after instantiation}}
}

template<> template<>
void X0<int>::g(int) { // expected-error{{after instantiation}}
}

template<>
struct X0<int>::Nested { }; // expected-error{{after instantiation}}

template<>
int X0<int>::member = 17; // expected-error{{after instantiation}}

template<>
struct X0<int> { }; // expected-error{{after instantiation}}

// Example from the standard
template<class T> class Array { /* ... */ };

template<class T> void sort(Array<T>& v) { /* ... */ }

struct String {};

void f(Array<String>& v) {

  sort(v); // expected-note{{required}}
           // use primary template
           // sort(Array<T>&), T is String
}

template<> void sort<String>(Array<String>& v); // // expected-error{{after instantiation}}
template<> void sort<>(Array<char*>& v);	// OK: sort<char*> not yet used

Add test for last commit


// RUN: %clang_cl_asan -O0 %s -Fe%t
// RUN: env ASAN_OPTIONS=handle_segv=0 %run %t 2>&1 | FileCheck %s --check-prefix=USER
// RUN: env ASAN_OPTIONS=handle_segv=1 not %run %t 2>&1 | FileCheck %s --check-prefix=ASAN
// Test the default.
// RUN: not %run %t 2>&1 | FileCheck %s --check-prefix=ASAN

// This test exits zero when its unhandled exception filter is set. ASan should
// not disturb it when handle_segv=0.

// USER: in main
// USER: in SEHHandler

// ASAN: in main
// ASAN: ERROR: AddressSanitizer: access-violation

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

static long WINAPI SEHHandler(EXCEPTION_POINTERS *info) {
  DWORD exception_code = info->ExceptionRecord->ExceptionCode;
  if (exception_code == EXCEPTION_ACCESS_VIOLATION) {
    fprintf(stderr, "in SEHHandler\n");
    fflush(stdout);
    TerminateProcess(GetCurrentProcess(), 0);
  }
  return EXCEPTION_CONTINUE_SEARCH;
}

int main() {
  SetUnhandledExceptionFilter(SEHHandler);
  fprintf(stderr, "in main\n");

  volatile int *p = nullptr;
  *p = 42;
}

Add Windows test for handle_segv and SetUnhandledExceptionFilter


class Solution {
public:
    bool isPossible(vector<int>& nums) {
        int st=0;
        for(int i=1; i<nums.size(); i++){
            if(nums[i]-nums[i-1]>1){
                if(!work(nums,st,i-1)) return false;
                st = i;
            }
        }
        return work(nums,st,nums.size()-1);
    }

    bool work(vector<int>& nums, int f, int r){
        vector<int> count(nums[r]-nums[f]+1,0);
        for(int i=f;i<=r;i++){
            count[nums[i]-nums[f]]++;
        }
        vector<int> one(nums[r]-nums[f]+2,0), two(nums[r]-nums[f]+2,0), tot(nums[r]-nums[f]+2,0);
        for(int i=0;i<nums[r]-nums[f]+1;i++){
            if(count[i]<one[i]+two[i]) return false;
            two[i+1]=one[i];
            one[i+1]=max(0,count[i]-tot[i]);
            tot[i+1]=count[i];
        }
        if(one[nums[r]-nums[f]+1]==0 & two[nums[r]-nums[f]+1]==0) return true;
        return false;
    }
};

Split Array into Consecutive Subsequences


const ll is_query = -(1LL<<62);
struct Line {
    ll m, b;
    mutable function<const Line*()> succ;
    bool operator<(const Line& rhs) const {
        if (rhs.b != is_query) return m < rhs.m;
        const Line* s = succ();
        if (!s) return 0;
        ll x = rhs.m;
        return b - s->b < (s->m - m) * x;
    }
};
struct HullDynamic : public multiset<Line> { // will maintain upper hull for maximum
    bool bad(iterator y) {
        auto z = next(y);
        if (y == begin()) {
            if (z == end()) return 0;
            return y->m == z->m && y->b <= z->b;
        }
        auto x = prev(y);
        if (z == end()) return y->m == x->m && y->b <= x->b;
        return (x->b - y->b)*(z->m - y->m) >= (y->b - z->b)*(y->m - x->m);
    }
    void insert_line(ll m, ll b) {
        auto y = insert({ m, b });
        y->succ = [=] { return next(y) == end() ? 0 : &*next(y); };
        if (bad(y)) { erase(y); return; }
        while (next(y) != end() && bad(next(y))) erase(next(y));
        while (y != begin() && bad(prev(y))) erase(prev(y));
    }
    ll eval(ll x) {
        auto l = *lower_bound((Line) { x, is_query });
        return l.m * x + l.b;
    }
};

Add dynamic convex hull trick, stolen from niklasb


#include "sockets.h"

class StandardInputOutput : public Socket {
	public:
		StandardInputOutput();
		unsigned int apiVersion() { return 3000; }
		std::string receive();
		void sendData(const std::string& data);
};

StandardInputOutput::StandardInputOutput() : connected(true) {}

std::string StandardInputOutput::receive() {
	std::string recvLine;
	std::getline(std::cin, recvLine);
	return recvLine;
}

void StandardInputOutput::sendData(const std::string& data) {
	std::cout << data << std::endl;
}

Make a standard input/output socket module mostly for testing purposes.


#include <shogun/classifier/svm/SVMOcas.h>
#include <shogun/features/DataGenerator.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/evaluation/ROCEvaluation.h>
#include <gtest/gtest.h>

#include <iostream>

using namespace shogun;

TEST(SVMOcasTest,train)
{
	index_t num_samples = 100, dim = 10;
	float64_t mean_shift = 1.0;
	CMath::init_random(5);
	SGMatrix<float64_t> data =
		CDataGenerator::generate_mean_data(num_samples, dim, mean_shift);
	CDenseFeatures<float64_t> features(data);

	SGVector<index_t> train_idx(100), test_idx(100);
	SGVector<float64_t> labels(100);
	for (index_t i = 0, j = 0; i < data.num_cols; ++i)
	{
		if (i % 2 == 0)
			train_idx[j] = i;
		else
			test_idx[j++] = i;

		labels[i/2] = (i < 100) ? 1.0 : -1.0;
	}

	CDenseFeatures<float64_t>* train_feats = (CDenseFeatures<float64_t>*)features.copy_subset(train_idx);
	CDenseFeatures<float64_t>* test_feats =  (CDenseFeatures<float64_t>*)features.copy_subset(test_idx);

	CBinaryLabels* ground_truth = new CBinaryLabels(labels);

	CSVMOcas* ocas = new CSVMOcas(1.0, train_feats, ground_truth);
	ocas->train();

	CLabels* pred = ocas->apply(test_feats);
	CROCEvaluation roc;
	float64_t err = CMath::abs(roc.evaluate(pred, ground_truth)-0.7684);
	EXPECT_TRUE(err < 10E-12);

	SG_UNREF(ocas);
	SG_UNREF(train_feats);
	SG_UNREF(test_feats);
}

Add unit test for SVMOcas


#include "skiplist.hh"
#include <vector>
#include <thread>
#include <iostream>

static unsigned int seed;

void insert(Skiplist *s, int n) {
    for (int x=0; x < n; x++) {
        unsigned r = rand_r(&seed);
        int *v = (int *) skiplist_malloc(sizeof(int));
        *v = r;
        Item *itm = newItem(v, sizeof(int));
        Skiplist_Insert(s, itm);
    }
}

int main() {

    srand(time(NULL));
    int i = 100;
    Skiplist *s = newSkiplist();
    std::vector<std::thread> threads;

    for (int x=0; x < 8; x++) {
        threads.push_back(std::thread(&insert,s, 1000000));
    }

    for (auto& th : threads) th.join();

    exit(0);
    int count = 0;
    Node *p = s->head;
    while (p) {
        if (p->itm->l == 4) {
            count++;
//            std::cout<<"itm "<<count<<" - "<<*((int *)(p->itm->data))<<std::endl;
        }

        NodeRef r = Node_getNext(p, 0);
        p = r.ptr;
    }

    std::cout<<count<<std::endl;
}

Add simple c++ insert test


/*
 Given a number, return the number of set bits of the number if binary representation
of the number is a palindrome, else return 1.
Condition : You can’t use array or any other data structure.
Eg . Input
  37
        Output   1

        Input
 165
        Output    4
*/

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int count_bits1(int a)
{
    int ans = 0;
    for (int i = 0; i < 32; i++)
    {
        if (((a >> i) & 1) == 1)
            ans++;
    }
    return ans;
}

int length(int a)
{
    int pos = 0;
    for (int i = 0; i < 32; i++)
    {
        if (((a >> i) & 1) == 1)
            pos = i;
    }
    return pos;
}

int main()
{
int input = 165;
int no1 = count_bits1(input);
int len = length(input);
for (int i = 0; i <= len/2; i++)
{
    //cout << "for i equal to  " << i << " the bits are " << ((input >> i) & 1) << "  " << ((input >> (len - i)) & 1) << endl;
    if (((input >> i) & 1) == ((input >> (len - i)) & 1))
        ;
    else
        return -1;
}
return no1;
}

Return number of set bits if int is palindrome. Question commented inside.


// RUN: %clangxx -fsanitize=integer -fsanitize-recover=integer %s -o %t
// RUN: not %t 2>&1 | FileCheck %s

// __ubsan_default_options() doesn't work on Darwin.
// XFAIL: darwin

#include <stdint.h>

extern "C" const char *__ubsan_default_options() {
  return "halt_on_error=1";
}

int main() {
  (void)(uint64_t(10000000000000000000ull) + uint64_t(9000000000000000000ull));
  // CHECK: ubsan_options.cc:[[@LINE-1]]:44: runtime error: unsigned integer overflow
  return 0;
}

Add a testcase for __ubsan_default_options() function.


/**
 * Remove Duplicates from Sorted Array II
 *
 * cpselvis(cpselvis@gmail.com)
 * September 21th, 2016
 */
#include<iostream>
#include<vector>
#include<unordered_map>

using namespace std;

class Solution {
public:
  int removeDuplicates(vector<int>& nums) {
    unordered_map<int, int> umap;

    int ret = nums.size();
    for (int i = 0; i < nums.size(); )
    {
      if (umap[nums[i]] < 2)
      {
        umap[nums[i]] ++;
	i ++;
      }
      else
      {
	nums.erase(nums.begin() + i);
	ret --;
      }
    }
    return ret;
  }
};

int main(int argc, char **argv)
{
  Solution s;
  int nums[6] = {1, 1, 1, 2, 2, 3};

  vector<int> vec(nums + 0, nums + 6);
  cout << s.removeDuplicates(vec) << endl;
}

Remove Duplicates from Sorted Array II.


// RUN: %clang_cc1 -fsyntax-only -verify %s
struct A {
  template <class T> operator T*();
};

template <class T> A::operator T*() { return 0; }
template <> A::operator char*(){ return 0; } // specialization
template A::operator void*(); // explicit instantiation

int main() {
  A a;
  int *ip;
  ip = a.operator int*();
}

// PR5742
namespace PR5742 {
  template <class T> struct A { };
  template <class T> struct B { };

  struct S {
    template <class T> operator T();
  } s;

  void f() {
    s.operator A<A<int> >();
    s.operator A<B<int> >();
    s.operator A<B<A<int> > >();
  }
}

// PR5762
class Foo {
 public:
  template <typename T> operator T();

  template <typename T>
  T As() {
    return this->operator T();
  }

  template <typename T>
  T As2() {
    return operator T();
  }

  int AsInt() {
    return this->operator int();
  }
};

template float Foo::As();
template double Foo::As2();

// Partial ordering with conversion function templates.
struct X0 {
  template<typename T> operator T*() {
    T x;
    x = 17; // expected-error{{read-only variable is not assignable}}
  }

  template<typename T> operator T*() const; // expected-note{{explicit instantiation refers here}}

  template<typename T> operator const T*() const {
    T x = T();
    return x; // expected-error{{cannot initialize return object of type 'char const *' with an lvalue of type 'char'}}
  }
};

template X0::operator const char*() const; // expected-note{{'X0::operator char const *<char>' requested here}}
template X0::operator const int*(); // expected-note{{'X0::operator int const *<int const>' requested here}}
template X0::operator float*() const; // expected-error{{explicit instantiation of undefined function template}}

void test_X0(X0 x0, const X0 &x0c) {
  x0.operator const int*();
  x0.operator float *();
  x0c.operator const char*();
}

Test case for naming of conversion function template specializations


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

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

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

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

#include "tensorflow/lite/micro/debug_log.h"

#include <stm32f4xx_hal.h>
#include <stm32f4xx_hal_uart.h>

#include <cstdio>

#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */

extern UART_HandleTypeDef DEBUG_UART_HANDLE;

PUTCHAR_PROTOTYPE {
  HAL_UART_Transmit(&DEBUG_UART_HANDLE, (uint8_t *)&ch, 1, HAL_MAX_DELAY);

  return ch;
}

extern "C" void DebugLog(const char *s) { fprintf(stderr, "%s", s); }

Debug log implementation to use the STM32 HAL UART implementation. Redirects (f)printf HAL_UART_Transmit using a UART_HandleTypeDef that must be provided as DEBUG_UART_HANDLE


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

#include "distortos/chip/lowLevelInitialization.hpp"

namespace distortos
{

namespace chip
{

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

void lowLevelInitialization()
{

}

}	// namespace chip

}	// namespace distortos

Add empty chip::lowLevelInitialization() for STM32L4


/*
 * optical_flow_mat_benchmark.cpp
 *
 *  Created on: May 22, 2016
 *      Author: Cody W. Eilar <Cody.Eilar@Gmail.com>
 */

#include <celero/Celero.h>

#include "../readers/video_file_reader.h"
#include "../datatypes/image.h"
#include "../optical_flow/motion_estimation.h"
#include "../optical_flow/optical_flow.h"
#include "../optical_flow/lk_flow.h"
#include "../optical_flow/farneback_flow.h"

#include "opencv2/core/utility.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/videoio.hpp"
#include <opencv2/imgproc/imgproc.hpp>

#include <string>
CELERO_MAIN

namespace oflow {

const std::string filename{
    "/Users/cody/Dropbox/CodyShared/PreProposal_AOLMEFall2015/"
    "ActivityClassifier/data/writing/Cropped/seg2.mov"};

BASELINE(OpticalFlowBenchmarks, NoGpuSupport, 3, 3) {
  std::shared_ptr<oflow::VideoFileReader> f(
      new oflow::VideoFileReader(filename));
  oflow::MotionEstimation<oflow::VideoFileReader, cv::Mat> me(f);
  std::shared_ptr<oflow::FarneBackFlow> my_flow(new oflow::FarneBackFlow());
  me.EstimateMotion(my_flow);
}

BENCHMARK(OpticalFlowBenchmarks, GpuSupport, 3, 3) {
  std::shared_ptr<oflow::VideoFileReader> f(
      new oflow::VideoFileReader(filename));
  oflow::MotionEstimation<oflow::VideoFileReader, cv::UMat> me(f);
  std::shared_ptr<oflow::FarneBackFlow> my_flow(new oflow::FarneBackFlow());
  me.EstimateMotion(my_flow);
}
}

Add benchmark for testing umat vs mat for optical flow


#include<iostream>
#include<set>

const int MAXN = 300042;
int A[MAXN];

int main()
{
	std::cin.tie(0);
	std::ios::sync_with_stdio(0);

	int n, q;
	std::cin >> n >> q;

	for(int i = 0; i < n; ++i)
		std::cin >> A[i];

	std::set<int> break_points;

	for(int i = 1; i < n; ++i)
	{
		if(A[i] <= A[i - 1])
			break_points.insert(i);
	}

	for(int i = 0; i < q; ++i)
	{
		char c;
		int x, y;
		std::cin >> c >> x >> y;

		if(c == '=')
		{
			A[x] = y;

			if(x > 0)
			{
				if(A[x] <= A[x - 1])
					break_points.insert(x);
				else break_points.erase(x);
			}

			if(x < n - 1)
			{
				if(A[x + 1] <= A[x])
					break_points.insert(x + 1);
				else break_points.erase(x + 1);
			}
		}
		else // ?
		{
			// [ x, y ) -> ( x, y )
			auto it = break_points.upper_bound(x);
			std::cout << (it != break_points.end() && *it >= y) << '\n';
		}
	}
}

Add author solution for problem


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

// Use this file to assert that *_list.h enums that are meant to do the bridge
// from Blink are valid.

#include "base/macros.h"
#include "content/public/common/screen_orientation_values.h"
#include "third_party/WebKit/public/platform/WebScreenOrientation.h"

namespace content {

#define COMPILE_ASSERT_MATCHING_ENUM(expected, actual) \
  COMPILE_ASSERT(int(expected) == int(actual), mismatching_enums)

COMPILE_ASSERT_MATCHING_ENUM(blink::WebScreenOrientationPortraitPrimary,
    PORTRAIT_PRIMARY);
COMPILE_ASSERT_MATCHING_ENUM(blink::WebScreenOrientationLandscapePrimary,
    LANDSCAPE_PRIMARY);
COMPILE_ASSERT_MATCHING_ENUM(blink::WebScreenOrientationPortraitSecondary,
    PORTRAIT_SECONDARY);
COMPILE_ASSERT_MATCHING_ENUM(blink::WebScreenOrientationLandscapeSecondary,
    LANDSCAPE_SECONDARY);

} // namespace content

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

// Use this file to assert that *_list.h enums that are meant to do the bridge
// from Blink are valid.

#include "base/macros.h"
#include "content/public/common/screen_orientation_values.h"
#include "third_party/WebKit/public/platform/WebScreenOrientation.h"

namespace content {

#define COMPILE_ASSERT_MATCHING_ENUM(expected, actual) \
  COMPILE_ASSERT(int(expected) == int(actual), mismatching_enums)

// TODO(mlamouri): this is temporary to allow to change the enum in Blink.
// COMPILE_ASSERT_MATCHING_ENUM(blink::WebScreenOrientationPortraitPrimary,
//     PORTRAIT_PRIMARY);
// COMPILE_ASSERT_MATCHING_ENUM(blink::WebScreenOrientationLandscapePrimary,
//     LANDSCAPE_PRIMARY);
// COMPILE_ASSERT_MATCHING_ENUM(blink::WebScreenOrientationPortraitSecondary,
//     PORTRAIT_SECONDARY);
// COMPILE_ASSERT_MATCHING_ENUM(blink::WebScreenOrientationLandscapeSecondary,
//     LANDSCAPE_SECONDARY);

} // namespace content

Comment enum matching assert to allow changes in Blink.


// This file is part of playd.
// playd is licenced under the MIT license: see LICENSE.txt.

/**
 * @file
 * Tests for the Tokeniser class.
 */

#include "catch.hpp"
#include "../io/tokeniser.hpp"

SCENARIO("Tokenisers can handle complete, unquoted commands", "[tokeniser]") {
	GIVEN("A fresh Tokeniser") {
		Tokeniser t;

		WHEN("the Tokeniser is fed a nullary command") {
			auto words = t.Feed("stop\n");

			THEN("one line is returned") {
				REQUIRE(words.size() == 1);
			}

			THEN("the line contains one word") {
				REQUIRE(words[0].size() == 1);
			}

			THEN("the word is the nullary command") {
				REQUIRE(words[0][0] == "stop");
			}
		}

		WHEN("the Tokeniser is fed a unary command") {
			auto words = t.Feed("seek 10s\n");

			THEN("one line is returned") {
				REQUIRE(words.size() == 1);
			}

			THEN("the line contains two words") {
				REQUIRE(words[0].size() == 2);
			}

			THEN("the first word is the command") {
				REQUIRE(words[0][0] == "seek");
			}

			THEN("the second word is the argument") {
				REQUIRE(words[0][1] == "10s");
			}
		}
	}
}

Implement basic, but useful Tokeniser tests.


// C++ Program Reverse String using Stack

#include<iostream>  // include header files
#include<string.h>
using namespace std;

#define size 20 // include preprocessor

int top = -1;    // global variables
char stack[size];

char push(char ch) // Function which push string in stack
{
 if(top==(size-1)) 	// condition check location of top when it equal to size-1 then stack overflows
  cout<<"Stack is Overflow\n";
 else
  stack[++top]=ch; // put char on pre increment top
}

char pop() // Function which pop string in stack
{
 if(top==-1) // condition check location of top when it equal to -1 then stack underflows
  cout<<"Stack is Underflow\n";
 else
  return stack[top--];
}

int main() // main() function from where execution starts
{
 char str[20];  	// define character array of 20 size to take string of length 20
 cout<<"Enter String:\t";
 gets(str); 	// Takes string from user
 int i;
 for(i=0;i<strlen(str);i++) 	// strlen() function present inside string.h header file to calculate length of string
  {
   push(str[i]);		// Testing of push() function
  }
 for(i=0;i<strlen(str);i++)
  {
      str[i]=pop();  // Testing of pop() function
  }
 cout<<"Reversed of String is : ";
 puts(str);	 // Show output to user

	return 0;
}

Add Reverse of String using Stack


// Intercept the implicit 'this' argument of class member functions.
//
// RUN: %clangxx_xray -g -std=c++11 %s -o %t
// RUN: rm log-args-this-* || true
// RUN: XRAY_OPTIONS="patch_premain=true verbosity=1 xray_logfile_base=log-args-this-" %run %t
//
// XFAIL: arm || aarch64 || mips
// UNSUPPORTED: powerpc64le
#include "xray/xray_interface.h"
#include <cassert>

class A {
 public:
  [[clang::xray_always_instrument, clang::xray_log_args(1)]] void f() {
    // does nothing.
  }
};

volatile uint64_t captured = 0;

void handler(int32_t, XRayEntryType, uint64_t arg1) {
  captured = arg1;
}

int main() {
  __xray_set_handler_arg1(handler);
  A instance;
  instance.f();
  __xray_remove_handler_arg1();
  assert(captured == (uint64_t)&instance);
}

Add test for logging the implicit "this" argument for C++ member functions.


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

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

#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"

// TODO(skerner): This test is flaky in chromeos.  Figure out why and fix.
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
#define MAYBE_Tabs DISABLED_Tabs
#else
#define MAYBE_Tabs Tabs
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
  StartHTTPServer();

  // The test creates a tab and checks that the URL of the new tab
  // is that of the new tab page.  Make sure the pref that controls
  // this is set.
  browser()->profile()->GetPrefs()->SetBoolean(
      prefs::kHomePageIsNewTabPage, true);

  ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}

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

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

#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"

// TODO(skerner): This test is flaky in chromeos and on Mac OS X 10.6.  Figure
// out why and fix.
#if (defined(OS_LINUX) && defined(TOOLKIT_VIEWS)) || defined(OS_MACOSX)
#define MAYBE_Tabs DISABLED_Tabs
#else
#define MAYBE_Tabs Tabs
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
  StartHTTPServer();

  // The test creates a tab and checks that the URL of the new tab
  // is that of the new tab page.  Make sure the pref that controls
  // this is set.
  browser()->profile()->GetPrefs()->SetBoolean(
      prefs::kHomePageIsNewTabPage, true);

  ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}

Disable ExtensionApiTest.Tabs on Mac. TEST=no random redness on Mac OS X 10.6 bot BUG=37387 TBR=skerner@


#include <iostream>
#include <OptionList.h>
#include <SQLiteDatabase.h>
#include <SimilarityStrategy.h>
#include <Generator.h>

#define PARAMS 1

using namespace SoundCity;
using std::cout;
using std::endl;

void
usage (char *s)
{
  fprintf(stderr, "Usage: %s <database>\n", s);
  exit(EXIT_FAILURE);
}

int
main(int argc, char *argv[])
{
  if (argc != PARAMS+1)
    usage(argv[0]);

  SimilarityStrategy similarity;
  SQLiteDatabase database(argv[1]);
  cout << "Crétation d'une liste d'options" << endl;
  OptionList options("",0,0,0,0,0,0,1);
  Generator generator(database, similarity);

  if(generator.initialization() == 0)
  {
    cout << "Erreur d'initialisation" << endl;
    exit(EXIT_FAILURE);
  }
  cout << "Lancement de la génération" << endl;
  Playlist playlist = generator.generate(options);
  cout << "Génération terminée" << endl;
  cout << "Taille de la playlist générée : " << playlist.size() << endl;
  for(auto it = playlist.begin(); it != playlist.end(); ++it)
    cout << (*it).getTitle() << " - " << it->getArtistName() << " (" <<  it->getAlbumReleaseDate() << ")" << endl;

  return EXIT_SUCCESS;
}

Test du Generator et de la Database en console


// 149. Max Points on a Line
/**
 * Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
 *
 * Tags: Hash Table, Math
 *
 * Author: Kuang Qin
 */

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

using namespace std;

/**
 * Definition for a point.
 */
struct Point {
    int x;
    int y;
    Point() : x(0), y(0) {}
    Point(int a, int b) : x(a), y(b) {}
};

// Hash Table
// Time: O(n^2)
class Solution {
public:
    int maxPoints(vector<Point>& points) {
        int n = points.size();
        if (n < 2)
        {
            return n;
        }

        // use a hash table to store slopes of lines containing a specific point
        unordered_map<double, int> slope;
        int count = 0;    // results
        for (int i = 0; i < n - 1; i++)
        {
            int duplicates = 1;    // duplicate points counter
            int vertical = 0;    // vertical slope counter
            for (int j = i + 1; j < n; j++)
            {
                // duplicate points
                if (points[j].x == points[i].x && points[j].y == points[i].y)
                {
                    duplicates++;
                    continue;
                }

                // points on a vertical line
                if (points[j].x == points[i].x)
                {
                    vertical++;
                    continue;
                }

                // points on a certain slope
                float k = (float)(points[j].y - points[i].y) / (points[j].x - points[i].x);
                if (slope.find(k) == slope.end())
                {
                    slope[k] = 1;
                }
                else
                {
                    slope[k]++;
                }
            }

            // scan the hash table for the max value
            count = max(count, vertical + duplicates);
            for (auto it = slope.begin(); it != slope.end(); it++)
            {
                if (it->second + duplicates > count)
                {
                    count = it->second + duplicates;
                }
            }

            slope.clear();
        }

        return count;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    return 0;
}

Add Solution for Problem 149


// Return multiple values

#include <tuple>

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

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

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

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

// Return multiple values

#include <tuple>

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

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

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

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

Use std::make_tuple in return multiple values sample


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

namespace {
    struct Person {
        int weight;
        int height;
    };

    bool operator>(const Person &a, const Person &b) {
        return std::tie(a.weight, a.height) > std::tie(b.weight, b.height);
    }

    bool operator<(const Person &a, const Person &b) {
        return std::tie(a.weight, a.height) < std::tie(b.weight, b.height);
    }

    bool operator==(const Person &a, const Person &b) {
        return std::tie(a.weight, a.height) == std::tie(b.weight, b.height);
    }
    using container_type = std::vector<Person>;

    void print(const container_type &data) {
        if (data.empty()) return;
        auto iter = data.cbegin();
        std::cout << "(" << iter->weight << "," << iter->height << ")";
        ++iter;
        for (; iter != data.cend(); ++iter) {
            std::cout << " (" << iter->weight << "," << iter->height << ")";
        }
        std::cout << "\n";
    }

    struct CircusTower {
        void search(const container_type &data) {
            size_t N = data.size();
            size_t max_height = 0;
            for (size_t i = 0; i < (N - 1); ++i) {
                size_t current_height = 1;
                Person prev = data[i];
                for (size_t j = i + 1; j < N; ++j) {
                    if (is_valid(prev, data[j])) {
                        prev = data[j];
                        ++current_height;
                    }
                }
                max_height = std::max(max_height, current_height);
            }
            print(data);
            std::cout << "max height: " << max_height << "\n";
        }

        bool is_valid(const Person &a, const Person &b) {
            return (a.weight <= b.weight) && (a.height <= b.height);
        }
    };

} // namespace
int main() {
    CircusTower tower;
    {
        container_type data1{{65, 100}, {70, 150}, {56, 90}, {75, 190}, {60, 95}, {68, 100}};
        std::sort(data1.begin(), data1.end());
        tower.search(data1);
    }

    {
        container_type data1{{65, 160}, {70, 150}, {66, 90}};
        std::sort(data1.begin(), data1.end());
        tower.search(data1);
    }
}

Add solution for 17.8 problem.


//TODO remove unused imports
#include <climits>
#include <cstring>
#include <unistd.h>
#include <sys/stat.h>
#include <algorithm>
#include <string>

#include <core/loader.h>
#include <core/module.h>
#include <core/logger.h>
#include <core/framework.h>
namespace lms{

std::string Framework::programDirectory(){
    static std::string directory;

    if(directory.empty()) {
        char path[PATH_MAX];
        memset (path, 0, PATH_MAX);
        if (readlink("/proc/self/exe", path, PATH_MAX) == -1) {
            perror("readlink failed");
            exit(1);
        }
        //get programmdirectory
        // TODO optimize this a bit
        directory = path;
        directory = directory.substr(0, directory.rfind("/"));
        directory = directory.substr(0, directory.rfind("/"));
        directory = directory + "/";
     }

    //std::cout << "ProgramDirectory: " << directory << std::endl;
    return directory;
}
}

//TODO remove unused imports
#include <climits>
#include <cstring>
#include <unistd.h>
#include <sys/stat.h>
#include <algorithm>
#include <string>

#include <core/loader.h>
#include <core/module.h>
#include <core/logger.h>
#include <core/framework.h>

#ifdef __APPLE__
    #include <mach-o/dyld.h>
#endif

namespace lms{

std::string Framework::programDirectory(){
    static std::string directory;

    if(directory.empty()) {
        char path[PATH_MAX];
        memset (path, 0, PATH_MAX);
#ifdef __APPLE__
        uint32_t size = PATH_MAX;
        if( _NSGetExecutablePath(path, &size) == 0 ) {
            char* fullpath = realpath(path, NULL);
            if( !fullpath ) {
                perror("realpath failed");
                exit(1);
            }
            directory = fullpath;
        } else {
            perror("_NSGetExecutablePath failed");
            exit(1);
        }
#else
        if (readlink("/proc/self/exe", path, PATH_MAX) == -1) {
            perror("readlink failed");
            exit(1);
        }
        directory = path;
#endif
        // TODO optimize this a bit
        directory = directory.substr(0, directory.rfind("/"));
        directory = directory.substr(0, directory.rfind("/"));
        directory = directory + "/";
     }

    //std::cout << "ProgramDirectory: " << directory << std::endl;
    return directory;
}
}

Fix Framework::programDirectory on OS X


// RUN: %clang_cc1 -fsyntax-only -verify %s
// expected-no-diagnostics
namespace llvm {
  template<typename T > struct StringSet;
  template<int I > struct Int;
  template <typename Inner, template <typename> class Outer>
    struct TemplTempl;
}

namespace lld {
  using llvm::StringSet;
  using llvm::Int;
  using llvm::TemplTempl;
};

namespace llvm {
  template<typename T > struct StringSet;
}

template<typename T> struct Temp{};

namespace llvm {
  template<typename T = int> struct StringSet{};
  template<int I = 5> struct Int{};
  template <typename Inner, template <typename> class Outer = Temp>
    struct TemplTempl{};
};

namespace lld {
  StringSet<> s;
  Int<> i;
  TemplTempl<int> tt;
}

Add Forgotten test for: Fix template parameter default args missed if redecled


// 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 "net/url_request/url_fetcher.h"

#include "net/url_request/url_fetcher_factory.h"
#include "net/url_request/url_fetcher_impl.h"

namespace net {

URLFetcher::~URLFetcher() {}

// static
URLFetcher* net::URLFetcher::Create(
    const GURL& url,
    URLFetcher::RequestType request_type,
    URLFetcherDelegate* d) {
  return new URLFetcherImpl(url, request_type, d);
}

// static
URLFetcher* net::URLFetcher::Create(
    int id,
    const GURL& url,
    URLFetcher::RequestType request_type,
    URLFetcherDelegate* d) {
  URLFetcherFactory* factory = URLFetcherImpl::factory();
  return factory ? factory->CreateURLFetcher(id, url, request_type, d) :
                   new URLFetcherImpl(url, request_type, d);
}

// static
void net::URLFetcher::CancelAll() {
  URLFetcherImpl::CancelAll();
}

// static
void net::URLFetcher::SetEnableInterceptionForTests(bool enabled) {
  URLFetcherImpl::SetEnableInterceptionForTests(enabled);
}

// static
void net::URLFetcher::SetIgnoreCertificateRequests(bool ignored) {
  URLFetcherImpl::SetIgnoreCertificateRequests(ignored);
}

}  // namespace net

// 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 "net/url_request/url_fetcher.h"

#include "net/url_request/url_fetcher_factory.h"
#include "net/url_request/url_fetcher_impl.h"

namespace net {

URLFetcher::~URLFetcher() {}

// static
URLFetcher* net::URLFetcher::Create(
    const GURL& url,
    URLFetcher::RequestType request_type,
    URLFetcherDelegate* d) {
  return URLFetcher::Create(0, url, request_type, d);
}

// static
URLFetcher* net::URLFetcher::Create(
    int id,
    const GURL& url,
    URLFetcher::RequestType request_type,
    URLFetcherDelegate* d) {
  URLFetcherFactory* factory = URLFetcherImpl::factory();
  return factory ? factory->CreateURLFetcher(id, url, request_type, d)
                 : new URLFetcherImpl(url, request_type, d);
}

// static
void net::URLFetcher::CancelAll() {
  URLFetcherImpl::CancelAll();
}

// static
void net::URLFetcher::SetEnableInterceptionForTests(bool enabled) {
  URLFetcherImpl::SetEnableInterceptionForTests(enabled);
}

// static
void net::URLFetcher::SetIgnoreCertificateRequests(bool ignored) {
  URLFetcherImpl::SetIgnoreCertificateRequests(ignored);
}

}  // namespace net

Use URLFetcherFactory for 3-arg overload of URLFetcher::Create


#include <boost/test/unit_test.hpp>
#include <ygo/deck/c/User.h>
#include <ygo/deck/c/DB.h>

struct User_Fixture
{
    User_Fixture()
    {
        DB_NAME(set_path)("test/card.db");
    }
};

BOOST_FIXTURE_TEST_SUITE(User, User_Fixture)

BOOST_AUTO_TEST_CASE(Create)
{
    auto user = USER_NAME(new_create)("Test");
    auto name = USER_NAME(name)(user);
    BOOST_CHECK_EQUAL(std::string(name), "Test");
    USER_NAME(delete_name)(name);
    USER_NAME(delete)(user);
}

BOOST_AUTO_TEST_CASE(Open)
{
    auto user = USER_NAME(new)("Test");
    auto name = USER_NAME(name)(user);
    BOOST_CHECK_EQUAL(std::string(name), "Test");
    USER_NAME(delete_name)(name);
    USER_NAME(delete)(user);
}

BOOST_AUTO_TEST_CASE(Unknown)
{
    auto user = USER_NAME(new)("NotKnown");
    BOOST_CHECK(user == nullptr);
}

BOOST_AUTO_TEST_CASE(Remove)
{
    auto user = USER_NAME(new)("Test");
    auto name = USER_NAME(name)(user);
    BOOST_CHECK_EQUAL(std::string(name), "Test");
    USER_NAME(remove)(user);
    USER_NAME(delete_name)(name);
    USER_NAME(delete)(user);

    auto user2 = USER_NAME(new)("Test");
    BOOST_CHECK(user2 == nullptr);
}

BOOST_AUTO_TEST_SUITE_END()

Add unit tests for user C bindings


/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "markup.h"

/*!
    \class BinEditor::Markup
    \brief The Markup class defines the range of the binary editor.

    Used for displaying class layouts by the debugger.

    \note Must not have linkage - used for soft dependencies.

    \sa Debugger::Internal::MemoryAgent
*/

Revert "BinEditor: Remove unused file"


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* transfer(vector<int>& nums, int start, int end){
        if(start > end) return NULL;
        else if(start == end) return new TreeNode(nums[start]);
        int mid = start + (end - start) / 2;
        TreeNode* root = new TreeNode(nums[mid]);
        root->left = transfer(nums, start, mid - 1);
        root->right = transfer(nums, mid + 1, end);
        return root;
    }
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return transfer(nums, 0, nums.size() - 1);
    }
};

Convert Sorted Array to Binary Search Tree


// Check existence of a key
// C++11

#include <map>
#include <string>

int main()
{
	std::map<std::string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};

	if (m.count("b"))
	{
		// We know "b" is in m
	}
}

// Check if a particular key is in an associative container.
//
// On [9], we create a [`std::map`](cpp/container/map) as an example
// associative container and initialize it with key-value pairs.
//
// On [11], we count the number of occurrences of the key `"b"` in `m`
// by using the memeber function [`count`](cpp/container/map/count).
// If `"b"` is in `m`, `count` will return 1; otherwise it will return
// 0.
//
// Note: in C++14, an instance of the searched key will not be created
// if the container's comparator is
// [transparent](http://stackoverflow.com/q/20317413/150634) and
// supports the appropriate comparison without conversions.

// Check existence of a key
// C++11

#include <map>
#include <string>

int main()
{
	std::map<std::string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};

	if (m.count("b"))
	{
		// We know "b" is in m
	}
}

// Check if a particular key is in an associative container.
//
// On [9], we create a [`std::map`](cpp/container/map) as an example
// associative container and initialize it with key-value pairs.
//
// On [11], we count the number of occurrences of the key `"b"` in `m`
// by using the member function [`count`](cpp/container/map/count).
// If `"b"` is in `m`, `count` will return 1; otherwise it will return
// 0.
//
// Note: in C++14, an instance of the searched key will not be created
// if the container's comparator is
// [transparent](http://stackoverflow.com/q/20317413/150634) and
// supports the appropriate comparison without conversions.

Fix typo in key existence sample


// Regression test for origin propagation in "select i1, float, float".
// https://code.google.com/p/memory-sanitizer/issues/detail?id=78

// RUN: %clangxx_msan -O2 -fsanitize-memory-track-origins %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out

// RUN: %clangxx_msan -O2 -fsanitize-memory-track-origins=2 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out

#include <stdio.h>
#include <sanitizer/msan_interface.h>

int main() {
  volatile bool b = true;
  float x, y;
  __msan_allocated_memory(&x, sizeof(x));
  __msan_allocated_memory(&y, sizeof(y));
  float z = b ? x : y;
  if (z > 0) printf(".\n");
  // CHECK: Uninitialized value was created by a heap allocation
  // CHECK: {{#0 0x.* in .*__msan_allocated_memory}}
  // CHECK: {{#1 0x.* in main .*select_float_origin.cc:}}[[@LINE-6]]
  return 0;
}

Fix origin propagation for select of floats.


// RUN: %clang_cc1 %s -triple=arm-linux-gnueabi -target-abi aapcs -emit-llvm -o - | FileCheck %s

class SMLoc {
 const char *Ptr;
public:
 SMLoc();
 SMLoc(const SMLoc &RHS);
};
SMLoc foo(void *p);
void bar(void *x) {
 foo(x);
}
void zed(SMLoc x);
void baz() {
  SMLoc a;
  zed(a);
}

// CHECK: declare arm_aapcscc void @_Z3fooPv(%class.SMLoc* sret, i8*)
// CHECK: declare arm_aapcscc void @_Z3zed5SMLoc(%class.SMLoc*)

Add test for previous commit.


#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
    using namespace boost::lambda;
    typedef std::istream_iterator<int> in;

    std::for_each(
        in(std::cin), in(), std::cout << (_1 * 3) << " " );
}

Add script to test install


#include <iostream>
#include <chrono>

struct Test {
	Test(long N) : n(N) {
		long sum = 0;
		for (long i = 0; i < n; ++i) {
			sum += i;
		}
	}

	Test() : n(1e8) {
		Test(n);
	}

	long n;
}; // struct Test

int main(int argc, char* argv[]) {
	const long N(1e8);
	auto start = std::chrono::system_clock::now();
	Test t1 = Test(N);
	auto stop = std::chrono::system_clock::now();

	std::cout << "Test t1 = Test() took " << (stop - start).count() << " to initialize\n";

	start = std::chrono::system_clock::now();
	Test t2(N);
	stop = std::chrono::system_clock::now();

	std::cout << "Test t2(N) took " << (stop - start).count() << " s to initialize\n";

	return 0;
}

Create a class to look at difference in time for constructors


#include <stan/math/matrix/mdivide_left_spd.hpp>
#include <stan/math/matrix/typedefs.hpp>
#include <gtest/gtest.h>

TEST(MathMatrix,mdivide_left_spd_val) {
  using stan::math::mdivide_left_spd;
  stan::math::matrix_d Ad(2,2);
  stan::math::matrix_d I;

  Ad << 2.0, 3.0,
        3.0, 7.0;

  I = mdivide_left_spd(Ad,Ad);
  EXPECT_NEAR(1.0,I(0,0),1.0E-12);
  EXPECT_NEAR(0.0,I(0,1),1.0E-12);
  EXPECT_NEAR(0.0,I(1,0),1.0E-12);
  EXPECT_NEAR(1.0,I(1,1),1.0e-12);
}

Add a test for double version of mdivide_left_sped.


// 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 "base/at_exit.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "base/test/launcher/unit_test_launcher.h"
#include "base/test/test_suite.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/angle/src/tests/end2end_tests/ANGLETest.h"

namespace {

int RunHelper(base::TestSuite* test_suite) {
  base::MessageLoop message_loop;
  return test_suite->Run();
}

}  // namespace

int main(int argc, char** argv) {
  base::CommandLine::Init(argc, argv);
  testing::InitGoogleMock(&argc, argv);
  testing::AddGlobalTestEnvironment(new ANGLETestEnvironment());
  base::TestSuite test_suite(argc, argv);
  int rt = base::LaunchUnitTestsSerially(
      argc,
      argv,
      base::Bind(&RunHelper, base::Unretained(&test_suite)));
  return rt;
}

// 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 "base/at_exit.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "base/test/launcher/unit_test_launcher.h"
#include "base/test/test_suite.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/angle/src/tests/test_utils/ANGLETest.h"

namespace {

int RunHelper(base::TestSuite* test_suite) {
  base::MessageLoop message_loop;
  return test_suite->Run();
}

}  // namespace

int main(int argc, char** argv) {
  base::CommandLine::Init(argc, argv);
  testing::InitGoogleMock(&argc, argv);
  testing::AddGlobalTestEnvironment(new ANGLETestEnvironment());
  base::TestSuite test_suite(argc, argv);
  int rt = base::LaunchUnitTestsSerially(
      argc,
      argv,
      base::Bind(&RunHelper, base::Unretained(&test_suite)));
  return rt;
}

Update gpu/angle_end2end_tets with recent file move


// RUN: %clang_cc1 -Wc++11-compat -verify -std=c++98 %s
// RUN: cp %s %t
// RUN: not %clang_cc1 -Wc++11-compat -Werror -x c++ -std=c++98 -fixit %t
// RUN: %clang_cc1 -Wall -pedantic-errors -Wc++11-compat -Werror -x c++ -std=c++98 %t

// This is a test of the code modification hints for C++11-compatibility problems.

#define bar "bar"
const char *p = "foo"bar; // expected-warning {{will be treated as a user-defined literal suffix}}

Test fix-it added in r152198.