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

#include <folly/Benchmark.h>
#include <folly/synchronization/detail/ThreadCachedInts.h>

using namespace folly;

void runTest(int iters) {
  BenchmarkSuspender susp;

  detail::ThreadCachedInts<void> counters;
  counters.increment(0);

  susp.dismiss();

  // run the test loop
  for (int i = 0; i < iters; i++) {
    counters.increment(0);
  }
}

BENCHMARK_DRAW_LINE();
BENCHMARK(Increment, iters) {
  runTest(iters);
}
BENCHMARK_DRAW_LINE();

int main(int argc, char* argv[]) {
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  folly::runBenchmarks();

  return 0;
}

Add thread cached ints benchmark


#include <stddef.h>
#include "util/timer.h"

#define MS_PER_SECOND 1000

unsigned long openxc::util::time::startupTimeMs() {
    static unsigned long startupTime = time::systemTimeMs();
    return startupTime;
}

unsigned long openxc::util::time::uptimeMs() {
    return systemTimeMs() - startupTimeMs();
}

/* Private: Return the period in ms given the frequency in hertz.
 */
float frequencyToPeriod(float frequency) {
    return 1 / frequency * MS_PER_SECOND;
}

bool openxc::util::time::shouldTick(FrequencyClock* clock) {
    if(clock == NULL) {
        return true;
    }

    unsigned long (*timeFunction)() =
            clock->timeFunction != NULL ? clock->timeFunction : systemTimeMs;
    float elapsedTime = timeFunction() - clock->lastTick;
    bool tick = false;
    if(!clock->started || clock->frequency == 0 ||
            elapsedTime >= frequencyToPeriod(clock->frequency)) {
        tick = true;
        clock->lastTick = timeFunction();
        clock->started = true;
    }
    return tick;
}

void openxc::util::time::initializeClock(FrequencyClock* clock) {
    clock->lastTick = -1;
    clock->frequency = 0;
    clock->timeFunction = systemTimeMs;

}

#include <stddef.h>
#include "util/timer.h"

#define MS_PER_SECOND 1000

unsigned long openxc::util::time::startupTimeMs() {
    static unsigned long startupTime = time::systemTimeMs();
    return startupTime;
}

unsigned long openxc::util::time::uptimeMs() {
    return systemTimeMs() - startupTimeMs();
}

/* Private: Return the period in ms given the frequency in hertz.
 */
float frequencyToPeriod(float frequency) {
    return 1 / frequency * MS_PER_SECOND;
}

bool openxc::util::time::shouldTick(FrequencyClock* clock) {
    if(clock == NULL) {
        return true;
    }

    unsigned long (*timeFunction)() =
            clock->timeFunction != NULL ? clock->timeFunction : systemTimeMs;
    float elapsedTime = timeFunction() - clock->lastTick;
    bool tick = false;
    if(!clock->started || clock->frequency == 0 ||
            elapsedTime >= frequencyToPeriod(clock->frequency)) {
        tick = true;
        clock->lastTick = timeFunction();
        clock->started = true;
    }
    return tick;
}

void openxc::util::time::initializeClock(FrequencyClock* clock) {
    clock->lastTick = -1;
    clock->frequency = 0;
    clock->timeFunction = systemTimeMs;
    clock->started = false;
}

Fix use of an uninitialized value.


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

#include "base/message_loop/message_loop.h"
#include "device/hid/hid_service.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace device {

TEST(HidServiceTest, Create) {
  base::MessageLoopForIO message_loop;
  HidService* service = HidService::Create(message_loop.message_loop_proxy());
  ASSERT_TRUE(service);

  std::vector<HidDeviceInfo> devices;
  service->GetDevices(&devices);
  for (std::vector<HidDeviceInfo>::iterator it = devices.begin();
      it != devices.end();
      ++it) {
    ASSERT_TRUE(it->device_id != kInvalidHidDeviceId);
  }
}

}  // namespace device

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

#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "device/hid/hid_service.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace device {

TEST(HidServiceTest, Create) {
  base::MessageLoopForIO message_loop;
  scoped_ptr<HidService> service(
      HidService::Create(message_loop.message_loop_proxy()));
  ASSERT_TRUE(service);

  std::vector<HidDeviceInfo> devices;
  service->GetDevices(&devices);
  for (std::vector<HidDeviceInfo>::iterator it = devices.begin();
      it != devices.end();
      ++it) {
    ASSERT_TRUE(it->device_id != kInvalidHidDeviceId);
  }
}

}  // namespace device

Fix memory leak in HidServiceTest.Create from r285774


// Return multiple values

#include <tuple>
#include <string>

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

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

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

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

Add "multiple return values" sample


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

#include <ews/ews.hpp>
#include <ews/ews_test_support.hpp>
#include <exception>
#include <iostream>
#include <ostream>
#include <stdlib.h>
#include <string>

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

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

        auto room_lists = service.get_room_lists();
        if (room_lists.empty())
        {
            std::cout << "There are no room lists configured\n";
        }
        else
        {
            for (const auto& room_list : room_lists)
            {
                std::cout << "The room list "
                          << room_list.name()
                          << " contains the following rooms:\n";
                auto rooms = service.get_rooms(room_list);
                if (rooms.empty())
                {
                    std::cout << "This room list does not contain any rooms\n";
                }
                else
                {
                    for (const auto& room : rooms)
                    {
                        std::cout << room.name() << "\n";
                    }
                }
            }
        }
    }
    catch (std::exception& exc)
    {
        std::cout << exc.what() << std::endl;
        res = EXIT_FAILURE;
    }

    ews::tear_down();
    return res;
}

// vim:et ts=4 sw=4

Add example for the room functions


/* A c++ program that can be linked without libstdc++ */

#include <cstdio> //Seems to be ok, requires libc
#include <cstdlib>

class C
{
public:
  C(int x) { data = x; mem = (int *)malloc(sizeof*mem); }
  ~C() { printf("Destroying C object with data = %i\n",data); free(mem); }
protected:
  int data;
  int *mem;
};

//Templates are ok
template<int N>
int retN()
{
  // This is ok (normal static data)
  static double f[] = {1,2,3};
  // Creating a static object bring in locking
  /* Brings in __cxa_guard_acquire/release
     static C cintemplate(19);  */
  return N+f[0];
}

static C cstatic(5); //This is also ok with g++/gcc

int main(void)
{
  C cstack(12);
  /* Requires libstdc++
  C *cp = new C(17);
  delete cp;
  */
  printf("ret12: %i\n",retN<12>());
  return 0;
}

Add C++ program that does not depend on libstdc++ but still uses many c++ features. This is for testing compilers.


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

using namespace std;
using namespace std::regex_constants;

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

Add solution for chapter 17 test 25


/* test OpenCL 1.1 Sampler Objects (section 5.5) */
#include "utest_helper.hpp"

void compiler_sampler(void)
{
  OCL_ASSERT(ctx != 0);
  cl_sampler s;
  cl_int err;
  int a1[] = {CL_TRUE, CL_FALSE},
      a2[] = {CL_ADDRESS_MIRRORED_REPEAT,
              CL_ADDRESS_REPEAT,
              CL_ADDRESS_CLAMP_TO_EDGE,
              CL_ADDRESS_CLAMP,
              CL_ADDRESS_NONE},
      a3[] = {CL_FILTER_NEAREST, CL_FILTER_LINEAR},
      a4[] = {CL_SAMPLER_REFERENCE_COUNT,
              CL_SAMPLER_CONTEXT,
              CL_SAMPLER_NORMALIZED_COORDS,
              CL_SAMPLER_ADDRESSING_MODE,
              CL_SAMPLER_FILTER_MODE};
  char pv[1000];
  size_t pv_size;
  int i, j, k, l;
  for(i=0; i<2; i++)
    for(j=0; j<5; j++)
      for(k=0; k<2; k++) {
        s = clCreateSampler(ctx, a1[i], a2[j], a3[k], &err);
        OCL_ASSERT(err == CL_SUCCESS);
        OCL_CALL(clRetainSampler, s);
        OCL_CALL(clReleaseSampler, s);
        for(l=0; l<5; l++)
          OCL_CALL(clGetSamplerInfo, s, a4[l], 1000, pv, &pv_size);
        OCL_CALL(clReleaseSampler, s);
      }
}

MAKE_UTEST_FROM_FUNCTION(compiler_sampler);

Test case for OpenCL 1.1 Sampler Objects


#include <iostream>
#include <fstream>
#include <vector>
#include <memory>

using namespace std;

void exercise1(int *b, int *e) {
    try {
        vector<int> v(b, e);
        int *p = new int[v.size()];
        ifstream in("ins");
        throw p;
    } catch(int *p) {
        delete[] p;
    }
}

void exercise2(int *b, int *e) {
    try {
        vector<int> v(b, e);
        unique_ptr<int[]> p(new int[v.size()]);
        ifstream in("ins");
    } catch(...) {

    }
}

void exercise3(int *b, int *e) {
    vector<int> v(b, e);
    int* p = new int[v.size()];
    ifstream in("ins");
    try {
        throw p;
    } catch(...) {
        delete[] p;
    }
    delete[] p;
}

int main() {
    int a[] = {1, 2, 3, 4};
    int *b = std::begin(a), *e = std::end(a);
    exercise1(b, e);
    exercise2(b, e);
    exercise3(b, e);
    return 0;
}

Add solution for chapter 18 test 3


#include "data.hpp"
#include "graph.hpp"
#include <string>
#include <vector>

namespace {
    enum Status : uint8_t { NONE, VISITED, PROCESSED };

    template <typename Graph> struct DFS {
        using index_type = unsigned int;
        explicit DFS(Graph &g) : graph(g), states(g.get_number_of_vertexes(), NONE) {}

        // Perform DFS traversal from given vertex.
        void pre_order(const std::vector<index_type> &vids) {
            std::vector<index_type> stack(vids.cbegin(), vids.cend());
            while (!stack.empty()) {
                auto vid = stack.back();
                stack.pop_back();
                visit(vid);
                auto range = graph.edges(vid);
                for (auto iter = range.begin; iter != range.end; ++iter) {
                    if (states[*iter] == NONE) { // Only check in a vertex if it has not been visited yet.
                        stack.push_back(*iter);
                    }
                }
            }
        }

        void reset_states() {
            states.assign(states.size(), NONE); // Reset node status
        }

        void visit(const index_type vid) {
            if (states[vid] == NONE) {
                states[vid] = VISITED;
                fmt::print("visit: {}\n", vid);
            }
        }

        Graph graph;
        std::vector<index_type> states;
    };
} // namespace

int main() {
    auto g = experiments::directed_graph();
    g.print();
    using graph_type = decltype(g);
    DFS<graph_type> dfs(g);

    // Visit node 0.
    dfs.pre_order({0});

    // Visit node 1.
    dfs.pre_order({1});
}

Add solution for problem 4.1


// 2.1 - remove duplicates from unsorted linked list

// uses STL list and set

#include<iostream>
#include<list>
#include<set>

using namespace std;

typedef list<int>::iterator iter;
typedef list<int>::const_iterator c_iter;

void remove_duplicates(list<int>& l)
{
    set<int> vals;
    iter p = l.begin();
    while (p != l.end()) {
        if (vals.find(*p) != vals.end())
            p = l.erase(p);
        else {
            vals.insert(*p);
            ++p;
        }
    }
}

void print(const list<int>& l)
{
    for (c_iter p = l.begin(); p!=l.end(); ++p)
        cout << *p << '\n';
}

void test(list<int>& l)
{
    cout << "Before:\n";
    print(l);
    remove_duplicates(l);
    cout << "\nAfter:\n";
    print(l);
    cout << '\n';
}

int main()
{
    list<int> l1;
    test(l1);
    list<int> l2 = { 1 };
    test(l2);
    list<int> l3 = { 1, 1 };
    test(l3);
    list<int> l4 = { 1, 2, 3 };
    test(l4);
    list<int> l5 = { 1, 2, 3, 1, 4, 1, 5, 5, 5 };
    test(l5);
}

Add Chapter 2, exercise 1: eliminate duplicates in linked list


// RUN: %clang_cc1 -fsyntax-only -verify %s
void g();

void f(); // expected-note 9{{candidate function}}
void f(int); // expected-note 9{{candidate function}}

template<class T> void t(T); // expected-note 3{{candidate function}}
template<class T> void t(T*); // expected-note 3{{candidate function}}

template<class T> void u(T);

int main()
{
  { bool b = (void (&)(char))f; } // expected-error{{does not match required type}}
  { bool b = (void (*)(char))f; } // expected-error{{does not match required type}}

  { bool b = (void (&)(int))f; } //ok
  { bool b = (void (*)(int))f; } //ok

  { bool b = static_cast<void (&)(char)>(f); } // expected-error{{does not match}}
  { bool b = static_cast<void (*)(char)>(f); } // expected-error{{address of overloaded function}}

  { bool b = static_cast<void (&)(int)>(f); } //ok
  { bool b = static_cast<void (*)(int)>(f); } //ok

  { bool b = reinterpret_cast<void (&)(char)>(f); } // expected-error{{cannot resolve}}
  { bool b = reinterpret_cast<void (*)(char)>(f); } // expected-error{{cannot resolve}}

  { bool b = reinterpret_cast<void (*)(char)>(g); } //ok
  { bool b = static_cast<void (*)(char)>(g); } // expected-error{{not allowed}}

  { bool b = reinterpret_cast<void (&)(int)>(f); } // expected-error{{cannot resolve}}
  { bool b = reinterpret_cast<void (*)(int)>(f); } // expected-error{{cannot resolve}}

  { bool b = (int (&)(char))t; } // expected-error{{does not match}}
  { bool b = (int (*)(char))t; } // expected-error{{does not match}}

  { bool b = (void (&)(int))t; } //ok
  { bool b = (void (*)(int))t; } //ok

  { bool b = static_cast<void (&)(char)>(t); } //ok
  { bool b = static_cast<void (*)(char)>(t); } //ok

  { bool b = static_cast<void (&)(int)>(t); } //ok
  { bool b = static_cast<void (*)(int)>(t); } //ok

  { bool b = reinterpret_cast<void (&)(char)>(t); } // expected-error{{cannot resolve}}
  { bool b = reinterpret_cast<void (*)(char)>(t); } // expected-error{{cannot resolve}}

  { bool b = reinterpret_cast<int (*)(char)>(g); } //ok
  { bool b = static_cast<int (*)(char)>(t); } // expected-error{{cannot be static_cast}}
  { bool b = static_cast<int (&)(char)>(t); } // expected-error{{does not match required}}

  { bool b = static_cast<void (&)(char)>(f); } // expected-error{{does not match}}
}

Add missing test case for PR8230


//usr/bin/g++ "$0" -o /tmp/Rdtsc && exec /tmp/Rdtsc "$@"

/*
 * Copyright (c) 2015-2018 Agalmic Ventures LLC (www.agalmicventures.com)
 *
 * 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.
 */

#include <cstdint>
#include <cstdio>
#include <cstdlib>

static inline uint64_t rdtsc()
{
	uint64_t tsc;
	asm volatile (
		//A is EDX:EAX
		"rdtsc" : "=A" (tsc) : :
	);
	return tsc;
}

int main()
{
	uint64_t time = rdtsc();
	std::printf("%llu\n", time);
}

Add rdtsc snippet and wrapper script


#include "stdafx.h"
#include "engineBootstrap.hpp"
#include <catch/catch.hpp>

namespace Annwvyn
{
	class TestEvent : public AnnUserSpaceEvent
	{
	public:
		TestEvent(const std::string& message) : AnnUserSpaceEvent("TestEvent"),
			storedMessage(message)
		{
		}

		std::string getMessage() const { return storedMessage; }
	private:
		std::string storedMessage;
	};

	class TestSubSystem : public AnnUserSubSystem
	{
	public:
		TestSubSystem() : AnnUserSubSystem("Test Subsystem"),
			dispatchedYet(false)
		{
		}

		virtual ~TestSubSystem()
		{
		}

		bool needUpdate() override
		{
			return true;
		}

		void update() override
		{
			if (!dispatchedYet)
			{
				if (AnnGetEngine()->getTimeFromStartupSeconds() > 3)
				{
					dispatchEvent(std::make_shared<TestEvent>("Message!"));
					dispatchedYet = true;
				}
			}
		}

	private:
		bool dispatchedYet;
	};

	class TestListener : LISTENER
	{
	public:
		TestListener(bool& state) : constructListener(),
			hash(AnnGetStringUtility()->hash("TestEvent")),
			state(state)
		{}

		void EventFromUserSubsystem(AnnUserSpaceEvent& e, AnnUserSpaceEventLauncher* /*origin*/) override
		{
			if (e.getType() == hash)
			{
				AnnDebug() << "got message : " << static_cast<TestEvent&>(e).getMessage();
				state = true;
			}
		}
	private:
		AnnUserSpaceEvent::AnnUserSpaceEventTypeHash hash;
		bool& state;
	};

	TEST_CASE("Test register subsystem")
	{
		auto GameEngine = bootstrapTestEngine("UserSubSystemTest");
		auto testSystem = std::make_shared<TestSubSystem>();
		REQUIRE(testSystem);
		GameEngine->registerUserSubSystem(testSystem);
		REQUIRE(GameEngine->isUserSubSystem(testSystem));
	}

	TEST_CASE("Test user events")
	{
		auto GameEngine = bootstrapTestEngine("UserSubSystemTest");
		AnnGetOnScreenConsole()->setVisible(true);
		GameEngine->refresh();

		auto testSystem = std::make_shared<TestSubSystem>();
		REQUIRE(testSystem);
		GameEngine->registerUserSubSystem(testSystem);
		REQUIRE(GameEngine->isUserSubSystem(testSystem));

		auto state = false;
		auto testListener = std::make_shared<TestListener>(state);
		REQUIRE(testListener);
		AnnGetEventManager()->addListener(testListener);

		//TODO make reseting this timer easier
		AnnGetVRRenderer()->getTimer()->reset();

		while (GameEngine->getTimeFromStartupSeconds() < 6)
			GameEngine->refresh();

		REQUIRE(state);
	}
}

Add tests for the user defined subsystem interface²


#include <iostream>
#include <string>

using namespace std;

template <typename T>
void g(T &&val) {
    T t = val;
    t -= 1;//for test
    if(val == t) {
        cout << "T is reference" << endl;
    } else {
        cout << "T is not reference" << endl;
    }
}

template <typename T>
void g3(const T& val) {
    T t = val;
    t -= 1;//for test
    if(val == t) {
        cout << "T is reference" << endl;
    } else {
        cout << "T is not reference" << endl;
    }
}

int main() {
    //test 16.42
    int i  = 0;
    const int ci = i;
    g(i);// T is int&
//    g(ci);// T is const int &
    g(i * ci);//T is int
    g(i = ci);

    //test 16.44
    g3(i);
    g3(ci);
    g3(i * ci);
}

Add solution for chapter 16 test 42.


/**
 * Remove Element
 *
 * cpselvis(cpselvis@gmail.com)
 * August 24th, 2016
 */
#include<iostream>
#include<vector>

using namespace std;

class Solution {
public:
  int removeElement(vector<int>& nums, int val) {
    int i;
    for (i = 0; i < nums.size(); )
    {
      if (nums[i] == val)
      {
	nums.erase(nums.begin() + i);
      }
      else
      {
	i ++;
      }
    }
    return i;
  }
};

int main(int argc, char **argv)
{
  int arr[4] = {3, 2, 2, 3};

  vector<int> nums(arr + 0, arr + 4);
  Solution s;
  cout << s.removeElement(nums, 3) << endl;
}

Remove gived elements from vector.


#include <openssl/bn.h>
#include <openssl/ecdsa.h>
#include <openssl/ec.h>
#include <openssl/evp.h>
#include <openssl/err.h>

#include <stdio.h>

main() {
  EC_KEY *eckey;
  BN_CTX *ctx;

  ctx = BN_CTX_new();
  if(!ctx) {
    printf("failed to create bn ctx\n");
    return 1;
  }

  eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime192v3);
  if (eckey == NULL) {
    printf("failed to initialize curve\n");
    return 1;
  }
  if (EC_KEY_generate_key(eckey) == 0) {
    printf("failed to generate key\n");
    return 1;
  }

  printf("private key: %s\n", BN_bn2hex(EC_KEY_get0_private_key(eckey)));
  printf("public key: %s\n",
	 EC_POINT_point2hex(EC_KEY_get0_group(eckey),
			    EC_KEY_get0_public_key(eckey),
			    POINT_CONVERSION_COMPRESSED, ctx));
  BN_CTX_free(ctx);
  return 0;
}

Add simple function for printing some freshly generated keys.


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

// type_traits

// is_convertible

// Test the fallback implementation.

#define _LIBCPP_USE_IS_CONVERTIBLE_FALLBACK
#include "is_convertible.pass.cpp"

Add tests for library version of is_convertible


#include <unordered_map>
#include <iostream>

using namespace std;

int romanToInteger(const string& s) {
	unordered_map<char, int> T = {
		{ 'I', 1 },
		{ 'V', 5 },
		{ 'X', 10 },
		{ 'L', 50 },
		{ 'C', 100 },
		{ 'D', 500 },
		{ 'M', 1000 }
	};

	int sum = T[s.back()];
	for (int i = s.length() - 2; i >= 0; i--) {
		if (T[s[i]] < T[s[i + 1]]) {
			sum -= T[s[i]];
		} else {
			sum += T[s[i]];
		}
	}

	return sum;
}

int main() {
	string s;
	cin >> s;
	cout << romanToInteger(s) << endl;
	return 0;
}

Add conversion Roman numbers to integer value.


// 77. Combinations
/**
 * Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
 *
 * For example,
 * If n = 4 and k = 2, a solution is:
 *
 * [
 *   [2,4],
 *   [3,4],
 *   [2,3],
 *   [1,2],
 *   [1,3],
 *   [1,4],
 * ]
 *
 * Tags: Backtracking
 *
 * Similar Problems: (M) Combination Sum, (M) Permutations
 *
 * Author: Kuang Qin
 */

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

using namespace std;

class Solution {
    void backtrack(vector<vector<int>> &res, vector<int> &comb, int index, int n, int k) {
        if (k == comb.size())
        {
            // size == k, record results
            res.push_back(comb);
            return;
        }

        for (int i = index; i <= n; i++)
        {
            comb.push_back(i);
            backtrack(res, comb, i + 1, n, k);
            comb.pop_back();
        }

        return;
    }
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> res;
        if (n < 1 || k < 1)
        {
            return res;
        }

        vector<int> comb;
        backtrack(res, comb, 1, n, k);
        return res;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Solution mySolution;
    vector<vector<int>> res = mySolution.combine(4, 2);
    return 0;
}

Add Solution for Problem 077


/*
	This program tests soring algorithms defined in sort.h
*/

#include<iostream>
#include<vector>
#include "sort.h"	// My implementation of some sorting algorithms on std::vector of int

// Displays vector

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

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

// Tests insertion sort on vector A

void testInsertionSort(std::vector<int> A){

	std::cout<<"Before: ";
	printVector(A);
	insertionSort(A);
	std::cout<<"After: ";
	printVector(A);
}

// tests insertion sort on several different inputs

void testInsertionSort(){

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

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

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

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

	// test on empty vector
	std::vector<int> v5;
	testInsertionSort(v5);

	std::vector<int> v6 = {2,4,-6,1,-9,3,0};
	testInsertionSort(v6);

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

int main(){

	// test insertion sort
	testInsertionSort();

	return 0;
}

Add test case for insertion sort


// Test is line- and column-sensitive; see below.

namespace std {
  namespace rel_ops {
    void f();
  }
}

namespace std {
  void g();
}

// FIXME: using directives, namespace aliases

// RUN: c-index-test -test-load-source all %s | FileCheck %s
// CHECK: load-namespaces.cpp:3:11: Namespace=std:3:11 (Definition) Extent=[3:11 - 7:2]
// CHECK: load-namespaces.cpp:4:13: Namespace=rel_ops:4:13 (Definition) Extent=[4:13 - 6:4]
// CHECK: load-namespaces.cpp:5:10: FunctionDecl=f:5:10 Extent=[5:10 - 5:13]
// CHECK: load-namespaces.cpp:9:11: Namespace=std:9:11 (Definition) Extent=[9:11 - 11:2]
// CHECK: load-namespaces.cpp:10:8: FunctionDecl=g:10:8 Extent=[10:8 - 10:11]

Add a simple test for indexing namespaces


/**
 * 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 {
int presum=0;
public:
    TreeNode* convertBST(TreeNode* root) {
        inorder(root);
        return root;
    }
private:
    void inorder(TreeNode* root){
        if(!root) return;
        inorder(root->right);
        root->val+=presum;
        presum+=(root->val-presum);
        inorder(root->left);
    }
};

Convert BST to Greater Tree


class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int cur = 0, count = 0, total = nums.size();
        for (auto iter = nums.begin(); iter != nums.end();) {
            if (iter == nums.begin()) {
                cur = *iter;
                count = 1;
                ++iter;
            } else {
                if (*iter == cur) {
                    if (count == 2) {
                        nums.erase(iter);
                        --total;
                    } else {
                        ++count;
                        ++iter;
                    }
                } else {
                    cur = *iter;
                    count = 1;
                    ++iter;
                }
            }
        }
        return total;
    }
};

Remove Duplicates from Sorted Array II


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

typedef long long ll;

ll sol(ll n, int m) {
    ll a, b, c, d, r;
    a = 1; b = 0; c = 0; d = 1;
    while (n) {
        if (n&1) {
            r = ((d*b) + (c*a)) % m;
            b = (d*(b+a) + (c*b)) % m;
            a = r;
        }
        r = (c*c + d*d) % m;
        d = (d * (2*c + d)) % m;
        c = r;
        n >>= 1;
    }
    return (a+b) % m;
}

int main() {
    ll n;
    int b, r, c = 0;
    while (scanf("%lld %d", &n, &b) && (n || b)) {
        //r = ((sol(n, b) % b) + b) % b;
        r = (((2*sol(n, b) - 1) % b) + b) % b;
        printf("Case %d: %lld %d %d\n", ++c, n, b, r);
    }
    return 0;
}

Add quantas chamadas recursivas to cadernaveis


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

extern "C" {
#if defined(GLES2_CONFORM_SUPPORT_ONLY)
#include "gpu/gles2_conform_support/gtf/gtf_stubs.h"
#else
#include "third_party/gles2_conform/GTF_ES/glsl/GTF/Source/eglNative.h"
#endif

GTFbool GTFNativeCreatePixmap(EGLNativeDisplayType nativeDisplay,
                              EGLDisplay eglDisplay, EGLConfig eglConfig,
                              const char *title, int width, int height,
                              EGLNativePixmapType *pNativePixmap) {
  return GTFtrue;
}

void GTFNativeDestroyPixmap(EGLNativeDisplayType nativeDisplay,
                            EGLNativePixmapType nativePixmap) {
}

}  // extern "C"

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

extern "C" {
#if defined(GLES2_CONFORM_SUPPORT_ONLY)
#include "gpu/gles2_conform_support/gtf/gtf_stubs.h"
#else
#include "third_party/gles2_conform/GTF_ES/glsl/GTF/Source/eglNative.h"
#endif

GTFbool GTFNativeCreatePixmap(EGLNativeDisplayType nativeDisplay,
                              EGLDisplay eglDisplay, EGLConfig eglConfig,
                              const char *title, int width, int height,
                              EGLNativePixmapType *pNativePixmap) {
  return GTFtrue;
}

void GTFNativeDestroyPixmap(EGLNativeDisplayType nativeDisplay,
                            EGLNativePixmapType nativePixmap) {
}

EGLImageKHR GTFCreateEGLImageExternal(
    int width, int height, int format,
    float r, float g, float b, float a, void** resource) {
  return (EGLImageKHR)NULL;
}

void GTFDestroyEGLImageExternal(EGLImageKHR image, void* resource) {
}

const int* GTFQueryFormatsEGLImageExternal(void) {
  return NULL;
}

GTFbool GTFIsAlphaFormatEGLImageExternal(int format) {
  return GTFfalse;
}

}  // extern "C"

Add a few stubs so we can link the latest OpenGL ES 2.0 conformance tests


// Test on debug info to make sure that anon typedef info is emitted.
// RUN: %llvmgcc -S --emit-llvm -x c++ -g %s -o - | grep composite
typedef struct { int a; long b; } foo;
foo x;

Test case for llvm-gcc rev. 64648.


// test cases for rule CWE-611

#include "tests.h"

// ---

typedef unsigned int XMLCh;

class XMLUni
{
public:
	static const XMLCh fgXercesDisableDefaultEntityResolution[];
};

class SAX2XMLReader
{
public:
	void setFeature(const XMLCh *feature, bool value);
	void parse(const InputSource &data);
};

class XMLReaderFactory
{
public:
	static SAX2XMLReader *createXMLReader();
};

// ---

void test3_1(InputSource &data) {
	SAX2XMLReader *p = XMLReaderFactory::createXMLReader();

	p->parse(data); // BAD (parser not correctly configured) [NOT DETECTED]
}

void test3_2(InputSource &data) {
	SAX2XMLReader *p = XMLReaderFactory::createXMLReader();

	p->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true);
	p->parse(data); // GOOD
}

SAX2XMLReader *p_3_3 = XMLReaderFactory::createXMLReader();

void test3_3(InputSource &data) {
	p_3_3->parse(data); // BAD (parser not correctly configured) [NOT DETECTED]
}

SAX2XMLReader *p_3_4 = XMLReaderFactory::createXMLReader();

void test3_4(InputSource &data) {
	p_3_4->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true);
	p_3_4->parse(data); // GOOD
}

SAX2XMLReader *p_3_5 = XMLReaderFactory::createXMLReader();

void test3_5_init() {
	p_3_5->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true);
}

void test3_5(InputSource &data) {
	test3_5_init();
	p_3_5->parse(data); // GOOD
}

Add test cases for SAX2XMLReader.


/*
 * isr.c:
 *	Wait for Interrupt test program - ISR method
 *
 *	How to test:
 *	  Use the SoC's pull-up and pull down resistors that are avalable
 *	on input pins. So compile & run this program (via sudo), then
 *	in another terminal:
 *		gpio mode 0 up
 *		gpio mode 0 down
 *	at which point it should trigger an interrupt. Toggle the pin
 *	up/down to generate more interrupts to test.
 *
 * Copyright (c) 2013 Gordon Henderson.
 ***********************************************************************
 * This file is part of wiringPi:
 *	https://projects.drogon.net/raspberry-pi/wiringpi/
 *
 *    wiringPi is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    wiringPi is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with wiringPi.  If not, see <http://www.gnu.org/licenses/>.
 ***********************************************************************
 */

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <wiringPi.h>

// What GPIO input are we using?
//	This is a wiringPi pin number

#define	BUTTON_PIN	0

// globalCounter:
//	Global variable to count interrupts
//	Should be declared volatile to make sure the compiler doesn't cache it.

static volatile int globalCounter = 0 ;

void fallingEdge(void)
{
    ++globalCounter ;
    fprintf("fallingEdge, %d\n", globalCounter);
}

/*
 *********************************************************************************
 * main
 *********************************************************************************
 */

int main (void)
{
    int myCounter = 0 ;

    if (wiringPiSetup () < 0)
    {
        fprintf (stderr, "Unable to setup wiringPi: %s\n", strerror (errno)) ;
        return 1 ;
    }

    // Set the button pin to input mode
    pinMode(BUTTON_PIN, INPUT);
    // Set the pull up resistor to up to fix it at 3.3V so it reads high until button is pressed
    pullUpDnControl(BUTTON_PIN, PUD_UP);

    // Register the interrupt callback function
    if (wiringPiISR (BUTTON_PIN, INT_EDGE_FALLING, &fallingEdge) < 0) {
        fprintf (stderr, "Unable to setup ISR: %s\n", strerror (errno)) ;
        return 1 ;
    }

    for (;;)
    {
        printf ("Waiting ... ") ; fflush (stdout) ;

        while (myCounter == globalCounter)
            delay (100) ;

        printf (" Done. counter: %5d\n", globalCounter) ;
        myCounter = globalCounter ;
    }

    return 0 ;
}

Add a pin interrupt test


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

using namespace Halide;

// FIXME: We should use a proper framework for this. See issue #898
void h_assert(bool condition, const char *msg) {
    if (!condition) {
        printf("FAIL: %s\n", msg);
        abort();
    }
}

int main() {
    Halide::Func f;
    Halide::Var x, y;

    // Function mixes type, the float16_t should be implicitly upcast
    // to a float
    f(x, y) = 0.25f + float16_t(0.75);

    // Use JIT for computation
    Image<float> simple = f.realize(10, 3);

    // Assert some basic properties of the image
    h_assert(simple.extent(0) == 10, "invalid width");
    h_assert(simple.extent(1) == 3, "invalid height");
    h_assert(simple.min(0) == 0, "unexpected non zero min in x");
    h_assert(simple.min(1) == 0, "unexpected non zero min in y");
    h_assert(simple.channels() == 1, "invalid channels");
    h_assert(simple.dimensions() == 2, "invalid number of dimensions");

    // Read result back
    for (int x = simple.min(0); x < simple.extent(0); ++x) {
        for (int y = simple.min(1); y < simple.extent(1); ++y) {
            h_assert(simple(x, y) == 1.0f, "Invalid value read back");
        }
    }
    printf("Success!\n");
    return 0;
}

Add test to check implicit upcasting of float16_t works.


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

#include <unistd.h>

#include "base/sys_info.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace base {
namespace android {

TEST(SysUtils, AmountOfPhysicalMemory) {
  // Check that the RAM size reported by sysconf() matches the one
  // computed by base::SysInfo::AmountOfPhysicalMemory().
  size_t sys_ram_size =
      static_cast<size_t>(sysconf(_SC_PHYS_PAGES) * PAGE_SIZE);
  EXPECT_EQ(sys_ram_size, SysInfo::AmountOfPhysicalMemory());
}

}  // namespace android
}  // namespace base

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

#include <unistd.h>

#include "base/sys_info.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace base {
namespace android {

TEST(SysUtils, AmountOfPhysicalMemory) {
  // Check that the RAM size reported by sysconf() matches the one
  // computed by base::SysInfo::AmountOfPhysicalMemory().
  size_t sys_ram_size =
      static_cast<size_t>(sysconf(_SC_PHYS_PAGES) * PAGE_SIZE);
  EXPECT_EQ(sys_ram_size,
            static_cast<size_t>(SysInfo::AmountOfPhysicalMemory()));
}

}  // namespace android
}  // namespace base

Fix comparison between signed and unsigned integer expressions.


#include <common/buffer.h>

#include <event/action.h>
#include <event/callback.h>
#include <event/event.h>
#include <event/event_system.h>

Action *
Callback::schedule(void)
{
	return (EventSystem::instance()->schedule(this));
}

Add file missed in r574.


#include <stdio.h>

int main(void)
{
    int sum = 0, count = 0;

    do
    {
        int num;

        printf("Enter the num= ");
        scanf("%d", &num);

        sum += (++count % 2 == 1) ? num : -num;
    }
    while(sum != 0);

    printf("Result: %d\n", count);

    return 0;
}

Add a solution of prob 1


#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>

#define FPGA_MANAGER_BASE 0xFF706000
#define FPGA_GPO_OFFSET 0x10
#define FPGA_GPI_OFFSET 0x14

int main()
{
    int dev_mem = open("/dev/mem", O_RDWR);

    if(dev_mem == 0) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    unsigned char *mem = (unsigned char *)mmap(0, 64, PROT_READ | PROT_WRITE, /* MAP_NOCACHE | */ MAP_SHARED , dev_mem, FPGA_MANAGER_BASE);

    if(mem == 0) {
        perror("mmap");
        exit(EXIT_FAILURE);
    }

    volatile unsigned long *gpo = (unsigned long*)(mem + FPGA_GPO_OFFSET);
    volatile unsigned long *gpi = (unsigned long*)(mem + FPGA_GPI_OFFSET);

    printf("gpi = 0x%08lX\n", *gpi);
    *gpo = 0xCAFEBABE;

    if(1) {
        long int i = 0;
        while(1) *gpo = i++;
    }

    exit(EXIT_SUCCESS);
}

Add ARM-to-FPGA 32-bit raw I/O example


/**
 * Copyright (c) 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <getopt.h>

#include "DexCommon.h"

void print_usage() {
  fprintf(stderr, "Usage: dexgrep <classname> <dexfile 1> <dexfile 2> ...\n");
}

int main(int argc, char* argv[]) {
  bool files_only = false;
  char c;
  static const struct option options[] = {
    { "files-without-match", no_argument, nullptr, 'l' },
  };
  while ((c = getopt_long(
            argc,
            argv,
            "hl",
            &options[0],
            nullptr)) != -1) {
    switch (c) {
      case 'l':
        files_only = true;
        break;
      case 'h':
        print_usage();
        return 0;
      default:
        print_usage();
        return 1;
    }
  }

  if (optind == argc) {
    fprintf(stderr, "%s: no dex files given\n", argv[0]);
    print_usage();
    return 1;
  }

  const char* search_str = argv[optind];

  for (int i = optind + 1; i < argc; ++i) {
    const char* dexfile = argv[i];
    ddump_data rd;
    open_dex_file(dexfile, &rd);

    auto size = rd.dexh->class_defs_size;
    for (uint32_t j = 0; j < size; j++) {
      dex_class_def* cls_def = rd.dex_class_defs + j;
      char* name = dex_string_by_type_idx(&rd, cls_def->typeidx);
      if (strstr(name, search_str) != nullptr) {
        if (files_only) {
          printf("%s\n", dexfile);
        } else {
          printf("%s: %s\n", dexfile, name);
        }
      }
    }
  }
}

Add dexgrep tool -- grep for class definitions


// Chapter 21, Try This 3: define a vector<Record>, initialise it with four
// records of your choice, and compute their total price using the functions
// given

#include "../lib_files/std_lib_facilities.h"
#include<numeric>

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

struct Record {
    Record(double up, int un) : unit_price(up), units(un) { }
    double unit_price;
    int units;  // number of units sold
};

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

double price(double v, const Record& r)
{
    return v + r.unit_price * r.units;  // calculate price and accumulate
}

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

void f(const vector<Record>& vr)
{
    double total = accumulate(vr.begin(),vr.end(),0.0,price);
    cout << "Total is " << total << "\n";
}

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

int main()
try {
    Record rec1 = Record(10.9,15);
    Record rec2 = Record(25.5,3);
    Record rec3 = Record(101,75);
    Record rec4 = Record(5.33,27);
    vector<Record> vr;
    vr.push_back(rec1);
    vr.push_back(rec2);
    vr.push_back(rec3);
    vr.push_back(rec4);
    f(vr);
}
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, Try This 3


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

#include <ews/ews.hpp>
#include <ews/ews_test_support.hpp>
#include <exception>
#include <iostream>
#include <ostream>
#include <stdlib.h>
#include <string>

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

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

        ews::distinguished_folder_id inbox = ews::standard_folder::inbox;
        ews::distinguished_folder_id trash =
            ews::standard_folder::deleted_items;

        auto folder_ids = service.find_folder(inbox);
        if (!folder_ids.empty())
        {
            // Move the first folder to the deleted items folder
            auto new_id = service.move_folder(folder_ids.front(), trash);

            // Move the folder back to the inbox,
            // using the newly created folder id
            service.move_folder(new_id, inbox);
        }
    }
    catch (std::exception& exc)
    {
        std::cout << exc.what() << std::endl;
        res = EXIT_FAILURE;
    }

    ews::tear_down();
    return res;
}

Add example for MoveFolder operation


// Chapter 25, exercise 10: write an example that initializes a PPN, then reads
// and prints each field value, then changes each field value (by assigning to
// the field) and prints the result. Repeat, but store the PPN information in a
// 32-bit unsigned integer and use bit manipulation operators to access the bits
// in the word.

#include<iostream>

using namespace std;

struct PPN {
    unsigned int PFN : 22;
    int : 3;
    unsigned int CCA : 3;
    bool nonreachable : 1;
    bool dirty : 1;
    bool valid : 1;
    bool global : 1;
};

int main()
{
    PPN pn;
    pn.PFN = 0;
    pn.CCA = 0;
    pn.nonreachable = 0;
    pn.dirty = 0;
    pn.valid = 0;
    pn.global = 0;
    cout << "PFN: " << pn.PFN << '\n'
        << "CCA: " << pn.CCA << '\n'
        << "nonreachable: " << pn.nonreachable << '\n'
        << "dirty: " << pn.dirty << '\n'
        << "valid: " << pn.valid << '\n'
        << "global: " << pn.global << '\n';
    pn.PFN = 15121;
    pn.CCA = 6;
    pn.nonreachable = 1;
    pn.dirty = 0;
    pn.valid = 0;
    pn.global = 1;
        cout << "\nAfter changing values:\n"
        << "PFN: " << pn.PFN << '\n'
        << "CCA: " << pn.CCA << '\n'
        << "nonreachable: " << pn.nonreachable << '\n'
        << "dirty: " << pn.dirty << '\n'
        << "valid: " << pn.valid << '\n'
        << "global: " << pn.global << '\n';

    unsigned int pni = 0;
    pni = 15121<<10;    // PFN
    pni |= 6<<4;        // CCA
    pni |= 1<<3;        // nonreachable
    pni |= 1;           // global
    cout << "\nUsing an unsigned int:\n"
        << "PFN: " << ((pni>>10)&0x3fffff) << '\n'
        << "CCA: " << ((pni>>4)&0x7) << '\n'
        << "nonreachable: " << ((pni>>3)&1) << '\n'
        << "dirty: " << ((pni>>2)&1) << '\n'
        << "valid: " << ((pni>>1)&1) << '\n'
        << "global: " << (pni&1) << '\n';
}

Add Chapter 25, exercise 10


/**
 * Floyd Warshall's Algorithm for All Pairs shortest path problem
 */
 #include <iostream>
 #include <limits.h>
 #define V 4
 #define INF INT_MAX
 using namespace std;

void print(int array[][V]) {
 	for (int i = 0; i < V; i++) {
 		for (int j = 0; j < V; j++) {
 			if (array[i][j] == INF)
 				cout<<"INF ";
 			else
 				cout<<array[i][j]<<" ";
 		}
 		cout<<endl;
 	}
 }

 void floyd_warshall(int graph[][V]) {
 	int dist[V][V], i, j, k;

 	for (i = 0; i < V; i++)
 		for(j = 0; j < V; j++)
 			dist[i][j] = graph[i][j];

 	for (k = 0; k < V; k++) {
 		for (j = 0; j < V; j++) {
 			for (i = 0; i < V; i++) {
 				if (dist[i][k] != INF && dist[k][j] != INF && dist[i][k] + dist[k][j] < dist[i][j])
 					dist[i][j] = dist[i][k] + dist[k][j];
 			}
 		}
 	}
 	print(dist);
 }

 int main() {
 	int graph[][V] = { {0,   5,  INF, 10},
                        {INF, 0,   3, INF},
                        {INF, INF, 0,   1},
                        {INF, INF, INF, 0}
                  	  };
    cout<<"Input Graph: \n";
    print(graph);
    cout<<"Solution: \n";
    floyd_warshall(graph);
    return 0;
}

Add floyd warshall all pairs shortest path


/*
 * Summation of primes
 *
 * The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
 *
 * Find the sum of all the primes below two million.
 */

#include <iostream>
#include <numeric>
#include <vector>

#include "sieve.hpp"

constexpr Long limit = 2'000'000;

int main(int, char **) {
    auto primes = sieve(limit - 1);
    auto sum = std::accumulate(primes.begin(), primes.end(), Long());

    std::cout << "Project Euler - Problem 10: Summation of primes\n\n";
    std::cout << "The sum of all prime numbers below " << limit << " is\n"
              << sum << '\n';
}

Add solution to problem 10.


#include <bits/stdc++.h>

using namespace std;

void merge(vector<int>& v, int beg1, int half, int beg2){
    int szL, szR;
    szL = half-beg1+1;
    szR = beg2-half;
    //create auxiliar arrays;
    int left[szL], right[szR];
    for (int i = 0; i < szL; i++)
        left[i] = v[beg1 + i];
    for (int i = 0; i < szR; i++)
        right[i] = v[half + 1 + i];
    //merge aux into v
    int i= 0, j= 0, k= beg1;
    while (i<szL && j<szR)
        v[k++] = (left[i]<right[j])?left[i++]:right[j++];
    while (i < szL)
        v[k++] = left[i++];
    while (j < szR)
        v[k++] = right[j++];
}

void mergeSort(vector<int>& v, int l, int r){
    if (l >= r)
        return;
    int half = l+(r-l)/2;
    mergeSort(v, l, half);
    mergeSort(v, half+1, r);

    merge(v, l, half, r);
}

Add merge sort c++ source code


#include "data.hpp"
#include "graph.hpp"
#include "dag_loop.hpp"
#include <string>
#include <vector>

// We will need two bfs operations to check that there is a path from node A to node B.
namespace graph {
    namespace algorithms {
    } // namespace algorithms

    template <typename Graph>
    bool detect_loop(Graph & g) {
        g.print();
        using graph_type = Graph;
        using Policy = graph::algorithms::BasicPolicy<graph_type>;
        graph::algorithms::LoopDetector<Policy> dfs(g);
        return dfs.traverse();
    }

} // namespace graph

int main() {
    // Has loop
    auto g1 = experiments::directed_graph_with_loop();
    fmt::print("The given graph {}\n", (graph::detect_loop<decltype(g1)>(g1) ? "has a cycle." : "is DAG."));

    // Does not have loop
    auto g2 = experiments::directed_graph();
    fmt::print("The given graph {}\n", graph::detect_loop(g2) ? "has loop." : "is DAG.");
}

Add a DQG cycle detection algorithm.


class Solution {
public:
    bool isSumEqual(string firstWord, string secondWord, string targetWord) {
        return (convert(firstWord) + convert(secondWord)) == convert(targetWord);
    }
private:
    int convert(std::string word) {
        int ret = 0, index = 0;
        while (index < word.size() && word[index] == '0') {
            ++index;
        }
        while (index < word.size()) {
            ret *= 10;
            ret += word[index] - 'a';
            ++index;
        }
        return ret;
    }
};

Check if Word Equals Summation of Two Words


// 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 "content/child/file_info_util.h"

#include "base/logging.h"
#include "third_party/WebKit/public/platform/WebFileInfo.h"

namespace content {

void FileInfoToWebFileInfo(const base::File::Info& file_info,
                           blink::WebFileInfo* web_file_info) {
  DCHECK(web_file_info);
  // Blink now expects NaN as uninitialized/null Date.
  if (file_info.last_modified.is_null()) {
    web_file_info->modificationTime = std::numeric_limits<double>::quiet_NaN();
    web_file_info->modificationTimeMS =
        std::numeric_limits<double>::quiet_NaN();
  } else {
    web_file_info->modificationTime = file_info.last_modified.ToJsTime();
    web_file_info->modificationTimeMS = file_info.last_modified.ToJsTime();
  }
  web_file_info->length = file_info.size;
  if (file_info.is_directory)
    web_file_info->type = blink::WebFileInfo::TypeDirectory;
  else
    web_file_info->type = blink::WebFileInfo::TypeFile;
}

static_assert(std::numeric_limits<double>::has_quiet_NaN,
              "should have quiet NaN");

}  // namespace content

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

#include "content/child/file_info_util.h"

#include "base/logging.h"
#include "third_party/WebKit/public/platform/WebFileInfo.h"

namespace content {

void FileInfoToWebFileInfo(const base::File::Info& file_info,
                           blink::WebFileInfo* web_file_info) {
  DCHECK(web_file_info);
  // Blink now expects NaN as uninitialized/null Date.
  if (file_info.last_modified.is_null())
    web_file_info->modificationTime = std::numeric_limits<double>::quiet_NaN();
  else
    web_file_info->modificationTime = file_info.last_modified.ToJsTime();
  web_file_info->length = file_info.size;
  if (file_info.is_directory)
    web_file_info->type = blink::WebFileInfo::TypeDirectory;
  else
    web_file_info->type = blink::WebFileInfo::TypeFile;
}

static_assert(std::numeric_limits<double>::has_quiet_NaN,
              "should have quiet NaN");

}  // namespace content

Upgrade Blink to milliseconds-based last modified filetimes, part 6.


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

#include <deque>

#include "dll_test.hpp"

#include "dll/neural/conv_layer.hpp"
#include "dll/neural/deconv_layer.hpp"
#include "dll/pooling/mp_layer.hpp"
#include "dll/pooling/upsample_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/trainer/stochastic_gradient_descent.hpp"

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

TEST_CASE("conv/ae/1", "[dense][dbn][mnist][sgd][ae]") {
    typedef dll::dbn_desc<
        dll::dbn_layers<
            dll::conv_desc<1, 28, 28, 2, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t,
            dll::mp_layer_3d_desc<2, 24, 24, 1, 2, 2>::layer_t,
            dll::upsample_layer_3d_desc<2, 12, 12, 1, 2, 2>::layer_t,
            dll::deconv_desc<2, 24, 24, 1, 5, 5, dll::activation<dll::function::SIGMOID>>::layer_t
        >, dll::trainer<dll::sgd_trainer>, dll::batch_size<20>>::dbn_t dbn_t;

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

    dll_test::mnist_scale(dataset);

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

    dbn->display();

    dbn->learning_rate = 0.1;

    auto ft_error = dbn->fine_tune_ae(dataset.training_images, 25);
    std::cout << "ft_error:" << ft_error << std::endl;

    CHECK(ft_error < 0.3);

    auto test_error = dll::test_set_ae(*dbn, dataset.test_images);
    std::cout << "test_error:" << test_error << std::endl;
    REQUIRE(test_error < 0.3);
}

Add convolutional auto encoder unit test


//Some useful equations
int main(){
  //area portion of a circle
  A = pi*r^2 * (theta/(2*pi))
  //area chord of a circle
  A = R * R * acos((R - h)/R) - (R - h) * sqrt(2 * R * h - h * h)
    // h is the height of the chord

}

Add some useful ecuations over a circle.


#include <osgDB/ImageOptions>

using namespace osgDB;

ImageOptions::ImageOptions()
{
    init();
}

ImageOptions::ImageOptions(const std::string& str)
{
    init();
    _str = str;
}

void ImageOptions::init()
{
    _sourceImageSamplingMode = NEAREST;
    _sourceImageWindowMode = ALL_IMAGE;

    _destinationImageWindowMode = ALL_IMAGE;
}

#include <osgDB/ImageOptions>

using namespace osgDB;

ImageOptions::ImageOptions()
{
    init();
}

ImageOptions::ImageOptions(const std::string& str)
{
    init();
    _str = str;
}

void ImageOptions::init()
{
    _sourceImageSamplingMode = NEAREST;
    _sourceImageWindowMode = ALL_IMAGE;

    _destinationImageWindowMode = ALL_IMAGE;

    _destinationDataType = GL_NONE;
    _destinationPixelFormat = GL_NONE;
}

Set default values for datatype & pixelformat.


#include "fastlib/fastlib.h"
#include "fastlib/tree/statistic.h"
#include "general_spacetree.h"
#include "contrib/dongryel/fast_multipole_method/fmm_stat.h"
#include "subspace_stat.h"
#include "cfmm_tree.h"
#include "mlpack/kde/dataset_scaler.h"

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

  fx_init(argc, argv, NULL);

  const char *fname = fx_param_str_req(NULL, "data");
  Matrix dataset;
  data::Load(fname, &dataset);

  int leaflen = fx_param_int(NULL, "leaflen", 30);
  int min_required_ws_index = fx_param_int(NULL, "min_ws_index", 2);

  printf("Constructing the tree...\n");
  fx_timer_start(NULL, "cfmm_tree_build");

  ArrayList<Matrix *> matrices;
  matrices.Init(1);
  matrices[0] = &dataset;

  ArrayList<Vector *> targets;
  const char *target_fname = fx_param_str_req(NULL, "target");

  Matrix target_incoming;

  data::Load(target_fname, &target_incoming);

  Vector target;
  target.Init(target_incoming.n_cols());

  for(index_t i = 0; i < target.length(); i++) {
    target[i] = target_incoming.get(0, i);
  }
  targets.Init(1);
  targets[0] = ⌖

  ArrayList< ArrayList<index_t> > old_from_new;
  ArrayList< ArrayList<proximity::CFmmTree< EmptyStatistic<Matrix> > *> > nodes_in_each_level;
  proximity::CFmmTree<EmptyStatistic<Matrix> > *root;
  root = proximity::MakeCFmmTree
    (matrices, targets, leaflen, min_required_ws_index, 2,
     &nodes_in_each_level, &old_from_new);

  fx_timer_stop(NULL, "cfmm_tree_build");

  for(index_t i = 0; i < nodes_in_each_level.size(); i++) {
    for(index_t j = 0; j < nodes_in_each_level[i].size(); j++) {
      printf("%u ", (nodes_in_each_level[i][j])->node_index());
    }
    printf("\n");
  }

  printf("Finished constructing the tree...\n");

  // Print the tree.
  root->Print();

  // Clean up the memory used by the tree...
  delete root;

  fx_done(fx_root);
  return 0;
}

Test file for CFMM tree added.


#include "gtest/gtest.h"

#include <typeinfo>

#include "request_message.h"
#include "requests.pb.h"

class TypeVisitor : public traffic::RequestVisitor
{
public:
	enum Type {
		SUMMARY,
		STATISTIC,
		ERROR,
		NOTSET
	};

private:
	Type _t;

protected:
	void visit(traffic::StatisticRequest const &) { _t = STATISTIC; }
	void visit(traffic::SummaryRequest const &) { _t = SUMMARY; }
	void visit(traffic::ErrorRequest const &) { _t = ERROR; }

public:
	TypeVisitor() : _t(NOTSET) { }

	Type visited() const { return _t; }
};

std::string summary_message()
{
	requests::Request req;
	req.set_version(1);

	requests::Summary *summary(req.mutable_summary());
	summary->mutable_range()->set_start(1UL);
	summary->mutable_range()->set_end(2UL);

	summary->add_addresses("peng1");
	summary->add_addresses("peng2");
	summary->add_addresses("peng3");
	summary->add_addresses("peng4");

	return req.SerializeAsString();
}

// Test that basic message serializing work
TEST(MessagesRequest, deserialize_summary_request) {
	std::string bytes(summary_message());

	traffic::RequestMessage::ptr_t msg(
			traffic::RequestMessage::parse_message(bytes.c_str(),
							       bytes.size()));

	ASSERT_EQ(typeid(traffic::SummaryRequest), typeid(*msg));

	TypeVisitor v;
	msg->accept(v);
	ASSERT_EQ(TypeVisitor::SUMMARY, v.visited());

	traffic::SummaryRequest* summary(dynamic_cast<traffic::SummaryRequest*>(msg.get()));

	ASSERT_NE(nullptr, summary);
	EXPECT_EQ(1, summary->range().start());
	EXPECT_EQ(2, summary->range().end());

	ASSERT_EQ(4U, summary->addresses().size());
	EXPECT_EQ("peng1", summary->addresses().at(0));
	EXPECT_EQ("peng2", summary->addresses().at(1));
	EXPECT_EQ("peng3", summary->addresses().at(2));
	EXPECT_EQ("peng4", summary->addresses().at(3));

}

/**
 * Shut down the protobuf library after the tests to make valgrind happy
 */
namespace {

class ShutdownEnvironment : public ::testing::Environment
{
public:
	void TearDown()
	{
		google::protobuf::ShutdownProtobufLibrary();
	}
};

#ifndef NDEBUG
::testing::Environment* const shutdown_env =
	::testing::AddGlobalTestEnvironment(new ShutdownEnvironment);
#endif
}

Add unittests for summary requests


/**
 * 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* sortedArrayToBST(vector<int>& nums) {
        return recur(nums, 0, nums.size()-1);
    }
private:
    TreeNode* recur(std::vector<int>& nums, int begin, int end) {
        if (begin > end) {
            return nullptr;
        }
        int mid = (begin + end) / 2;
        TreeNode* root = new TreeNode{nums[mid]};
        root->left = recur(nums, begin, mid-1);
        root->right = recur(nums, mid+1, end);
        return root;
    }
};

Convert Sorted Array to Binary Search Tree


#if defined(HAVE_CAIRO)
#include "catch.hpp"

#include <mapnik/map.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/cairo/cairo_renderer.hpp>

#include <sstream>

#include <cairo-pdf.h>

static cairo_status_t write(
	void *closure,
    const unsigned char *data,
    unsigned int length)
{
	std::ostream & ss = *static_cast<std::ostream*>(closure);
	ss.write(reinterpret_cast<char const *>(data), length);
    return ss ? CAIRO_STATUS_SUCCESS : CAIRO_STATUS_WRITE_ERROR;
}

static void render(std::ostream & output, bool text_outlines)
{
    const std::string map_style = R"STYLE(
<Map>
    <Style name="1">
        <Rule>
            <TextSymbolizer
                placement="point"
                face-name="DejaVu Sans Book"
                >
                "Text"
            </TextSymbolizer>
        </Rule>
    </Style>
    <Layer name="1">
        <StyleName>1</StyleName>
        <Datasource>
            <Parameter name="type">csv</Parameter>
            <Parameter name="inline">
			x, y
			0, 0
			</Parameter>
        </Datasource>
    </Layer>
</Map>
    )STYLE";

	mapnik::Map map(256, 256);
	mapnik::load_map_string(map, map_style);

    const std::string fontdir("fonts");
    REQUIRE(map.register_fonts(fontdir, true));

    const mapnik::box2d<double> bbox(-1, -1, 1, 1);
	map.zoom_to_box(bbox);

    mapnik::cairo_surface_ptr surface(
        // It would be better to use script surface,
        // but it's not included in the Mason Cairo library.
        cairo_pdf_surface_create_for_stream(
            write, &output, map.width(), map.height()),
        mapnik::cairo_surface_closer());
    mapnik::cairo_ptr image_context(
        mapnik::create_context(surface));
    mapnik::cairo_renderer<mapnik::cairo_ptr> ren(
        map, image_context, 1.0, 0, 0, text_outlines);
    ren.apply();
    cairo_surface_finish(&*surface);
}

TEST_CASE("cairo_renderer") {

SECTION("text_outlines") {

    {
        std::stringstream output;
        render(output, true);

        // Output should not contain any fonts
        CHECK(output.str().find("/Font") == std::string::npos);
    }

    {
        std::stringstream output;
        render(output, false);

        // Check fonts are there if text_outlines == false
        CHECK(output.str().find("/Font") != std::string::npos);
    }
}

}

#endif

Test of rendering text as outlines


#include "gtest/gtest.h"

#include "src/common/entity/Block.h"
#include "src/common/entity/Bomb.h"
#include "src/common/entity/Bonus.h"
#include "src/common/entity/Character.h"
#include "src/common/entity/Fire.h"
#include "src/common/entity/Wall.h"
#include "src/common/net/Deserializer.h"

using namespace common::entity;
using namespace common::net;

TEST(EntitySerializationTest, Serialization) {
  QByteArray buffer;
  QDataStream in(&buffer, QIODevice::OpenModeFlag::WriteOnly);
  QDataStream out(&buffer, QIODevice::OpenModeFlag::ReadOnly);

  Block block(QPoint(1,2));
  in << block;
  auto block_out = Deserializer::DeserializeEntity(out);
  EXPECT_EQ(block, *static_cast<Block*>(block_out.get()));

  Bomb bomb(QPoint(3,4), 123, 456, 2);
  in << bomb;
  auto bomb_out = Deserializer::DeserializeEntity(out);
  EXPECT_EQ(bomb, *static_cast<Bomb*>(bomb_out.get()));

  Bonus bonus(QPoint(1,2));
  in << bonus;
  auto bonus_out = Deserializer::DeserializeEntity(out);
  EXPECT_EQ(bonus, *static_cast<Bonus*>(bonus_out.get()));

  Character character(QPoint(5,4), 2, 5, 3);
  in << character;
  auto character_out = Deserializer::DeserializeEntity(out);
  EXPECT_EQ(character, *static_cast<Character*>(character_out.get()));

  Fire fire(QPoint(8,9), 456);
  in << fire;
  auto fire_out = Deserializer::DeserializeEntity(out);
  EXPECT_EQ(fire, *static_cast<Fire*>(fire_out.get()));

  Wall wall(QPoint(5,4));
  in << wall;
  auto wall_out = Deserializer::DeserializeEntity(out);
  EXPECT_EQ(wall, *static_cast<Wall*>(wall_out.get()));
}

Add serialization tests for entities.


/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     RandomListNode *next, *random;
 *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 * };
 */
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        if(!head) return NULL;
        unordered_map<RandomListNode*, RandomListNode*> m;
        RandomListNode *cur=head;
        RandomListNode *newhead=new RandomListNode(head->label);
        RandomListNode *newh=newhead;
        m[cur]=newh;
        while(cur->next){
            cur=cur->next;
            newh->next=new RandomListNode(cur->label);
            m[cur]=newh->next;
            newh=newh->next;
        }
        cur=head;
        newh=newhead;
        while(cur){
            if(cur->random==NULL){
                newh->random=NULL;
            }else{
                newh->random=m[cur->random];
            }
            cur=cur->next;
            newh=newh->next;
        }
        return newhead;
    }
};

Copy List with Random Pointer


#include <bits/stdc++.h>

using namespace std;

int main(){
  string needle = "CD", haystack ="MANICD";
  if(haystack.find(needle) != string::npos) cout << "Gotcha!!!";
  else cout << "Not Gotcha";
  cout << endl;
  return 0;
}

Add Naive find over strings.


#include "stdafx.h"
#include "CppUnitTest.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;

namespace You {
namespace DataStore {
namespace UnitTests {
TEST_CLASS(DataStoreApiTest) {
public:
	//TEST_METHOD(TestMethod1) {
	//	// TODO: Your test code here
	//}

};

}  // namespace UnitTests
}  // namespace DataStore
}  // namespace You

Create unit test file for datastore api


/* Copyright 2020 Sergei Bastrakov
 *
 * This file is part of alpaka.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <alpaka/acc/AccDevProps.hpp>
#include <alpaka/acc/Traits.hpp>

#include <alpaka/test/acc/TestAccs.hpp>

#include <catch2/catch.hpp>

//-----------------------------------------------------------------------------
TEMPLATE_LIST_TEST_CASE( "getAccDevProps", "[acc]", alpaka::test::acc::TestAccs)
{
    using Acc = TestType;
    using Dev = alpaka::dev::Dev<Acc>;
    using Pltf = alpaka::pltf::Pltf<Dev>;
    Dev const dev(alpaka::pltf::getDevByIdx<Pltf>(0u));
    auto const devProps = alpaka::acc::getAccDevProps<Acc>(dev);

    REQUIRE(devProps.m_gridBlockExtentMax.prod() > 0);
    // Note: this causes signed overflow for some configurations,
    // will be fixed separately
    // REQUIRE(devProps.m_blockThreadExtentMax.prod() > 0);
    REQUIRE(devProps.m_threadElemExtentMax.prod() > 0);
    REQUIRE(devProps.m_gridBlockCountMax > 0);
    REQUIRE(devProps.m_blockThreadCountMax > 0);
    REQUIRE(devProps.m_threadElemCountMax > 0);
    REQUIRE(devProps.m_multiProcessorCount > 0);
    REQUIRE(devProps.m_sharedMemSizeBytes > 0);
}

Add unit test for acc::getAccDevProps


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

#include "chrome/test/webdriver/commands/response.h"

#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/values.h"

namespace webdriver {

namespace {

// Error message taken from:
// http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes
const char* const kStatusKey = "status";
const char* const kValueKey = "value";
const char* const kMessageKey = "message";
const char* const kScreenKey = "screen";
const char* const kClassKey = "class";
const char* const kStackTraceFileNameKey = "stackTrace.fileName";
const char* const kStackTraceLineNumberKey = "stackTrace.lineNumber";

}  // namespace

Response::Response() {
  SetStatus(kSuccess);
  SetValue(Value::CreateNullValue());
}

Response::~Response() {}

ErrorCode Response::GetStatus() const {
  int status;
  if (!data_.GetInteger(kStatusKey, &status))
    NOTREACHED();
  return static_cast<ErrorCode>(status);
}

void Response::SetStatus(ErrorCode status) {
  data_.SetInteger(kStatusKey, status);
}

const Value* Response::GetValue() const {
  Value* out = NULL;
  LOG_IF(WARNING, !data_.Get(kValueKey, &out))
      << "Accessing unset response value.";  // Should never happen.
  return out;
}

void Response::SetValue(Value* value) {
  data_.Set(kValueKey, value);
}

void Response::SetError(ErrorCode error_code, const std::string& message,
                        const std::string& file, int line) {
  DictionaryValue* error = new DictionaryValue;
  error->SetString(kMessageKey, message);
  error->SetString(kStackTraceFileNameKey, file);
  error->SetInteger(kStackTraceLineNumberKey, line);

  SetStatus(error_code);
  SetValue(error);
}

void Response::SetField(const std::string& key, Value* value) {
  data_.Set(key, value);
}

std::string Response::ToJSON() const {
  std::string json;
  base::JSONWriter::Write(&data_, false, &json);
  return json;
}

}  // namespace webdriver

Fix build. Forgot to explictly add file while patching. BUG=none TEST=none TBR=rsleevi


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

vector< vector<bool> > dp;
string s;

void preprocess() {
	int n = s.size();

	//single letter is always a pallindrome
	for(int i = 0; i < n; ++i)
		dp[i][i] = true;

	//if adjacent letters are same then they are pallindrome
	for(int i = 0; i < n - 1; ++i)
		if(s[i] == s[i + 1])
			dp[i][i + 1] = true;

	//if s[i] == s[j] and between i + 1 and j - 1 is pallindrome
	//then from i to j is also a pallindrome
	for(int gap = 2; gap < n; ++gap) {
		for(int i = 0; i + gap < n; ++i) {
			int j = gap + i;
			if(s[i] == s[j] and dp[i + 1][j - 1])
				dp[i][j] = true;
		}
	}
}

bool is_pallindrome(int l, int r) {
	return dp[l][r];
}

int main() {
	std :: ios_base :: sync_with_stdio(false);
	cin.tie(NULL), cout.tie(NULL);

	cin >> s;
	dp.assign(s.size(), vector<bool>(s.size(), false));

	preprocess();

	int l, r;
	cin >> l >> r;
	l--, r--;

	if(is_pallindrome(l, r))
		cout << "Substring is a pallindrome" << endl;
	else
		cout << "Substring is not a pallindrome" << endl;
}

Add pallindromic substring algorithm to find if a substring of a string is pallindrome or not.


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

#include "fuzz/Fuzz.h"

void fuzz_SVGCanvas(Fuzz* f);

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

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

#include "fuzz/Fuzz.h"
#include "src/core/SkFontMgrPriv.h"
#include "tools/fonts/TestFontMgr.h"

void fuzz_SVGCanvas(Fuzz* f);

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

Use test font manager for SVG fuzzer


#include "naive_bayes.h"

#include <iostream>

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

  nb.set_training_data_file(std::string("training.dat"));

  nb.add_training_data("Buy cheap viagra SPAM");
  nb.add_training_data("Buy cheap airlines airlines tickets HAM");
  nb.add_training_data("Dear friend I am the king of Persia king SPAM");
  nb.add_training_data("Hello friend I am from Persia you must be from New York HAM");
  nb.add_training_data("Hi friend how are you doing I love you HAM");
  nb.add_training_data("New York is a big city HAM");

  nb.train();

  std::string class_ = nb.classify(std::string("Buy cheap viagra tickets"));
  std::cout << "Your message is " << class_ << std::endl;

  class_ = nb.classify(std::string("Hello friend how are you"));
  std::cout << "Your message is " << class_ << std::endl;

  class_ = nb.classify(std::string("Dhaka is a big city"));
  std::cout << "Your message is " << class_ << std::endl;

  return 0;
}

Test source file - initial commit.


#include <read_and_write_data.h>
using namespace std;

void importData(FileReader &reader, vector<DataObject> &data) {
	// Definition goes here!!
}

void exportData(FileWriter &writer, const vector<DataObject> &data) {
	// Definition goes here!!
}

Define the methods declared in read-and-write-data header file


#include <rmc.h>

// Ok first make sure the regular old C ones still work
void mp_send(rmc_int *flag, rmc_int *data) {
    VEDGE(wdata, wflag);
    L(wdata, rmc_store(data, 42));
    L(wflag, rmc_store(flag, 1));
}

int mp_recv(rmc_int *flag, int *data) {
    int rf;
    XEDGE(rflag, rdata);
    do {
        LS(rflag, rf = rmc_load(flag));
    } while (rf == 0);
    LS(rdata, int rd = *data);
    return rd;
}

Add a C++ test. Just using C things now


#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "outputtrack.h"

int main(int argc, char** argv)
{
	FILE* fpInput = fopen("../output.bin", "rb");
	if (fpInput == NULL)
	{
		printf("Error opening input file\n");
		exit(1);
	}

	//Loop over all events in the input file.
	//Number of events is not stored int the file, but we just read until we reach the end of file.
	//All values stored in the file are either int or float, so 32 bit.
	//Thus, we do not need to care about alignment. The same data structures must be used again for reading the file.
	int nEvents = 0;
	std::vector<unsigned int> ClusterIDs;
	while (!feof(fpInput))
	{
		int numTracks; //Must be int!
		OutputTrack track;
		fread(&numTracks, sizeof(numTracks), 1, fpInput);
		printf("Event: %d, Number of tracks: %d\n", nEvents, numTracks);
		for (int iTrack = 0;iTrack < numTracks;iTrack++)
		{
			fread(&track, sizeof(track), 1, fpInput);
			printf("Track %d Parameters: Alpha %f, X %f, Y %f, Z %f, SinPhi %f, DzDs %f, Q/Pt %f, Number of clusters %d, Fit OK %d\n", iTrack, track.Alpha, track.X, track.Y, track.Z, track.SinPhi, track.DzDs, track.QPt, track.NClusters, track.FitOK);
			if (track.NClusters > ClusterIDs.size()) ClusterIDs.resize(track.NClusters);
			fread(&ClusterIDs[0], sizeof(ClusterIDs[0]), track.NClusters, fpInput);
			printf("Cluster IDs:");
			for (int iCluster = 0;iCluster < track.NClusters;iCluster++)
			{
				printf(" %d", ClusterIDs[iCluster]);
			}
			printf("\n");
		}

		nEvents++;
	}
	fclose(fpInput);
}

Add example to read tracks from binary output file


#include "EntityManager.h"

namespace zmc
{
EntityManager::EntityManager(std::shared_ptr<ComponentManager> componentManager)
    : mLastEntityID(0)
    , mComponentManager(componentManager)
{
}

EntityManager::~EntityManager()
{

}

int EntityManager::getEntityCount()
{
    return mEntityMap.size();
}

void EntityManager::removeEntity(int entityID)
{
    auto found = mEntityMap.find(entityID);
    //No entity
    if (found == mEntityMap.end())
        return;
    mEntityMap.erase(entityID);
}

void EntityManager::removeEntitiesInGroup(int groupIdentifier)
{
    for (std::pair<const int, std::unique_ptr<BaseEntity>> &pair : mEntityMap) {
        if (pair.second->getGroup() == groupIdentifier)
            mEntityMap.erase(pair.second->getEntityID());
    }
}

std::vector<BaseEntity *> EntityManager::getEntitiesInGroup(int groupIdentifier)
{
    std::vector<BaseEntity*> group;
    for (std::pair<const int, std::unique_ptr<BaseEntity>> &pair : mEntityMap) {
        if (pair.second->getGroup() == groupIdentifier) {
            group.push_back(mEntityMap.at(pair.second->getEntityID()).get());
        }
    }
    return group;
}
}

#include "EntityManager.h"

namespace zmc
{
EntityManager::EntityManager(ComponentManager *componentManager)
    : mLastEntityID(0)
    , mComponentManager(componentManager)
{
}

EntityManager::~EntityManager()
{

}

int EntityManager::getEntityCount()
{
    return mEntityMap.size();
}

void EntityManager::removeEntity(int entityID)
{
    auto found = mEntityMap.find(entityID);
    //No entity
    if (found == mEntityMap.end())
        return;
    mEntityMap.erase(entityID);
}

void EntityManager::removeEntitiesInGroup(int groupIdentifier)
{
    for (std::pair<const int, std::unique_ptr<BaseEntity>> &pair : mEntityMap) {
        if (pair.second->getGroup() == groupIdentifier)
            mEntityMap.erase(pair.second->getEntityID());
    }
}

std::vector<BaseEntity *> EntityManager::getEntitiesInGroup(int groupIdentifier)
{
    std::vector<BaseEntity*> group;
    for (std::pair<const int, std::unique_ptr<BaseEntity>> &pair : mEntityMap) {
        if (pair.second->getGroup() == groupIdentifier) {
            group.push_back(mEntityMap.at(pair.second->getEntityID()).get());
        }
    }
    return group;
}
}

Replace std::shared_ptr with pointer and make the constructor explicit


// RUN: %clang_cc1 %s -emit-llvm -o - | FileCheck %s

typedef float float32_t;
typedef signed char poly8_t;
typedef short poly16_t;
typedef unsigned long long uint64_t;

typedef __attribute__((neon_vector_type(2))) int int32x2_t;
typedef __attribute__((neon_vector_type(4))) int int32x4_t;
typedef __attribute__((neon_vector_type(1))) uint64_t uint64x1_t;
typedef __attribute__((neon_vector_type(2))) uint64_t uint64x2_t;
typedef __attribute__((neon_vector_type(2))) float32_t float32x2_t;
typedef __attribute__((neon_vector_type(4))) float32_t float32x4_t;
typedef __attribute__((neon_polyvector_type(16))) poly8_t  poly8x16_t;
typedef __attribute__((neon_polyvector_type(8)))  poly16_t poly16x8_t;

// CHECK: 16__simd64_int32_t
void f1(int32x2_t v) { }
// CHECK: 17__simd128_int32_t
void f2(int32x4_t v) { }
// CHECK: 17__simd64_uint64_t
void f3(uint64x1_t v) { }
// CHECK: 18__simd128_uint64_t
void f4(uint64x2_t v) { }
// CHECK: 18__simd64_float32_t
void f5(float32x2_t v) { }
// CHECK: 19__simd128_float32_t
void f6(float32x4_t v) { }
// CHECK: 17__simd128_poly8_t
void f7(poly8x16_t v) { }
// CHECK: 18__simd128_poly16_t
void f8(poly16x8_t v) { }

Add a test for Neon vector mangling


// RUN: %clang_cc1 -std=c++1y -fsyntax-only -verify %s -DMAX=1234 -fconstexpr-steps 1234
// RUN: %clang_cc1 -std=c++1y -fsyntax-only -verify %s -DMAX=10 -fconstexpr-steps 10
// RUN: %clang -std=c++1y -fsyntax-only -Xclang -verify %s -DMAX=12345 -fconstexpr-steps=12345

// This takes a total of n + 4 steps according to our current rules:
//  - One for the compound-statement that is the function body
//  - One for the 'for' statement
//  - One for the 'int k = 0;' statement
//  - One for each of the n evaluations of the compound-statement in the 'for' body
//  - One for the 'return' statemnet
constexpr bool steps(int n) {
  for (int k = 0; k != n; ++k) {}
  return true; // expected-note {{step limit}}
}

static_assert(steps((MAX - 4)), ""); // ok
static_assert(steps((MAX - 3)), ""); // expected-error {{constant}} expected-note{{call}}

Add test forgotten in r181388.


// Copyright 2016 Mitchell Kember. Subject to the MIT License.
// Project Euler: Problem 21
// Amicable numbers

#include "common.hpp"

#include <array>

namespace problem_21 {

long solve() {
	typedef std::vector<long>::size_type sz_t;

	constexpr sz_t max = 10000;
	std::vector<long> sums(max);
	for (sz_t i = 1; i < max; ++i) {
		sums[i] = common::sum_proper_divisors(static_cast<long>(i));
	}

	long total = 0;
	for (sz_t i = 1; i < max; ++i) {
		sz_t si = static_cast<sz_t>(sums[i]);
		if (i < si && si < max && static_cast<sz_t>(sums[si]) == i) {
			total += i;
			total += si;
		}
	}
	return total;
}

} // namespace problem_21

Solve problem 21 in C++


// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <cassert>

#include <visionaray/math/math.h>

#include <gtest/gtest.h>

using namespace visionaray;

//-------------------------------------------------------------------------------------------------
// Helper functions
//

// nested for loop over matrices --------------------------

template <typename Func>
void for_each_mat4_e(Func f)
{
    for (int i = 0; i < 4; ++i)
    {
        for (int j = 0; j < 4; ++j)
        {
            f(i, j);
        }
    }
}

// get rows and columns -----------------------------------

vec4 get_row(mat4 const& m, int i)
{
    assert( i >= 0 && i < 4 );

    return vec4(
        m(i, 0),
        m(i, 1),
        m(i, 2),
        m(i, 3)
        );
}

vec4 get_col(mat4 const& m, int j)
{
    assert( j >= 0 && j < 4 );

    return m(j);
}

TEST(Matrix, Inverse)
{

    //-------------------------------------------------------------------------
    // mat4
    //

    mat4 I = mat4::identity();

    // make some non-singular matrix
    mat4 A = make_rotation(vec3(1, 0, 0), constants::pi<float>() / 4);
    mat4 B = inverse(A);
    mat4 C = A * B;

    for_each_mat4_e(
        [&](int i, int j)
        {
            EXPECT_FLOAT_EQ(C(i, j), I(i, j));
        }
        );
}

TEST(Matrix, Mult)
{

    //-------------------------------------------------------------------------
    // mat4
    //

    // make some non-singular matrices
    mat4 A = make_rotation(vec3(1, 0, 0), constants::pi<float>() / 4);
    mat4 B = make_translation(vec3(3, 4, 5));
    mat4 C = A * B;

    for_each_mat4_e(
        [&](int i, int j)
        {
            float d = dot(get_row(A, i), get_col(B, j));
            EXPECT_FLOAT_EQ(C(i, j), d);
        }
        );
}

TEST(Matrix, Transpose)
{

    //-------------------------------------------------------------------------
    // mat4
    //

    // make some non-singular matrix
    mat4 A = make_rotation(vec3(1, 0, 0), constants::pi<float>() / 4);
    mat4 B = transpose(A);

    for_each_mat4_e(
        [&](int i, int j)
        {
            EXPECT_FLOAT_EQ(A(i, j), B(j, i));
        }
        );
}

Add unit tests for matrices


// Test harness for the HtmlParser class.
#include <iostream>
#include <cstdlib>
#include "FileUtil.h"
#include "HtmlParser.h"
#include "util.h"

void Usage() {
    std::cerr << "Usage: " << ::progname << " html_filename\n";
    std::exit(EXIT_FAILURE);
}

class Parser: public HtmlParser {
public:
    Parser(const std::string &document): HtmlParser(document) { }
    virtual void notify(const HtmlParser::Chunk &chunk);
};

void Parser::notify(const HtmlParser::Chunk &chunk) {
    std::cout << chunk.toString() << '\n';
}

int main(int argc, char *argv[]) {
    ::progname = argv[1];
    if (argc != 2)
        Usage();

    try {
        const std::string input_filename(argv[1]);
        std::string html_document;
        if (not FileUtil::ReadString(input_filename, &html_document))
            ERROR("failed to read an HTML document from \"" + input_filename + "\"!");

        Parser parser(html_document);
        parser.parse();
    } catch (const std::exception &x) {
        ERROR(x.what());
    }
}

Test harness for the HtmlParser class.


#include "Halide.h"
#include "test/common/check_call_graphs.h"

#include <stdio.h>

using namespace Halide;

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

    f(x, y, c) = x + y + c;

    f.reorder(c, x, y);
    Var yo("yo"), yi("yi");
    f.split(y, yo, yi, 2, TailStrategy::RoundUp);

    Var yoo("yoo"), yoi("yoi");
    f.split(yo, yoo, yoi, 64, TailStrategy::GuardWithIf);

    Buffer<int> im = f.realize(3000, 2000, 3);
    auto func = [](int x, int y, int c) {
        return x + y + c;
    };
    if (check_image(im, func)) {
        return -1;
    }

    return 0;
}

Add test case that exposes the out of bound errors in apply split


/*********************************************************************
** Author: Zach Colbert
** Date: 27 September 2017
** Description: A simple input/output program with mathematical operations. By prompting the user for three floats, the program will calculate and output a sum.
*********************************************************************/

#include <iostream>
using namespace std;

// A simple input/output program with mathematical operations.
int main()
{

}

Set up the bare structure of the source


// RUN: %clang_cc1 -fsyntax-only -verify %s
// expected-no-diagnostics

void bar();
namespace foo { using ::bar; }
using foo::bar;
void bar() {}

void f();
using ::f;
void f() {}

Add a test case for PR17575.


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

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

#include <Utils/TestUtils.hpp>
#include "gtest/gtest.h"

#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Models/Character.hpp>

using namespace RosettaStone;
using namespace TestUtils;

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

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

    Player& curPlayer = game.GetCurrentPlayer();

    auto& curField = curPlayer.GetFieldZone();

    auto card1 = GenerateMinionCard("minion1", 3, 6);
    PlayMinionCard(curPlayer, card1);
    EXPECT_EQ(curField[0]->GetHealth(), 6);

    curField[0]->SetDamage(2);
    EXPECT_EQ(curField[0]->GetHealth(), 4);

    curField[0]->SetHealth(8);
    EXPECT_EQ(curField[0]->GetDamage(), 0);
    EXPECT_EQ(curField[0]->GetHealth(), 8);

    curField[0]->SetHealth(0);
    EXPECT_EQ(curField[0]->isDestroyed, true);
}

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

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

    Player& curPlayer = game.GetCurrentPlayer();

    auto& curField = curPlayer.GetFieldZone();

    auto card1 = GenerateMinionCard("minion1", 3, 6);
    PlayMinionCard(curPlayer, card1);
    EXPECT_EQ(curField[0]->GetSpellPower(), 0);

    curField[0]->SetSpellPower(4);
    EXPECT_EQ(curField[0]->GetSpellPower(), 4);
}

Add unit test for Character class


// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -O3 -o - | FileCheck %s
#include <typeinfo>

class __pbase_type_info : public std::type_info {
public:
  unsigned int __flags;
  const std::type_info *__pointee;

  enum __masks {
    __const_mask = 0x1,
    __volatile_mask = 0x2,
    __restrict_mask = 0x4,
    __incomplete_mask = 0x8,
    __incomplete_class_mask = 0x10
  };
};

template<typename T> const T& to(const std::type_info &info) {
return static_cast<const T&>(info);
}
struct Incomplete;

// CHECK: define i32 @_Z1fv()
int f() {
  if (to<__pbase_type_info>(typeid(Incomplete *)).__flags != __pbase_type_info::__incomplete_mask)
    return 1;

  // Success!
  return 0;
}

#ifdef HARNESS
extern "C" void printf(const char *, ...);

int main() {
  int result = f();

  if (result == 0)
    printf("success!\n");
  else
    printf("test %d failed!\n", result);

  return result;
}
#endif

Add a (currently failing) RTTI layout test.


// RUN: %llvmgxx %s -emit-llvm -fapple-kext -S -o -
// The extra check in 71555 caused this to crash on Darwin X86
// in an assert build.
class foo {
 virtual ~foo ();
};
foo::~foo(){}

Test for llvm-gcc commit 81037.


#include "cmbf.h"
#include <unordered_map>

using namespace sketch::cmbf;

int main(int argc, char *argv[]) {
    cmbf_exp_t thing(4, 16, 1);
    cmbf_t thingexact(4, 16, 5);
    auto [x, y] = thing.est_memory_usage();
    std::fprintf(stderr, "stack space: %zu\theap space:%zu\n", x, y);
    size_t nitems = argc > 1 ? std::strtoull(argv[1], nullptr, 10): 100000;
    std::vector<uint64_t> items;
    std::mt19937_64 mt;
    while(items.size() < nitems) items.emplace_back(mt());
    for(const auto el: thing.ref()) {
        assert(unsigned(el) == 0);
    }
    auto &ref = thing.ref();
    for(const auto item: items) thing.add_conservative(item), thingexact.add_conservative(item);
    //, std::fprintf(stderr, "Item %" PRIu64 " has count %u\n", item, unsigned(thing.est_count(item)));
    std::unordered_map<uint64_t, uint64_t> histexact, histapprox;
    for(const auto j: items) {
        //std::fprintf(stderr, "est count: %zu\n", size_t(thing.est_count(j)));
        ++histapprox[thing.est_count(j)];
        ++histexact[thingexact.est_count(j)];
    }
    for(const auto &pair: histexact) {
        std::fprintf(stderr, "Exact %" PRIu64 "\t%" PRIu64 "\n", pair.first, pair.second);
    }
    for(const auto &pair: histapprox) {
        std::fprintf(stderr, "Approx %" PRIu64 "\t%" PRIu64 "\n", pair.first, pair.second);
    }
}

Add testing code for min-counting.


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

using std::string;
using std::vector;

bool isunique (const string& s);
bool isuniqueV2 (const string& s);

int main()
{
    string s = "cciao";

    if (isuniqueV2(s))
        std::cout << "All characters are unique" << std::endl;
    else
        std::cout << "Characters not unique "<< std::endl;
    return 0;
}

bool isunique (const string& s)
{
    if (s.size() > 128)
        return false;
    //we are taking ASCII
    vector<bool> char_set(128);
    for (string::size_type i=0; i<s.size(); ++i) {
        int val = s.at(i);
        if (char_set[val])
            return false;

        char_set[val] = true;
    }
   return true;
}

bool isuniqueV2 (const string& s)
{
    if (s.size() > 128)
        return false;
    //we are taking ASCII
    int check = 0;
    for (string::size_type i=0; i<s.size(); ++i) {
        int val = s.at(i) - 'a';
        int a = 'a';
        std::cout << val << " a " <<  a << std::endl;
        if ( (check & (1 << val)) > 0  )
            return false;

        check |= (1 << val);
    }
   return true;
}

Check if a string contain just unique charachers


#include <iostream>
#include <iomanip>
#include <type_traits>
#include <typeinfo>
#include <typeindex>

class A { };

class A1 {  char c;  };

class A2 {  char c1; char c2; };

class B {  char c;    int i; };

class C {  char c;    int i;    double d; };

class D {  int i;     char c;    double d; };

class E {  char c[6];  int i;    double d;  };

class F {  char c[6];  int i;  };

using namespace std;

template<class T> class AlignmentSizeInfo;

template <class T>
ostream& operator<<(ostream& out, const AlignmentSizeInfo<T>& alignsize)
{
    out << right
    << setw(3) << alignment_of<T>::value << " "
    << setw(3) << sizeof(T) <<  "  "
    << left << setw(13) << type_index(typeid(T)).name()
    << endl;

    return out;
}

template <class T>
class AlignmentSizeInfo
{
    public:
        AlignmentSizeInfo() {
            cout << *this;
        }
};

int main(int argc, char *argv[])
{
    AlignmentSizeInfo<char> asChar;
    AlignmentSizeInfo<int> asInt;
    AlignmentSizeInfo<double> asDouble;
    AlignmentSizeInfo<A> asA;
    AlignmentSizeInfo<A1> asA1;
    AlignmentSizeInfo<A2> asA2;
    AlignmentSizeInfo<B> asB;
    AlignmentSizeInfo<C> asC;
    AlignmentSizeInfo<D> asD;
    AlignmentSizeInfo<E> asE;
    AlignmentSizeInfo<F> asF;
}

Print alignment and size of fundamantal and user-defined types


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

int w = z.;  // expected-error {{use of undeclared identifier 'z'}} \
             // expected-error {{expected unqualified-id}}

int x = { y[  // expected-error {{use of undeclared identifier 'y'}} \
              // expected-note {{to match this '['}} \
              // expected-note {{to match this '{'}} \
              // expected-error {{expected ';' after top level declarator}}

// The errors below all occur on the last line of the file, so splitting them
// among multiple lines doesn't work.
// expected-error {{expected expression}} expected-error {{expected ']'}} expected-error {{expected '}'}}

Add the test that was supposed to be included with r223162.


class Solution {
public:
    bool hasAllCodes(string s, int k) {
        if (k > s.size()) {
            return false;
        }
        int need = 1 << k;
        for (int i = 0; i <= (s.size()-k); ++i) {
            std::string cur = s.substr(i, k);
            auto iter = s_.find(cur);
            if (iter == s_.end()) {
                s_.emplace(cur);
                --need;
                if (need == 0)
                    return true;
            }
        }
        return false;
    }
private:
    std::unordered_set<std::string> s_;
};

Check If a String Contains All Binary Codes of Size K


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

void f() noexcept;
void (&r)() = f;
void (&s)() noexcept = r; // expected-error {{cannot bind}}

void (&cond1)() noexcept = true ? r : f; // expected-error {{cannot bind}}
void (&cond2)() noexcept = true ? f : r; // expected-error {{cannot bind}}
// FIXME: Strictly, the rules in p4 don't allow this, because the operand types
// are not of the same type other than cv-qualifiers, but we consider that to
// be a defect, and instead allow reference-compatible types here.
void (&cond3)() = true ? r : f;
void (&cond4)() = true ? f : r;

Add another testcase missed from r284905.


#include <iostream>

using std::cout;
using std::endl;

template <typename T>
struct Node {
    T data;
    Node *next;

    Node(T _data, Node *_next = nullptr) :
            data(_data), next(_next) {}
};

template <typename T>
class Stack {
    Node<T> *top;
    int size;

    void clear() {
        while (!isEmpty()) {
            pop();
        }
    }

    void copy(const Stack& other) {
        size = other.size;
        if (other.top == nullptr)
            top = nullptr;
        else {
            Node<T> *currOther = other.top;
            Node<T> *curr = new Node<T>(currOther->data);
            top = curr;
            currOther = currOther->next;
            while (currOther != nullptr) {
                curr->next = new Node<T>(currOther->data);
                curr = curr->next;
                currOther = currOther->next;
            }
        }
    }

public:

    Stack() {
        top = nullptr;
        size = 0;
    }

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

    Stack& operator=(const Stack& other) {
        if (this != &other) {
            clear();
            copy(other);
        }

        return *this;
    }

    ~Stack() {
        clear();
    }

    int getSize() const {
        return size;
    }

    bool isEmpty() const {
        return top == nullptr;
    }

    const T& getTop() const {
        return top->data;
    }

    void push(const T element) {
        top = new Node<T>(element, top);
        size++;
    }

    void pop() {
        Node<T> *toDel = top;
        top = top->next;
        delete toDel;
        size--;
    }

    void print() {
        Node<T> *curr = top;
        while (curr != nullptr) {
            cout << curr->data << " ";
            curr = curr->next;
        }
        cout << endl;
    }
};

int main() {
    Stack<int> s1;
    cout << s1.isEmpty() << endl;
    s1.push(5);
    cout << s1.isEmpty() << endl;
    s1.push(7);
    s1.push(9);
    cout << s1.getTop() << endl;
    cout << s1.getSize() << endl;
    s1.print();
    Stack<int> s2 = s1;
    s2.print();
    s2.pop();
    s2.push(12);
    s1.print();
    s2.print();
    s1 = s2;
    s1.print();
    s2.print();

    return 0;
}

Add solution to problem 1


//
//  RemoveDuplicatesFromSortedArrayII.cpp
//  c++
//
//  Created by sure on 1/20/15.
//  Copyright (c) 2015 Shuo Li. All rights reserved.
//
// http://blog.csdn.net/myjiayan/article/details/26334279
// Gives me a better solution. Implement it in C++

#include <stdio.h>

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if (n == 0) {
            return 0;
        }
        int times = 0;
        int index = 0;
        for (int i = 0; i < n; i ++) {
            if (A[index] == A[i]) {
                times ++;
                if (times == 2) {
                    index ++;
                    A[index] = A[i];
                }
            } else {
                index ++;
                A[index] = A[i];
                times = 1;
            }
        }
        return (index + 1);
    }
};

int main() {
    Solution *s = new Solution();
    int A[5] = {1, 1, 1, 2, 3};
    s->removeDuplicates(A, 5);
}

Remove Duplicates From Sorted Array II


// RUN: %clang_cc1 -triple x86_64-unknown-unknown -ast-dump %s | FileCheck -strict-whitespace %s

void testArrayInitExpr()
{
    int a[10];
    auto l = [a]{
    };
    // CHECK: |-ArrayInitLoopExpr 0x{{[^ ]*}} <col:15> 'int [10]'
    // CHECK: | `-ArrayInitIndexExpr 0x{{[^ ]*}} <<invalid sloc>> 'unsigned long'
}

Add dump tests for ArrayInitLoopExpr and ArrayInitIndexExpr


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

bool circleSortRec(int a[], int low, int high)
{
    bool swapped = false;

    if (low == high)
        return false;

    int lo = low, hi = high;

    while (lo < hi)
    {

        if (a[lo] > a[hi])
        {
            swap(a[lo], a[hi]);
            swapped = true;
        }
        lo++;
        hi--;
    }

    if (lo == hi)
        if (a[lo] > a[hi + 1])
        {
            swap(a[low], a[hi+1]);
            swapped = true;
        }

    int mid = (high - low) / 2;
    bool firstHalf = circleSortRec(a, low, low+mid);
    bool secondHalf = circleSortRec(a, low+mid+1, high);

    return swapped || firstHalf || secondHalf;
}

void circleSort(int a[], int n)
{

    while (circleSortRec(a, 0, n-1))
    {
       ;
    }
}

int main()
{
    int a[] = {7, 5, 3, 1, 2, 4, 6, 8};
    int n = sizeof(a)/sizeof(a[0]);

    printf("\nUnsorted : ");
    for (int i=0; i<n; i++)
        cout << a[i] << " ";

    circleSort(a, n);

    printf("\nSorted : ");
    for (int i=0; i<n; i++)
        cout << a[i] << " ";

    return 0;
}

Add "Circle sort" to the list


#include <iostream>

namespace Exercise {
    int ivar = 0;
    double dvar = 0;
    const int limit = 1000;
}

int ivar = 0;
//using namespace Exercise;
//using Exercise::ivar;
//using Exercise::dvar;
//using Exercise::limit;

void manip() {
//    using namespace Exercise;
using Exercise::ivar;
using Exercise::dvar;
using Exercise::limit;
    double dvar = 3.1416;
    int iobj = limit + 1;
    ++ ivar;
    ++ ::ivar;
}

int main() {
    return 0;
}

Add solution for chapter 18 test 16, test 17