167. Two Sum II - Input array is sorted
/**
 * Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
 *
 * The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
 *
 * You may assume that each input would have exactly one solution.
 *
 * Input: numbers={2, 7, 11, 15}, target=9
 * Output: index1=1, index2=2
 *
 * Tags: Array, Two Pointers, Binary Search
 *
 * Similar Problems: (E) Two Sum
 *
 * Author: Kuang Qin
 */

#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> res;
        int n = numbers.size();
        if (n < 2)
            return res;

        // use two pointers
        int left = 0, right = n - 1;

        while (left < right)
        {
            int sum = numbers[left] + numbers[right];

            if (sum == target)
            {
                res.push_back(left + 1);
                res.push_back(right + 1);
                break;
            }
            else if (sum < target)
                left++;
            else    // sum > target
                right--;
        }

        return res;
    }
};

int main()
{
    vector<int> numbers = {2, 3, 4};
    int target = 6;
    Solution sol;
    vector<int> res = sol.twoSum(numbers, target);
    cout << "index1 = " << res[0] << ", index2 = " << res[1] << endl;
    cin.get();

    return 0;
}

Add Solution for 167. Two Sum II - Input array is sorted


/**
 * To implement minimum stack that returns minimum element in O(1) time
 */
 #include <iostream>
 #include <stack>
 using namespace std;

 class MinStack {
 private:
 	stack<int> min;
 	stack<int> s;
 public:
 	void push(int data) {
 		if (min.empty()) {
 			min.push(data);
 		} else if (data < min.top()) {
 			min.push(data);
 		} else if (data > min.top()) {
 			min.push(min.top());
 		}

 		s.push(data);
 	}

 	void pop() {
 		min.pop();
 		s.pop();
 	}

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

 	/**
 	 * T(n) = O(1)
 	 **/
 	int getMin() {
 		return min.top();
 	}
 };

 int main() {
 	MinStack minStack;
 	int keys[] = {3, 1, 2, -1, 0, 4, -6};
 	int size = sizeof(keys)/sizeof(keys[0]);

 	for (int i = 0; i < size; i++) {
 		cout<<"Pushing key: "<<keys[i]<<endl;
 		minStack.push(keys[i]);
 		cout<<"Current Minimum: "<<minStack.getMin()<<endl;
 	}

 	cout<<"Popping 5 values\n";
 	for (int i = 0; i < 5; i++) {
 		cout<<"Popping: "<<minStack.top()<<endl;
 		minStack.pop();
 		cout<<"Current Minimum: "<<minStack.getMin()<<endl;
 	}

 	return 0;
 }

Implement minimum stack that will return
the minimum element from the entire stack
in O(1) time

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


#include <iostream>
#include <queue>

using std::cout;
using std::queue;

int dequeue_min(queue<int>& q) {
  unsigned long queue_size = q.size();

  int min = q.front();
  q.pop();

  for (int i = 1; i < queue_size; ++i) {
    int front = q.front();
    q.pop();

    if (front < min) {
      q.push(min);
      min = front;
    } else {
      q.push(front);
    }
  }

  return min;
}

void print_queue(queue<int> q) {
  while (!q.empty()) {
    cout << q.front() << ' ';
    q.pop();
  }
}

int main() {
  queue<int> q;
  q.push(4);
  q.push(2);
  q.push(6);
  q.push(-1);
  q.push(3);

  cout << dequeue_min(q) << '\n';
  print_queue(q);
  cout << '\n';

  return 0;
}

Add dequeue min task solution

Add dequeue min task solution


/*
 * Copyright 2010, NagaChaitanya Vellanki
 *
 * Author NagaChaitanya Vellanki
 *
 * Print length of the period of decimal representation of 1/n for n > 1
 */

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

using namespace std;

int main() {
  int32_t n = 0;

  cout << "Enter n(n > 1)" << endl;
  cin >> n;

  if(n <= 1) {
    exit(0);
  }

  int32_t rem = 1;
  int32_t i = 0;

  // period of a fraction cannot be less than the period of sequence of
  // remainders
  while(i < n) {
    rem = (10 * rem) % n;
    i++;
  }

  // c is the (n + 1)th term in the sequence remainders
  int32_t c = rem;

  rem = (10 * rem) % n; // (n + 2)th term in the sequence of remainders
  i =  1;

  while(rem != c) {
    rem = (rem * 10) % n;
    i++;
  }

  cout << "The period length of " << 1 << "/" << n << " is " << i << endl;
  return 0;
}

Add period length of 1/n

Add period length of 1/n


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

using namespace std;

struct Base1 {
    void print(int i) const {
        cout << "Base1::print(int)" << endl;
    }

protected:
    int ival;
    double dval;
    char cval;
private:
    int *id;
};

struct Base2 {
    void print(double d) const {
        cout << "Base2::print(double)" << endl;
    }
protected:
    double fval;
private:
    double dval;
};

struct Derived : public Base1 {
    void print(string s) const {
        cout << "Derived::print(string)" << endl;
    }
protected:
    string sval;
    double dval;
};

struct MI : public Derived, public Base2 {
    void print(vector<double> dvec) {
        cout << "MI::print(vector<double>)" << endl;
    }

    //for test 18.26
    void print(int i) const {
        cout << "MI::print(int)" << endl;
        Base1::print(i);
    }
    void foo(double);

protected:
    int *ival;
    vector<double> dvec;
};

int ival;
double dval;

//for test 18.27
void MI::foo(double cval) {
    int dval;
    dval = Base1::dval + Derived::dval;
    Base2::fval = dvec[dvec.size() - 1];
    sval[0] = Base1::cval;
}

int main() {
    MI mi;
    mi.print(42);

    return 0;
}

Add solution for chapter 18, test 26, 27


// Write class type objects to a stream

#include <iostream>

class foo
{
	public:
		foo(int x)
			: x(x)
		{ }

		friend std::ostream& operator<<(std::ostream& stream,
		                                foo const& f);

	private:
		int x;
};

std::ostream& operator<<(std::ostream& stream,
                         foo const& f)
{
	return stream << "A foo with x = " << f.x;
}

int main()
{
	foo f(10);
	std::cout << f << std::endl;
}

// Write your class type objects to an output stream by implementing
// `operator<<`.
//
// We implement `operator<<` on [19-23], which takes a reference to an
// [`std::ostream`](cpp/io/basic_ostream) (the base class for all
// output streams) and the `foo` object we wish to write to the stream.
// On [22], we simply write a string representing the `foo` object to
// the steam and return a reference to the stream itself, allowing
// this call to be chained.
//
// Note that we declare this `operator<<` as a `friend` of `foo` on
// [12-13]. This gives it access to `foo`'s private member, `x`.
//
// On [27-28], we stream a `foo` object to [`std::cout`](cpp/io/cout).

Add "write class type objects" sample

Add "write class type objects" sample


#include <iostream>
// yaml-cpp includes
#include "yaml-cpp/yaml.h"

int main()
{
   YAML::Emitter out;
   out << "Hello, World!";

   std::cout << "Here's the output YAML:\n" << out.c_str();

   return 0;
}

#include <iostream>
#include <yaml-cpp/yaml.h>

int main()
{
   YAML::Emitter out;
   out << "Hello, World!";

   std::cout << "Here's the output YAML:\n" << out.c_str();

   return 0;
}

Remove comment. Just a trigger for a new build.


#include <cmath>
#include <memory>
#include <vector>
#include <parfil/robot.h>
#include <parfil/filter.h>

void TestCase1(std::vector<parfil::Motion>& motions, std::vector<parfil::Measurement>& measurements) {
  // fill in motions
  int num_motions = 8;
  motions.resize(num_motions);
  for (int i=0; i<num_motions; ++i) {
    motions[i].steering_angle = 2.0*M_PI/10.0;
    motions[i].forward_distance = 20.0;
  }

  // fill in measurements
  double[] measurements_arr = {
      4.746936, 3.859782, 3.045217, 2.045506,
      3.510067, 2.916300, 2.146394, 1.598332,
      2.972469, 2.407489, 1.588474, 1.611094,
      1.906178, 1.193329, 0.619356, 0.807930,
      1.352825, 0.662233, 0.144927, 0.799090,
      0.856150, 0.214590, 5.651497, 1.062401,
      0.194460, 5.660382, 4.761072, 2.471682,
      5.717342, 4.736780, 3.909599, 2.342536
  };
  int num_measurements = 8;
  int measurement_dimension = 4;
  measurements.resize(8);
  for (int i=0; i<num_measurements; ++i) {
    measurements[i].resize(measurement_dimension);
    double* from = measurements_arr + measurement_dimension*i;
    double* to = from + measurement_dimension;
    measurements[i].assign(from,to);
  }
}

int main(int, char**) {
  int num_particles = 500;
  std::unique_ptr<parfil::Filter> filter(new parfil::Filter(num_particles));

  std::vector<parfil::Motion> motions;
  std::vector<parfil::Measurement> measurements;
  TestCase1(motions,measurements);

  filter->run(motions,measurements);

  double x,y,heading;
  filter->GetPose(x,y,heading);
  std::cout << "x: " << x << " y: " << y << " heading: " << heading << std::endl;

  return 0;
}

Add toy example showing use of the interface


#include "cvd/internal/load_and_save.h"
#include "cvd/internal/io/bmp.h"
#include <vector>
using namespace std;
using namespace CVD;

namespace CVD{
namespace BMP{

void writeBMPHeader(unsigned int width, unsigned int height, unsigned int channels, std::ostream& out);

class WritePimpl
{
	public:
		WritePimpl(ostream& o_, ImageRef sz, const string& t)
		:o(o_),size(sz)
		{
			int ch;

			if(t == "unsigned char")
				ch=1;
			else if(t == "CVD::Rgb<unsigned char>")
			{
				ch=3;
				int l=size.x*3;
				if(l%4 != 0)
					l = (l/4+1)*4;
				buf.resize(l);
			}
			else
				throw Exceptions::Image_IO::UnsupportedImageSubType("BMP", t);

			writeBMPHeader(size.x, size.y, ch, o);

			pad = ((ch*size.x) % 4) ? (4 - ((ch*size.x) % 4)) : 0;
		}

		void write_raw_pixel_line(const byte* r)
		{
			char zeros[]={0,0,0,0};
			o.write((const char*)r, size.x);
			o.write(zeros,pad);
		}

		void write_raw_pixel_line(const Rgb<byte>* r)
		{
			//Transform to BGR
			for(int i=0; i < size.x; i++)
			{
				buf[i*3+0] = r[i].blue;
				buf[i*3+1] = r[i].green;
				buf[i*3+2] = r[i].red;
			}
			o.write(&buf[0], buf.size());
		}

	private:
		ostream& o;
		ImageRef size;
		int pad;
		vector<char> buf;

};

Writer::Writer(std::ostream&o, ImageRef size, const std::string& type, const std::map<std::string, Parameter<> >&)
:t(new WritePimpl(o, size, type))
{}

Writer::~Writer()
{}

void Writer::write_raw_pixel_line(const byte* l)
{
	t->write_raw_pixel_line(l);
}
void Writer::write_raw_pixel_line(const Rgb<byte>* l)
{
	t->write_raw_pixel_line(l);
}

}
}

Add missing file from the previous commit.


// RUN: %clang_cc1 -x c++ -fmodules -fmodules-local-submodule-visibility -fmodules-cache-path=%t %s -verify
// RUN: %clang_cc1 -x c++ -fmodules -fmodules-cache-path=%t %s -verify

// expected-no-diagnostics

#pragma clang module build A
  module A { }
#pragma clang module contents
#pragma clang module begin A
struct A {
   virtual void Foo(double x) const;
};
#pragma clang module end
#pragma clang module endbuild

#pragma clang module build B
  module B { }
#pragma clang module contents
#pragma clang module begin B
#pragma clang module import A
struct B : A {
   using A::Foo;
   virtual void Foo(double x) const;
};
#pragma clang module end
#pragma clang module endbuild

#pragma clang module import B

int main() {
  B b;
  b.Foo(1.0);
}

[modules] Add test for using declaration in classes.

Summary:
This adds a test that checks if the using declaration in classes still works as intended with modules.

The motivation for this is that we tried to add a shortcut to `removeDecl` that would skip the removal of declarations from the lookup table if they are hidden. This optimization passed the clang test suite but actually broke the using declaration in combination with -fmodules-local-submodule-visibility. In this mode we hide all decls from other modules such as by chance the parent method, in which case don't remove the parent method from the lookup table and get ambiguous lookup errors. After this patch we now correctly see if this behavior is broken by a patch like this in the test suite.

Reviewers: v.g.vassilev

Reviewed By: v.g.vassilev

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D37180

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


#include "mbed.h"
#include "test_env.h"
#include "rtos.h"

#if defined(MBED_RTOS_SINGLE_THREAD)
  #error [NOT_SUPPORTED] test not supported
#endif

#define NUM_THREADS         5
#define THREAD_STACK_SIZE   256

DigitalOut led1(LED1);
volatile bool should_exit = false;
volatile bool allocation_failure = false;

void task_using_malloc(void)
{
    void* data;
    while (1) {
        // Repeatedly allocate and free memory
        data = malloc(100);
        if (data != NULL) {
            memset(data, 0, 100);
        } else {
            allocation_failure = true;
        }
        free(data);

        if (should_exit) {
            return;
        }
    }
}

int main()
{
    Thread *thread_list[NUM_THREADS];
    int test_time = 15;
    GREENTEA_SETUP(20, "default_auto");

    // Allocate threads for the test
    for (int i = 0; i < NUM_THREADS; i++) {
        thread_list[i] = new Thread(osPriorityNormal, THREAD_STACK_SIZE);
        if (NULL == thread_list[i]) {
            allocation_failure = true;
        }
        thread_list[i]->start(task_using_malloc);
    }

    // Give the test time to run
    while (test_time) {
        led1 = !led1;
        Thread::wait(1000);
        test_time--;
    }

    // Join and delete all threads
    should_exit = 1;
    for (int i = 0; i < NUM_THREADS; i++) {
        if (NULL == thread_list[i]) {
            continue;
        }
        thread_list[i]->join();
        delete thread_list[i];
    }

    GREENTEA_TESTSUITE_RESULT(!allocation_failure);
}

Add a test for thread-safe malloc

Add a test for thread-safe malloc

Add a test to repeatedly malloc and free from different threads to
test if these functions are thread safe.


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

using namespace Halide;

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

    //int W = 64*3, H = 64*3;
    const int W = 128, H = 48;

    Image<uint16_t> in(W, H, 2);
    for (int c = 0; c < 2; c++) {
        for (int y = 0; y < H; y++) {
            for (int x = 0; x < W; x++) {
                in(x, y, c) = rand() & 0xff;
            }
        }
    }

    Var x("x"), y("y");

    Func interleaved("interleaved");
    interleaved(x, y) = select(x%2 == 0, in(x, y, 0), in(x, y, 1));

    Target target = get_jit_target_from_environment();
    if (target.has_gpu_feature()) {
        interleaved.gpu_tile(x, y, 16, 16);
    } else if (target.features_any_of({Target::HVX_64, Target::HVX_128})) {
        interleaved.hexagon().vectorize(x, 32);
    } else {
        Var xo("xo"), yo("yo");
        interleaved.tile(x, y, xo, yo, x, y, 8, 8).vectorize(x);
    }

    Image<uint16_t> out = interleaved.realize(W, H, target);
    for (int y = 0; y < H; y++) {
        for (int x = 0; x < W; x++) {
            uint16_t correct = x%2 == 0 ? in(x, y, 0) : in(x, y, 1);
            if (out(x, y) != correct) {
                printf("out(%d, %d) = %d instead of %d\n", x, y, out(x, y), correct);
                return -1;
            }
        }
    }

    printf("Success!\n");

    return 0;

}

Add test failing on hexagon.

Add test failing on hexagon.


Add string generator for war

Add string generator for war


#include <array>

// C++17 only
// requires template argument deduction for class templates
namespace std
{
    template <typename... T>
    array(T... t) -> array<std::common_type_t<T...>, sizeof...(t)>;
}

int main()
{
    int a[] = {1,2,3};
    int b[] {4,5,6};

    // See: https://stackoverflow.com/q/7107606
    // not allowed as {1, 2, 3, 4} is purely a syntactic construct- it is not an expression and does not have a type,
    // therefore, auto cannot deduce its type from it.
    //auto c[] = {1,2,3};
    //auto d[] {4,5,6};

    // Alternative via std::array (see above), but not quite the same...
    // https://stackoverflow.com/q/6114067
    std::array e{1, 2, 3, 4};
}

Add explanation about auto and arrays.

Add explanation about auto and arrays.


#include <stddef.h>
// 199 Binary Tree Right Side View
/**
* Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
*
* For example:
* Given the following binary tree,
*    1            <---
*  /   \
* 2     3         <---
*  \     \
*   5     4       <---
* You should return [1, 3, 4].
*
* Tag:     Tree, Depth First Search, Breadth First Search
*
* Author:  Yanbin Lu
*/

#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:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> res;
        if(!root) return res;

		// using level order traverse
		// use a queue to store all nodes in the current level
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            int n = q.size();
            for(int i = 0; i < n;i++){
                TreeNode* node = q.front();
                q.pop();
                if(node->left) q.push(node->left);
                if(node->right) q.push(node->right);

				// push the last node (right most node) to res
                if(i == n-1) res.push_back(node->val);
            }
        }
        return res;
    }
};

int main()
{
	// creat a binary tree
	TreeNode* root = new TreeNode(0);
	root->left = new TreeNode(3);
	root->right = new TreeNode(2);
	root->left->right = new TreeNode(5);

	Solution* sol = new Solution();
	vector<int> res = sol->rightSideView(root);

	for(int i = 0; i < res.size(); i++)
		cout<<res[i]<<std::endl;

	char c;
	std::cin>>c;

	return 0;
}

Add 199 Binary Tree Right Side View

Add 199 Binary Tree Right Side View


// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm-only -fdump-vtable-layouts 2>&1 | FileCheck %s

/// Examples from the Itanium C++ ABI specification.
/// http://www.codesourcery.com/public/cxx-abi/

namespace Test1 {

// This is from http://www.codesourcery.com/public/cxx-abi/cxx-vtable-ex.html

// CHECK:      Vtable for 'Test1::A' (5 entries).
// CHECK-NEXT:    0 | offset_to_top (0)
// CHECK-NEXT:    1 | Test1::A RTTI
// CHECK-NEXT:        -- (Test1::A, 0) vtable address --
// CHECK-NEXT:    2 | void Test1::A::f()
// CHECK-NEXT:    3 | void Test1::A::g()
// CHECK-NEXT:    4 | void Test1::A::h()
struct A {
  virtual void f ();
  virtual void g ();
  virtual void h ();
  int ia;
};
void A::f() {}

}

Add tests from the Itanium C++ ABI spec.

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


#include "Halide.h"

using namespace Halide;

int main() {

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

    Func f;
    Var x, y, c;
    RDom r(0, 10);
    f(x, y, c) = sum(r);
    f.bound(c, 0, 3).glsl(x, y, c);

    f.realize(100, 100, 3);

    printf("Success!\n");

    return 0;
}

Add failing opengl test using an inline reduction

Former-commit-id: 3bfba4f85346721aa33cea58841060f01b759019


/*
Example of iterating over cell's variables using boost::mpl.

Copyright 2015 Ilja Honkonen
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this
  list of conditions and the following disclaimer in the documentation and/or
  other materials provided with the distribution.

* Neither the name of copyright holders nor the names of their contributors
  may be used to endorse or promote products derived from this software
  without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "iostream"

#include "boost/mpl/for_each.hpp"
#include "boost/mpl/vector.hpp"
#include "gensimcell.hpp"

using namespace std;

struct variable1 {
	using data_type = int;
};

struct variable2 {
	using data_type = float;
};

struct variable3 {
	using data_type = char;
};

int main(int, char**)
{
	gensimcell::Cell<
		gensimcell::Never_Transfer,
		variable1,
		variable2,
		variable3
	> cell;
	cell[variable1()] = 3;
	cell[variable2()] = 1.5;
	cell[variable3()] = '3';

	// lambda with auto argument requires C++14,
	// see documentation of boost::mpl::for_each
	// on how to support older compilers
	boost::mpl::for_each<
		boost::mpl::vector<variable1, variable3>
	>(
		[&cell](auto variable){
			cout << cell[variable] << " ";
		}
	);
	cout << endl;
	// prints 3 3

	return 0;
}

Add an example of iteration over (some) variables in a cell with boost::mpl.


//===- llvm/unittest/ADT/SmallStringTest.cpp ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// SmallString unit tests.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "llvm/ADT/SmallString.h"
#include <stdarg.h>
#include <climits>
#include <cstring>

using namespace llvm;

namespace {

// Test fixture class
class SmallStringTest : public testing::Test {
protected:
  typedef SmallString<40> StringType;

  StringType theString;

  void assertEmpty(StringType & v) {
    // Size tests
    EXPECT_EQ(0u, v.size());
    EXPECT_TRUE(v.empty());
    // Iterator tests
    EXPECT_TRUE(v.begin() == v.end());
  }
};

// New string test.
TEST_F(SmallStringTest, EmptyStringTest) {
  SCOPED_TRACE("EmptyStringTest");
  assertEmpty(theString);
  EXPECT_TRUE(theString.rbegin() == theString.rend());
}

TEST_F(SmallStringTest, AppendUINT64_MAX) {
  SCOPED_TRACE("AppendUINT64_MAX");
  theString.clear();
  assertEmpty(theString);
  theString.append_uint(UINT64_MAX);
  EXPECT_TRUE(0 == strcmp(theString.c_str(),"18446744073709551615"));
}

TEST_F(SmallStringTest, AppendINT64_MIN) {
  SCOPED_TRACE("AppendINT64_MIN");
  theString.clear();
  assertEmpty(theString);
  theString.append_sint(INT64_MIN);
  EXPECT_TRUE(0 == strcmp(theString.c_str(),"-9223372036854775808"));
}

}

Add SmallString unit test.
 - Patch by Ryan Flynn!

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


#include "catch.hpp"
#include "tangram.h"
#include "style/textStyle.h"

#include "alfons/textBatch.h"
#include "alfons/textShaper.h"
#include "alfons/atlas.h"
#include "alfons/alfons.h"
#include "alfons/fontManager.h"

#include "text/lineWrapper.h"

#include <memory>

namespace Tangram {

struct ScratchBuffer : public alfons::MeshCallback {
    void drawGlyph(const alfons::Quad& q, const alfons::AtlasGlyph& atlasGlyph) override {}
    void drawGlyph(const alfons::Rect& q, const alfons::AtlasGlyph& atlasGlyph) override {}
};

struct AtlasCallback : public alfons::TextureCallback {
    void addTexture(alfons::AtlasID id, uint16_t textureWidth, uint16_t textureHeight) override {}
    void addGlyph(alfons::AtlasID id, uint16_t gx, uint16_t gy, uint16_t gw, uint16_t gh,
            const unsigned char* src, uint16_t padding) override {}
};

TEST_CASE("Ensure empty line is given when giving empty shape to alfons", "[Core][Alfons]") {
    AtlasCallback atlasCb;
    ScratchBuffer buffer;
    alfons::LineMetrics metrics;
    alfons::TextShaper shaper;
    alfons::GlyphAtlas atlas(atlasCb);
    alfons::TextBatch batch(atlas, buffer);
    alfons::FontManager fontManager;

    auto font = fontManager.addFont("default", alf::InputSource("fonts/NotoSans-Regular.ttf"), 24);

    auto line = shaper.shape(font, "");
    metrics = drawWithLineWrapping(line, batch, 15, TextLabelProperty::Align::center, 1.0);

    REQUIRE(line.shapes().size() == 0);
}

}

Add unit tests for alfons

wip: Add unit tests for alfons


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

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

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

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

        ews::distinguished_folder_id inbox = ews::standard_folder::inbox;
        ews::distinguished_folder_id junk = ews::standard_folder::junk_email;

        auto item_ids = service.find_item(inbox);
        if (!item_ids.empty())
        {
            // Move the first item to the junk box
            auto new_id = service.move_item(item_ids.front(), junk);

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

    ews::tear_down();
    return res;
}

Add example for MoveItem operation

Add example for MoveItem operation


#include <boost/test/unit_test.hpp>

#include "../unittest_config.h"

#include "test_element.h"
#include "clotho/mutation/element_generator.hpp"

typedef clotho::powersets::element_key_of< test_element >::key_type          key_type;

struct test_key_generator {
    key_type operator()( key_type & k ) { return k; }
};

typedef clotho::mutations::element_generator< test_element, test_key_generator >  elem_generator;

BOOST_AUTO_TEST_SUITE( test_element_generation )

/**
 *  Test that the expected width per block is initialized correctly
 *
 */
BOOST_AUTO_TEST_CASE( key_generator_test ) {
    test_key_generator tkg;
    elem_generator gen( tkg );

    key_type k = 0.25;

    test_element te = gen(k);

    BOOST_REQUIRE_MESSAGE( te.k == k, "Unexpected key: " << te.k << "(" << k << ")" );
}

BOOST_AUTO_TEST_SUITE_END()

Test whether element generator template works


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

#include <base/config.h>
#include <cmath>
#include <limits>

DEAL_II_NAMESPACE_OPEN

namespace deal_II_numbers
{
  bool is_finite (const double x)
  {
#ifdef DEAL_II_HAVE_ISFINITE
    return std::isfinite (x);
#else
				     // check against infinities. not
				     // that if x is a NaN, then both
				     // comparisons will be false
    return ((x >= -std::numeric_limits<double>::max())
	    &&
DEAL_II_NAMESPACE_CLOSE
	    (x <= std::numeric_limits<double>::max()));
#endif
  }
}

DEAL_II_NAMESPACE_CLOSE

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

#include <base/config.h>
#include <cmath>
#include <limits>

DEAL_II_NAMESPACE_OPEN

namespace deal_II_numbers
{
  bool is_finite (const double x)
  {
#ifdef DEAL_II_HAVE_ISFINITE
    return std::isfinite (x);
#else
				     // check against infinities. not
				     // that if x is a NaN, then both
				     // comparisons will be false
    return ((x >= -std::numeric_limits<double>::max())
	    &&
	    (x <= std::numeric_limits<double>::max()));
#endif
  }
}

DEAL_II_NAMESPACE_CLOSE

Remove a DEAL_II_NAMESPACE_CLOSE which has been added accidentally.

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


// Copyright (c) 2011 Timur Iskhodzhanov and MIPT students. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "gtest/gtest.h"

#include "base/common.h"

TEST(CommonTest, DebugOrRelease) {
#ifdef NDEBUG
  printf("NDEBUG defined, this is a Release build\n");
#else
  printf("NDEBUG is not defined, this is a Debug build\n");
#endif
}

Add a test that prints out the current build type


// RUN: %clang_cc1 -fexceptions -verify %s
struct A { };
struct B { };

struct X0 {
  virtual ~X0() throw(A); // expected-note{{overridden virtual function is here}}
};
struct X1 {
  virtual ~X1() throw(B); // expected-note{{overridden virtual function is here}}
};
struct X2 : public X0, public X1 { }; // expected-error 2{{exception specification of overriding function is more lax than base version}}

Add Sema test case for exception-specifiers implicitly added to destructors.

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


// The run lines are below, because this test is line- and
// column-number sensitive.

template<typename T>
struct X {
  X(T);
};

struct Virt { };
struct Y : virtual Virt { };

struct Z : public X<int>, public Y {
  Z();

  int a, b, c;
};

Z::Z() : ::X<int>(0), Virt(), a() { }

// RUN: c-index-test -code-completion-at=%s:18:10 %s | FileCheck -check-prefix=CHECK-CC1 %s
// CHECK-CC1: NotImplemented:{TypedText a}{LeftParen (}{Placeholder args}{RightParen )} (4)
// CHECK-CC1: NotImplemented:{TypedText b}{LeftParen (}{Placeholder args}{RightParen )} (5)
// CHECK-CC1: NotImplemented:{TypedText c}{LeftParen (}{Placeholder args}{RightParen )} (6)
// CHECK-CC1: NotImplemented:{TypedText Virt}{LeftParen (}{Placeholder args}{RightParen )} (3)
// CHECK-CC1: NotImplemented:{TypedText X<int>}{LeftParen (}{Placeholder args}{RightParen )} (1)
// CHECK-CC1: NotImplemented:{TypedText Y}{LeftParen (}{Placeholder args}{RightParen )} (2)

// RUN: c-index-test -code-completion-at=%s:18:23 %s | FileCheck -check-prefix=CHECK-CC2 %s
// CHECK-CC2: NotImplemented:{TypedText a}{LeftParen (}{Placeholder args}{RightParen )} (3)
// CHECK-CC2: NotImplemented:{TypedText b}{LeftParen (}{Placeholder args}{RightParen )} (4)
// CHECK-CC2: NotImplemented:{TypedText c}{LeftParen (}{Placeholder args}{RightParen )} (5)
// CHECK-CC2: NotImplemented:{TypedText Virt}{LeftParen (}{Placeholder args}{RightParen )} (2)
// CHECK-CC2: NotImplemented:{TypedText Y}{LeftParen (}{Placeholder args}{RightParen )} (1)

Add missing test case for constructor-initializer code completions

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


#include <SFML\Graphics.hpp>
#include "Vector2d.h"

int main()
{
	sf::CircleShape object(15, 3);

	sf::Vector2f vector2f; //original compatible vector2f object from SFML

	Vector2d vector2d; //vector from Vector2d class, if you want to compute vector first you must create vector object, becouse it have float type components  x & y

	vector2d = Vector2d::pointToPointVector(-13, 14, 21, 24); //Compute point to point vector

	vector2f.x = vector2d.x; //We can initiate vector SFML vector class vector2d, becouse the components have the same type - Float
	vector2f.y = vector2d.y; //Vector2d use float type as x & y components, but if You like You can convert to other primitive type using reinterpreter_cast<>

	object.move(vector2f); //Now you can translate object's with sfml compatible vector
	object.setRotation(Vector2d::rotationInDegreesFromVector(-13, 14, 21, 24)); //if you want the moved object was rotated in the direction of movement

	return EXIT_SUCCESS;
}

Add a Example Integrations with SFML graphics library


#include "fish_detector/common/species_dialog.h"
#include "ui_species_dialog.h"

namespace fish_detector {

SpeciesDialog::SpeciesDialog(QWidget *parent)
  : QDialog(parent)
  , ui_(new Ui::SpeciesDialog) {
  ui_->setupUi(this);
}

void SpeciesDialog::on_ok_clicked() {
}

void SpeciesDialog::on_cancel_clicked() {
}

void SpeciesDialog::on_removeSubspecies_clicked() {
}

void SpeciesDialog::on_addSubspecies_clicked() {
}

Species SpeciesDialog::getSpecies() {
  Species species;
  return species;
}

#include "../../include/fish_detector/common/moc_species_dialog.cpp"

} // namespace fish_detector

Add framework for source file

Add framework for source file


// Attempting to replicate the CFG from Figure 11.25 of Aho and Ullman 1972.
#include <iostream>

int main() {
  unsigned n;
  std::cin >> n;

  int *A = new int[n];

  int i = -1;
  int sum = 0;
_2:
  ++i;
_3:
  if (A[i] % 2 == 0) {
    goto _4;
  }
_7:
  sum += A[i];
  goto _2;
_4:
  if (i < n && A[i] % 3 == 0) {
    ++i;
    goto _4;
  }
_5:
  if (i < n && A[i] % 5 != 0) {
    goto _2;
  }
_6:
  sum += A[i++];
  if (i < n) {
    goto _3;
  }
  std::cout << sum << '\n';

  delete[] A;
}

Add Example 11.34 from Aho'72

Add Example 11.34 from Aho'72


// RUN: %clang_cc1 -verify -std=c++2a %s
// expected-no-diagnostics

const unsigned halt = (unsigned)-1;

enum Dir { L, R };
struct Action {
  bool tape;
  Dir dir;
  unsigned next;
};
using State = Action[2];

// An infinite tape!
struct Tape {
  constexpr Tape() = default;
  constexpr ~Tape() {
    if (l) { l->r = nullptr; delete l; }
    if (r) { r->l = nullptr; delete r; }
  }
  constexpr Tape *left() {
    if (!l) { l = new Tape; l->r = this; }
    return l;
  }
  constexpr Tape *right() {
    if (!r) { r = new Tape; r->l = this; }
    return r;
  }
  Tape *l = nullptr;
  bool val = false;
  Tape *r = nullptr;
};

// Run turing machine 'tm' on tape 'tape' from state 'state'. Return number of
// steps taken until halt.
constexpr unsigned run(const State *tm) {
  Tape *tape = new Tape;
  unsigned state = 0;
  unsigned steps = 0;

  for (state = 0; state != halt; ++steps) {
    auto [val, dir, next_state] = tm[state][tape->val];
    tape->val = val;
    tape = (dir == L ? tape->left() : tape->right());
    state = next_state;
  }

  delete tape;
  return steps;
}

// 3-state busy beaver. S(bb3) = 21.
constexpr State bb3[] = {
  { { true, R, 1 }, { true, R, halt } },
  { { true, L, 1 }, { false, R, 2 } },
  { { true, L, 2 }, { true, L, 0 } }
};
static_assert(run(bb3) == 21, "");

// 4-state busy beaver. S(bb4) = 107.
constexpr State bb4[] = {
  { { true, R, 1 }, { true, L, 1 } },
  { { true, L, 0 }, { false, L, 2 } },
  { { true, R, halt }, { true, L, 3 } },
  { { true, R, 3 }, { false, R, 0 } } };
static_assert(run(bb4) == 107, "");

[c++20] Add a C++20 version of the existing turing machine test.

Unlike the C++11 version, this one uese mutable state and dynamic
allocation instead of a carefully balanced and ever-accumulating pile of
temporaries.

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


// 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 "ui/message_center/message_center.h"

#include "base/observer_list.h"
#include "ui/message_center/message_center_impl.h"

namespace message_center {

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

namespace {
static MessageCenter* g_message_center;
}

// static
void MessageCenter::Initialize() {
  DCHECK(g_message_center == NULL);
  g_message_center = new MessageCenterImpl();
}

// static
MessageCenter* MessageCenter::Get() {
  DCHECK(g_message_center);
  return g_message_center;
}

// static
void MessageCenter::Shutdown() {
  DCHECK(g_message_center);
  delete g_message_center;
  g_message_center = NULL;
}

MessageCenter::MessageCenter() {
}

MessageCenter::~MessageCenter() {
}

}  // namespace message_center

// 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 "ui/message_center/message_center.h"

#include "base/observer_list.h"
#include "ui/message_center/message_center_impl.h"

namespace message_center {

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

namespace {
static MessageCenter* g_message_center = NULL;
}

// static
void MessageCenter::Initialize() {
  DCHECK(g_message_center == NULL);
  g_message_center = new MessageCenterImpl();
}

// static
MessageCenter* MessageCenter::Get() {
  DCHECK(g_message_center);
  return g_message_center;
}

// static
void MessageCenter::Shutdown() {
  DCHECK(g_message_center);
  delete g_message_center;
  g_message_center = NULL;
}

MessageCenter::MessageCenter() {
}

MessageCenter::~MessageCenter() {
}

}  // namespace message_center

Initialize the global message center instance to NULL

BUG=Uninitialized global message center instance leads to trouble when
modifying gyps.

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

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


// Copyright 2014 Irfan Hamid
//
// 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 "Enable.hpp"
#include <immintrin.h>
#include <cmath>
#include "Avx2Internals.hpp"

namespace khyber
{
  namespace avx2
  {
    void InternalAdd(size_t size,
                     sp_t* sum,
                     sp_t* augend,
                     const sp_t* addend)
    {
      __m256* pSum = (__m256*)sum;
      __m256* pAugend = (__m256*)augend;
      __m256* pAddend = (__m256*)addend;

      size_t i;
      for ( i = 0; i < (size >> 3); ++i ) {
        pSum[i] = _mm256_add_ps(pAugend[i], pAddend[i]);
      }

      i <<= 3;
      for ( ; i < size; ++i ) {
        sum[i] = augend[i] + addend[i];
      }
    }

    void InternalNegate(size_t size,
                        sp_t *dst,
                        sp_t *src)
    {
      __m256i* pDst = (__m256i*)dst;
      __m256i* pSrc = (__m256i*)src;
      __m256i mask = _mm256_set_epi32(0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000);

      size_t i;
      for ( i = 0; i < (size >> 3); ++i ) {
        pDst[i] = _mm256_xor_si256(pSrc[i], mask);
      }

      i <<= 3;
      for ( ; i < size; ++i ) {
        dst[i] = -src[i];
      }
    }
  }
}

Check in avx2 internals in new directory


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

// UNSUPPORTED: libcxxabi-no-exceptions

// This test checks that the compiler does not make incorrect assumptions
// about the alignment of the exception (only in that specific case, of
// course).
//
// There was a bug where Clang would emit a call to memset assuming a 16-byte
// aligned exception even when back-deploying to older Darwin systems where
// exceptions are 8-byte aligned, which caused a segfault on those systems.

struct exception {
    exception() : x(0) { }
    virtual ~exception() { }
    int x;
};

struct foo : exception { };

int main() {
    try {
      throw foo();
    } catch (...) {

    }
    return 0;
}

[libcxxabi] Add a test for invalid assumptions on the alignment of exceptions

rdar://problem/49864414

git-svn-id: 6a9f6578bdee8d959f0ed58970538b4ab6004734@361039 91177308-0d34-0410-b5e6-96231b3b80d8


/*************************************************************************
	> File Name: PA.cpp
	> Author: Gavin Lee
	> School: National Chiao Tung University
	> Team: NCTU_Ragnorok
	> Mail: sz110010@gmail.com
	> Created Time: Mon 04 Apr 2016 10:33:00 PM CST
 ************************************************************************/

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

bool prefix(string,string);

int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        int n;
        scanf("%d", &n);
        string str[10000];
        for(int i = 0; i < n; ++i)
            cin >> str[i];
        sort(str, str+n);
        bool che = true;
        for(int i = 0; i < n-1; ++i)
        {
            if(prefix(str[i],str[i+1]))
            {
                che = false;
                break;
            }
        }
        if(che) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
    return 0;
}

bool prefix(string a, string b)
{
    if(a.length() > b.length())
        return false;
    for(int i = 0; i < a.length(); ++i)
    {
        if(a[i] != b[i])
            return false;
    }
    return true;
}

Add PCCA summer camp practice

Add PCCA summer camp practice


#include <iostream>

using std::cout;
using std::boolalpha;

bool is_factor(int factor, int number) {
  return number % factor == 0;
}

bool is_prime(int number) {
  if (number == 2) {
    return true;
  }

  for (int i = 2; i < number; ++i) {
    if (is_factor(i, number)) {
      return false;
    }
  }

  return true;
}

bool is_prime_factor(int factor, int number) {
  return is_factor(factor, number) && is_prime(factor);
}

bool has_prime_factors_of(int number1, int number2) {
  for (int i = 2; i <= number2; ++i) {
    if (is_prime_factor(i, number2) && !is_factor(i, number1)) {
      return false;
    }
  }

  return true;
}

bool has_same_prime_factors(int number1, int number2) {
  return has_prime_factors_of(number1, number2) &&
         has_prime_factors_of(number2, number1);
}

int main() {
  cout << boolalpha << has_same_prime_factors(10, 20) << '\n';
  cout << boolalpha << has_same_prime_factors(10, 60) << '\n';

  return 0;
}

Add solution to same prime factors problem


/**
 * Remove Duplicates from Sorted List II
 *
 * cpselvis(cpselvis@gmail.com)
 * Oct 9th, 2016
 */
#include<iostream>

using namespace std;

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

class Solution {
public:
  ListNode* deleteDuplicates(ListNode* head) {
    if (head == NULL || head -> next == NULL) return head;

    ListNode *dummy = new ListNode(-1);
    dummy -> next = head;
    head = dummy;

    while (head -> next != NULL && head -> next -> next != NULL)
    {
      if (head -> next -> val == head -> next -> next -> val)
      {
	int val = head -> next -> val;
	while (head -> next != NULL && head -> next -> val == val)
	{
	  head -> next = head -> next -> next;
	}
      }
      else
      {
	head = head -> next;
      }
    }
    return dummy -> next;
  }
};

int main(int argc, char **argv)
{
  ListNode *head = new ListNode(1);
  head -> next = new ListNode(2);
  head -> next -> next = new ListNode(3);
  head -> next -> next -> next = new ListNode(3);
  head -> next -> next -> next -> next = new ListNode(4);
  head -> next -> next -> next -> next -> next = new ListNode(4);
  head -> next -> next -> next -> next -> next -> next = new ListNode(5);

  Solution s;
  ListNode *node = s.deleteDuplicates(head);
  while(node != NULL)
  {
    cout << node -> val << endl;
    node = node -> next;
  }
}

Remove Duplicates from Sorted List II.

Remove Duplicates from Sorted List II.


// RUN: %clangxx_asan %stdcxx11 -O1 -fsanitize-address-use-after-scope %s -o %t && \
// RUN:     not %run %t 2>&1 | FileCheck %s

struct IntHolder {
  const IntHolder& Self() const {
    return *this;
  }
  int val = 3;
};

const IntHolder *saved;

int main(int argc, char *argv[]) {
  saved = &IntHolder().Self();
  int x = saved->val;  // BOOM
  // CHECK: ERROR: AddressSanitizer: stack-use-after-scope
  // CHECK:  #0 0x{{.*}} in main {{.*}}use-after-scope-temp2.cc:[[@LINE-2]]
  return x;
}

[asan] Add test which detects bugs undetectable before r288563

Reviewers: kcc, eugenis

Subscribers: llvm-commits, kubabrecka

Differential Revision: https://reviews.llvm.org/D27583

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


class Solution {
public:
    bool checkOnesSegment(string s) {
        bool flag = false;
        bool cont_flag = false;
        for (const auto &c : s) {
            if (c == '1') {
                if (flag && !cont_flag) {
                    return false;
                }
                flag = true;
                cont_flag = true;
            } else {
                cont_flag = false;
            }
        }
        return true;
    }
};

Check if Binary String Has at Most One Segment of Ones


#include "utils/GLFWApp.h"

#include <string>
#include "utils/Shader.h"

class UniformOrder: public GLFWApp {
    public:
        void Init(GLFWwindow*) override {

            const std::string vs =
                R"(in vec4 a_position;
                void main(){
                    gl_Position = a_position;
                })";

            const std::string fs =
                R"(#version 100
                   #extension GL_EXT_blend_func_extended : require
                   precision highp float;
                   uniform vec4 src;
                   uniform vec4 src1;
                   void main() {
                       gl_FragData[0] = src;
                       gl_SecondaryFragDataEXT[0] = src1;
                   })";

            mProgram = CompileProgram(vs, fs);
            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        }

        void Frame() override {
            glViewport(0, 0, 640, 480);
            glClearColor(0.5, 0.5, 0.5, 0.5);
            glClear(GL_COLOR_BUFFER_BIT);

            glEnable(GL_BLEND);
            glBlendEquation(GL_FUNC_ADD);
            glBlendFuncSeparate(GL_SRC1_COLOR, GL_SRC_ALPHA, GL_ONE_MINUS_SRC1_COLOR, GL_ONE_MINUS_SRC1_ALPHA);

            glUseProgram(mProgram);

            GLint location = glGetUniformLocation(mProgram, "src");
            glUniform4f(location, 1.0, 1.0, 1.0, 1.0);
            GLint location2 = glGetUniformLocation(mProgram, "src1");
            glUniform4f(location2, 0.3, 0.6, 0.9, 0.7);

            GLfloat vertices[] = {
                0.0f,  0.5f, 0.0f,
                -0.5f, -0.5f, 0.0f,
                0.5f, -0.5f, 0.0f,
            };

            glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vertices);
            glEnableVertexAttribArray(0);

            glDrawArrays(GL_TRIANGLES, 0, 3);
        }

        void Destroy() override {

        }

        GLuint mProgram;
};

int main(int argc, const char** argv) {
    return GLFWApp::Run(new UniformOrder);
}

Add secondary frag data test

Add secondary frag data test


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

using namespace std;
typedef long long ll;

bool is_prime(ll n){
    if (n<=1) return false;
    if (n==2) return true;
    if (n%2==0) return false;
    ll root = sqrt(n);
    for (int i=3; i<= root; i+=2){
        if(n%i == 0 )
            return false;
    }
    return true;

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

}

Add folder for storage the problem with primes.


///////////////////////////////////////
/// file: linklist_test.cpp
///////////////////////////////////////

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

///
/// 打印链表
///
template<typename T>
void PrintList(LinkList<T> L)
{
    cout << "(";
    auto p = L->next;
    while(p) {
        cout << " " << p->data;
        p = p->next;
    }
    cout << " )" << endl;
}

bool eq(int a, int b)
{
    return a==b;
}

void print(int x)
{
    cout << " " << x;
}

int main()
{
    // 建立链表
    LinkList<int> L;
    // 初始化
    InitList(L);
    PrintList(L);

    // 插入元素
    ListInsert(L,1,3);
    ListInsert(L,2,1);
    ListInsert(L,3,4);
    ListInsert(L,4,1);
    ListInsert(L,5,5);
    ListInsert(L,6,9);
    PrintList(L);

    // 元素定位
    cout << "LocateElem 9 = ";
    cout << "L(@" << LocateElem(L,9,eq) << ")" << endl;

    // 遍历线性表
    cout << "ListTraverse: ";
    ListTraverse(L,print);
    cout << endl;

    // 销毁链表
    DestroyList(L);

    return 0;
}

Add test for locate and traverse of linklist


#include "impl_request_posture.hpp"

static RequsetPosture* pattern = new PatternRequestPosture;
static RequestPosture* torajectoy = new TorajectoryRequestPosture;

std::map<std::string, RequestPosture*> RequestPostureFactory::reqs = {{"pattern", pattern},
                                                                      {"torajectory", torajectory}};

const RequestPosture* RequestPostureFactory::get(std::string& name) {
  std::map<std::string, RequestPosture*>::iterator found_it = reqs.find(name);
  if (found_it != reqs.end()) return NULL;
  return found_it;
}

Add request posture cpp, and figure of req factory


#include "../../source/thewizardplusplus/wizard_parser/lexer/tokenize.hpp"
#include "../../source/thewizardplusplus/wizard_parser/lexer/token.hpp"
#include "../vendor/catch/catch.hpp"
#include <regex>

TEST_CASE("lexer::tokenize() function with exceptions", "[lexer]") {
	using namespace thewizardplusplus::wizard_parser;

	SECTION("without exceptions") {
		const auto [tokens, rest_offset] = lexer::tokenize(
			{
				{std::regex{"[[:alpha:]]+"}, "alpha"},
				{std::regex{"[[:digit:]]+"}, "digit"},
				{std::regex{"[[:space:]]+"}, "space"}
			},
			{},
			"test 23"
		);
		CHECK(tokens == lexer::token_group{
			{"alpha", "test", {}},
			{"space", " ", 4},
			{"digit", "23", 5}
		});
		CHECK(rest_offset == 7);
	}

	SECTION("with exceptions") {
		const auto [tokens, rest_offset] = lexer::tokenize(
			{
				{std::regex{"[[:alpha:]]+"}, "alpha"},
				{std::regex{"[[:digit:]]+"}, "digit"},
				{std::regex{"[[:space:]]+"}, "space"}
			},
			{"space"},
			"test 23"
		);
		CHECK(tokens == lexer::token_group{
			{"alpha", "test", {}},
			{"digit", "23", 5}
		});
		CHECK(rest_offset == 7);
	}
}

Add the `lexer::tokenize()` function with exceptions: cover it with tests


// 96 Unique Binary Search Trees
/**
* Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
*
* For example,
* Given n = 3, there are a total of 5 unique BST's.
*
*    1         3     3      2      1
*     \       /     /      / \      \
*      3     2     1      1   3      2
*     /     /       \                 \
*    2     1         2                 3
*
* Tag:    Tree, Dynamic Programming
*
* 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;

class Solution {
public:
    int numTrees(int n) {
        if(n<=1) return 1;
        vector<int> dp(n+1,0);
        dp[0] = 1;
        dp[1] = 1;

        for(int i = 2; i<=n;i++)
            // set i as the root compute the number of trees on left side and right side
            for(int j = 1; j<=i;j++)
                dp[i] += dp[j-1]*dp[i-j];
        return dp[n];
    }
};

int main()
{

	Solution* sol = new Solution();

    cout << sol->numTrees(5) << endl;
    cout << sol->numTrees(1) << endl;
    cout << sol->numTrees(500) << endl;

    char c;
    std::cin>>c;

    return 0;
}

Add 96 Unique Binary Search Trees

Add 96 Unique Binary Search Trees


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

// expected-no-diagnostics
constexpr void copy(const char *from, unsigned long count, char *to) {
        unsigned long n = (count + 7) / 8;
        switch(count % 8) {
        case 0: do {    *to++ = *from++;
        case 7:         *to++ = *from++;
        case 6:         *to++ = *from++;
        case 5:         *to++ = *from++;
        case 4:         *to++ = *from++;
        case 3:         *to++ = *from++;
        case 2:         *to++ = *from++;
        case 1:         *to++ = *from++;
                } while(--n > 0);
        }
}

struct S {
  char stuff[14];
  constexpr S() : stuff{} {
    copy("Hello, world!", 14, stuff);
  }
};

constexpr bool streq(const char *a, const char *b) {
  while (*a && *a == *b) ++a, ++b;
  return *a == *b;
}

static_assert(streq(S().stuff, "Hello, world!"), "should be same");
static_assert(!streq(S().stuff, "Something else"), "should be different");

Add another C++14 constexpr test case.

Add another C++14 constexpr test case.

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


/*
 * Copyright (C) 2015 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 <stdlib.h>
#include <stdint.h>

#include "test_generate_terms.h"

#include <check.h>

START_TEST(numeric_test)
{
	ck_assert_int_eq(numeric_test(), 0);
}
END_TEST

START_TEST(date_test)
{
	ck_assert_int_eq(date_test(), 0);
}
END_TEST

START_TEST(geo_test)
{
	ck_assert_int_eq(geo_test(), 0);
}
END_TEST

Suite* Generate_Terms(void)
{
	Suite *s = suite_create("Testing Generation of terms");
	TCase *n = tcase_create("Generation numerical terms");
	TCase *d = tcase_create("Generation of terms for dates");
	TCase *g = tcase_create("Generation of terms for geospatials");

	tcase_add_test(n, numeric_test);
	tcase_add_test(d, date_test);
	tcase_add_test(g, geo_test);
	suite_add_tcase(s, n);
	suite_add_tcase(s, d);
	suite_add_tcase(s, g);
	return s;
}

int main(void)
{
	Suite *st = Generate_Terms();
	SRunner *sr = srunner_create(st);

	srunner_run_all(sr, CK_NORMAL);
	int number_failed = srunner_ntests_failed(sr);
	srunner_free(sr);

	return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}

Test for generate terms was added

Test for generate terms was added


// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#include "mfem.hpp"
#include "catch.hpp"

using namespace mfem;

class FakeSolver : public Solver
{
private:
   Operator& op;

public:
   FakeSolver(Operator& op_) : Solver(op_.Height()), op(op_) { }
   void SetOperator(const Operator &op) { }
   void Mult(const Vector& x, Vector& y) const { op.Mult(x, y); }
};

TEST_CASE("CGSolver", "[Indefinite]")
{
   // Define indefinite SparseMatrix
   SparseMatrix indefinite(2, 2);
   indefinite.Add(0, 1, 1.0);
   indefinite.Add(1, 0, 1.0);
   indefinite.Finalize();

   Vector v(2);
   v(0) = 1.0;
   v(1) = -1.0;
   Vector x(2);
   x = 0.0;

   // check indefinite operator
   CGSolver cg;
   cg.SetOperator(indefinite);
   cg.SetPrintLevel(1);
   cg.Mult(v, x);
   REQUIRE(!cg.GetConverged());

   // check indefinite preconditioner
   IdentityOperator identity(2);
   FakeSolver indefprec(indefinite);
   CGSolver cg2;
   cg2.SetOperator(identity);
   cg2.SetPreconditioner(indefprec);
   cg2.SetPrintLevel(1);
   x = 0.0;
   cg2.Mult(v, x);
   REQUIRE(!cg2.GetConverged());
}

Add (failing) unit test to demonstrate CGSolver bug with indefinite preconditioner.


#include <QApplication>
#include <QMainWindow>
#include <QToolBar>
#include <QDir>
#include <QDebug>
#include "../core/folder.h"
#include "../foldermodel.h"
#include "../folderview.h"
#include "../cachedfoldermodel.h"
#include "../proxyfoldermodel.h"
#include "../pathedit.h"

int main(int argc, char** argv) {
    QApplication app(argc, argv);
    QMainWindow win;

    Fm::FolderView folder_view;
    win.setCentralWidget(&folder_view);

    auto home = Fm2::FilePath::fromLocalPath(QDir().homePath().toLocal8Bit().constData());
    Fm::CachedFolderModel* model = Fm::CachedFolderModel::modelFromPath(home);
    auto proxy_model = new Fm::ProxyFolderModel();
    proxy_model->sort(Fm::FolderModel::ColumnFileName, Qt::AscendingOrder);
    proxy_model->setSourceModel(model);
    folder_view.setModel(proxy_model);

    QToolBar toolbar;
    win.addToolBar(Qt::TopToolBarArea, &toolbar);
    Fm::PathEdit edit;
    edit.setText(home.toString().get());
    toolbar.addWidget(&edit);
    auto action = new QAction("Go");
    toolbar.addAction(action);
    QObject::connect(action, &QAction::triggered, [&]() {
        auto path = Fm2::FilePath(edit.text().toLocal8Bit().constData());
        auto new_model = Fm::CachedFolderModel::modelFromPath(path);
        proxy_model->setSourceModel(new_model);
    });

    win.show();
    return app.exec();
}

Add the missing test case for folder view.


#include <gtest/gtest.h>
#include <array>
#include <memory>
#include "Map.hpp"

struct MapTest : public :: testing :: Test{
std::shared_ptr<Map> setmap = std::make_shared<Map>();
};

TEST_F(MapTest, LoadMapSwitchTest) {
    EXPECT_EQ(10,(setmap->getGridmap(1)).size());
    EXPECT_FALSE((setmap->getGridmap(1)).empty());
    EXPECT_FALSE((setmap->getGridmap(2)).empty());
    EXPECT_FALSE((setmap->getGridmap(3)).empty());
    EXPECT_FALSE((setmap->getGridmap(4)).empty());
}

TEST_F(MapTest, SetstartTest) {
    EXPECT_EQ(std::make_pair(2, 3),setmap->SetStart(2,3));
}

TEST_F(MapTest, SetgoalTest) {
    EXPECT_EQ(std::make_pair(4, 6),setmap->SetGoal(4,6));
}

Add unit test for Map class -User Story 8


// RUN: %clangxx_asan -O1 -mllvm -asan-use-after-scope=1 %s -o %t && \
// RUN:     not %run %t 2>&1 | FileCheck %s
// XFAIL: *

// FIXME: This works only for arraysize <= 8.

char *p = 0;

int main() {
  {
    char x[1024] = {};
    p = x;
  }
  return *p;  // BOOM
}

Add another failing use-after-scope test

Summary:
  Use after scope is not detected if array larger then 8 bytes.

Subscribers: kubabrecka

Differential Revision: http://reviews.llvm.org/D19572

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


--- src/rpcclient.cpp.orig	2017-05-18 01:39:08 UTC
+++ src/rpcclient.cpp
@@ -39,7 +39,7 @@ Object CallRPC(const string& strMethod,
     // Connect to localhost
     bool fUseSSL = GetBoolArg("-rpcssl", false);
     asio::io_service io_service;
-    ssl::context context(io_service, ssl::context::sslv23);
+    ssl::context context(ssl::context::sslv23);
     context.set_options(ssl::context::no_sslv2);
     asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
     SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);

Fix build for boost 1.66

Fix build for boost 1.66


// RUN: %clang_cc1 -std=c++14 -fsyntax-only -analyze -analyzer-checker=core,deadcode,debug.ExprInspection -verify %s

int clang_analyzer_eval(int);

void generalizedCapture() {
  int v = 7;
  auto lambda = [x=v]() {
    return x;
  };

  int result = lambda();
  clang_analyzer_eval(result == 7); // expected-warning {{TRUE}}
}

void sideEffectsInGeneralizedCapture() {
  int v = 7;
  auto lambda = [x=v++]() {
    return x;
  };
  clang_analyzer_eval(v == 8); // expected-warning {{TRUE}}

  int r1 = lambda();
  int r2 = lambda();
  clang_analyzer_eval(r1 == 7); // expected-warning {{TRUE}}
  clang_analyzer_eval(r2 == 7); // expected-warning {{TRUE}}
  clang_analyzer_eval(v == 8); // expected-warning {{TRUE}}
}

int addOne(int p) {
 return p + 1;
}

void inliningInGeneralizedCapture() {
  int v = 7;
  auto lambda = [x=addOne(v)]() {
    return x;
  };

  int result = lambda();
  clang_analyzer_eval(result == 8); // expected-warning {{TRUE}}
}

void caseSplitInGeneralizedCapture(bool p) {
  auto lambda = [x=(p ? 1 : 2)]() {
    return x;
  };

  int result = lambda();
  clang_analyzer_eval(result == 1); // expected-warning {{FALSE}} expected-warning {{TRUE}}
}

[analyzer] Add tests for generalized lambda capture (C++14). NFC.

Add tests demonstrating that the analyzer supports generalized lambda capture. This
support falls out naturally from the work Gábor Horváth did adding C++11 lambdas to
the analyzer.

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


#include <iostream>
#define N 8
using namespace std;

// A utility function to check the valid indexes
// of N*N chess board
bool isSafe(int x, int y, int sol[N][N]) {
	return (x >= 0
		&& y >= 0
		&& x < N
		&& y < N
		&& sol[x][y] == -1);
}

/**
 * Print the solution
 */
void printSolution(int sol[N][N]) {
	for (int i = 0; i < N; i++) {
		for (int j = 0; j < N; j++) {
			cout<<sol[i][j]<<" ";
		}
		cout<<endl;
	}
}
bool solveKTUtil(int x, int y, int movei, int sol[N][N],
                int xMove[N], int yMove[N]) {
   int k, next_x, next_y;
   if (movei == N*N)
       return true;

   /* Try all next moves from the current coordinate x, y */
   for (k = 0; k < 8; k++)
   {
       next_x = x + xMove[k];
       next_y = y + yMove[k];
       if (isSafe(next_x, next_y, sol))
       {
         sol[next_x][next_y] = movei;
         if (solveKTUtil(next_x, next_y, movei+1, sol,
                         xMove, yMove) == true)
             return true;
         else
             sol[next_x][next_y] = -1;// backtracking
       }
   }

   return false;
}

void solveKT() {
	int sol[N][N];

	for (int i = 0; i < N; i++) {
		for (int j = 0; j < N; j++) {
			sol[i][j] = -1;
		}
	}

	/* xMove[] and yMove[] define next move of Knight.
       xMove[] is for next value of x coordinate
       yMove[] is for next value of y coordinate */
    int xMove[8] = {  2, 1, -1, -2, -2, -1,  1,  2 };
    int yMove[8] = {  1, 2,  2,  1, -1, -2, -2, -1 };
	sol[0][0] = 0;

  	/* Start from 0,0 and explore all tours using
       solveKTUtil() */
	if (solveKTUtil(0, 0, 1, sol, xMove, yMove) == false) {
		cout<<"Solution does not exists";
		return;
	} else {
		printSolution(sol);
	}
}

int main() {
	solveKT();
	return 0;
}

Implement Knight in Tours problem

Implement Knight in Tours problem

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


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

namespace test1 {
  static int abc = 42; // expected-warning {{variable 'abc' is not needed and will not be emitted}}
  template <typename T>
  int foo(void) {
    return abc;
  }
}

namespace test2 {
  struct bah {
  };
  namespace {
    struct foo : bah {
      static char bar;
      virtual void zed();
    };
    void foo::zed() {
      bar++;
    }
    char foo::bar=0;
  }
  bah *getfoo() {
    return new foo();
  }
}

Add a basic testcase for the "variable is not needed" warning and one that
regressed in r168519.

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


double integrate(double (*f)(double), double a, double b, double delta = 1) {
    if(abs(a - b) < delta) {
        return (b-a)/6 * (f(a) + 4 * f((a+b)/2) + f(b));
    }

    return integrate(f, a, (a+b)/2, delta) + integrate(f, (a+b)/2, b, delta);
}

Add numeric integration using Simpson's method.


#inlude <bits/stdc++.h>

using namespace std;

void parse_cmd(string str, string cmd) {
	// Clear whatever cmd contains
	cmd = "";
}

void execute_cmd(string cmd) {

}

int main() {
	string hexLine;
	string parsedCmd;

	int err = 0;

	while( !err ) {
		// Read each line from .hex file
		getline(cin, hexLine);
		// Now parse the string to a more friendly format
		err = parse_cmd(hexLine, parsedCmd);
		if(!err) {
			// If no errors proceed to execute the command
			execute_cmd(parsedCmd);
		}
	}
	return 0;
}

Create initial file version for AVR instruccions parser

* At least there will be two methods one for .hex -> cmds
* And from cmds to execute them

Signed-off-by: Ulises Mendez Martinez <64c66da2351c01d4afecd1591810410a1c01865c@gmail.com>


#include<iostream>

using namespace std;

int main()
{
	string s1,s2;
	cout<<"Enter the two strings:";
	cin>>s1>>s2;

	int l1=s1.length();
	int l2=s2.length();

	int d[l1+1][l2+1];

	for(int i=0;i<=l1;i++)
		for(int j=0;j<=l2;j++){
			if(i==0)
				d[0][j]=j;
			else if(j==0)
				d[i][0]=i;

			else if(s1[i-1]==s2[j-1])
				d[i][j]=d[i-1][j-1];
			else
				d[i][j]=1+min(d[i-1][j],min(d[i][j-1],d[i-1][j-1]));
		}

	cout<<"Edit distance is "<<d[l1][l2]<<".\n";
}

Edit distance between two strings

Edit distance between two strings


#include <iostream>
#include <string>
#include "ucl++.h"

int main(int argc, char **argv)
{
	std::string input, err;

	input.assign((std::istreambuf_iterator<char>(std::cin)),
		std::istreambuf_iterator<char>());

	auto obj = ucl::Ucl::parse(input, err);

	if (obj) {
		std::cout << obj.dump(UCL_EMIT_CONFIG) << std::endl;

		for (const auto &o : obj) {
			std::cout << o.dump(UCL_EMIT_CONFIG) << std::endl;
		}
	}
	else {
		std::cerr << "Error: " << err << std::endl;

		return 1;
	}
}

Add a simple C++ example.

Add a simple C++ example.


/**
 * link: https://leetcode.com/problems/number-of-1-bits/
 */
class Solution {
public:
    int hammingWeight(uint32_t n) {
        int res = 0;
        while(n)
        {
            res += (n & 1);
            n >>= 1;
        }
        return res;
    }
};

Add solution for 191. Number of 1 Bits.

Add solution for 191. Number of 1 Bits.


// Copyright 2016 Mitchell Kember. Subject to the MIT License.
// Project Euler: Problem 17
// Number letter counts

namespace problem_17 {

long solve() {
	constexpr long and_word = 3;
	constexpr long hundred = 7;
	constexpr long one_thousand = 3 + 8;
	constexpr long a = 0+3+3+5+4+4+3+5+5+4; //  0,  1, ...,  9
	constexpr long b = 3+6+6+8+8+7+7+9+8+8; // 10, 11, ..., 19
	constexpr long c = 6+6+5+5+5+7+6+6;     // 20, 30, ..., 90
	constexpr long s99 = 10*c + 9*a + b;
	constexpr long result =
		10*s99 + (100*a + 9*100*hundred) + 9*99*and_word + one_thousand;
	return result;
}

} // namespace problem_17

Solve problem 17 in C++

Solve problem 17 in C++


/**
 * Merge sort algorithm. One of the efficient sorting algorithm. Works
 * on the principle of divide and conquer strategy.
 *
 * Very well suited especially for linked lists. Unlike array, in linked
 * lists, we can insert items in the middle in O(1) space and O(1) time.
 * So, merge operation can be implemented without extra space.
 */

/**
 * Merge sort algorithm on Singly linked list.
 */
#include <bits/stdc++.h>
using namespace std;

// Singly Linked list node structure
struct node {
    int data;
    struct node* next;
};

struct node* merge(struct node* a, struct node* b) {
  struct node* result = NULL;

  if (a == NULL) return(b);
  else if (b == NULL) return(a);

  if (a->data <= b->data) {
     result = a;
     result->next = merge(a->next, b);
  } else {
     result = b;
     result->next = merge(a, b->next);
  }
  return(result);
}

void split(struct node* source, struct node** frontRef,
           struct node** backRef)
{
  struct node* fast;
  struct node* slow;

  if (source==NULL || source->next==NULL) {
    *frontRef = source;
    *backRef = NULL;
  } else {
    slow = source;
    fast = source->next;

    while (fast != NULL)
    {
      fast = fast->next;
      if (fast != NULL)
      {
        slow = slow->next;
        fast = fast->next;
      }
    }

    // 'slow' pointer is before the midpoint in the list
    // so splitting in two at that point.
    *frontRef = source;
    *backRef = slow->next;
    slow->next = NULL;
  }
}

void mergeSort(struct node** headRef) {
  struct node* a;
  struct node* b;

  if (*headRef == NULL || (*headRef)->next == NULL) return;

  // Split the list into two sublists.
  split(*headRef, &a, &b);

  // Recursively sort the sublists.
  mergeSort(&a);
  mergeSort(&b);

  *headRef = merge(a, b);
}

void push(node** head, int val) {
  node* newNode = new node;
  newNode->data = val;
  newNode->next = *head;
  *head = newNode;
}

int main() {
    int n;
    cin >> n;

    struct node *l = NULL;
    for (int i = 0; i < n; i++) {
        int val;
        cin >> val;
        push(&l, val);
    }

    mergeSort(&l);

    // Print the sorted list
    while(l != NULL) {
        cout << l->data << ' ';
        l = l->next;
    }
    cout << endl;

    return 0;
}
// Time Complexity is O(nlogn).
// Space Complexity is constant.

Add merge sort implementation for singly linked list


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

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

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

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

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

namespace tensorflow {

REGISTER_OP("KafkaDataset")
    .Input("topics: string")
    .Input("servers: string")
    .Input("group: string")
    .Input("eof: bool")
    .Input("timeout: int64")
    .Output("handle: variant")
    .SetIsStateful()
    .SetShapeFn(shape_inference::ScalarShape)
    .Doc(R"doc(
Creates a dataset that emits the messages of one or more Kafka topics.

topics: A `tf.string` tensor containing one or more subscriptions,
  in the format of [topic:partition:offset:length],
  by default length is -1 for unlimited.
servers: A list of bootstrap servers.
group: The consumer group id.
eof: If True, the kafka reader will stop on EOF.
timeout: The timeout value for the Kafka Consumer to wait
  (in millisecond).
)doc");

}  // namespace tensorflow

Allow is_initialized and initializer to be called on MirroredVariables and TowerLocalVariables.

PiperOrigin-RevId: 203520287


/*
 * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
 *
 * This file is part of libbitcoin.
 *
 * libbitcoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <boost/test/unit_test.hpp>
#include <bitcoin/bitcoin.hpp>

BOOST_AUTO_TEST_SUITE(satoshi_words)

#ifndef ENABLE_TESTNET
BOOST_AUTO_TEST_CASE(satoshi_words_mainnet)
{
    // Create genesis block.
    auto block = bc::genesis_block();

    // Genesis block contains a single coinbase transaction.
    BOOST_REQUIRE_EQUAL(block.transactions.size(), 1);

    // Get first transaction in block (coinbase).
    const bc::transaction_type& coinbase_tx = block.transactions[0];

    // Coinbase tx has a single input.
    BOOST_REQUIRE_EQUAL(coinbase_tx.inputs.size(), 1);
    const bc::transaction_input_type& coinbase_input = coinbase_tx.inputs[0];

    // Convert the input script to its raw format.
    const bc::data_chunk& raw_message = bc::save_script(coinbase_input.script);

    // Convert to a string after removing the 8 byte checksum.
    BOOST_REQUIRE_GT(raw_message.size(), 8u);
    std::string message;
    message.resize(raw_message.size() - 8);
    std::copy(raw_message.begin() + 8, raw_message.end(), message.begin());

    BOOST_REQUIRE_EQUAL(message, "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks");
}
#endif

BOOST_AUTO_TEST_SUITE_END()

Convert satoshiwords to test case.

Convert satoshiwords to test case.


// RUN: %clang_cc1 -fsyntax-only -verify -Wunneeded-member-function %s

namespace {
  class A {
    void g() {} // expected-warning {{is not needed and will not be emitted}}
    template <typename T>
    void foo() {
      g();
    }
  };
}

Add missing test for -Wunneeded-member-functions.

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


#include "df_hi_res_time.h"

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

static double g_tickInterval = -1.0;
static double g_timeShift = 0.0;

inline double GetLowLevelTime();

static void InitialiseHighResTime()
{
    LARGE_INTEGER count;
    QueryPerformanceFrequency(&count);
    g_tickInterval = 1.0 / (double)count.QuadPart;
	g_timeShift = GetLowLevelTime();
}

inline double GetLowLevelTime()
{
    if (g_tickInterval < 0.0)
        InitialiseHighResTime();

    LARGE_INTEGER count;
    QueryPerformanceCounter(&count);
    return (double)count.QuadPart * g_tickInterval;
}

double GetHighResTime()
{
	double timeNow = GetLowLevelTime();
    timeNow -= g_timeShift;
    return timeNow;
}

void SleepMillisec(int milliseconds)
{
	Sleep(milliseconds);
}

#include "df_hi_res_time.h"

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

static double g_tickInterval = -1.0;
static double g_timeShift = 0.0;

inline double GetLowLevelTime();

static void InitialiseHighResTime()
{
    LARGE_INTEGER count;
    QueryPerformanceFrequency(&count);
    g_tickInterval = 1.0 / (double)count.QuadPart;
	g_timeShift = GetLowLevelTime();
}

inline double GetLowLevelTime()
{
    if (g_tickInterval < 0.0)
        InitialiseHighResTime();

    LARGE_INTEGER count;
    QueryPerformanceCounter(&count);
    return (double)count.QuadPart * g_tickInterval;
}

__declspec(noinline) double GetHighResTime()
{
	double timeNow = GetLowLevelTime();
    timeNow -= g_timeShift;
    return timeNow;
}

void SleepMillisec(int milliseconds)
{
	Sleep(milliseconds);
}

Make sure GetHighResTime() doesn't get inlined because it is a slow function anyway since it calls QueryPerformanceCounter(). Also, it is often used when profiling, and when it gets inlined, it makes the disassembly look confusing.


#include <Halide.h>
#include <iostream>

using namespace Halide;

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

    Func kernel1;
    kernel1(x) = floor(x / 3.0f);

    Func kernel2;
    kernel2(x) = sqrt(4 * x * x) + kernel1(x);

    Func kernel3;
    kernel3(x) = cast<int32_t>(x + kernel2(x));

    Target target = get_target_from_environment();
    if (target.features & Target::CUDA ||
	target.features & Target::OpenCL) {
        kernel1.cuda_tile(x, 32).compute_root();
        kernel2.cuda_tile(x, 32).compute_root();

        kernel3.cuda_tile(x, 32);
    }

    Image<int32_t> result = kernel3.realize(256);

    for (int i = 0; i < 256; i ++)
      assert(result(i) == static_cast<int32_t>(floor(i / 3.0f) + sqrt(4 * i * i) + i));

    std::cout << "Success!" << std::endl;
}

Add a test for multiple Func's that are compute_root when compiling
for a GPU target.

Former-commit-id: b81caa7f043020d0e6222abc0cbdea766fd79c45


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

/* http://codeforces.com/contest/527/submission/13054549 */

#include <iostream>
#include <vector>

int main() {
    int n;
    std::cin >> n;
    /* Sieve of Eratosthenes */
    std::vector<char> prime(n+1, true);
    prime[0] = prime[1] = false;
    for (int i = 2; i <= n; i++) {
        if (1ll * i * i <= n) {
            for (int x = i * i; x <= n; x += i) {
                prime[x] = false;
            }
        }
    }
    typedef std::vector<int> Ints;
    Ints result;
    for (int i = 0; i <= n; i++) {
        if (prime[i]) {
            int s = 1;
            while (s <= n / i) {
                s *= i;
                result.push_back(s);
            }
        }
    }
    std::cout << result.size() << std::endl;
    for (Ints::const_iterator i = result.begin(); i != result.end(); i++) {
        std::cout << *i << " ";
    }
    std::cout << std::endl;
    return 0;
}

Add the second codeforces problem

Add the second codeforces problem


// Common implementation. Note below I add a NodeAfterPrefix to remove duplicate code
// in search and startsWith. I also add a ~Trie() destructor to prevent memory leak.
// Since the interface of Trie doesn't need to expose TrieNode, it's actually better
// to implement TrieNode as a inner class of Trie.

class TrieNode {
    static const int kNumChar = 26;
    TrieNode* successors[kNumChar];
    bool is_node_;
    friend class Trie;
public:
    // Initialize your data structure here.
    TrieNode(): is_node_(false) {
        fill(successors, successors + kNumChar, nullptr);
    }
};

class Trie {
public:
    Trie(): root_(new TrieNode) {}

    // Inserts a word into the trie.
    void insert(const string& word) {
        TrieNode* current = root_;
        for (char c: word) {
            if (current->successors[c-'a'] == nullptr) {
                current->successors[c-'a'] = new TrieNode;
            }
            current = current->successors[c-'a'];
        }
        current->is_node_ = true;
    }

    // Returns if the word is in the trie.
    bool search(const string& word) {
        TrieNode* p = NodeAfterPrefix(word);
        return p != nullptr && p->is_node_;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(const string& prefix) {
        TrieNode* p = NodeAfterPrefix(prefix);
        return p != nullptr;
    }

    ~Trie() {
        DeleteNodes(root_);
    }

private:
    TrieNode* NodeAfterPrefix(const string& prefix) {
        TrieNode* current = root_;
        for (char c: prefix) {
            if (current->successors[c-'a'] == nullptr) {
                return nullptr;
            }
            current = current->successors[c-'a'];
        }
        return current;
    }
    void DeleteNodes(TrieNode* n) {
        for (int i = 0; i < TrieNode::kNumChar; ++i) {
            if (n->successors[i] != nullptr) {
                DeleteNodes(n->successors[i]);
            }
        }
        delete n;
    }
    TrieNode* root_;
};

// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");

Add a solution for problem 208: Implement Trie (Prefix Tree).


#include <map>

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

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

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

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

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

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

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

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

	return (true);
}

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

git-svn-id: 9e2532540f1574e817ce42f20b9d0fb64899e451@885 4068ffdb-0463-0410-8185-8cc71e3bd399


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

#include <string>

#if defined(OS_CHROMEOS)
#include "base/basictypes.h"
#include "base/string_util.h"
#endif

namespace l10n_util {

// Return true blindly for now.
bool IsLocaleSupportedByOS(const std::string& locale) {
#if !defined(OS_CHROMEOS)
  return true;
#else
  // We don't have translations yet for am, fa and sw.
  // We don't have fonts for te and kn, yet.
  // TODO(jungshik): Once the above issues are resolved, change this back
  // to return true.
  static const char* kUnsupportedLocales[] = {"am", "fa", "kn", "sw", "te"};
  for (size_t i = 0; i < arraysize(kUnsupportedLocales); ++i) {
    if (LowerCaseEqualsASCII(locale, kUnsupportedLocales[i]))
      return false;
  }
  return true;
#endif
}

}  // namespace l10n_util

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

#include <string>

#if defined(OS_CHROMEOS)
#include "base/basictypes.h"
#include "base/string_util.h"
#endif

namespace l10n_util {

// Return true blindly for now.
bool IsLocaleSupportedByOS(const std::string& locale) {
#if !defined(OS_CHROMEOS)
  return true;
#else
  // We don't have translations yet for am, and sw.
  // TODO(jungshik): Once the above issues are resolved, change this back
  // to return true.
  static const char* kUnsupportedLocales[] = {"am", "sw"};
  for (size_t i = 0; i < arraysize(kUnsupportedLocales); ++i) {
    if (LowerCaseEqualsASCII(locale, kUnsupportedLocales[i]))
      return false;
  }
  return true;
#endif
}

}  // namespace l10n_util

Enable Kannada, Farsi and Telugu on CrOS

BUG=chromium-os:21717
TEST=On login screen, Kannada, Telugu and Farsi can be selected.
Review URL: http://codereview.chromium.org/8301012

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


// Copyright 2016 Mitchell Kember. Subject to the MIT License.
// Project Euler: Problem 20
// Factorial digit sum

#include "common.hpp"

#include <gmpxx.h>

namespace problem_20 {

long solve() {
	mpz_class n(1);
	for (long i = 2; i <= 100; ++i) {
		n *= i;
	}
	return common::sum_of_digits(n);
}

} // namespace problem_20

Solve problem 20 in C++

Solve problem 20 in C++


//083 Remove Duplicates from Sorted List
/*
 *Given a sorted linked list, delete all duplicates such that each element appear only once.
 *
 *For example,
 *Given 1->1->2, return 1->2.
 *Given 1->1->2->3->3, return 1->2->3.
 *
 *Tag: Linked List
 *
 *Author: Linsen Wu
 */

#include "stdafx.h"

 //Definition for singly-linked list.
struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
		if (head  == NULL)
		{
			return NULL;
		}

		ListNode* current = head->next;
		ListNode* previous = head;

		while (current != NULL)
		{
			if (previous->val == current->val)
			{
				current = current->next;
				if (current == NULL)
				{
					previous->next = NULL;
				}

			} else
			{
				previous->next = current;
				previous = current;
				current = current->next;
			}
		}

		return head;
    }
};

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

Add solution for problem 083 Remove Duplicates from Sorted List


#define BOOST_TEST_MODULE test_experimental

#include <stdexcept>
#include <memory>

#include <boost/test/included/unit_test.hpp>

#include "variable.hxx"
#include "function.hxx"

BOOST_AUTO_TEST_SUITE(test_experimental)

double sum(std::vector<double> & args)
{
  double res(0.);
  for (unsigned i = 0; i < args.size(); ++i) {
    res += double(args[i]);
  }
  return res;
}

struct compsetup {
  compsetup() : myfuncvar(NULL), myvar(NULL), varsum(NULL)
  {
    myfuncvar = std::make_shared<function>(); // 1
    myvar = std::make_shared<variable>();     // 1
    fnbase_vec vars {myfuncvar, myvar};
    varsum = std::make_shared<function>(sum, vars); // 1+1
  }
  ~compsetup() {}
  fnbase_ptr myfuncvar;
  fnbase_ptr myvar;
  fnbase_ptr varsum;
};

BOOST_FIXTURE_TEST_CASE(compare_variable_impl, compsetup)
{
  BOOST_CHECK_EQUAL(2, *varsum);
}

BOOST_AUTO_TEST_SUITE_END()

Test to check how different variable implementations

Check between `variable' based, and `function' based variable.


// Bug in clang/gcc or perhaps libc/nptl around static linking and condition
// variables.
//
// Fails: clang++ -std=c++11 -static -o cv cv.cc -lpthread
//
// Workaround:
// clang++ -std=c++11 -static -o cv cv.cc -Wl,--whole-archive -lpthread \
//   -Wl,--no-whole-archive
//
#include <condition_variable>
#include <iostream>

using namespace std;

int main( void )
{
  { condition_variable cv; }
  cout << "No fault!" << endl;
  return 0;
}

Document bug with condition variables and static linking (C++)


#include <iostream>

class A {
public:
        void f();
        void g();
};

class B : public A {
public:
        void f();
};

class C {
public:
        virtual void f();
        void g();
};

class D : public C {
public:
        void f();
};

void A::f() {
        std::cout << "A\n";
}

void A::g() {
        f();
}

void B::f() {
        std::cout << "B\n";
}

void C::f() {
        std::cout << "C\n";
}

void C::g() {
        f();
}

void D::f() {
        std::cout << "D\n";
}

int main() {
        B b;
        A &a = b;

        a.g();  // A

        D d;
        C &c = d;

        c.g();  // D
        return 0;
}

Add a c++ inheritance example

Add a c++ inheritance example

The example shows what is the difference between overriding a function
and hiding it.


#include <iostream>
#include <cstring>
using namespace std;

void swap(int &a, int &b)
{
	int temp = a;
	a = b;
	b = temp;
}

void reverse(int *a, int start, int end)
{
	for (int i = 0; i < (end - start + 1) / 2; i++) {
		swap(a[start + i], a[end - i]);
	}
}

void print(int *a, int start, int end)
{
	for (int i = start; i <= end; i++) {
		cout << a[i] << " ";
	}
	cout << endl;
}

//Not inplace but doesn't need extra space
int partition_1(int *a, int start, int end)
{
	int p = start;
	for (int i = start + 1; i <= end; i++) {
		if (a[i] < a[start]) {
			swap(a[++p], a[i]);
		}
	}
	swap(a[p], a[start]);
	return p;
}

//Inplace but need extra space O(n)
int partition_2(int *a, int start, int end)
{
	int n = end - start + 1;
	int *temp = new int[n];
	int i = 0, j = n - 1;
	for (int k = start + 1; k <= end; k++) {
		if (a[k] < a[start]) {
			temp[i++] = a[k];
		}
		else {
			temp[j--] = a[k];
		}
	}
	temp[i] = a[start];
	memcpy(a + start, temp, n * sizeof(int));
	reverse(a, start + i + 1, end);
	return start + i;
}

void quicksort(int *a, int start, int end)
{
	if (start < end) {
		int mid = partition_2(a, start, end);
		quicksort(a, start, mid - 1);
		quicksort(a, mid + 1, end);
		print(a, start, end);
	}
}

int main()
{
	int n;
	cin >> n;
	int *a = new int[n];
	for (int i = 0; i < n; i++) {
		cin >> a[i];
	}
	quicksort(a, 0, n - 1);
	// print(a, 0, n - 1);
	return 0;
}

Add the solution to "QuickSort".

Add the solution to "QuickSort".


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 /*
 Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
    2
   / \
  1   3
Binary tree [2,1,3], return true.
Example 2:
    1
   / \
  2   3
Binary tree [1,2,3], return false.
*/

class Solution {
public:
    TreeNode* prev = NULL;
    bool isValidBST(TreeNode* root)
    {
        if (root)
        {
            if (!isValidBST(root->left))
                return false;
            if (prev && root->val <= prev->val)
                return false;
            prev = root; cout<<prev->val<<endl;
            return isValidBST(root->right);
        }

    return true;
    }
};

Update Check BST or not

Update Check BST or not


#include <iostream>
#include <random>
#include <ctime>

using namespace std;

int generate_random_number(unsigned long long seed = time(0), const int a = 0, const int b = 9) {
    static default_random_engine e;
    static uniform_int_distribution<unsigned> u(a, b);
    e.seed(seed);
    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 29, test 30


/*
 * ============================================================================
 *
 *       Filename:  test-io.cc
 *    Description:  Tests of the IO module.
 *        License:  GPLv3+
 *         Author:  Kevin Murray, spam@kdmurray.id.au
 *
 * ============================================================================
 */

#include "catch.hpp"

#include "qc-io.hh"

TEST_CASE("Read access and clearing", "[Read]") {

    qcpp::Read read;

    SECTION("Filling read members works") {
        read.name = "Name";
        read.sequence = "ACGT";
        read.quality = "IIII";

        REQUIRE(read.name.size() == 4);
        REQUIRE(read.sequence.size() == 4);
        REQUIRE(read.quality.size() == 4);
    }

    SECTION("Clearing a read empties members") {
        read.clear();

        REQUIRE(read.name.size() == 0);
        REQUIRE(read.sequence.size() == 0);
        REQUIRE(read.quality.size() == 0);
    }
}

Add tests of the Read struct

Add tests of the Read struct


// Ben Deane:
// https://twitter.com/ben_deane/status/964549956437606400
// https://t.co/mkOX0mf8jt
// When giving unique_ptr a custom deleter, prefer a stateless functor type over
// a function pointer type. The implementation won't have to store the pointer
// or call through it, and EBO means no overhead.

#include <memory>

struct custom_deleter_t {
  void operator()(int *) {}
};

int main() {
  using T = std::unique_ptr<int, void (*)(int *)>;
  using U = std::unique_ptr<int, custom_deleter_t>;
  static_assert(sizeof(T) == sizeof(int *) * 2);
  static_assert(sizeof(U) == sizeof(int *));
}

Add Ben Deane's unique_ptr guideline from his Twitter.


// 031. Next Permutation
/**
 * Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
 *
 * If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
 *
 * The replacement must be in-place, do not allocate extra memory.
 *
 * Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
 * 1,2,3  1,3,2
 * 3,2,1  1,2,3
 * 1,1,5  1,5,1
 *
 * Tags: Array
 *
 * Similar Problems: (M) Permutations (M) Permutations II (M) Permutation Sequence (M) Palindrome Permutation II
 *
 * Author: Kuang Qin
 */

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

using namespace std;

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n = nums.size();
        if (n < 2)
        {
            return;
        }

        // start from the last element, search for the first pair in ascending order
        int i = n - 1;
        while ((i > 0) && (nums[i - 1] >= nums[i]))
        {
            i--;
        }

        // if found, start from the last element, search for the first element that is larger
        if (i != 0)
        {
            int j = n - 1;
            while ((j >= i) && (nums[i - 1] >= nums[j]))
            {
                j--;
            }
            // swap these two elements
            swap(nums[i - 1], nums[j]);
        }

        // reverse the rest of the array
        reverse(nums.begin() + i, nums.end());
        return;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    vector<int> nums;
    nums.push_back(1);
    nums.push_back(6);
    nums.push_back(6);
    nums.push_back(3);
    cout << "Current Permutation: ";
    for (int i = 0; i < nums.size(); i++)
    {
        cout << nums[i] << " ";
    }
    cout << endl;

    Solution mySolution;
    mySolution.nextPermutation(nums);
    cout << "Next Permutation: ";
    for (int i = 0; i < nums.size(); i++)
    {
        cout << nums[i] << " ";
    }
    cout << endl;
    system("pause");
    return 0;
}

Add Solution for Problem 031

Add Solution for Problem 031


//190. Reverse Bits
/*
 *Reverse bits of a given 32 bits unsigned integer.
 *
 *For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
 *
 *Follow up:
 *If this function is called many times, how would you optimize it?
 *
 *Related problem: Reverse Integer
 *
 *Tag: Bit Manipulation
 *
 *Author: Linsen Wu
 */

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

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t left = 0x80000000;
		uint32_t right = 0x00000001;

		for (int i = 0; i < 16; i++)
		{
			uint32_t leftbit = n & left;
			uint32_t rightbit = n & right;
			leftbit = leftbit >> 31-i*2;
			rightbit = rightbit << 31-i*2;

			n = n & ~left & ~right;
			n = n | leftbit | rightbit;

			left = left >> 1;
			right = right << 1;

		}

		return n;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
	uint32_t input = 0x80000000;

	Solution _solution;
	_solution.reverseBits(input);

	return 0;
}

Add solution for 190 Reverse Bits

Add solution for 190 Reverse Bits


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head) return 0;
        if (!head->next) return head;
        int val = head->val;
        ListNode* p = head->next;
        if (p->val != val) {
            head->next = deleteDuplicates(p);
            return head;
        } else {
            while (p && p->val == val) p = p->next;
            return deleteDuplicates(p);
        }
    }
};

Remove Duplicates from Sorted List II

Remove Duplicates from Sorted List II