#include <UnitTest++.h>

// Unit tests for vec classes

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

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/operations.hpp>
namespace bf = boost::filesystem;

struct FileFixture
{
   FileFixture()
   {
      test_file = bf::path("test_file.osb");
      bf::remove(test_file);
   }

   ~FileFixture()
   {
      bf::remove(test_file);
   }

   bf::path test_file;
};

TEST_FIXTURE(FileFixture, CreateOSBFile)
{
   OSG::NodePtr n = OSG::Node::create();

   CHECK(!bf::exists(test_file));
   OSG::SceneFileHandler::the()->write(n, test_file.native_file_string().c_str());
   CHECK(bf::exists(test_file));

   OSG::NodePtr new_n =
      OSG::SceneFileHandler::the()->read(test_file.native_file_string().c_str());
   CHECK(new_n != OSG::NullFC);
}

TEST_FIXTURE(FileFixture, TestNameRetention)
{
   std::string start_name("node");
   OSG::NodePtr n = OSG::Node::create();
   OSG::setName(n, start_name);

   CHECK(!bf::exists(test_file));
   OSG::SceneFileHandler::the()->write(n, test_file.native_file_string().c_str());
   CHECK(bf::exists(test_file));

   OSG::NodePtr new_n =
      OSG::SceneFileHandler::the()->read(test_file.native_file_string().c_str());
   CHECK(new_n != OSG::NullFC);
   CHECK(OSG::getName(new_n) != NULL);
   std::string cur_name = std::string(OSG::getName(new_n));

   CHECK(cur_name == start_name);
}

Add test to demonstrate bug where names are not loaded by the osb loader.

git-svn-id: 6c7e10cdde2c115f53707ba8ec4efe535f92d362@241 4683daeb-ad0f-0410-a623-93161e962ae5


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

#include "../Fuzz.h"

void fuzz_NullGLCanvas(Fuzz* f);

extern "C" {

    // Set default LSAN options.
    const char *__lsan_default_options() {
        // Don't print the list of LSAN suppressions on every execution.
        return "print_suppressions=0";
    }

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

Add libFuzzer style fuzzer for NullGLCanvas for use on OSS-Fuzz.

Bug: 827225
Change-Id: Icb30c0c234326340213af0cc402a4124dd0336b3
Reviewed-on: https://skia-review.googlesource.com/117150
Commit-Queue: Mike Klein <14574f09dfa9b4e14759b88c3426a495a0e627b0@chromium.org>
Reviewed-by: Mike Klein <14574f09dfa9b4e14759b88c3426a495a0e627b0@chromium.org>


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod = 1e9 + 7;

int a[2010];
int dp[2010][2010];

int main(void) {
    int n, h;
    scanf("%d %d", &n, &h);
    for (int i = 1; i <= n; i++)
        scanf("%d", &a[i]);

    // fill up the base cases
    dp[1][0] = (a[1] == h || a[1]  + 1 == h) ? 1 : 0; // left alone OR opened and closed
    dp[1][1] = (a[1] + 1 == h) ? 1 : 0; // opened and did not close

    for (int i = 2; i <= n; i++) {
        // the value of open must satisfy one of the following equations
        // a[i] + open = h     => open = h - a[i];
        // a[i] + open + 1 = h => open = h - a[i] - 1;
        for (int open = max(h - a[i] - 1, 0); open <= min(h - a[i], i); open++) {
            if (a[i] + open == h) {
                // do nothing
                dp[i][open] = (dp[i][open] + dp[i - 1][open]) % mod;

                // close one
                if (open > 0)
                    dp[i][open] = (dp[i][open] + dp[i - 1][open - 1]) % mod;

            }
            else if (a[i] + open + 1 == h) {
                // open one here and close it as well
                dp[i][open] = (dp[i][open] + dp[i - 1][open]) % mod;

                // have open + 1 from earlier and close one of them
                dp[i][open] = (dp[i][open] + (dp[i - 1][open + 1] * (ll)(open + 1)) % mod) % mod;

                // have open from earlier, close one of them and open your own
                dp[i][open] = (dp[i][open] + (dp[i - 1][open] * (ll)open) % mod) % mod;
            }
        }
    }
    printf("%d\n", dp[n][0]);
    return 0;
}

Increase Sequence - 466D - Codeforces

Increase Sequence - 466D - Codeforces

http://codeforces.com/contest/466/problem/D

Great problem. The dynamic programming solution involved thinking
of transitions as opening or closing segments and the state was
(i, open) where
    i:      the index at which we are
    open:   the number of still open segments we have.

Had to look at the solution of this one. Loved the problem though,
awesome.


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

template<typename T>
T kadane_method(const std::vector<T>& v){
	T ret = 0;
	std::for_each(v.begin(), v.end(), [c_max = 0, max = 0, &ret](T m) mutable {
		c_max  = c_max + m;
		// the ccurrent max is a negative number,
		// we can't use that cuz it will not give us
		// the maximum sum
		if (c_max < 0) c_max = 0;
		// we have to check if there is a new max
		// if c_max is greater than it means there is a new max so we
		// have to use that instead.
		if (max < c_max) max = c_max;

		//std::cout << "m: " << m << " c_max: "
		//			<< c_max << " max: " << max << '\n';
		ret = max;
	});

	return ret;
}

int main() {
	std::cout << kadane_method<int>({-2, -3, 4, -1, -2, 1, 5, -3}) << '\n';
	std::cout << kadane_method<int>({-2, 1, -3, 4, -1, 2, 1, -5, 4}) << '\n';
	std::cout << kadane_method<int>({2, 3, 7, -5, -1, 4, -10}) << '\n';
}

Add max sub array implementaion in C++

Add max sub array implementaion in C++


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

/*
 psimpl-c
 Copyright (c) 2013 Jamie Bullock <jamie@jamiebullock.com>

 Based on psimpl
 Copyright (c) 2010-2011 Elmar de Koning <edekoning@gmail.com>
 */

#include "psimpl-c.h"
#include "psimpl/psimpl.h"

#include <stdio.h>

double *psimpl_simplify_douglas_peucker(
                                        psimpl_LineDimension dimensions,
                                        uint64_t points,
                                        double tolerance,
                                        double *original_points,
                                        double *simplified_points
                                        )
{
    double *original_end = original_points + (points * dimensions);

    switch (dimensions)
    {
        case psimpl_LineDimension_1D:
            return psimpl::simplify_douglas_peucker <1> (original_points, original_end, tolerance, simplified_points);

        case psimpl_LineDimension_2D:
            return psimpl::simplify_douglas_peucker <2> (original_points, original_end, tolerance, simplified_points);

        case psimpl_LineDimension_3D:
            return psimpl::simplify_douglas_peucker <3> (original_points, original_end, tolerance, simplified_points);

        default:
            fprintf(stderr, "Error: invalid dimensions: %d\n", dimensions);
            return  NULL;
            break;
    }
}

Add basic wrapper for Douglas-Peucker

Add basic wrapper for Douglas-Peucker


//===- SimplifyCFG.cpp - CFG Simplification Routines -------------*- C++ -*--=//
//
// This file provides several routines that are useful for simplifying CFGs in
// various ways...
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/SimplifyCFG.h"
#include "llvm/BasicBlock.h"
#include "llvm/Method.h"
#include "llvm/iTerminators.h"
#include "llvm/iOther.h"
#include "llvm/Type.h"

// UnifyAllExitNodes - Unify all exit nodes of the CFG by creating a new
// BasicBlock, and converting all returns to unconditional branches to this
// new basic block.  The singular exit node is returned.
//
// If there are no return stmts in the Method, a null pointer is returned.
//
BasicBlock *cfg::UnifyAllExitNodes(Method *M) {
  vector<BasicBlock*> ReturningBlocks;

  // Loop over all of the blocks in a method, tracking all of the blocks that
  // return.
  //
  for(Method::iterator I = M->begin(), E = M->end(); I != E; ++I)
    if ((*I)->getTerminator()->getInstType() == Instruction::Ret)
      ReturningBlocks.push_back(*I);

  if (ReturningBlocks.size() == 0)
    return 0;                          // No blocks return
  else if (ReturningBlocks.size() == 1)
    return ReturningBlocks.front();    // Already has a single return block

  // Otherwise, we need to insert a new basic block into the method, add a PHI
  // node (if the function returns a value), and convert all of the return
  // instructions into unconditional branches.
  //
  BasicBlock *NewRetBlock = new BasicBlock("", M);

  if (M->getReturnType() != Type::VoidTy) {
    // If the method doesn't return void... add a PHI node to the block...
    PHINode *PN = new PHINode(M->getReturnType());
    NewRetBlock->getInstList().push_back(PN);

    // Add an incoming element to the PHI node for every return instruction that
    // is merging into this new block...
    for (vector<BasicBlock*>::iterator I = ReturningBlocks.begin(),
                                       E = ReturningBlocks.end(); I != E; ++I)
      PN->addIncoming((*I)->getTerminator()->getOperand(0), *I);

    // Add a return instruction to return the result of the PHI node...
    NewRetBlock->getInstList().push_back(new ReturnInst(PN));
  } else {
    // If it returns void, just add a return void instruction to the block
    NewRetBlock->getInstList().push_back(new ReturnInst());
  }

  // Loop over all of the blocks, replacing the return instruction with an
  // unconditional branch.
  //
  for (vector<BasicBlock*>::iterator I = ReturningBlocks.begin(),
                                     E = ReturningBlocks.end(); I != E; ++I) {
    delete (*I)->getInstList().pop_back();  // Remove the return insn
    (*I)->getInstList().push_back(new BranchInst(NewRetBlock));
  }
  return NewRetBlock;
}

Add method to unify all exit nodes of a method

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


#include "generator/geo_objects/geo_objects_filter.hpp"

#include "generator/osm_element_helpers.hpp"

#include "indexer/ftypes_matcher.hpp"

using namespace feature;

namespace generator
{
namespace geo_objects
{
bool GeoObjectsFilter::IsAccepted(OsmElement const & element)
{
  return osm_element::IsBuilding(element) || osm_element::HasHouse(element) || osm_element::IsPoi(element);
}

bool GeoObjectsFilter::IsAccepted(FeatureBuilder const & feature)
{
  if (!feature.GetParams().IsValid())
    return false;

  return IsBuilding(feature) || HasHouse(feature) || IsPoi(feature);
}

// static
bool GeoObjectsFilter::IsBuilding(FeatureBuilder const & fb)
{
  auto const & checker = ftypes::IsBuildingChecker::Instance();
  return checker(fb.GetTypes());
}

// static
bool GeoObjectsFilter::HasHouse(FeatureBuilder const & fb)
{
  return !fb.GetParams().house.IsEmpty();
}

// static
bool GeoObjectsFilter::IsPoi(FeatureBuilder const & fb)
{
  auto const & poiChecker = ftypes::IsPoiChecker::Instance();
  return poiChecker(fb.GetTypes());
}
}  // namespace geo_objects
}  // namespace generator

#include "generator/geo_objects/geo_objects_filter.hpp"

#include "generator/osm_element_helpers.hpp"

#include "indexer/ftypes_matcher.hpp"

using namespace feature;

namespace generator
{
namespace geo_objects
{
bool GeoObjectsFilter::IsAccepted(OsmElement const & element)
{
  return osm_element::IsBuilding(element) || osm_element::HasHouse(element) || osm_element::IsPoi(element);
}

bool GeoObjectsFilter::IsAccepted(FeatureBuilder const & feature)
{
  if (!feature.GetParams().IsValid())
    return false;

  if (feature.IsLine())
    return false;

  return IsBuilding(feature) || HasHouse(feature) || IsPoi(feature);
}

// static
bool GeoObjectsFilter::IsBuilding(FeatureBuilder const & fb)
{
  auto const & checker = ftypes::IsBuildingChecker::Instance();
  return checker(fb.GetTypes());
}

// static
bool GeoObjectsFilter::HasHouse(FeatureBuilder const & fb)
{
  return !fb.GetParams().house.IsEmpty();
}

// static
bool GeoObjectsFilter::IsPoi(FeatureBuilder const & fb)
{
  auto const & poiChecker = ftypes::IsPoiChecker::Instance();
  return poiChecker(fb.GetTypes());
}
}  // namespace geo_objects
}  // namespace generator

Fix features filter: ignore lines

[generator:geo_objects] Fix features filter: ignore lines


// Chapter 20, Exercise 04: Find and fix the errors in the Jack-and-Jill example
// from 20.3.1 by using STL techniques throughout.

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

double* get_from_jack(int* count)
{
    string ifname = "pics_and_txt/chapter20_ex02_in1.txt";
    ifstream ifs(ifname.c_str());
    if (!ifs) error("Can't open input file ",ifname);

    // Elegantly read input into vector first
    vector<double> v;
    double d;
    while (ifs>>d) v.push_back(d);

    *count = v.size();
    double* data = new double[*count];
    for (int i = 0; i<v.size(); ++i)
        data[i] = v[i];

    return data;
}

vector<double>* get_from_jill()
{
    string ifname = "pics_and_txt/chapter20_ex02_in2.txt";
    ifstream ifs(ifname.c_str());
    if (!ifs) error ("Can't open input file ",ifname);

    vector<double>* v = new vector<double>;
    double d;
    while (ifs>>d) (*v).push_back(d);

    return v;
}

// return an iterator to the element in [first:last) that has the highest value
template<class Iterator>
Iterator high(Iterator first, Iterator last)
{
    if (first==last) error("No highest value in empty sequence");
    Iterator high = first;
    for (Iterator p = first; p!=last; ++p)
        if (*high<*p) high = p;
    return high;
}

void fct()
{
    int jack_count = 0;
    double* jack_data = get_from_jack(&jack_count);
    vector<double>* jill_data = get_from_jill();

    double* jack_high = high(jack_data,jack_data+jack_count);
    vector<double>& v = *jill_data;
    double* jill_high = high(&v[0],&v[0]+v.size());
    cout << "Jill's high " << *jill_high << "; Jack's high " << *jack_high;

    delete[] jack_data;
    delete jill_data;
}

int main()
try {
    fct();
}
catch (Range_error& re) {
    cerr << "bad index: " << re.index << "\n";
}
catch (exception& e) {
    cerr << "exception: " << e.what() << endl;
}
catch (...) {
    cerr << "exception\n";
}

Add Chapter 20, exercise 4

Add Chapter 20, exercise 4


// Copyright 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 "media/base/media.h"

#include "base/logging.h"

// This file is intended for platforms that don't need to load any media
// libraries (e.g., Android and iOS).
namespace media {

bool InitializeMediaLibrary(const base::FilePath& module_dir) {
  return true;
}

void InitializeMediaLibraryForTesting() {
}

bool IsMediaLibraryInitialized() {
  return true;
}

}  // namespace media

// Copyright 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 "media/base/media.h"

#include "base/logging.h"

#if defined(OS_ANDROID)
#include "base/android/jni_android.h"
#include "media/base/android/media_jni_registrar.h"
#endif

// This file is intended for platforms that don't need to load any media
// libraries (e.g., Android and iOS).
namespace media {

bool InitializeMediaLibrary(const base::FilePath& module_dir) {
  return true;
}

void InitializeMediaLibraryForTesting() {
#if defined(OS_ANDROID)
  // Register JNI bindings for android.
  JNIEnv* env = base::android::AttachCurrentThread();
  RegisterJni(env);
#endif
}

bool IsMediaLibraryInitialized() {
  return true;
}

}  // namespace media

Android: Fix media and content unittests on Android debug bots

BUG=

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

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


/* mbed Microcontroller Library
 * Copyright (c) 2017 ARM Limited
 *
 * 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 "mbed.h"
#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"
#include "rtos.h"

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

using namespace utest::v1;

#define TEST_STACK_SIZE 512
#define TEST_DELAY 10

static int change_counter = 0;
static Mutex mutex;
static ConditionVariable cond(mutex);

void increment_on_signal()
{
    mutex.lock();

    cond.wait();
    change_counter++;

    mutex.unlock();
}

void test_notify_one()
{
    Thread t1(osPriorityNormal, TEST_STACK_SIZE);
    Thread t2(osPriorityNormal, TEST_STACK_SIZE);

    change_counter = 0;
    t1.start(increment_on_signal);
    t2.start(increment_on_signal);

    wait_ms(TEST_DELAY);
    TEST_ASSERT_EQUAL(0, change_counter);

    mutex.lock();
    cond.notify_one();
    mutex.unlock();

    wait_ms(TEST_DELAY);
    TEST_ASSERT_EQUAL(1, change_counter);

    mutex.lock();
    cond.notify_one();
    mutex.unlock();

    t1.join();
    t2.join();
}

void test_notify_all()
{
    Thread t1(osPriorityNormal, TEST_STACK_SIZE);
    Thread t2(osPriorityNormal, TEST_STACK_SIZE);

    change_counter = 0;
    t1.start(increment_on_signal);
    t2.start(increment_on_signal);

    wait_ms(TEST_DELAY);
    TEST_ASSERT_EQUAL(0, change_counter);

    mutex.lock();
    cond.notify_all();
    mutex.unlock();

    wait_ms(TEST_DELAY);
    TEST_ASSERT_EQUAL(2, change_counter);

    t1.join();
    t2.join();
}

utest::v1::status_t test_setup(const size_t number_of_cases)
{
    GREENTEA_SETUP(10, "default_auto");
    return verbose_test_setup_handler(number_of_cases);
}

Case cases[] = {
    Case("Test notify one", test_notify_one),
    Case("Test notify all", test_notify_all),
};

Specification specification(test_setup, cases);

int main()
{
    return !Harness::run(specification);
}

Add test cases for ConditionVariable

Add test cases for ConditionVariable

Add basic tests for the ConditionVariable class.


// Test case for PR1420
// RUN: %llvmgxx %s -O0 -o %t.exe
// RUN: %t.exe > %t.out
// RUN: grep {sizeof(bitFieldStruct) == 8} %t.out
// RUN: grep {Offset bitFieldStruct.i = 0} %t.out
// RUN: grep {Offset bitFieldStruct.c2 = 7} %t.out
// XFAIL: *

#include <stdio.h>

class bitFieldStruct {
  public:
    int i;
    unsigned char c:7;
    int s:17;
    char c2;
};

int main()
{
  printf("sizeof(bitFieldStruct) == %d\n", sizeof(bitFieldStruct));

  if (sizeof(bitFieldStruct) != 2 * sizeof(int))
    printf("bitFieldStruct should be %d but is %d \n",
            2 * sizeof(int), sizeof(bitFieldStruct));

  bitFieldStruct x;

  char* xip = (char*) &x.i;
  char* xc2p = (char*) &x.c2;
  printf("Offset bitFieldStruct.i = %d\n", xip - xip);
  printf("Offset bitFieldStruct.c2 = %d\n", xc2p - xip);

  return 0;
}

Add a test case for PR1420

Add a test case for PR1420

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


#include <cassert>
#include <cstdint>
#include <iostream>
#include <malloc.h>
#include <new>

class alignas(32) Vec3d {
    double x, y, z;
};

int main() {
    std::cout << "sizeof(Vec3d) is " << sizeof(Vec3d) << '\n';
    std::cout << "alignof(Vec3d) is " << alignof(Vec3d) << '\n';

    auto Vec = Vec3d{};
    auto pVec = new Vec3d[10];

    if (reinterpret_cast<uintptr_t>(&Vec) % alignof(Vec3d) == 0) {
        std::cout << "Vec is aligned to alignof(Vec3d)!\n";
    } else {
        std::cout << "Vec is not aligned to alignof(Vec3d)!\n";
    }

    if (reinterpret_cast<uintptr_t>(pVec) % alignof(Vec3d) == 0) {
        std::cout << "pVec is aligned to alignof(Vec3d)!\n";
    } else {
        std::cout << "pVec is not aligned to alignof(Vec3d)!\n";
    }

    delete[] pVec;
}

Add struct alignement test example.

Add struct alignement test example.


// RUN: %clang_analyze_cc1 -analyzer-checker=core,unix -verify %s

// expected-no-diagnostics

// Test functions that are called "memcpy" but aren't the memcpy
// we're looking for. Unfortunately, this test cannot be put into
// a namespace. The out-of-class weird memcpy needs to be recognized
// as a normal C function for the test to make sense.
typedef __typeof(sizeof(int)) size_t;
void *memcpy(void *, const void *, size_t);

struct S {
  static S s1, s2;

  // A weird overload within the class that accepts a structure reference
  // instead of a pointer.
  void memcpy(void *, const S &, size_t);
  void test_in_class_weird_memcpy() {
    memcpy(this, s2, 1); // no-crash
  }
};

// A similarly weird overload outside of the class.
void *memcpy(void *, const S &, size_t);

void test_out_of_class_weird_memcpy() {
  memcpy(&S::s1, S::s2, 1); // no-crash
}

Add the forgotten test file.

[analyzer] CStringChecker: Add the forgotten test file.

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

rdar://problem/45366551

git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@349683 91177308-0d34-0410-b5e6-96231b3b80d8
(cherry picked from commit 2ac8dae2d6fcf14ef1b60e456eacd2a9eeb5a6ee)


// RUN: %clangxx -g -O0 %s -emit-llvm -S -o - | FileCheck %s
// PR14471

class C
{
  static int a;
  const static int const_a = 16;
protected:
  static int b;
  const static int const_b = 17;
public:
  static int c;
  const static int const_c = 18;
  int d;
};

int C::a = 4;
int C::b = 2;
int C::c = 1;

int main()
{
        C instance_C;
        instance_C.d = 8;
        return C::c;
}

// The definition of C::a drives the emission of class C, which is
// why the definition of "a" comes before the declarations while
// "b" and "c" come after.

// CHECK: metadata !"a", {{.*}} @_ZN1C1aE, metadata ![[DECL_A:[0-9]+]]} ; [ DW_TAG_variable ] [a] {{.*}} [def]
// CHECK: ![[DECL_A]] = metadata {{.*}} [ DW_TAG_member ] [a] [line {{.*}}, size 0, align 0, offset 0] [private] [static]
// CHECK: metadata !"const_a", {{.*}} [ DW_TAG_member ] [const_a] [line {{.*}}, size 0, align 0, offset 0] [private] [static]
// CHECK: ![[DECL_B:[0-9]+]] {{.*}} metadata !"b", {{.*}} [ DW_TAG_member ] [b] [line {{.*}}, size 0, align 0, offset 0] [protected] [static]
// CHECK: metadata !"const_b", {{.*}} [ DW_TAG_member ] [const_b] [line {{.*}}, size 0, align 0, offset 0] [protected] [static]
// CHECK: ![[DECL_C:[0-9]+]] {{.*}} metadata !"c", {{.*}} [ DW_TAG_member ] [c] [line {{.*}}, size 0, align 0, offset 0] [static]
// CHECK: metadata !"const_c", {{.*}} [ DW_TAG_member ] [const_c] [line {{.*}}, size 0, align 0, offset 0] [static]
// CHECK: metadata !"b", {{.*}} @_ZN1C1bE, metadata ![[DECL_B]]} ; [ DW_TAG_variable ] [b] {{.*}} [def]
// CHECK: metadata !"c", {{.*}} @_ZN1C1cE, metadata ![[DECL_C]]} ; [ DW_TAG_variable ] [c] {{.*}} [def]

Add testcase missed yesterday. Patch from Paul Robinson.

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


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

// <array>

// iterator, const_iterator

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

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

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

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

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

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

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

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

git-svn-id: 273b07cebdae5845b4a75aae04570b978db9eb50@187809 91177308-0d34-0410-b5e6-96231b3b80d8


// 9.exercise.04.cpp
//
//  Look at the headache-inducing last example of §8.4. Indent it properly and
//  explain the meaning of the construct. Note that the example doesn't do
//  anything meaningful; it is pure obfuscation.
//
//  COMMENTS

int maint()
try
{
    return 0;
}
catch(exception& e)
{
    cerr << e.what() << '\n';
    return 1;
}
catch(...)
{
    cerr << "Unknown exception!\n";
    return 2;
}

Prepare exercise 4 from chapter 9.

Prepare exercise 4 from chapter 9.


#include <iostream>
#include <cstring>

using namespace std;

class Card {
    char title[100];
    char author[100];
    unsigned int count;

public:

    Card(const char _title[], const char _author[], unsigned int _count) {
        strcpy(title, _title);
        strcpy(author, _author);
        count = _count;
    }

    void print() {
        cout << "Title: " << title << endl;
        cout << "Author: " << author << endl;
        cout << "Count of available copies: " << count << endl;
    }
};

int main() {
    Card winFriendsInfluencePeople = Card("How to win friends and influence people", "Dale Carnegie", 3);
    winFriendsInfluencePeople.print();

    return 0;
}

Add solution to task 1

Add solution to task 1


#include <iostream>
#include <cmath>

using namespace std;

class Point3D {
  double x;
  double y;
  double z;

public:

  double getX() {
    return x;
  }

  double getY() {
    return y;
  }

  double getZ() {
    return z;
  }

  void setX(double newX) {
    x = newX;
  }

  void setY(double newY) {
    y = newY;
  }

  void setZ(double newZ) {
    z = newZ;
  }

  void translate(Point3D translationVector) {
    setX(getX() + translationVector.getX());
    setY(getY() + translationVector.getY());
    setZ(getZ() + translationVector.getZ());
  }

  double distanceTo(Point3D other) {
    return sqrt(pow(getX() - other.getX(), 2) +
                pow(getY() - other.getY(), 2) +
                pow(getZ() - other.getZ(), 2));
  }

  void print() {
    cout << '(' << getX() << ", " << getY() << ", " << getZ() << ')' << '\n';
  }
};

void testTranslate() {
  Point3D point;
  point.setX(3);
  point.setY(5);
  point.setZ(2);

  Point3D translationVector;
  translationVector.setX(4);
  translationVector.setY(7);
  translationVector.setZ(1);

  point.translate(translationVector);
  point.print();
}

void testDistanceBetween() {
  Point3D firstPoint;
  firstPoint.setX(3);
  firstPoint.setY(5);
  firstPoint.setZ(2);

  Point3D secondPoint;
  secondPoint.setX(4);
  secondPoint.setY(1);
  secondPoint.setZ(7);

  cout << firstPoint.distanceTo(secondPoint) << '\n';
}

int main() {
  testTranslate();
  testDistanceBetween();

  return 0;
}

Add solution to the first problem - '3D point'


// RUN: %clangxx_xray -g -std=c++11 %s -o %t
// RUN: rm xray-log.fdr-reinit* || true
// RUN: XRAY_OPTIONS="verbosity=1" %run %t
// RUN: rm xray-log.fdr-reinit* || true
#include "xray/xray_log_interface.h"
#include <cassert>
#include <cstddef>
#include <thread>

volatile uint64_t var = 0;

std::atomic_flag keep_going = ATOMIC_FLAG_INIT;

[[clang::xray_always_instrument]] void __attribute__((noinline)) func() {
  ++var;
}

int main(int argc, char *argv[]) {
  // Start a thread that will just keep calling the function, to spam calls to
  // the function call handler.
  keep_going.test_and_set(std::memory_order_acquire);
  std::thread t([] {
    while (keep_going.test_and_set(std::memory_order_acquire))
      func();
  });

  static constexpr char kConfig[] =
      "buffer_size=1024:buffer_max=10:no_file_flush=true";

  // Then we initialize the FDR mode implementation.
  assert(__xray_log_select_mode("xray-fdr") ==
         XRayLogRegisterStatus::XRAY_REGISTRATION_OK);
  auto init_status = __xray_log_init_mode("xray-fdr", kConfig);
  assert(init_status == XRayLogInitStatus::XRAY_LOG_INITIALIZED);

  // Now we patch the instrumentation points.
  __xray_patch();

  // Spin for a bit, calling func() enough times.
  for (auto i = 0; i < 1 << 20; ++i)
    func();

  // Then immediately finalize the implementation.
  auto finalize_status = __xray_log_finalize();
  assert(finalize_status == XRayLogInitStatus::XRAY_LOG_FINALIZED);

  // Once we're here, we should then flush.
  auto flush_status = __xray_log_flushLog();
  assert(flush_status == XRayLogFlushStatus::XRAY_LOG_FLUSHED);

  // Without doing anything else, we should re-initialize.
  init_status = __xray_log_init_mode("xray-fdr", kConfig);
  assert(init_status == XRayLogInitStatus::XRAY_LOG_INITIALIZED);

  // Then we spin for a bit again calling func() enough times.
  for (auto i = 0; i < 1 << 20; ++i)
    func();

  // Then immediately finalize the implementation.
  finalize_status = __xray_log_finalize();
  assert(finalize_status == XRayLogInitStatus::XRAY_LOG_FINALIZED);

  // Once we're here, we should then flush.
  flush_status = __xray_log_flushLog();
  assert(flush_status == XRayLogFlushStatus::XRAY_LOG_FLUSHED);

  // Finally, we should signal the sibling thread to stop.
  keep_going.clear(std::memory_order_release);

  // Then join.
  t.join();
}

[XRay] Add a test for re-initialising FDR mode (NFC)

This change adds an end-to-end test that ensures FDR mode can be
re-initialised safely in the face of multiple threads being traced.

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


// Copyright (c) 2014 GitHub, Inc. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/atom_browser_main_parts.h"

#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "library_loaders/libgio.h"
#include "ui/gfx/switches.h"

namespace atom {

namespace {

const char* kInterfaceSchema = "org.gnome.desktop.interface";
const char* kScaleFactor = "scale-factor";

}  // namespace

void AtomBrowserMainParts::SetDPIFromGSettings() {
  LibGioLoader libgio_loader;

  // Try also without .0 at the end; on some systems this may be required.
  if (!libgio_loader.Load("libgio-2.0.so.0") &&
      !libgio_loader.Load("libgio-2.0.so")) {
    VLOG(1) << "Cannot load gio library. Will fall back to gconf.";
    return;
  }

  GSettings* client = libgio_loader.g_settings_new(kInterfaceSchema);
  if (!client) {
    VLOG(1) << "Cannot create gsettings client.";
    return;
  }

  gchar** keys = libgio_loader.g_settings_list_keys(client);
  if (!keys) {
    g_object_unref(client);
    return;
  }

  // Check if the "scale-factor" settings exsits.
  gchar** iter = keys;
  while (*iter) {
    if (strcmp(*iter, kScaleFactor) == 0)
      break;
    iter++;
  }

  if (*iter) {
    guint scale_factor = libgio_loader.g_settings_get_uint(
        client, kScaleFactor);
    if (scale_factor >= 1) {
      base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
          switches::kForceDeviceScaleFactor, base::UintToString(scale_factor));
    }
  }

  g_strfreev(keys);
  g_object_unref(client);
}

}  // namespace atom

linux: Set scale factor to the value in gsettings


#include "go_quic_spdy_server_stream_go_wrapper.h"
#include "net/quic/quic_session.h"
#include "net/quic/quic_data_stream.h"

#include "go_functions.h"

GoQuicSpdyServerStreamGoWrapper::GoQuicSpdyServerStreamGoWrapper(net::QuicStreamId id, net::QuicSession* session, void* go_quic_spdy_server_stream)
  : net::QuicDataStream(id, session),
    go_quic_spdy_server_stream_(go_quic_spdy_server_stream) {
}

GoQuicSpdyServerStreamGoWrapper::~GoQuicSpdyServerStreamGoWrapper() {
}
// TODO(hodduc) more more implementation
//
uint32 GoQuicSpdyServerStreamGoWrapper::ProcessData(const char* data, uint32 data_len) {
  if (data_len > INT_MAX) {
    LOG(DFATAL) << "Data length too long: " << data_len;
    return 0;
  }

  uint32_t ret_data_len = DataStreamProcessorProcessData_C(go_quic_spdy_server_stream_, data, data_len);

  return data_len;
}

#include "go_quic_spdy_server_stream_go_wrapper.h"
#include "net/quic/quic_session.h"
#include "net/quic/quic_data_stream.h"

#include "go_functions.h"

GoQuicSpdyServerStreamGoWrapper::GoQuicSpdyServerStreamGoWrapper(net::QuicStreamId id, net::QuicSession* session, void* go_quic_spdy_server_stream)
  : net::QuicDataStream(id, session),
    go_quic_spdy_server_stream_(go_quic_spdy_server_stream) {
}

GoQuicSpdyServerStreamGoWrapper::~GoQuicSpdyServerStreamGoWrapper() {
}
// TODO(hodduc) more more implementation
//
uint32 GoQuicSpdyServerStreamGoWrapper::ProcessData(const char* data, uint32 data_len) {
  if (data_len > INT_MAX) {
    LOG(DFATAL) << "Data length too long: " << data_len;
    return 0;
  }

  uint32_t ret_data_len = DataStreamProcessorProcessData_C(go_quic_spdy_server_stream_, data, data_len);

  return ret_data_len;
}

Fix GoQuicSpdyServerStreamGoWrapper not returning correct len


#include <cstdio>
#include <cstring>

using namespace std;

int binary_to_decimal(char * number)
{
  int result = 0;
  int power = 0;
  for (int i = strlen(number) - 1; i >= 0; i--)
  {
    int x = number[i] - '0';
    result +=  x * (1 << power);
    power++;
  }

  return result;
}

int octal_to_decimal(char * number)
{
  int result = 0;
  int number_length = strlen(number);
  for (int i = 0; i < number_length; i++)
  {
    result += number[i] - '0';
    if (i < number_length - 1)
    {
      result *= 8;
    }
  }

  return result;
}

int hexadecimal_to_decimal(char *number)
{
  int number_length = strlen(number);
  char result[100] = "";
  for (int i = 0; i < number_length; i++)
  {
    if (number[i] == '0') strcat(result, "0000");
    else if (number[i] == '1') strcat(result, "0001");
    else if (number[i] == '2') strcat(result, "0010");
    else if (number[i] == '3') strcat(result, "0011");
    else if (number[i] == '4') strcat(result, "0100");
    else if (number[i] == '5') strcat(result, "0101");
    else if (number[i] == '6') strcat(result, "0110");
    else if (number[i] == '7') strcat(result, "0111");
    else if (number[i] == '8') strcat(result, "1000");
    else if (number[i] == '9') strcat(result, "1001");
    else if (number[i] == 'A') strcat(result, "1010");
    else if (number[i] == 'B') strcat(result, "1011");
    else if (number[i] == 'C') strcat(result, "1100");
    else if (number[i] == 'D') strcat(result, "1101");
    else if (number[i] == 'E') strcat(result, "1110");
    else if (number[i] == 'F') strcat(result, "1111");
  }

  return binary_to_decimal(result);
}

int main()
{
  int numeral_system;
  char number[100];

  while (scanf("%d%s", &numeral_system, number))
  {
    if (numeral_system == 2) printf("%d\n", binary_to_decimal(number));
    else if (numeral_system == 8) printf("%d\n", octal_to_decimal(number));
    else if (numeral_system == 16) printf("%d\n", hexadecimal_to_decimal(number));
  }

  return 0;
}

Add a solution for task 1a

Add a solution for task 1a


/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#include "catch.hpp"

#include <mapnik/datasource.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/raster.hpp>
#include <mapnik/util/fs.hpp>

namespace {

mapnik::datasource_ptr get_gdal_ds(std::string const& file_name,
                                   boost::optional<mapnik::value_integer> band)
{
    std::string gdal_plugin("./plugins/input/gdal.input");
    if (!mapnik::util::exists(gdal_plugin))
    {
        return mapnik::datasource_ptr();
    }

    mapnik::parameters params;
    params["type"] = std::string("gdal");
    params["file"] = file_name;
    if (band)
    {
        params["band"] = *band;
    }

    auto ds = mapnik::datasource_cache::instance().create(params);
    REQUIRE(ds != nullptr);

    return ds;
}

} // anonymous namespace

TEST_CASE("gdal") {

    SECTION("upsampling")
    {
        std::string dataset = "test/data/tiff/ndvi_256x256_gray32f_tiled.tif";
        mapnik::datasource_ptr ds = get_gdal_ds(dataset, 1);

        if (!ds)
        {
            // GDAL plugin not built.
            return;
        }

        mapnik::box2d<double> envelope = ds->envelope();
        CHECK(envelope.width() == 256);
        CHECK(envelope.height() == 256);

        // Indicate four times bigger resolution.
        mapnik::query::resolution_type resolution(2.0, 2.0);
        mapnik::query query(envelope, resolution, 1.0);

        auto features = ds->features(query);
        auto feature = features->next();

        mapnik::raster_ptr raster = feature->get_raster();

        REQUIRE(raster != nullptr);
        CHECK(raster->data_.width() == 256);
        CHECK(raster->data_.height() == 256);
    }

} // END TEST CASE

Add test that GDAL plugin does not upsample.


#include <iostream>

using namespace std;

class Class {
public:
    Class() {
        cout << "Class()" << endl;
    }
};

class Base : public Class {
public:
    Base() {
        cout << "Base()" << endl;
    }
};

class D1 : virtual public Base {
public:
    D1() {
        cout << "D1()" << endl;
    }
};

class D2 : virtual public Base {
public:
    D2() {
        cout << "D2()" << endl;
    }
};

class MI : public D1, public D2 {
public:
    MI() {
        cout << "MI()" << endl;
    }
};

class Final : public MI, public Class {
public:
    Final() {
        cout << "Final()" << endl;
    }
};

int main() {
    //(a)(b)
    Final f;

    //(c)
    Base *pb = nullptr;
    Class *pc = nullptr;
    MI *pmi = nullptr;
    D2 *pd2 = nullptr;
//    pb = new Class;//invalid conversion
//    pc = new Final;//'Class' is an ambiguous base of 'Final'
//    pmi = pb;//invalid conversion
//    pd2 = pmi;//ok
    return 0;
}

Add solution for chapter 18, test 29

Add solution for chapter 18, test 29


#include <iostream>
#include <cassert>

class [[clang::consumable(unconsumed)]] Object {
public:
    Object() {}
    Object(Object&& other) { other.invalidate(); }
    [[clang::callable_when(unconsumed)]]
    void do_something() { assert(m_valid); }

private:
    [[clang::set_typestate(consumed)]]
    void invalidate() { m_valid = false; }
    bool m_valid { true };
};

int main(int, char**) {
    Object object;
    auto other = std::move(object);
    object.do_something();
    return 0;
}

Add example of clang attributes for prevention of use after move.

Compile with:

clang -Wconsumed move_bugs.cpp -o move_bugs -lstdc++

Warning message is generated during compilation:

move_bugs.cpp:20:12: warning: invalid invocation of method 'do_something' on object 'object' while it is in the 'consumed' state [-Wconsumed]
    object.do_something();
           ^
1 warning generated.


#include <atomic>
#include <thread>
#include <iostream>

struct thing {
    unsigned int a : 15;
    unsigned int b : 15;
};

thing x;

void f1(int n) {
    for (int i = 0; i < n; i++) {
        x.a++;
    }
}
void f2(int n) {
    for (int i = 0; i < n; i++) {
        x.b++;
    }
}

int main() {
    std::cout << sizeof(thing) << "\n";
    std::thread t1(f1, 1000000);
    std::thread t2(f2, 1000000);
    t1.join();
    t2.join();

    std::cout << x.a << " " << x.b << "\n";

    return 0;
}

Add an experiment that tests some bitfield stuff


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

// trigger a problem in DerivativeApproximation with memory handling

#include <base/logstream.h>
#include <lac/vector.h>
#include <grid/tria.h>
#include <grid/grid_generator.h>
#include <grid/tria_accessor.h>
#include <dofs/hp_dof_handler.h>
#include <fe/fe_dgq.h>
#include <numerics/derivative_approximation.h>

#include <fstream>

template <int dim>
void test ()
{
  Triangulation<dim> tria;
  GridGenerator::hyper_cube(tria);
  tria.refine_global (1);

  hp::FECollection<dim> fe_collection;
  fe_collection.push_back (FE_DGQ<dim> (1));

  hp::DoFHandler<dim> dof_handler(tria);
  dof_handler.distribute_dofs (fe_collection);

  Vector<double> v(dof_handler.n_dofs());
  Vector<float> e(tria.n_active_cells());
  DerivativeApproximation::approximate_gradient (dof_handler, v, e);
}

int main ()
{
  std::ofstream logfile("crash_04/output");
  logfile.precision(2);

  deallog.attach(logfile);
  deallog.depth_console(0);
  deallog.threshold_double(1.e-10);

  test<1> ();
  test<2> ();
  test<3> ();

  deallog << "OK" << std::endl;
}

Add new test that shows failure in DerivativeApproximation

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


// Simple example file for the the fparser optimization bug
// (c) 2014 by Daniel Schwen
// ========================================================

// $CXX -o optimizer_bug optimizer_bug.cc -I ../../../installed/include/libmesh/ ../../../build/contrib/fparser/.libs/libfparser_la-fp*

#include "../fparser.hh"

#include <iostream>
#include <fstream>
#include <string>

int main()
{
  std::ofstream myfile;
  double p[3] = {0.0, 2.0, 0.1};
  const double step = 0.01;
  FunctionParser fparser;

  // The White Whale
  std::string func = "c*2*(1-c)^2 - c^2*(1-c)*2";

  // Parse the input expression into bytecode
  fparser.Parse(func, "c");
#ifdef FUNCTIONPARSER_SUPPORT_DEBUGGING
  std::cout << "Input Expression:\n" << func << std::endl;
  fparser.PrintByteCode(std::cout);
  std::cout << std::endl;
#endif

  // eval into file
  myfile.open ("pre.dat");
  for (p[0]=0.0; p[0]<=1.0; p[0]+=0.01) myfile << p[0] << ' ' << fparser.Eval(p) << std::endl;
  myfile.close();

  FunctionParser fparser2(fparser);

  // output optimized version
  fparser.Optimize();
#ifdef FUNCTIONPARSER_SUPPORT_DEBUGGING
  std::cout << "Optimized Input Expression:\n" << func << std::endl;
  fparser.PrintByteCode(std::cout);
  std::cout << std::endl;
#endif

  // eval into file
  myfile.open ("post.dat");
  for (p[0]=0.0; p[0]<=1.0; p[0]+=0.01) myfile << p[0] << ' ' << fparser.Eval(p) << std::endl;
  myfile.close();

  // compute difference
  double diff = 0.0;
  for (p[0]=0.0; p[0]<=1.0; p[0]+=step) diff+=step*(fparser.Eval(p)-fparser2.Eval(p));

  std::cout << "Integral of f_optimized()-f_original() on [0,1] = " << diff << "  (should be ~0.0)" << std::endl;
  return 0;
}

Add minimal testcase for optimizer bug in FParser.


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

using namespace std;

int main() {
    Sales_data item("book1", 4, 30.0), *p = &item;
    auto pdata = &Sales_data::isbn;
    cout << (item.*pdata)() << endl;
    cout << (p ->* pdata)() << endl;
    return 0;
}

Add solution for chapter 19, test 13

Add solution for chapter 19, test 13


/** \file    xml_parser_test.cc
 *  \brief   Tests the FileUtil::GetFileName() function.
 *  \author  Dr. Johannes Ruscheinski
 */

/*
    Copyright (C) 2015, Library of the University of Tübingen

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

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

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

#include <iostream>
#include <stdexcept>
#include "FileUtil.h"
#include "util.h"

__attribute__((noreturn)) void Usage() {
    std::cerr << "usage: " << ::progname << " path\n";
    std::exit(EXIT_FAILURE);
}

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

    try {
	FILE *file(std::fopen(argv[1], "r"));
	std::cout << "File pointer points to \"" << FileUtil::GetFileName(file) << "\".\n";
    } catch(const std::exception &x) {
	Error("caught exception: " + std::string(x.what()));
    }
}

Test for the new FileUtil::GetFileName() functions.


#include "tbb/parallel_sort.h"
#include <math.h>

using namespace tbb;

const int N = 100000;
float a[N], b[N], c[N], d[N];

void SortExample() {
  for( int i = 0; i < N; i++ ) {
     a[i] = sin((double)i);
     b[i] = cos((double)i);
     c[i] = 1/sin((double)i);
     d[i] = 1/cos((double)i);
  }
  parallel_sort(a, a + N);
  parallel_sort(b, b + N, std::greater<float>());
  parallel_sort(c);
  parallel_sort(d, std::greater<float>());
}

int main( void )
{
  SortExample();
  return 0;
}

Add in Intel TBB tests

Add in Intel TBB tests


#include "gtest/gtest.h"
#include "gmock/gmock.h"

#include "Vec2i.h"

TEST(TestVec2i, DisplacingDirectionWithOffsetWillWrap ) {

    ASSERT_EQ( Knights::EDirection::kWest,  Knights::wrapDirection(  Knights::EDirection::kNorth, -1 ) );
    ASSERT_EQ( Knights::EDirection::kNorth, Knights::wrapDirection(  Knights::EDirection::kEast, -1 ) );
    ASSERT_EQ( Knights::EDirection::kEast,  Knights::wrapDirection(  Knights::EDirection::kSouth, -1 ) );
    ASSERT_EQ( Knights::EDirection::kSouth,  Knights::wrapDirection(  Knights::EDirection::kWest, -1 ) );

    ASSERT_EQ( Knights::EDirection::kNorth,  Knights::wrapDirection(  Knights::EDirection::kNorth, -4 ) );
    ASSERT_EQ( Knights::EDirection::kEast, Knights::wrapDirection(  Knights::EDirection::kEast, -4 ) );
    ASSERT_EQ( Knights::EDirection::kSouth,  Knights::wrapDirection(  Knights::EDirection::kSouth, -4 ) );
    ASSERT_EQ( Knights::EDirection::kWest,  Knights::wrapDirection(  Knights::EDirection::kWest, -4 ) );

    ASSERT_EQ( Knights::EDirection::kEast,  Knights::wrapDirection(  Knights::EDirection::kNorth, +1 ) );
    ASSERT_EQ( Knights::EDirection::kSouth, Knights::wrapDirection(  Knights::EDirection::kEast, +1 ) );
    ASSERT_EQ( Knights::EDirection::kWest,  Knights::wrapDirection(  Knights::EDirection::kSouth, +1 ) );
    ASSERT_EQ( Knights::EDirection::kNorth,  Knights::wrapDirection(  Knights::EDirection::kWest, +1 ) );

    ASSERT_EQ( Knights::EDirection::kNorth,  Knights::wrapDirection(  Knights::EDirection::kNorth, +4 ) );
    ASSERT_EQ( Knights::EDirection::kEast, Knights::wrapDirection(  Knights::EDirection::kEast, +4 ) );
    ASSERT_EQ( Knights::EDirection::kSouth,  Knights::wrapDirection(  Knights::EDirection::kSouth, +4 ) );
    ASSERT_EQ( Knights::EDirection::kWest,  Knights::wrapDirection(  Knights::EDirection::kWest, +4 ) );
}

Add basic test for Vec2

Add basic test for Vec2


/**
 *
 * Authors:
 *   Tim Dwyer <tgdwyer@gmail.com>
 *
 * Copyright (C) 2005 Authors
 *
 * This version is released under the CPL (Common Public License) with
 * the Graphviz distribution.
 * A version is also available under the LGPL as part of the Adaptagrams
 * project: http://sourceforge.net/projects/adaptagrams.
 * If you make improvements or bug fixes to this code it would be much
 * appreciated if you could also contribute those changes back to the
 * Adaptagrams repository.
 */
#include "variable.h"
std::ostream& operator <<(std::ostream &os, const Variable &v) {
	os << "(" << v.id << "=" << v.position() << ")";
	return os;
}

Add the vpsc library for IPSEPCOLA features


// RUN: %llvmgxx -O0 -emit-llvm -S -g -o - %s | grep 'uint 1,' &&
// RUN: %llvmgxx -O0 -emit-llvm -S -g -o - %s | grep 'uint 2,'

class A {
public:
  int x;
protected:
  int y;
private:
  int z;
};

A a;

Make sure C++ protection shows up in debug info

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


//
// Programmer:    Craig Stuart Sapp <craig@ccrma.stanford.edu>
// Creation Date: Mon 18 Apr 2022 06:34:46 PM UTC
// Last Modified: Mon 18 Apr 2022 06:34:49 PM UTC
// Filename:      imagedemo.cpp
// URL:           https://github.com/craigsapp/humlib/blob/master/cli/imagedemo.cpp
// Syntax:        C++11
// vim:           ts=3 noexpandtab nowrap
//
// Description:   Demonstration of how to use PixelColor class
//                to create simple images.
//

#include "humlib.h"
#include <iostream>

using namespace hum;
using namespace std;

void   processFile         (HumdrumFile& infile, Options& options);
double calculateNpviRhythm (HumdrumFile& infile, Options& option);
double calculateCvPitch    (HumdrumFile& infile, Options& options);
string getReference        (HumdrumFile& infile, const string& targetKey);

///////////////////////////////////////////////////////////////////////////

int main(int argc, char** argv) {
	Options options;
	options.define("x|columns=i:4", "Number of columns in image");
	options.define("y|rows=i:4", "Number of rows in image");
	options.process(argc, argv);

	int rows = options.getInteger("rows");
	int cols = options.getInteger("columns");

	vector<vector<PixelColor>> image;
	for (int y=0; y<(int)image.size(); y++) {
			for (int x=0; x<(int)image[y].size(); x++) {
				image[y][x].setRedF((double)y/rows);
				image[y][x].setBlueF((double)x/cols);
			}
	}

	// Output image header:
	cout << "P3" << endl;
	cout << cols << " " << rows << endl;
	cout << 255 << endl;

	// Output image pixels:
	for (int y=0; y<(int)image.size(); y++) {
			for (int x=0; x<(int)image[y].size(); x++) {
				cout << image[y][x] << " ";
			}
			cout << endl;
	}

	return 0;
}

Add image generation demo file.

Add image generation demo file.


class Solution {
public:
    vector<string> divideString(string s, int k, char fill) {
        std::vector<std::string> ret;
        std::string cur;
        for (int i = 0; i < s.size(); i += k) {
            ret.emplace_back(s.substr(i, k));
        }
        while (ret[ret.size()-1].size() < k) {
            ret[ret.size()-1] += fill;
        }
        return ret;
    }
};

Divide a String Into Groups of Size k

Divide a String Into Groups of Size k


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    inline bool isLeaf(TreeNode* n) {
        return n->left == NULL && n->right == NULL;
    }
    bool isValidBSTInternal(TreeNode* root, int& minVal, int& maxVal)
    {
        int currMin, currMax;

        if (root == NULL) {
            return true;
        }
        if (isLeaf(root)) {
            minVal = maxVal = root->val;
            return true;
        }

        if (root->left) {
            if (!isValidBSTInternal(root->left, minVal, maxVal)) {
                return false;
            }

            if (root->val <= maxVal) {
                return false;
            }

            currMin = min(root->val, minVal);
            currMax = max(root->val, maxVal);
        } else {
            currMin = currMax = root->val;
        }

        if (root->right) {
            if (!isValidBSTInternal(root->right, minVal, maxVal)) {
                return false;
            }
            if (root->val >= minVal) {
                return false;
            }
            minVal = min(minVal, currMin);
            maxVal = max(maxVal, currMax);
        } else {
            minVal = currMin;
            maxVal = currMax;
        }

        return true;
    }

    bool isValidBST(TreeNode* root) {
        int minVal, maxVal;
        return isValidBSTInternal(root, minVal, maxVal);
    }
};

Validate if a binary tree is BST

Validate if a binary tree is BST


// 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/extensions/extension_apitest.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"

class DownloadsApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
  }

  void SetUpTempDownloadsDir() {
    ASSERT_TRUE(tmpdir.CreateUniqueTempDir());
    browser()->profile()->GetPrefs()->SetFilePath(
        prefs::kDownloadDefaultDirectory, tmpdir.path());
  }

 private:
  ScopedTempDir tmpdir;
};

IN_PROC_BROWSER_TEST_F(DownloadsApiTest, DownloadsApiTest) {
  SetUpTempDownloadsDir();
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("downloads")) << message_;
}

// 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/extensions/extension_apitest.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"

class DownloadsApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
  }

  void SetUpTempDownloadsDir() {
    ASSERT_TRUE(tmpdir.CreateUniqueTempDir());
    browser()->profile()->GetPrefs()->SetFilePath(
        prefs::kDownloadDefaultDirectory, tmpdir.path());
  }

 private:
  ScopedTempDir tmpdir;
};

// This test is disabled. See bug http://crbug.com/130950
IN_PROC_BROWSER_TEST_F(DownloadsApiTest, DISABLED_DownloadsApiTest) {
  SetUpTempDownloadsDir();
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("downloads")) << message_;
}

Disable DownloadsApiTest.DownloadsApiTest because it is too flaky and times out too often.

BUG=130950
TBR=benjhayden@chromium.org

Review URL: https://chromiumcodereview.appspot.com/10499011

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


// RUN: %llvmgxx %s -S -o - | grep '%XX = global int 4'

struct S {
  int  A[2];
};

int XX = (int)&(((struct S*)0)->A[1]);

Add a testcase to check that initializer that CAN be evaluated statically ARE.

These used to result in dynamic initializations.

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


#include<iostream>

using namespace std;

class Node{
	public:

	int data;
	Node *next,*head;

	Node(){}

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

	Node *addElement(Node *head, int d){

		Node *nde=new Node(d);
		Node *tmp=head;

		if(head==NULL)
			return nde;
		else{
			while(tmp->next)
				tmp=tmp->next;
		}

		tmp->next=nde;

		return head;
	}

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

		if(head==NULL)
			cout<<"No elements in the list! :(";
		else{
			cout<<"Elements in the list are:\n";
			while(nde){
				cout<<nde->data<<"\n";
				nde=nde->next;
			}
		}
	}
};

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

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

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

	np.displayList(head);
}

Add code to print linked list

Add code to print linked list


#include <iostream>
#include <fstream>

int main()
{
    std::ifstream file("data.txt");
    std::string line;
    // See: https://stackoverflow.com/q/7219062/496459
    // std::getline has no buffer-size limitation, per the standard.
    while(std::getline(file, line))
    {
        std::cout << line << '\n';
    }

    return 0;
}

Add idiom to read lines from a file.

Add idiom to read lines from a file.


#include <iostream>
#include <cblas.h>
int main ( int argc, char* argv[] ) {
    const long n = ((long)1 << 31) - 1;
    std::cout << n <<std::endl;
    float*  A = new float[n];
    float*  B = new float[n];
    float*  C = new float[1];
    for(long i =0; i <n; i++){
        A[i] = 1;
        B[i] = 1;

    }
    cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, 1, 1, n,  1.0, A, n, B, 1, 0.0, C, 1);
    std::cout << *C <<std::endl;
    delete[] A;
    delete[] B;
    delete[] C;
    return 0;
}

Add trivial gemm test for multithread consistency


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

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

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

void partition(int *a, int n)
{
	int *temp = new int[n];
	int i = 0, j = n - 1;
	for (int k = 1; k < n; k++) {
		if (a[k] < a[0]) {
			temp[i++] = a[k];
		}
		else {
			temp[j--] = a[k];
		}
	}
	temp[i] = a[0];
	memcpy(a, temp, n * sizeof(int));
	reverse(a, i + 1, n - 1);
}

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

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

Add the solution to "QuickSort1 - Partition".


class Solution {
public:
    bool isValidSerialization(string preorder) {
        vector<string> h;
        string t;
        for(int i=0;i<preorder.size();){
            if(preorder[i]==','){
                h.push_back(t);
                t.erase(t.begin(),t.end());
                preorder.erase(preorder.begin()+i,preorder.begin()+i+1);
            }else{
                t+=preorder[i];
                i++;
            }
        }
        h.push_back(t);
        int o=look(h,0);
        if(o==h.size()) return true;
        return false;
    }
    int look(vector<string>& h, int x){
        //cout<<x<<" "<<h[x]<<endl;
        if(x>=h.size()) return x+1;
        if(h[x][0]-'#'==0) return x+1;
        int k=look(h,x+1);
        //if(k>=h.size()) return k+1;
        return look(h,k);
    }
};

Verify Preorder Serialization of a Binary Tree


#include <iostream>
#include <interpreter.h>
#include <gui.h>
#include <easylogging++.h>
#include <SFML/Graphics.hpp>

INITIALIZE_EASYLOGGINGPP

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

    int i = foo();
    std::cout << str() + 1 << std::endl << i << std::endl;
    LOG(INFO) << "Drawing...";

    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(shape);
        window.display();
    }

    return 0;
}

#include <iostream>
#include <interpreter.h>
#include <gui.h>
#include <easylogging++.h>
#include <SFML/Graphics.hpp>

INITIALIZE_EASYLOGGINGPP

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

    std::cout << "Who am I ? where am I ?    Lei" << std::endl;

    int i = foo();
    std::cout << str() + 1 << std::endl << i << std::endl;
    LOG(INFO) << "I'm drawing here...";

    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(shape);
        window.display();
    }

    return 0;
}

Revert "Revert "this is my test""

Revert "Revert "this is my test""

This reverts commit e59e3561a7b65c75b584757780adb3ceaf6181c6.


// Copyright 2015 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 "sandbox/linux/services/resource_limits.h"

#include <errno.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>

#include "base/logging.h"
#include "sandbox/linux/tests/test_utils.h"
#include "sandbox/linux/tests/unit_tests.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace sandbox {

namespace {

// Not being able to fork breaks LeakSanitizer, so disable on
// all ASAN builds.
SANDBOX_TEST(ResourceLimits, DISABLE_ON_ASAN(NoFork)) {
  // Make sure that fork will fail with EAGAIN.
  SANDBOX_ASSERT(ResourceLimits::Lower(RLIMIT_NPROC, 0));
  errno = 0;
  pid_t pid = fork();
  // Reap any child if fork succeeded.
  TestUtils::HandlePostForkReturn(pid);
  SANDBOX_ASSERT_EQ(-1, pid);
  CHECK_EQ(EAGAIN, errno);
}

}  // namespace

}  // namespace sandbox

// Copyright 2015 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 "sandbox/linux/services/resource_limits.h"

#include <errno.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>

#include "base/logging.h"
#include "sandbox/linux/tests/test_utils.h"
#include "sandbox/linux/tests/unit_tests.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace sandbox {

namespace {

// Fails on Android: crbug.com/459158
#if !defined(OS_ANDROID)
#define MAYBE_NoFork DISABLE_ON_ASAN(NoFork)
#else
#define MAYBE_NoFork DISABLED_NoFork
#endif  // OS_ANDROID

// Not being able to fork breaks LeakSanitizer, so disable on
// all ASAN builds.
SANDBOX_TEST(ResourceLimits, MAYBE_NoFork) {
  // Make sure that fork will fail with EAGAIN.
  SANDBOX_ASSERT(ResourceLimits::Lower(RLIMIT_NPROC, 0));
  errno = 0;
  pid_t pid = fork();
  // Reap any child if fork succeeded.
  TestUtils::HandlePostForkReturn(pid);
  SANDBOX_ASSERT_EQ(-1, pid);
  CHECK_EQ(EAGAIN, errno);
}

}  // namespace

}  // namespace sandbox

Disable ResourceLimits.NoFork in sandbox_linux_unittests on Android.

This fixes sandbox_linux_unittests on Android.

TBR=jln@chromium.org
BUG=459158

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

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#316560}


Add Chapter 20, exercise 15

Add Chapter 20, exercise 15


#include <iostream>
#include <tuple>
#include <algorithm>
#include <vector>
#include <string>

#include "test16_62_Sales_data.h"

using namespace std;

bool compareIsbn(const Sales_data &lhs, const Sales_data &rhs) {
    return lhs.isbn() < rhs.isbn();
}

typedef tuple<vector<Sales_data>::size_type, vector<Sales_data>::const_iterator,
    vector<Sales_data>::const_iterator> matches;

vector<matches> find_book(const vector<vector<Sales_data>> &files, const string &book) {
    vector<matches> ret;
    for(auto itr = files.cbegin(); itr != files.cend(); ++ itr) {
        auto found = equal_range(itr -> cbegin(), itr -> cend(), book, compareIsbn);
        if(found.first != found.second) {
            ret.push_back(make_tuple(itr - files.cbegin(), found.first, found.second));
        }
    }
    return ret;
}

void reportResults(istream &in, ostream &os, const vector<vector<Sales_data>> &files) {
    string s;
    while(in >> s) {
        auto found = find_book(files, s);
        if(found.empty()) {
            os << s << " is not found in any stores" << endl;
        }
        for(const auto &store : found) {
            os << "store: " << get<0>(store) << " sales: "
            << accumulate(get<1>(store), get<2>(store), Sales_data(s)) << endl;
        }
    }
}

int main() {
    vector<Sales_data> store1 = {{"book1", 2, 30.0}, {"book2", 1, 15.0}, {"book2", 2, 15.0}, {"book4", 5, 20.0}};
    vector<Sales_data> store2 = {{"book1", 1, 30.0}, {"book3", 6, 12.0}, {"book4", 1, 20.0}};
    vector<vector<Sales_data>> files = {store1, store2};
    reportResults(cin, cout, files);

    return 0;
}

Add solution for chapter 17 test 4

Add solution for chapter 17 test 4


#include <iostream>

using namespace std;

const int MAX = 100;

struct Person {
  string firstName;
  string lastName;

  void input() {
    cout << "Enter person's first and last names separated by a space: ";
    cin >> firstName >> lastName;
  }

  void print() {
    cout << firstName << ' ' << lastName << '\n';
  }
};

struct Client {
  Person person;
  double account;

  void input() {
    person.input();

    cout << "Enter account: ";
    cin >> account;
  }

  void print() {
    person.print();
    cout << "Account: " << account << '\n';
  };
};

void inputClients(int n) {
  Client clients[MAX];

  for (int i = 0; i < n; ++i) {
    clients[i].input();
  }
}

void printClients(Client clients[], int n) {
  for (int i = 0; i < n; ++i) {
    clients[i].print();
  }
}

double sumAccounts(Client clients[], int n) {
  double sum = 0;

  for (int i = 0; i < n; ++i) {
    sum += clients[i].account;
  }

  return sum;
}

int main() {
  return 0;
}

Add solution to first problem

Add solution to first problem


// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/javascript_environment.h"

#include "base/command_line.h"
#include "gin/array_buffer.h"
#include "gin/v8_initializer.h"

namespace atom {

JavascriptEnvironment::JavascriptEnvironment()
    : initialized_(Initialize()),
      isolate_(isolate_holder_.isolate()),
      isolate_scope_(isolate_),
      locker_(isolate_),
      handle_scope_(isolate_),
      context_(isolate_, v8::Context::New(isolate_)),
      context_scope_(v8::Local<v8::Context>::New(isolate_, context_)) {
}

bool JavascriptEnvironment::Initialize() {
  auto cmd = base::CommandLine::ForCurrentProcess();
  if (cmd->HasSwitch("debug-brk")) {
    // Need to be called before v8::Initialize().
    const char expose_debug_as[] = "--expose_debug_as=v8debug";
    v8::V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
  }
  gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode,
                                 gin::ArrayBufferAllocator::SharedInstance());
  return true;
}

}  // namespace atom

// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include <string>

#include "atom/browser/javascript_environment.h"

#include "base/command_line.h"
#include "gin/array_buffer.h"
#include "gin/v8_initializer.h"

namespace atom {

JavascriptEnvironment::JavascriptEnvironment()
    : initialized_(Initialize()),
      isolate_(isolate_holder_.isolate()),
      isolate_scope_(isolate_),
      locker_(isolate_),
      handle_scope_(isolate_),
      context_(isolate_, v8::Context::New(isolate_)),
      context_scope_(v8::Local<v8::Context>::New(isolate_, context_)) {
}

bool JavascriptEnvironment::Initialize() {
  auto cmd = base::CommandLine::ForCurrentProcess();
  if (cmd->HasSwitch("debug-brk")) {
    // Need to be called before v8::Initialize().
    const char expose_debug_as[] = "--expose_debug_as=v8debug";
    v8::V8::SetFlagsFromString(expose_debug_as, sizeof(expose_debug_as) - 1);
  }

  const std::string js_flags_switch = "js-flags";

  if (cmd->HasSwitch(js_flags_switch)) {
    const char *js_flags_value =
      (cmd->GetSwitchValueASCII(js_flags_switch)).c_str();
    v8::V8::SetFlagsFromString(js_flags_value, strlen(js_flags_value));
  }

  gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode,
                                 gin::ArrayBufferAllocator::SharedInstance());

  return true;
}

}  // namespace atom

Add --js-flags support for main thread.

Add --js-flags support for main thread.

Allow use of flags that must be set before V8 is initialized, such as
"--harmony_proxies", e.g. --js-flags="--harmony_proxies
--harmony_collections"


#include <iostream>
#include <vector>

#include <UnitTest++.h>
#include "model/focus-cycle.h"
#include "logging/logging.h"
#include "logging/stream.h"

const int last_window = 9;
StreamLog log(std::cerr);

struct FocusCycleFixture
{
    FocusCycle cycle;
    std::vector<Window> windows;

    FocusCycleFixture() :
        cycle(log)
    {
        for (int win = 0; win < last_window + 1; win++)
        {
            windows.push_back(win);
        }

        cycle.update_window_list(windows);
    }
};

SUITE(FocusModelSuite)
{
    /**
     * Ensures that FocusCycle.get_next returns the correct value in cases when
     * it doesn't wrap around.
     */
    TEST_FIXTURE(FocusCycleFixture, test_gets_windows)
    {
        // It starts at the first window, but get_next() doesn't return it, so
        // we have to start at the second window.
        for (int win = 1; win < last_window + 1; win++)
        {
            CHECK_EQUAL(cycle.get_next(), win);
        }
    }

    /**
     * This ensures that the FocusCycle wraps around when it gets past the
     * last window.
     */
    TEST_FIXTURE(FocusCycleFixture, test_wraparound)
    {
        for (int win = 1; win < last_window + 1; win++)
        {
            cycle.get_next();
        }

        CHECK_EQUAL(cycle.get_next(), 0);
    }

    /**
     * This ensures that setting the focus to a valid window causes the window
     * after it to be returned by get_next.
     */
    TEST_FIXTURE(FocusCycleFixture, test_set_focus)
    {
        // As before, setting the focus means that the window *after* the current
        // focus will be returned by get_next
        cycle.set_focus(5);
        for (int win = 6; win < last_window; win++)
        {
            CHECK_EQUAL(cycle.get_next(), win);
        }
    }

    /**
     * This ensures that setting the focus to an invalid window does nothing.
     */
    TEST_FIXTURE(FocusCycleFixture, test_set_invalid)
    {
        // As before, setting the focus means that the window *after* the current
        // focus will be returned by get_next
        cycle.set_focus(100);
        CHECK_EQUAL(cycle.get_next(), 1);
    }
}

int main()
{
    return UnitTest::RunAllTests();
}

Add a test for FocusCycle.

Add a test for FocusCycle.


#include "TaskBase.h"
#include <gtest/gtest.h>
#include <unistd.h>

using namespace tpool;

namespace {
  struct FakeTask : public TaskBase {
    virtual void DoRun()
    {
      sleep(2);
    }
  };
}

TEST(TaskBase, test_GetState)
{
  FakeTask task;

  EXPECT_EQ(TaskBase::INIT, task.GetState());

}

Add unit test for TaskBase.

Add unit test for TaskBase.


#include <QApplication>
#include <QMainWindow>
#include <QToolBar>
#include <QDir>
#include <QDebug>
#include "../placesview.h"
#include "libfmqt.h"

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

    Fm::LibFmQt contex;
    QMainWindow win;

    Fm::PlacesView view;
    win.setCentralWidget(&view);

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

Add a missing test case for places view.


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

#include <limits.h>

const bool swchar = (wchar_t)-1 > (wchar_t)0;

#ifdef __WCHAR_UNSIGNED__
int signed_test[!swchar];
#else
int signed_test[swchar];
#endif

int max_test[WCHAR_MAX == (swchar ? -(WCHAR_MIN+1) : (wchar_t)-1)];
int min_test[WCHAR_MIN == (swchar ? 0 : -WCHAR_MAX-1)];

Add a missing test for the limits on wchar

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


#include <iostream>

using namespace std;

bool check_pow_2(int num) {
    if ((num & (num-1)) == 0)
    	return true;
    return false;
}

int main() {
    int num = 2;

    check_pow_2(num) ? cout << "Num is a Power of 2" : cout << "Num is not a power of 2";
    cout << endl;

    num = 5;
    check_pow_2(num) ? cout << "Num is a Power of 2" : cout << "Num is not a power of 2";
    cout << endl;

    return 0;
}

Check power of 2 cpp

Check power of 2 cpp


// 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/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

static const double kErrorUploadRatio = 0.0;
void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  // We only want to upload |kErrorUploadRatio| ratio of errors.
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync

// 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/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/rand_util.h"
#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#endif

#include "chrome/common/chrome_constants.h"

namespace browser_sync {

static const double kErrorUploadRatio = 0.15;
void ChromeReportUnrecoverableError() {
  // TODO(lipalani): Add this for other platforms as well.
#if defined(OS_WIN)
  // We only want to upload |kErrorUploadRatio| ratio of errors.
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  // Get the breakpad pointer from chrome.exe
  typedef void (__cdecl *DumpProcessFunction)();
  DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>(
      ::GetProcAddress(::GetModuleHandle(
                       chrome::kBrowserProcessExecutableName),
                       "DumpProcessWithoutCrash"));
  if (DumpProcess)
    DumpProcess();
#endif  // OS_WIN

}

}  // namespace browser_sync

Revert 144124 - [Sync] Set error upload rate to 0.

This prevents sync from uploading error stacks to breakpad.

BUG=134607
TEST=

Review URL: https://chromiumcodereview.appspot.com/10664028

TBR=zea@chromium.org
Review URL: https://chromiumcodereview.appspot.com/10680007

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


// RUN: %clang_cc1 -mconstructor-aliases -fms-extensions %s -emit-llvm -o - -triple x86_64-windows-msvc | FileCheck %s

struct __declspec(dllexport) A { virtual ~A(); };
struct __declspec(dllexport) B { virtual ~B(); };
struct __declspec(dllexport) C : A, B { virtual ~C(); };
C::~C() {}

// This thunk should *not* be dllexport.
// CHECK: define linkonce_odr i8* @"\01??_EC@@W7EAAPEAXI@Z"
// CHECK: define dllexport void @"\01??1C@@UEAA@XZ"

[MS] Test that deleting destructor thunks are not exported

The MSVC linker emits the LNK4102 warning if they are.

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


//===-- asan_dll_thunk.cc -------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// This file defines a family of thunks that should be statically linked into
// the DLLs that have ASan instrumentation in order to delegate the calls to the
// shared runtime that lives in the main binary.
// See https://code.google.com/p/address-sanitizer/issues/detail?id=209 for the
// details.
//===----------------------------------------------------------------------===//

// Only compile this code when buidling asan_dll_thunk.lib
// Using #ifdef rather than relying on Makefiles etc.
// simplifies the build procedure.
#ifdef ASAN_DLL_THUNK
#include <windows.h>

// ------------------------- Helper macros ------------------ {{{1

static FARPROC getRealProcAddressOrDie(const char *name) {
  FARPROC ret = GetProcAddress(GetModuleHandle(NULL), name);
  if (!ret)
    abort();
  return ret;
}

#define WRAP_VV(name)                                                          \
  extern "C" void name() {                                                     \
    typedef void (*fntype)();                                                  \
    fntype fn = (fntype)getRealProcAddressOrDie(#name);                        \
    fn();                                                                      \
  }

#define WRAP_VW(name)                                                          \
  extern "C" void name(void *arg) {                                            \
    typedef void (*fntype)(void *arg);                                         \
    fntype fn = (fntype)getRealProcAddressOrDie(#name);                        \
    fn(arg);                                                                   \
  }

#define WRAP_VWW(name)                                                         \
  extern "C" void name(void *arg1, void *arg2) {                               \
    typedef void (*fntype)(void *, void *);                                    \
    fntype fn = (fntype)getRealProcAddressOrDie(#name);                        \
    fn(arg1, arg2);                                                            \
  }
// }}}

WRAP_VV(__asan_init_v3)

WRAP_VW(__asan_report_store1)
WRAP_VW(__asan_report_store2)
WRAP_VW(__asan_report_store4)
WRAP_VW(__asan_report_store8)
WRAP_VW(__asan_report_store16)
WRAP_VWW(__asan_report_store_n)

WRAP_VW(__asan_report_load1)
WRAP_VW(__asan_report_load2)
WRAP_VW(__asan_report_load4)
WRAP_VW(__asan_report_load8)
WRAP_VW(__asan_report_load16)
WRAP_VWW(__asan_report_load_n)

WRAP_VWW(__asan_register_globals)
WRAP_VWW(__asan_unregister_globals)

// TODO(timurrrr): Add more interface functions on the as-needed basis.

// TODO(timurrrr): Add malloc & friends (see asan_malloc_win.cc).

#endif // ASAN_DLL_THUNK

[ASan/Win] Add the first version of the RTL thunk that should be linked with instrumented DLLs

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


#include <iostream>
#include <string>

#include "test16_2_compare.h"

using namespace std;

template <typename It>
auto fcn3(It beg, It end) -> decltype(*beg + 0) {
    return *beg;
}

int main() {
    cout << compare<char*>("hi", "world") << endl;
    cout << compare<string>("dad", "bye") << endl;
    return 0;
}

Add solution for chapter 16 test 39.

Add solution for chapter 16 test 39.


#include <botan/botan.h>
#include <botan/benchmark.h>
#include <botan/filters.h>

#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <cstdlib>

/*
Try to find the fastest SHA-1 implementation and use it to hash
files. In most programs this isn't worth the bother and
overhead. However with large amount of input, it is worth it. On tests
on a Core2 system with the SHA-1 SSE2 code enabled, over a few hundred
Mb or so the overhead paid for itself.

Of course you could also just do this once and save it as an
application config, which is probably the smart thing to do.
*/

void set_fastest_implementation(const std::string& algo,
                                Botan::RandomNumberGenerator& rng,
                                double ms = 30)
   {
   Botan::Default_Benchmark_Timer timer;

   Botan::Algorithm_Factory& af = Botan::global_state().algorithm_factory();

   std::map<std::string, double> results =
      Botan::algorithm_benchmark(algo, ms, timer, rng, af);

   std::string fastest_provider = "";
   double best_res = 0;

   for(std::map<std::string, double>::iterator r = results.begin();
       r != results.end(); ++r)
      {
      std::cout << r->first << " @ " << r->second << " MiB/sec\n";

      if(fastest_provider == "" || r->second > best_res)
         {
         fastest_provider = r->first;
         best_res = r->second;
         }
      }

   std::cout << "Using " << fastest_provider << "\n";

   af.set_preferred_provider(algo, fastest_provider);
   }

int main(int argc, char* argv[])
   {
   if(argc <= 1)
      {
      std::cout << "Usage: " << argv[0] << " <file> <file> ...\n";
      return 1;
      }

   Botan::LibraryInitializer init;
   Botan::AutoSeeded_RNG rng;

   const std::string hash = "SHA-1";

   //set_fastest_implementation(hash, rng);

   // Here we intentionally use the 'old style' lookup interface
   // which will also respect the provider settings. Or can use:
   //   global_state().algorithm_factory().make_hash_function(hash)
   Botan::Pipe pipe(
      new Botan::Hash_Filter(Botan::get_hash(hash)),
      new Botan::Hex_Encoder
      );

   for(size_t i = 1; argv[i]; ++i)
      {
      std::ifstream in(argv[i]);
      if(!in)
         continue;

      pipe.start_msg();
      in >> pipe;
      pipe.end_msg();

      std::cout << argv[i] << " = "
                << pipe.read_all_as_string(Botan::Pipe::LAST_MESSAGE) << "\n";

      }
   }

Add an example of using the benchmark system to choose the fastest SHA-1 implementation and then setting it as the default.


/*
	This program tests Counting sort
*/

#include<iostream>
#include<vector>
#include "countingsort.h"	// My implementation of Counting sort

// Displays vector

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

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

// Tests Counting sort on vector A

void testCountingSort(std::vector<int> A, int k){

	std::cout<<"Before: ";
	printVector(A);
	CountingSort::sort(A, k);
	std::cout<<"After: ";
	printVector(A);
}

// tests Counting sort on several different inputs

void testCountingSort(){

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

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

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

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

	// test on empty vector
	std::vector<int> v5;
	testCountingSort(v5, 5);

	std::vector<int> v6 = {100,152,0,64,36,19,43,22,97,33,46,95,73,20};
	testCountingSort(v6, 152);

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

int main(){

	// test Counting sort
	testCountingSort();

	return 0;
}

Add test program for counting sort

Add test program for counting sort


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

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

// EWS provides two methods that allow you to discover changes that have
// occurred in your mailbox from some starting point (indicated by a
// sync_state) until the time the request is made:
//
// - sync_folder_hierarchy is used to watch for changes made to your mailbox's
//   folders
// - sync_folder_items is used to determine changes to the contents of a single
//   folder
//
// This example is about the latter.

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

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

        ews::distinguished_folder_id folder = ews::standard_folder::inbox;

        // Initial synchronization call
        auto result = service.sync_folder_hierarchy(folder);

        // Store sync_state for further synchronization calls
        const auto sync_state = result.get_sync_state();

        // Output all existing folders
        for (const auto& folder : result.get_created_folders())
        {
            std::cout << folder.get_display_name() << "\n";
        }

        // Create test folder
        ews::folder new_folder;
        new_folder.set_display_name("Duck Cave");
        auto new_folder_id = service.create_folder(new_folder, folder);

        // Follow-up synchronization call
        result = service.sync_folder_hierarchy(folder, sync_state);

        // Output all newly created folders
        for (const auto& folder : result.get_created_folders())
        {
            std::cout << folder.get_display_name() << "\n";
        }

        // Delete test item
        service.delete_folder(new_folder_id);

        // Follow-up synchronization call
        result = service.sync_folder_hierarchy(folder, sync_state);

        // Output all deleted folders
        for (const auto& folder : result.get_deleted_folder_ids())
        {
            std::cout << folder.id() << "\n";
        }
    }
    catch (std::exception& exc)
    {
        std::cout << exc.what() << std::endl;
        res = EXIT_FAILURE;
    }

    ews::tear_down();
    return res;
}

Add example for SyncFolderHierarchy operation


// -*- C++ -*-
//===----------------------------------------------------------------------===//
//
//                     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.
//
//===----------------------------------------------------------------------===//

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

// <tuple>

// template <class TupleLike> tuple(TupleLike&&); // libc++ extension

// See llvm.org/PR31384

#include <tuple>
#include <cassert>

int count = 0;

template<class T>
struct derived : std::tuple<T> {
  using std::tuple<T>::tuple;
  template<class U>
  operator std::tuple<U>() && {
    ++count;
    return {};
  }
};

int main() {
  std::tuple<int> foo = derived<int&&>{42};
  assert(count == 1);
}

Add test case for PR31384

Add test case for PR31384

git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@289774 91177308-0d34-0410-b5e6-96231b3b80d8


//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// packet_manager_test.cpp
//
// Identification: test/wire/packet_manager_test.cpp
//
// Copyright (c) 2016-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "common/harness.h"
#include "gtest/gtest.h"
#include "common/logger.h"
#include "wire/libevent_server.h"
#include <pqxx/pqxx>

#define NUM_THREADS 1

namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Packet Manager Tests
//===--------------------------------------------------------------------===//

class PacketManagerTests: public PelotonTest {
};

static void* LaunchServer(void *) {
	try {
		// Setup
		peloton::PelotonInit::Initialize();
		LOG_INFO("Server initialized\n");
		// Launch server
		peloton::wire::LibeventServer libeventserver;
		LOG_INFO("Server Closed\n");
		// Teardown
		// Todo: Peloton cannot shut down normally, will try to fix this soon
		//peloton::PelotonInit::Shutdown();
		LOG_INFO("Peloton has shut down\n");
	} catch (peloton::ConnectionException exception) {
		// Nothing to do here!
	}
	return NULL;
}

static void* SimpleQueryTest(void *) {
	try {
		pqxx::connection C("host=127.0.0.1 port=15721 user=postgres sslmode=disable");
		LOG_INFO("Connected to %s\n", C.dbname());
		pqxx::work W(C);

		// create table and insert some data
		W.exec("DROP TABLE IF EXISTS employee;");
		W.exec("CREATE TABLE employee(id INT, name VARCHAR(100));");
		W.exec("INSERT INTO employee VALUES (1, 'Han LI');");
		W.exec("INSERT INTO employee VALUES (2, 'Shaokun ZOU');");
		W.exec("INSERT INTO employee VALUES (3, 'Yilei CHU');");

		pqxx::result R = W.exec("SELECT name FROM employee where id=1;");

		EXPECT_EQ(R.size(), 1);
		LOG_INFO("Found %lu employees\n", R.size());
		W.commit();
	} catch (const std::exception &e) {
		LOG_INFO("Exception occurred\n");
	}

	LOG_INFO("Client has closed\n");
	return NULL;
}

TEST_F(PacketManagerTests, SimpleQueryTest) {
	pthread_t threads[NUM_THREADS];
	int rc = pthread_create(&threads[0], NULL, LaunchServer, NULL);
	if (rc) {
		LOG_INFO("Error:unable to create server thread");
		exit(-1);
	}
	sleep(5);

	SimpleQueryTest(NULL);

	pthread_kill(threads[0], SIGHUP);
	pthread_join(threads[0], NULL);
}

}  // End test namespace
}  // End peloton namespace

Add simple wire protocol test

Add simple wire protocol test


AliAnalysisTaskStrangenessLifetimes *AddTaskStrangenessLifetimes(
    TString tskname = "LifetimesFiltering", TString suffix = "") {
  // Get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskStrangenessLifetimes", "No analysis manager found.");
    return 0x0;
  }

  // Check the analysis type using the event handlers connected to the analysis
  // manager.
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskStrangenessLifetimes",
            "This task requires an input event handler");
    return 0x0;
  }

  tskname.Append(suffix.Data());
  AliAnalysisTaskStrangenessLifetimes *task =
      new AliAnalysisTaskStrangenessLifetimes(tskname.Data());

  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(
      Form("%s_summary", tskname.Data()), TList::Class(),
      AliAnalysisManager::kOutputContainer, "AnalysisResults.root");

  AliAnalysisDataContainer *coutput2 =
      mgr->CreateContainer(Form("V0tree%s", suffix.Data()), TTree::Class(),
                           AliAnalysisManager::kOutputContainer, "V0tree.root");
  coutput2->SetSpecialOutput();

  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, coutput1);
  mgr->ConnectOutput(task, 2, coutput2);
  return task;
}

AliAnalysisTaskStrangenessLifetimes *AddTaskStrangenessLifetimes(bool isMC = false,
    TString tskname = "LifetimesFiltering", TString suffix = "") {
  // Get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskStrangenessLifetimes", "No analysis manager found.");
    return 0x0;
  }

  // Check the analysis type using the event handlers connected to the analysis
  // manager.
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskStrangenessLifetimes",
            "This task requires an input event handler");
    return 0x0;
  }

  tskname.Append(suffix.Data());
  AliAnalysisTaskStrangenessLifetimes *task =
      new AliAnalysisTaskStrangenessLifetimes(isMC, tskname.Data());

  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(
      Form("%s_summary", tskname.Data()), TList::Class(),
      AliAnalysisManager::kOutputContainer, "AnalysisResults.root");

  AliAnalysisDataContainer *coutput2 =
      mgr->CreateContainer(Form("V0tree%s", suffix.Data()), TTree::Class(),
                           AliAnalysisManager::kOutputContainer, "V0tree.root");
  coutput2->SetSpecialOutput();

  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, coutput1);
  mgr->ConnectOutput(task, 2, coutput2);
  return task;
}

Enable MC flag in the AddTask 😅

Enable MC flag in the AddTask 😅


// https://leetcode.com/problems/word-search/
// Using a DFS solution, stop as early as possible.

class Solution {
    bool dfs(const vector<vector<char> > &board,
             int r, int c,
             const char* word,
             vector<vector<bool> >* visited){
        if (*word != board[r][c]) {
            return false;
        }
        if (*(word+1) == '\0') {
            return true;
        }
        (*visited)[r][c] = true;
        int offr[] = {0, -1, 0, 1};
        int offc[] = {-1, 0, 1, 0};
        for (int i = 0; i < 4; ++i) {
            int nr = r + offr[i];
            int nc = c + offc[i];
            if (nr >= 0 && nr < board.size() && nc >= 0 && nc < board[0].size() && !(*visited)[nr][nc]) {
                if (dfs(board, nr, nc, word+1, visited)) {
                    return true;
                }
            }
        }
        (*visited)[r][c] = false;

        return false;
    }
public:
    bool exist(vector<vector<char> > &board, string word) {
        int nrows = board.size();
        if (nrows == 0) return false;
        int ncols = board[0].size();
        if (ncols == 0) return false;

        vector<vector<bool> > visited(nrows, vector<bool>(ncols, false));
        for (int r = 0; r < nrows; ++r) {
            for (int c = 0; c < ncols; ++c) {
                if (dfs(board, r, c, word.c_str(), &visited)) {
                    return true;
                }
            }
        }
        return false;
    }
};

Add a solution for problem 79: Word Search.


/**
 * @file       main.cpp
 * @author     Volodymyr Shymanskyy
 * @license    This project is released under the MIT License (MIT)
 * @copyright  Copyright (c) 2015 Volodymyr Shymanskyy
 * @date       Mar 2015
 * @brief
 */

//#define BLYNK_DEBUG
#define BLYNK_PRINT stdout
#ifdef RASPBERRY
 #include <BlynkApiWiringPi.h>
#else
 #include <BlynkApiLinux.h>
#endif
#include <BlynkSocket.h>
#include <BlynkOptionsParser.h>

static BlynkTransportSocket _blynkTransport;
BlynkSocket Blynk(_blynkTransport);

BLYNK_WRITE(1)
{
  BLYNK_LOG("Got a value: %s", param[0].asStr());
}

int main(int argc, char* argv[])
{
    const char *auth, *serv, *port;
    parse_options(argc, argv, auth, serv, port);

    Blynk.begin(auth, serv, port);

    while(true) {
        Blynk.run();
    }

    return 0;
}

/**
 * @file       main.cpp
 * @author     Volodymyr Shymanskyy
 * @license    This project is released under the MIT License (MIT)
 * @copyright  Copyright (c) 2015 Volodymyr Shymanskyy
 * @date       Mar 2015
 * @brief
 */

//#define BLYNK_DEBUG
#define BLYNK_PRINT stdout
#ifdef RASPBERRY
 #include <BlynkApiWiringPi.h>
#else
 #include <BlynkApiLinux.h>
#endif
#include <BlynkSocket.h>
#include <BlynkOptionsParser.h>

static BlynkTransportSocket _blynkTransport;
BlynkSocket Blynk(_blynkTransport);

BLYNK_WRITE(V1)
{
  BLYNK_LOG("Got a value: %s", param[0].asStr());
}

int main(int argc, char* argv[])
{
    const char *auth, *serv, *port;
    parse_options(argc, argv, auth, serv, port);

    Blynk.begin(auth, serv, port);

    while(true) {
        Blynk.run();
    }

    return 0;
}

Fix pin name in example

Fix pin name in example


#include "Halide.h"

using namespace Halide;

bool errored = false;
void my_error(void *, const char *msg) {
    printf("Expected error: %s\n", msg);
    errored = true;
}

void my_print(void *, const char *msg) {
    // Empty to neuter debug message spew
}

int main(int argc, char **argv) {
    Target t = get_jit_target_from_environment();
    if (!t.has_feature(Target::CUDA)) {
        printf("Not running test because cuda not enabled\n");
        return 0;
    }

    // Turn on debugging so that the pipeline completes and error
    // checking is done before realize returns. Otherwise errors are
    // discovered too late to call a custom error handler.
    t.set_feature(Target::Debug);

    Func f;
    Var c, x;
    f(c, x) = x + c + 3;
    f.bound(c, 0, 3).unroll(c);

    Func g;
    g(c, x) = f(c, x) * 8;

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

    g.set_error_handler(&my_error);
    g.set_custom_print(&my_print);

    // Should succeed
    g.realize(3, 100, t);
    if (errored) {
        printf("There was not supposed to be an error\n");
        return -1;
    }

    // Should trap
    g.realize(4, 100, t);

    if (!errored) {
        printf("There was supposed to be an error\n");
        return -1;
    }

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

Add test for gpu assertions

Add test for gpu assertions


#include <iostream>
#include <cstring>

using namespace std;

class Dog {
    char name[30];
public:
    Dog(const char _name[] = "") {
        strcpy(name, _name);
    }
    void greet() {
        cout << "Bark, bark! I am " << name << ", a talking dog." << endl;
    }
};

class Person {
    char name[30];
    int age;
    Dog dog;
public:
    Person(const char _name[], int _age, Dog _dog) {
        strcpy(name, _name);
        age = _age;
        dog = _dog;
    }
    void greet() {
        cout << "Hi! I am " << name << " and I am " << age << " years old." << endl;
        cout << "And this is my dog:" << endl;
        dog.greet();
    }
};

int main() {
    Person ivan("Ivan", 15, Dog("Johny"));
    ivan.greet();

    return 0;
}

Add solution to task one using cstring Use char[] instead of string for demonstration