#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

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

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

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

MacViews: Fix compile regression after SmartLock error bubble in r313408

toolkit-views builds on mac are getting:
Undefined symbols for architecture x86_64:
   ShowProximityAuthErrorBubble

To fix, move proximity_auth_error_bubble.cc to mac_sources. This works
because the symbol is only referenced on platforms with extensions,
which are toolkit_views platforms + mac.

After proximity_auth_error_bubble_view.cc moves in
chrome_browser_ui.gypi from chrome_browser_ui_views_non_mac_sources to
chrome_browser_ui_views_sources then proximity_auth_error_bubble.cc can
be deleted.

BUG=399191
TBR=sky@chromium.org

Review URL: https://codereview.chromium.org/887563003

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#313888}


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

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


#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

Add error test for inlined stages

Former-commit-id: af3d38c75bfc1411ff46d64446da37878bee33e7


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

BUG=none

Review URL: https://codereview.chromium.org/1149103002

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#331083}


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

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

git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@5292 2bbb7eff-a529-9590-31e7-b0007b416f81


#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

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!

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


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

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

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.

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


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

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

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

Add oss-fuzz endpoint for PathMeasure

Bug: skia:
Change-Id: I3e051cefd6861b63bab33a1812674eacf67a35dd
Reviewed-on: https://skia-review.googlesource.com/113748
Reviewed-by: Mike Klein <14574f09dfa9b4e14759b88c3426a495a0e627b0@google.com>
Commit-Queue: Kevin Lubick <7cdab2cfab351f23814786ba39716e90eed69047@google.com>


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

This test fails without LLVM r286615

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@286618 91177308-0d34-0410-b5e6-96231b3b80d8


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

Former-commit-id: 85284b599397bb280d879f9ec99bce9096ed8db4


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

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

Signed-off-by: WajahatSiddiqui <3c3ea4adfdf19decee174766aef6add34b32b7f0@gmail.com>


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

Fixes #610


#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"

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

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

Fix Ozone clang build errors

NOTRY=true
BUG=none
TBR=spang@chromium.org

Review URL: https://codereview.chromium.org/346773005

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@279103 0039d316-1c4b-4281-b951-d872f2087c98


#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;
}

enh: 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);
}

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

git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@216665 91177308-0d34-0410-b5e6-96231b3b80d8


#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

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

test: 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

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

git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@5292 2bbb7eff-a529-9590-31e7-b0007b416f81


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

Add a test that presently fails.

git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@12882 0785d39b-7218-0410-832d-ea1e28bc413d


#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

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

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

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

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.

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

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.  :)

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


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

ToolbarModel's GetIcon method returns a resource ID, so the TestToolbarModel should be initialized with a valid resource ID for |icon_|. This CL updates the TestToolbarModel to return IDR_LOCATION_BAR_HTTP by default instead of 0, which is never valid.

BUG=None

Review URL: https://chromiumcodereview.appspot.com/11362031

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@165461 0039d316-1c4b-4281-b951-d872f2087c98


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

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++

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

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

Add linked list based solution


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

        return true;
    }
};

Swap Adjacent in LR String

Swap Adjacent in LR String


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

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

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

  matrix_v a_inv = inverse_spd(a);

  matrix_v I = multiply(a,a_inv);

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

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

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

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

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

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

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

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

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

Add unit test for inverse_spd.

Add unit test for inverse_spd.


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

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

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

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

Add extra testing for init-captures.

Add extra testing for init-captures.

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


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

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

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

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

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

Add a crazy test case for r243987

[Sema] Add a crazy test case for r243987

It's not valid code (maybe it can be made valid, but I'm not sure how).
To trigger the crash fixed in r243987 requires a friend function with
more than four template parameter lists. With this test we have at least
some coverage.

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


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

#include "catch.hpp"

#include "hooks.hh"

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

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

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

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

Add tests for hook class

Add tests for hook class


#include "mock_player.hpp"

#include <ctime>

#include <boost/random/discrete_distribution.hpp>

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

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

namespace Quoridor {

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

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

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

MockPlayer::~MockPlayer()
{
}

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

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

}  /* namespace Quoridor */

#include "mock_player.hpp"

#include <ctime>

#include <boost/random/discrete_distribution.hpp>

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

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

namespace Quoridor {

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

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

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

MockPlayer::~MockPlayer()
{
}

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

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

}  /* namespace Quoridor */

Check available moves in MockPlayer

Check available moves in MockPlayer


#include <iostream>

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

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

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


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

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

using namespace std;

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

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

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

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

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

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

        string str;

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

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

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

Add Solution for Problem 017

Add Solution for Problem 017


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

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

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

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

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

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

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

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

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

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

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

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

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

    return 0;
}

Add examples on the use of class range

Add examples on the use of class range


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

#include<iostream>
#include<iomanip>

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

Add Chapter 24, Try This 1

Add Chapter 24, Try This 1


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

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

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

BOOST_AUTO_TEST_SUITE(block_tests)

BOOST_AUTO_TEST_CASE(block_with_invalid_tx_test)
{
   tester main;

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

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

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

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

}

BOOST_AUTO_TEST_SUITE_END()

Add push block with invalid transaction test