#include <botan/botan.h>
#include <botan/benchmark.h>
#include <botan/filters.h>

#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <cstdlib>

/*
Try to find the fastest SHA-1 implementation and use it to hash
files. In most programs this isn't worth the bother and
overhead. However with large amount of input, it is worth it. On tests
on a Core2 system with the SHA-1 SSE2 code enabled, over a few hundred
Mb or so the overhead paid for itself.

Of course you could also just do this once and save it as an
application config, which is probably the smart thing to do.
*/

void set_fastest_implementation(const std::string& algo,
                                Botan::RandomNumberGenerator& rng,
                                double ms = 30)
   {
   Botan::Default_Benchmark_Timer timer;

   Botan::Algorithm_Factory& af = Botan::global_state().algorithm_factory();

   std::map<std::string, double> results =
      Botan::algorithm_benchmark(algo, ms, timer, rng, af);

   std::string fastest_provider = "";
   double best_res = 0;

   for(std::map<std::string, double>::iterator r = results.begin();
       r != results.end(); ++r)
      {
      std::cout << r->first << " @ " << r->second << " MiB/sec\n";

      if(fastest_provider == "" || r->second > best_res)
         {
         fastest_provider = r->first;
         best_res = r->second;
         }
      }

   std::cout << "Using " << fastest_provider << "\n";

   af.set_preferred_provider(algo, fastest_provider);
   }

int main(int argc, char* argv[])
   {
   if(argc <= 1)
      {
      std::cout << "Usage: " << argv[0] << " <file> <file> ...\n";
      return 1;
      }

   Botan::LibraryInitializer init;
   Botan::AutoSeeded_RNG rng;

   const std::string hash = "SHA-1";

   //set_fastest_implementation(hash, rng);

   // Here we intentionally use the 'old style' lookup interface
   // which will also respect the provider settings. Or can use:
   //   global_state().algorithm_factory().make_hash_function(hash)
   Botan::Pipe pipe(
      new Botan::Hash_Filter(Botan::get_hash(hash)),
      new Botan::Hex_Encoder
      );

   for(size_t i = 1; argv[i]; ++i)
      {
      std::ifstream in(argv[i]);
      if(!in)
         continue;

      pipe.start_msg();
      in >> pipe;
      pipe.end_msg();

      std::cout << argv[i] << " = "
                << pipe.read_all_as_string(Botan::Pipe::LAST_MESSAGE) << "\n";

      }
   }

Add an example of using the benchmark system to choose the fastest SHA-1 implementation and then setting it as the default.


/*
	This program tests Counting sort
*/

#include<iostream>
#include<vector>
#include "countingsort.h"	// My implementation of Counting sort

// Displays vector

void printVector(std::vector<int> A){
	for(auto x: A){
		std::cout<<x<<" ";

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

// Tests Counting sort on vector A

void testCountingSort(std::vector<int> A, int k){

	std::cout<<"Before: ";
	printVector(A);
	CountingSort::sort(A, k);
	std::cout<<"After: ";
	printVector(A);
}

// tests Counting sort on several different inputs

void testCountingSort(){

	std::vector<int> v1 = {10,9,8,7,6,5,4,3,2,1};
	testCountingSort(v1, 10);

	std::vector<int> v2 = {5,4,3,2,1};
	testCountingSort(v2, 5);

	std::vector<int> v3 = {1,2,3,4,5,6,7,8,9,10};
	testCountingSort(v3, 10);

	std::vector<int> v4 = {6,5,4,7,8,9,9,5,4,9,2,0,3,1,5,9,8,7,4,5,6,3};
	testCountingSort(v4, 9);

	// test on empty vector
	std::vector<int> v5;
	testCountingSort(v5, 5);

	std::vector<int> v6 = {100,152,0,64,36,19,43,22,97,33,46,95,73,20};
	testCountingSort(v6, 152);

	std::vector<int> v7 = {1,2,3,4,5,6,7,8,9,0};
	testCountingSort(v7, 9);
}

int main(){

	// test Counting sort
	testCountingSort();

	return 0;
}

Add test program for counting sort


//   Copyright 2018 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 <exception>
#include <iostream>
#include <ostream>
#include <stdlib.h>
#include <string>

// EWS provides two methods that allow you to discover changes that have
// occurred in your mailbox from some starting point (indicated by a
// sync_state) until the time the request is made:
//
// - sync_folder_hierarchy is used to watch for changes made to your mailbox's
//   folders
// - sync_folder_items is used to determine changes to the contents of a single
//   folder
//
// This example is about the latter.

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

        ews::distinguished_folder_id folder = ews::standard_folder::inbox;

        // Initial synchronization call
        auto result = service.sync_folder_hierarchy(folder);

        // Store sync_state for further synchronization calls
        const auto sync_state = result.get_sync_state();

        // Output all existing folders
        for (const auto& folder : result.get_created_folders())
        {
            std::cout << folder.get_display_name() << "\n";
        }

        // Create test folder
        ews::folder new_folder;
        new_folder.set_display_name("Duck Cave");
        auto new_folder_id = service.create_folder(new_folder, folder);

        // Follow-up synchronization call
        result = service.sync_folder_hierarchy(folder, sync_state);

        // Output all newly created folders
        for (const auto& folder : result.get_created_folders())
        {
            std::cout << folder.get_display_name() << "\n";
        }

        // Delete test item
        service.delete_folder(new_folder_id);

        // Follow-up synchronization call
        result = service.sync_folder_hierarchy(folder, sync_state);

        // Output all deleted folders
        for (const auto& folder : result.get_deleted_folder_ids())
        {
            std::cout << folder.id() << "\n";
        }
    }
    catch (std::exception& exc)
    {
        std::cout << exc.what() << std::endl;
        res = EXIT_FAILURE;
    }

    ews::tear_down();
    return res;
}

Add example for SyncFolderHierarchy operation


// -*- C++ -*-
//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// UNSUPPORTED: c++98, c++03

// <tuple>

// template <class TupleLike> tuple(TupleLike&&); // libc++ extension

// See llvm.org/PR31384

#include <tuple>
#include <cassert>

int count = 0;

template<class T>
struct derived : std::tuple<T> {
  using std::tuple<T>::tuple;
  template<class U>
  operator std::tuple<U>() && {
    ++count;
    return {};
  }
};

int main() {
  std::tuple<int> foo = derived<int&&>{42};
  assert(count == 1);
}

Add test case for PR31384


//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// packet_manager_test.cpp
//
// Identification: test/wire/packet_manager_test.cpp
//
// Copyright (c) 2016-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "common/harness.h"
#include "gtest/gtest.h"
#include "common/logger.h"
#include "wire/libevent_server.h"
#include <pqxx/pqxx>

#define NUM_THREADS 1

namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Packet Manager Tests
//===--------------------------------------------------------------------===//

class PacketManagerTests: public PelotonTest {
};

static void* LaunchServer(void *) {
	try {
		// Setup
		peloton::PelotonInit::Initialize();
		LOG_INFO("Server initialized\n");
		// Launch server
		peloton::wire::LibeventServer libeventserver;
		LOG_INFO("Server Closed\n");
		// Teardown
		// Todo: Peloton cannot shut down normally, will try to fix this soon
		//peloton::PelotonInit::Shutdown();
		LOG_INFO("Peloton has shut down\n");
	} catch (peloton::ConnectionException exception) {
		// Nothing to do here!
	}
	return NULL;
}

static void* SimpleQueryTest(void *) {
	try {
		pqxx::connection C("host=127.0.0.1 port=15721 user=postgres sslmode=disable");
		LOG_INFO("Connected to %s\n", C.dbname());
		pqxx::work W(C);

		// create table and insert some data
		W.exec("DROP TABLE IF EXISTS employee;");
		W.exec("CREATE TABLE employee(id INT, name VARCHAR(100));");
		W.exec("INSERT INTO employee VALUES (1, 'Han LI');");
		W.exec("INSERT INTO employee VALUES (2, 'Shaokun ZOU');");
		W.exec("INSERT INTO employee VALUES (3, 'Yilei CHU');");

		pqxx::result R = W.exec("SELECT name FROM employee where id=1;");

		EXPECT_EQ(R.size(), 1);
		LOG_INFO("Found %lu employees\n", R.size());
		W.commit();
	} catch (const std::exception &e) {
		LOG_INFO("Exception occurred\n");
	}

	LOG_INFO("Client has closed\n");
	return NULL;
}

TEST_F(PacketManagerTests, SimpleQueryTest) {
	pthread_t threads[NUM_THREADS];
	int rc = pthread_create(&threads[0], NULL, LaunchServer, NULL);
	if (rc) {
		LOG_INFO("Error:unable to create server thread");
		exit(-1);
	}
	sleep(5);

	SimpleQueryTest(NULL);

	pthread_kill(threads[0], SIGHUP);
	pthread_join(threads[0], NULL);
}

}  // End test namespace
}  // End peloton namespace

Add simple wire protocol test


AliAnalysisTaskStrangenessLifetimes *AddTaskStrangenessLifetimes(
    TString tskname = "LifetimesFiltering", TString suffix = "") {
  // Get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskStrangenessLifetimes", "No analysis manager found.");
    return 0x0;
  }

  // Check the analysis type using the event handlers connected to the analysis
  // manager.
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskStrangenessLifetimes",
            "This task requires an input event handler");
    return 0x0;
  }

  tskname.Append(suffix.Data());
  AliAnalysisTaskStrangenessLifetimes *task =
      new AliAnalysisTaskStrangenessLifetimes(tskname.Data());

  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(
      Form("%s_summary", tskname.Data()), TList::Class(),
      AliAnalysisManager::kOutputContainer, "AnalysisResults.root");

  AliAnalysisDataContainer *coutput2 =
      mgr->CreateContainer(Form("V0tree%s", suffix.Data()), TTree::Class(),
                           AliAnalysisManager::kOutputContainer, "V0tree.root");
  coutput2->SetSpecialOutput();

  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, coutput1);
  mgr->ConnectOutput(task, 2, coutput2);
  return task;
}

AliAnalysisTaskStrangenessLifetimes *AddTaskStrangenessLifetimes(bool isMC = false,
    TString tskname = "LifetimesFiltering", TString suffix = "") {
  // Get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskStrangenessLifetimes", "No analysis manager found.");
    return 0x0;
  }

  // Check the analysis type using the event handlers connected to the analysis
  // manager.
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskStrangenessLifetimes",
            "This task requires an input event handler");
    return 0x0;
  }

  tskname.Append(suffix.Data());
  AliAnalysisTaskStrangenessLifetimes *task =
      new AliAnalysisTaskStrangenessLifetimes(isMC, tskname.Data());

  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(
      Form("%s_summary", tskname.Data()), TList::Class(),
      AliAnalysisManager::kOutputContainer, "AnalysisResults.root");

  AliAnalysisDataContainer *coutput2 =
      mgr->CreateContainer(Form("V0tree%s", suffix.Data()), TTree::Class(),
                           AliAnalysisManager::kOutputContainer, "V0tree.root");
  coutput2->SetSpecialOutput();

  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, coutput1);
  mgr->ConnectOutput(task, 2, coutput2);
  return task;
}

Enable MC flag in the AddTask 😅


// https://leetcode.com/problems/word-search/
// Using a DFS solution, stop as early as possible.

class Solution {
    bool dfs(const vector<vector<char> > &board,
             int r, int c,
             const char* word,
             vector<vector<bool> >* visited){
        if (*word != board[r][c]) {
            return false;
        }
        if (*(word+1) == '\0') {
            return true;
        }
        (*visited)[r][c] = true;
        int offr[] = {0, -1, 0, 1};
        int offc[] = {-1, 0, 1, 0};
        for (int i = 0; i < 4; ++i) {
            int nr = r + offr[i];
            int nc = c + offc[i];
            if (nr >= 0 && nr < board.size() && nc >= 0 && nc < board[0].size() && !(*visited)[nr][nc]) {
                if (dfs(board, nr, nc, word+1, visited)) {
                    return true;
                }
            }
        }
        (*visited)[r][c] = false;

        return false;
    }
public:
    bool exist(vector<vector<char> > &board, string word) {
        int nrows = board.size();
        if (nrows == 0) return false;
        int ncols = board[0].size();
        if (ncols == 0) return false;

        vector<vector<bool> > visited(nrows, vector<bool>(ncols, false));
        for (int r = 0; r < nrows; ++r) {
            for (int c = 0; c < ncols; ++c) {
                if (dfs(board, r, c, word.c_str(), &visited)) {
                    return true;
                }
            }
        }
        return false;
    }
};

Add a solution for problem 79: Word Search.


/**
 * @file       main.cpp
 * @author     Volodymyr Shymanskyy
 * @license    This project is released under the MIT License (MIT)
 * @copyright  Copyright (c) 2015 Volodymyr Shymanskyy
 * @date       Mar 2015
 * @brief
 */

//#define BLYNK_DEBUG
#define BLYNK_PRINT stdout
#ifdef RASPBERRY
 #include <BlynkApiWiringPi.h>
#else
 #include <BlynkApiLinux.h>
#endif
#include <BlynkSocket.h>
#include <BlynkOptionsParser.h>

static BlynkTransportSocket _blynkTransport;
BlynkSocket Blynk(_blynkTransport);

BLYNK_WRITE(1)
{
  BLYNK_LOG("Got a value: %s", param[0].asStr());
}

int main(int argc, char* argv[])
{
    const char *auth, *serv, *port;
    parse_options(argc, argv, auth, serv, port);

    Blynk.begin(auth, serv, port);

    while(true) {
        Blynk.run();
    }

    return 0;
}

/**
 * @file       main.cpp
 * @author     Volodymyr Shymanskyy
 * @license    This project is released under the MIT License (MIT)
 * @copyright  Copyright (c) 2015 Volodymyr Shymanskyy
 * @date       Mar 2015
 * @brief
 */

//#define BLYNK_DEBUG
#define BLYNK_PRINT stdout
#ifdef RASPBERRY
 #include <BlynkApiWiringPi.h>
#else
 #include <BlynkApiLinux.h>
#endif
#include <BlynkSocket.h>
#include <BlynkOptionsParser.h>

static BlynkTransportSocket _blynkTransport;
BlynkSocket Blynk(_blynkTransport);

BLYNK_WRITE(V1)
{
  BLYNK_LOG("Got a value: %s", param[0].asStr());
}

int main(int argc, char* argv[])
{
    const char *auth, *serv, *port;
    parse_options(argc, argv, auth, serv, port);

    Blynk.begin(auth, serv, port);

    while(true) {
        Blynk.run();
    }

    return 0;
}

Fix pin name in example


#include "Halide.h"

using namespace Halide;

bool errored = false;
void my_error(void *, const char *msg) {
    printf("Expected error: %s\n", msg);
    errored = true;
}

void my_print(void *, const char *msg) {
    // Empty to neuter debug message spew
}

int main(int argc, char **argv) {
    Target t = get_jit_target_from_environment();
    if (!t.has_feature(Target::CUDA)) {
        printf("Not running test because cuda not enabled\n");
        return 0;
    }

    // Turn on debugging so that the pipeline completes and error
    // checking is done before realize returns. Otherwise errors are
    // discovered too late to call a custom error handler.
    t.set_feature(Target::Debug);

    Func f;
    Var c, x;
    f(c, x) = x + c + 3;
    f.bound(c, 0, 3).unroll(c);

    Func g;
    g(c, x) = f(c, x) * 8;

    g.gpu_tile(x, 8);
    f.compute_at(g, Var::gpu_blocks()).gpu_threads(x);

    g.set_error_handler(&my_error);
    g.set_custom_print(&my_print);

    // Should succeed
    g.realize(3, 100, t);
    if (errored) {
        printf("There was not supposed to be an error\n");
        return -1;
    }

    // Should trap
    g.realize(4, 100, t);

    if (!errored) {
        printf("There was supposed to be an error\n");
        return -1;
    }

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

Add test for gpu assertions


#include <iostream>
#include <cstring>

using namespace std;

class Dog {
    char name[30];
public:
    Dog(const char _name[] = "") {
        strcpy(name, _name);
    }
    void greet() {
        cout << "Bark, bark! I am " << name << ", a talking dog." << endl;
    }
};

class Person {
    char name[30];
    int age;
    Dog dog;
public:
    Person(const char _name[], int _age, Dog _dog) {
        strcpy(name, _name);
        age = _age;
        dog = _dog;
    }
    void greet() {
        cout << "Hi! I am " << name << " and I am " << age << " years old." << endl;
        cout << "And this is my dog:" << endl;
        dog.greet();
    }
};

int main() {
    Person ivan("Ivan", 15, Dog("Johny"));
    ivan.greet();

    return 0;
}

Add solution to task one using cstring Use char[] instead of string for demonstration


#include "humlib.h"

using namespace std;
using namespace hum;

void processFile(HumdrumFile& infile);

int main(int argc, char** argv) {
	Options options;
	options.process(argc, argv);
	HumdrumFileStream instream(options);
	HumdrumFile infile;
	while (instream.read(infile)) {
		processFile(infile);
	}
	return 0;
}

//////////////////////////////
//
// processFile --
//

void processFile(HumdrumFile& infile) {
	infile.analyzeNonNullDataTokens();
	for (int i=0; i<infile.getLineCount(); i++) {
		HTp token = infile.token(i, 0);
cerr << "LINE " << i << endl;
		cout << "\t" << infile[i] << "\t" << token->getNextNNDT() << endl;
	}
}

Add test for getting the next non-null data token.


// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

#include <thread>
#include <cassert>
#include <iostream>
#include "../include/analyzer/Timer.hpp"

int main(void)
{
    analyzer::diagnostic::Timer timer(true);
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::size_t count = timer.GetCount().MilliSeconds();
    std::cout << "Test 1: " << count << std::endl;
    assert(count >= 2000);

    std::this_thread::sleep_for(std::chrono::seconds(1));
    count = timer.PauseGetCount().MilliSeconds();
    std::cout << "Test 2: " << count << std::endl;
    assert(count >= 3000);

    std::this_thread::sleep_for(std::chrono::seconds(1));
    count = timer.GetCount().MilliSeconds();
    std::cout << "Test 3: " << count << std::endl;
    assert(count >= 3000 && count < 3100);

    timer.Start();
    std::this_thread::sleep_for(std::chrono::seconds(2));
    count = timer.GetCount().MilliSeconds();
    std::cout << "Test 4: " << count << std::endl;
    assert(count >= 5000);

    timer.Reset(true);
    std::this_thread::sleep_for(std::chrono::seconds(1));
    count = timer.GetCount().MilliSeconds();
    std::cout << "Test 5: " << count << std::endl;
    assert(count >= 1000 && count < 1100);

    std::this_thread::sleep_for(std::chrono::seconds(1));
    double res = timer.PauseGetCount().Seconds();
    std::cout << "Test 6: " << res << std::endl;
    assert(count >= 2.0);

    std::cout << "Test success." << std::endl;
    return 0;
}

Add new test for timer class


#include <string>
#include <iostream>

#include "Graph.hh"
#include "GraphInput.hh"

using namespace std;

template <typename V>
class RawTextGraphInput : public GraphInput<string, V> {
public:

  RawTextGraphInput(Graph<V>& g) : GraphInput<string, V>(g) {}

  void input(string path) {
    cout << "Fetching graph from file " << path << endl;
  }
};

Add a first choice for a GraphInput


// Flip a biased coin

#include <random>

int main()
{
	std::random_device random_device;
	std::mt19937 random_engine{random_device()};
	std::bernoulli_distribution coin_distribution{0.25};

	bool outcome = coin_distribution(random_engine);
}

// Generate a random boolean value according to a bernoulli
// distribution.
//
// The [`std::random_device`](cpp/numeric/random/random_device) on [7]
// provides a source of uniform non-deterministic random numbers
// (where such a source is available). We use this to seed the
// Mersenne Twister random number engine,
// [`std::mt19937`](cpp/numeric/random/mersenne_twister_engine), on
// [8]. Consider [other random number
// engines](http://en.cppreference.com/w/cpp/numeric/random#Predefined_random_number_generators)
// for different properties.
//
// On [9], we create a
// [`std::bernoulli_distribution`](cpp/numeric/random/bernoulli_distribution)
// representing a bernoulli distribution with a success probability of
// `0.25`. This can be thought of as a biased coin that will land on
// heads only a quarter of the time.
//
// Finally, we generate a random number from the random engine,
// distributed according to the bernoulli distribution ([11]).
// This gives us a boolean value that will be `true` with `0.25`
// probability and `false` otherwise.

Add "flip a biased coin" sample


// Copyright 2012, Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: tomasz.kaftal@gmail.com (Tomasz Kaftal)
//
// This file contains a custom googletest main method to launch tests.
// It launches the Supersonic initialisation routine.

#include <iostream>

#include "supersonic/base/infrastructure/init.h"
#include "gtest/gtest.h"

GTEST_API_ int main(int argc, char** argv) {
  std::cout << "Running main() from supersonic_test_main.cc\n";

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

// Copyright 2012, Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: tomasz.kaftal@gmail.com (Tomasz Kaftal)
//
// This file contains a custom googletest main method to launch tests.
// It launches the Supersonic initialisation routine.

#include <iostream>

#include "supersonic/base/infrastructure/init.h"
#include "gtest/gtest.h"

GTEST_API_ int main(int argc, char** argv) {
  std::cout << "Running main() from supersonic_test_main.cc\n";

  // Make sure to parse gtest_* flags before parsing other flags.
  testing::InitGoogleTest(&argc, argv);
  supersonic::SupersonicInit(&argc, &argv);
  return RUN_ALL_TESTS();
}

Make sure to parse gtest_* flags before other flags when running tests.


// 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 "chrome/browser/ui/proximity_auth/proximity_auth_error_bubble.h"

#include "base/logging.h"

#if !defined(TOOLKIT_VIEWS)
void ShowProximityAuthErrorBubble(const base::string16& message,
                                  const gfx::Range& link_range,
                                  const GURL& link_url,
                                  const gfx::Rect& anchor_rect,
                                  content::WebContents* web_contents) {
  NOTIMPLEMENTED();
}
#endif

// 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 "chrome/browser/ui/proximity_auth/proximity_auth_error_bubble.h"

#include "base/logging.h"

#if !defined(TOOLKIT_VIEWS) || !defined(USE_AURA)
void ShowProximityAuthErrorBubble(const base::string16& message,
                                  const gfx::Range& link_range,
                                  const GURL& link_url,
                                  const gfx::Rect& anchor_rect,
                                  content::WebContents* web_contents) {
  NOTIMPLEMENTED();
}
#endif

Fix compile regression after SmartLock error bubble in r313408


//===-- IsInf.cpp ---------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Platform-independent wrapper around C99 isinf().
//
//===----------------------------------------------------------------------===//

#include "Config/config.h"
#if HAVE_ISINF_IN_MATH_H
# include <math.h>
#elif HAVE_ISINF_IN_CMATH
# include <cmath>
#elif HAVE_STD_ISINF_IN_CMATH
# include <cmath>
using std::isinf;
#else
# error "Don't know how to get isinf()"
#endif

namespace llvm {

int IsInf (float f)  { return isinf (f); }
int IsInf (double d) { return isinf (d); }

}; // end namespace llvm;

Add platform-independent wrapper function for isinf(). Patch contributed by Bill Wendling.


#include <array>
#include <iostream>

template<typename T, std::size_t N>
typename std::enable_if<N < 128 && std::is_integral<T>::value, void>::type insertion_sort(std::array<T, N>& array) {
	for (std::size_t i = 0; i < N; i++) {
		for (std::size_t j = i; j > 0 && array[j] < array[j-1]; j--) {
			std::swap(array[j], array[j-1]);
		}
	}
}

int main() {
	std::array<int, 10> arr = { 2, 3, -1, 0, 12, -4, -9, 6, 7, 1 };
	insertion_sort(arr);
	for (std::size_t i = 0; i < arr.size(); i++) {
		std::cout << arr[i] << " ";
	}
	return 0;
}

Add template insertion sort implementation.


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

using namespace Halide;

int main(int argc, char **argv) {
    Func f, g;
    Var x, y;

    f(x) = x;
    f(x) += x;
    g(x) = f(x);

    // f is inlined, so this schedule is bad.
    f.vectorize(x, 4);

    g.realize(10);

    printf("There should have been an error\n");
    return 0;
}

Add error test for inlined stages


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if (!head)
            return nullptr;
        ListNode *fast = head, *slow = head, *dummy;
        while (fast && fast->next) {
            fast = fast->next->next;
            dummy = slow;
            slow = slow->next;
        }
        TreeNode *root = new TreeNode{slow->val};
        if (slow == head)
            return root;
        if (dummy)
            dummy->next = nullptr;
        root->left = sortedListToBST(head);
        root->right = sortedListToBST(slow->next);
        return root;
    }
};

Convert Sorted List to Binary Search Tree


// 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 "ios/web/public/web_state/credential.h"

namespace web {

Credential::Credential() = default;

Credential::~Credential() = default;

}  // namespace web

// 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 "ios/web/public/web_state/credential.h"

namespace web {

Credential::Credential() : type(CREDENTIAL_TYPE_EMPTY) {
}

Credential::~Credential() = default;

}  // namespace web

Initialize primitive member of web::Credential.


// Chapter 21, Exercise 4: implement count_if() yourself and test it

#include "../lib_files/std_lib_facilities.h"

//------------------------------------------------------------------------------

template<class In, class Pred>
int my_count_if(In first, In last, const Pred& p)
{
    int ctr = 0;
    while (first != last) {
        if (p(*first)) ++ctr;
        ++first;
    }
    return ctr;
}
//------------------------------------------------------------------------------

template<class T>
class Less_than {
    T val;
public:
    Less_than(T v) :val(v) { }
    bool operator()(const T& v) const { return v<val; }
};

//------------------------------------------------------------------------------

template<class T>
class Greater_than {
    T val;
public:
    Greater_than(T v) :val(v) { }
    bool operator()(const T& v) const { return v>val; }
};

//------------------------------------------------------------------------------

bool odd(int i) { return i%2 != 0; }

//------------------------------------------------------------------------------

int main()
try {
    vector<int> vi;
    for (int i = 0; i<10; ++i)
        vi.push_back(randint(10));
    cout << "vi:\n";
    for (vector<int>::iterator p = vi.begin(); p!=vi.end(); ++p)
        cout << *p << '\n';

    // Test Less_than function object
    cout << "Enter value for less than count, -1 to exit: ";
    int val;
    while (cin>>val) {
        if (val==-1) break;
        int ctr = my_count_if(vi.begin(),vi.end(),Less_than<int>(val));
        cout << "There " << (ctr==1 ? "is " : "are ") << ctr << " value"
            << (ctr==1 ? " " : "s ") << "less than " << val << " in vi.\n"
            << "Next value: ";
    }

    // Test Greater_than function object
    cout << "Enter value for greater than count, -1 to exit: ";
    while (cin>>val) {
        if (val==-1) break;
        int ctr = my_count_if(vi.begin(),vi.end(),Greater_than<int>(val));
        cout << "There " << (ctr==1 ? "is " : "are ") << ctr << " value"
            << (ctr==1 ? " " : "s ") << "greater than " << val << " in vi.\n"
            << "Next value: ";
    }

    // Test odd() function
    int ctr = my_count_if(vi.begin(),vi.end(),odd);
    cout << "There are " << ctr << " odd values in vi.\n";
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

//------------------------------------------------------------------------------

Add Chapter 21, exercise 4


#include <iostream>
#include <vector>
#include <assert.h>
using namespace std;

class ImageDithering {
public:
  int count(string dithered, vector<string> screen) {
    unsigned d[26];
    for (int i = 0; i < 26; i++) {
      d[i] = 0;
    }
    for (unsigned i = 0; i < dithered.length(); i++) {
      d[dithered[i] - '0'] = 1;
    }
    int count = 0;

    for (vector<string>::iterator str = screen.begin(); str != screen.end(); ++str) {
      for (unsigned i = 0; i < str->length(); i++) {
        count += d[(*str)[i] - '0'];
      }
    }

    return count;
  }
};

int main()
{
  ImageDithering id;
  string sc[] = {
    "AAAAAAAA",
    "ABWBWBWA",
    "AWBWBWBA",
    "ABWBWBWA",
    "AWBWBWBA",
    "AAAAAAAA"
  };
  vector<string> scr1(sc, sc + 6);
  assert( id.count("BW", scr1) == 24);

  return 0;
}

Solve SRM 144, Div 2, Problem ImageDithering


#include "testHooks.h"
#include "math/Algebra.h"

/**
     * Built from a cubic function (a*x^3 + b*x^2 + c*x + d) defined at
     * f(-1) = 0
     * f( 1) = 1
     * f( 0) = hoverPoint
     * with the last degree of freedom setting the x^3 vs x balance
     *     which corresponds to how "linear" the curve is
     */

bool testNoThrottle(){
    ThrottleCurve curves[] = {
        ThrottleCurve(0.5, 0.5),
        ThrottleCurve(0.2, 0.5),
        ThrottleCurve(0.5, 0.2),
        ThrottleCurve(0.8, 0.5),
        ThrottleCurve(0.5, 0.8),
    };
    FPASSERT(curves[0].get(0.0), 0.0);
    FPASSERT(curves[1].get(0.0), 0.0);
    FPASSERT(curves[2].get(0.0), 0.0);
    FPASSERT(curves[3].get(0.0), 0.0);
    FPASSERT(curves[4].get(0.0), 0.0);
}

bool testFullThrottle(){
    ThrottleCurve curves[] = {
        ThrottleCurve(0.5, 0.5),
        ThrottleCurve(0.2, 0.5),
        ThrottleCurve(0.5, 0.2),
        ThrottleCurve(0.8, 0.5),
        ThrottleCurve(0.5, 0.8),
    };
    FPASSERT(curves[0].get(1.0), 1.0);
    FPASSERT(curves[1].get(1.0), 1.0);
    FPASSERT(curves[2].get(1.0), 1.0);
    FPASSERT(curves[3].get(1.0), 1.0);
    FPASSERT(curves[4].get(1.0), 1.0);
}

bool testHoverPoint(){
    ThrottleCurve curves[] = {
        ThrottleCurve(0.5, 0.5),
        ThrottleCurve(0.2, 0.5),
        ThrottleCurve(0.5, 0.2),
        ThrottleCurve(0.8, 0.5),
        ThrottleCurve(0.5, 0.8),
    };
    FPASSERT(curves[0].get(0.5), 0.5);
    FPASSERT(curves[1].get(0.5), 0.5);
    FPASSERT(curves[2].get(0.5), 0.2);
    FPASSERT(curves[3].get(0.5), 0.5);
    FPASSERT(curves[4].get(0.5), 0.8);
}

void benchmarkCalculate(){
    volatile float x = 0.1777;
    x = ThrottleCurve(0.25, 0.4).get(x);
}

int main(void){
    TEST(testNoThrottle);
    TEST(testFullThrottle);
    TEST(testHoverPoint);
    BENCHMARK(benchmarkCalculate);
    return 0;
}

Implement tests and benchmarks for throttleCurve


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

#include "SkTypes.h"

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

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

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

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

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

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

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

Add a new SkMemory implementation that uses mozalloc instead of malloc


#include <iterator>

#define foreach (x,v) for (typeof(v).begin() x=(v).begin(); x!=(v).end(); ++x)

using namespace std;

int main(){

    return 0;
}

Implement good macro for iterate over an array.


/// \file dijkstra.cpp
///
/// Unit tests for the Dijkstra algorithm
///

#include <iostream>
#include <string>
#include "../algorithms/dijkstra.hpp"
#include "../handle.hpp"
#include "catch.hpp"

#include <sglib/hash_graph.hpp>

namespace vg {
namespace unittest {
using namespace std;

using sglib::HashGraph;

TEST_CASE("Dijkstra search handles early stopping correctly", "[dijkstra][algorithms]") {

    HashGraph graph;

    handle_t start = graph.create_handle("GAT");
    handle_t middle = graph.create_handle("TA");
    handle_t snp1 = graph.create_handle("C");
    handle_t snp2 = graph.create_handle("T");
    handle_t end = graph.create_handle("A");

    graph.create_edge(start, middle);
    graph.create_edge(middle, snp1);
    graph.create_edge(middle, snp2);
    graph.create_edge(snp1, end);
    graph.create_edge(snp2, end);

    // Track what we reach and at what distance
    unordered_map<handle_t, size_t> seen;

    SECTION("Does not hit all handles at a given distance when told to stop at one") {

        algorithms::dijkstra(&graph, start, [&](const handle_t& reached, size_t distance) {
            seen[reached] = distance;
            if (reached == snp1 || reached == snp2) {
                // Stop at either branch of the SNP
                return false;
            }
            return true;
        });

        // The handles up to the SNP and one branch of the SNP should be captured.
        REQUIRE(seen.size() == 3);
        REQUIRE(seen.count(start));
        REQUIRE(seen.count(middle));
        REQUIRE(seen.count(snp1) != seen.count(snp2));
        REQUIRE(!seen.count(end));

        // The distance calculation should be from the end of the start handle
        REQUIRE(seen.at(middle) == 0);

    }

    SECTION("Does hit all handles at a given distance when told to stop after") {

        algorithms::dijkstra(&graph, start, [&](const handle_t& reached, size_t distance) {
            if (distance > 2) {
                // Stop after the SNP
                return false;
            }
            seen[reached] = distance;
            return true;
        });

        // The handles up to the SNP and one branch of the SNP should be captured.
        REQUIRE(seen.size() == 4);
        REQUIRE(seen.count(start));
        REQUIRE(seen.count(middle));
        REQUIRE(seen.count(snp1));
        REQUIRE(seen.count(snp2));
        REQUIRE(!seen.count(end));

        // The distance calculation should be from the end of the start handle
        REQUIRE(seen.at(snp1) == 2);
        REQUIRE(seen.at(snp2) == 2);

    }

}

}
}

Add some tests for Dijkstra search


#include <iostream>
#include <stdexcept>
#include <string_view>

void* operator new(std::size_t n) {
	std::cout << "new() " << n << " bytes\n";
	return malloc(n);
}

int main() {
	std::string_view str_view("abcdef");

	try {
		for (std::size_t i = 0; true; i++) {
			std::cout << i << ": " << str_view.at(i) << '\n';
		}
	} catch (const std::out_of_range& e) {
		std::cout << "Whooops. Index is out of range.\n";
		std::cout << e.what() << '\n';
	}

	return 0;
}

Add string_view c++17 feature example. Compile with -std=c++17 flags.


// RUN: %clang -emit-llvm -g -S %s -o - | FileCheck %s
// Radar 9239104
class Class
{
public:
//CHECK: DW_TAG_const_type
    int foo (int p) const {
        return p+m_int;
    }

protected:
    int m_int;
};

Class c;

Add a test case for r128957. It fixed a bug!


/*
 *
 * Example of dumping a map, containing values which are phmap maps or sets
 * building this requires c++17 support
 *
 */

#include <iostream>
#include <parallel_hashmap/phmap_dump.h>

template <class K, class V>
class MyMap : public phmap::flat_hash_map<K, phmap::flat_hash_set<V>>
{
public:
    using Set = phmap::flat_hash_set<V>;

    void dump(const std::string &filename)
    {
        phmap::BinaryOutputArchive ar_out (filename.c_str());

        ar_out.dump(this->size());
        for (auto& [k, v] : *this)
        {
            ar_out.dump(k);
            v.dump(ar_out);
        }
    }

    void load(const std::string & filename)
    {
        phmap::BinaryInputArchive ar_in(filename.c_str());

        size_t size;
        ar_in.load(&size);
        this->reserve(size);

        while (size--)
        {
            K k;
            Set v;

            ar_in.load(&k);
            v.load(ar_in);

            this->insert_or_assign(std::move(k), std::move(v));
        }
    }

    void insert(K k, V v)
    {
        Set &set = (*this)[k];
        set.insert(v);
    }

    friend std::ostream& operator<<(std::ostream& os, const MyMap& map)
    {
        for (const auto& [k, m] : map)
        {
            os << k << ": [";
            for (const auto& x : m)
                os << x << ", ";
            os << "]\n";
        }
        return os;
    }
};

int main()
{
    MyMap<size_t, size_t> m;
    m.insert(1, 5);
    m.insert(1, 8);
    m.insert(2, 3);
    m.insert(1, 15);
    m.insert(1, 27);
    m.insert(2, 10);
    m.insert(2, 13);

    std::cout << m << "\n";

    m.dump("test_archive");
    m.clear();
    m.load("test_archive");

    std::cout << m << "\n";

    return 0;
}

Add example demonstrating saving nested hashmaps to binary file.


// Chapter 25, Try This 1: demonstrate free store fragmentation... not much
// to be seen here!

#include<iostream>

using namespace std;

// type that requires a little more space than a Node
struct Message {
    int a;
    int b;
    int c;
};

// somewhat smaller type, but not half as small as a Message
struct Node {
    int a;
    int b;
};

void frag()
{
    Message* p = new Message();
    Node* n1 = new Node();
    delete p;
    Node* n2 = new Node();
    Message* pp = 0;
    Node* nn1 = 0;
    Node* nn2 = 0;
    for (int i = 0; i<100; ++i) {
        pp = new Message();
        nn1 = new Node();
        delete pp;
        nn2 = new Node();
    }
    cout << "Difference with fragmentation: " << nn2-n1 << '\n';
}

void non_frag()
{
    Node* n1 = new Node();
    Node* n2 = new Node();
    Message* p = new Message();
    delete p;
    Message* pp = 0;
    Node* nn1 = 0;
    Node* nn2 = 0;
    for (int i = 0; i<100; ++i) {
        nn1 = new Node();
        nn2 = new Node();
        pp = new Message();
        delete pp;
    }
    cout << "Difference without fragmentation: " << nn2-n1 << '\n';
}

int main()
{
    cout << "sizeof(Message): " << sizeof(Message) << '\n';
    cout << "sizeof(Node): " << sizeof(Node) << '\n';
    frag();
    non_frag();
}

Add Chapter 25, Try This 1


///////////////////////////////////////
/// file: postexpr.cpp
/// 计算后缀表达式
///////////////////////////////////////

#include <iostream>
#include "sqstack.h"
using namespace std;

///
/// 执行计算
///
int Operate(int a, char theta, int b)
{
    switch(theta) {
    case '+': return a+b;
    case '-': return a-b;
    case '*': return a*b;
    case '/': return a/b;
    }
    throw "Unknown operator";
}

/// 读取运算符或操作数，分别返回 OPERATOR 或 OPERAND
/// op 返回运算符，num 返回操作数
enum {OPERATOR,OPERAND};
int Read(char& op, int& num)
{
    char c = cin.peek();  // 查看输入流中的下一个字符
    while(isspace(c)) { cin.ignore(1); c = cin.peek(); } // 跳过空白
    if(c>='0' && c<='9') {  // 数字开头即为操作数
        cin >> num; // 读取操作数
        return OPERAND;
    } else {  // 非数字即为运算符
        cin >> op;  // 读取运算符
        return OPERATOR;
    }
}

///
/// 计算后缀表达式
///
int EvaluatePostfixExpression()
{
    SqStack<int> S;
    char c;
    bool isop;
    char op;
    int num;
    // 初始化操作数栈
    InitStack(S);
    // 读取一个运算符 op 或操作数 num
    isop = Read(op, num);
    while(isop==OPERAND || op!='=') {
        // 处理运算符或操作数
        if(isop==OPERAND) { // 遇到操作数直接入栈
            Push(S,num);
        } else { // 遇到运算符执行运算，结果入栈
            int a,b;
            Pop(S,b);
            Pop(S,a);
            Push(S,Operate(a,op,b));
        }
        // 继续读取运算符或操作数
        isop = Read(op, num);
    }

    // 返回计算结果
    int result;
    Pop(S,result);
    return result;
}

/// 输入后缀表达式（支持+-*/，以等号=结尾），计算并输出结果
/// 如 1+2*3+(4*5+6)*7 对于的后缀表达式为：
/// 1 2 3 * + 4 5 * 6 + 7 * + =
/// 正确结果 189
int main()
{
    cout << "Input a postfix expression (support +-*/ and end with =)" << endl;
    int result = EvaluatePostfixExpression();
    cout << result << endl;

    return 0;
}

Add evaluation for postfix expression


// RUN: %clang -cc1 -std=c++11 -verify %s

// Error cases.

[[gnu::this_attribute_does_not_exist]] int unknown_attr;
// expected-warning@-1 {{unknown attribute 'this_attribute_does_not_exist' ignored}}
int [[gnu::unused]] attr_on_type;
// expected-warning@-1 {{attribute 'unused' ignored, because it is not attached to a declaration}}
int *[[gnu::unused]] attr_on_ptr;
// expected-warning@-1 {{attribute 'unused' ignored, because it cannot be applied to a type}}

// Valid cases.

void alias1() {}
void alias2 [[gnu::alias("_Z6alias1v")]] ();

[[gnu::aligned(8)]] int aligned;
void aligned_fn [[gnu::aligned(32)]] ();
struct [[gnu::aligned(8)]] aligned_struct {};

[[gnu::malloc, gnu::alloc_size(1,2)]] void *alloc_size(int a, int b);

void always_inline [[gnu::always_inline]] ();

__thread int tls_model [[gnu::tls_model("local-exec")]];

void cleanup(int *p) {
  int n [[gnu::cleanup(cleanup)]];
}

void deprecated1 [[gnu::deprecated]] (); // expected-note {{here}}
[[gnu::deprecated("custom message")]] void deprecated2(); // expected-note {{here}}
void deprecated3() {
  deprecated1(); // expected-warning {{deprecated}}
  deprecated2(); // expected-warning {{custom message}}
}

[[gnu::naked(1,2,3)]] void naked(); // expected-error {{takes no arguments}}

void nonnull [[gnu::nonnull]] (); // expected-warning {{applied to function with no pointer arguments}}

int noreturn [[gnu::noreturn]]; // expected-warning {{'noreturn' only applies to function types}}

struct [[gnu::packed]] packed { char c; int n; };
static_assert(sizeof(packed) == sizeof(char) + sizeof(int), "not packed");

Add extra tests for [[gnu::...]] attributes, missed from r172382.


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteMiddle(ListNode* head) {
        ListNode* dummy;
        // dummy->next = head;
        ListNode* fast = head;
        ListNode* slow = head;
        while (fast && fast->next) {
            fast = fast->next->next;
            dummy = slow;
            slow = slow->next;
        }
        if (head == slow)
            return nullptr;
        dummy->next = slow->next;
        slow->next = nullptr;
        return head;
    }
};

Delete the Middle Node of a Linked List


/*
 * Copyright (C) 2004-2011  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include <Python.h>

void fail(PyObject* py, int n) {
	// Doesn't clear any variables, but meh, finalize anyway...
	if (!py) {
		PyErr_Print();
		Py_Finalize();
		exit(n);
	}
}

int main(int argc, char** argv) {
	// Don't use this as an example: this has awful memory leaks.
	Py_Initialize();

	PyObject* pyModule = PyImport_ImportModule("py_compile");
	fail(pyModule, 1);

	PyObject* pyFunc = PyObject_GetAttrString(pyModule, "compile");
	fail(pyFunc, 2);

	PyObject* pyKW = Py_BuildValue("{sssN}", "cfile", argv[2], "doraise", Py_True);
	fail(pyKW, 3);

	PyObject* pyArg = Py_BuildValue("(s)", argv[1]);
	fail(pyArg, 4);

	PyObject* pyRes = PyObject_Call(pyFunc, pyArg, pyKW);
	fail(pyRes, 5);

	Py_Finalize();
	return 0;
}

/*
 * Copyright (C) 2004-2011  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include <Python.h>
#include <string>

void fail(PyObject* py, int n) {
	// Doesn't clear any variables, but meh, finalize anyway...
	if (!py) {
		PyErr_Print();
		Py_Finalize();
		exit(n);
	}
}

int main(int argc, char** argv) {
	// Don't use this as an example: this has awful memory leaks.
	Py_Initialize();

	PyObject* pyModule = PyImport_ImportModule("py_compile");
	fail(pyModule, 1);

	PyObject* pyFunc = PyObject_GetAttrString(pyModule, "compile");
	fail(pyFunc, 2);

	std::string cfile = argv[2];
	if (cfile.find('/') == std::string::npos) {
		cfile = "./" + cfile;
	}
	PyObject* pyKW = Py_BuildValue("{sssN}", "cfile", cfile.c_str(), "doraise", Py_True);
	fail(pyKW, 3);

	PyObject* pyArg = Py_BuildValue("(s)", argv[1]);
	fail(pyArg, 4);

	PyObject* pyRes = PyObject_Call(pyFunc, pyArg, pyKW);
	fail(pyRes, 5);

	Py_Finalize();
	return 0;
}

Support compiling python modules in cwd


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

#include "../Fuzz.h"

void fuzz_PathMeasure(Fuzz* f);

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
    auto fuzz = Fuzz(SkData::MakeWithoutCopy(data, size));
    fuzz_PathMeasure(&fuzz);
    return 0;
}

Add oss-fuzz endpoint for PathMeasure


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

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

#include <stdio.h>

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

Add a test that uses coverage and printf from a DLL


#include <cmath>
#include <ctime>
#include <iostream>
#include <vector>

using namespace std;

vector<long int> primes;

void InitVector(long int s) {
	primes.reserve(s/10);
	primes.push_back(2);
}

int main(int argc, char const *argv[]) {
	clock_t begin = clock();

	auto max = 10000000;
	auto lprime = 2;
	auto b = 1;
	auto c = 0;
	auto square = 1;
	auto is_prime = true;

	InitVector(max);

	auto primes_s = primes.size();

	for (long int i = 3; i < max; i += 2) {
		is_prime = true;
//		b = static_cast<int>(sqrt(i));
		for (auto j = 0; b >= primes[j] && is_prime; ++j) {
			if (i % primes[j] == 0) {
				is_prime = false;
			}
		}
		if (is_prime) {
			primes.push_back(i);
			lprime = i;
		}
		if (i > square) {
			c++;
			square = square + 1 + 2 * c;
			b++;
		}
	}

	clock_t end = clock();
    double elapsed_secs = double(end - begin)/CLOCKS_PER_SEC;
    cout << "Seconds: " << elapsed_secs << endl;

	cout << "Latest prime: " << lprime << endl;
	cout << "Number of primes: " << primes.size() << endl;
	cout << "Primes pr. sec: " << primes.size() / elapsed_secs << endl;
	return 0;
}

Use addition and multiplication rather than sqrt. Not much to gain.


#include <iostream>
#include <cmath>

using namespace std;

struct Point2D {
  double x;
  double y;
};

Point2D translate(Point2D point, double dx, double dy) {
  Point2D translated;

  translated.x = point.x + dx;
  translated.y = point.y + dy;

  return translated;
}

double distanceBetween(Point2D firstPoint, Point2D secondPoint) {
  return sqrt(pow(firstPoint.x - secondPoint.x, 2) +
              pow(firstPoint.y - secondPoint.y, 2));
}

void printPoint(Point2D point) {
  cout << '(' << point.x << ", " << point.y << ')' << '\n';
}

void testTranslate() {
  Point2D point;
  point.x = 3;
  point.y = 5;

  Point2D translated = translate(point, 2, 3);
  printPoint(translated);
}

void testDistanceBetween() {
  Point2D firstPoint;
  firstPoint.x = 3;
  firstPoint.y = 5;

  Point2D secondPoint;
  secondPoint.x = 4;
  secondPoint.y = 1;

  cout << distanceBetween(firstPoint, secondPoint) << '\n';
}

int main() {
  testTranslate();
  testDistanceBetween();

  return 0;
}

Add solution to first part of first problem. 2D point structure with outer functions.


#include <bits/stdc++.h>
#include <stdio.h>
#include <string.h>
using namespace std;

int lps(char *str)
{
    int n = strlen(str);
    int dp[n][n]; // Create a table to store results of subproblems

    // Strings of length 1 are palindrome of length 1
    for (int i = 0; i < n; i++)
        dp[i][i] = 1;

    // Build the table. Note that the lower diagonal values of table are
    // useless and not filled in the process.
    for (int cl = 2; cl <= n; cl++)
    {
        for (int i = 0; i < n - cl + 1; i++)
        {
            int j = i + cl - 1;
            if (str[i] == str[j] && cl == 2)
                dp[i][j] = 2;
            else if (str[i] == str[j])
                dp[i][j] = dp[i + 1][j - 1] + 2;
            else
                dp[i][j] = max(dp[i][j - 1], dp[i + 1][j]);
        }
    }
    return dp[0][n - 1];
}

int main()
{
    char seq[] = "BABCBAB";
    int n = strlen(seq);
    printf("The length of the LPS is %d", lps(seq));
    return 0;
}

Add Longest Palindrome Subsequence in DP


#include <stdio.h>
#include "Halide.h"
#include <fstream>
#include <cassert>
#include <iostream>

#include "test/common/halide_test_dirs.h"

using namespace Halide;

int main(int argc, char **argv) {
    Var x("x"), y("y");
    Func f("f");

    f(x, y) = 42;

    std::string bitcode_file = Internal::get_test_tmp_dir() + "extern.bc";
    f.compile_to_bitcode(bitcode_file, {}, "extern");

    std::vector<uint8_t> bitcode;
    std::ifstream bitcode_stream(bitcode_file, std::ios::in | std::ios::binary);
    bitcode_stream.seekg(0, std::ios::end);
    bitcode.resize(bitcode_stream.tellg());
    bitcode_stream.seekg(0, std::ios::beg);
    bitcode_stream.read(reinterpret_cast<char *>(&bitcode[0]), bitcode.size());

    ExternalCode external_code = ExternalCode::bitcode_wrapper(get_target_from_environment(), bitcode, "extern");

    Func f_extern;
    f_extern.define_extern("extern", { }, type_of<int32_t>(), 2);

    Func result;
    result(x, y) = f_extern(x, y);

    Module module = result.compile_to_module({}, "forty_two");

    module.append(external_code);

    auto forty_two = module.get_function_by_name("forty_two");

    Internal::JITModule jit_module(module, forty_two, {});

    auto argv_wrapper = jit_module.argv_function();

    Buffer<int32_t> buf(16, 16);
    const void *args[1];
    args[0] = buf.raw_buffer();

    int ret_code = argv_wrapper(args);

    assert(ret_code == 0);
    for (int i = 0; i < 16; i++) {
        for (int j = 0; j < 16; j++) {
            assert(buf(i, j) == 42);
        }
    }

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

Add a test for ExternalCode functionality.


/**
 * 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* deleteNode(TreeNode* root, int key) {
        if(!root) return NULL;
        if(root->val==key){
            if(!root->right){
                TreeNode* ret=root->left;
                delete root;
                return ret;
            }else{
                TreeNode* right=root->right;
                while(right->left) right=right->left;
                swap(root->val,right->val);
            }
        }
        root->left=deleteNode(root->left,key);
        root->right=deleteNode(root->right,key);
        return root;
    }
};

Delete Node in a BST


#include <iostream>
#include <string>
#include <stack>
using namespace std;

struct ExpressionTree {
	char expr;
	ExpressionTree *left, *right;
	ExpressionTree(char opr) : expr(opr) {
		left = NULL;
		right = NULL;
	}
};

bool isOperator(char opr) {
	return opr == '+' || opr == '-' || opr == '*'
	|| opr == '/' || opr == '%' || opr == '^';
}

void inOrder(ExpressionTree *node) {
    if (!node) return;
	inOrder(node->left);
	cout<<node->expr<<" ";
	inOrder(node->right);
}

ExpressionTree* buildTree(string postfix) {
	stack<ExpressionTree*> s;
	ExpressionTree *node, *t1, *t2;
	for (int i = 0; i < postfix.size(); i++) {
		if (!isOperator(postfix[i])) {
			s.push(new ExpressionTree(postfix[i]));
		} else {
			node = new ExpressionTree(postfix[i]);
			node->right = s.top();
			s.pop();
			node->left = s.top();
			s.pop();
			s.push(node);
		}
	}
	ExpressionTree *result = s.top();
	s.pop();
	return result;
}

int main() {
	string postfix = "ab+ef*g*-";
	ExpressionTree *expressionTree = buildTree(postfix);
	inOrder(expressionTree);

	return 0;
}

Implement Expression tree to convert post fix expression in to an expression tree


// 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 "sky/compositor/opacity_layer.h"

namespace sky {
namespace compositor {

OpacityLayer::OpacityLayer() {
}

OpacityLayer::~OpacityLayer() {
}

void OpacityLayer::Paint(PaintContext::ScopedFrame& frame) {
  SkColor color = SkColorSetARGB(alpha_, 0, 0, 0);
  RefPtr<SkColorFilter> colorFilter = adoptRef(
      SkColorFilter::CreateModeFilter(color, SkXfermode::kSrcOver_Mode));
  SkPaint paint;
  paint.setColorFilter(colorFilter.get());
  SkCanvas& canvas = frame.canvas();
  canvas.saveLayer(has_paint_bounds() ? &paint_bounds() : nullptr, &paint);
  PaintChildren(frame);
  canvas.restore();
}

}  // namespace compositor
}  // namespace sky

// 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 "sky/compositor/opacity_layer.h"

namespace sky {
namespace compositor {

OpacityLayer::OpacityLayer() {
}

OpacityLayer::~OpacityLayer() {
}

void OpacityLayer::Paint(PaintContext::ScopedFrame& frame) {
  SkPaint paint;
  paint.setColor(SkColorSetARGB(alpha_, 0, 0, 0));
  paint.setXfermodeMode(SkXfermode::kSrcOver_Mode);
  SkCanvas& canvas = frame.canvas();
  canvas.saveLayer(has_paint_bounds() ? &paint_bounds() : nullptr, &paint);
  PaintChildren(frame);
  canvas.restore();
}

}  // namespace compositor
}  // namespace sky

Fix OpacityLayer to blend in the correct direction


#include <iostream>

int sum_of_multiples(int n){
    int sum = 0;
    for(int i=3;i<n;i++){
        if((i%3==0) || (i%5==0))
            sum+=i;
    }
    return sum;
}

int main(){
    std::cout << sum_of_multiples(1000);
}

Add C++ solution to multiples of 3 and 5 problem.


// 4.1 - determine if a binary tree is balanced, where "balanced" is defined as
// "the subtrees of each node have a height differnce of no more than 1"

// improve to have less calls to height(): have height() return -1 if the Node
// it is called for is not balanced; it knows because it checks the heights of
// both subtrees. If the recursive call to either child node returns -1, it
// immediately returns -1; if the height difference is > 1, it returns -1; if
// both subtrees are balanced and have a smaller height difference, it returns
// the actual height

#include<iostream>
#include<algorithm>
#include<cstdlib>

using namespace std;

struct Node {
    Node() :left(0), right(0) { }
    Node* left;
    Node* right;
};

int height(Node* n)
{
    if (!n) return 0;   // leaf
    return max(height(n->left),height(n->right)) + 1;
}

bool is_balanced(Node* n)
{
    if (!n) return true;    // leaf
    if (abs(height(n->left)-height(n->right)) > 1) return false;
    return is_balanced(n->left) && is_balanced(n->right);
}

int main()
{
    Node* n21 = new Node();
    Node* n22 = new Node();
    Node* n11 = new Node();
    n11->left = n21;
    n11->right = n22;
    Node* n01 = new Node();
    n01->left = n11;
    cout << "Root balanced: " << is_balanced(n01) << '\n';
    cout << "Left subtree balanced: " << is_balanced(n11) << '\n';
}

Add Chapter 4, exercise 1 (solution in O(N log N)


/*
Objective: Given a string, compute recursively a new string where all appearances of "pi" have been replaced by "3.14".
Time Complexity: O(N)
Space Complexity: O(N)
*/
#include <iostream>
using namespace std;
#include <iostream>

using namespace std;

#include <bits/stdc++.h>

void help(char input[], int size)
{
    if(size==0) //base case
        return;
    if(input[0]=='p')
    {
        if(input[1]=='i')
        {
            for(int i=size;i>1;i--)
            {
                input[i+2]=input[i];
            }
            input[0]='3';
            input[1]='.';
            input[2]='1';
            input[3]='4';
            size =size +2;

        }
    }

    help(input+1,size-1);//recursive call
}
int main() {
    char input[10000];
    cin.getline(input, 10000);
    replacePi(input);
    cout << input << endl;
}\

Replace occurrences of "pi" with "3.14"


#include <gtest/gtest.h>

#include "std2_type_traits.hpp"

namespace {
struct NothrowMoveConstructible {
   NothrowMoveConstructible(NothrowMoveConstructible&&) noexcept = default;
};

struct ThrowMoveConstructible {
   ThrowMoveConstructible(ThrowMoveConstructible&&) {};
};

struct NothrowMoveAssignable {
   NothrowMoveAssignable& operator=(NothrowMoveAssignable&&) noexcept {
      return *this;
   }
};

struct ThrowMoveAssignable {
   ThrowMoveAssignable& operator=(ThrowMoveAssignable&&) {
      return *this;
   }
};
} // namespace

TEST(TestOfStdTypeTraits, CompileTimeCheckForNothrowMoveConstructible) {
   static_assert(std2::is_nothrow_move_constructible_v<NothrowMoveConstructible>,
      "NothrowMoveConstructible has no throwing move constructor");
   static_assert(std2::is_nothrow_move_constructible_v<ThrowMoveConstructible> == false,
      "ThrowMoveConstructible has throwing move constructor");
}

TEST(TestOfStdTypeTraits, CompileTimeCheckForNothrowMoveAssignable) {
   static_assert(std2::is_nothrow_move_assignable_v<NothrowMoveAssignable>,
      "NothrowMoveAssignable has no throwing move assignment operator");
   static_assert(std2::is_nothrow_move_assignable_v<ThrowMoveAssignable> == false,
      "ThrowMoveAssignable has throwing move assignment operator");
}

Add std2 type traits tests


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

// std includes
#include <iostream>

// CMOH includes
#include <cmoh/attribute.hpp>
#include <cmoh/accessor_bundle.hpp>

// local includes
#include "person.hpp"

// At first, we declare attributes we want to access. This may be done in a
// separate header. Note that the age of a person cannot be set.
using name = cmoh::attribute<std::string>;
using age = cmoh::attribute<const unsigned int>;

int main(int argc, char* argv[]) {
    // From the attributes we pull accessors for a concrete C++ type and bundle
    // them in an accessor bundle.
    auto accessors = bundle(
        name::binding<person>::methods<&person::name, &person::set_name>(),
        age::binding<person>::methods<&person::age>()
    );

    person p;
    p.set_name("Hans");
    p.set_age(54);

    // We can read attributes from a real class via the accessor bundle
    std::cout << "Name: " << accessors.get<name>(p) << std::endl;
    std::cout << "Age: " << accessors.get<age>(p) << std::endl;

    // We can also set the attributes via the bundle
    std::cout << "Setting name..." << std::endl;
    accessors.set<name>(p, "Hans Wurst");

    // Re-read the attributes to demonstrate they have indeed changed
    std::cout << "Name: " << accessors.get<name>(p) << std::endl;
    std::cout << "Age: " << accessors.get<age>(p) << std::endl;

    return 0;
}

Add basic example demonstrating access of attributes


// 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 "ui/ozone/public/gpu_platform_support.h"

#include "base/logging.h"
#include "ui/ozone/ozone_export.h"

namespace ui {

namespace {

// No-op implementation of GpuPlatformSupport.
class StubGpuPlatformSupport : public GpuPlatformSupport {
 public:
  // GpuPlatformSupport:
  virtual void OnChannelEstablished(IPC::Sender* sender) {}
  bool OnMessageReceived(const IPC::Message&) OVERRIDE { return false; }
};

}  // namespace

GpuPlatformSupport::GpuPlatformSupport() {
}

GpuPlatformSupport::~GpuPlatformSupport() {
}

GpuPlatformSupport* CreateStubGpuPlatformSupport() {
  return new StubGpuPlatformSupport;
}

}  // namespace ui

// 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 "ui/ozone/public/gpu_platform_support.h"

#include "base/logging.h"
#include "ui/ozone/ozone_export.h"

namespace ui {

namespace {

// No-op implementation of GpuPlatformSupport.
class StubGpuPlatformSupport : public GpuPlatformSupport {
 public:
  // GpuPlatformSupport:
  virtual void OnChannelEstablished(IPC::Sender* sender) OVERRIDE {}
  virtual bool OnMessageReceived(const IPC::Message&) OVERRIDE { return false; }
};

}  // namespace

GpuPlatformSupport::GpuPlatformSupport() {
}

GpuPlatformSupport::~GpuPlatformSupport() {
}

GpuPlatformSupport* CreateStubGpuPlatformSupport() {
  return new StubGpuPlatformSupport;
}

}  // namespace ui

Fix Ozone clang build errors


#include <iostream>
#include <gflags/gflags.h>

DEFINE_string(message, "Hello World!", "The message to print");

int main(int argc, char **argv)
{
  gflags::SetUsageMessage("Test CMake configuration of gflags library (gflags-config.cmake)");
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  std::cout << FLAGS_message << std::endl;
  gflags::ShutDownCommandLineFlags();
  return 0;
}

#include <iostream>
#include <gflags/gflags.h>

DEFINE_string(message, "Hello World!", "The message to print");

static bool ValidateMessage(const char* flagname, const std::string &message)
{
  return !message.empty();
}
DEFINE_validator(message, ValidateMessage);

int main(int argc, char **argv)
{
  gflags::SetUsageMessage("Test CMake configuration of gflags library (gflags-config.cmake)");
  gflags::SetVersionString("0.1");
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  std::cout << FLAGS_message << std::endl;
  gflags::ShutDownCommandLineFlags();
  return 0;
}

Add usage of DEFINE_validator to test project


// Make sure LIBCMT doesn't accidentally get added to the list of DEFAULTLIB
// directives.  REQUIRES: asan-dynamic-runtime
// RUN: %clang_cl_asan -LD %s | FileCheck %s
// CHECK: Creating library
// CHECK-NOT: LIBCMT

void foo(int *p) { *p = 42; }

__declspec(dllexport) void bar() {
  int x;
  foo(&x);
}

Add a test case for r216663 [-Zl vs LIBCMT vs asan_win_uar_thunk]


#include <iostream>
#include <random>
#include <string>

using namespace std;

bool play(bool first) {
    static default_random_engine e;
    static bernoulli_distribution b;
    return b(e);
}

int main() {
    string resp;
    static default_random_engine e;
    static bernoulli_distribution b;
    do {
        bool first = b(e);
        cout << first << endl;
        cout << (first ? "We go first"
                 : "You get to go first") << endl;
        cout << (play(first) ? "Sorry, you lost"
                 : "Congrats, you won") << endl;
        cout << "Play again? Enter 'yes' or 'no'" << endl;
    } while(cin >> resp && resp[0] == 'y');
    return 0;
}

Add solution for chapter 17 test 31, test 32


double gss(double l, double r) {
    double m1 = r-(r-l)/gr, m2 = l+(r-l)/gr;
    double f1 = f(m1), f2 = f(m2);
    while(fabs(l-r)>EPS) {
        if(f1>f2) l=m1, f1=f2, m1=m2, m2=l+(r-l)/gr, f2=f(m2);
        else r=m2, f2=f1, m2=m1, m1=r-(r-l)/gr, f1=f(m1);
    }
    return l;
}

Add Golden Section Search (Ternary Search)


#include "path_aggregation_test.hpp"

INSTANTIATE_TEST_CASE_P(PathAggregationTest, PathAggregationTest, testing::Combine(
	testing::Values(0, 1, 10),
	testing::Values(10, 20),
	testing::Values(120, 40)
));

Add file which defines test case


class Trie{
public:
    vector<Trie*> children;
    bool wholeWord;
    Trie(){
        children = vector<Trie*>(26, NULL);
        wholeWord = false;
    }
};

class WordDictionary {
private:
    Trie* root;
public:
    WordDictionary(){
        root = new Trie();
    }
    // Adds a word into the data structure.
    void addWord(string word) {
        Trie* p = root;
        for(char c : word){
            int idx = c - 'a';
            if(p->children[idx] == NULL) p->children[idx] = new Trie();
            p = p->children[idx];
        }
        p->wholeWord = true;
    }

    // Returns if the word is in the data structure. A word could
    // contain the dot character '.' to represent any one letter.
    bool _search(Trie* p, string word, int idx){
        if(p == NULL) return false;
        if(idx == word.length()) return p->wholeWord;
        if(word[idx] == '.'){
            for(Trie* child : p->children){
                if(_search(child, word, idx+1)) return true;
            }
        }else{
            return _search(p->children[word[idx] - 'a'], word, idx+1);
        }
        return false;
    }
    bool search(string word) {
        if(word.empty()) return false;
        return _search(root, word, 0);
    }
};

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");

Add and Search Word - Data structure design


// Copyright (c) 2018 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 <Utils/TestUtils.hpp>
#include "gtest/gtest.h"

#include <hspp/Games/Game.hpp>
#include <hspp/Games/GameConfig.hpp>
#include <hspp/Games/GameManager.hpp>
#include <hspp/Tasks/PlayerTasks/ChooseTask.hpp>

using namespace Hearthstonepp;
using namespace PlayerTasks;

TEST(Game, Mulligan)
{
    GameConfig config;
    config.player1Class = CardClass::WARRIOR;
    config.player2Class = CardClass::ROGUE;
    config.startPlayer = PlayerType::PLAYER1;
    config.doFillDecks = true;
    config.skipMulligan = false;

    Game game(config);
    game.StartGame();

    auto& curPlayer = game.GetCurrentPlayer();
    auto& opPlayer = game.GetOpponentPlayer();

    Task::Run(curPlayer,
              ChooseTask::Mulligan(curPlayer, std::vector<std::size_t>()));
    Task::Run(opPlayer,
              ChooseTask::Mulligan(opPlayer, std::vector<std::size_t>()));

    game.nextStep = Step::MAIN_BEGIN;
    GameManager::ProcessNextStep(game, game.nextStep);
}

Add unit test for Game to test mulligan process code


/**
* @file ConstArray_test.cpp
* @brief Unit tests for the ConstArray class.
* @author Dominique LaSalle <dominique@solidlake.com>
* Copyright 2018
* @version 1
* @date 2018-11-14
*/

#include "UnitTest.hpp"
#include "ConstArray.hpp"
#include "Array.hpp"

#include <cstdlib>
#include <vector>

namespace sl
{

UNITTEST(ConstArray, Size)
{
  ConstArray<int> m(1001UL);
  testEqual(m.size(), 1001UL);
}

UNITTEST(ConstArray, FromArray)
{
  ConstArray<int> m(Array<int>(5, 1));
  testEqual(m.size(), 5UL);

  for (int const v : m) {
    testEqual(v, 1);
  }
}

UNITTEST(ConstArray, FromExternalMemory)
{
  std::vector<int> a(5, 1);
  {
    // make sure the const array is free'd before vector
    ConstArray<int> m(a.data(), a.size());
    testEqual(m.size(), 5UL);

    for (int const v : m) {
      testEqual(v, 1);
    }
  }
}

UNITTEST(ConstArray, Front)
{
  Array<size_t> a(10UL);
  for (size_t i = 0; i < a.size(); ++i) {
    a[i] = i;
  }
  ConstArray<size_t> m(std::move(a));

  testEqual(m.front(), 0UL);
}

UNITTEST(ConstArray, Back)
{
  Array<size_t> a(10UL);
  for (size_t i = 0; i < a.size(); ++i) {
    a[i] = i;
  }
  ConstArray<size_t> m(std::move(a));

  testEqual(m.back(), m.size()-1);
}

}

Add unit tests for ConstArray


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

#include "SkTypes.h"

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

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

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

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

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

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

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

Add a new SkMemory implementation that uses mozalloc instead of malloc


//----------------------------  find_cell_1.cc  ---------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2003, 2004, 2005, 2006 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//----------------------------  find_cell_1.cc  ---------------------------

// take a 3d mesh and check that we can find an arbitrary point's cell
// in it

#include "../tests.h"
#include <base/logstream.h>
#include <grid/tria.h>
#include <grid/tria_accessor.h>
#include <grid/tria_iterator.h>
#include <grid/grid_tools.h>
#include <grid/grid_generator.h>
#include <grid/tria_boundary_lib.h>

#include <fstream>

void check (Triangulation<3> &tria)
{
  Point<3> p (0.75,0,0);

  Triangulation<3>::active_cell_iterator cell
    = GridTools::find_active_cell_around_point (tria, p);

  deallog << cell << std::endl;
  for (unsigned int v=0; v<GeometryInfo<2>::vertices_per_cell; ++v)
    deallog << "<" << cell->vertex(v) << "> ";
  deallog << std::endl;

  Assert (p.distance (cell->center()) < cell->diameter()/2,
	  ExcInternalError());
}

int main ()
{
  std::ofstream logfile("find_cell_1/output");
  deallog.attach(logfile);
  deallog.depth_console(0);
  deallog.threshold_double(1.e-10);

  Triangulation<3> coarse_grid;
  GridGenerator::hyper_cube (coarse_grid);
  coarse_grid.refine_global (3);
  check (coarse_grid);
}

Add a test that presently fails.


#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int *W, *A, N;
	cin >> N;
	W = new int[N + 1];
	A = new int[N + 1];
	for (int i = 1; i < N + 1; i++)
	{
		cin >> W[i];
	}
	A[0] = 0;
	A[1] = W[1];
	for (int i = 2; i < N + 1; i++)
	{
		A[i] = max(A[i - 1], A[i - 2] + W[i]);
	}
	cout << A[N]<<endl;
}

Add an implementation of Maximum Weight Independent Subsequence in CPP


// two_dim_rand.cpp
//
#include <iostream>

#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/random.hpp>

double on_circle_prob(double x, double y)
{
    static const double k_delta = 0.01;
    if (std::abs(x*x + y*y - 1) <= k_delta)
        return 1.0;
    else
        return 0;
}

int main(int argc, char* argv[])
{
    using boost::lexical_cast;
    using boost::random::uniform_real_distribution;
    using boost::random::discrete_distribution;

    std::size_t samples = argc > 1 ? lexical_cast<std::size_t>(argv[1]) : 100;
    std::size_t n = argc > 2 ? lexical_cast<std::size_t>(argv[2]) : 100;
    double xmin = -1.0;
    double xmax = 1.0;
    double ymin = -1.0;
    double ymax = 1.0;

    boost::mt19937 gen;
    uniform_real_distribution<> x_dist(xmin, xmax);
    for (int i = 0; i < samples; ) {
        double x = x_dist(gen);
        discrete_distribution<> y_dist(n, ymin, ymax, boost::bind(on_circle_prob, x, _1));
        int rand_n = y_dist(gen);
        double y = (rand_n * 1.0 / n) * (ymax - ymin) + ymin;
        if (true || on_circle_prob(x, y) != 0) {
            std::cout << x << ' ' << y << std::endl;
            i++;
        }
    }
}

Implement a simple two-dimension point generation procedure with regard to certain probability function, with the help of discrete_distribution


/*
* @author Abhishek Datta
* @github_id abdatta
* @since 15th October, 2017
*
* The following algroithm takes complex coeeficients
* and calculates its inverse discrete fourier transform
*/

#include <complex>
#include <iostream>
#include <iomanip>
#include <valarray>

const double PI = std::acos(-1);

typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;

// recursive fft (in-place)
void fft(CArray& x)
{
    const size_t N = x.size();
    if (N <= 1) return;

    // divide
    CArray even = x[std::slice(0, N/2, 2)];
    CArray  odd = x[std::slice(1, N/2, 2)];

    // conquer
    fft(even);
    fft(odd);

    // combine
    for (size_t k = 0; k < N/2; ++k)
    {
        Complex t = std::polar(1.0, 2 * PI * k / N) * odd[k];
        x[k    ] = even[k] + t;
        x[k+N/2] = even[k] - t;
    }
}

// inverse fft (in-place)
void ifft(CArray& x)
{
    // conjugate the complex numbers
    x = x.apply(std::conj);

    // forward fft
    fft( x );

    // conjugate the complex numbers again
    x = x.apply(std::conj);

    // scale the numbers
    x /= x.size();
}

int main()
{
	int t; // no. of test cases to try on
	std::cin>>t;
	while(t--)
	{
		int n; // n is for order of the polynomial
		std::cin>>n;
	    Complex test[n];
	    for (int i = 0; i < n; ++i)
	    {
	    	double real, imag;
	    	std::cin>>real>>imag; // reading each coefficient as a complex number
	    	test[i].real(real); // setting real part to real
	    	test[i].imag(imag); // and imaginary part to imaginary
	    }

	    CArray data(test, n);

	    ifft(data);

	    for (int i = 0; i < n; ++i)
	    {
	        std::cout << std::fixed << std::setprecision(6) << data[i].real() << " " << data[i].imag() << std::endl;
	    }
	}
}

Add algorithm for Inverse FFT


#include <cstdio>
#include <cmath>

using namespace std;

int a[1000010];

bool is_prime(int number)
{
  if (number < 2) return false;
  double root = sqrt(number);
  for (int i = 2; i <= root; i++)
  {
    if (number % i == 0) return false;
  }

  return true;
}

int main()
{
  for (int i = 1; i <= 1000000; i++)
  {
    if (is_prime(i)) a[i] = 1;
  }

  for (int i = 1; i <= 1000000; i++)
  {
    a[i] += a[i - 1];
  }

  int tests;
  scanf("%d", &tests);

  while (tests--)
  {
    int x, y;
    scanf("%d%d", &x, &y);
    printf("%d\n", a[y] - a[x - 1]);
  }

  return 0;
}

Add a solution for task 1b


class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int index = 1;
        int cur_count = 1;
        int total = nums.size();
        for (int i = 1; i < total; ++i) {
            if (nums[i] == nums[i-1]) {
                ++cur_count;
                if (cur_count <= 2) {
                    nums[index] = nums[i];
                    ++index;
                }
            } else {
                nums[index] = nums[i];
                ++index;
                cur_count = 1;
            }
        }
        return index;
    }
};

Remove Duplicates from Sorted Array II


#include "eigen.hh"

#include "geometry/intersection/sphere_plane.hh"
#include "geometry/rotation_to.hh"
#include "geometry/shapes/circle.hh"
#include "geometry/shapes/halfspace.hh"
#include "geometry/shapes/sphere.hh"

#include "viewer/primitives/simple_geometry.hh"
#include "viewer/window_3d.hh"

namespace geometry {
namespace intersection {

using Vec3 = Eigen::Vector3d;

void put_circle(viewer::SimpleGeometry& geo, const geometry::shapes::Circle& circle) {
  constexpr double DELTA_RAD = 0.01;

  const auto rot_real_from_circle = geometry::rotation_to(Vec3::UnitZ(), circle.u_normal);
  const SE3 world_from_circle = SE3(rot_real_from_circle, circle.center);

  viewer::Polygon polygon;
  polygon.outline = true;
  for (double s = 0.0; s <= M_PI * 2.0; s += DELTA_RAD) {
    const Vec3 local_pt =
        Vec3(circle.radius * std::cos(s), circle.radius * std::sin(s), 0.0);

    polygon.points.push_back(world_from_circle * local_pt);
  }
  geo.add_polygon(polygon);
}

void go() {
  const auto view = viewer::get_window3d("Mr. Walks, walks");
  view->set_target_from_world(
      SE3(SO3::exp(Eigen::Vector3d(-3.1415 * 0.5, 0.0, 0.0)), Eigen::Vector3d::Zero()));
  const auto geo = view->add_primitive<viewer::SimpleGeometry>();
  view->set_continue_time_ms(20);

  constexpr double dt = 0.1;
  for (double t = 0.0; t < 100.0; t += dt) {
    const shapes::Plane ground{Vec3::UnitZ(), 0.0};
    geo->add_plane({ground});

    const shapes::Sphere sphere{Vec3(1.0, 1.0, std::cos(t)), 1.0};
    geo->add_billboard_circle({sphere.center, sphere.radius});

    const auto intersection = sphere_plane_intersection(sphere, ground);

    if (intersection) {
      put_circle(*geo, *intersection);
    }

    geo->flip();
    view->spin_until_step();
  }
}

}  // namespace intersection
}  // namespace geometry
int main() {
  geometry::go();
}

Add a simple demo for sphere-plane intersection


// Read a line of integers into a container

#include <vector>
#include <sstream>
#include <iterator>

int main()
{
	std::istringstream stream{"4 36 72 8"};
	std::vector<int> values;

	std::copy(std::istream_iterator<int>{stream},
	          std::istream_iterator<int>{},
	          std::back_inserter(values));
}

// Read a sequence of delimited integers from a single line of an
// input stream into a standard container.
//
// On [9], we declare a [`std::istringstream`](cpp/io/basic_istringstream)
// as the input stream, although any other input stream could be used.
// For user input, you can simply replace `stream` with
// [`std::cin`](cpp/io/cin) instead. We have similarly used
// [`std::vector`](cpp/container/vector) as an example container
// ([10]).
//
// On [12-14], we use the [`std::copy`](cpp/algorithm/copy) algorithm
// to copy values from the input stream to the container. This
// algorithm takes iterator arguments.
//
// To iterate over the stream, we use the
// [`std::istream_iterator<int>`](cpp/iterator/istream_iterator) type
// on [12], which internally uses `operator>>` to extract `int`s. The
// default constructed `std::istream_iterator<int>` on [13] denotes
// the end of the stream.
//
// We use the [`std::back_inserter`](cpp/iterator/back_inserter)
// helper function on [14] to create an output iterator that will
// internally `push_back` elements into the given container.

Add "read line of integers" sample


//
// Copyright 2013 Jeff Bush
//
// 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 "output.h"

Output output;

void manual_switch(int value)
{
	static void *label_array[] = {
		&&label4,
		&&label2,
		&&label3,
		&&label1
	};

	goto *label_array[value];

label1:
	output << "label1";
	return;

label2:
	output << "label2";
	return;

label3:
	output << "label3";
	return;

label4:
	output << "label4";
}

int main()
{
	manual_switch(0);	// CHECK: label4
	manual_switch(1);	// CHECK: label2
	manual_switch(2);	// CHECK: label3
	manual_switch(3);	// CHECK: label1
}

Test for address of label operator.


#include <map>

#include <common/buffer.h>
#include <common/endian.h>

#include <ssh/ssh_algorithm_negotiation.h>
#include <ssh/ssh_protocol.h>

namespace {
	static uint8_t constant_cookie[16] = {
		0x00, 0x10, 0x20, 0x30,
		0x40, 0x50, 0x60, 0x70,
		0x80, 0x90, 0xa0, 0xb0,
		0xc0, 0xd0, 0xe0, 0xf0
	};

	template<typename T>
	Buffer name_list(T list)
	{
		typename T::const_iterator it;
		std::vector<Buffer> names;
		Buffer merged;
		uint32_t len;
		Buffer out;

		for (it = list.begin(); it != list.end(); ++it)
			names.push_back(it->first);
		merged = Buffer::join(names, ",");
		len = merged.length();
		len = BigEndian::encode(len);
		out.append(&len);
		out.append(merged);
		return (out);
	}
}

bool
SSHAlgorithmNegotiation::input(Buffer *in)
{
	switch (in->peek()) {
	case SSH::Message::KeyExchangeInitializationMessage:
		DEBUG(log_) << "Just ignoring initialization message.";
		return (true);
	default:
		DEBUG(log_) << "Unsupported algorithm negotiation message:" << std::endl << in->hexdump();
		return (false);
	}
}

bool
SSHAlgorithmNegotiation::output(Buffer *out)
{
	ASSERT(out->empty());

	out->append(SSH::Message::KeyExchangeInitializationMessage);
	out->append(constant_cookie, sizeof constant_cookie); /* XXX Synchronous random byte generation?  */
	out->append(name_list(key_exchange_map_));
	out->append(name_list(server_host_key_map_));
	out->append(name_list(encryption_client_to_server_map_));
	out->append(name_list(encryption_server_to_client_map_));
	out->append(name_list(mac_client_to_server_map_));
	out->append(name_list(mac_server_to_client_map_));
	out->append(name_list(compression_client_to_server_map_));
	out->append(name_list(compression_server_to_client_map_));
	out->append(name_list(language_client_to_server_map_));
	out->append(name_list(language_server_to_client_map_));
	out->append(SSH::Boolean::False);
	uint32_t reserved(0);
	out->append(&reserved);

	return (true);
}

Add file missed in r884: initial sketching of algorithm negotiation initialization.


#include "catch.hpp"

#include "Harp.hpp"
using namespace harp;

#define XYZDIR SRCDIR "/files/xyz/"

TEST_CASE("Read files in XYZ format", "[XYZ]"){
    auto file = Trajectory(XYZDIR"helium.xyz");
    Frame frame;

    SECTION("Stream style reading"){
        file >> frame;
        CHECK(frame.natoms() == 125);
        // Check positions
        auto positions = frame.positions();
        CHECK(positions[0] == Vector3D(0.49053f, 8.41351f, 0.0777257f));
        CHECK(positions[125] == Vector3D(8.57951f, 8.65712f, 8.06678f));
        // Check topology
        auto topology = frame.topology();
        CHECK(topology.atom_types().size() == 1);
        CHECK(topology.atom_list().size() == 125);
        CHECK(topology[0] == Atom("He"));
    }

    SECTION("Method style reading"){
        frame = file.read_next_step();
        CHECK(frame.natoms() == 125);
        // Check positions
        auto positions = frame.positions();
        CHECK(positions[0] == Vector3D(0.49053f, 8.41351f, 0.0777257f));
        CHECK(positions[125] == Vector3D(8.57951f, 8.65712f, 8.06678f));
        // Check topology
        auto topology = frame.topology();
        CHECK(topology.atom_types().size() == 1);
        CHECK(topology.atom_list().size() == 125);
        CHECK(topology[0] == Atom("He"));
    }
}

Add first test for XYZ format


// 3. Longest Substring Without Repeating Characters
/**
 * Given a string, find the length of the longest substring without repeating characters.
 *
 * Examples:
 *
 * Given "abcabcbb", the answer is "abc", which the length is 3.
 *
 * Given "bbbbb", the answer is "b", with the length of 1.
 *
 * Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
 *
 * Tags: Hash Table, Two Pointers, String
 *
 * Similar Problems: (H) Longest Substring with At Most Two Distinct Characters
 *
 * Author: Kuang Qin
 */

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

using namespace std;

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.size();
        if (n == 0)
            return 0;

        vector<int> map(128, -1);    // hash table for ascii chars
        int left = 0, right = 0, len = 0;

        for (right = 0; right < n; right++) {
            if (map[s[right]] != -1) {   // s[right] found
                if (left < map[s[right]] + 1)
                    left = map[s[right]] + 1;    // update left position to the first non-repeating character
            }

            map[s[right]] = right;  // update the last appeared location of s[right]
            if (len < right - left + 1)
                len = right - left + 1;   // update the max length
        }

        return len;
    }
};

int main() {
    string s = "pwwkwe";
    Solution sol;
    int len = sol.lengthOfLongestSubstring(s);
    cout << len << endl;
    cin.get();

    return 0;
}

Add Solution for 3. Longest Substring Without Repeating Characters


//===- ProfileInfoLoaderPass.cpp - LLVM Pass to load profile info ---------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements a concrete implementation of profiling information that
// loads the information from a profile dump file.
//
//===----------------------------------------------------------------------===//

#include "llvm/Pass.h"
#include "llvm/Analysis/ProfileInfo.h"
#include "llvm/Analysis/ProfileInfoLoader.h"
using namespace llvm;

namespace {
  class LoaderPass : public Pass, public ProfileInfo {
    std::string Filename;
  public:
    LoaderPass(const std::string &filename = "llvmprof.out")
      : Filename(filename) {}

    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.setPreservesAll();
    }

    virtual const char *getPassName() const {
      return "Profiling information loader";
    }

    /// run - Load the profile information from the specified file.
    virtual bool run(Module &M);

    unsigned getExecutionCount(BasicBlock *BB) { return 0; }
  };

  RegisterOpt<LoaderPass>
  X("profile-loader", "Load profile information from llvmprof.out");

  RegisterAnalysisGroup<ProfileInfo, LoaderPass> Y;
}  // End of anonymous namespace

/// createProfileLoaderPass - This function returns a Pass that loads the
/// profiling information for the module from the specified filename, making it
/// available to the optimizers.
Pass *llvm::createProfileLoaderPass(const std::string &Filename) {
  return new LoaderPass(Filename);
}

bool LoaderPass::run(Module &M) {

  return false;
}

Add skeleton profileinfoloader pass. This will be enhanced to actually LOAD a profile tommorow. :)


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

#include "chrome/browser/ui/toolbar/test_toolbar_model.h"

TestToolbarModel::TestToolbarModel()
    : ToolbarModel(),
      should_replace_url_(false),
      security_level_(NONE),
      icon_(0),
      should_display_url_(true),
      input_in_progress_(false) {}

TestToolbarModel::~TestToolbarModel() {}

string16 TestToolbarModel::GetText(
    bool display_search_urls_as_search_terms) const {
  return text_;
}

GURL TestToolbarModel::GetURL() const {
  return url_;
}

bool TestToolbarModel::WouldReplaceSearchURLWithSearchTerms() const {
  return should_replace_url_;
}

ToolbarModel::SecurityLevel TestToolbarModel::GetSecurityLevel() const {
  return security_level_;
}

int TestToolbarModel::GetIcon() const {
  return icon_;
}

string16 TestToolbarModel::GetEVCertName() const {
  return ev_cert_name_;
}

bool TestToolbarModel::ShouldDisplayURL() const {
  return should_display_url_;
}

void TestToolbarModel::SetInputInProgress(bool value) {
  input_in_progress_ = value;
}

bool TestToolbarModel::GetInputInProgress() const {
  return input_in_progress_;
}

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

#include "chrome/browser/ui/toolbar/test_toolbar_model.h"

#include "grit/theme_resources.h"

TestToolbarModel::TestToolbarModel()
    : ToolbarModel(),
      should_replace_url_(false),
      security_level_(NONE),
      icon_(IDR_LOCATION_BAR_HTTP),
      should_display_url_(true),
      input_in_progress_(false) {}

TestToolbarModel::~TestToolbarModel() {}

string16 TestToolbarModel::GetText(
    bool display_search_urls_as_search_terms) const {
  return text_;
}

GURL TestToolbarModel::GetURL() const {
  return url_;
}

bool TestToolbarModel::WouldReplaceSearchURLWithSearchTerms() const {
  return should_replace_url_;
}

ToolbarModel::SecurityLevel TestToolbarModel::GetSecurityLevel() const {
  return security_level_;
}

int TestToolbarModel::GetIcon() const {
  return icon_;
}

string16 TestToolbarModel::GetEVCertName() const {
  return ev_cert_name_;
}

bool TestToolbarModel::ShouldDisplayURL() const {
  return should_display_url_;
}

void TestToolbarModel::SetInputInProgress(bool value) {
  input_in_progress_ = value;
}

bool TestToolbarModel::GetInputInProgress() const {
  return input_in_progress_;
}

Use a reasonable default for the icon value in TestToolbarModel.


/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ---------------------------------------------------------------------
 */

/** @file
Google test main program
*/

#include "gtest/gtest.h"
#include "sample1.h"

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

Add the main() for google tests


// Copyright 2016 Mitchell Kember. Subject to the MIT License.
// Project Euler: Problem 25
// 1000-digit Fibonacci number

#include <gmpxx.h>

namespace problem_25 {

long solve() {
	mpz_class first(1);
	mpz_class second(1);
	mpz_class power_of_ten(10);
	mpz_class* a = &first;
	mpz_class* b = &second;

	long index = 1;
	long digits = 1;
	while (digits < 1000) {
		std::swap(a, b);
		*b += *a;
		++index;
		if (*a / power_of_ten >= 1) {
			++digits;
			power_of_ten *= 10;
		}
	}
	return index;
}

} // namespace problem_25

Solve problem 25 in C++


#include <iostream>
#include <string>

using namespace std;

template <typename T>
int compare(const T &l , const T &r) {//remove the &, then works.
    if(l > r) return 1;
    if(r > l) return -1;
    return 0;
}

int main() {
//    cout << compare("hi", "world");
    cout << compare("bye", "dad");
    return 0;
}

Add solution for chapter 16 test 34


#include <stdio.h>
#include "Halide.h"
#include <fstream>
#include <cassert>
#include <iostream>

#include "test/common/halide_test_dirs.h"

using namespace Halide;

int main(int argc, char **argv) {
    Var x("x"), y("y");
    Func f("f");

    f(x, y) = 42;

    std::string bitcode_file = Internal::get_test_tmp_dir() + "extern.bc";
    f.compile_to_bitcode(bitcode_file, {}, "extern");

    std::vector<uint8_t> bitcode;
    std::ifstream bitcode_stream(bitcode_file, std::ios::in | std::ios::binary);
    bitcode_stream.seekg(0, std::ios::end);
    bitcode.resize(bitcode_stream.tellg());
    bitcode_stream.seekg(0, std::ios::beg);
    bitcode_stream.read(reinterpret_cast<char *>(&bitcode[0]), bitcode.size());

    ExternalCode external_code = ExternalCode::bitcode_wrapper(get_target_from_environment(), bitcode, "extern");

    Func f_extern;
    f_extern.define_extern("extern", { }, type_of<int32_t>(), 2);

    Func result;
    result(x, y) = f_extern(x, y);

    Module module = result.compile_to_module({}, "forty_two");

    module.append(external_code);

    auto forty_two = module.get_function_by_name("forty_two");

    Internal::JITModule jit_module(module, forty_two, {});

    auto argv_wrapper = jit_module.argv_function();

    Buffer<int32_t> buf(16, 16);
    const void *args[1];
    args[0] = buf.raw_buffer();

    int ret_code = argv_wrapper(args);

    assert(ret_code == 0);
    for (int i = 0; i < 16; i++) {
        for (int j = 0; j < 16; j++) {
            assert(buf(i, j) == 42);
        }
    }

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

Add a test for ExternalCode functionality.


#include <cassert>
#include <iostream>
#include <vector>

using namespace std;

const int MAX_N = 100;

// We will put the regions in a circular doubly linked list.
struct Region {
  int id;
  Region *prev, *next;
};

int main() {
  while (true) {
    int N;
    cin >> N;
    if (N == 0)
      break;

    // Allocate Region nodes. Note they are stack-allocated so do not
    // need to be deleted. The id members are initialized here and
    // never change; the prev and next pointers are reinitialized for
    // every iteration of the next loop.
    Region regions[MAX_N];
    for (int i = 0; i < MAX_N; ++i)
      regions[i].id = i+1;

    int m;
    // Exhaustive search for the value of m that makes region 13
    // (Wellington) the last region turned on.
    for (m = 1; m <= N; ++m) {
      // Set up pointers for a doubly linked circular list of N nodes.
      for (int i = 0; i < N; ++i) {
	regions[i].next = &regions[(i+1)%N];
	regions[i].prev = &regions[(i-1+N)%N];
      }

      // Repeatedly delete the m'th element until only one node
      // remains.
      Region* head = &regions[0];
      while (head->next != head) {
	// delete this region
	Region* next = head->next;
	head->prev->next = head->next;
	head->next->prev = head->prev;

	// advance m steps
	head = next; // one step
	for (int i = 0; i < (m-1); ++i) // m-1 steps
	  head = head->next;
      }

      // Region 13 is the only one left, this is the best choice of m.
      if (head->id == 13)
	break;
    }

    cout << m << endl;
  }

  return 0;
}

Add linked list based solution