//Given a sorted linked list, delete all duplicates such that each element appear only once.
//
//For example,
//Given 1->1->2, return 1->2.
//Given 1->1->2->3->3, return 1->2->3.

#include <iostream>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
		ListNode dummy(-1);
		dummy.next = head;

		ListNode *p=&dummy;
		if(p->next==NULL || p->next->next==NULL)
			return dummy.next;

		while(1)
		{
			p = p->next;

			if(p==NULL || p->next ==NULL)
				break;
			ListNode *temp = p->next;

			if(p->val==temp->val)
			{
				while(temp->next!=NULL)
				{
					if(p->val!=temp->next->val)
						break;
					ListNode *ttemp = temp;
					temp = temp->next;
					delete ttemp;
				}
				p->next = temp->next;
				delete temp;
			}
		}

		return dummy.next;
    }
};

int main()
{
	//ListNode a(1);
	//ListNode b(1),c(1),d(2),e(3);
	//a.next = &b;b.next = &c; c.next = &d; d.next = &e;

	ListNode a(1);
	ListNode b(1);
	a.next  = &b;
	Solution solute;

	solute.deleteDuplicates(&a);
}

Remove Duplicates from Sorted List


#include "catch.hpp"

#include <mapnik/debug.hpp>
#include <mapnik/xml_tree.hpp>
#include <mapnik/xml_loader.hpp>

TEST_CASE("xml parser") {

  SECTION("trims whitespace") {

    // simple and non-valid mapnik XML reduced from the empty_parameter2.xml
    // test case. this is to check that the xml parsing routine is trimming
    // whitespace from text nodes as part of the parsing operation.
    const std::string xml("<Map>"
                          "  <Layer>"
                          "    <Datasource>"
                          "      <Parameter name=\"empty\"><![CDATA[ ]]></Parameter>"
                          "    </Datasource>"
                          "  </Layer>"
                          "</Map>");

    mapnik::xml_tree tree("utf8");
    tree.set_filename("xml_datasource_parameter_trim.cpp");
    REQUIRE_NOTHROW(read_xml_string(xml, tree.root(), ""));

    REQUIRE(tree.root().has_child("Map"));
    mapnik::xml_node const &map = tree.root().get_child("Map");

    REQUIRE(map.has_child("Layer"));
    mapnik::xml_node const &layer = map.get_child("Layer");

    REQUIRE(layer.has_child("Datasource"));
    mapnik::xml_node const &datasource = layer.get_child("Datasource");

    REQUIRE(datasource.has_child("Parameter"));
    mapnik::xml_node const &parameter = datasource.get_child("Parameter");

    // parser should call mapnik::util::trim on the text content and
    // this should result in an empty text string in the parameter.
    REQUIRE(parameter.get_text() == "");
  }
}

Add test for XML parser whitespace trimming behaviour.


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

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

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

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

#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER4(UnaryOp, CPU, "Asin", functor::asin, Eigen::half, bfloat16, float,
          double);

#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED)
REGISTER3(UnaryOp, GPU, "Asin", functor::asin, Eigen::half, float, double);
#endif
REGISTER(UnaryOp, GPU, "Asin", functor::asin, bfloat16)
#endif

}  // namespace tensorflow

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

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

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

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

#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER6(UnaryOp, CPU, "Asin", functor::asin, Eigen::half, bfloat16, float,
          double, complex64, complex128);

#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED)
REGISTER3(UnaryOp, GPU, "Asin", functor::asin, Eigen::half, float, double);
#endif
REGISTER(UnaryOp, GPU, "Asin", functor::asin, bfloat16)
#endif

}  // namespace tensorflow

Add complex support for tf.math.asin


#include "gtest/gtest.h"

#include "worker.h"
#include "requests.pb.h"

class TestMessageWorker : public traffic::MessageWorker
{
protected:
	bool set_up() { return true; }

	bool process_summary() {
		summary = true;
		return true;
	}

	bool process_statistics() {
		statistic = true;
		return true;
	}

public:
	bool statistic;
	bool summary;

	using traffic::MessageWorker::process;

	TestMessageWorker()
	:
		traffic::MessageWorker(),
		statistic(false),
		summary(false)
	{ }
};

TEST(ServerMessageWorker, basic_message_worker) {
	TestMessageWorker w;

	request::Request request;
	request.set_version(1);

	request::Statistic *stat = request.mutable_statistic();

	request::TimeRange *range = stat->mutable_range();

	range->set_start(1);
	range->set_end(2);

	stat->set_address("10.10.10.10");

	std::string buffer;
	request.SerializeToString(&buffer);

	std::string out_buffer;
	w.process(out_buffer, (void *)buffer.c_str(), buffer.size());

	EXPECT_TRUE(w.statistic);
	EXPECT_FALSE(w.summary);
}

Add simple test for message prototype


#include <iostream>
#include <queue>

using namespace std;

struct edge{
    int to, weight;
    edge(){}
    edge(int _to, int _weight){
        to = _to;
        weight = _weight;
    }
    bool operator < (edge e) const {
        return weight > e.weight;
    }
};

typedef priority_queue<edge> pq;

int main(){
    pq edges;

    edges.push(edge(1, 23));
    edges.push(edge(2, 3));
    edges.push(edge(3, 10));
    edges.push(edge(4, 11));
    edges.push(edge(5, 4));

    while(!edges.empty()){
        edge a = edges.top();
        edges.pop();
        cout << a.to << endl;
    }
}

Add useful structure for combininig with more powerful structure.


#include <iostream>
#include <fstream>

using std::ifstream;
using std::ios;
using std::cout;

int main() {
  ifstream text_file("lines.txt", ios::binary);

  char buffer[100];
  while (text_file.read(buffer, 100).gcount()) {
    for (int i = 0; i < text_file.gcount(); ++i) {
      cout << (int)buffer[i] << ' ';
    }
    cout << '\n';
  }

  text_file.close();

  return 0;
}

Add program which prints the bytes in a file as numbers in base-ten number system


class Solution {
public:
    bool closeStrings(string word1, string word2) {
        std::vector<int> v1(26, 0), v2(26, 0);
        std::unordered_set<char> s1, s2;
        for (const auto& c: word1) {
            v1[c-'a']++;
            s1.emplace(c);
        }
        for (const auto& c: word2) {
            v2[c-'a']++;
            s2.emplace(c);
        }
        std::sort(v1.begin(), v1.end());
        std::sort(v2.begin(), v2.end());
        return s1 == s2 && v1 == v2;
    }
};

Determine if Two Strings Are Close


// RUN: %clang_cc1 -triple i386-apple-darwin9 -analyze -analyzer-experimental-internal-checks -checker-cfref -analyzer-store=region -verify -fblocks -analyzer-opt-analyze-nested-blocks %s
// RUN: %clang_cc1 -triple x86_64-apple-darwin9 -analyze -analyzer-experimental-internal-checks -checker-cfref -analyzer-store=region -verify -fblocks   -analyzer-opt-analyze-nested-blocks %s
// XFAIL: *

// This test case currently crashes because of an assertion failure.
char &test1_aux();
char *test1() {
  return &test1_aux();
}

Add failing test case for C++ static analysis.


// https://leetcode.com/problems/serialize-and-deserialize-binary-tree/

// Use level order or preorder traversal to serialize since these two methods
// saves parents before childs. It would be convenient to deserialize.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
    void serialize(const TreeNode* root, string* rep) {
        if (root == nullptr) {
            rep->push_back('#');
            return;
        }
        rep->append(to_string(root->val));
        rep->push_back(' ');
        serialize(root->left, rep);
        serialize(root->right, rep);
    }

    TreeNode* deserialize(istringstream& inbuf) {
        char c;
        inbuf >> c;
        if (c == '#') return nullptr;
        else {
            inbuf.putback(c);
            int v;
            inbuf >> v;
            TreeNode* root = new TreeNode(v);
            root->left = deserialize(inbuf);
            root->right = deserialize(inbuf);
            return root;
        }
    }

public:

    // Encodes a tree to a single string.
    string serialize(const TreeNode* root) {
        string rep;
        serialize(root, &rep);
        return rep;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(const string& data) {
        istringstream inbuf(data);
        return deserialize(inbuf);
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

Add a solution for problem 297: Serialize and Deserialize Binary Tree.


/*
 * =====================================================================================
 *
 *       Filename:  max_product.cc
 *
 *    Description:  max product algorithms
 *
 *        Version:  1.0
 *        Created:  02/05/2015 05:56:41 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:   (Qi Liu), liuqi.edward@gmail.com
 *   Organization:  antq.com
 *
 * =====================================================================================
 */
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>

template<typename Type>
inline Type Max(Type t1, Type t2, Type t3)
{
	t1 = t1 > t2 ? t1 : t2;
	return t1 > t3 ? t1 : t3;
}

template<typename Type>
inline Type Min(Type t1, Type t2, Type t3)
{
	t1 = t1 < t2 ? t1 : t2;
	return t1 < t3 ? t1 : t3;
}

/*
 * Find the maximum continuous product sub-array
 */
template<typename Type>
Type MaxContinuousProduct(Type* array, int32_t size)
{
	int i;
	Type max;
	Type* max_array = (Type*)malloc(size*sizeof(Type));
	Type* min_array = (Type*)malloc(size*sizeof(Type));

	max = array[0];
	max_array[0] = array[0];
	min_array[0] = array[0];
	for(i = 1; i < size; ++i)
	{
		max_array[i] = Max(array[i], array[i] * max_array[i-1], array[i]*min_array[i-1]);
		min_array[i] = Min(array[i], array[i] * max_array[i-1], array[i]*min_array[i-1]);
		if(max_array[i] > max)
			max = max_array[i];
	}
	free(max_array);
	free(min_array);
	return max;
}

int main()
{
	int array[9] = {-3, 5, 5, 10, -3, 9, 8, 2, -1};
	int ans = MaxContinuousProduct(array, 9);
	fprintf(stdout, "Max: %d\n", ans);
	return 0;
}

Add maximum continuous product of sub array


/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "Test.h"
#include "picture_utils.h"
#include "SkString.h"

static void test_filepath_creation(skiatest::Reporter* reporter) {
    SkString result;
    SkString filename("test");
    const char* dir = "test/path";
    sk_tools::make_filepath(&result, dir, filename);
    REPORTER_ASSERT(reporter, result.equals("test/path/test"));
}

static void test_get_basename(skiatest::Reporter* reporter) {
    SkString result;
    SkString path("/path/basename");
    sk_tools::get_basename(&result, path);
    REPORTER_ASSERT(reporter, result.equals("basename"));

    result.reset();
    path.set("/path/dir/");
    sk_tools::get_basename(&result, path);
    REPORTER_ASSERT(reporter, result.equals("dir"));

    result.reset();
    path.set("path");
    sk_tools::get_basename(&result, path);
    REPORTER_ASSERT(reporter, result.equals("path"));

#if defined(SK_BUILD_FOR_WIN)
    result.reset();
    path.set("path\\winbasename");
    sk_tools::get_basename(&result, path);
    REPORTER_ASSERT(reporter, result.equals("winbasename"));

    result.reset();
    path.set("path\\windir\\");
    sk_tools::get_basename(&result, path);
    REPORTER_ASSERT(reporter, result.equals("windir"));
#endif
}

static void TestPictureUtils(skiatest::Reporter* reporter) {
    test_filepath_creation(reporter);
    test_get_basename(reporter);
}

#include "TestClassDef.h"
DEFINE_TESTCLASS("PictureUtils", PictureUtilsTestClass, TestPictureUtils)

Allow specific files and multiple inputs for picture testing tools.


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

using namespace Halide;

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

    f(x, y) = x + y;
    f.bound(y, 0, 1);
    f.parallel(y);

    f.realize(10, 1);

    return 0;
}

Add a test for the warning about parallel for loops of size one


#include "mfem.hpp"
#include "catch.hpp"
#include <fstream>
#include <iostream>

using namespace mfem;

namespace pa_kernels
{

template <typename INTEGRATOR>
double test_vector_pa_integrator(int dim)
{
   Mesh *mesh;
   if (dim == 2)
   {
      mesh = new Mesh(2, 2, Element::QUADRILATERAL, 0, 1.0, 1.0);
   }
   if (dim == 3)
   {
      mesh = new Mesh(2, 2, 2, Element::HEXAHEDRON, 0, 1.0, 1.0, 1.0);
   }

   int order = 2;
   H1_FECollection fec(order, dim);
   FiniteElementSpace fes(mesh, &fec, dim);

   GridFunction x(&fes), y_fa(&fes), y_pa(&fes);
   x.Randomize(1);

   BilinearForm blf_fa(&fes);
   blf_fa.AddDomainIntegrator(new INTEGRATOR);
   blf_fa.Assemble();
   blf_fa.Finalize();
   blf_fa.Mult(x, y_fa);

   BilinearForm blf_pa(&fes);
   blf_pa.SetAssemblyLevel(AssemblyLevel::PARTIAL);
   blf_pa.AddDomainIntegrator(new INTEGRATOR);
   blf_pa.Assemble();
   blf_pa.Mult(x, y_pa);

   y_fa -= y_pa;
   double difference = y_fa.Norml2();

   delete mesh;
   return difference;
}

TEST_CASE("Nonlinear Convection", "[PartialAssembly], [NonlinearPA]")
{
   SECTION("2D")
   {
      REQUIRE(test_vector_pa_integrator<VectorMassIntegrator>(2) == Approx(0.0));
      REQUIRE(test_vector_pa_integrator<VectorDiffusionIntegrator>(2) == Approx(0.0));
   }

   SECTION("3D")
   {
      REQUIRE(test_vector_pa_integrator<VectorMassIntegrator>(3) == Approx(0.0));
      REQUIRE(test_vector_pa_integrator<VectorDiffusionIntegrator>(3) == Approx(0.0));
   }
}

}

Add consistency test for PA vector mass and diffusion


#include <iostream>
#include <math.h>

using namespace std;
typedef long long ll;

bool is_prime(ll n){
    if (n < 2) return false;
    if (n < 4) return true;
    if (n % 2 == 0 || n % 3 == 0) return false;
    if (n < 25) return true;
    for(int i = 5; i*i <= n; i += 6){
        if(n % i == 0 || n % (i + 2) == 0)
            return false;
    }
    return true;
}

int main(){
    cout << is_prime(23234) << endl;
    cout << is_prime(2) << endl;
    cout << is_prime(7454) << endl;
    cout << is_prime(976) << endl;
    cout << is_prime(1973) << endl;
    return 0;

}

Add algorithm primaly test .


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

// <array>

// iterator, const_iterator

#include <array>
#include <iterator>
#include <cassert>

int main()
{
    {
    typedef std::array<int, 5> C;
    C c;
    C::iterator i;
    i = c.begin();
    C::const_iterator j;
    j = c.cbegin();
    assert(i == j);
    }
    {
    typedef std::array<int, 0> C;
    C c;
    C::iterator i;
    i = c.begin();
    C::const_iterator j;
    j = c.cbegin();
    assert(i == j);
    }

#if _LIBCPP_STD_VER > 11
    { // N3664 testing
        {
        typedef std::array<int, 5> C;
        C::iterator ii1{}, ii2{};
        C::iterator ii4 = ii1;
        C::const_iterator cii{};
        assert ( ii1 == ii2 );
        assert ( ii1 == ii4 );
        assert ( ii1 == cii );

        assert ( !(ii1 != ii2 ));
        assert ( !(ii1 != cii ));

//         C c;
//         assert ( ii1 != c.cbegin());
//         assert ( cii != c.begin());
//         assert ( cii != c.cend());
//         assert ( ii1 != c.end());
        }
        {
        typedef std::array<int, 0> C;
        C::iterator ii1{}, ii2{};
        C::iterator ii4 = ii1;
        C::const_iterator cii{};
        assert ( ii1 == ii2 );
        assert ( ii1 == ii4 );
        assert ( ii1 == cii );

        assert ( !(ii1 != ii2 ));
        assert ( !(ii1 != cii ));

//         C c;
//         assert ( ii1 != c.cbegin());
//         assert ( cii != c.begin());
//         assert ( cii != c.cend());
//         assert ( ii1 != c.end());
        }
    }
#endif
}

Implement tests for NULL iterators for <array> re: N3644


#include <peelo/text/rune.hpp>
#include <cassert>

int main()
{
  peelo::rune auml(0x00e4);

  assert(auml.equals(0x00e4));
  assert(auml.equals_icase(0x00c4));
  assert(auml.compare('a') > 0);
  assert(auml.compare(0x00e4) == 0);
  assert(auml.compare(0x00f6) < 0);
  assert(auml.compare_icase('A') > 0);
  assert(auml.compare_icase(0x00c4) == 0);
  assert(auml.compare_icase(0x00f6) < 0);

  assert(peelo::rune::to_upper(0x00e4) == 0x00c4);
  assert(peelo::rune::to_lower(0x00c4) == 0x00e4);

  auml = peelo::rune::min;
  --auml;
  assert(auml == peelo::rune::max);

  auml = peelo::rune::max;
  ++auml;
  assert(auml == peelo::rune::min);

  return 0;
}

Add test case for rune class.


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

struct meta {
  template<typename U>
  struct apply {
    typedef U* type;
  };
};

template<typename T, typename U>
void f(typename T::template apply<U>::type);

void test_f(int *ip) {
  f<meta, int>(ip);
}

Add a test case for r95555.


class Solution {
public:
    bool arrayStringsAreEqual(vector<string>& word1, vector<string>& word2) {
        std::string s1 = "", s2 = "";
        for (const auto& word : word1) {
            s1 += word;
        }
        for (const auto& word : word2) {
            s2 += word;
        }
        return s1 == s2;
    }
};

Check If Two String Arrays are Equivalent


#include <iostream>

/**
 * Need to use 'auto' return type to return a lambda since we can't type it's
 * type. This is only possible in C++14 or later.
 */

auto func(void)
{
  auto lmb = [](int x){ return x+1; };
  return lmb;
}

int main(void)
{
  auto lmb = func();

  std::cout << "Lambda: " << lmb(1) << std::endl;

  return 0;
}

Add c++ lambda return type test


// RUN: %llvmgxx -S %s -o - | FileCheck %s

#include <utility>

typedef std::pair<int,int> P;
// CHECK: @_ZZ1fvE1X {{.*}} undef

P f() {
  static const P X = P(1,2);
  return X;
}

Check that P is not zero initialized.


#include<iostream>
#include<cstdlib>

using namespace std;

class Node{
	public:

	int data;
	Node *prev, *next;

	Node(){}

	Node(int d){
		data=d;
		prev=NULL;
		next=NULL;
	}

	Node *insertNode(Node *head, int d){
		Node *np=new Node(d);
		Node *t=head;

		if(head==NULL)
			return np;

		while(t->next!=NULL)
			t=t->next;

		t->next=np;
		np->prev=t;

		return head;
	}

	Node *deleteNode(Node *head, int pos){
		Node *t=head;
		int c=1;

		if(pos==1){
			head=head->next;
			free(head->prev);
			return head;
		}

		while(c<pos-1){
			t=t->next;
			c++;
		}
		if(t->next->next!=NULL)
			t->next->next->prev=t;
		Node *tm=t->next;
		t->next=t->next->next;
		free(tm);

		return head;
	}

	void displayList(Node *head){
                cout<<"\nElements of the list are:\n";

                while(head){
                        cout<<head->data<<"\n";
                        head=head->next;
                }
        }
};

int main()
{
        int n,p,pos,d;
        Node np;
        Node *head=NULL;

        cout<<"Enter the size of linked list: ";
        cin>>n;

        for(int i=0;i<n;i++){
                        cout<<"\nEnter element "<<i+1<<": ";
                        cin>>p;
                        head=np.insertNode(head,p);
                }

        cout<<"\nEnter the position where you wish to delete the element: ";
        cin>>pos;

        if(pos>n)
                cout<<"\nSorry! The position you entered is out of bounds.\n";
        else
                head=np.deleteNode(head,pos);

        np.displayList(head);
}

Add code to delete node in doubly linked list


#pragma once

#include <Windows.h>
#include <WinINet.h>
#include <IOStream>
#include <String>

#pragma comment(lib, "WinINet.lib")

std::string replaceAll(std::string subject, const std::string& search,
    const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
        subject.replace(pos, search.length(), replace);
        pos += replace.length();
    };
    return subject;
};

std::string DownloadURL(std::string URL) {
    HINTERNET interwebs = InternetOpenA("Mozilla/5.0", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, NULL);
    HINTERNET urlFile;
    std::string rtn;
    if (interwebs) {
        urlFile = InternetOpenUrlA(interwebs, URL.c_str(), NULL, NULL, NULL, NULL);
        if (urlFile) {
            char buffer[2000];
            DWORD bytesRead;
            do {
                InternetReadFile(urlFile, buffer, 2000, &bytesRead);
                rtn.append(buffer, bytesRead);
                memset(buffer, 0, 2000);
            } while (bytesRead);
            InternetCloseHandle(interwebs);
            InternetCloseHandle(urlFile);
            std::string p = replaceAll(rtn, "|n", "\r\n");
            return p;
        };
    };
    InternetCloseHandle(interwebs);
    std::string p = replaceAll(rtn, "|n", "\r\n");
    return p;
};

std::string keychecker() {
    std::string key;
    std::cout << "Enter Key: ";
    std::cin >> key;
    return key;
};

void auth() {
    std::string hostfile = ""; //Hwid check site [Pastebin etc.]
    std::string hot = keychecker();
    std::string result = DownloadURL(hostfile += hot);
    if (result == "1") {
        std::cout << "Whitelisted Key: " + hot, +"\n"; //Success message.
    }
    else {
        std::cout << "Key Not Found\n" << hot.c_str();
        Sleep(10000);
        exit(10);
    };
};

Rename to be more descriptive correction


/*
 * gtest_main.cpp
 *
 *  Created on: May 12, 2015
 *      Author: Vance Zuo
 */

#include "gmock/gmock.h"
#include <stdio.h>

int main(int argc, char **argv) {
  printf("Running main() from gtest_main.cpp\n");
  testing::InitGoogleMock(&argc, argv);
  return RUN_ALL_TESTS();
}

Add google testing framework main


#include  <iostream>
using namespace std;

// function to sort a using shellSort
int shellSort(int a[],int n)
{
	for(int shell=n/2;shell>0; shell/=2)
	{
		for(int i=shell;i<n;i++)
		{
			int tmp=a[i];
			int j;
			for (j=i;(j>=shell) && (a[j-shell]>tmp); j-=shell)
				a[j]=a[j-shell];
			a[j]=tmp;
		}
	}
	return 0;
}
int main()
{
	int n,arr[10000];
	cin >> n;
	for (int i=0;i<n;i++)
		cin >> arr[i];
	shellSort(arr,n);
	cout << "Array after sorting: \n";
	for (int i=0;i<n;i++)
		cout << arr[i] << " ";
	cout << endl;

	return 0;
}

Add shell sort in cpp


/*
 * Copyright (C) 2015-2016 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#include <bits/stdc++.h>

typedef std::pair<double, double> DoublePair;
typedef std::vector<DoublePair> DoublePairs;

// circle
int x, y, r;
// line
int A, B, C;

bool pointOfLine(DoublePair point) {
    double factor = A * point.first + B * point.second + C;
    return std::fabs(factor) < 1e-10;
}

DoublePair moveInDirection(DoublePair start, DoublePair vect, double dist) {
    double factor = dist / std::sqrt(A * A + B * B);
    DoublePair res(
        start.first + vect.first * factor,
        start.second + vect.second * factor
    );
    return res;
}

DoublePair getNearest(double dist) {
    DoublePair center(x, y), normal1(A, B), normal2(-A, -B);
    DoublePair nearest1 = moveInDirection(center, normal1, dist);
    DoublePair nearest2 = moveInDirection(center, normal2, dist);
    if (pointOfLine(nearest1)) {
        return nearest1;
    } else {
        return nearest2;
    }
}

int main() {
    std::cin >> x >> y >> r >> A >> B >> C;
    // distance from the center of the circle to the line
    double dist = std::abs(A * x + B * y + C) / std::sqrt(A * A + B * B);
    DoublePair nearest = getNearest(dist);
    DoublePairs ans;
    if (r > dist) {
        double path = std::sqrt(r * r - dist * dist);
        DoublePair direction1(B, -A);
        DoublePair direction2(-B, A);
        ans.push_back(moveInDirection(nearest, direction1, path));
        ans.push_back(moveInDirection(nearest, direction2, path));
    } else if (std::fabs(r - dist) < 1e-10) {
        // r == dist
        ans.push_back(nearest);
    }
    std::cout << ans.size() << std::endl;
    for (int i = 0; i < ans.size(); i++) {
        std::cout << std::setprecision(8) << std::fixed;
        std::cout << ans[i].first << " " << ans[i].second << std::endl;
    }
    return 0;
}

Add intersection of line and circle


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

Convert Sorted List to Binary Search Tree


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

int main()
{
  using namespace agency;

  std::cout << "Starting predecessor and continuation tasks asynchronously..." << std::endl;

  std::mutex mut;

  // asynchronously create 5 agents to greet us in a predecessor task
  std::future<void> predecessor = bulk_async(par(5), [&](parallel_agent& self)
  {
    mut.lock();
    std::cout << "Hello, world from agent " << self.index() << " in the predecessor task" << std::endl;
    mut.unlock();
  });

  // create a continuation to the predecessor
  std::future<void> continuation = bulk_then(par(5), [&](parallel_agent& self)
  {
    mut.lock();
    std::cout << "Hello, world from agent " << self.index() << " in the continuation" << std::endl;
    mut.unlock();
  },
  predecessor);

  std::cout << "Sleeping before waiting on the continuation..." << std::endl;
  std::this_thread::sleep_for(std::chrono::seconds(1));
  std::cout << "Woke up, waiting for the continuation to complete..." << std::endl;

  // wait for the continuation to complete before continuing
  continuation.wait();

  std::cout << "OK" << std::endl;
  return 0;
}

Add an example program for bulk_then


// Test the DAS class.
// Read attributes from one or more files, printing the resulting table to
// stdout. If a file is named `-' read from stdin for that file. The option
// `-d' causes new/delete run-time debugging to be turned on.
//
// jhrg 7/25/94

// $Log: das-test.cc,v $
// Revision 1.1  1994/08/02 18:08:38  jimg
// Test driver for DAS (and AttrTable) classes.
//

#include <iostream.h>
#include <String.h>
#include <Pix.h>
#include <GetOpt.h>

#include "DAS.h"
#include "Space.h"

int
main(int argc, char *argv[])
{
    GetOpt getopt (argc, argv, "d");
    int option_char;

    // process options first so that debugging in on for object instantitaion.
    while ((option_char = getopt ()) != EOF)
	switch (option_char)
	  {
	    case 'd':
	      space_debug = 1;
	      executable_name = "das-test";
	      break;
	    case '?':
	      fprintf (stderr, "usage: %s [d] filename ...\n", argv[0]);
	  }

    DAS das;

    for (int i = getopt.optind; i < argc; ++i) {
	if (strcmp(argv[i], "-") == 0) {
	    cout << "Enter attributes:\n";
	    das.parse();
	    cout << das;
	}
	else {
	    cout << "Reading from: " << argv[i] << endl;
	    das.parse(argv[i]);
	    cout << das;
	}
    }
}


// http://www.geeksforgeeks.org/bipartite-graph/
#include<iostream>
#include<queue>
#define V 4
using namespace std;

bool isBipartite(int Graph[][V], int src) {
    int color[V];
    for (int i = 0; i < V; i++)
        color[i] = -1;
    color[src] = 1;
    queue<int> q;
    q.push(src);
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int v = 0; v < V; v++) {
            if (Graph[u][v] && color[v] == -1) {
                color[v] = 1 - color[u];
                q.push(v);
            } else if (Graph[u][v] && color[u] == color[v]) return false;
        }
    }
    return true;
}

int main() {
    int Graph[][V] = {{0, 1, 0, 1},
                      {1, 0, 1, 0},
                      {0, 1, 0, 1},
                      {1, 0, 1, 0}};
    isBipartite(Graph, 0) ? cout<<"Yes" : cout<<"No";

    return 0;
}

Implement is bipartite for a given graph


/*
Copyright 2015 Rogier van Dalen.

This file is part of Rogier van Dalen's Mathematical tools library for C++.

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

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

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/** \file
Integration check to see whether using dense symbols in a sequence works.
*/

#define BOOST_TEST_MODULE test_sequence_alphabet
#include "utility/test/boost_unit_test.hpp"

#include "math/sequence.hpp"
#include "math/alphabet.hpp"

#include <string>

BOOST_AUTO_TEST_SUITE (test_suite_sequence_alphabet)

typedef math::alphabet <std::string> alphabet_type;

BOOST_AUTO_TEST_CASE (test_sequence_alphabet) {
    alphabet_type alphabet;

    auto symbol1 = alphabet.add_symbol ("hello");
    auto symbol2 = alphabet.add_symbol ("bye");

    typedef decltype (symbol1) internal_symbol_type;

    math::empty_sequence <internal_symbol_type> empty_sequence;
    math::optional_sequence <internal_symbol_type> sequence1 (symbol1);
    math::single_sequence <internal_symbol_type> sequence2 (symbol2);

    // The first symbol will be chosen because dense symbols are not in
    // lexicographical order.
    BOOST_CHECK (math::choose (sequence1, sequence2) == sequence1);
    BOOST_CHECK (math::plus (sequence1, sequence2) == empty_sequence);

    auto sequence12 = sequence1 * sequence2;
    BOOST_CHECK_EQUAL (range::size (sequence12.symbols()), 2);
    BOOST_CHECK (range::first (sequence12.symbols()) == symbol1);
    BOOST_CHECK (range::second (sequence12.symbols()) == symbol2);
}

BOOST_AUTO_TEST_SUITE_END()

Test integration of sequence and alphabet


// Write a program to find the increasing array with the largest sum of array.

#include <stdio.h>

const int MIN = -2147483647;

void importArray(int array[], int &length);
void exportArray(int array[], int length);
void exportArray(int array[], int length, int from, int to);
void handleRequirement(int array[], int length, int &from, int &to);

int main() {
	int array[100], length, from, to;

	importArray(array, length);
	exportArray(array, length);
	handleRequirement(array, length, from, to);
	exportArray(array, length, from, to);

	return 0;
}

void handleRequirement(int array[], int length, int &from, int &to) {
	int result, max, index, pointer;

	result = MIN;

	for (index = 0; index < length - 1; index++) {

		max = array[index];

		for (pointer = index + 1; pointer < length; pointer++) {
			if (array[pointer] >= array[pointer - 1]) {
				to = pointer;
				max += array[pointer];
			} else {
				break;
			}
		}

		if (result <= max) {
			from = index;
			to = pointer - 1;
			result = max;
		}
	}
}

void importArray(int array[], int &length) {
	int index;

	do
	{
		printf("N: ");
		scanf("%d", &length);
	} while (length < 0);

	printf("Import array: ");

	for (index = 0; index < length; index++) {
		scanf("%d", &array[index]);
	}
}

void exportArray(int array[], int length) {
	int index;

	printf("Export array: ");

	for (index = 0; index < length; index++) {
		printf("%d ", array[index]);
	}
	printf("\n");
}

void exportArray(int array[], int length, int from, int to) {
	int index;

	printf("Export array: ");

	for (index = from; index <= to; index++) {
		printf("%d ", array[index]);
	}
	printf("\n");
}

Add problem: Write a program to find the increasing array with the largest sum of array.


#include <csetjmp>
#include <unistd.h>

#if defined(__APPLE__)
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif

#include "Halide.h"
#include "HalideRuntimeOpenGL.h"

std::string error_message;

/*
** Don't rely on func.set_error_handler() mechanism, it doesn't seem to catch
** the user OpenGL state errors. That might be a separate bug.
*/
jmp_buf env;
void on_sigabrt (int signum)
{
  longjmp (env, 1);
}
void catching_stderr_abort(std::function<void ()> func)
{
    auto ferr = tmpfile();
    auto prev_stderr = dup(2);
    dup2(fileno(ferr), 2);
    if (setjmp (env) == 0) {
        auto prev_handler = signal(SIGABRT, &on_sigabrt);
        (func)();
        signal(SIGABRT, prev_handler);
    }
    fseek(ferr, 0, SEEK_END);
    error_message.resize(ftell(ferr));
    rewind(ferr);
    fread(&error_message[0], 1, error_message.size(), ferr);
    dup2(prev_stderr, 2);
    close(prev_stderr);
}

using namespace Halide;

int main()
{
    // This test must be run with an OpenGL target
    const Target &target = get_jit_target_from_environment();
    if (!target.has_feature(Target::OpenGL))  {
        fprintf(stderr,"ERROR: This test must be run with an OpenGL target, e.g. by setting HL_JIT_TARGET=host-opengl.\n");
        return 1;
    }

    Image<uint8_t> output(255, 10, 3);

    Var x, y, c;
    Func g;
    g(x, y, c) = Halide::cast<uint8_t>(255);
    g.bound(c, 0, 3);
    g.glsl(x, y, c);

    // Let Halide initialize OpenGL
    g.realize(output);

    // Bad OpenGL call leaves OpenGL in a bad state
    glEnableVertexAttribArray(-1);

    // Halide should report that the OpenGL context is in a bad state due to user code`
    catching_stderr_abort( [&] () { g.realize(output); } );

    if (error_message.empty()) {
        fprintf(stderr, "Failed to report error in user OpenGL state\n");
        return 1;
    }
    else if (error_message.find("user OpenGL state") == std::string::npos) {
        error_message.erase(error_message.size() - 1); // remove trailing newline
        fprintf(stderr, "Reported error '%s' rather than identifying error at 'user OpenGL state'\n", error_message.c_str());
        return 1;
    }

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

Add (failing) test that halide reports user error when called with OpenGL in bad state


#include <iostream>
#include <new>
#include <cstdlib>

using namespace std;

void* operator new (size_t size) {
    cout << "operator new(" << size << ")" << endl;
    if(void *mem = malloc(size)) {
        return mem;
    } else {
        throw bad_alloc();
    }
}

void operator delete(void *mem) noexcept {
    cout << "operator delete(" << mem << ")" << endl;
    free(mem);
}

class Test {
private:
    int i;
    long l;
};

int main() {
    int *pi = new int(1);
    delete pi;
    long *pl = new long(10);
    delete pl;
    Test *pt = new Test();
    delete pt;
    return 0;
}

Add solution for chapter 19, test 1


#include <iostream>
#include <vector>
#include <list>

template <template<class,class> class Container, class Object>
class UDTContainer{
	private:
		Container<Object,std::allocator<Object> > m_cointainer;
	public:

};

int main(){

	UDTContainer<std::vector,std::string> obj_udtc;
}

Update gitignore and added a test class that accepts STL class as a template template argument


#include <stdio.h>
#include <stdlib.h> /* rand(), srand() */
#include <time.h> /* time() */

int count_one_came_out_when_throwing_dice(const int count)
{
    int rc = 0;

    for(int i = 0; i < count; ++i)
        if(rand() % 6 + 1 == 1) ++rc;

    return rc;
}

int main(void)
{
    srand(time(NULL));

    const int max = 10000;

    int six = 0, twelve = 0;
    for(int i = 0; i < max; ++i)
    {
        six += (count_one_came_out_when_throwing_dice(6) >= 1);
        twelve += (count_one_came_out_when_throwing_dice(12) >= 2);
    }

    printf("Result: %s\n", (six == twelve) ? "SAME" : (six < twelve) ? "SIX" : "TWELVE");

    return 0;
}

Add solution of prob 5


// RUN: clang-cc %s -emit-llvm -o - | FileCheck %s

// CHECK: store i32 49, i32* %size
// CHECK: store i32 52, i32* %size
template<typename T>
class TemplateClass {
public:
  void templateClassFunction() {
    int size = sizeof(__PRETTY_FUNCTION__);
  }
};

// CHECK: store i32 27, i32* %size
// CHECK: store i32 30, i32* %size
template<typename T>
void functionTemplate(T t) {
  int size = sizeof(__PRETTY_FUNCTION__);
}

int main() {
  TemplateClass<int> t1;
  t1.templateClassFunction();
  TemplateClass<double> t2;
  t2.templateClassFunction();

  functionTemplate<int>(0);
  functionTemplate(0.0);

  return 0;
}

Add test for dependent PredefinedExprs.


/*
 * Copyright 2010, NagaChaitanya Vellanki
 *
 * Author NagaChaitanya Vellanki
 *
 * Swapping two variables without auxillary
 */

#include <iostream>
#include <inttypes.h>

using namespace std;

int main()
{
  int32_t a = 10;
  int32_t b = 20;
  cout << "a is " << a << ",b is " << b << endl;
  a = a + b;
  b = a - b;
  a = a - b;
  cout << "After Swapping " << endl;
  cout << "a is " << a << ",b is " << b << endl;
  return 0;
}

Add Swapping without a auxillary variable


#include "EM_Classes.h"

Model::Model(const int &N_, const int &lagsS_, const int &lagsY_,
			 const bool &sigma_, const bool &beta_,
			 const bool &meanCorrected):
	N(N_), lagsS(lagsS_), lagsY(lagsY_), sigma(sigma_), beta(beta_),
	meanCorrected(meanCorrected){}

Model::Model(const int &N_ = 2, const int &lagsS_= 0,
			 const int &lagsY_= 0, const bool &sigma_ = TRUE,
			 const bool &beta_ = TRUE, const bool &meanCorrected):
	N(N_), lagsS(lagsS_), lagsY(lagsY_), sigma(sigma_), beta(beta_),
	meanCorrected(meanCorrected){}

Data::Data(const MatrixXd & y,const MatrixXd & x):
	Y(y){
	MatrixXd c;
	if (y.rows() > y.cols())
		Y.transposeInPlace();
	if (x.rows() > x.cols())
		x.transposeInPlace();
	T = y.rows();
	M = y.cols(); // if M = 1, Univariate model
	// T can't be different from x.rows()
	Mx = x.cols();
	X << c.setOnes(T, 0) << x;
}

Data::Data(const MatrixXd & y):
	Y(y){
	if(y.cols > y.rows)
		y.transposeInPlace()
	T = y.rows();
	M = y.cols();
	x.setOnes(T, 0);
	mX = x.cols();
}

Create constructors for classes Data and Model


/**
 * Delete Node in a Linked List
 *
 * cpselvis(cpselvis@gmail.com)
 * Oct 8th, 2016
 */

struct ListNode {
  int val;
  ListNode *next;
  ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
  void deleteNode(ListNode* node) {
    if (node != NULL)
      {
	node -> val = node -> next -> val;
	node -> next = node -> next -> next;
      }
  }
};

Delete Node in a Linked List.


#include <stdio.h>

typedef struct _NODE {
  int data;
  _NODE* left;
  _NODE* right;
} NODE;

NODE* newNode(int data) {
  NODE* node = new NODE();
  node->data = data;
  node->left = nullptr;
  node->right = nullptr;

  return node;
}

int toSumTree(NODE* root) {
  if (root == nullptr) return 0;

  int old_value = root->data;
  printf("old_value : [%d] \n", old_value);

  root->data = toSumTree(root->left) + toSumTree(root->right);

  printf("root->data : [%d] \n", root->data);
  return root->data + old_value;
}

void printInorder(NODE* node) {
  if (node) {
    printInorder(node->left);
    printf("%d ", node->data);
    printInorder(node->right);
  }
}

#if 0
                  10
               /      \
              -2        6
           /   \      /  \
         8     -4    7    5
#endif
int main(int argc, char const* argv[]) {
  NODE* root = newNode(10);
  root->left = newNode(-2);
  root->right = newNode(6);
  root->left->left = newNode(8);
  root->left->right = newNode(-4);
  root->right->left = newNode(7);
  root->right->right = newNode(5);

  toSumTree(root);

  // Print inorder traversal of the converted tree to test result of toSumTree()
  printf("Inorder Traversal of the resultant tree is: \n");
  printInorder(root);
  return 0;
}

Convert the given tree for sum property.


// 155. Min Stack
/**
 * Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
 *
 * push(x) -- Push element x onto stack.
 * pop() -- Removes the element on top of the stack.
 * top() -- Get the top element.
 * getMin() -- Retrieve the minimum element in the stack.
 *
 * Example:
 *
 * MinStack minStack = new MinStack();
 * minStack.push(-2);
 * minStack.push(0);
 * minStack.push(-3);
 * minStack.getMin();   --> Returns -3.
 * minStack.pop();
 * minStack.top();      --> Returns 0.
 * minStack.getMin();   --> Returns -2.
 *
 * Tags: Stack Design
 *
 * Similar Problems: (H) Sliding Window Maximum
 *
 * Author: Kuang Qin
 */

using namespace std;

#include <stack>
#include <iostream>

class MinStack {
private:
    stack<int> s1;    // s1 as the original stack
    stack<int> s2;    // s2 always keeps the current minimun element on the top

public:
    /** initialize your data structure here. */
    MinStack() {

    }

    void push(int x) {
        s1.push(x);
        if (s2.empty() || x <= getMin())
            s2.push(x);     // keep the top element of s2 the minimum
    }

    void pop() {
        if (s1.top() == getMin())
            s2.pop();
        s1.pop();
    }

    int top() {
        return s1.top();
    }

    int getMin() {
        return s2.top();
    }
};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

int main()
{
    MinStack obj;
    obj.push(0);
    obj.push(1);
    obj.push(0);
    int param_1 = obj.getMin();
    obj.pop();
    int param_2 = obj.top();
    int param_3 = obj.getMin();

    cout << param_1 << " " << param_2 << " " << param_3 << endl;
    system("pause");

    return 0;
}

Add Solution for 155 Min Stack


#include <iostream>
#include <string>
#include <map>
#include <list>
using namespace std;

typedef struct node
{
	int num;
	string str;
}c_node;

int main()
{
	int n;
	cin >> n;
	c_node *a = new c_node[n];
	for (int i = 0; i < n; i++) {
		cin >> a[i].num >> a[i].str;
	}
	map< int, list<string> > int_list_map;
	for (int i = 0; i < n; i++) {
		if (i < n / 2) {
			a[i].str = "-";
		}
		map< int, list<string> >::iterator iter = int_list_map.find(a[i].num);
		if (iter == int_list_map.end()) {
			list<string> str_list;
			str_list.push_back(a[i].str);
			int_list_map.insert(pair< int, list<string> > (a[i].num, str_list));
		}
		else {
			iter->second.push_back(a[i].str);
		}
	}
	for (map< int, list<string> >::iterator i = int_list_map.begin(); i != int_list_map.end(); i++) {
		while (!i->second.empty()) {
			cout << i->second.front() << " ";
			i->second.pop_front();
		}
	}
	delete [] a;
	return 0;
}

Add the solution to "The Full Counting Sort".


// RUN: %clang_cc1 -fsyntax-only -std=c++11 2>&1 %s | FileCheck -strict-whitespace %s

struct A {
  unsigned int a;
};

// PR10696
void testOverlappingInsertions(int b) {
  A var = { b };
  // CHECK:  A var = { b };
  // CHECK:            ^
  // CHECK:            static_cast<unsigned int>( )
}

Add a test for r158229 (overlapping fixits). This was PR10696!


// 035. Search Insert Position
/**
 * Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
 *
 * You may assume no duplicates in the array.
 *
 * Here are few examples.
 * [1,3,5,6], 5 -> 2
 * [1,3,5,6], 2 -> 1
 * [1,3,5,6], 7 -> 4
 * [1,3,5,6], 0 -> 0
 *
 * Tags: Array, Binary Search
 *
 * Similar Problems: (E) First Bad Version
 *
 * Author: Kuang Qin
 */

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

using namespace std;

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

        int left = 0, right = n - 1;
        while (left <= right)
        {
            int mid = (left + right) / 2;
            if (target == nums[mid])
            {
                return mid;
            }
            else if (target > nums[mid])
            {
                left = mid + 1;
            }
            else // target < nums[mid]
            {
                right = mid - 1;
            }
        }

        return left;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    vector<int> nums;
    nums.push_back(1);
    nums.push_back(3);
    nums.push_back(5);
    nums.push_back(6);
    int target = 0;

    Solution mySolution;
    int res = mySolution.searchInsert(nums, target);
    cout << res << endl;
    system("pause");
    return 0;
}

Add Solution for Problem 035


//
// Test Suite for geos::operation::OverlayOp class for UNION

#include <tut.hpp>
// geos
#include <geos/operation/overlay/OverlayOp.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/PrecisionModel.h>
#include <geos/io/WKBReader.h>
#include <geos/io/WKTReader.h>
// std
#include <string>
#include <memory>

using namespace geos::geom;
using namespace geos::operation;

namespace tut
{
    //
    // Test Group
    //

    struct test_overlayopunion_data
    {
        typedef geos::geom::Geometry::AutoPtr GeometryPtr;
        typedef geos::geom::GeometryFactory GeometryFactory;
        typedef geos::geom::GeometryFactory::unique_ptr GeometryFactoryPtr;
    };

    typedef test_group<test_overlayopunion_data> group;
    typedef group::object object;

    group test_issimpleop_group("geos::operation::OverlayOp::UNION");

    //
    // Test Cases
    //

    // 1 - Union four segments of a square
    template<>
    template<>
    void object::test<1>()
    {
        // Arrange
        geos::geom::PrecisionModel pm(1e+13);
        GeometryFactoryPtr factory = geos::geom::GeometryFactory::create(&pm);
        geos::io::WKTReader reader(*factory);
        GeometryPtr line1(reader.read("LINESTRING(0 0, 0 5)"));
        GeometryPtr line2(reader.read("LINESTRING(0 5, 5 5)"));
        GeometryPtr line3(reader.read("LINESTRING(5 5, 5 0)"));
        GeometryPtr line4(reader.read("LINESTRING(5 0, 0 0)"));

        // Act: union segments incrementally
        GeometryPtr lines12(line1->Union(line2.get()));
        GeometryPtr lines123(lines12->Union(line3.get()));
        GeometryPtr lines1234(lines123->Union(line4.get()));

        // Assert
        ensure_equals(lines1234->getGeometryTypeId(), geos::geom::GEOS_MULTILINESTRING);
    }

} // namespace tut

Add basic test for geos::operation::OverlayOp with UNION.


#include <stdio.h>
#include <map>
#include <vector>

typedef struct _NODE {
  int data;
  _NODE* left;
  _NODE* right;
} NODE;

NODE* NewNode(int data) {
  NODE* node = new NODE();
  node->data = data;
  node->left = node->right = nullptr;

  return node;
}

void PrintTopViewUtil(NODE* node, int level, std::map<int, int>& map) {
  if (node) {
    PrintTopViewUtil(node->left, level - 1, map);
    PrintTopViewUtil(node->right, level + 1, map);
    map[level] = node->data;
  }
}

void PrintTopView(NODE* node) {
  std::map<int, int> map;

  PrintTopViewUtil(node, 0, map);

  std::map<int, int>::iterator it;

  for (it = map.begin(); it != map.end(); it++) {
    printf("%d ", it->second);
  }
}

int main(int argc, char** argv) {
  NODE* root = NewNode(1);
  root->left = NewNode(2);
  root->right = NewNode(3);
  root->left->right = NewNode(4);
  root->left->right->right = NewNode(5);
  root->left->right->right->right = NewNode(6);

  PrintTopView(root);

  return 0;
}

Print top view of the binary tree.


// Description: Print slur linking info

#include "humlib.h"

using namespace hum;

int main(int argc, char** argv) {
   if (argc != 2) {
      return 1;
   }
   HumdrumFile infile;
   if (!infile.read(argv[1])) {
      return 1;
   }
cerr << "ANALYZING SLURS" << endl;
   infile.analyzeKernSlurs();
cerr << "DONE ANALYZING SLURS" << endl;
   return 0;
}

Add test program for slur parsing.


#include <iostream>
#include <string>

using namespace std;

int main()
{
  string time12;

  cin >> time12;

  char p = time12[time12.size() - 2];
  if (p == 'P')
  {
    int t = (int)time12[0] - '0';
    t = t * 10;
    t += (int)time12[1] - '0';
    if (t < 12)
    {
      t += 12;
    }
    cout << t;
    for (int i = 2; i < time12.size() - 2; i++)
    {
      cout << time12[i];
    }
    cout << endl;
  }
  else
  {
    int t = (int)time12[0] - '0';
    t = t * 10;
    t += (int)time12[1] - '0';
    if (t == 12)
    {
      t = 0;
    }

    if (t < 10) cout << 0;
    cout << t;
    for (int i = 2; i < time12.size() - 2; i++)
    {
      cout << time12[i];
    }
    cout << endl;
  }

  return 0;
}

Add a solution for time converter task


#include <iostream>

int main() {
  std::cout << "Hello, World!" << std::endl;
  return 0;
}

#include <iostream>
#include <stdlib.h>

#include "exampleConfig.h"
#include "example.h"

/*
 * Simple main program that demontrates how access
 * CMake definitions (here the version number) from source code.
 */
int main() {
  std::cout << "C++ Boiler Plate v"
            << PROJECT_VERSION_MAJOR
            << "."
            << PROJECT_VERSION_MINOR
            << std::endl;
  std::system("cat ../LICENCE");

  // Bring in the dummy class from the example source,
  // just to show that it is accessible from main.cpp.
  Dummy d = Dummy();
  return d.doSomething() ? 0 : -1;
}

Update example to demonstrate version numbers.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "../excercise04/make_random_data/make_random_data.hpp"
#include "../excercise04/sort/heap.hpp"
#include "../excercise04/sort/swap.hpp"
#include "priority_queue/priority_queue.hpp"

#define MIN_SIZE    100
#define MAX_SIZE    100000
#define SIZE_STEP   10

#define M   100

int main(void)
{
    srand(time(NULL));
    int *original = make_random_data(MAX_SIZE);

    for(int size_of_data = MIN_SIZE; size_of_data <= MAX_SIZE; size_of_data *= SIZE_STEP)
    {
        printf("SIZE OF DATA: %d\n", size_of_data);

        {
            const int capacity = size_of_data * 3;

            int data[capacity];
            memcpy(data, original, sizeof(int) * size_of_data);

            convert_to_binary_max_heap(data, size_of_data);

            clock_t before = clock();

            int count = size_of_data;
            for(int i = 0; i < M; ++i)
            {
                if(rand() % 2 == 0)
                    push_priority_queue(data, capacity, count, original[count]);
                else
                    pop_priority_queue(data, count);
            }

            clock_t after = clock();

            printf("Using heap:\t\t%lf\n", (double)(after - before)/CLOCKS_PER_SEC);
        }
        {
            int data[size_of_data];
            memcpy(data, original, sizeof(int) * size_of_data);

            clock_t before = clock();

            int count = size_of_data;
            for(int i = 0; i < M; ++i)
            {
                int max = data[0];
                if(rand() % 2 == 0) /* Push */
                {
                    data[count] = original[count++];
                }
                else /* Pop */
                {
                    for(int i = 0; i < count; ++i)
                        if(data[i] > max)
                        {
                            max = data[i];
                            swap(data[i], data[count--]);
                        }
                }
            }

            clock_t after = clock();

            printf("Not using heap:\t\t%lf\n", (double)(after - before)/CLOCKS_PER_SEC);
        }

        putchar('\n');
    }

    free_random_data(original);

    return 0;
}

Add a solution of prob 2


/*
 * Lattice paths
 *
 * Starting in the top left corner of a 2×2 grid, and only being able to move
 * to the right and down, there are exactly 6 routes to the bottom right corner.
 *
 * How many such routes are there through a 20×20 grid?
 */

#include <iostream>

using Long = unsigned long long int;

// Forward declaration
constexpr Long binomial(unsigned n, unsigned k);

constexpr unsigned cols = 20;
constexpr unsigned rows = 20;

int main(int, char **) {
    // The number of paths through an n×m lattice is binomial(n+m, n).
    auto paths = binomial(rows + cols, rows);

    std::cout << "Project Euler - Problem 15: Lattice paths\n\n";
    std::cout << "The number of paths through a " << rows << u8"×" << cols
              << " lattice is\n"
              << paths << '\n';
}

/**
 * Compute the binomial coefficient n over k.
 *
 * @param n Parameter n.
 * @param k Parameter k.
 * @return The binomial coefficient, or 0 if k > n.
 */
constexpr Long binomial(unsigned n, unsigned k) {
    if(k > n) {
        return 0;
    }
    if(k > (n + 1) / 2) {
        return binomial(n, n - k);
    }
    Long result = 1;
    for(unsigned j = 1; j <= k; j++) {
        result = result * (n + 1 - j) / j;
    }
    return result;
}

Add solution to problem 15 in C++.


#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
	int n, money;
	cin >> n >> money;
	int *toys = new int[n];
	for (int i = 0; i < n ; i++) {
		cin >> toys[i];
	}
	sort(toys, toys + n);
	int sum = 0;
	int count = 0;
	for (int i = 0; i < n; i++) {
		if (sum + toys[i] > money) {
			break;
		}
		else {
			sum += toys[i];
			count++;
		}
	}
	cout << count;
	delete [] toys;
	return 0;
}

Add the solution to "Mark and Toys".


// Copyright [2016] <Malinovsky Rodion>

#include "core/engine.h"
#include "gtest/gtest.h"

// Implement Engine test
// 1. Create a fixture, take base code from EngineLauncher
// 2. create cond var, which will emulate  SIGINT
// 3. run engine -> create server socket
// 4. create tcp client and write data to server socket
// 5. verify output of the echo server.

#error missing-implementation

Add stub for engine test with test plan


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


#include <UnitTest++.h>

// Unit tests for vec classes

#include <OpenSG/OSGNode.h>
#include <OpenSG/OSGNameAttachment.h>

TEST(CreateNode)
{
   OSG::NodePtr n = OSG::Node::create();
   CHECK(n != OSG::NullFC);
}

// --- Cloning --- //
TEST(TreeCloningName)
{
   OSG::NodePtr root = OSG::Node::create();
   OSG::NodePtr child_node = OSG::Node::create();
   root->addChild(child_node);
   OSG::setName(root, "root");
   OSG::setName(child_node, "child_node");

   OSG::NodePtr new_root = OSG::cloneTree(root);

   CHECK(new_root->getNChildren() == 1);
   CHECK(new_root != root);
   CHECK(new_root->getChild(0) != child_node);

   std::string new_name = OSG::getName(new_root);
   CHECK(new_name == "root");
}

Add node test. Fails for now. Need to figure out a way to handle osgInit.


#include "classad/classad_distribution.h"

#include <string>
#include <string.h>
#include <sys/types.h>

/* This is the driver for the classad fuzz tester.
 * Note this is intentionally not in the cmake file, it should not be built
 * by default.
 *
 * To use, compile all of classads with clang -fsanitize=fuzzer-nolink,address
 * then recompile this one file with clang -fsanitize=fuzzer
 * This adds a magic main function here.
 * Then, just run ./a.out and let it run for a long time.
 */

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *input, size_t len) {

	classad::ClassAdParser parser;
	classad::ExprTree  *tree;
	std::string s(input, input + len);

	tree = parser.ParseExpression(s);
	delete tree;

	return 0;
}

Add fuzzing driver to classads HTCONDOR-814


// 145 Binary Tree PostOrder Tranversal
/**
* Given a binary tree, return the postorder traversal of its nodes' values.
*
* For example:
* Given binary tree {1,#,2,3},
*    1
*     \
*      2
*     /
*    3
* return [3,2,1].
*
* Note: Recursive solution is trivial, could you do it iteratively?
*
* Tag:    Tree, Stack
*
* Author: Yanbin Lu
*/

#include <stddef.h>
#include <vector>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <stack>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if(!root) return res;

        stack<TreeNode*> s;
        s.push(root);
        TreeNode* pre = NULL;
        TreeNode* cur;
        while (!s.empty()) {
            cur = s.top();

            // !pre coresponds to the root case, otherwise going down
            if(!pre || pre->left == cur || pre->right == cur){
                if(cur->left)               // to left child if exist
                    s.push(cur->left);      // t right child if left child doesnt exist
                else if(cur->right)
                    s.push(cur->right);
                else{                       // this is the leaf
                    s.pop();
                    res.push_back(cur->val);
                }
            }

            // going up from the left child
            else if(cur->left == pre){
                if(cur->right)
                    s.push(cur->right);      // to the right child if exist
                else{
                    s.pop();
                    res.push_back(cur->val);
                }
            }

            // going up from the right side, done from this point dowm
            else if(cur->right == pre){
                s.pop();
                res.push_back(cur->val);
            }

            pre = cur;
        }

        return res;
    }
};

int main()
{

    TreeNode* root = new TreeNode(2);
    root->left = new TreeNode(3);
    root->right = new TreeNode(4);
    root->left->right = new TreeNode(5);
    Solution* sol = new Solution();
    vector<int> res = sol->postorderTraversal(root);
    for(int i = 0; i < res.size(); i++)
        cout << res[i] << endl;

    char c;
    std::cin>>c;

    return 0;
}

Add 145 Binary Tree Postorder Traversal


Check if sum exists in two arrays


#include "path.hpp"

void Path::init()
{
    // FIXME: unimplemented
}

#include <stdlib.h>

IFile *Path::openIFile(std::string const &path)
{
    // FIXME: unimplemented
    abort();
    return NULL;
}

Add placeholder Windows path code


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

void f() {
  void *p = malloc(sizeof(int) * 10); // expected-error{{no matching function for call to 'malloc'}}
}

int malloc(double);

Add test case to insure that implicit builtin declarations for C library functions aren't created in C++


#include <cmath>
#include <fmt/format.h>

struct ieee754 {
	int sign;
	int biased_exponent;
	uint64_t fraction;

	uint64_t significand() const { return 0x10'0000'0000'0000 | fraction; }
	int exponent() const { return biased_exponent - 1023; }

	explicit ieee754(double value) {
		auto bits = fmt::internal::bit_cast<uint64_t>(value);
		sign = bits >> 63;
		biased_exponent = static_cast<int>(bits >> 52) & 0x7ff;
		fraction = bits & 0xf'ffff'ffff'ffff;
	}
};

template <>
struct fmt::formatter<ieee754> {
	auto parse(format_parse_context& ctx) { return ctx.begin(); }

	auto format(ieee754 n, format_context& ctx) {
		return format_to(ctx.out(), "{} {:011b} {:052b} [e = {}]", n.sign, n.biased_exponent, n.fraction, n.exponent());
	}
};

int main(int argc, char* argv[]) {
	fmt::print("{}\n", ieee754(M_PI));
	return 0;
}

ADD floating point format library example.


// Copyright (c) 2017 Pierre Fourgeaud
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include <bandit/bandit.h>
#include "core/math/utils.h"

using namespace bandit;
using namespace snowhouse;
using namespace CodeHero;

go_bandit([]() {
    describe("::Clamp", []() {
        it("should not do anything if in the range", [] {
            AssertThat(Clamp(5.0f, 0.0f, 10.0f), Equals(5.0f));
            AssertThat(Clamp(5, 0, 10), Equals(5));
        });

        it("should Clamp the value back in the range is value is smaller than min", [] {
            AssertThat(Clamp(-5.0f, 0.0f, 10.0f), Equals(0.0f));
            AssertThat(Clamp(-5, 0, 10), Equals(0));
        });

        it("should Clamp the value back in the range is value is bigger than max", [] {
            AssertThat(Clamp(15.0f, 0.0f, 10.0f), Equals(10.0f));
            AssertThat(Clamp(15, 0, 10), Equals(10));
        });
    });
});

Add test for Clamp function in math/utils


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

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

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

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

#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"

namespace tensorflow {

// Filesystem Ops ----------------------------------------------------------

REGISTER_OP("FileSystemSetConfiguration")
    .Input("scheme: string")
    .Input("key: string")
    .Input("value: string")
    .SetIsStateful()
    .SetShapeFn(shape_inference::ScalarShape);

}  // namespace tensorflow

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

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

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

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

#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"

namespace tensorflow {

// Filesystem Ops ----------------------------------------------------------

REGISTER_OP("FileSystemSetConfiguration")
    .Input("scheme: string")
    .Input("key: string")
    .Input("value: string")
    .SetIsStateful()
    .SetShapeFn(shape_inference::NoOutputs);

}  // namespace tensorflow

Set NoOutputs as the shape inference function for the FileSystemSetConfiguration op.


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

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

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

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

#include "tensorflow/core/platform/cuda_libdevice_path.h"

#include <stdlib.h>

#include <vector>

#include "tensorflow/core/platform/platform.h"

#if !defined(PLATFORM_GOOGLE)
#include "third_party/gpus/cuda/cuda_config.h"
#endif
#include "tensorflow/core/platform/logging.h"

namespace tensorflow {

std::vector<string> CandidateCudaRoots() {
#if !defined(PLATFORM_GOOGLE)
  VLOG(3) << "CUDA root = " << TF_CUDA_TOOLKIT_PATH;
  return {TF_CUDA_TOOLKIT_PATH, string("/usr/local/cuda")};
#else
  return {string("/usr/local/cuda")};
#endif
}

bool PreferPtxasFromPath() { return true; }

}  // namespace tensorflow

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

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

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

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

#include "tensorflow/core/platform/cuda_libdevice_path.h"

#include <stdlib.h>

#include <string>
#include <vector>

#include "tensorflow/core/platform/platform.h"

#if !defined(PLATFORM_GOOGLE)
#include "third_party/gpus/cuda/cuda_config.h"
#endif
#include "tensorflow/core/platform/logging.h"

namespace tensorflow {

std::vector<std::string> CandidateCudaRoots() {
#if !defined(PLATFORM_GOOGLE)
  VLOG(3) << "CUDA root = " << TF_CUDA_TOOLKIT_PATH;
  return {TF_CUDA_TOOLKIT_PATH, std::string("/usr/local/cuda")};
#else
  return {std::string("/usr/local/cuda")};
#endif
}

bool PreferPtxasFromPath() { return true; }

}  // namespace tensorflow

Fix missing qualifier for std::string


#include <iostream>
#include <bitset>
#include <vector>
using namespace std;

int main() {
    vector<int> ivec = {1, 2, 3, 5, 8, 13, 21};
    unsigned long val = 0UL;
    for(auto i : ivec) {
        val |= 1UL << i;
    }
    cout << val << endl;
    bitset<32> b(val);
    cout << b << endl;

    bitset<32> bb;
    for(auto i : ivec) {
        bb.set(i);
    }
    cout << bb << endl;
    if(b == bb) {
        cout << "b == bb" << endl;
    }
}

Add solution for chapter 17 test 10


/**
g++ pipe_fds.cpp -g -O0 -o pipe_fds

About the limits:
[winlin@dev6 srs]$ ulimit -n
    1024
[winlin@dev6 srs]$ sudo lsof -p 21182
    pipe_fds 21182 winlin    0u   CHR  136,4      0t0       7 /dev/pts/4
    pipe_fds 21182 winlin    1u   CHR  136,4      0t0       7 /dev/pts/4
    pipe_fds 21182 winlin    2u   CHR  136,4      0t0       7 /dev/pts/4
    pipe_fds 21182 winlin    3r  FIFO    0,8      0t0  464543 pipe
    pipe_fds 21182 winlin 1021r  FIFO    0,8      0t0  465052 pipe
    pipe_fds 21182 winlin 1022w  FIFO    0,8      0t0  465052 pipe
So, all fds can be open is <1024, that is, can open 1023 files.
The 0, 1, 2 is opened file, so can open 1023-3=1020files,
Where 1020/2=512, so we can open 512 pipes.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int main(int argc, char** argv)
{
    if (argc <= 1) {
        printf("Usage: %s <nb_pipes>\n"
            "   nb_pipes the pipes to open.\n"
            "For example:\n"
            "   %s 1024\n", argv[0], argv[0]);
        exit(-1);
    }

    int nb_pipes = ::atoi(argv[1]);
    for (int i = 0; i < nb_pipes; i++) {
        int fds[2];
        if (pipe(fds) < 0) {
            printf("failed to create pipe. i=%d, errno=%d(%s)\n",
                i, errno, strerror(errno));
            break;
        }
    }

    printf("Press CTRL+C to quit, use bellow command to show the fds opened:\n");
    printf("    sudo lsof -p %d\n", getpid());
    sleep(-1);
    return 0;
}

Revert "Revert "add test file to show the max open files.""


#include <iostream>

using namespace std;

int main(){
  cout << "Starting Program..." << flush;

  cout << "This is the first line" << endl;

  cout << "-Item 1. " << "-Item 2. " << "-Item 3." << endl;

  cout << "The Program is ending." << endl;

  return 0;
}

Implement Outputting Text Program in C++


// Chapter 25, exercise 7: write out the hexadecimal values from 0 to 400; write
// out the hexadecimal values from -200 to 200

#include<iostream>
#include<iomanip>

using namespace std;

int main()
{
    cout << "0 to 400:\n\n";
    for (int i = 0; i<=400; ++i)
        cout << hex << i << (i%16 ? '\t' : '\n');

    cout << "\n\n-200 to 200:\n\n";
    for (int i = -200; i<=200; ++i)
        cout << hex << i << (i%8 ? '\t' : '\n');
}

Add Chapter 25, exercise 7


#include <iostream>
#include <string>
#include <sstream>

using namespace std;

template <typename T>
string debug_rep(const T &t) {
    ostringstream ret;
    ret << t;
    return ret.str();
}

template <typename T>
string debug_rep(T *p) {
    ostringstream ret;
    ret << "pointer: " << p;
    if(p) {
        ret << " content: " << debug_rep(*p);
    } else {
        ret << " null pointer";
    }
    return ret.str();
}

string debug_rep(const string &s) {
    return '"' + s + '"' + "no template";
}

int main() {
    string s("hi");
    cout << debug_rep(s) << endl;//call debug_rep(const T&t), T is string, when the third function is commented
    cout << debug_rep(&s) << endl;//call debug_rep(T*p), T is string

    const string *sp = &s;
    cout << debug_rep(sp) << endl;//call debug_rep(T* p), T is const string, this one is more specialize

    //const char*
    cout << debug_rep("hi world!") << endl;
}

Add solution for chapter 16 test 48.


// Decorator (run-time)

class foo
{
	public:
		virtual void do_work() = 0;
};

class foo_concrete : public foo
{
	public:
		virtual void do_work()
		{ }
};

class foo_decorator : public foo
{
	public:
		foo_decorator(foo& f)
			: f(f)
		{ }

		virtual void do_work() {
			// Do something else here to decorate
			// the do_work function
			f.do_work();
		}

	private:
		foo& f;
};

void bar(foo& f)
{
	f.do_work();
}

int main()
{
	foo_concrete f;
	foo_decorator decorated_f{f};

	bar(decorated_f);
}

// Wrap a class with a decorator to extend its functionality.
//
// On [9-14], we define the class that we wish to decorate,
// `foo_concrete`, which implements the `foo` interface.
//
// The `foo_decorator` class, on [16-31], also implements the
// `foo` interface. This decorator class wraps any other `foo`
// object, which is passed to the constructor by reference[19-21]
// and decorates its member functions. That is, the
// `foo_decorator::do_work` function ([23-27]) simply calls the
// wrapped object's `do_work` function, while doing some extra work.
//
// To demonstrate, we wrap a `foo_concrete` with a `foo_decorator` on
// [40-41], and pass it to the `bar` function on [43], which takes a
// reference to any `foo` object and calls `do_work` on it. In this
// case, the call will be decorated by `foo_decorator`.

Add "run-time decorator pattern" sample


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

// This is the function actually selected during overload resolution, and the
// only one defined.
template <typename T> void f(T*, int) {}

template <typename T> struct S;
template <typename T> struct S_ : S<T> { typedef int type; }; // expected-note{{in instantiation}}
template <typename T> struct S {
  // Force T to have a complete type here so we can observe instantiations with
  // incomplete types.
  T t; // expected-error{{field has incomplete type}}
};

// Provide a bad class and an overload that instantiates templates with it.
class NoDefinition; // expected-note{{forward declaration}}
template <typename T> S_<NoDefinition>::type f(T*, NoDefinition*); // expected-note{{in instantiation}}

void test(int x) {
  f(&x, 0);
}

Add a test for a subtle instantiation pattern that showed up within a Boost miscompile reduction. Clang already handles this correctly, but let's make sure it stays that way.


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

using namespace Halide;

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

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

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

    g.realize(10);

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

Add error test for inlined stages


// RUN: clang-format -output-replacements-xml -sort-includes %s > %t.xml
// RUN: FileCheck -strict-whitespace -input-file=%t.xml %s

// CHECK: <?xml
// CHECK-NEXT: {{<replacements.*incomplete_format='false'}}
// CHECK-NEXT: {{<replacement.*#include
#include <}}
// CHECK-NEXT: {{<replacement.*>
<}}
// CHECK-NEXT: {{<replacement.*> <}}
#include
#include

int a;int*b;

Add test for (properly escaped) XML output.


#include "types.hpp"
#include "constants.hpp"

#include "sys/sysctl.hpp"

#include <iostream>  /* std::cout, std::cerr */
#include <chrono>    /* std::chrono::steady_clock::now() */
#include <thread>    /* std::this_thread::sleep_until() */

#include <sys/resource.h>  /* CPUSTATES */

namespace {

using namespace types;
using namespace constants;

} /* namespace */

int main(int argc, char * argv[]) {
	sys::ctl::SysctlOnce<coreid_t, 2> const ncpu{0, {CTL_HW, HW_NCPU}};
	sys::ctl::Sysctl<2> const cp_times_ctl = {CP_TIMES};

	auto cp_times = std::unique_ptr<cptime_t[][CPUSTATES]>(
	    new cptime_t[2 * ncpu][CPUSTATES]{});

	auto time = std::chrono::steady_clock::now();
	//auto const start = time;
	size_t sample = 0;
	while (true) {
		std::this_thread::sleep_until(time += ms{50});
		cp_times_ctl.get(cp_times[sample * ncpu],
		                 ncpu * sizeof(cp_times[0]));
		for (size_t i = 0; i < ncpu; ++i) {
			std::cout << "cpu" << i << ':';
			for (size_t q = 0; q < CPUSTATES; ++q) {
				std::cout << ' '
				          << (cp_times[sample * ncpu + i][q] -
				              cp_times[((sample + 1) % 2) * ncpu + i][q]);
			}
			std::cout << '\n';
		}
		sample = (sample + 1) % 2;
	}
}

Add primitive load recorder prototype


/*
 * Copyright (C) 2015-2016 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#include <bits/stdc++.h>

void generate(std::string prefix, int open, int len) {
    if (len == prefix.size()) {
        std::cout << prefix << std::endl;
    } else {
        if (open < (len - prefix.size())) {
            generate(prefix + '(', open + 1, len);
        }
        if (open > 0 ) {
            generate(prefix + ')', open - 1, len);
        }
    }
}

int main() {
    int n;
    std::cin >> n;
    generate("", 0, n * 2);
    return 0;
}

Add problem about parenthesis sequences


#include<iostream>
#include<cstdlib>

using namespace std;

class Node{
        public:
                int data;
                Node *next;

                Node(){}

                Node(int d){
                        data=d;
                        next=NULL;
                }

                Node *insertElement(Node *head,int d){
                        Node *np=new Node(d);
                        Node *tmp=head;

                        if(head==NULL)
                                return np;
                        else
                                while(tmp->next)
                                        tmp=tmp->next;

                        tmp->next=np;

                        return head;
                }

		void deleteList(Node *head){
			while(head->next!=NULL){
				Node *t=head;
				cout<<"Freeing "<<t->data<<".\n";
				head=head->next;
				free(t);
			}
			cout<<"Freeing "<<head->data<<".\n";
			free(head);
			cout<<"The list is empty now.\n";
		}
};

int main()
{
        int n,p;
        Node np;
        Node *head=NULL;

        cout<<"Enter the size of linked list: ";
        cin>>n;

        for(int i=0;i<n;i++){
                        cout<<"\nEnter element "<<i+1<<": ";
                        cin>>p;
                        head=np.insertElement(head,p);
                }
	np.deleteList(head);
}

Add code to delete a Linked List


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

#include "tests.h"

#if defined(BOTAN_HAS_X509_CERTIFICATES)

#include <botan/datastor.h>

namespace Botan_Tests {

class Datastore_Tests : public Test
   {
   public:
      std::vector<Test::Result> run() override
         {
         Test::Result result("Data_Store");

         Botan::Data_Store ds1;
         Botan::Data_Store ds2;

         result.confirm("equality", ds1 == ds2);

         result.test_eq("has_value", ds1.has_value("key"), false);
         result.test_eq("get1 with default", ds1.get1("key", "default"), "default");

         result.test_throws("get1", "Data_Store::get1: No values set for missing_key",
                            [&ds1]() { ds1.get1("missing_key"); });

         result.test_eq("search_for", ds1.search_for([](std::string, std::string) { return true; }).size(), 0);

         ds1.add("key", "value");

         result.test_eq("search_for", ds1.search_for([](std::string, std::string) { return true; }).size(), 1);

         result.test_eq("equality", ds1 == ds2, false);

         result.test_eq("has_value", ds1.has_value("key"), true);
         result.test_eq("get1 with default", ds1.get1("key", "default"), "value");
         result.test_eq("get1", ds1.get1("key"), "value");

         result.test_eq("get1_memvec", ds1.get1_memvec("memvec").size(), 0);

         const std::vector<uint8_t> memvec = { 9, 1, 1, 4 };
         ds1.add("memvec", memvec);

         result.test_eq("get1_memvec", ds1.get1_memvec("memvec"), memvec);

         result.test_eq("get1_uint32", ds1.get1_uint32("memvec"), size_t(9010104));

         result.test_eq("get1_uint32", ds1.get1_uint32("missing", 999), size_t(999));

         ds1.add("key", "value2");

         result.test_throws("get1", "Data_Store::get1: More than one value for key",
                            [&ds1]() { ds1.get1("key"); });

         result.test_eq("get multiple", ds1.get("key").size(), 2);

         return {result};
         }
   };

BOTAN_REGISTER_TEST("x509_datastore", Datastore_Tests);

}

#endif

Add some basic tests of Data_Store class


#include <iostream>
#include <stack>
#include <utility>

using std::cout;
using std::boolalpha;
using std::stack;
using std::pair;

class ParenthesesPair {
  pair<char, char> parentheses;

public:

  ParenthesesPair(char opening, char closing): parentheses(opening, closing) {}

  char opening() const {
    return parentheses.first;
  }

  char closing() const {
    return parentheses.second;
  }

  bool operator==(const ParenthesesPair& other_parentheses_pair) const {
    return opening() == other_parentheses_pair.opening() &&
           closing() == other_parentheses_pair.closing();
  }
};

ParenthesesPair parentheses_pairs[4] {
  {'(', ')'},
  {'[', ']'},
  {'{', '}'},
  {'<', '>'}
};

bool is_opening_parenthesis(char character) {
  for (int i = 0; i < 4; ++i) {
    if (parentheses_pairs[i].opening() == character) {
      return true;
    }
  }

  return false;
}

bool is_closing_parenthesis(char character) {
  for (int i = 0; i < 4; ++i) {
    if (parentheses_pairs[i].closing() == character) {
      return true;
    }
  }

  return false;
}

bool parentheses_match(const ParenthesesPair& parentheses_pair) {
  for (int i = 0; i < 4; ++i) {
    if (parentheses_pairs[i] == parentheses_pair) {
      return true;
    }
  }

  return false;
}

bool are_parentheses_correct(const char* expression) {
  stack<char> opening_parentheses;

  while (*expression) {
    if (is_opening_parenthesis(*expression)) {
      opening_parentheses.push(*expression);
    } else if (is_closing_parenthesis(*expression)) {
      if (!opening_parentheses.empty() &&
          parentheses_match(ParenthesesPair(opening_parentheses.top(), *expression))) {
        opening_parentheses.pop();
      } else {
        return false;
      }
    }

    ++expression;
  }

  return opening_parentheses.empty();
}

int main() {
  cout << boolalpha << are_parentheses_correct("{(1 + 2) * [(2 + 3) / 2]}") << '\n';
  cout << boolalpha << are_parentheses_correct("(1 + 2) * [(2 + 3] / 2]") << '\n';
  cout << boolalpha << are_parentheses_correct("(1 + 2))( * [(2 + 3) / 2]") << '\n';

  return 0;
}

Add solution to the matching parentheses problem with multiple kinds of parentheses. This solution uses stack data structure


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

#include <cassert>

struct  A {};
A a;
const A ca = A();

void test1 ()
{
    try
    {
        throw &a;
        assert(false);
    }
    catch ( const A* )
    {
    }
    catch ( A *)
    {
        assert (false);
    }
}

void test2 ()
{
    try
     {
    	throw &a;
        assert(false);
    }
    catch ( A* )
    {
    }
    catch ( const A *)
    {
         assert (false);
    }
}

void test3 ()
{
    try
    {
        throw &ca;
        assert(false);
    }
    catch ( const A* )
    {
    }
    catch ( A *)
    {
        assert (false);
    }
}

void test4 ()
{
    try
    {
        throw &ca;
        assert(false);
    }
    catch ( A *)
    {
        assert (false);
    }
    catch ( const A* )
    {
    }
}

int main()
{
    test1();
    test2();
    test3();
    test4();
}

Add test for pointer qualification conversion.


#include <iostream>
#include <string>

void findPossiblePlainTexts(const std::string&, int);
char* decrypt(const char*);

int main(int argc, char** argv)
{
  std::cout << "Letter Frequency attack on additive cipher\n";
  std::cout << "Enter the cipher text: ";

  std::string ciphertext;
  std::cin >> ciphertext;

  int num;
  std::cout << "Total possible plaintext sets: ";
  std::cin >> num;

  findPossiblePlainTexts(ciphertext, num);
}

void findPossiblePlainTexts(const std::string& cipherText, int num)
{
  int i = 0;
  const char *array = cipherText.c_str();
  while (i < num) {
    std::cout << i + 1 << decrypt(array) << "\n";
  }
}

char* decrypt(const char *cipherText)
{
  return nullptr;
}

Add basic structure and interface


/*
    This file is part of KAddressBook.
    Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>

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

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "kcmkabldapconfig.h"

#include <QtGui/QCheckBox>
#include <QtGui/QVBoxLayout>

#include <kaboutdata.h>
#include <kcomponentdata.h>
#include <kdemacros.h>
#include <kgenericfactory.h>
#include <klocale.h>

#include "ldapoptionswidget.h"

K_PLUGIN_FACTORY(KCMKabLdapConfigFactory, registerPlugin<KCMKabLdapConfig>();)
K_EXPORT_PLUGIN(KCMKabLdapConfigFactory( "kcmkabldapconfig" ))

KCMKabLdapConfig::KCMKabLdapConfig( QWidget *parent, const QVariantList & )
  : KCModule( KCMKabLdapConfigFactory::componentData(), parent )
{
  KGlobal::locale()->insertCatalog( "libkldap" );
  QVBoxLayout *layout = new QVBoxLayout( this );
  mConfigWidget = new LDAPOptionsWidget( this );
  layout->addWidget( mConfigWidget );

  connect( mConfigWidget, SIGNAL( changed( bool ) ), SIGNAL( changed( bool ) ) );

  load();

  KAboutData *about = new KAboutData( I18N_NOOP( "kcmkabldapconfig" ), 0,
                                      ki18n( "KAB LDAP Configure Dialog" ),
                                      0, KLocalizedString(), KAboutData::License_GPL,
                                      ki18n( "(c), 2003 - 2004 Tobias Koenig" ) );

  about->addAuthor( ki18n("Tobias Koenig"), KLocalizedString(), "tokoe@kde.org" );
  setAboutData( about );
}

void KCMKabLdapConfig::load()
{
  mConfigWidget->restoreSettings();
}

void KCMKabLdapConfig::save()
{
  mConfigWidget->saveSettings();
}

void KCMKabLdapConfig::defaults()
{
  mConfigWidget->defaults();
}

#include "kcmkabldapconfig.moc"

Insert libkldap catalog to translate dialogbox when we "add host"


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

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

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

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

#if !defined(PLATFORM_GOOGLE)
#include "tensorflow/compiler/xla/stream_executor/tpu/tpu_initializer_helper.h"
#endif

namespace tensorflow {
namespace tpu {
namespace {
#if !defined(PLATFORM_GOOGLE)
static Status tpu_library_finder = FindAndLoadTpuLibrary();
#endif
}  // namespace
}  // namespace tpu
}  // namespace tensorflow

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

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

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

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

#if !defined(PLATFORM_GOOGLE)
#include "tensorflow/compiler/xla/stream_executor/tpu/tpu_initializer_helper.h"
#include "tensorflow/core/platform/status.h"
#endif

namespace tensorflow {
namespace tpu {
namespace {
#if !defined(PLATFORM_GOOGLE)
static Status tpu_library_finder = FindAndLoadTpuLibrary();
#endif
}  // namespace
}  // namespace tpu
}  // namespace tensorflow

Fix TPU VM tf-nightly build


// -*- C++ -*-
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// REQUIRES: clang
// XFAIL: *

// This tests is meant to demonstrate an existing ABI bug between the
// C++03 and C++11 implementations of std::function. It is not a real test.

// RUN: %cxx -c %s -o %t.first.o %flags %compile_flags -std=c++03 -g
// RUN: %cxx -c %s -o %t.second.o -DWITH_MAIN %flags %compile_flags -g -std=c++11
// RUN: %cxx -o %t.exe %t.first.o %t.second.o %flags %link_flags -g
// RUN: %run

#include <functional>
#include <cassert>

typedef std::function<void(int)> Func;

Func CreateFunc();

#ifndef WITH_MAIN
// In C++03, the functions call operator, which is a part of the vtable,
// is defined as 'void operator()(int)', but in C++11 it's
// void operator()(int&&)'. So when the C++03 version is passed to C++11 code
// the value of the integer is interpreted as its address.
void test(int x) {
  assert(x == 42);
}
Func CreateFunc() {
  Func f(&test);
  return f;
}
#else
int main() {
  Func f = CreateFunc();
  f(42);
}
#endif

Check in test that demonstrates ABI break for std::function.


// Given a Binary Search Tree (BST), modify it so that all greater values in the given BST are added to every node.

#include <iostream>
using namespace std;

struct Node{
	int data;
	struct Node *left;
	struct Node *right;
};

struct Node *newNode(int x){
	struct Node *newptr = new Node;
	newptr->data = x;
	newptr->left = NULL;
	newptr->right = NULL;
return newptr;
}

void displayInorder(struct Node *root){
	if(root == NULL)
		return;
	displayInorder(root->left);
	cout<<root->data<<" ";
	displayInorder(root->right);
}

struct Node *insertNode(struct Node *root, int x){
	struct Node *newptr = newNode(x);
	if(root == NULL)
		return newptr;
	if(x > root->data)
		root->right = insertNode(root->right, x);
	else
		root->left = insertNode(root->left, x);
return root;
}

void modifyBSTUtil(struct Node *root, int *sum){
	// Base case
	if(root == NULL)
		return;
	// Recur for right subtree
	modifyBSTUtil(root->right, sum);

	// Now *sum has sum of nodes in right subtree, add root->data to sum and update root->data
	*sum = *sum + root->data;
	root->data = *sum;

	// Recur for left subtree
	modifyBSTUtil(root->left, sum);
}

void modifyBST(struct Node *root){
	int sum = 0;
	modifyBSTUtil(root, &sum);
}

int main(){
	struct Node *root = NULL;
	int num, size;
	cout<<"Enter the number of elements in BST\n";
	cin>>size;
	cout<<"Enter the elements of BST\n";
	while(size--){
		cin>>num;
		root = insertNode(root, num);
	}
	cout<<"Inorder traversal of original BST is\n";
	displayInorder(root);

	modifyBST(root);

	cout<<"\nInorder traversal of modified BST is\n";
	displayInorder(root);
return 0;
}

Add all greater nodes to a node in BST.


#include <bits/stdc++.h>

using namespace std;

int main()
{
    int arr[9] = { 1, 4, 2, 3, 8, 3, 4, 1, 9};		// LIS should be {1, 2, 3, 8, 9}
   	int	f[9] = {}, LIS[9] = {}, max = 1, L = 0;		// f used to record previous location of LIS
    for (int i = 0; i < 9; i++)
    {
        LIS[i] = 1;
        f[i] = i;
    }
    for (int i = 1; i < 9; i++)
    {
        for (int j = 0; j <= i; j++)
        {
            if (arr[j] < arr[i] && LIS[j]+1 > LIS[i])
            {
                LIS[i] = LIS[j] + 1;
                if (LIS[i] > max)
				{
					max = LIS[i];
					L = i;
				}
                f[i] = j;
            }
        }
    }
	int tmp = L;
	while(LIS[L]--)
	{
		cout << arr[tmp] << " ";
		tmp = f[tmp];
	}
    cout << endl;
    return 0;
}

Add longest increasing subsequence in c++


#include <algorithm>

#include <bts/import_bitcoin_wallet.hpp>

#include <fc/exception/exception.hpp>
#include <fc/log/logger.hpp>

#include <fc/crypto/aes.hpp>
#include <fc/crypto/base58.hpp>
#include <fc/crypto/hex.hpp>

namespace bts { namespace bitcoin {

std::vector<fc::ecc::private_key> import_bitcoin_wallet( const fc::path& wallet_dat, const std::string& passphrase )
{ try {
  FC_ASSERT( !"Support for Importing Bitcoin Core wallets was not compiled in.", "Unable to load wallet ${wallet}", ("wallet",wallet_dat) );
} FC_RETHROW_EXCEPTIONS( warn, "" ) }

} } // bts::bitcoin

#include <algorithm>

#include <fc/exception/exception.hpp>
#include <fc/log/logger.hpp>

#include <fc/crypto/aes.hpp>
#include <fc/crypto/base58.hpp>
#include <fc/crypto/hex.hpp>
#include <fc/crypto/elliptic.hpp>
#include <fc/filesystem.hpp>

namespace bts { namespace bitcoin {

std::vector<fc::ecc::private_key> import_bitcoin_wallet( const fc::path& wallet_dat, const std::string& passphrase )
{ try {
  FC_ASSERT( !"Support for Importing Bitcoin Core wallets was not compiled in.", "Unable to load wallet ${wallet}", ("wallet",wallet_dat) );
} FC_RETHROW_EXCEPTIONS( warn, "" ) }

} } // bts::bitcoin

Fix includes for compiling the bitcoin import stub used when berkeley db is not available


#include "test_helper.h"
#include "uTensor/loaders/tensorIdxImporter.hpp"

#include <iostream>
using std::cout;
using std::endl;

TensorIdxImporter t_import;
Context ctx;

void test_core_ntoh32(void) {

  uint32_t input = 63;

  uint32_t result = ntoh32(input);

  EXPECT_EQ(result, 1056964608);
}

void test_core_importUchar(void) {

  TensorIdxImporter t_import;

  Tensor* t =
      t_import.ubyte_import("/fs/constants/idxImport/uint8_4d_power2.idx");

  double result = sum<unsigned char>(t);
  EXPECT_EQ(result, 4518);
  delete t;
}

void test_core_importShort(void) {

  TensorIdxImporter t_import;

  Tensor* t =
      t_import.short_import("/fs/constants/idxImport/int16_4d_power2.idx");

  double result = sum<short>(t);
  EXPECT_EQ(result, 270250);
  delete t;
}

void test_core_importInt(void) {

  TensorIdxImporter t_import;

  Tensor* t =
      t_import.int_import("/fs/constants/idxImport/int32_4d_power2.idx");

  double result = sum<int>(t);
  EXPECT_EQ((int)result, 7158278745);
  delete t;
}

void test_core_importFloat(void) {

  TensorIdxImporter t_import;

  Tensor* t =
      t_import.float_import("/fs/constants/idxImport/float_4d_power2.idx");

  double result = sum<float>(t);

  DEBUG("***floating point test yielded: %.8e\r\n", (float)result);
  EXPECT_EQ((float)result, -1.0f);
  delete t;
}

// First configure the uTensor test runner
UTENSOR_TEST_CONFIGURE()

// Second declare tests to run
UTENSOR_TEST(core, ntoh32, "test ntoh32")
UTENSOR_TEST(core, importUchar, "Test unsigned char import")
UTENSOR_TEST(core, importShort, "Test short inport")
UTENSOR_TEST(core, importInt, "Test import Int")
UTENSOR_TEST(core, importFloat, "Test import float")

// Third, run like hell
UTENSOR_TEST_RUN()

Add tests for idx importer


// 58. Length of Last Word
/**
 * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
 *
 * If the last word does not exist, return 0.
 *
 * Note: A word is defined as a character sequence consists of non-space characters only.
 *
 * For example,
 * Given s = "Hello World",
 * return 5.
 *
 * Tags: String
 *
 * Author: Kuang Qin
 */

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

using namespace std;

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

        // remove trailing spaces
        int last = n - 1;
        while (last >= 0 && s[last] == ' ')
        {
            last--;
        }

        // start to count of the last word
        int len = 0;
        while (last >= 0 && s[last] != ' ')
        {
            len++;
            last--;
        }

        return len;
    }
};

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

Add Solution for Problem 058


//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2014       Bernhard Beschow <bbeschow@cs.tu-berlin.de>
//

#include "StereographicProjection.h"
#include "ViewportParams.h"
#include "TestUtils.h"

namespace Marble
{

class StereographicProjectionTest : public QObject
{
    Q_OBJECT

 private slots:
    void screenCoordinatesOfCenter_data();
    void screenCoordinatesOfCenter();
};

void StereographicProjectionTest::screenCoordinatesOfCenter_data()
{
    ViewportParams stereographic;
    stereographic.setProjection( Stereographic );

    QTest::addColumn<QPoint>( "screenCoordinates" );
    QTest::addColumn<GeoDataCoordinates>( "expected" );

    addRow() << QPoint( 5, 15 ) << GeoDataCoordinates( -45, 76.135, 0, GeoDataCoordinates::Degree );
    addRow() << QPoint( 15, 5 ) << GeoDataCoordinates( 135, 76.135, 0, GeoDataCoordinates::Degree );
}

void StereographicProjectionTest::screenCoordinatesOfCenter()
{
    QFETCH( QPoint, screenCoordinates );
    QFETCH( GeoDataCoordinates, expected );

    ViewportParams viewport;
    viewport.setProjection( Stereographic );
    viewport.setRadius( 180 / 4 ); // for easy mapping of lon <-> x
    viewport.setSize( QSize( 20, 20 ) );
    viewport.centerOn( 0 * DEG2RAD, 90 * DEG2RAD );

    {
        qreal lon, lat;
        const bool retval = viewport.geoCoordinates( screenCoordinates.x(), screenCoordinates.y(), lon, lat, GeoDataCoordinates::Degree );

        QVERIFY( retval ); // we want valid coordinates
        QCOMPARE( lon, expected.longitude( GeoDataCoordinates::Degree ) );
        QFUZZYCOMPARE( lat, expected.latitude( GeoDataCoordinates::Degree ), 0.0001 );
    }
}

}

QTEST_MAIN( Marble::StereographicProjectionTest )

#include "StereographicProjectionTest.moc"

Add test for Stereographic projection for real.