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

TEST_CASE("OperatorChebyshevSmoother", "[Chebyshev symmetry]")
{
   for (int order = 2; order < 5; ++order)
   {
      const int cheb_order = 2;

      Mesh mesh(4, 4, 4, Element::HEXAHEDRON, true);
      FiniteElementCollection *fec = new H1_FECollection(order, 3);
      FiniteElementSpace fespace(&mesh, fec);
      Array<int> ess_bdr(mesh.bdr_attributes.Max());
      ess_bdr = 1;
      Array<int> ess_tdof_list;
      fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);

      BilinearForm aform(&fespace);
      aform.SetAssemblyLevel(AssemblyLevel::PARTIAL);
      aform.AddDomainIntegrator(new DiffusionIntegrator);
      aform.Assemble();
      OperatorPtr opr;
      opr.SetType(Operator::ANY_TYPE);
      aform.FormSystemMatrix(ess_tdof_list, opr);
      Vector diag(fespace.GetTrueVSize());
      aform.AssembleDiagonal(diag);

      Solver* smoother = new OperatorChebyshevSmoother(opr.Ptr(), diag, ess_tdof_list,
                                                       cheb_order);

      int n = smoother->Width();
      Vector left(n);
      Vector right(n);
      int seed = (int) time(0);
      left.Randomize(seed);
      right.Randomize(seed + 2);

      // test that x^T S y = y^T S x
      Vector out(n);
      out = 0.0;
      smoother->Mult(right, out);
      double forward_val = left * out;
      smoother->Mult(left, out);
      double transpose_val = right * out;

      double error = fabs(forward_val - transpose_val) / fabs(forward_val);
      std::cout << "Order " << order << " symmetry error: " << error << std::endl;
      REQUIRE(error < 1.e-13);

      delete smoother;
   }
}

Add unit test for symmetry of OperatorChebyshevSmoother


#include "gsl/gsl-lite.hpp"
#include "nonstd/span.hpp"

int main()
{
    const int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };

    { using gsl::span;    span<const int> spn( arr ); }
    { using nonstd::span; span<const int> spn( arr ); }
}

// cl -nologo -EHsc -Dspan_FEATURE_MAKE_SPAN -I../include -I../../span-lite/include 03-gsl-span.cpp && 03-gsl-span
// g++ -Wall        -Dspan_FEATURE_MAKE_SPAN -I../include -I../../span-lite/include -o 03-gsl-span 03-gsl-span.cpp && 03-gsl-span

Add example that uses both gsl lite and span lite


/*
 * Part of HTTPP.
 *
 * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2013 Thomas Sanchez.  All rights reserved.
 *
 */

#include "httpp/http/Utils.hpp"

#include <boost/algorithm/string.hpp>
#include <iostream>

namespace HTTPP
{
namespace HTTP
{

static const std::string CLOSE = "Close";
static const std::string KEEPALIVE = "Keep-Alive";

void setShouldConnectionBeClosed(const Request& request, Response& response)
{
    auto headers = request.getSortedHeaders();
    auto const& connection = headers["Connection"];

    if (boost::iequals(connection, CLOSE))
    {
        response.connectionShouldBeClosed(true);
        return;
    }

    if (boost::iequals(connection, KEEPALIVE))
    {
        response.connectionShouldBeClosed(false);
        return;
    }

    if (request.major == 1 && request.minor == 1)
    {
        response.connectionShouldBeClosed(false);
        return;
    }

    response.connectionShouldBeClosed(true);
    return;
}

} // namespace HTTP
} // namespace HTTPP

/*
 * Part of HTTPP.
 *
 * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2013 Thomas Sanchez.  All rights reserved.
 *
 */

#include "httpp/http/Utils.hpp"

#include <boost/algorithm/string.hpp>
#include <iostream>

namespace HTTPP
{
namespace HTTP
{

static const std::string CLOSE = "Close";
static const std::string KEEPALIVE = "Keep-Alive";

void setShouldConnectionBeClosed(const Request& request, Response& response)
{
    auto headers = request.getSortedHeaders();
    auto const& connection = headers["Connection"];

    if (boost::iequals(connection, CLOSE))
    {
        response.connectionShouldBeClosed(true);
        return;
    }

    if (boost::iequals(connection, KEEPALIVE))
    {
        response.connectionShouldBeClosed(false);
        response.addHeader("Connection", KEEPALIVE);
        return;
    }

    if (request.major == 1 && request.minor == 1)
    {
        response.connectionShouldBeClosed(false);
        return;
    }

    response.connectionShouldBeClosed(true);
    return;
}

} // namespace HTTP
} // namespace HTTPP

Fix timeouts when using keepalive in apache bench.


#include <gtest/gtest.h>
#include <platform.h>

#include "util.h"

/** Pony code that parses, but is erroneous. Typically type check errors and
 * things used is invalid contexts.
 *
 * We build all the way up to and including code gen and check that we do not
 * assert, segfault, etc but that the build fails and at least one error is
 * reported.
 *
 * There is definite potential for overlap with other tests but this is also a
 * suitable location for tests which don't obviously belong anywhere else.
 */

class BadPonyTest : public PassTest
{
protected:
  void test(const char* src)
  {
    DO(test_error(src, "ir"));
    ASSERT_NE(0, get_error_count());
  }
};

// Cases from reported issues

TEST_F(BadPonyTest, DontCareInFieldType)
{
  // From issue #207
  const char* src =
    "class Abc\n"
    "  var _test1: (_)";

  DO(test(src));
}

TEST_F(BadPonyTest, ClassInOtherClassProvidesList)
{
  // From issue #218
  const char* src =
    "class Named\n"
    "class Dog is Named\n"

    "actor Main\n"
    "  new create(env: Env) =>\n"
    "    None";

  DO(test(src));
}

TEST_F(BadPonyTest, TypeParamMissingForTypeInProvidesList)
{
  // From issue #219
  const char* src =
    "trait Bar[A]\n"
    "  fun bar(a: A) =>\n"
    "    None\n"

    "trait Foo is Bar // here also should be a type argument, like Bar[U8]\n"
    "  fun foo() =>\n"
    "    None\n"

    "actor Main\n"
    "  new create(env: Env) =>\n"
    "    None";

  DO(test(src));
}

TEST_F(BadPonyTest, DontCareInIntLiteralType)
{
  // From issue #222
  const char* src =
    "actor Main\n"
    "  new create(env: Env) =>\n"
    "    let crashme: (_, I32) = (4, 4)";

  DO(test(src));
}

Add unit tests for parsable, but erroneous programs


#include <cassert>
#include <vector>
using namespace std;

class WidgetRepairs {
public:
  int days(vector<int> arrs, int numPerDay) {
    int ans = 0;
    int stack = 0;
    for (int d : arrs) {
      stack += d;
      if (stack > 0) {
        ans++;
      }
      stack -= numPerDay;
      if (stack < 0) {
        stack = 0;
      }
    }
    while (stack > 0) {
      stack -= numPerDay;
      ans++;
    }
    return ans;
  }
};

int main()
{
  WidgetRepairs wr;
  vector<int> v1 = { 10, 0, 0, 4, 20 };
  assert (wr.days(v1, 8) == 6);
  return 0;
}

Solve SRM 150, Div 2, Problem WidgetRepairs


//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Baozeng Ding <sploving1@gmail.com>
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------

#include "cling/Interpreter/RuntimeExceptions.h"

#include "clang/Basic/SourceLocation.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaDiagnostic.h"

namespace cling {
  namespace runtime {
    cling_null_deref_exception::cling_null_deref_exception(
      void* Loc, clang::Sema* S) : m_Location(*(unsigned *)Loc), m_Sema(S){}

    cling_null_deref_exception::~cling_null_deref_exception() {}

    void cling_null_deref_exception::what() throw() {
        clang::DiagnosticsEngine& Diag = m_Sema->getDiagnostics();
        Diag.Report(clang::SourceLocation::getFromRawEncoding(m_Location),
                                              clang::diag::warn_null_arg);
    }
  } // end namespace runtime
} // end namespace cling

Add forgotten to commit file.


// lower_bound/upper_bound example
#include <iostream>     // cout
#include <algorithm>    // lower_bound, upper_bound, sort
#include <vector>       // vector
using namespace std;
int main () {
  int myints[] = {10,20,30,30,20,10,10,20};
  vector<int> v(myints,myints+8);           // 10 20 30 30 20 10 10 20

  sort (v.begin(), v.end());                // 10 10 10 20 20 20 30 30

  vector<int>::iterator low,up;
  low=lower_bound (v.begin(), v.end(), 20); //          ^
  up= upper_bound (v.begin(), v.end(), 20); //                   ^

  cout << "lower_bound at position " << (low- v.begin()) << '\n';
  cout << "upper_bound at position " << (up - v.begin()) << '\n';
  /*
lower_bound at position 3
upper_bound at position 6
   *

  return 0;
}

Add useful script for lower and upper bound over an array.


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

using namespace Halide;

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

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

    g.gpu_tile(x, 16);
    f.compute_at(g, Var::gpu_blocks()).gpu_threads(x);

    // The amount of shared memory required varies with x

    Image<int> out = g.realize(100);
    for (int x = 0; x < 100; x++) {
        int correct = 3*x;
        if (out(x) != correct) {
            printf("out(%d) = %d instead of %d\n",
                   x, out(x), correct);
            return -1;
        }
    }

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

Test for shared allocations and thread blocks that depend on blockidx


//--------------------------------------------------------------------------//
/// Copyright (c) 2018 Milos Tosic. All Rights Reserved.                   ///
/// License: http://www.opensource.org/licenses/BSD-2-Clause               ///
//--------------------------------------------------------------------------//

#include <rbase_test_pch.h>
#include <rbase/inc/stringview.h>

using namespace rtm;

SUITE(rbase)
{
	TEST(string)
	{
		char buffer[128];
		const char* testString = "This is the test string";

		CHECK(23 == strLen(testString));

		strlCpy(buffer, 128, testString);

		CHECK(0 == strCmp(buffer, testString));

		strToUpper(buffer);
		CHECK(0 == strCmp(buffer, "THIS IS THE TEST STRING"));
		CHECK(0 == striCmp(buffer, testString));

		strToLower(buffer);
		CHECK(0 == strCmp(buffer, "this is the test string"));
		CHECK(0 == striCmp(buffer, testString));

		CHECK(0 == striCmp(strStr(buffer, "test"), "test string"));

		StringTemp<> fs(testString);
		String ds = fs;
		StringView vs(ds.data(), ds.length());

		CHECK(0 == strCmp(vs, testString));

		CHECK(true);
	}
}

Add basic string unit test


#include <xpcc/architecture/platform.hpp>
#include <xpcc/debug/logger.hpp>

using namespace xpcc::atmega;

// Create a new UART object and configure it to a baudrate of 115200
Uart0 uart(115200);
xpcc::IODeviceWrapper< Uart0 > loggerDevice(uart);

// Set all four logger streams to use the UART
xpcc::log::Logger xpcc::log::debug(loggerDevice);
xpcc::log::Logger xpcc::log::info(loggerDevice);
xpcc::log::Logger xpcc::log::warning(loggerDevice);
xpcc::log::Logger xpcc::log::error(loggerDevice);

// Set the log level
#undef	XPCC_LOG_LEVEL
#define	XPCC_LOG_LEVEL xpcc::log::DEBUG

int
main()
{
	// Enable interrupts, this is needed for every buffered UART
	sei();

	// Use the logging streams to print some messages.
	// Change XPCC_LOG_LEVEL above to enable or disable these messages
	XPCC_LOG_DEBUG   << "debug"   << xpcc::endl;
	XPCC_LOG_INFO    << "info"    << xpcc::endl;
	XPCC_LOG_WARNING << "warning" << xpcc::endl;
	XPCC_LOG_ERROR   << "error"   << xpcc::endl;

	while (1)
	{
	}
}

#include <xpcc/architecture/platform.hpp>
#include <xpcc/debug/logger.hpp>

using namespace xpcc::atmega;
typedef xpcc::avr::SystemClock clock;

// Create a new UART object and configure it to a baudrate of 115200
Uart0 uart;
xpcc::IODeviceWrapper< Uart0 > loggerDevice(uart);

// Set all four logger streams to use the UART
xpcc::log::Logger xpcc::log::debug(loggerDevice);
xpcc::log::Logger xpcc::log::info(loggerDevice);
xpcc::log::Logger xpcc::log::warning(loggerDevice);
xpcc::log::Logger xpcc::log::error(loggerDevice);

// Set the log level
#undef	XPCC_LOG_LEVEL
#define	XPCC_LOG_LEVEL xpcc::log::DEBUG

int
main()
{
    GpioOutputD1::connect(Uart0::Tx);
    GpioInputD0::connect(Uart0::Rx);
    Uart0::initialize<clock, 115200>();

	// Enable interrupts, this is needed for every buffered UART
	sei();

	// Use the logging streams to print some messages.
	// Change XPCC_LOG_LEVEL above to enable or disable these messages
	XPCC_LOG_DEBUG   << "debug"   << xpcc::endl;
	XPCC_LOG_INFO    << "info"    << xpcc::endl;
	XPCC_LOG_WARNING << "warning" << xpcc::endl;
	XPCC_LOG_ERROR   << "error"   << xpcc::endl;

	while (1)
	{
	}
}

Fix Uart in Logger example


// Copyright (c) 2015 The Gulden developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifdef __APPLE__
#include <TargetConditionals.h>
    #import "BRMerkleBlock.h"
#endif
#include "diff_common.h"
#include "diff_delta.h"
#include "diff_old.h"
#ifdef BUILD_IOS
    #import "BRMerkleBlock.h"
#endif

unsigned int GetNextWorkRequired(const INDEX_TYPE indexLast, const BLOCK_TYPE block, unsigned int nPowTargetSpacing, unsigned int nPowLimit)
{
    static int nDeltaSwitchoverBlock = DIFF_SWITCHOVER(350000, 1, 250000);
    static int nOldDiffSwitchoverBlock = DIFF_SWITCHOVER(500, 500, 260000);

    if (INDEX_HEIGHT(indexLast)+1 >= nOldDiffSwitchoverBlock)
    {
        if (INDEX_HEIGHT(indexLast)+1 >= nDeltaSwitchoverBlock)
        {
            return GetNextWorkRequired_DELTA(indexLast, block, nPowTargetSpacing, nPowLimit, nDeltaSwitchoverBlock);
        }
        else
        {
            return 524287999;
        }
    }
    return diff_old(INDEX_HEIGHT(indexLast)+1);
}

Add file missed in previous commit.


#include <iostream>
#include <gtest/gtest.h>
#include "ell.hpp"
#include "exceptions/cancelled.hpp"

TEST(test_task, simple_yield)
{
  using namespace ell;
  EventLoop loop;

  int count    = 0;
  bool has_run = false;

  auto task2 = loop.call_soon([&]()
                              {
                                for (int i = 0; i < 5; ++i)
                                {
                                  ASSERT_TRUE(has_run); // make sure that has run first.
                                  count--;
                                  ASSERT_EQ(0, count);
                                  yield();
                                }
                              });
  auto task = loop.call_soon([&]()
                             {
                               for (int i = 0; i < 5; ++i)
                               {
                                 has_run = true;
                                 ASSERT_EQ(0, count);
                                 count++;
                                 yield();
                               }
                             });
  loop.run_until_complete(task);
  ASSERT_EQ(0, count);
}

TEST(test_task, chained)
{
  using namespace ell;

  EventLoop loop;
  int count = 0;
  auto task = loop.call_soon([&]()
                             {
                               ASSERT_EQ(0, count);
                               yield([&]()
                                     {
                                       ASSERT_EQ(0, count);
                                       count++;

                                       yield([&]()
                                             {
                                               ASSERT_EQ(1, count);
                                               count++;

                                               yield([&]()
                                                     {
                                                       ASSERT_EQ(2, count);
                                                       count++;
                                                       yield();
                                                     });
                                             });
                                     });
                             });
  loop.run_until_complete(task);
  ASSERT_EQ(3, count);
}

int main(int ac, char **av)
{
  ell::initialize_logger();
  ::testing::InitGoogleTest(&ac, av);
  return RUN_ALL_TESTS();
}

Add some tests for tasks.


//===----------------------------------------------------------------------===//
//
// 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: c++98, c++03

// RUN: %build -fno-exceptions
// RUN: %run

// RUN: %build
// RUN: %run

// UNSUPPORTED: c++98, c++03

// <vector>

// Test that vector won't try to call the move constructor when resizing if
// the class has a deleted move constructor (but a working copy constructor).

#include <vector>

class CopyOnly {
public:
  CopyOnly() { }

  CopyOnly(CopyOnly&&) = delete;
  CopyOnly& operator=(CopyOnly&&) = delete;

  CopyOnly(const CopyOnly&) = default;
  CopyOnly& operator=(const CopyOnly&) = default;
};

int main() {
    std::vector<CopyOnly> x;
    x.emplace_back();

    CopyOnly c;
    x.push_back(c);

    return 0;
}

Add a test for resizing of a vector with copy-only elements


/**
 * \file
 * \brief board::lowLevelInitialization() implementation for NUCLEO-F429ZI
 *
 * \author Copyright (C) 2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/board/lowLevelInitialization.hpp"

namespace distortos
{

namespace board
{

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

void lowLevelInitialization()
{

}

}	// namespace board

}	// namespace distortos

Add empty board::lowLevelInitialization() for NUCLEO-F429ZI


# include <iostream>
# include <algorithm>

using namespace std;

bool isAnagram(string str1, string str2) {
	if str1.size() != str2.size()
		return false;
	sort(str1.begin(), str1.end());
	sort(str2.begin(), str2.end());
	return str1 == str2;
}

int main() {
	string str1, str2;
	cout << "Enter first string" << endl;
	cin >> str1;
	cout << "Enter second string" << endl;
	cin >> str2;

	cout << "Strings are anagram: " << isAnagram(str1, str2) << endl;

	return 0;
}

Check if strings are anagram


extern "C"{
    #include "global_fakes.h"
}
#include <gtest/gtest.h>

DEFINE_FFF_GLOBALS;

class FFFTestSuite: public testing::Test
{
public:
    void SetUp()
    {
        RESET_FAKE(voidfunc1);
        RESET_FAKE(voidfunc2);
        RESET_FAKE(longfunc0);
        RESET_HISTORY();
    }
};

#include "test_cases.include"

Test suite for global fakes from a cpp context


#include <bits/stdc++.h>

#define MAX ...

vector<int> G[MAX];

/* this array may be initialized with false
    eg.: memset(visited, false, sizeof visited) */
bool visited[MAX];

void dfs(int at) {
    if(visited[at])
        return;
    visited[at] = true;
    for (int i= 0; i< (int)G[at].size(); i++)
        dfs(G[at][i]);
}

Add dfs implementation in c++


// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/

#include "test.hh"

namespace pegtl
{
   void unit_test()
   {
      verify_analyze< not_at< eof > >( __LINE__, __FILE__, false );
      verify_analyze< not_at< any > >( __LINE__, __FILE__, false );

      verify_rule< not_at< eof > >( __LINE__, __FILE__,  "", result_type::LOCAL_FAILURE, 0 );
      verify_rule< not_at< eof > >( __LINE__, __FILE__,  " ", result_type::SUCCESS, 1 );
      verify_rule< not_at< any > >( __LINE__, __FILE__,  "", result_type::SUCCESS, 0 );
      verify_rule< not_at< any > >( __LINE__, __FILE__,  "a", result_type::LOCAL_FAILURE, 1 );
      verify_rule< not_at< any > >( __LINE__, __FILE__,  "aa", result_type::LOCAL_FAILURE, 2 );
      verify_rule< not_at< any > >( __LINE__, __FILE__,  "aaaa", result_type::LOCAL_FAILURE, 4 );
   }

} // pegtl

#include "main.hh"

Fix wrong renames detected by git.


// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chromeos/settings/cros_settings_names.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ChromeOSInfoPrivateTest) {
  // Set the initial timezone to a different one that JS function
  // timezoneSetTest() will attempt to set.
  base::StringValue initial_timezone("America/Los_Angeles");
  chromeos::CrosSettings::Get()->Set(chromeos::kSystemTimezone,
                                     initial_timezone);

  ASSERT_TRUE(RunComponentExtensionTest("chromeos_info_private")) << message_;
}

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chromeos/settings/cros_settings_names.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_ChromeOSInfoPrivateTest) {
  // Set the initial timezone to a different one that JS function
  // timezoneSetTest() will attempt to set.
  base::StringValue initial_timezone("America/Los_Angeles");
  chromeos::CrosSettings::Get()->Set(chromeos::kSystemTimezone,
                                     initial_timezone);

  ASSERT_TRUE(RunComponentExtensionTest("chromeos_info_private")) << message_;
}

Disable ChromeOSInfoPrivateTest due to DST failure.


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

// Returns the longest repeating non-overlapping substring
string longestRepeatedSubstring(string str){
    int n = str.length();
    int LCSRe[n+1][n+1];
    // Setting all to 0
    memset(LCSRe, 0, sizeof(LCSRe));
    string res; // To store result
    int res_length  = 0; // To store length of result

    // building table in bottom-up manner
    int i, index = 0;
    for (i=1; i<=n; i++){
      for (int j=i+1; j<=n; j++){
        // (j-i) > LCSRe[i-1][j-1] to remove
        if (str[i-1] == str[j-1] &&
          LCSRe[i-1][j-1] < (j - i)){
          LCSRe[i][j] = LCSRe[i-1][j-1] + 1;
          if (LCSRe[i][j] > res_length){
            res_length = LCSRe[i][j];
            index = max(i, index);
          }
        }
        else
          LCSRe[i][j] = 0;
      }
    }
    if (res_length > 0){
  		cout <<  (index  - res_length +1)<<endl;
  	  for (i = index - res_length + 1; i <= index; i++)
          res.push_back(str[i-1]);
		}
    return res;
}

// Driver program to test the above function
int main(){
    string str = "hello,p23puoeouhello,oues";
    cout << longestRepeatedSubstring(str); //hello,
    return 0;
}

Add algorithm to find Longest Repeated substring withot overlapping.


#include<iostream>

using namespace std;

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

                Node(){}

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

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

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

                        tmp->next=np;

                        return head;
                }

		void displayFromEnd(Node *head){

			if(!head->next){
				cout<<head->data<<"\n";
				return;
			}

			displayFromEnd(head->next);
			cout<<head->data<<"\n";
		}
};

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

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

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

	if(!head)
		cout<<"Sorry! No elements in the list. :(\n";
	else{
		cout<<"The elements accessed from the end are: \n";
		np.displayFromEnd(head);
	}
}

Print elements from the end of linked list


#include <test.hpp>

TEST_CASE("skip") {

    SECTION("check that skip skips the right amount of bytes") {

        std::vector<std::string> filenames = {
            "boolean/data-true",
            "boolean/data-false",
            "bytes/data-one",
            "bytes/data-string",
            "bytes/data-binary",
            "double/data-zero",
            "double/data-pos",
            "double/data-neg",
            "float/data-zero",
            "float/data-pos",
            "float/data-neg",
            "fixed32/data-zero",
            "fixed32/data-max-uint",
            "fixed32/data-min-uint",
            "fixed64/data-zero",
            "fixed64/data-max-uint",
            "fixed64/data-min-uint",
            "sfixed32/data-zero",
            "sfixed32/data-max-int",
            "sfixed32/data-min-int",
            "sfixed64/data-zero",
            "sfixed64/data-max-int",
            "sfixed64/data-min-int",
            "message/data-message",
            "string/data-one",
            "string/data-string",
            "int32/data-zero",
            "int32/data-pos",
            "int32/data-neg",
            "int32/data-min",
            "int32/data-max",
            "int64/data-zero",
            "int64/data-pos",
            "int64/data-neg",
            "int64/data-min",
            "int64/data-max",
            "sint32/data-zero",
            "sint32/data-pos",
            "sint32/data-neg",
            "sint32/data-min",
            "sint32/data-max",
            "sint64/data-zero",
            "sint64/data-pos",
            "sint64/data-neg",
            "sint64/data-min",
            "sint64/data-max",
            "uint32/data-zero",
            "uint32/data-pos",
            "uint32/data-max",
            "uint64/data-zero",
            "uint64/data-pos",
            "repeated/data-one",
        };

        for (const auto& filename : filenames) {
            std::string buffer = get_file_data(std::string("test/t/") + filename + ".pbf");

            mapbox::util::pbf item(buffer.data(), buffer.size());

            REQUIRE(item.next());
            item.skip();
            REQUIRE(!item);
        }

    }

}

Add tests of skip() function.


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

using namespace Halide;

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

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

    // This should throw an error because downcasting will loose precision which
    // should only happen if the user explicitly asks for it
    f(x, y) = 0.1f;

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

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

    printf("Should not be reached!\n");
    return 0;
}

Add test case to check that implicit downcasting when a Func returns float (32 bits) but the buffer has type float16_t (16 bits) is an error.


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

int *A;
int sum;

void f(int i) {
  A[i] = i * 3;
}

void g(int i) {
  sum += A[i];
}

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

  A = new int[n];
  sum = 0;

  for (unsigned i = 0; i < n; ++i) {
    f(i);
    g(i);
  }

  cout << sum << '\n';
  return 0;
}

Add cross-call example (case 2)


// RUN: %clang_cc1 %s -chain-include %s -ast-dump | FileCheck -strict-whitespace %s

// CHECK: TranslationUnitDecl 0x{{.+}} <<invalid sloc>> <invalid sloc>
// CHECK: `-<undeserialized declarations>

Add test for current AST dump behavior


#include <iostream>

using namespace std;

struct Base {
    void bar(int i) {
        cout << "Base::bar(int)" << endl;
    }
protected:
    int ival = 0;
};

struct Derived1 : virtual public Base {
    void bar(char c) {
        cout << "Derived1::bar(char)" << endl;
    }
    void foo(char c) {
        cout << "Derived1::foo(char)" << endl;
    }
protected:
    char cval = 'c';
};
struct Derived2 : virtual public Base {
    void foo(int i) {
        cout << "Derived2::foo(int)" << endl;
    }
protected:
    int ival = 1;
    char cval = 'd';
};
class VMI : public Derived1, public Derived2 {
public:
    void access_ival() {
        cout << Base::ival << endl;//without Base::, it will be Derived2::ival
    }

    void access_cval() {
        cout << Derived1::cval << endl;//both cval need ::
    }
};

int main() {
    VMI vmi;
    vmi.access_ival();
    vmi.access_cval();
    vmi.Derived1::foo('c');//both need ::
    vmi.bar(1);//call Derived1::bar()
    vmi.bar('c');//call Derived1::bar()
    vmi.Base::bar(1);

    return 0;
}

Add solution for chapter 18, test 28


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

#include "ui/message_center/message_center_util.h"

#include "base/command_line.h"
#include "ui/message_center/message_center_switches.h"

namespace message_center {

bool IsRichNotificationEnabled() {
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableRichNotifications);
}

}  // namespace message_center

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

#include "ui/message_center/message_center_util.h"

#include "base/command_line.h"
#include "ui/message_center/message_center_switches.h"

namespace message_center {

bool IsRichNotificationEnabled() {
#if defined(OS_WIN) && defined(USE_AURA)
  return false;
#else
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableRichNotifications);
#endif
}

}  // namespace message_center

Fix for crash trying to deference ash::Shell::message_center()


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

struct GrGLInterface;

const GrGLInterface* GrGLDefaultInterface() {
    return NULL;
}

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

#include "GrGLInterface.h"

const GrGLInterface* GrGLDefaultInterface() {
    return NULL;
}

Include GrGLInterface.h instead of forward declaring, since we have to get NULL defined anyway.


/*
* DTLS Hello Verify Request
* (C) 2012 Jack Lloyd
*
* Released under the terms of the Botan license
*/

#include <botan/internal/tls_messages.h>
#include <botan/lookup.h>
#include <memory>

namespace Botan {

namespace TLS {

Hello_Verify_Request::Hello_Verify_Request(const MemoryRegion<byte>& buf)
   {
   if(buf.size() < 3)
      throw Decoding_Error("Hello verify request too small");

   if(buf[0] != 254 || (buf[1] != 255 && buf[1] != 253))
      throw Decoding_Error("Unknown version from server in hello verify request");

   m_cookie.resize(buf.size() - 2);
   copy_mem(&m_cookie[0], &buf[2], buf.size() - 2);
   }

Hello_Verify_Request::Hello_Verify_Request(const MemoryVector<byte>& client_hello_bits,
                                           const std::string& client_identity,
                                           const SymmetricKey& secret_key)
   {
   std::auto_ptr<MessageAuthenticationCode> hmac(get_mac("HMAC(SHA-256)"));
   hmac->set_key(secret_key);

   hmac->update_be(client_hello_bits.size());
   hmac->update(client_hello_bits);
   hmac->update_be(client_identity.size());
   hmac->update(client_identity);

   m_cookie = hmac->final();
   }

MemoryVector<byte> Hello_Verify_Request::serialize() const
   {
   /* DTLS 1.2 server implementations SHOULD use DTLS version 1.0
      regardless of the version of TLS that is expected to be
      negotiated (RFC 6347, section 4.2.1)
   */

   Protocol_Version format_version(Protocol_Version::TLS_V11);

   MemoryVector<byte> bits;
   bits.push_back(format_version.major_version());
   bits.push_back(format_version.minor_version());
   bits += m_cookie;
   return bits;
   }

}

}

Add missing source for DTLS hello verify


extern "C" {
#include <wiringPi.h>
}

#include <signal.h>
#include <errno.h>

#include <iostream>
#include <thread>
#include <chrono>

void gpio4Callback(void) {
    std::cout << "Hello" << std::endl;
}

int main(){
    sigset_t set;
    int sig;
    int *sigptr = &sig;
    int ret_val;
    sigemptyset(&set);
    sigaddset(&set, SIGQUIT);
    sigaddset(&set, SIGINT);
    sigaddset(&set, SIGTERM);
    sigaddset(&set, SIGUSR1);
    sigprocmask( SIG_BLOCK, &set, NULL );
    std::cout << "Waiting for a signal or button\n";

    wiringPiSetup () ;

    wiringPiISR (4, INT_EDGE_FALLING, &gpio4Callback) ;

    ret_val = sigwait(&set,sigptr);
    if(ret_val == -1)
        perror("sigwait failed\n");
    else {
        std::cout << "sigwait returned with sig: " << *sigptr << std::endl;
    }

    return 0;
}

Add gpio interrupt plus signal wait


#include <iostream>
#include <limits>

using namespace std;

template <typename T1, typename T2>
auto sum(T1 a, T2 b) -> decltype(a + b) {
    return a + b;
}

int main() {
    char c1 = 127;
    char c2 = 127;
    long lng = numeric_limits<long>::max() - 200;
    cout << sum(c1, c2) << endl;
    cout << sum(c2, lng) << endl;
    return 0;
}

Add solution for chapter 16 test 41


#include <iostream>
using namespace std;

int main(){

  string animals[][3] = {
    {"fox", "dog", "cat"},
    {"mouse", "squirrel", "parrot"}
  };

  for(int i = 0; i < sizeof(animals)/sizeof(animals[0]); i++){
    for(int j = 0; j < sizeof(animals[0])/sizeof(string); j++){
      cout << animals[i][j] << " " << flush;
    }
    cout << endl;
  }

  return 0;
}

Implement For Loop Using Sizeof Example


class Solution {
public:
    long long minimalKSum(vector<int>& nums, int k) {
        auto cmp = [](int left, int right){
            return left > right;
        };
        std::priority_queue<int, std::vector<int>, decltype(cmp)> q(cmp);
        for (const auto& num : nums) {
            q.emplace(std::move(num));
        }
        // while (!q.empty()) {
        //     std::cout << q.top() << std::endl;
        //     q.pop();
        // }
        int64_t ret = 0;
        int start = 0;
        while (!q.empty()) {
            int cur = q.top();
            q.pop();
            if (cur == start) continue;
            int count = cur - start - 1;
            if (count == 0) {
                start = cur;
                continue;
            }
            if (count >= k) {
                ret += int64_t((start + 1 + start + k)) * int64_t(k) / 2;
                return ret;
            } else {
                ret += int64_t((start + cur)) * int64_t(count) / 2;
                k -= count;
                start = cur;
            }
        }
        if (k > 0) {
            ret += int64_t((start + 1 + start + k)) * int64_t(k) / 2;
        }
        return ret;
    }
};

Append K Integers With Minimal Sum


// Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "wallet/test/wallet_test_fixture.h"

#include "rpc/server.h"
#include "wallet/db.h"
#include "wallet/wallet.h"

CWallet *pwalletMain;

WalletTestingSetup::WalletTestingSetup(const std::string& chainName):
    TestingSetup(chainName)
{
    bitdb.MakeMock();

    bool fFirstRun;
    std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, "wallet_test.dat"));
    pwalletMain = new CWallet(std::move(dbw));
    pwalletMain->LoadWallet(fFirstRun);
    RegisterValidationInterface(pwalletMain);

    RegisterWalletRPCCommands(tableRPC);
}

WalletTestingSetup::~WalletTestingSetup()
{
    UnregisterValidationInterface(pwalletMain);
    delete pwalletMain;
    pwalletMain = nullptr;

    bitdb.Flush(true);
    bitdb.Reset();
}

// Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "wallet/test/wallet_test_fixture.h"

#include "rpc/server.h"
#include "wallet/db.h"
#include "wallet/wallet.h"

std::unique_ptr<CWallet> pwalletMain;

WalletTestingSetup::WalletTestingSetup(const std::string& chainName):
    TestingSetup(chainName)
{
    bitdb.MakeMock();

    bool fFirstRun;
    std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, "wallet_test.dat"));
    pwalletMain = std::unique_ptr<CWallet>(new CWallet(std::move(dbw)));
    pwalletMain->LoadWallet(fFirstRun);
    RegisterValidationInterface(pwalletMain.get());

    RegisterWalletRPCCommands(tableRPC);
}

WalletTestingSetup::~WalletTestingSetup()
{
    UnregisterValidationInterface(pwalletMain.get());
    pwalletMain.reset();

    bitdb.Flush(true);
    bitdb.Reset();
}

Use unique_ptr for pwalletMain (CWallet)


#include <sstream>
#include <gtest/gtest.h>
#include "portsocket.h"

#define TEST_CLASS PortSocketTest

class TEST_CLASS : public testing::Test {
protected:
    class DummySocket : PortSocket {
    public:
        DummySocket(bool *sentinel) : sentinel(sentinel) { *sentinel = true; }
        int read(PortType port, SizeType len, void *buffer) { }
        int write(PortType port, SizeType len, const void *buffer) { }
        ~DummySocket() { *sentinel = false; }
    private:
        bool *sentinel;
    };
};

TEST_F(TEST_CLASS, TestConstructDestruct) {
    bool sentinel = false;
    {
        DummySocket sock(&sentinel);
        ASSERT_EQ(sentinel, true) << "Failed to construct instance";
    }
    ASSERT_EQ(sentinel, false) << "Failed to destruct instance";
}

Create dumb test for better coverage


// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -o - %s -std=c++14 | FileCheck %s

template<typename> struct custom_copy_ctor {
  custom_copy_ctor() = default;
  custom_copy_ctor(custom_copy_ctor const &) {}
};

// CHECK: define {{.*}} @_ZN16custom_copy_ctorIvEC2ERKS0_(
void pr22354() {
  custom_copy_ctor<void> cc;
  [cc](auto){}(1);
}

Add a test that we emit copy-ctors for captures in generic lambdas.


#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <complex>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cwchar>
#include <cwctype>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <strstream>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>

Add an input file that includes all standard C++ headers


#include <iostream>

using namespace std;

struct Node {
  int data;

  Node* left;
  Node* right;

  Node(int data, Node* left = nullptr, Node* right = nullptr)
    : data(data), left(left), right(right) {}
};

class BinaryTree {
  Node* root;

  BinaryTree(Node* node) {
    root = copyNode(node);
  }

  Node* copyNode(Node* node) {
    if (node == nullptr)
      return node;
    return new Node(node->data,
                    copyNode(node->left),
                    copyNode(node->right));
  }

  void eraseNode(Node* node) {
    if (node != nullptr) {
      eraseNode(node->left);
      eraseNode(node->right);
      delete node;
    }
  }

  void assignFrom(Node*& to, Node*& from) {
    Node* toDel = to;
    to = from;
    from = nullptr;
    eraseNode(toDel);
  }

public:
  BinaryTree() : root(nullptr) {}

  BinaryTree(int rootData,
             BinaryTree&& left = BinaryTree(),
             BinaryTree&& right = BinaryTree()) {
    root = new Node(rootData);
    assignFrom(root->left, left.root);
    assignFrom(root->right, right.root);
  }

  BinaryTree(const BinaryTree& other) {
    root = copyNode(other.root);
  }

  BinaryTree& operator=(const BinaryTree& other) {
    if (this != &other) {
      eraseNode(root);
      root = copyNode(other.root);
    }
  }

  ~BinaryTree() {
    eraseNode(root);
  }

  bool empty() const { return root == nullptr; }

  BinaryTree leftTree() const {
    return BinaryTree(root->left);
  }

  BinaryTree rightTree() const {
    return BinaryTree(root->right);
  }

  int getRoot() const {
    return root->data;
  }

  friend ostream& operator<<(ostream& os, const BinaryTree& bt) {
    if (bt.empty())
      return os << '.';

    return os << '(' << bt.getRoot() << ' ' << bt.leftTree() << ' '
      << bt.rightTree() << ')';
  }

};

int main() {
  BinaryTree bt(3);
  BinaryTree bt2(3, 4, 5);

  BinaryTree bt3(3, 4, BinaryTree(5, 6, 7));

  cout << bt3 << endl;

  return 0;
}

Add binary tree live implementation


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

class Node {
public:
  int data;
  Node *left;
  Node *right;

  Node(int x) {
    data = x;
    left = NULL;
    right = NULL;
  }
};

vector<Node *> rightView(Node *root) {
  vector<Node *> rightView;
  if (root == NULL) return rightView;
  queue<Node *> q;
  q.push(root);
  while (!q.empty()) {
    int n = q.size();
    for (int i = 0; i < n; i++) {
      Node *elem = q.front();
      q.pop();
      if (i == n - 1) rightView.push_back(elem);
      if (elem->left != NULL) q.push(elem->left);
      if (elem->right != NULL) q.push(elem->right);
    }
  }
  return rightView;
}

vector<Node *> leftView(Node *root) {
  vector<Node *> leftView;
  if (root == NULL) return leftView;
  queue<Node *> q;
  q.push(root);
  while (!q.empty()) {
    int n = q.size();
    for (int i = 0; i < n; i++) {
      Node *elem = q.front();
      q.pop();
      if (i == 0) leftView.push_back(elem);
      if (elem->left != NULL) q.push(elem->left);
      if (elem->right != NULL) q.push(elem->right);
    }
  }
  return leftView;
}

int main() {
  Node *root = new Node(5);
  root->left = new Node(9);
  root->right = new Node(6);
  root->right->right = new Node(8);
  root->right->left = new Node(3);
  root->right->left->left = new Node(16);
  root->right->left->left->right = new Node(66);
  root->left->right = new Node(10);
  vector<Node *> Rview = rightView(root);
  cout << "Right view:\n";
  for (auto node : Rview) {
    cout << node->data << endl;
  }
  cout << "Left view:\n";
  vector<Node *> Lview = leftView(root);
  for (auto node : Lview) {
    cout << node->data << endl;
  }
  return 0;
}

Add c++ code for printing the side view of a binary tree


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

#include <exception>
#include <stdlib.h>
#include <assert.h>

struct A {};

// Despite being marked as noexcept, this function must have an EHT entry that
// is not 'cantunwind', so that the unwinder can correctly deal with the throw.
void f1() noexcept
{
    try {
        A a;
        throw a;
        assert(false);
    } catch (...) {
        assert(true);
        return;
    }
    assert(false);
}

int main()
{
    f1();
}

Add EH test case checking that handlers in noexcept functions can still unwind


// RUN: %clang_cc1 -emit-llvm %s -o - -triple=x86_64-pc-linux-gnu | FileCheck %s

extern int aa __attribute__((section(".sdata")));
// CHECK-DAG: @aa = external global i32, section ".sdata", align 4

extern int bb __attribute__((section(".sdata"))) = 1;
// CHECK-DAG: @bb = global i32 1, section ".sdata", align 4

int foo() {
  return aa + bb;
}

Add test forgotten in r314262.


#include <iostream>
using namespace std;

long long solve(int n)
{
    long long *res = new long long[n + 1];
    switch (n) {
    case 1: return 1;
    case 2: return 2;
    case 3: return 3;
    case 4: return 6;
    }
    res[1] = 1;
    res[2] = 2;
    res[3] = 3;
    res[4] = 6;
    for (int i = 5; i <= n; i++) {
        res[i] = res[i - 1] + res[i - 2] + res[i - 4];
    }
    long long x = res[n];
    delete [] res;
    return x;
}

int main()
{
    int T;
    cin >> T;
    while (T--) {
        int x;
        cin >> x;
        cout << solve(x) << endl;
    }
    return 0;
}

Add the solution to "Cached Calculations".


/*

    Copyright Eli Dupree and Isaac Dupree, 2011, 2012

    This file is part of Lasercake.

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

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

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

*/

#include "../utils.hpp"
#include <limits>
#include <array>

//#define BOOST_TEST_DYN_LINK
//#define BOOST_TEST_MODULE utils test
#include <boost/test/unit_test.hpp>
#include <boost/test/parameterized_test.hpp>

namespace /* anonymous */ {

void i64sqrt_test(uint64_t radicand) {
  uint64_t sqrt_result = i64sqrt(radicand); //implicit cast the result to 64 bits so we can square it
  BOOST_CHECK(sqrt_result * sqrt_result <= radicand);
  if(sqrt_result != std::numeric_limits<uint32_t>::max()) {
    BOOST_CHECK((sqrt_result+1) * (sqrt_result+1) > radicand);
  }
}

BOOST_AUTO_TEST_CASE( my_sqrt ) {
  std::array<uint64_t, 19> numbers_to_test = {{ 0, 1, 2, 3, 4, 5, 17, 232, 500,
    78978978, 8948954789789349789ull, 0xfffffffful, 0x100000000ull,
    0x100000001ull, 0xffffffffffffffffull, 0xfffffffffffffffeull,
    0xeeeeeeeeeeeeeeeeull, 0xfffffffe00000001ull, 0xfffffffe00000000ull
  }};
  BOOST_PARAM_TEST_CASE(i64sqrt_test, numbers_to_test.begin(), numbers_to_test.end());
}

}  /* end anonymous namespace */

Add a test for i64sqrt


#include <gtest/gtest.h>

#include "photoeffects.hpp"

using namespace cv;

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

    EXPECT_EQ(10, glow(image));
}

Add tests for glow implementation


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

#include "chrome/browser/net/async_dns_field_trial.h"

#include "base/metrics/field_trial.h"
#include "build/build_config.h"
#include "chrome/common/chrome_version_info.h"

namespace chrome_browser_net {

bool ConfigureAsyncDnsFieldTrial() {
#if defined(OS_ANDROID) || defined(OS_IOS) || defined(OS_CHROMEOS)
  // There is no DnsConfigService on those platforms so disable the field trial.
  return false;
#endif
  const base::FieldTrial::Probability kAsyncDnsDivisor = 100;
  base::FieldTrial::Probability enabled_probability = 0;

  // TODO(szym): expand to DEV channel after fixing http://crbug.com/121085
  if (chrome::VersionInfo::GetChannel() <= chrome::VersionInfo::CHANNEL_CANARY)
    enabled_probability = 50;

  scoped_refptr<base::FieldTrial> trial(
      base::FieldTrialList::FactoryGetFieldTrial(
          "AsyncDns", kAsyncDnsDivisor, "disabled", 2012, 9, 30, NULL));

  int enabled_group = trial->AppendGroup("enabled", enabled_probability);
  return trial->group() == enabled_group;
}

}  // namespace chrome_browser_net

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

#include "chrome/browser/net/async_dns_field_trial.h"

#include "base/metrics/field_trial.h"
#include "build/build_config.h"
#include "chrome/common/chrome_version_info.h"

namespace chrome_browser_net {

bool ConfigureAsyncDnsFieldTrial() {
#if defined(OS_ANDROID) || defined(OS_IOS) || defined(OS_CHROMEOS)
  // There is no DnsConfigService on those platforms so disable the field trial.
  return false;
#endif
  const base::FieldTrial::Probability kAsyncDnsDivisor = 100;
  base::FieldTrial::Probability enabled_probability = 0;

  // TODO(szym): expand to DEV channel after fixing http://crbug.com/121085
  if (chrome::VersionInfo::GetChannel() <= chrome::VersionInfo::CHANNEL_CANARY)
    enabled_probability = 0;

  scoped_refptr<base::FieldTrial> trial(
      base::FieldTrialList::FactoryGetFieldTrial(
          "AsyncDns", kAsyncDnsDivisor, "disabled", 2012, 9, 30, NULL));

  int enabled_group = trial->AppendGroup("enabled", enabled_probability);
  return trial->group() == enabled_group;
}

}  // namespace chrome_browser_net

Disable Async DNS field trial


// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++0x

class Trivial { int n; void f(); };
class NonTrivial1 { NonTrivial1(const NonTrivial1 &); };
class NonTrivial2 { NonTrivial2(NonTrivial2 &&); };
class NonTrivial3 { NonTrivial3 operator=(const NonTrivial3 &); };
class NonTrivial4 { NonTrivial4 operator=(NonTrivial4 &&); };
class NonTrivial5 { ~NonTrivial5(); };

static_assert(__is_trivial(Trivial), "Trivial is not trivial");
static_assert(!__is_trivial(NonTrivial1), "NonTrivial1 is trivial");
static_assert(!__is_trivial(NonTrivial2), "NonTrivial2 is trivial");
static_assert(!__is_trivial(NonTrivial3), "NonTrivial3 is trivial");
static_assert(!__is_trivial(NonTrivial4), "NonTrivial4 is trivial");
static_assert(!__is_trivial(NonTrivial5), "NonTrivial5 is trivial");

Test for C++11 [class]p6 (trivial classes).


#include "LanguageEasy.h"

//Windows
WindowMessage::WindowMessage()
{
	MessageName = "";
	Message = "";
}

WindowMessage::WindowMessage(string NewMessageName, string NewMessage)
{
	MessageName = NewMessageName;
	Message = NewMessage;
}

void WindowMessage::OutputWindow()
{
	char MessageBuffer[9999];
	char MessageNameBuffer[9999];
	sprintf_s(MessageBuffer, Message.c_str());
	sprintf_s(MessageNameBuffer, MessageName.c_str());
	MessageBoxA(NULL, MessageBuffer, MessageNameBuffer, MB_OK);
}

Add Window Message Class (Continued)


#include "logic.h"

#define ARBITRARY_SIZE 20

block* blockAlloc( void );
void blockFree( block * );

//Object pool:

static int mem_size {0};
static int mem_used {0};
static block* mem_array[BOARD_HEIGHT * BOARD_WIDTH / PIECES_PER_BLOCK];

block* blockAlloc( void )
{
  //check if enough space exists
  if( mem_used <= mem_size )
    {
      //get more space
    }
  return mem_array[ mem_used++ ];
}

void blockFree( block *b )
{
}

Add basic skeleton for object pool


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

struct Queue {
    stack<int> s1, s2;
};

void enqueue(Queue *Q, int data) {
    Q->s1.push(data);
}

int dequeue(Queue *Q) {
    int top;
    if (!Q->s2.empty()) {
        top = Q->s2.top();
        Q->s2.pop();
    } else {
        while (!Q->s1.empty()) {
            Q->s2.push(Q->s1.top());
            Q->s1.pop();
        }
        top = Q->s2.top();
        Q->s2.pop();
    }
    return top;
}

int main() {
    Queue *Q = new Queue();
    cout<<"enqueue 1,2,3,4\n";
    enqueue(Q, 1);
    enqueue(Q, 2);
    enqueue(Q, 3);
    enqueue(Q, 4);
    cout<<"Dequeuing front 3\n";
    int i = 0;
    while (i < 3) {
        cout<<dequeue(Q)<<" ";
        i++;
    }
    cout<<endl<<"enqueue 5,6,7,8\n";
    enqueue(Q, 5);
    enqueue(Q, 6);
    enqueue(Q, 7);
    enqueue(Q, 8);
    cout<<"Dequeuing again front 3\n";
    i = 0;
    while (i < 3) {
        cout<<dequeue(Q)<<" ";
        i++;
    }
    cout<<endl<<"enqueue 9,10\n";
    enqueue(Q, 9);
    enqueue(Q, 10);
    cout<<"Dequeuing again front 3\n";
    i = 0;
    while (i < 3) {
        cout<<dequeue(Q)<<" ";
        i++;
    }
    cout<<endl;
    delete Q;
    return 0;
}

Implement queue using only stack


// RUN: %clang_cc1 -DSTDCPP11 -std=c++11 -verify -fsyntax-only %s
// RUN: %clang_cc1 -DSTDGNU11 -std=gnu++11 -verify -fsyntax-only %s
// RUN: %clang_cc1 -DSTDGNU11TRI -trigraphs -std=gnu++11 -verify -fsyntax-only %s
// RUN: %clang_cc1 -DSTDCPP17 -std=c++1z -verify -fsyntax-only %s
// RUN: %clang_cc1 -DSTDCPP17TRI -trigraphs -std=c++1z -verify -fsyntax-only %s

void foo() {
#if defined(NOFLAGS) || defined(STDCPP11) || defined(STDGNU11TRI) || defined(STDCPP17TRI)
  const char c[] = "??/n"; // expected-warning{{trigraph converted to '\' character}}
#elif defined(STDGNU11) || defined(STDCPP17)
  const char c[] = "??/n"; // expected-warning{{trigraph ignored}}
#else
#error Not handled.
#endif
}

Add test coverage for cc1's trigraph option handling.


// 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/compositor/test/test_suite.h"

#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/compositor_switches.h"
#include "ui/gfx/gfx_paths.h"
#include "ui/gl/gl_surface.h"

#if defined(OS_WIN)
#include "ui/gfx/win/dpi.h"
#endif

namespace ui {
namespace test {

CompositorTestSuite::CompositorTestSuite(int argc, char** argv)
    : TestSuite(argc, argv) {}

CompositorTestSuite::~CompositorTestSuite() {}

void CompositorTestSuite::Initialize() {
  base::TestSuite::Initialize();
  gfx::GLSurface::InitializeOneOffForTests();

  gfx::RegisterPathProvider();

#if defined(OS_WIN)
  gfx::InitDeviceScaleFactor(1.0f);
#endif

  message_loop_.reset(new base::MessageLoopForUI);
}

void CompositorTestSuite::Shutdown() {
  message_loop_.reset();

  base::TestSuite::Shutdown();
}

}  // namespace test
}  // namespace ui

// 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/compositor/test/test_suite.h"

#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/compositor_switches.h"
#include "ui/gfx/gfx_paths.h"
#include "ui/gl/gl_surface.h"

#if defined(OS_WIN)
#include "ui/gfx/win/dpi.h"
#endif

namespace ui {
namespace test {

CompositorTestSuite::CompositorTestSuite(int argc, char** argv)
    : TestSuite(argc, argv) {}

CompositorTestSuite::~CompositorTestSuite() {}

void CompositorTestSuite::Initialize() {
  base::TestSuite::Initialize();
  gfx::GLSurface::InitializeOneOffForTests(true);

  gfx::RegisterPathProvider();

#if defined(OS_WIN)
  gfx::InitDeviceScaleFactor(1.0f);
#endif

  message_loop_.reset(new base::MessageLoopForUI);
}

void CompositorTestSuite::Shutdown() {
  message_loop_.reset();

  base::TestSuite::Shutdown();
}

}  // namespace test
}  // namespace ui

Make compositor unittests opt into real GL NullDraw contexts.


#include <cstdio> // Libreria estandar de IO C++

int main( int argc, char *argv[] ) {
    /*
        Usamos el operador de resolucion :: para acceder a los elementos
        dentro de la libreria estandar std
    */

    std::cout << "Hola mundo!" << std::endl;
}

Add CPP hello world example


// 043. Multiply Strings
/**
 * Given two numbers represented as strings, return multiplication of the numbers as a string.
 *
 * Note: The numbers can be arbitrarily large and are non-negative
 *
 * Tags: Math, String
 *
 * Similar Problems: (M) Add Two Numbers, (E) Plus One, (E) Add Binary
 *
 * Author: Kuang Qin
 */

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

using namespace std;

class Solution {
public:
    string multiply(string num1, string num2) {
        if ((num1 == "0") || (num2 == "0"))
        {
            return "0";
        }

        // use an integer array to store multiplication products
        int len1 = num1.size(), len2 = num2.size(), len = len1 + len2;
        int *product = new int[len]();
        for (int i = len1 - 1; i >= 0; i--)
        {
            for (int j = len2 - 1; j >= 0; j--)
            {
                product[i + j + 1] += (num1[i] - '0') * (num2[j] - '0');
            }
        }

        // gather carry info to make each digit valid
        for (int i = len - 1; i > 0; i--)
        {
            product[i - 1] += product[i] / 10;    // add carry to previous digit
            product[i] = product[i] % 10;         // set current digit
        }

        // convert int into string
        string res("");
        if (product[0] != 0)    // first position could be zero
        {
            res += product[0] + '0';
        }

        for (int i = 1; i < len; i++)
        {
            res += product[i] + '0';
        }

        return res;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    string num1("8354"), num2("7890");
    Solution mySolution;
    string res = mySolution.multiply(num1, num2);
    cout << num1 << " x " << num2 << " = " << res << endl;
    system("pause");
    return 0;
}

Add Solution for Problem 043


#include "stdafx.h"
#include "ShowModeConverter.h"

WORD ShowModeConverter::ToShowWindowFlag(const ShowMode& showMode)
{
	if (showMode == SHOW_MODE_HIDE)
	{
		return SW_HIDE;
	}

	if (showMode == SHOW_MODE_NORMAL)
	{
		return SW_NORMAL;
	}

	if (showMode == SHOW_MODE_SHOW)
	{
		return SW_SHOW;
	}

	return 0;
}

Add arg for show mode


#include "LinuxEventHandler.h"
#include "OSEventHandlerExport.h"

std::shared_ptr<ni::EventHandler> GetOSEventHandler(ni::DeviceType devices) {
	return std::make_shared<ni::LinuxEventHandler>(devices);
}

Add Linux event handler export function.


//
//  Remove_Duplicates_from_Sorted_Array_2.cpp
//  leetcode
//
//  Created by 邵建勇 on 15/5/11.
//  Copyright (c) 2015年 John Shaw. All rights reserved.
//

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

using namespace std;

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.size() == 0) {
            return 0;
        }
        if (nums.size() <= 2) {
            return (int)nums.size();
        }
        int index = 2;
        for (int i = 2; i < nums.size(); i++) {
            if (nums[index - 2] != nums[i]) {
                nums[index++] = nums[i];
            }
        }
        return index;
    }
};

Remove Duplicates from Sorted Array II


#include <common/buffer.h>

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

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

Add file missed in r574.


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <map>

using namespace std;
/*
  struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
  };
*/

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head)
    {
        map<int, int> lookup;
        ListNode* mover = head;
        if (head == NULL)
            return head;
        lookup[head->val] = 1;
        int c = 2;
        while (mover != NULL)
        {
            if ((mover->next != NULL) && (lookup.find(mover->next->val) == lookup.end()))
            {
                lookup[mover->next->val] = c;
                c++;
                mover = mover->next;
            }
            else if (mover->next == NULL)
                return head;
            else
                mover->next = mover->next->next;
        }
        return head;
    }
};

Remove Duplicates from sorted list (Made general case for unsorted list).


#include "unittest/gtest.hpp"

#include "arch/streamed_tcp.hpp"

namespace unittest {

namespace {

/* `run_in_thread_pool()` starts a RethinkDB IO layer thread pool and calls the
given function within a coroutine inside of it. */

struct starter_t : public thread_message_t {
    thread_pool_t *tp;
    boost::function<void()> fun;
    starter_t(thread_pool_t *tp, boost::function<void()> fun) : tp(tp), fun(fun) { }
    void run() {
        fun();
        tp->shutdown();
    }
    void on_thread_switch() {
        coro_t::spawn_now(boost::bind(&starter_t::run, this));
    }
};
void run_in_thread_pool(boost::function<void()> fun) {
    thread_pool_t thread_pool(1);
    starter_t starter(&thread_pool, fun);
    thread_pool.run(&starter);
}

void handle_echo_conn(boost::scoped_ptr<streamed_tcp_conn_t> &conn) {
    while (conn->get_istream().good()) {
        // Read a line and send it back
        std::string str;
        conn->get_istream() >> str;
        if (!conn->get_istream().fail()) {
            conn->get_ostream() << str << std::endl; // endl causes flush()
        }
    }
}

}   /* anonymous namespace */

void run_tcp_stream_test() {
    int port = 10000 + rand() % 20000;
    streamed_tcp_listener_t listener(port, boost::bind(&handle_echo_conn, _1));

    streamed_tcp_conn_t conn("localhost", port);
    std::string test_str = "0";
    for (int i = 0; i < 8192 / 32; ++i, test_str += std::string(32, static_cast<char>('a' + (i % 26)))) {
        conn.get_ostream() << test_str.substr(0, i);
        conn.get_ostream() << test_str.substr(i) << std::endl; // endl causes flush()
        //fprintf(stderr, "sent stuff of size %lu\n", test_str.length());
        std::string str;
        conn.get_istream() >> str;
        //fprintf(stderr, "got stuff\n");
        EXPECT_TRUE(!conn.get_istream().fail());
        EXPECT_EQ(str, test_str);
    }
    conn.get_ostream().flush();
}
TEST(TCPStreamTest, StartStop) {
    run_in_thread_pool(&run_tcp_stream_test);
}

}

Add a streamed tcp conn unit test


// Test that -Wsystem-headers works with default and custom mappings like -Werror.
// Keep run lines at the bottom for line number stability.

#ifdef IS_SYSHEADER
#pragma clang system_header

int f() { return (int)0; } // Use the old-style-cast warning as an arbitrary "ordinary" diagnostic for the purpose of testing.

#warning "custom message"

#if defined(A) || defined(B)
// expected-warning@9 {{"custom message"}}
#elif defined(C)
// expected-warning@7 {{use of old-style cast}}
// expected-warning@9 {{"custom message"}}
#elif defined(D)
// expected-error@7 {{use of old-style cast}}
// expected-error@9 {{"custom message"}}
#elif defined(E)
// expected-error@7 {{use of old-style cast}}
// expected-warning@9 {{"custom message"}}
#endif

#else
#define IS_SYSHEADER
#include __FILE__
#endif

// RUN: %clang_cc1 -verify -fsyntax-only -DA %s
// RUN: %clang_cc1 -verify -fsyntax-only -DB -Wold-style-cast %s
// RUN: %clang_cc1 -verify -fsyntax-only -DC -Wold-style-cast -Wsystem-headers %s
// RUN: %clang_cc1 -verify -fsyntax-only -DD -Wold-style-cast -Wsystem-headers -Werror %s
// RUN: %clang_cc1 -verify -fsyntax-only -DE -Wold-style-cast -Wsystem-headers -Werror=old-style-cast %s

Add a proper test for -Wsystem-headers


// Chapter 24, exercise 10: test rand(); write a program that takes two integers
// n and d and calls randint(n) d times; output the number of draws for each
// [0:n) and see if there are any obvious biases

#include<iostream>
#include<iomanip>
#include<cstdlib>
#include<ctime>
#include<map>

using namespace std;

inline int randint(int max) { return rand()%max; }

inline int randint(int min, int max) { return randint(max-min)+min; }

int main()
try
{
    while (true) {
        cout << "Enter biggest number: ";
        int n;
        cin >> n;
        cout << "Enter number of draws (0 to exit): ";
        int d;
        cin >> d;
        if (d==0) break;
        srand(time(0));

        int r = 0;
        map<int,int> histo;
        for (int i = 0; i<d; ++i)
            ++histo[randint(n)];

        for (int i= 0; i<n; ++i) {
            cout << setw(2) << i << ": ";
            for (int j = 0; j<histo[i]; ++j)
                cout << '*';
            cout << '\n';
        }
    }
}
catch (exception& e) {
    cerr << "Exception: " << e.what() << '\n';
}
catch (...) {
    cerr << "Exception\n";
}

Add Chapter 24, exercise 10


#include <bits/stdc++.h>

using namespace std;

int main()
{
    int sum = 0;
    int max_sum = array[0];
    for (int i = 0; i < length; ++i)
    {
        sum += array[i];
        sum = max(0, sum);
        max_sum = max(sum, max_sum);
    }
    return max_sum;
}

Add Maximum consecutive sum in c++


// Copyright Louis Dionne 2015
// Distributed under the Boost Software License, Version 1.0.

#include <boost/hana.hpp>
#include <boost/hana/struct_macros.hpp>

#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
using namespace boost::hana;
using namespace std::literals;

std::string quote(std::string s) { return "\"" + s + "\""; }

template <typename Xs>
std::string join(Xs&& xs, std::string sep) {
  return fold.left(intersperse(std::forward<Xs>(xs), sep), "", _ + _);
}

template <typename T>
auto to_json(T&& x) -> decltype(std::to_string(std::forward<T>(x))) {
  return std::to_string(std::forward<T>(x));
}

std::string to_json(char c) { return quote({c}); }
std::string to_json(std::string s) { return quote(s); }

template <typename T>
std::enable_if_t<models<Struct, T>(), std::string> to_json(T&& x) {
  auto as_tuple = to<Tuple>(std::forward<T>(x));

  auto json = transform(std::move(as_tuple),
    fuse([](auto name, auto&& member) {
      return quote(to<char const*>(name)) + " : " +
                to_json(std::forward<decltype(member)&&>(member));
    }));

  return "{" + join(std::move(json), ", ") + "}";
}

template <typename Xs>
std::enable_if_t<models<Sequence, Xs>(), std::string> to_json(Xs&& xs) {
  auto json = transform(std::forward<Xs>(xs), [](auto&& x) {
    return to_json(std::forward<decltype(x)&&>(x));
  });

  return "[" + join(std::move(json), ", ") + "]";
}

struct Person {
  BOOST_HANA_DEFINE_STRUCT(Person,
    (std::string, name),
    (int, age)
  );
};

int main() {
  Person joe{"Joe", 30};
  std::cout << to_json(make_tuple(1, 'c', joe));
}

Add an example of JSON generation


// Verifies that speculative loads from unions do not happen under asan.
// RUN: %clangxx_asan -O0 %s -o %t && ASAN_OPTIONS=detect_leaks=0 %run %t 2>&1
// RUN: %clangxx_asan -O1 %s -o %t && ASAN_OPTIONS=detect_leaks=0 %run %t 2>&1
// RUN: %clangxx_asan -O2 %s -o %t && ASAN_OPTIONS=detect_leaks=0 %run %t 2>&1
// RUN: %clangxx_asan -O3 %s -o %t && ASAN_OPTIONS=detect_leaks=0 %run %t 2>&1

typedef union {
  short q;
  struct {
    short x;
    short y;
    int for_alignment;
  } w;
} U;
int main() {
  char *buf = new char[2];
  buf[0] = buf[1] = 0x0;
  U *u = (U *)buf;
  return  u->q == 0 ? 0 : u->w.y;
}

Disable gvn non-local speculative loads under asan.


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

#include "config.h"
#include "core/dom/RemoteSecurityContext.h"

#include "core/frame/csp/ContentSecurityPolicy.h"
#include "platform/weborigin/SecurityOrigin.h"

namespace blink {

RemoteSecurityContext::RemoteSecurityContext()
    : SecurityContext()
{
    // RemoteSecurityContext's origin is expected to stay uninitialized until
    // we set it using replicated origin data from the browser process.
    ASSERT(!haveInitializedSecurityOrigin());

    // CSP will not be replicated for RemoteSecurityContexts, as it is moving
    // to the browser process.  For now, initialize CSP to a default
    // locked-down policy.
    setContentSecurityPolicy(ContentSecurityPolicy::create());

    // FIXME: Document::initSecurityContext has a few other things we may
    // eventually want here, such as enforcing a setting to
    // grantUniversalAccess().
}

PassRefPtr<RemoteSecurityContext> RemoteSecurityContext::create()
{
    return adoptRef(new RemoteSecurityContext());
}

void RemoteSecurityContext::setReplicatedOrigin(PassRefPtr<SecurityOrigin> origin)
{
    // FIXME: Currently, replicated security origins are passed only at
    // RemoteFrame creation time.  Eventually, this class will also need to
    // handle origin updates to handle cases like setting document.domain, but
    // for now, check that this is the first and only time we are setting the
    // origin.
    ASSERT(!haveInitializedSecurityOrigin());
    setSecurityOrigin(origin);
}

} // namespace blink

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

#include "config.h"
#include "core/dom/RemoteSecurityContext.h"

#include "core/frame/csp/ContentSecurityPolicy.h"
#include "platform/weborigin/SecurityOrigin.h"

namespace blink {

RemoteSecurityContext::RemoteSecurityContext()
    : SecurityContext()
{
    // RemoteSecurityContext's origin is expected to stay uninitialized until
    // we set it using replicated origin data from the browser process.
    ASSERT(!haveInitializedSecurityOrigin());

    // CSP will not be replicated for RemoteSecurityContexts, as it is moving
    // to the browser process.  For now, initialize CSP to a default
    // locked-down policy.
    setContentSecurityPolicy(ContentSecurityPolicy::create());

    // FIXME: Document::initSecurityContext has a few other things we may
    // eventually want here, such as enforcing a setting to
    // grantUniversalAccess().
}

PassRefPtr<RemoteSecurityContext> RemoteSecurityContext::create()
{
    return adoptRef(new RemoteSecurityContext());
}

void RemoteSecurityContext::setReplicatedOrigin(PassRefPtr<SecurityOrigin> origin)
{
    setSecurityOrigin(origin);
}

} // namespace blink

Allow replicated origins to be updated.


//===-- SelectionDAGPrinter.cpp - Implement SelectionDAG::viewGraph() -----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This implements the SelectionDAG::viewGraph method.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/SelectionDAG.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/Function.h"
#include "llvm/Support/GraphWriter.h"
#include <fstream>
using namespace llvm;

/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
/// rendered using 'dot'.
///
void SelectionDAG::viewGraph() {
  std::string Filename = "/tmp/dag." +
    getMachineFunction().getFunction()->getName() + ".dot";
  std::cerr << "Writing '" << Filename << "'... ";
  std::ofstream F(Filename.c_str());

  if (!F) {
    std::cerr << "  error opening file for writing!\n";
    return;
  }

  WriteGraph(F, this);
  F.close();
  std::cerr << "\n";

  std::cerr << "Running 'dot' program... " << std::flush;
  if (system(("dot -Tps -Nfontname=Courier -Gsize=7.5,10 " + Filename
              + " > /tmp/dag.tempgraph.ps").c_str())) {
    std::cerr << "Error running dot: 'dot' not in path?\n";
  } else {
    std::cerr << "\n";
    system("gv /tmp/dag.tempgraph.ps");
  }
  system(("rm " + Filename + " /tmp/dag.tempgraph.ps").c_str());
}

Implement initial selectiondag printing support. This gets us a nice graph with no labels! :)


// RUN: %clangxx_asan -O0 -fsanitize-address-use-after-scope %s -o %t

// RUN: not %run %t 'A' 2>&1 | FileCheck %s
// RUN: not %run %t 'B' 2>&1 | FileCheck %s

// Missing lifetime markers in test_a
// https://bugs.llvm.org/show_bug.cgi?id=34353
// XFAIL: *

struct B {
  B() : p('B') {}
  char p;
};

struct C {
  const char *p;
  explicit C(const char *c) : p(c) {}
  C(const B &b) : p(&b.p) {} // NOLINT
};

struct A {
  char p;
  explicit A() : p('C') {}
  const operator C() const { return C(&p); }
};

volatile char r;
void test_a() {
  C s = A();
  r = *s.p;
}

void test_b() {
  C s = B();
  r = *s.p;
}

int main(int argc, char **argv) {
  switch (argv[1][0]) {
  case 'A':
    test_a();
    return 0;
  case 'B':
    test_b();
    return 0;
  }
  return 1;
}

// CHECK: ERROR: AddressSanitizer: stack-use-after-scope

Add use-after-scope test which fails because of bug in clang


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

#include "chrome/browser/apps/app_browsertest_util.h"
#include "extensions/test/extension_test_message_listener.h"

// This class of BrowserTests is a helper to create tests related to crashes in
// Chrome Apps. To be tested, the app will have to be placed as any other test
// app (see PlatformAppBrowserTest) and will need to send a "Done" message back.
// When the "Done" message is received, the test succeed. If it is not, it is
// assumed that Chrome has crashed and the test will anyway fail.
//
// The entry in this file should be something like:
// IN_PROC_BROWSER_TEST_F(AppCrashTest, <TEST_NAME>) {
//   ASSERT_TRUE(RunAppCrashTest("<DIRECTORY_TEST_NAME>"));
// }

class AppCrashTest : public extensions::PlatformAppBrowserTest {
public:
 void RunAppCrashTest(const char* name) {
   LoadAndLaunchPlatformApp(name, "Done");
  }
};

IN_PROC_BROWSER_TEST_F(AppCrashTest, HiddenWindows) {
  RunAppCrashTest("crashtest_hidden_windows");
}

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

#include "chrome/browser/apps/app_browsertest_util.h"
#include "extensions/test/extension_test_message_listener.h"

// This class of BrowserTests is a helper to create tests related to crashes in
// Chrome Apps. To be tested, the app will have to be placed as any other test
// app (see PlatformAppBrowserTest) and will need to send a "Done" message back.
// When the "Done" message is received, the test succeed. If it is not, it is
// assumed that Chrome has crashed and the test will anyway fail.
//
// The entry in this file should be something like:
// IN_PROC_BROWSER_TEST_F(AppCrashTest, <TEST_NAME>) {
//   ASSERT_TRUE(RunAppCrashTest("<DIRECTORY_TEST_NAME>"));
// }

class AppCrashTest : public extensions::PlatformAppBrowserTest {
public:
 void RunAppCrashTest(const char* name) {
   LoadAndLaunchPlatformApp(name, "Done");
  }
};

// Disabling flaky test on ASAN,  crbug.com/469249
#if !defined(ADDRESS_SANITIZER)
IN_PROC_BROWSER_TEST_F(AppCrashTest, HiddenWindows) {
  RunAppCrashTest("crashtest_hidden_windows");
}
#endif

Disable a flaky test. See crbug.com/469249.


//===- InlineAlways.cpp - Code to perform simple function inlining --------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements bottom-up inlining of functions into callees.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "inline"
#include "llvm/CallingConv.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Module.h"
#include "llvm/Type.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/InlinerPass.h"
#include "llvm/Transforms/Utils/InlineCost.h"
#include "llvm/ADT/SmallPtrSet.h"

using namespace llvm;

namespace {

  // AlwaysInliner only inlines functions that are mark as "always inline".
  class VISIBILITY_HIDDEN AlwaysInliner : public Inliner {
    // Functions that are never inlined
    SmallPtrSet<const Function*, 16> NeverInline;
    InlineCostAnalyzer CA;
  public:
    // Use extremely low threshold.
    AlwaysInliner() : Inliner(&ID, -2000000000) {}
    static char ID; // Pass identification, replacement for typeid
    int getInlineCost(CallSite CS) {
      return CA.getInlineCost(CS, NeverInline);
    }
    float getInlineFudgeFactor(CallSite CS) {
      return CA.getInlineFudgeFactor(CS);
    }
    virtual bool doInitialization(CallGraph &CG);
  };
}

char AlwaysInliner::ID = 0;
static RegisterPass<AlwaysInliner>
X("always-inline", "Inliner that handles always_inline functions");

Pass *llvm::createAlwaysInlinerPass() { return new AlwaysInliner(); }

// doInitialization - Initializes the vector of functions that have not
// been annotated with the "always inline" attribute.
bool AlwaysInliner::doInitialization(CallGraph &CG) {

  Module &M = CG.getModule();

  for (Module::iterator I = M.begin(), E = M.end();
       I != E; ++I)
    if (!I->isDeclaration() && I->getNotes() != FN_NOTE_AlwaysInline)
      NeverInline.insert(I);

  return false;
}

Add custom inliner that handles only functions that are marked as always_inline.


#include "Inputs/HeaderWithSymbol.h"
#define FOO int bar;
FOO

int foo;

// RUN: not clang-rename -new-name=qux -offset=259 %s -- 2>&1 | FileCheck %s
// CHECK-NOT: CHECK
// CHECK: error: SourceLocation in file {{.*}}InvalidOffset.cpp at offset 259 is invalid

Add test case for r287758.


// REQUIRES: shell
// RUN: rm -rf %t
// RUN: mkdir -p %t

// This is a reproducer for PR37091.
//
// Verify that no temporary files are left behind by the clang-tidy invocation.

// RUN: env TMPDIR=%t TEMP=%t TMP=%t clang-tidy %s -- --target=mips64
// RUN: rmdir %t

Clean up tmp files when deleting Compilation objects


#include "tree_node.h"
#include "gtest\gtest.h"

/*
 This file will include all the test for the TreeNode class.
*/

TEST(TreeNodeTest, AddChild) {
	//Initialize a node with some children.
	TreeNode<int> focusNode;
	TreeNode<int> child1;
	TreeNode<int> child2;

	focusNode.addChild(&child1);
	focusNode.addChild(&child2);
	EXPECT_EQ(focusNode.getChildren().size(), 2);
}

TEST(TreeNodeTest, RemoveChild) {
	//Initialize a node with some children then remove them.
	TreeNode<int> focusNode;
	TreeNode<int> child1;
	TreeNode<int> child2;

	focusNode.addChild(&child1);
	focusNode.addChild(&child2);

	focusNode.removeChild(1);
	EXPECT_EQ(focusNode.getChildren().size(), 1);

	focusNode.removeChild(0);
	EXPECT_EQ(focusNode.getChildren().size(), 0);

	EXPECT_NO_THROW(focusNode.removeChild(0));
}

TEST(TreeNodeTest, AddParent) {
	//Initialize a node with a parent.
	TreeNode<int> root;
	TreeNode<int> focusNode;

	EXPECT_EQ(focusNode.getParent(), nullptr);

	focusNode.setParent(&root);
	EXPECT_EQ(focusNode.getParent(), &root);
}

TEST(TreeNodeTest, RemoveParent) {
	//Initialize a node with a parent and then remove it.
	TreeNode<int> root;
	TreeNode<int> focusNode;

	focusNode.setParent(&root);
	EXPECT_EQ(focusNode.getParent(), &root);

	focusNode.removeParent();
	EXPECT_EQ(focusNode.getParent(), nullptr);
}

TEST(TreeNodeTest, Value) {
	//Initialize a node with a value.
	TreeNode<int> focusNode;

	focusNode.setValue(1);
	EXPECT_EQ(focusNode.getValue(), 1);
}

Add test for the treenode.


// Chapter 25, exercise 5: write an infinite loop and execute it

#include<iostream>
#include<exception>

using namespace std;

int main()
try
{
    while (true)
        cout << "Looping!\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
    return 2;
}

Add Chapter 25, exercise 5


#include <stdio.h>

int main(void)
{
    int N;

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

    /* Get the largest number in the power of two, which satisfies less than or equal to N */
    int v = 1;

    while(v <= N) v = v << 1;
    v = v >> 1;

    /* Calculate and print to screen */
    while(v > 0)
    {
        if(N >= v)
        {
            N -= v;
            putchar('1');
        }
        else
            putchar('0');

        v /= 2;
    }
    putchar('\n');

    return 0;
}

Add a solution of prob 3


// Read lines from a stream

#include <sstream>
#include <string>

int main()
{
	std::istringstream stream{"This stream\n"
	                          "contains many\n"
	                          "lines.\n"};
	std::string line;

	while (std::getline(stream, line)) {
		// Process line
	}
}

// Process the contents of an input stream line-by-line.
//
// We use a [`std::istringstream`](cpp/io/basic_istringstream) as an
// example input stream ([8-10]) containing multiple lines (separated
// by `\n`). This stream could be replaced with
// [`std::cin`](cpp/io/cin) or a file stream, for example. On [11], we
// introduce a [`std::string`](cpp/string/basic_string) into which we
// will read each line of the stream.
//
// On [13-15], we use a `while` loop to iterate over each line of the
// stream. The condition of the loop is a call to
// [`std::getline`](cpp/string/getline), which extracts lines from
// `stream` into `line`. The result of this call will evaluate to
// `false` only when the extraction fails, such as when there are no
// lines left to extract.

Add "read lines from stream" sample


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

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

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

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

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

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

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

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

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

Allow specific files and multiple inputs for picture testing tools.


class Solution {
public:
    bool isValidSerialization(string preorder) {
        int diff = 1;
        std::string temp = "";
        for (const auto &c : preorder) {
            if (c == ',') {
                --diff;
                if (diff < 0)
                    return false;
                if (temp != "#")
                    diff += 2;
                temp = "";
            } else {
                temp += c;
            }
        }
        --diff;
        if (diff < 0)
            return false;
        if (temp != "#")
            diff += 2;
        return diff == 0;
    }
};

Verify Preorder Serialization of a Binary Tree


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

class BinaryCode {
public:
  vector <string> decode(string message) {
    vector <string> result;
    unsigned len = message.length() + 2;
    int P[len];
    int Q[len];
    Q[0] = Q[len-1] = 0;
    for (unsigned i = 0; i < message.length(); i++) {
      Q[i+1] = message[i] - '0';
    }

    for (int init = 0; init <= 1; init++) {
      P[0] = 0;
      P[1] = init;
      for (unsigned i = 2; i < len; i++) {
        P[i] = Q[i-1] - P[i-1] - P[i-2];
      }

      string orig;
      if (P[len-1] != 0) {
        orig = "NONE";
      } else {
        for (unsigned i = 1; i <= message.length(); i++) {
          //cout << char('0' + P[i]) << " added..." << endl;
          if (P[i] == 0 || P[i] == 1) {
            orig += ('0' + P[i]);
          } else {
            orig = "NONE";
            break;
          }
        }
      }

      result.push_back(orig);
    }
    return result;
  }

  void disp(string message) {
    cout << decode(message)[0] << endl
         << decode(message)[1] << endl;
  }
};

int main() {
  BinaryCode bc;
  bc.disp("123210122");
  bc.disp("22111");
}

Solve SRM 144, Div 2, Problem BinaryCode


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

#include <bits/stdc++.h>

typedef std::pair<int, int> IntPair;
typedef std::vector<IntPair> IntPairs;

int vectorMul(IntPair a, IntPair b) {
    return a.first * b.second - b.first * a.second;
}

int scalarMul(IntPair a, IntPair b) {
    return a.first * b.first + a.second * b.second;
}

int main() {
    // number of vertices and coordinates of starting point
    int N, x, y;
    std::cin >> N >> x >> y;
    // vectors for all vertices (starting point --> curr vertex)
    IntPairs vectors;
    for (int i = 0; i < N; i++) {
        // polygon vertex
        int vx, vy;
        std::cin >> vx >> vy;
        vectors.push_back(IntPair(vx - x, vy - y));
    }
    double sum = 0;
    for (int i = 0; i < N; i++) {
        IntPair v1 = vectors[i];
        IntPair v2 = vectors[(i + 1) % N];
        sum += std::atan2(vectorMul(v1, v2), scalarMul(v1, v2));
    }
    bool outside = (std::fabs(sum) < 1e-9);
    std::cout << (outside ? "NO" : "YES") << std::endl;
    return 0;
}

Add PIP (point in polygon) problem


// Decorator (compile-time)

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

template <typename Foo>
class foo_decorator
{
	public:
		foo_decorator(Foo& f)
			: f{f}
		{ }

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

	private:
		Foo& f;
};

template <typename Foo>
void bar(Foo& f)
{
	f.do_work();
}

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

	bar(decorated_f);
}

// Wrap a class with a decorator to extend its functionality.
//
// On [3-8], we define the class that we wish to decorate,
// `foo_concrete`.
//
// The `foo_decorator` class template, on [10-26], implements the
// same interface as `foo_concrete` and wraps any other object with
// that interface, passed in to the constructor by reference on
// [14-16]. A `foo_decorator` object can be used anywhere a
// `foo_concrete` would be expected, but also decorates its member
// functions. That is, the `foo_decorator::do_work` function ([18-22])
// calls the wrapped object's `do_work` function, while also doing
// some extra work.
//
// To demonstrate, we wrap a `foo_concrete` with a `foo_decorator` on
// [36-37], and pass it to the `bar` function template on [39], which
// expects any object that implements the `do_work` function. In this
// case, the call to `do_work` on [31] will be decorated.

Add "compile-time decorator pattern" sample


#include "../../test.h"
#include "../../func/func-common.h"
#include <iostream>

TEST_CASE( "sensor get_option memory leak", "[live]" )
{
    // running this test with the following command:
    // `valgrind --leak-check=yes --show-leak-kinds=all --track-origins=yes ./unit-tests/build/utilities/memory/test-sensor-option/test-utilities-memory-sensor-option 2>&1 | grep depends`
    // should print nothing!

    auto devices = find_devices_by_product_line_or_exit(RS2_PRODUCT_LINE_DEPTH);
    if (devices.size() == 0) return;
    auto dev = devices[0];

    auto depth_sens = dev.first< rs2::depth_sensor >();
    // float option_value(depth_sens.get_option(RS2_OPTION_EXPOSURE));
    float option_value(depth_sens.get_option(RS2_OPTION_ENABLE_AUTO_EXPOSURE));

    std::cout << "Declare: BOOL::" << option_value << std::endl;
}

Add test for memory leak to be run with valgrind


/**
 * \file
 * \brief chip::lowLevelInitialization() implementation for STM32F7
 *
 * \author Copyright (C) 2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/chip/lowLevelInitialization.hpp"

namespace distortos
{

namespace chip
{

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

void lowLevelInitialization()
{

}

}	// namespace chip

}	// namespace distortos

Add empty chip::lowLevelInitialization() for STM32F7


// Copyright © 2012 Lénaïc Bagnères, hnc@singularity.fr

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

//#include <hnc/header_you_test.hpp>
#include <hnc/test.hpp>
#include <hnc/to_string.hpp>

int main()
{
	int nb_test = 0;

	// Do test
	++nb_test;
	{
		// Do test
		nb_test -= hnc::test::warning(true, "Return 1 if the condition is true, 0 else\n");
	}
	std::cout << std::endl;

	hnc::test::warning(nb_test == 0, "hnc::header_you_test: " + hnc::to_string(nb_test) + " test fail!\n");

	return nb_test;
}

Add test file template (to create a new test)


#include <iostream>
#include <vector>
#include <limits>
#include <algorithm>

void print(std::vector<int> &solutions) {
  std::for_each(solutions.begin(), solutions.end(), [](auto item) {
      std::cout << item << " ";
    });
  std::cout << "\n";
}

class MinNumberOfCoints {
public:
  int min(const int val) {
    std::vector<int> solutions(val+1, 0);
    for (int idx = 1; idx <= val; ++idx) {
      int count = idx;
      for (size_t coinIdx = 0; coinIdx < Coins.size(); ++coinIdx) {
        auto currentCoin = Coins[coinIdx];
        if (idx > currentCoin) {
          count = std::min(count, 1 + solutions[idx - currentCoin]);
        } else if (idx == currentCoin) {
          count = std::min(count, 1);
        }
      }
      solutions[idx] = count;
    }

    // For debugging purpose.
    // print(solutions);

    return solutions[val];
  }

private:
  std::vector<int> Coins{1, 5, 8, 10, 15, 25};
};

int main() {
  MinNumberOfCoints solver;

  {
    int value = 5;
    std::cout << "Minimum number of coins for " << value << " is " << solver.min(value) << "\n";
  }

  {
    int value = 9;
    std::cout << "Minimum number of coins for " << value << " is " << solver.min(value) << "\n";
  }

  {
    int value = 21;
    std::cout << "Minimum number of coins for " << value << " is " << solver.min(value) << "\n";
  }
}

Add solution for the minimum number of coins problem.


/**
 * link: https://leetcode.com/problems/merge-two-sorted-lists/
 * Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
 */

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution
{
  public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
    {
        if (l1 == NULL)
            return l2;
        if (l2 == NULL)
            return l1;

        ListNode *head;
        ListNode *current = head = NULL;
        while (l1 && l2)
        {
            if (l1->val <= l2->val)
            {
                if (current == NULL)
                {
                    current = head = l1;
                }
                else
                {
                    current->next = l1;
                    current = current->next;
                }
                l1 = l1->next;
            }
            else
            {
                if (current == NULL)
                {
                    current = head = l2;
                }
                else
                {
                    current->next = l2;
                    current = current->next;
                }
                l2 = l2->next;
            }
            current->next = NULL;
        }

        if (l2)
            current->next = l2;
        if (l1)
            current->next = l1;
        return head;
    }
};

Add solution for 21. Merge Two Sorted Lists.


#include "wtf/event.h"

#include <fstream>

#include "testing/base/public/gunit.h"

namespace wtf {
namespace {

class EventTest : public ::testing::Test {
 protected:
  void TearDown() override {}

  EventDefinition CreateEventDefinition(const char *name_spec) {
    return EventDefinition::Create<int, const char*>(
        /*wire_id=*/0, EventClass::kScoped, /*flags=*/0, name_spec);
  }
};

TEST_F(EventTest, CheckNameSpecParsing) {
  std::string output;

  auto event = CreateEventDefinition("MyFunc");
  event.AppendName(&output);
  EXPECT_EQ(output, "MyFunc");
  output.clear();
  event.AppendArguments(&output);
  EXPECT_EQ(output, "int32 a0, ascii a1");

  output.clear();
  event = CreateEventDefinition("MyNamespace::MyClass::MyFunc");
  event.AppendName(&output);
  EXPECT_EQ(output, "MyNamespace#MyClass#MyFunc");
  output.clear();
  event.AppendArguments(&output);
  EXPECT_EQ(output, "int32 a0, ascii a1");

  output.clear();
  event = CreateEventDefinition("MyClass::MyFunc2:  arg1 , arg2");
  event.AppendName(&output);
  EXPECT_EQ(output, "MyClass#MyFunc2");
  output.clear();
  event.AppendArguments(&output);
  EXPECT_EQ(output, "int32 arg1, ascii arg2");

  output.clear();
  event = CreateEventDefinition("MyFunc2:  arg1 , arg2");
  event.AppendName(&output);
  EXPECT_EQ(output, "MyFunc2");
  output.clear();
  event.AppendArguments(&output);
  EXPECT_EQ(output, "int32 arg1, ascii arg2");

  output.clear();
  event = CreateEventDefinition("MyFunc3:  arg1");
  event.AppendName(&output);
  EXPECT_EQ(output, "MyFunc3");
  output.clear();
  event.AppendArguments(&output);
  EXPECT_EQ(output, "int32 arg1, ascii a1");
}

}  // namespace
}  // namespace wtf

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

Add test for event.cc changes to name_spec parsing


// RUN: rm -rf %t
// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t -verify %s
// expected-no-diagnostics

#pragma clang module build sys_types
module sys_types {}
#pragma clang module contents
#pragma clang module begin sys_types
extern "C" {
  typedef union { bool b; } pthread_mutex_t;
}
#pragma clang module end
#pragma clang module endbuild

typedef union { bool b; } pthread_mutex_t;
#pragma clang module import sys_types

const pthread_mutex_t *m;

Add a regression test for merging anon decls in extern C contexts.


// Shared ownership

#include <memory>
#include <utility>

struct foo {};

void func(std::shared_ptr<foo> obj)
{ }

int main()
{
	std::shared_ptr<foo> obj = std::make_shared<foo>();
	pass_shared_ownership(obj);
}

// Share ownership of a dynamically allocated object with another
// unit of code.
//
// On [13], we create a [`std::shared_ptr`](cpp/memory/shared_ptr)
// which has ownership of a dynamically allocated `foo` object
// (allocated with the [`std::make_shared`](cpp/memory/shared_ptr/make_shared)
// utility function). [!14] then demonstrates sharing ownership of this
// object with a function. That is, both `main` and `func` have access
// to the same `foo` object. When ownership of an object is shared, it
// will only be destroyed when all `std::shared_ptr`s owning it are
// destroyed.
//
// In other cases, you may instead wish to [transfer unique ownership
// of an object](/common-tasks/memory-management/transfer-ownership-of-object.html).

// Shared ownership

#include <memory>
#include <utility>

struct foo {};

void func(std::shared_ptr<foo> obj)
{ }

int main()
{
	std::shared_ptr<foo> obj = std::make_shared<foo>();
	func(obj);
}

// Share ownership of a dynamically allocated object with another
// unit of code.
//
// On [13], we create a [`std::shared_ptr`](cpp/memory/shared_ptr)
// which has ownership of a dynamically allocated `foo` object
// (allocated with the [`std::make_shared`](cpp/memory/shared_ptr/make_shared)
// utility function). [!14] then demonstrates sharing ownership of this
// object with a function. That is, both `main` and `func` have access
// to the same `foo` object. When ownership of an object is shared, it
// will only be destroyed when all `std::shared_ptr`s owning it are
// destroyed.
//
// In other cases, you may instead wish to [transfer unique ownership
// of an object](/common-tasks/memory-management/transfer-ownership-of-object.html).

Correct shared ownership sample code