#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
#include <string>

static int callback(void *data, int argc, char **argv, char **azColName){
  int i;
  fprintf(stderr, "%s: ", (const char*)data);
  for(i=0; i<argc; i++){
    printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
  }
  printf("\n");
  return 0;
}

int main(int argc, char* argv[])
{
  sqlite3 *db_user;
  sqlite3 *db_file;
  char *zErrMsg = 0;
  int rc;

  const char* data = "Callback function called";
  /* Open database */
  rc = sqlite3_open("UsersTable.db", &db_user);
  if( rc ){
    fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db_user));
    exit(0);
  }
  else{
    fprintf(stderr, "Opened database successfully\n");
  }

  /* Create merged SQL statement */
  /*  sql = "DELETE from COMPANY where ID=2; "	*/
  std::string sql = "SELECT * from UsersTable";

   /* Execute SQL statement */
  rc = sqlite3_exec(db_user, sql.c_str(), callback, (void*)data, &zErrMsg);
   if( rc != SQLITE_OK ){
     fprintf(stderr, "SQL error: %s\n", zErrMsg);
     /*sqlite3_free(zErrMsg);*/
   }
   else{
     fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db_user);

  /* Open database */
  rc = sqlite3_open("FilesTable.db", &db_file);
  if( rc ){
    fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db_file));
    exit(0);
  }
  else{
    fprintf(stderr, "Opened database successfully\n");
  }

  /* Create merged SQL statement */
  /*  sql = "DELETE from COMPANY where ID=2; "	*/
  sql = "SELECT * from FilesTable";

   /* Execute SQL statement */
  rc = sqlite3_exec(db_file, sql.c_str(), callback, (void*)data, &zErrMsg);
   if( rc != SQLITE_OK ){
     fprintf(stderr, "SQL error: %s\n", zErrMsg);
     sqlite3_free(zErrMsg);
   }
   else{
     fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db_file);

 return 0;
}

Print Users' Database. For testing.


// Chapter 25, Try This 5: int, char, unsigned char and signed char example
// using si = 128

#include<iostream>

using namespace std;

template<class T> void print(T i) { cout << i << '\t'; }

void print(char i) { cout << int(i) << '\t'; }

void print(signed char i) { cout << int(i) << '\t'; }

void print(unsigned char i) { cout << int(i) << '\t'; }

int main()
{
    int si = 128;           // 00000000000000000000000010000000 is  128
    char c = si;            //                         10000000 is -128
    unsigned char uc = si;  //                         10000000 is  128
    signed char sc = si;    //                         10000000 is -128
    print(si);
    print(c);
    print(uc);
    print(sc);
    cout << '\n';
}

Add Chapter 25, Try This 5


//===--- HostInfo.cpp - Host specific information -----------------------*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/HostInfo.h"

using namespace clang::driver;

HostInfo::HostInfo(const char *_Arch, const char *_Platform,
                   const char *_OS)
  : Arch(_Arch), Platform(_Platform), OS(_OS)
{

}

HostInfo::~HostInfo() {
}

// Darwin Host Info

DarwinHostInfo::DarwinHostInfo(const char *Arch, const char *Platform,
                               const char *OS)
  : HostInfo(Arch, Platform, OS) {

  // FIXME: How to deal with errors?

  // We can only call 4.2.1 for now.
  GCCVersion[0] = 4;
  GCCVersion[1] = 2;
  GCCVersion[2] = 1;
}

bool DarwinHostInfo::useDriverDriver() const {
  return true;
}

ToolChain *DarwinHostInfo::getToolChain(const ArgList &Args,
                                        const char *ArchName) const {
  return 0;
}

// Unknown Host Info

UnknownHostInfo::UnknownHostInfo(const char *Arch, const char *Platform,
                               const char *OS)
  : HostInfo(Arch, Platform, OS) {
}

bool UnknownHostInfo::useDriverDriver() const {
  return false;
}

ToolChain *UnknownHostInfo::getToolChain(const ArgList &Args,
                                         const char *ArchName) const {
  return 0;
}

Add host info (add new files).


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

#include "chrome/browser/chromeos/drive/drive_system_service.h"

#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"

namespace drive {

class DriveSystemServiceBrowserTest : public InProcessBrowserTest {
};

// Verify DriveSystemService is created during login.
IN_PROC_BROWSER_TEST_F(DriveSystemServiceBrowserTest, CreatedDuringLogin) {
  EXPECT_TRUE(DriveSystemServiceFactory::FindForProfile(browser()->profile()));
}

}  // namespace drive

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

#include "chrome/browser/chromeos/drive/drive_system_service.h"

#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"

namespace drive {

class DriveSystemServiceBrowserTest : public InProcessBrowserTest {
};

// Verify DriveSystemService is created during login.
IN_PROC_BROWSER_TEST_F(DriveSystemServiceBrowserTest, CreatedDuringLogin) {
  EXPECT_TRUE(DriveSystemServiceFactory::FindForProfile(browser()->profile()));
}

IN_PROC_BROWSER_TEST_F(DriveSystemServiceBrowserTest,
                       DisableDrivePolicyTest) {
  // First make sure the pref is set to its default value which should permit
  // drive.
  browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableDrive, false);

  drive::DriveSystemService* drive_service =
      drive::DriveSystemServiceFactory::GetForProfile(browser()->profile());

  EXPECT_TRUE(drive_service);

  // ...next try to disable drive.
  browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableDrive, true);

  drive_service =
      drive::DriveSystemServiceFactory::GetForProfile(browser()->profile());

  EXPECT_FALSE(drive_service);
}

}  // namespace drive

Add a test to verify that the DriveDisabled policy prevents Drive access for realz.


// 104 Maximum Depth of Binary Tree
/**
* Given a binary tree, find its maximum depth.
*
* The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
*
* Author: Yanbin Lu
*/

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

using namespace std;

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

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root)
            return 1 + max(maxDepth(root->left), maxDepth(root->right));
        else
            return 0;
    }
};

int main()
{

    TreeNode* root = new TreeNode(0);
    root->left = new TreeNode(1);
    root->right = new TreeNode(2);
    root->left->right = new TreeNode(3);

    Solution* sol = new Solution();
    cout << sol->maxDepth(root) << endl;

    char c;
    std::cin>>c;

    return 0;
}

Add 104 Maximum Depth of Binary Tree


// RUN: %clang_cc1 -o /dev/null -emit-llvm -std=c++17 -triple x86_64-pc-windows-msvc %s

struct Foo {
  virtual void f();
  virtual void g();
};

void Foo::f() {}
void Foo::g() {}

template <void (Foo::*)()>
void h() {}

void x() {
  h<&Foo::f>();
  h<&Foo::g>();
}

Add missing test case for r332639


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

using namespace std;

bool valid(const smatch &m) {
    if(m[1].matched) {
        return m[3].matched && m[4].matched == 0;
    } else {
        return m[3].matched == 0 && m[4].str() == m[7].str();
    }
}

int main() {
    string phone = "(\\()?(\\d{3})(\\))?([-.])?([ ]+)?(\\d{3})([-.])?([ ]+)?(\\d{4})";
    regex r(phone);
    string s;
    while(getline(cin, s)) {
        for(sregex_iterator it(s.begin(), s.end(), r), it_end; it != it_end; ++ it) {
            if(valid(*it)) {
                cout << "valid: " << it -> str() << endl;
            } else {
                cout << "not valid: " << it -> str() << endl;
            }
        }
    }
    return 0;
}

Add solution for chapter 17 test 22


/**
 * @file version.cpp
 * @author Ryan Curtin
 *
 * The implementation of GetVersion().
 */
#include "version.hpp"

#include <sstream>

// If we are not a git revision, just use the macros to assemble the version
// name.
std::string mlpack::util::GetVersion()
{
#ifndef __MLPACK_SUBVERSION
  std::stringstream o;
  o << "mlpack " << __MLPACK_VERSION_MAJOR << "." << __MLPACK_VERSION_MINOR
      << "." << __MLPACK_VERSION_PATCH;
  return o.str();
#else
  #include "svnversion.hpp"
#endif
}

/**
 * @file version.cpp
 * @author Ryan Curtin
 *
 * The implementation of GetVersion().
 */
#include "version.hpp"

#include <sstream>

// If we are not a git revision, just use the macros to assemble the version
// name.
std::string mlpack::util::GetVersion()
{
#ifndef __MLPACK_GIT_VERSION
  std::stringstream o;
  o << "mlpack " << __MLPACK_VERSION_MAJOR << "." << __MLPACK_VERSION_MINOR
      << "." << __MLPACK_VERSION_PATCH;
  return o.str();
#else
  // This file is generated by CMake as necessary and contains just a return
  // statement with the git revision in it.
  #include "gitversion.hpp"
#endif
}

Add a comment, and fix macro name.


// RUN: clang -fsyntax-only -verify %s
struct X {
  union {
    float f3;
    double d2;
  } named;

  union {
    int i;
    float f;

    union {
      float f2;
      mutable double d;
    };
  };

  void test_unqual_references();

  struct {
    int a;
    float b;
  };

  void test_unqual_references_const() const;

  mutable union { // expected-error{{anonymous union at class scope must not have a storage specifier}}
    float c1;
    double c2;
  };
};

void X::test_unqual_references() {
  i = 0;
  f = 0.0;
  f2 = f;
  d = f;
  f3 = 0; // expected-error{{use of undeclared identifier 'f3'}}
  a = 0;
}

void X::test_unqual_references_const() const {
  d = 0.0;
  f2 = 0; // expected-error{{read-only variable is not assignable}}
  a = 0; // expected-error{{read-only variable is not assignable}}
}

void test_unqual_references(X x, const X xc) {
  x.i = 0;
  x.f = 0.0;
  x.f2 = x.f;
  x.d = x.f;
  x.f3 = 0; // expected-error{{no member named 'f3'}}
  x.a = 0;

  xc.d = 0.0;
  xc.f = 0; // expected-error{{read-only variable is not assignable}}
  xc.a = 0; // expected-error{{read-only variable is not assignable}}
}

struct Redecl {
  int x; // expected-note{{previous declaration is here}}
  class y { };

  union {
    int x; // expected-error{{member of anonymous union redeclares 'x'}}
    float y;
    double z; // FIXME: note here
    double zz; // expected-note{{previous definition is here}}
  };

  int z; // FIXME: should complain here!
  void zz(); // expected-error{{redefinition of 'zz' as different kind of symbol}}
};

union { // expected-error{{anonymous unions at namespace or global scope must be declared 'static'}}
  int int_val;
  float float_val;
};

static union {
  int int_val2;
  float float_val2;
};

void f() {
  int_val2 = 0;
  float_val2 = 0.0;
}

void g() {
  union {
    int i;
    float f;
  };
  i = 0;
  f = 0.0;
}

Test case for anonymous unions in C++


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

#include "test_serialise_list.h"

#include "gtest/gtest.h"

TEST(StringListTest, StringList) {
	EXPECT_EQ(test_StringList(), 0);
}

TEST(CartesianListTest, CartesianList) {
	EXPECT_EQ(test_CartesianList(), 0);
}

TEST(RangeListTest, RangeList) {
	EXPECT_EQ(test_RangeList(), 0);
}

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

Add set of tests for SerialiseList


#include <bits/stdc++.h>

using namespace std;

const int TAM = 5;
int arr[TAM];

/* Recursive
 * l -> left
 * r -> right
 * x -> element to search
 */
int binary_search(int l, int r, int x){

    if (r >= l){
        int mid = l + (r - l)/2;

        // The element in the middle
        if (arr[mid] == x)  return mid;

        // Smaller of the middle element
        if (arr[mid] > x) return binary_search( l, mid-1, x);

        // Greater that the middle element
        return binary_search(mid+1, r, x);
   }

   return -1;
}

/* Iterative
 * l -> left
 * r -> right
 * x -> element to search
 */
int binary_search_it( int l, int r, int x){
  while (l <= r){
    int m = l + (r-l)/2;

    // The element in the middle
    if (arr[m] == x)  return m;

    // Smaller of the middle element
    if (arr[m] < x)  l = m + 1;

    // Greater that the middle element
    else r = m - 1;
  }

  // if we reach here, then element was not present
  return -1;
}

int main(void){
    arr[0] = 2;
    arr[1] = 3;
    arr[2] = 4;
    arr[3] = 10;
    arr[4] = 40;

   int x = 10;
   int result = binary_search_it(0, TAM-1, x);
   (result == -1)? printf("Element is not present in array")
                 : printf("Element is present at index %d \n", result);
   return 0;
}

Add beautiful implementation binary search.


// Check that when the program closed its std(in|out|err), running the external
// symbolizer still works.

// RUN: rm -f %t.log.*
// RUN: %clangxx_asan -O0 %s -o %t 2>&1 && ASAN_OPTIONS=log_path=%t.log:verbosity=2 not %run %t 2>&1
// RUN: FileCheck %s --check-prefix=CHECK-FILE < %t.log.*

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv) {
  int result = fprintf(stderr, "Closing streams.\n");
  assert(result > 0);
  close(STDIN_FILENO);
  close(STDOUT_FILENO);
  close(STDERR_FILENO);
  result = fprintf(stderr, "Can you hear me now?\n");
  assert(result < 0);
  char *x = (char *)malloc(10 * sizeof(char));
  free(x);
  x[argc] = 'X';  // BOOM
  // CHECK-FILE: {{.*ERROR: AddressSanitizer: heap-use-after-free on address}}
  // CHECK-FILE:   {{0x.* at pc 0x.* bp 0x.* sp 0x.*}}
  // CHECK-FILE: {{WRITE of size 1 at 0x.* thread T0}}
  // CHECK-FILE: {{    #0 0x.* in main .*closed-fds.cc:}}[[@LINE-4]]
  return 0;
}

Add a symbolizer testcase for closed stdin/stdout


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

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

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

};

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

Create unit test file for datastore api


// Test that leaks detected after forking without exec().
// RUN: %clangxx_lsan %s -o %t && not %run %t 2>&1 | FileCheck %s

#include <assert.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main() {
  pid_t pid = fork();
  assert(pid >= 0);
  if (pid > 0) {
    int status = 0;
    waitpid(pid, &status, 0);
    assert(WIFEXITED(status));
    return WEXITSTATUS(status);
  } else {
    malloc(1337);
    // CHECK: LeakSanitizer: detected memory leaks
  }
  return 0;
}

Check that leak sanitizer works in the forked process


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<ListNode*> splitListToParts(ListNode* root, int k) {
        int d=depth(root);
        vector<int> ls;
        while(k>0){
            ls.push_back(d/k);
            d-=d/k;
            k--;
        }
        vector<ListNode*> ans;
        ListNode* prev=root;
        while(ls.size() && root){
            while(ls.back()>1){
                root=root->next;
                ls.back()--;
            }
            ListNode* tmp=root;
            root=root->next;
            tmp->next=NULL;
            ans.push_back(prev);
            prev=root;
            ls.pop_back();
        }
        while(ls.size()){
            ans.push_back(NULL);
            ls.pop_back();
        }
        return ans;
    }
    int depth(ListNode* root){
        if(!root) return 0;
        return 1+depth(root->next);
    }
};

Split Linked List in Parts


#include<bits/stdc++.h>
#define debug(x) cout << #x << " = "<< x << endl
#define pb push_back
/*
	Algorithm to find all possible substrings of size k given a set of values
*/
using namespace std;
set<string> subs;

//print all possible substrings of size k
void substringSizek(char set[], string prefix, int n, int k){
	//Base case
	if( 0 == k){
		cout << prefix <<endl;
		subs.insert(prefix);
		return;
	}
	for( int i=0;  i < n ; ++i){
		string newprefix = prefix + set[i];
		//k is decreased because we add a new caracter
		substringSizek(set, newprefix, n, k-1);
	}
}
void init(char set[], int k){
	 int n = strlen(set);
	 substringSizek(set, "", n, k);
}

int main(){
	char set[3] ={'a', 'b'};
	int k = 3;
	init(set, k);
	/*
	aaa
	aab
	aba
	abb
	baa
	bab
	bba
	bbb
	*/
}

Add useful algorithm to find all possible substrings of size k of a set of characters.


// remove chars in s1 which are present in the s2
#include <iostream>
#include <string>
using namespace std;

void removeChars(string &s1, string &s2) {
	int map[256] = {0};
	int s2_len = s2.length();
	for (int i = 0; i < s2_len; i++) {
		map[s2[i]] = 1;
	}
	int s1_len = s1.length();
	string result;
	for (int i = 0; i < s1_len; i++) {
		if (!map[s1[i]]) result.push_back(s1[i]);
	}
	cout<<result<<endl;
}

int main() {
	string s1 = "hello world";
	string s2 = "aeiou";
	removeChars(s1, s2);

	return 0;
}

Remove chars in s2 from s1


//===- RustWrapper.cpp - Rust wrapper for core functions --------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines alternate interfaces to core functions that are more
// readily callable by Rust's FFI.
//
//===----------------------------------------------------------------------===//

#include "llvm-c/Core.h"
#include "llvm-c/Object.h"
#include <cstdlib>

static char *LLVMRustError;

extern "C" LLVMMemoryBufferRef
LLVMRustCreateMemoryBufferWithContentsOfFile(const char *Path) {
  LLVMMemoryBufferRef MemBuf = NULL;
  LLVMCreateMemoryBufferWithContentsOfFile(Path, &MemBuf, &LLVMRustError);
  return MemBuf;
}

extern "C" const char *LLVMRustGetLastError(void) {
  return LLVMRustError;
}

LLVMOpaqueObjectFile* (*RustHackToFetchObjectO)(LLVMOpaqueMemoryBuffer*)
  = LLVMCreateObjectFile;

Add a hack to force the linker to fetch Object.o


/*
 * Unit tests for the Point3 class.
 * Author: Dino Wernli
 */

#include <gtest/gtest.h>

#include "util/point3.h"

TEST(Point3, Distance) {
  Point3 p(1, 2, 3);
  EXPECT_DOUBLE_EQ(0, Point3::Distance(p, p));

  Point3 q(1, 2, 4);
  EXPECT_DOUBLE_EQ(1, Point3::Distance(p, q));

  Point3 r(1, 2, 1);
  EXPECT_DOUBLE_EQ(2, Point3::Distance(p, r));
}

TEST(Point3, SquaredDistance) {
  Point3 p(1, 2, 3);
  EXPECT_DOUBLE_EQ(0, Point3::SquaredDistance(p, p));

  Point3 q(1, 2, 4);
  EXPECT_DOUBLE_EQ(1, Point3::SquaredDistance(p, q));

  Point3 r(1, 2, 1);
  EXPECT_DOUBLE_EQ(4, Point3::SquaredDistance(p, r));
}

Add unit tests for point.


#include <stdio.h>

int get_gcd(const int num1, const int num2)
{
    /* Euclidean algorithm */
    /* Base case */
    if(num1 < num2) return get_gcd(num2, num1); /* Swap two numbers; num2 should be less than num1 */
    if(num1 % num2 == 0) return num2; /* num2 is GCD */

    /* Recursive case */
    return get_gcd(num1 % num2, num2);
}

int main(void)
{
    int num1, num2;
    printf("Enter a num1= "); scanf("%d", &num1);
    printf("Enter a num2= "); scanf("%d", &num2);

    printf("Result: %d\n", get_gcd(num1, num2));

    return 0;
}

Add a solution of prob 4


/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

#include <cassert>
#include <cstdint>
#include <fstream>
#include <vector>

extern "C" bool read_box_from_buffer(uint8_t *buffer, size_t size);

void test_arg_validation()
{
  bool rv;
  rv = read_box_from_buffer(nullptr, 0);
  assert(!rv);

  size_t len = 4097;
  rv = read_box_from_buffer(nullptr, len);
  assert(!rv);

  std::vector<uint8_t> buf;
  rv = read_box_from_buffer(buf.data(), buf.size());
  assert(!rv);

  buf.reserve(len);
  rv = read_box_from_buffer(buf.data(), buf.size());
  assert(!rv);
}

void read_file(const char* filename)
{
  std::ifstream f(filename);
  assert(f.is_open());

  size_t len = 4096;
  std::vector<uint8_t> buf;
  buf.reserve(len);
  f.read(reinterpret_cast<char*>(buf.data()), buf.size());
  bool rv = read_box_from_buffer(buf.data(), buf.size());
  assert(!rv); // Expected fail: need to trap eof.
}

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

  for (auto i = 1; i < argc; ++i) {
    read_file(argv[i]);
  }

  return 0;
}

Add a C++ linkage example.


/*
 * Copyright (C) 2009, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

// This file is used by the package script to determine Boost location
# include <boost/foreach.hpp>

Add specific header to help find boost location.


/*
 * Written by Nitin Kumar Maharana
 * nitin.maharana@gmail.com
 */

//Print 2-D matrix in clockwise spiral order.

#include <iostream>
#include <vector>

using namespace std;

void printSpiral(vector<vector<int>>& input)
{
	int top, bottom, left, right, direction;

	top = left = 0;
	bottom = input.size()-1;
	right = input[0].size()-1;
	direction = 0;

	while(top <= bottom && left <= right)
	{
		if(direction == 0)
		{
			for(int i = left; i <= right; i++)
				cout << input[top][i] << " ";
			top++;
			direction = 1;
		}else if(direction == 1)
		{
			for(int i = top; i <= bottom; i++)
				cout << input[i][right] << " ";
			right--;
			direction = 2;
		}else if(direction == 2)
		{
			for(int i = right; i >= left; i--)
				cout << input[bottom][i] << " ";
			bottom--;
			direction = 3;
		}else
		{
			for(int i = bottom; i >= top; i--)
				cout << input[i][left] << " ";
			left++;
			direction = 0;
		}
	}

	return;
}

int main(void)
{
	int arr[] = {1,2,3,4};

	vector<vector<int>> input(4, vector<int>(arr, arr+4));

	printSpiral(input);

	cout << endl;

	return 0;
}


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

template<typename T>
struct X0 {
  struct MemberClass {
    T member; // expected-error{{with function type}}
  };

  T* f0(T* ptr) {
    return ptr + 1; // expected-error{{pointer to function}}
  }

  static T* static_member;
};

template<typename T>
T* X0<T>::static_member = ((T*)0) + 1; // expected-error{{pointer to function}}

template class X0<int>; // okay

template class X0<int(int)>; // expected-note 3{{requested here}}

// Specialize everything, so that the explicit instantiation does not trigger
// any diagnostics.
template<>
struct X0<int(long)>::MemberClass { };

typedef int int_long_func(long);
template<>
int_long_func *X0<int_long_func>::f0(int_long_func *) { return 0; }

template<>
int_long_func *X0<int(long)>::static_member;

template class X0<int(long)>;

Test for interaction between explicit instantiations and specializations


#include <mart-common/enum/EnumDefinitionMacro.h>

MART_UTILS_DEFINE_ENUM( Airplains, int, 5, F114, A380, F22, Eurofighter, Cessna );

Add test for enum definition macro


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

bool isSumProperty(NODE* root) {
  int left_node_data = 0;
  int right_node_data = 0;

  if (root == NULL || (root->left == NULL && root->right == NULL)) {
    return true;
  } else {
    if (root->left) {
      left_node_data = root->left->data;
    }

    if (root->right) {
      right_node_data = root->right->data;
    }

    if ((root->data == (left_node_data + right_node_data)) &&
        isSumProperty(root->left) && isSumProperty(root->right))
      return true;
    else
      return false;
  }
}

int main(int argc, char const* argv[]) {
  NODE* root = newNode(10);
  root->left = newNode(8);
  root->right = newNode(2);
  root->left->left = newNode(3);
  root->left->right = newNode(5);
  root->right->right = newNode(2);
  if (isSumProperty(root))
    printf("The given tree satisfies the children sum property ");
  else
    printf("The given tree does not satisfy the children sum property ");
  return 0;
}

Check whether given tree satisfies children sum property.


// RUN: %clangxx_tsan %s -o %t
// RUN: %deflake %run %t 2>&1 | FileCheck %s

#include <thread>

#import "../test.h"

extern "C" {
void *__tsan_external_register_tag(const char *object_type);
void *__tsan_external_assign_tag(void *addr, void *tag);
void __tsan_external_read(void *addr, void *caller_pc, void *tag);
void __tsan_external_write(void *addr, void *caller_pc, void *tag);
void __tsan_write8(void *addr);
}

void *tag;

__attribute__((no_sanitize("thread")))
void ExternalWrite(void *addr) {
  __tsan_external_write(addr, __builtin_return_address(0), tag);
}

int main(int argc, char *argv[]) {
  barrier_init(&barrier, 2);
  tag = __tsan_external_register_tag("HelloWorld");
  fprintf(stderr, "Start.\n");
  // CHECK: Start.

  for (int i = 0; i < 4; i++) {
    void *opaque_object = malloc(16);
    std::thread t1([opaque_object] {
      ExternalWrite(opaque_object);
      barrier_wait(&barrier);
    });
    std::thread t2([opaque_object] {
      barrier_wait(&barrier);
      ExternalWrite(opaque_object);
    });
    // CHECK: WARNING: ThreadSanitizer: race on a library object
    t1.join();
    t2.join();
  }

  fprintf(stderr, "First phase done.\n");
  // CHECK: First phase done.

  for (int i = 0; i < 4; i++) {
    void *opaque_object = malloc(16);
    std::thread t1([opaque_object] {
      ExternalWrite(opaque_object);
      barrier_wait(&barrier);
    });
    std::thread t2([opaque_object] {
      barrier_wait(&barrier);
      ExternalWrite(opaque_object);
    });
    // CHECK: WARNING: ThreadSanitizer: race on a library object
    t1.join();
    t2.join();
  }

  fprintf(stderr, "Second phase done.\n");
  // CHECK: Second phase done.
}

// CHECK: ThreadSanitizer: reported 2 warnings

Add a test for "external" API that checks the dup suppression is based on the caller PC


// Chapter 23, exercise 8: modify program from 23.8.7 to take as input a pattern
// and a file name, then output numbered lines (line-number: line) that contain
// a match of the pattern. No match - no output

#include<regex>
#include<iostream>
#include<iomanip>
#include<string>
#include<fstream>
#include<sstream>
#include<stdexcept>

using namespace std;

int main()
try {
    while (true) {
        string pat;
        cout << "Enter pattern (q to exit): ";
        getline(cin,pat);   // read pattern
        if (pat=="q") break;
        regex pattern;
        try {
            pattern = pat;  // this checks pat
        }
        catch (regex_error) {
            cerr << "Not a valid regular expression: " << pat << '\n';
            continue;
        }

        string fname;
        cout << "Enter file name: ";
        getline(cin,fname);
        ifstream ifs(fname);
        if (!ifs) throw runtime_error("Can't open " + fname);
        string line;
        int lineno = 0;
        while (getline(ifs,line)) {
            ++lineno;
            smatch matches;
            if (regex_search(line,matches,pattern))
                cout << setw(3) << lineno << ": " << line << '\n';
        }
    }
}
catch (exception& e) {
    cerr << "Exception: " << e.what() << '\n';
}
catch (...) {
    cerr << "Exception\n";
}

Add Chapter 23, exercise 8


#include <catch.hpp>

#define private public
#include <libgearbox_http_interface_p.h>
#include <libgearbox_http_interface.cpp>

TEST_CASE("Test libgearbox_http_interface", "[http]")
{
    SECTION("")
    {
    }
}

Add test skeleton for HttpInterface


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

// CHECK-NOT: ZN12basic_stringIcEC1Ev
// CHECK: ZN12basic_stringIcED1Ev
// CHECK: ZN12basic_stringIcED1Ev
template<class charT>
class basic_string
{
public:
	basic_string();
	~basic_string();
};

template <class charT>
__attribute__ ((__visibility__("hidden"), __always_inline__)) inline
basic_string<charT>::basic_string()
{
}

template <class charT>
inline
basic_string<charT>::~basic_string()
{
}

typedef basic_string<char> string;

extern template class basic_string<char>;

int main()
{
	string s;
}

Migrate from llvm/test/FrontendC++ and FileCheckize.


#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>

static void CrashCatcher(int sig)
{
  const char *msg;
  switch (sig) {
    case SIGILL:  msg = "CRASHED: SIGILL\n";  break;
    case SIGTRAP: msg = "CRASHED: SIGTRAP\n"; break;
    case SIGABRT: msg = "CRASHED: SIGABRT\n"; break;
    case SIGFPE:  msg = "CRASHED: SIGFPE\n";  break;
    case SIGBUS:  msg = "CRASHED: SIGBUS\n";  break;
    case SIGSEGV: msg = "CRASHED: SIGSEGV\n"; break;
    case SIGSYS:  msg = "CRASHED: SIGSYS\n";  break;
    default:      msg = "CRASHED: SIG????\n"; break;
  }
  write(STDERR_FILENO, msg, strlen(msg));
  _exit(0);
}

static void CatchCrashes(void) __attribute__((used,constructor));
static void CatchCrashes(void)
{
  // Disable buffering on stdout so that everything is printed before crashing.
  setbuf(stdout, 0);

  signal(SIGILL,  CrashCatcher);
  signal(SIGTRAP, CrashCatcher);
  signal(SIGABRT, CrashCatcher);
  signal(SIGFPE,  CrashCatcher);
  signal(SIGBUS,  CrashCatcher);
  signal(SIGSEGV, CrashCatcher);
  signal(SIGSYS,  CrashCatcher);
}

Add new file for crash testing.


// Check that 8-byte store updates origin for the full store range.
// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O0 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s < %t.out
// RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O2 %s -o %t && not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out && FileCheck %s < %t.out

#include <sanitizer/msan_interface.h>

int main() {
  uint64_t *volatile p = new uint64_t;
  uint64_t *volatile q = new uint64_t;
  *p = *q;
  char *z = (char *)p;
  return z[6];
// CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value
// CHECK:   in main {{.*}}origin-store-long.cc:[[@LINE-2]]

// CHECK:  Uninitialized value was created by a heap allocation
// CHECK:   in main {{.*}}origin-store-long.cc:[[@LINE-8]]
}

Update origin for the entire destination range on memory store.


//1. Two Sum
/**
 * Given an array of integers, return indices of the two numbers such that they add up to a specific target.
 * You may assume that each input would have exactly one solution.
 *
 * Example:
 * Given nums = [2, 7, 11, 15], target = 9,
 * Because nums[0] + nums[1] = 2 + 7 = 9,
 * return [0, 1].
 *
 * The return format had been changed to zero-based indices. Please read the above updated description carefully.
 *
 * Tags: Array, Hash Table
 *
 * Similar Problems: (M) 3Sum, (M) 4Sum, (M) Two Sum II - Input array is sorted, (E) Two Sum III - Data structure design
 *
 * Author: Kuang Qin
 */

#include <iostream>
#include <unordered_map>
#include <vector>

using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int len = nums.size();
        vector<int> res;
        unordered_map<int, int> map;

        for (int i = 0; i < len; i++)
        {
            int diff = target - nums[i];
            if (map.find(diff) != map.end())    // use hash map to quick search, if found, ouput the result
            {
                res.push_back(map[diff]);
                res.push_back(i);
                break;
            }

            // Save the numbers into an unordered map when searching
            map[nums[i]] = i;
        }

        return res;
    }
};

int main()
{
    vector<int> nums = {2, 7, 11, 15};
    int target = 9;
    Solution sol;
    vector<int> ans = sol.twoSum(nums, target);
    cout << "[" << ans[0] << ", " << ans[1] << "]" << endl;
    cin.get();

    return 0;
}

Add Solution for 1 Two Sum


#include <gtest/gtest.h>

#include "photoeffects.hpp"

using namespace cv;

TEST(photoeffects, AntiqueTest)
{
    Mat image(10, 10, CV_8UC1);

    EXPECT_EQ(10, antique(image).cols);
}

Add test for antique effect


// RUN: clang-tidy -checks=-*,modernize-use-nullptr %s -- --driver-mode=cl /DTEST1 /DFOO=foo /DBAR=bar | FileCheck -implicit-check-not="{{warning|error}}:" %s
int *a = 0;
// CHECK: :[[@LINE-1]]:10: warning: use nullptr
#ifdef TEST1
int *b = 0;
// CHECK: :[[@LINE-1]]:10: warning: use nullptr
#endif
#define foo 1
#define bar 1
#if FOO
int *c = 0;
// CHECK: :[[@LINE-1]]:10: warning: use nullptr
#endif
#if BAR
int *d = 0;
// CHECK: :[[@LINE-1]]:10: warning: use nullptr
#endif

Add a test for clang-tidy using the clang-cl driver.


// 82 Remove Duplicates from Sorted List II
/**
* Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
*
* For example,
* Given 1->2->3->3->4->4->5, return 1->2->5.
* Given 1->1->1->2->3, return 2->3.
*
* Tag:      Linked List
*
* Author:   Yanbin Lu
*/

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

using namespace std;

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

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        // check empty or single node list
        if(!head || !head->next) return head;

        // if the first element is not a duplicate, recursive start from the next one
        if(head->val != head->next->val){
            head->next = deleteDuplicates(head->next);
            return head;
        }

        // if the first element is duplicate, go along untill a different value
        else{
            int val = head->val;
            ListNode* node = head;
            while(node && node->val == val) node = node->next;
            return deleteDuplicates(node);
        }
    }
};

int main()
{
    // creat a duplicate list
    ListNode* list = new ListNode(0);
    list->next = new ListNode(0);
    list->next->next = new ListNode(1);
    list->next->next->next = new ListNode(1);
    list->next->next->next->next = new ListNode(2);
    list->next->next->next->next->next = new ListNode(3);

    Solution* sol = new Solution();
    ListNode* test = sol->deleteDuplicates(list);

    ListNode* node = test;
    while(node){
        cout<<node->val<<endl;
        node = node->next;
    }

	char c;
	std::cin>>c;

	return 0;
}

Add 82 Remove Duplicates from Sorted List II


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

void printPathUtil(int* path, int len) {
  for (int i = 0; i < len; i++) {
    printf("%d ", path[i]);
  }
  printf("\n");
}

void printPathRec(NODE* root, int path[], int len) {
  if (root == nullptr) return;
  path[len] = root->data;
  len++;

  if (root->left == nullptr && root->right == nullptr) {
    printPathUtil(path, len);
  } else {
    printPathRec(root->left, path, len);
    printPathRec(root->right, path, len);
  }
}

void printPaths(NODE* root) {
  int path[10];
  printPathRec(root, path, 0);
}

int main(int argc, char const* argv[]) {
  NODE* root = newnode(10);
  root->left = newnode(8);
  root->right = newnode(2);
  root->left->left = newnode(3);
  root->left->right = newnode(5);
  root->right->left = newnode(2);

  printPaths(root);
  return 0;
}

Print all path from root to leaf.


extern "C"
{
    #include "lua.h"
    #include "lauxlib.h"
    #include "lualib.h"
}

#include "RtMidi.h"
static RtMidiOut midi;

int midi_send(lua_State* L)
{
    double status = lua_tonumber(L, -3);
    double data1 = lua_tonumber(L, -2);
    double data2 = lua_tonumber(L, -1);

    std::vector<unsigned char> message(3);
    message[0] = static_cast<unsigned char> (status);
    message[1] = static_cast<unsigned char> (data1);
    message[2] = static_cast<unsigned char> (data2);
    midi.sendMessage(&message);

    return 0;
}

int main(int argc, char const* argv[])
{
    if (argc < 1) { return -1; }

    unsigned int ports = midi.getPortCount();
    if (ports < 1) { return -1; }
    midi.openPort(0);

    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    lua_pushcfunction(L, midi_send);
    lua_setglobal(L, "midi_send");
    luaL_dofile(L, argv[1]);

    lua_close(L);
    return 0;
}

Add C++ Bindings to Lua


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

using namespace Halide;

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

    // Create a simple function computed at root.
    f(x) = x;
    f.compute_root();

    // Create a function that uses an undefined buffer after f is
    // freed.
    g(x) = undef<int>() + f(x);
    g(x) += 1;
    g.compute_root();

    // This just forces g to be stored somewhere (the re-used buffer).
    h(x) = g(x);
    h.compute_root();

    // Bound it so the allocations go on the stack.
    h.bound(x, 0, 16);

    Image<int> result = h.realize(16);
    for (int i = 0; i < result.width(); i++) {
        if (result(i) != i + 1) {
            printf("Error! Allocation did not get reused at %d (%d != %d)\n", i, result(i), i + 1);
            return -1;
        }
    }

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

Test to ensure stack allocations can be reused.


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

#include <alpaka/core/OmpSchedule.hpp>
#include <alpaka/core/Unused.hpp>

#include <catch2/catch.hpp>

//-----------------------------------------------------------------------------
TEST_CASE("ompScheduleDefaultConstructor", "[core]")
{
    auto const schedule = alpaka::omp::Schedule{};
    alpaka::ignore_unused(schedule);
}

//-----------------------------------------------------------------------------
TEST_CASE("ompScheduleConstructor", "[core]")
{
    auto const staticSchedule = alpaka::omp::Schedule{alpaka::omp::Schedule::Static, 5};
    alpaka::ignore_unused(staticSchedule);

    auto const guidedSchedule = alpaka::omp::Schedule{alpaka::omp::Schedule::Guided};
    alpaka::ignore_unused(guidedSchedule);
}

//-----------------------------------------------------------------------------
TEST_CASE("ompScheduleConstexprConstructor", "[core]")
{
    constexpr auto schedule = alpaka::omp::Schedule{alpaka::omp::Schedule::Dynamic};
    alpaka::ignore_unused(schedule);
}

//-----------------------------------------------------------------------------
TEST_CASE("ompGetSchedule", "[core]")
{
    auto const schedule = alpaka::omp::getSchedule();
    alpaka::ignore_unused(schedule);
}

//-----------------------------------------------------------------------------
TEST_CASE("ompSetSchedule", "[core]")
{
    auto const expectedSchedule = alpaka::omp::Schedule{alpaka::omp::Schedule::Dynamic, 3};
    alpaka::omp::setSchedule(expectedSchedule);
    // The check makes sense only when this feature is supported
#if defined _OPENMP && _OPENMP >= 200805 && ALPAKA_ACC_CPU_B_OMP2_T_SEQ_ENABLED
    auto const actualSchedule = alpaka::omp::getSchedule();
    REQUIRE(expectedSchedule.kind == actualSchedule.kind);
    REQUIRE(expectedSchedule.chunkSize == actualSchedule.chunkSize);
#endif
}

//-----------------------------------------------------------------------------
TEST_CASE("ompSetNoSchedule", "[core]")
{
    auto const expectedSchedule = alpaka::omp::Schedule{alpaka::omp::Schedule::Guided, 2};
    alpaka::omp::setSchedule(expectedSchedule);
    auto const noSchedule = alpaka::omp::Schedule{alpaka::omp::Schedule::NoSchedule};
    alpaka::omp::setSchedule(noSchedule);
    // The check makes sense only when this feature is supported
#if defined _OPENMP && _OPENMP >= 200805 && ALPAKA_ACC_CPU_B_OMP2_T_SEQ_ENABLED
    auto const actualSchedule = alpaka::omp::getSchedule();
    REQUIRE(expectedSchedule.kind == actualSchedule.kind);
    REQUIRE(expectedSchedule.chunkSize == actualSchedule.chunkSize);
#endif
}

Add unit tests for omp::Schedule


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    int getDecimalValue(ListNode* head) {
        std::vector<int> v;
        while (head) {
            v.emplace_back(head->val);
            head = head->next;
        }
        int ret = 0, index = 1;
        for (int i = 0; i < v.size(); ++i) {
            ret += v[v.size()-i-1] * index;
            index *= 2;
        }
        return ret;
    }
};

Convert Binary Number in a Linked List to Integer


// 4 Median of Two Sorted Array
/**
* There are two sorted arrays nums1 and nums2 of size m and n respectively.
* Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
*
* Tag:    Divide and Conquer, Array, Binary Search
*
* 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;

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {

        int len1 = nums1.size();
        int len2 = nums2.size();

        // always consider nums1 is shorter than nums2
        if(len1 > len2) return findMedianSortedArrays(nums2, nums1);

        int mid = (len1 + len2 -1) / 2;
        int leftin1 = 0, rightin1 = len1;   // the rightin1 is a boundary, not an actual index
        while(leftin1 < rightin1){
            int mid1 = (leftin1 + rightin1) / 2;    // mid point in array 1
            int mid2 = mid - mid1;                  // mid point in array 2
            if(nums1[mid1] < nums2[mid2])
                leftin1 = mid1 + 1;
            else
                rightin1 = mid1;
        }

        //len1 + len2 is odd
        // median is either nums1[leftin1 - 1] or nums2[mid - leftin1]
        int temp1 = max(leftin1 > 0 ? nums1[leftin1 - 1] : INT_MIN, mid - leftin1 >= 0 ? nums2[mid - leftin1] :INT_MIN);
        if ((len1 + len2) % 2 == 1)
            return (double) temp1;

        //len1 + len2 is even
        // median is either nums1[leftin1] or nums2[mid - leftin1 + 1]
        int temp2 = min(leftin1 < len1 ? nums1[leftin1] : INT_MAX, mid - leftin1 + 1 < len2 ? nums2[mid - leftin1 + 1] : INT_MAX);
        return (temp1 + temp2) / 2.0;
    }
};

int main()
{
    vector<int> nums1;
    nums1.push_back(1);
    nums1.push_back(2);
    nums1.push_back(4);
    nums1.push_back(5);

    vector<int> nums2;
    nums2.push_back(3);
    nums2.push_back(3);
    nums2.push_back(4);
    nums2.push_back(5);
    nums2.push_back(6);
    Solution* sol = new Solution();
    cout << sol->findMedianSortedArrays(nums1, nums2) << endl;

    char c;
    std::cin>>c;

    return 0;
}

Add 004 Median of Two Sorted Array


#include <bits/stdc++.h>
using namespace std;
//Compute the largest increasing subsequence
int lis( int arr[], int n ){
	int *lis, i, j, max = 0;
	lis = (int*) malloc ( sizeof( int ) * n );
	for (i = 0; i < n; i++ )
		lis[i] = 1;
	for (i = 1; i < n; i++ )
		for (j = 0; j < i; j++ )
			if ( arr[i] > arr[j] && lis[i] < lis[j] + 1)
				lis[i] = lis[j] + 1;
	for (i = 0; i < n; i++ )
		if (max < lis[i])
			max = lis[i];
	free(lis);
	return max;
}
int main(){
	int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
	int n = sizeof(arr)/sizeof(arr[0]);
	printf("Length of lis is %d\n", lis( arr, n ) );
  //sol = 10, 22, 33, 50, 60
	return 0;
}

Implement solution Longest increasing subsequence.


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

#include "condor_common.h"

// mongodb-devel includes
#include <mongo/client/dbclient.h>

// seems boost meddles with assert defs
#include "assert.h"
#include "condor_config.h"
#include "../condor_negotiator.V6/NegotiatorPlugin.h"
#include "../condor_daemon_core.V6/condor_daemon_core.h"
#include "get_daemon_name.h"

using namespace mongo;
DBClientConnection c;
std::string db_name("condor.negotiator");

void writeJobAd(ClassAd* ad) {
    clock_t start, end;
    double elapsed;
    ExprTree *expr;
    const char *name;
    ad->ResetExpr();

    BSONObjBuilder b;
    start = clock();
    while (ad->NextExpr(name,expr)) {
        b.append(name,ExprTreeToString(expr));
    }
    try {
        c.insert(db_name, b.obj());
    }
    catch(DBException& e) {
        cout << "caught DBException " << e.toString() << endl;
    }
    end = clock();
    elapsed = ((float) (end - start)) / CLOCKS_PER_SEC;
    std:string last_err = c.getLastError();
    if (!last_err.empty()) {
        printf("getLastError: %s\n",last_err.c_str());
    }
    printf("Time elapsed: %1.9f sec\n",elapsed);
}

struct ODSNegotiatorPlugin : public Service, NegotiatorPlugin
{
	void
	initialize()
	{
		char *tmp;
		std::string mmName;

		dprintf(D_FULLDEBUG, "ODSNegotiatorPlugin: Initializing...\n");

		// pretty much what the daemon does
		tmp = default_daemon_name();
		if (NULL == tmp) {
			mmName = "UNKNOWN NEGOTIATOR HOST";
		} else {
			mmName = tmp;
			free(tmp); tmp = NULL;
		}

		c.connect("localhost");
	}

	void
	shutdown()
	{
		dprintf(D_FULLDEBUG, "ODSNegotiatorPlugin: shutting down...\n");
	}

	void
	update(const ClassAd &ad)
	{
		writeJobAd(const_cast<ClassAd*>(&ad));
	}

};

static ODSNegotiatorPlugin instance;

Add negotiator plugin prototype for ODS contrib


// RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o - %s | FileCheck %s

namespace std {
  typedef decltype(sizeof(int)) size_t;

  // libc++'s implementation with __size_ replaced by __end_
  template <class _E>
  class initializer_list
  {
    const _E* __begin_;
    const _E* __end_;

    initializer_list(const _E* __b, const _E* __e)
      : __begin_(__b),
        __end_(__e)
    {}

  public:
    typedef _E        value_type;
    typedef const _E& reference;
    typedef const _E& const_reference;
    typedef size_t    size_type;

    typedef const _E* iterator;
    typedef const _E* const_iterator;

    initializer_list() : __begin_(nullptr), __end_(nullptr) {}

    size_t    size()  const {return __end_ - __begin_;}
    const _E* begin() const {return __begin_;}
    const _E* end()   const {return __end_;}
  };
}

void fn1(int i) {
  // CHECK: define void @_Z3fn1i
  // temporary array
  // CHECK: [[array:%[^ ]+]] = alloca [3 x i32]
  // CHECK: getelementptr inbounds [3 x i32]* [[array]], i{{32|64}} 0
  // CHECK-NEXT: store i32 1, i32*
  // CHECK-NEXT: getelementptr
  // CHECK-NEXT: store
  // CHECK-NEXT: getelementptr
  // CHECK-NEXT: load
  // CHECK-NEXT: store
  // init the list
  // CHECK-NEXT: getelementptr
  // CHECK-NEXT: getelementptr inbounds [3 x i32]*
  // CHECK-NEXT: store i32*
  // CHECK-NEXT: getelementptr
  // CHECK-NEXT: getelementptr inbounds [3 x i32]* [[array]], i{{32|64}} 0, i{{32|64}} 3
  // CHECK-NEXT: store i32*
  std::initializer_list<int> intlist{1, 2, i};
}

struct destroyme1 {
  ~destroyme1();
};
struct destroyme2 {
  ~destroyme2();
};

void fn2() {
  // CHECK: define void @_Z3fn2v
  void target(std::initializer_list<destroyme1>);
  // objects should be destroyed before dm2, after call returns
  target({ destroyme1(), destroyme1() });
  // CHECK: call void @_ZN10destroyme1D1Ev
  destroyme2 dm2;
  // CHECK: call void @_ZN10destroyme2D1Ev
}

void fn3() {
  // CHECK: define void @_Z3fn3v
  // objects should be destroyed after dm2
  auto list = { destroyme1(), destroyme1() };
  destroyme2 dm2;
  // CHECK: call void @_ZN10destroyme2D1Ev
  // CHECK: call void @_ZN10destroyme1D1Ev
}

Add a testcase for start+end implementations of std::initializer_list.


// Chapter 25, exercise 8: write out the numerical values of each character on
// your keyboard

#include<iostream>

using namespace std;

void print(char ch)
{
    cout << ch << ": " << int(ch) << '\t';
}

int main()
{
    print('');
    print('+');
    print('"');
    print('*');
    print('');
    print('%');
    print('&');
    print('/');
    print('(');
    print(')');
    print('=');
    print('?');
    print('`');
    print('');
    print('1');
    print('2');
    cout << '\n';
    print('3');
    print('4');
    print('5');
    print('6');
    print('7');
    print('8');
    print('9');
    print('0');
    print('\'');
    print('^');
    print('');
    print('@');
    print('#');
    print('');
    print('|');
    print('');
    cout << '\n';
    print('');
    print('~');
    print('Q');
    print('W');
    print('E');
    print('R');
    print('T');
    print('Z');
    print('U');
    print('I');
    print('O');
    print('P');
    print('');
    print('!');
    print('q');
    print('w');
    cout << '\n';
    print('e');
    print('r');
    print('t');
    print('z');
    print('u');
    print('i');
    print('o');
    print('p');
    print('');
    print('');
    print('');
    print('[');
    print(']');
    print('A');
    print('B');
    print('C');
    cout << '\n';
    print('D');
    print('E');
    print('F');
    print('G');
    print('H');
    print('J');
    print('K');
    print('L');
    print('');
    print('');
    print('');
    print('a');
    print('s');
    print('d');
    print('f');
    print('g');
    cout << '\n';
    print('h');
    print('j');
    print('k');
    print('l');
    print('');
    print('');
    print('$');
    print('{');
    print('}');
    print('>');
    print('Y');
    print('X');
    print('C');
    print('V');
    print('B');
    print('N');
    cout << '\n';
    print('M');
    print(';');
    print(':');
    print('_');
    print('<');
    print('y');
    print('x');
    print('c');
    print('v');
    print('b');
    print('n');
    print('m');
    print(',');
    print('.');
    print('-');
    print('\\');
    cout << '\n';
}

Add Chapter 25, exercise 8


// Chapter 23, exercise 13: test if the reuglar expression '.' matches the
// newline character '\n'

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

using namespace std;

int main()
{
    string s = "\n";
    regex pat(".");
    smatch matches;
    if (regex_match(s,matches,pat))
        cout << "'.' matches '\\n'\n";
    else
        cout << "'.' does not match '\\n'\n";
}

Add Chapter 23, exercise 13


// RUN: %clang_cc1 -fsyntax-only -verify -ftemplate-backtrace-limit 2 %s

template<int N, typename T> struct X : X<N+1, T*> {};
// expected-error-re@3 {{recursive template instantiation exceeded maximum depth of 1024{{$}}}}
// expected-note@3 {{instantiation of template class}}
// expected-note@3 {{skipping 1023 contexts in backtrace}}
// expected-note@3 {{use -ftemplate-depth=N to increase recursive template instantiation depth}}

X<0, int> x; // expected-note {{in instantiation of}}

Add test missed from r278983.


/*******************************************************************************

Connect nodes at same level
===========================

Ref - http://www.geeksforgeeks.org/connect-nodes-at-same-level/

--------------------------------------------------------------------------------

Problem
=======
Connect a child node to its next sibling or the next node at same level.

--------------------------------------------------------------------------------

Time Complexity
===============
O(n)

--------------------------------------------------------------------------------

Output
======
Tree is:
1
2 3
4 5 6
Connected 1 to NULL
Connected 2 to 3
Connected 3 to NULL
Connected 4 to 5
Connected 5 to 6
Connected 6 to NULL

*******************************************************************************/

#include <stdio.h>
#include <queue>
using namespace std;

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

struct Node * getNode(int data)  {
    Node *newNode = new Node();
    newNode->data = data;
    newNode->left = newNode->right = newNode->nextSibling = NULL;

    return newNode;
}

void printTree(Node *root) {
    queue<Node *> q;
    q.push(root);
    q.push(NULL);
    while(!q.empty()) {
        root = q.front();
        q.pop();
        if(root)    {
            printf("%d ", root->data);
            if(root->left)
                q.push(root->left);
            if(root->right)
                q.push(root->right);
        }
        else    {
            printf("\n");
            if(!q.empty())
                q.push(NULL);
        }
    }
}

void connectSiblings(Node *root) {
    if(root)    {
        queue<Node *> q;
        q.push(root);
        q.push(NULL);
        while(!q.empty())   {
            Node *temp = q.front();
            q.pop();
            if(temp)    {
                temp->nextSibling = q.front();
                if(q.front())
                    printf("Connected %d to %d\n", temp->data, q.front()->data);
                else
                    printf("Connected %d to NULL\n", temp->data);
                if(temp->left)
                    q.push(temp->left);
                if(temp->right)
                    q.push(temp->right);
            }
            else    {
                if(!q.empty())
                    q.push(NULL);
            }
        }
    }
}

int main()  {
    Node *root = getNode(1);
    root->left = getNode(2);
    root->right = getNode(3);
    root->left->left = getNode(4);
    root->left->right = getNode(5);
    root->right->right = getNode(6);
    printf("Tree is:\n");
    printTree(root);
    connectSiblings(root);
    return 0;
}

Connect nodes at same level


#include<iostream>

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

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

			int cnt=1;

			if(pos==1){
				np->next=tmp;
				return np;
			}
			while(cnt!=pos-1){
				tmp=tmp->next;
				cnt++;
			}

			np->next=tmp->next;
			tmp->next=np;

			return head;
		}

		void displayList(Node *head){
			Node *tmp=head;

			if(head==NULL)
				cout<<"No elements in the list! :(\n";
			else{
				cout<<"Elements are: \n";
				while(tmp){
					cout<<tmp->data<<"\n";
					tmp=tmp->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.insertElement(head,p);
	        }

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

	if(pos>n+1)
		cout<<"\nSorry! The position you entered is out of bounds.\n";
	else{
		cout<<"\nInput the data of the node: ";
		cin>>d;
		head=np.insertElementPos(head,d,pos);
	}

        np.displayList(head);}

Add code to insert node in linked list


// RUN: %clang_cc1 -emit-llvm %s -o - -triple=i386-pc-win32 -fexceptions -fcxx-exceptions -fexternc-nounwind | FileCheck %s

namespace test1 {
struct Cleanup { ~Cleanup(); };
extern "C" void never_throws();
void may_throw();

void caller() {
  Cleanup x;
  never_throws();
  may_throw();
}
}
// CHECK-LABEL: define void @"\01?caller@test1@@YAXXZ"(
// CHECK: call void @never_throws(
// CHECK: invoke void @"\01?may_throw@test1@@YAXXZ"(

Add a test for r261425.


#include <iostream>
#include <set>
#include <vector>

using namespace std;

void setZeroes(vector<vector<int> > &matrix) {
    set<int> rows;
    set<int> columns;

    int noRows = matrix.size();
    int noColumns = matrix.at(0).size();

    for (int i = 0; i < noRows; ++i) {
        for (int j = 0; j < noColumns; ++j) {
            if (matrix[i][j] == 0) {
                if (!rows.count(i)) {
                    rows.insert(i);
                }

                if (!columns.count(j)) {
                    columns.insert(j);
                }
            }
        }
    }

    for (set<int>::iterator i = rows.begin(); i != rows.end(); ++i) {
        for (int k = 0; k < noColumns; ++k) {
            matrix[*i][k] = 0;
        }
    }

    for (set<int>::iterator i = columns.begin(); i != columns.end(); ++i) {
        for (int k = 0; k < noRows; ++k) {
            matrix[k][*i] = 0;
        }
    }
}

Set Zeroes in a Matrix


/*
Ex 8.5:
Write two functions that reverse the order of elements in a vector<int>. For
example, 1, 3, 5, 7, 9 becomes 9, 7, 5, 3, 1. The first reverse function should
produce a new vector with the reversed sequence, leaving its original vector
unchanged. The other reverse function should reverse the elements of its vector
without using any other vectors (hint: swap).
*/

#include <vector>
#include <iostream>
#include <stdexcept>
#include <algorithm> // for swap (c++98)
#include <utility>  // for swap (c++11)

using namespace std;

vector<int> create_reverse(vector<int> v){
    vector<int> reverse;
    for(int i = v.size() - 1; i >= 0; --i)
        reverse.push_back(v[i]);
    return reverse;
}

void reverse_this(vector<int>& v){
    int mid = v.size() / 2;
    int end = v.size() -1;
    for(int i = 0; i < mid; ++i)
        swap(v[i], v[end - i]);
}

// int main(int argc, char const *argv[])
// {
//     vector<int> v{1,2,3,4,5,6,7};
//     try{
//         /*Test create_reverse:*/
//         vector<int> reverse = create_reverse(v);
//         for(auto i : reverse)
//             cout << " " << i;
//         cout << endl;
//         Test reverse_this:
//         reverse_this(v);
//         for(auto i: v)
//             cout << " " << i;
//         cout << endl;
//     }catch(runtime_error &e){
//         cout << e.what() << endl;
//     }catch(...){
//         cout << "Exiting..." << endl;
//     }
//     return 0;
// }

int main(int argc, char const *argv[])
{
    vector<int> v(10000,10000);
    try{
        // /*Test performance of create_reverse: real  0m0.452s*/
        // for (int i = 0; i < 1000; ++i)
        //     vector<int> reverse = create_reverse(v);

        // /*Test performance of reverse_this: real  0m0.144s*/
        // for (int i = 0; i < 1000; ++i)
        //     reverse_this(v);

        /*Test performance of std lib: real  0m0.215s ???*/
        for (int i = 0; i < 1000; ++i)
            reverse(v.begin(), v.end());
    }catch(runtime_error &e){
        cout << e.what() << endl;
    }catch(...){
        cout << "Exiting..." << endl;
    }
    return 0;
}

Add ex8.5 and result of performance testing


/*
	This program tests Quick sort
*/

#include<iostream>
#include<vector>
#include "quicksort.h"	// My implementation of Quick sort

// Displays vector

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

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

// Tests Quick sort on vector A

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

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

// tests Quick sort on several different inputs

void testQuickSort(){

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

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

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

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

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

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

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

int main(){

	// test Quick sort
	testQuickSort();

	return 0;
}

Add program to test quicksort


// This file is part of the HörTech Open Master Hearing Aid (openMHA)
// Copyright © 2020 HörTech gGmbH
//
// openMHA is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// openMHA 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 Affero General Public License, version 3 for more details.
//
// You should have received a copy of the GNU Affero General Public License,
// version 3 along with openMHA.  If not, see <http://www.gnu.org/licenses/>.

#include <gtest/gtest.h>
#include "mha_parser.hh"
#include "mha_error.hh"

TEST(mha_parser, insert_2_subparsers_with_same_name_fails)
{
  // create a parser
  MHAParser::parser_t parser;

  // create two parser variables
  MHAParser::int_t i1("i1 help","0","[,]");
  MHAParser::int_t i2("i2 help","0","[,]");

  // try to register both parser variables under the same name
  parser.insert_item("i", &i1);
  EXPECT_THROW(parser.insert_item("i", &i2), MHA_Error);

  // try again to check the error message content
  try {
    parser.insert_item("i", &i2);
    FAIL() << "parser.insert_item should have thrown an exception";
  } catch(MHA_Error & e) {
    ASSERT_STREQ("(mha_parser) The entry \"i\" already exists.", e.get_msg());
  }
}

// Local Variables:
// compile-command: "make -C .. unit-tests"
// coding: utf-8-unix
// c-basic-offset: 2
// indent-tabs-mode: nil
// End:

Add unit test to ensure that inserting the same name twice raises an error


#include <thread>
#include <iostream>
#include <silicon/mhd_serve.hh>
#include <silicon/api.hh>
#include <silicon/client.hh>

using namespace sl;

int main()
{
  auto api = make_api(

    @my_tracking_id = [] (tracking_cookie c) {
      return D(@id = c.id());
    }

    );

  // Start server.
  std::thread t([&] () { mhd_json_serve(api, 12345); });
  usleep(.1e6);

  // Test.
  auto c = json_client(api, "127.0.0.1", 12345);

  auto r1 = c.my_tracking_id();
  auto r2 = c.my_tracking_id();

  std::cout << r1.response.id << std::endl;
  std::cout << r2.response.id << std::endl;

  assert(r1.response.id == r2.response.id);

  exit(0);
}

Add and test cookie tracking to microhttpd.


// Naive solution would iterate all lists to take the smallest head every time to
// add to the merged list. Actually we have a efficient data structure to retrieve
// the smallest element from a bunch of elements. That is a "min heap".
// In the implementation below, I created a wrapper for list so that we could use
// heap provided by STL more smoothly.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    struct Proxy {
        ListNode* list;
        Proxy(){}
        Proxy(ListNode* head): list(head){}
        bool next() {
            list = list->next;
            return list != nullptr;
        }
        bool operator < (const Proxy& rhs) const {
            return list->val > rhs.list->val;
        }
    };
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        vector<Proxy> heads;
        for (auto l: lists) {
            if (l != nullptr) {
                heads.push_back(Proxy(l));
            }
        }
        make_heap(heads.begin(), heads.end());
        ListNode dummy(0);
        ListNode* merged_list = &dummy;
        while (!heads.empty()) {
            pop_heap(heads.begin(), heads.end());
            Proxy& smallest = heads.back();
            merged_list->next = smallest.list;
            merged_list = merged_list->next;
            if (smallest.next()) {
                push_heap(heads.begin(), heads.end());
            } else {
                heads.pop_back();
            }
        }
        return dummy.next;
    }
};

Add a solution for problem 23: Merge k Sorted Lists.


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

#include "content/app/mojo/mojo_init.h"

#include "base/memory/scoped_ptr.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/simple_platform_support.h"

namespace content {

void InitializeMojo() {
  mojo::embedder::Init(scoped_ptr<mojo::embedder::PlatformSupport>(
      new mojo::embedder::SimplePlatformSupport()));
}

}  // namespace content

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

#include "content/app/mojo/mojo_init.h"

#include "base/memory/scoped_ptr.h"
#include "mojo/edk/embedder/configuration.h"
#include "mojo/edk/embedder/embedder.h"
#include "mojo/edk/embedder/simple_platform_support.h"

namespace content {

void InitializeMojo() {
  // Things like content_shell and DevTools ocassionally send big
  // message which includes whole rendered screen or all loaded
  // scripts. The buffer size has to be big enough to allow such use
  // cases.
  mojo::embedder::GetConfiguration()->max_message_num_bytes = 64*1024*1024;
  mojo::embedder::Init(scoped_ptr<mojo::embedder::PlatformSupport>(
      new mojo::embedder::SimplePlatformSupport()));
}

}  // namespace content

Raise the message size limit.


#include<iostream>

int main()
{
    unsigned N,K;
    unsigned Ai[1000],VarAi[1000];
    unsigned max=0,capacity,varIndx,v_capacity;
    unsigned big,hasMoreValues,flag=1;

    do
    {
        std::cin>>N;
    }while(N<1 || N>1000);
    do
    {
        std::cin>>K;
    }while(K<1 || K>1000);

    for(int i=0;i<N;i++)
    {
        do
        {
            std::cin>>Ai[i];
        }while(Ai[i]<1 || Ai[i]>100000);
        if(Ai[i]>max)
        {
            max=Ai[i];
        }
    }
    capacity=max;

    while(1)
    {
        flag=1;
        for(int h=0;h<N;h++)
        {
            VarAi[h]=Ai[h];
        }

        for(int i=0;i<K;i++)
        {
            v_capacity=capacity;
            while(1)
            {
                big=0;
                hasMoreValues=0;
                for(int j=0;j<N;j++)
                {
                    if(VarAi[j]>big && VarAi[j]<=v_capacity)
                    {
                        hasMoreValues=1;
                        big=VarAi[j];
                        varIndx=j;;
                    }
                }

                if(hasMoreValues)
                {
                    VarAi[varIndx]=0;
                    v_capacity-=big;
                    continue;
                }
                else
                {
                    break;
                }
            }
        }
        for(int k=0;k<N;k++)
        {
            if(VarAi[k]!=0)
                flag=0;
        }
        if(flag)
        {
            std::cout<<capacity;
            break;
        }
        else
            capacity++;
    }

    return 0;
}

Add fixed solution to fast tast "Kozichki"


#include <iostream>
#include <vector>
#include <algorithm>
#include <random>

using namespace std;

int main() {

	vector<int> vec(10000);
	generate(vec.begin(), vec.end(), rand);

	sort(vec.begin(), vec.end(), [](int a, int b) -> bool { return a > b; });

	for (auto &a : vec) {
		cout << a << " ";
	}
	cout << endl;

	return 0;
}

Add qsort with lambda function in c++11 standard.


#include "PTask.h"

PFunction::PFunction(svector<PWire*>*p, Statement*s)
: ports_(p), statement_(s)
{
}

PFunction::~PFunction()
{
}

Add functions up to elaboration (Ed Carter)


#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace cv;

#if defined(_MSC_VER) || defined(WIN32)  || defined(_WIN32) || defined(__WIN32__) \
    || defined(WIN64)    || defined(_WIN64) || defined(__WIN64__)
# include <io.h>
# include <fcntl.h>
# define SET_BINARY_MODE(handle) setmode(handle, O_BINARY)
#else
# define SET_BINARY_MODE(handle) ((void)0)
#endif

#define BUFSIZE 10240
int main ( int argc, char **argv )
{

    SET_BINARY_MODE(fileno(stdin));
    std::vector<char> data;
    bool skip=true;
    bool imgready=false;
    bool ff=false;
    int readbytes=-1;
    while (1)
    {
        char ca[BUFSIZE];
        uchar c;
        if (readbytes!=0)
        {
            readbytes=read(fileno(stdin),ca,BUFSIZE);
            for(int i=0;i<readbytes;i++)
            {
                c=ca[i];
                if(ff && c==(uchar)0xd8)
                {
                    skip=false;
                    data.push_back((uchar)0xff);
                }
                if(ff && c==0xd9)
                {
                    imgready=true;
                    data.push_back((uchar)0xd9);
                    skip=true;
                }
                ff=c==0xff;
                if(!skip)
                {
                    data.push_back(c);
                }
                if(imgready)
                {
                    if(data.size()!=0)
                    {
                        cv::Mat data_mat(data);
                        cv::Mat frame(imdecode(data_mat,1));

                        imshow("frame",frame);
                        waitKey(1);
                    }else
                    {
                        printf("warning");
                    }
                    imgready=false;
                    skip=true;
                    data.clear();
                }
            }
        }
        else
        {
            throw std::string("zero byte read");
        }
    }
}

Enable to pass mjpeg stream from node to c++


#include <cstdio>
#include <cctype>

using namespace std;

int a[10];

void print_number(int a[])
{
  for (int i = 9; i >= 0; i--)
  {
    while (a[i] > 0)
    {
      printf("%d", i);
      a[i]--;
    }
  }
  printf("\n");
}

int main()
{
  char x;

  while (scanf("%c", &x) != EOF)
  {
    if (x == ' ')
    {
      print_number(a);
    }
    else if (isdigit(x))
    {
      a[x - '0']++;
    }
  }
  print_number(a);

  return 0;
}

Add a solution for task 4a


// 005. Longest Palindromic Substring
/**
 * Given a string S, find the longest palindromic substring in S.
 * You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
 *
 * Tags: String
 *
 * Author: Kuang Qin
 */

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

using namespace std;

class Solution {
public:
    string longestPalindrome(string s) {
        int n = s.size();
        if (n < 2)
        {
            return s;
        }

        int start = 0, maxLen = 0, left = 0, right = 0, index = 0;
        // stop if max length is larger than twice the length from index to end
        while ((index < n) && (maxLen < 2 * (n - index)))
        {
            left = right = index;
            while ((right < n - 1) && (s[right + 1] == s[right]))
            {
                right++;    // skip all duplicates
            }

            index = right + 1;    // set next index

            while ((left > 0) && (right < n - 1) && (s[left - 1] == s[right + 1]))
            {
                left--;
                right++;
            }

            // current maxlength at index
            int curLen = right - left + 1;
            if (curLen > maxLen)
            {
                maxLen = curLen;
                start = left;
            }
        }

        return s.substr(start, maxLen);
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    string s("abcbababc");
    Solution mySolution;
    string res = mySolution.longestPalindrome(s);
    cout << res << endl;
    system("pause");
    return 0;
}

Add Solution for Problem 005


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


// 459. Repeated Substring Pattern
/**
 * Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
 * You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
 *
 * Example 1:
 *
 * Input: "abab"
 * Output: True
 * Explanation: It's the substring "ab" twice.
 *
 * Example 2:
 *
 * Input: "aba"
 * Output: False
 *
 * Example 3:
 *
 * Input: "abcabcabcabc"
 * Output: True
 * Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
 *
 *
 * Tags: String
 *
 * Similar Problems: (E) Implement strStr()
 *
 * Author: Kuang Qin
 */

#include <iostream>
#include <string>

using namespace std;

// build new string to check repeated pattern
class Solution2 {
public:
    bool repeatedSubstringPattern(string str) {
        int n = str.size();

        // start from n/2 to check its possible substring
        for (int i = n / 2; i > 0; i--) {
            if (n % i == 0) {
                int m = n / i;  // repeated m times
                string s = str.substr(0, i);
                string p = "";
                while (m--) {
                    p += s; // create a new patterned string to compare
                }

                if (p == str) { // if equal return true
                    return true;
                }
            }
        }

        return false;
    }
};

// check prefix and suffix inspired by KMP
class Solution {
public:
    bool repeatedSubstringPattern(string str) {
        int n = str.size();

        // start from n/2 to check its possible substring
        for (int i = n / 2; i > 0; i--) {
            if (n % i == 0) {
                string pre = str.substr(0, n - i);  // prefix
                string suf = str.substr(i);         // suffix
                if (pre == suf) {   // if equal return true
                    return true;
                }
            }
        }

        return false;
    }
};

int main() {
    string str = "aaaaa";
    Solution sol;
    bool ans = sol.repeatedSubstringPattern(str);
    cout << ans << endl;
    cin.get();

    return 0;
}

Add Solution for 459 Repeated Substring Pattern


// RUN: %clang_cc1 -fsyntax-only -std=c++11 -Wc++14-compat-pedantic -verify %s
// RUN: %clang_cc1 -fsyntax-only -std=c++17 -Wc++14-compat-pedantic -verify %s

#if __cplusplus < 201402L

// expected-no-diagnostics
// FIXME: C++11 features removed or changed in C++14?

#else

static_assert(true); // expected-warning {{incompatible with C++ standards before C++17}}

template<int ...N> int f() { return (N + ...); } // expected-warning {{incompatible with C++ standards before C++17}}

namespace [[]] NS_with_attr {} // expected-warning {{incompatible with C++ standards before C++17}}
enum { e [[]] }; // expected-warning {{incompatible with C++ standards before C++17}}

template<typename T = int> struct X {};
X x; // expected-warning {{class template argument deduction is incompatible with C++ standards before C++17}}

template<template<typename> class> struct Y {};
Y<X> yx; // ok, not class template argument deduction

template<typename T> void f(T t) {
  X x = t; // expected-warning {{incompatible}}
}

template<typename T> void g(T t) {
  typename T::X x = t; // expected-warning {{incompatible}}
}
struct A { template<typename T> struct X { X(T); }; };
void h(A a) { g(a); } // expected-note {{in instantiation of}}

#endif

Add test file missed from r341097.


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

#include "athena/content/content_activity_factory.h"

#include "athena/activity/public/activity_manager.h"
#include "athena/content/app_activity.h"
#include "athena/content/web_activity.h"
#include "base/logging.h"

namespace athena {

ContentActivityFactory::ContentActivityFactory() {
}

ContentActivityFactory::~ContentActivityFactory() {}

Activity* ContentActivityFactory::CreateWebActivity(
    content::BrowserContext* browser_context,
    const base::string16& title,
    const GURL& url) {
  Activity* activity = new WebActivity(browser_context, title, url);
  ActivityManager::Get()->AddActivity(activity);
  return activity;
}

Activity* ContentActivityFactory::CreateWebActivity(
    content::WebContents* contents) {
  Activity* activity = new WebActivity(contents);
  ActivityManager::Get()->AddActivity(activity);
  return activity;
}

Activity* ContentActivityFactory::CreateAppActivity(
    const std::string& app_id,
    views::WebView* web_view) {
  Activity* activity = new AppActivity(app_id, web_view);
  ActivityManager::Get()->AddActivity(activity);
  return activity;
}

ActivityFactory* CreateContentActivityFactory() {
  return new ContentActivityFactory();
}

}  // namespace athena

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

#include "athena/content/content_activity_factory.h"

#include "athena/activity/public/activity_manager.h"
#include "athena/content/app_activity.h"
#include "athena/content/web_activity.h"
#include "base/logging.h"
#include "ui/aura/window.h"

namespace athena {

ContentActivityFactory::ContentActivityFactory() {
}

ContentActivityFactory::~ContentActivityFactory() {}

Activity* ContentActivityFactory::CreateWebActivity(
    content::BrowserContext* browser_context,
    const base::string16& title,
    const GURL& url) {
  Activity* activity = new WebActivity(browser_context, title, url);
  ActivityManager::Get()->AddActivity(activity);
  activity->GetWindow()->SetName("WebActivity");
  return activity;
}

Activity* ContentActivityFactory::CreateWebActivity(
    content::WebContents* contents) {
  Activity* activity = new WebActivity(contents);
  ActivityManager::Get()->AddActivity(activity);
  return activity;
}

Activity* ContentActivityFactory::CreateAppActivity(
    const std::string& app_id,
    views::WebView* web_view) {
  Activity* activity = new AppActivity(app_id, web_view);
  ActivityManager::Get()->AddActivity(activity);
  activity->GetWindow()->SetName("AppActivity");
  return activity;
}

ActivityFactory* CreateContentActivityFactory() {
  return new ContentActivityFactory();
}

}  // namespace athena

Set window name to activities


#include <iostream>
#include <random>

using namespace std;

int generate_random_number(const int a = 0, const int b = 9) {
    static default_random_engine e;
    static uniform_int_distribution<unsigned> u(a, b);
    return u(e);
}

int main() {

    for(int i = 0; i != 20; ++ i) {
        cout << generate_random_number() << endl;
    }

    return 0;
}

Add solution for chapter 17 test 28


// Copyright Daniel Wallin 2009. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include "test.hpp"
#include <luabind/luabind.hpp>
#include <luabind/detail/shared_ptr_converter.hpp>

struct X
{
    X(int value)
      : value(value)
    {}

    int value;
};

int get_value(boost::shared_ptr<X> const& p)
{
    return p->value;
}

void test_main(lua_State* L)
{
    using namespace luabind;

    module(L) [
        class_<X>("X")
            .def(constructor<int>()),
        def("get_value", &get_value)
    ];

    DOSTRING(L,
        "x = X(1)\n"
        "assert(get_value(x) == 1)\n"
    );
}

// Copyright Daniel Wallin 2009. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include "test.hpp"
#include <luabind/luabind.hpp>
#include <luabind/shared_ptr_converter.hpp>

struct X
{
    X(int value)
      : value(value)
    {}

    int value;
};

int get_value(boost::shared_ptr<X> const& p)
{
    return p->value;
}

boost::shared_ptr<X> filter(boost::shared_ptr<X> const& p)
{
    return p;
}

void test_main(lua_State* L)
{
    using namespace luabind;

    module(L) [
        class_<X>("X")
            .def(constructor<int>()),
        def("get_value", &get_value),
        def("filter", &filter)
    ];

    DOSTRING(L,
        "x = X(1)\n"
        "assert(get_value(x) == 1)\n"
    );

    DOSTRING(L,
        "assert(x == filter(x))\n"
    );
}

Test object identity with shared_ptr_converter.


/*
Assume you have a method isSubstring which checks
if one word is a substring of another string.
Given two strings s1, and s2. write code to check
if s2 is a rotation of s1 using only one call to
isSubstring (i.e., “waterbottle” is a rotation of “erbottlewat”).
*/

# include <iostream>

using namespace std;

bool isSubstring(string str1, string str2) {
	return (str1.find(str2) != string::npos);
}

bool isRotation(string s1, string s2) {
	string tmp = s1 + s1;

	return isSubstring(tmp, s2);
}

int main() {
	string str1 = "erbottlewat";
	string str2 = "waterbottle";

	cout << "Is Rotation? " << isRotation(str1, str2);
}

Call substr only once to check isRotation of strings


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

#include "chrome/common/chrome_version_info.h"

#include "base/android/build_info.h"
#include "base/logging.h"
#include "base/strings/string_util.h"

namespace chrome {

// static
std::string VersionInfo::GetVersionStringModifier() {
  switch (GetChannel()) {
    case CHANNEL_UNKNOWN: return "unknown";
    case CHANNEL_CANARY: return "canary";
    case CHANNEL_DEV: return "dev";
    case CHANNEL_BETA: return "beta";
    case CHANNEL_STABLE: return std::string();
  }
  NOTREACHED() << "Unknown channel " << GetChannel();
  return std::string();
}

// static
VersionInfo::Channel VersionInfo::GetChannel() {
  const base::android::BuildInfo* bi = base::android::BuildInfo::GetInstance();
  DCHECK(bi && bi->package_name());

  if (!strcmp(bi->package_name(), "com.android.chrome"))
    return CHANNEL_STABLE;
  if (!strcmp(bi->package_name(), "com.chrome.beta"))
    return CHANNEL_BETA;
  if (!strcmp(bi->package_name(), "com.google.android.apps.chrome_dev"))
    return CHANNEL_DEV;

  return CHANNEL_UNKNOWN;
}

}  // namespace chrome

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

#include "chrome/common/chrome_version_info.h"

#include "base/android/build_info.h"
#include "base/logging.h"
#include "base/strings/string_util.h"

namespace chrome {

// static
std::string VersionInfo::GetVersionStringModifier() {
  switch (GetChannel()) {
    case CHANNEL_UNKNOWN: return "unknown";
    case CHANNEL_CANARY: return "canary";
    case CHANNEL_DEV: return "dev";
    case CHANNEL_BETA: return "beta";
    case CHANNEL_STABLE: return std::string();
  }
  NOTREACHED() << "Unknown channel " << GetChannel();
  return std::string();
}

// static
VersionInfo::Channel VersionInfo::GetChannel() {
  const base::android::BuildInfo* bi = base::android::BuildInfo::GetInstance();
  DCHECK(bi && bi->package_name());

  if (!strcmp(bi->package_name(), "com.android.chrome"))
    return CHANNEL_STABLE;
  if (!strcmp(bi->package_name(), "com.chrome.beta"))
    return CHANNEL_BETA;
  if (!strcmp(bi->package_name(), "com.google.android.apps.chrome_dev"))
    return CHANNEL_DEV;
  if (!strcmp(bi->package_name(), "com.chrome.canary"))
    return CHANNEL_CANARY;

  return CHANNEL_UNKNOWN;
}

}  // namespace chrome

Fix VersionInfo::GetChannel for Android canary.


// Make sure we emit the MS ABI default ctor closure with PCH.
//
// Test this without pch.
// RUN: %clang_cc1 -fms-extensions -triple x86_64-windows-msvc -std=c++11 -include %s -emit-llvm -o - %s | FileCheck %s

// Test with pch.
// RUN: %clang_cc1 -fms-extensions -triple x86_64-windows-msvc -std=c++11 -emit-pch -o %t %s
// RUN: %clang_cc1 -fms-extensions -triple x86_64-windows-msvc -std=c++11 -include-pch %t -emit-llvm -o - %s | FileCheck %s

#ifndef HEADER
#define HEADER

struct __declspec(dllexport) Foo {
  enum E { E0 } e;
  Foo(E e = E0) : e(e) {}
};

// Demangles as:
// void Foo::`default constructor closure'(void)
// CHECK: define weak_odr dllexport void @"\01??_FFoo@@QEAAXXZ"(%struct.Foo*{{.*}})
// CHECK:   call %struct.Foo* @"\01??0Foo@@QEAA@W4E@0@@Z"(%struct.Foo* {{.*}}, i32 0)

#else

#endif

Add dllexport default ctor closure PCH regression test for PR31121


// Chapter 19, exercise 10: implement a simple auto_ptr supporting only a
// constructor, destructor, ->, * and release() - don't try assignment or copy
// constructor

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

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

struct Tracer {
    Tracer() { cout << "Tracer()\n"; }
    ~Tracer() { cout << "~Tracer()\n"; }
};

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

template<class T> class auto_pntr {
    T* val;
public:
    auto_pntr(T* arg) : val(arg) { }

    ~auto_pntr() { delete val; }

    T operator*() const { return *val; }
    T* operator->() const { return val; }

    T* release()
    {
        T* temp = val;
        val = 0;
        return temp;
    }
};

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

// demonstrates how only destructor of object held by auto_pntr is called
Tracer* f()
{
    Tracer* p1 = new Tracer();          // destructor never called
    auto_pntr<Tracer> p2(new Tracer()); // destructor called when out of scope
    auto_pntr<Tracer> p3(new Tracer()); // released from auto_pntr
    return p3.release();
}

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

int main()
try {
    Tracer* p = f();
    delete p;
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

Add Chapter 19, exercise 10


#include "DayTime.hpp"
#include "CommonTime.hpp"
#include <iostream>

using namespace gpstk;
using namespace std;

int main()
{
CommonTime common = CommonTime();
DayTime day = DayTime();

day = common;
common = day;

day = CommonTime();
common = DayTime();

return 0;
}

Test case to check CommonTime and DayTime compatability


// RUN: clang-cc %s -emit-llvm-only

class Base {
public:
   virtual ~Base();
};

Base::~Base()
{
}

class Foo : public Base {
public:
   virtual ~Foo();
};

Foo::~Foo()
{
}

Test for non-canonical decl and vtables.


// https://leetcode.com/problems/contains-duplicate-ii/
// Compared to 'contains duplicate i', now we also need to know the index of number for
// query. So we use a number to index map.

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int, size_t> value_index_map;
        for (size_t i = 0; i < nums.size(); ++i) {
            auto itr = value_index_map.find(nums[i]);
            if (itr != value_index_map.end() && i - itr->second <= k) {
                return true;
            }
            value_index_map[nums[i]] = i;
        }
        return false;
    }
};

Add a solution for problem 219: Contains Duplicate II.


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

char convert(char x)
{
	if (x >= 'A' && x <= 'P') {
		return ((x - 'A') / 3 + 2) + '0';
	}
	if (x >= 'R' && x <= 'Y') {
		return ((x - 'A' - 1) / 3 + 2) + '0';
	}
	else {
		return x;
	}
}

string mapper(string s)
{
	string res = "";
	for (string::size_type i = 0; i != s.size(); i++) {
		if (s[i] != '-') {
			res.push_back(convert(s[i]));
		}
	}
	return res;
}

int main()
{
	int T;
	cin >> T;
	while (T--) {
		list<string> str_list;
		int k;
		cin >> k;
		while (k--) {
			string s;
			cin >> s;
			str_list.push_back(mapper(s));
		}
		map<string, int> str_int_map;
		for (list<string>::iterator iter = str_list.begin(); iter != str_list.end(); iter++) {
			map<string, int>::iterator map_iter = str_int_map.find(*iter);
			if (map_iter == str_int_map.end()) {
				str_int_map.insert(pair<string, int>(*iter, 1));
			}
			else {
				map_iter->second++;
			}
		}
		for (map<string, int>::iterator iter = str_int_map.begin(); iter != str_int_map.end(); iter++) {
			if (iter->second >= 2) {
				string res = iter->first;
				cout << res.substr(0, 3) + "-" + res.substr(3,4) + " " << iter->second << endl ;
			}
		}

	}
	return 0;
}

Add the solution to "Phone Patterns".


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

unsigned long long p[3];

unsigned long long* gcdEx(unsigned long long a, unsigned long long b, unsigned long long *p) {
    if (b == 0) {
        p[0] = 1, p[1] = 0, p[2] = a;
        return p;
    } else {
        p = gcdEx(b, b%a, p);
        unsigned long long t = p[0];
        p[0] = p[1];
        p[1] = t - a/b*p[1];
        return p;
    }
}

void swap(unsigned long long &a, unsigned long long &b) {
    if (a != b) {
        a ^= b ^= a ^= b;
    }
}

unsigned long long gcd(unsigned long long a, unsigned long long b) {
    if (a == 0 || b == 0) return 0;
    while (a && b) b%=a^=b^=a^=b;
    return a+b;
}

void solve() {
    unsigned long long n;

    scanf("%llu", &n);

    // ans  = ans1 / ans2;
    unsigned long long ans1, ans2;

    unsigned long long a, b;

    scanf("%llu", &a);
    scanf("%llu", &b);
    if (a > b) {
        swap(a, b);
    }
    ans1 = a * b;
    ans2 = 2 * (b - a);
    unsigned long long g = gcd(ans1, ans2);
    if (g != 0) {
        ans1 /= g;
        ans2 /= g;
    } else {
        ans1 = 0;
        ans2 = 1;
    }

    for (unsigned long long i = 2; i < n; ++ i) {
        scanf("%llu", &b);

        if (a > b) {
            swap(a, b);
        }
        unsigned long long newans1, newans2;
        newans1 = a * b;
        newans2 = 2 * (b - a);

        unsigned long long g = gcd(newans1, newans2);
        if (g != 0) {
            newans1 /= g;
            newans2 /= g;
        } else {
            continue;
        }

        if (ans1 == 0) {
            ans1 = newans1;
            ans2 = newans2;
            continue;
        }

        g = gcd(ans1 * newans2, newans1 * ans2);
        ans1 *= newans1 * ans2 / g;
        g = gcd(ans1, ans2);
        ans1 /= g;
        ans2 /= g;
    }

    printf("%llu %llu", ans1, ans2);
}

void test() {
    gcdEx(8, 5, p);
    printf("%llu %llu %llu\n", p[0], p[1], p[2]);
}

int main() {
    solve();

    return 0;
}

Add 3101 astronomy cpp version, which doesn't handle the big integer and WA. JAVA was used instead to AC


// 134. Gas Station
/**
 * There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
 *
 * You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
 *
 * Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
 *
 * Note:
 * The solution is guaranteed to be unique.
 *
 * Tags: Greedy
 *
 * Author: Kuang Qin
 */

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

using namespace std;

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int n = gas.size();
        int start = 0, sum = 0, total = 0;

        // start: the starting point
        // sum:   remaining gas from start up to current station
        // total: overall remaining gas
        for (int i = 0; i < n; i++)
        {
            int remain = gas[i] - cost[i];    // remaining gas at station i
            sum += remain;
            total += remain;
            if (sum < 0)    // no gas at this point
            {
                sum = 0;    // reset sum
                start = i + 1;    // start from next station
            }
        }

        if (total < 0)    // unable to travel once if the total is negative
        {
            return -1;
        }

        // Conclusion:
        // If the total remaining gas is positive, the circuit can be travelled around once from the start position
        // (at any station, the cumulative remaining gas from the start station is positive)
        //
        // Proof:
        // from the for loop we know that from start to n the sum is positive, so
        //
        //     remain[start] + ... + remain[n - 1] >= 0
        //
        // also, it is the last time where sum < 0 at station (start - 1), it means that the cumulative total:
        //
        //     remain[0] + ... + remain[start - 1] is the minimum
        //
        // so if the total remaining gas is positive, given any station j we have the wrap around total:
        //
        //     remain[start] + ... + remain[n - 1] + remain[0] + ... + remain[j]
        //  >= remain[start] + ... + remain[n - 1] + remain[0] + ... + remain[start - 1]
        //   = remain[0] + remain[n - 1] = total > 0

        return start;
    }
};

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

Add Solution for Problem 134


#include <string>
#include <cstdio>

std::string GetFilenameExt(std::string filename) {
  std::string ext_name("");
  std::string::size_type index = filename.rfind('.');
  if(index != std::string::npos)
    ext_name = filename.substr(index+1);
  return ext_name;
}
int main (int argc, char *argv[]) {
  for(unsigned int index = 1; index < argc; index++) {
    printf("DEBUG: File name: %s. ext name: %s\n",argv[index], GetFilenameExt(argv[index]).c_str());
  }
}

Print the file name and file extension name of all arguments


#include <iostream>

using namespace std;

template <typename T>
T calc(T a, int i) {
    return a;
}

template <typename T>
T fcn(T a, T b) {
    return a;
}

int main() {
    double d;
    float f;
    char c = 'a';
    calc(c, 'c');//good
    calc(d, f);//good
    cout << fcn(c, 'c');
//    fcn(d, f);
}

Add solution for chapter 16 test 35


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

using namespace std;

bool valid(const smatch &m) {
    if(m[1].matched) {
        return m[3].matched && (m[4].matched == 0 || m[4].str() == " ");
    } else {
        return m[3].matched == 0 && m[4].str() == m[6].str();
    }
}

int main() {
    string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})";
    regex r(phone);
    string s;
    while(getline(cin, s)) {
        for(sregex_iterator it(s.begin(), s.end(), r), it_end; it != it_end; ++ it) {
            if(valid(*it)) {
                cout << "valid: " << it -> str() << endl;
            } else {
                cout << "not valid: " << it -> str() << endl;
            }
        }
    }
    return 0;
}

Add solution for chapter 17 test 20


Add initial foundation cpp file.