// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest LLC.
//
// 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 <gtest/gtest.h>
#include <SurgSim/Framework/Runtime.h>
#include <SurgSim/Framework/Scene.h>

using namespace SurgSim::Framework;

TEST(SceneTest, ConstructorTest)
{
	ASSERT_NO_THROW( {Scene scene;});
}

// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest LLC.
//
// 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 <gtest/gtest.h>
#include "MockObjects.h"
#include <SurgSim/Framework/Runtime.h>
#include <SurgSim/Framework/Scene.h>

using namespace SurgSim::Framework;

TEST(SceneTest, ConstructorTest)
{
	ASSERT_NO_THROW( {Scene scene;});
}

TEST(SceneTest, ElementManagement)
{
	std::shared_ptr<Scene> scene(new Scene());
	std::shared_ptr<MockSceneElement> element1(new MockSceneElement("one"));
	std::shared_ptr<MockSceneElement> element2(new MockSceneElement("two"));

	EXPECT_EQ(0, scene->getSceneElements().size());

	EXPECT_TRUE(scene->addSceneElement(element1));
	EXPECT_EQ(1, scene->getSceneElements().size());
	EXPECT_TRUE(scene->addSceneElement(element2));
	EXPECT_EQ(2, scene->getSceneElements().size());

	EXPECT_FALSE(scene->addSceneElement(element1));
	EXPECT_EQ(2, scene->getSceneElements().size());

	EXPECT_EQ(element1, scene->getSceneElement("one"));
	EXPECT_EQ(element2, scene->getSceneElement("two"));
	EXPECT_EQ(nullptr, scene->getSceneElement("nonexistentelement"));
}

Add tests for Scene, SceneElement access


/*
 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
 *
 * 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.
 *
 */

// CLASS HEADER
#include "color-controller-impl.h"

namespace Dali
{

namespace Internal
{

namespace Adaptor
{

Dali::ColorController ColorController::Get()
{
  Dali::ColorController colorController;
  return colorController;
}

ColorController::ColorController()
{
}

ColorController::~ColorController()
{
}

bool ColorController::RetrieveColor( const std::string& colorCode, Vector4& colorValue )
{
  return false;
}

bool ColorController::RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor)
{
  return false;
}

} // namespace Adaptor

} // namespace Internal

} // namespace Dali

/*
 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
 *
 * 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.
 *
 */

// CLASS HEADER
#include "color-controller-impl.h"

namespace Dali
{

namespace Internal
{

namespace Adaptor
{

Dali::ColorController ColorController::Get()
{
  return Dali::ColorController( new ColorController() );
}

ColorController::ColorController()
{
}

ColorController::~ColorController()
{
}

bool ColorController::RetrieveColor( const std::string& colorCode, Vector4& colorValue )
{
  return false;
}

bool ColorController::RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor)
{
  return false;
}

} // namespace Adaptor

} // namespace Internal

} // namespace Dali

Fix for ColorController.
Creates an internal implementation for the default color controller to avoid a crash if it's called.

[problem] Crash if the default ColorController is used.
[cause] There is no internal implementation.
[solution] Create an internal implementation.

Change-Id: I49ac335ed6db2dfc68b6dae3beea42c1b5db275e
Signed-off-by: Victor Cebollada <bd4ca07245b7f4eb2d3ace02513dff6e050d7f4b@samsung.com>


// Test that -Weverything does not trigger any backend remarks.
//
// This was triggering backend remarks for which there were no frontend
// flags to filter them. The handler in BackendConsumer::DiagnosticHandlerImpl
// should not emitting diagnostics for unhandled kinds.

// RUN: %clang -c -Weverything -O0 -o /dev/null %s 2> %t.err
// RUN: FileCheck < %t.err %s

typedef __char32_t char32_t;
typedef long unsigned int size_t;
template <class _CharT>
struct __attribute__((__type_visibility__("default"))) char_traits;

template <>
struct __attribute__((__type_visibility__("default"))) char_traits<char32_t> {
  typedef char32_t char_type;
  static void assign(char_type& __c1, const char_type& __c2) throw() {
    __c1 = __c2;
  }
  static char_type* move(char_type* __s1, const char_type* __s2, size_t __n);
};
char32_t* char_traits<char32_t>::move(char_type* __s1, const char_type* __s2,
                                      size_t __n) {
  { assign(*--__s1, *--__s2); }
}

// CHECK-NOT: {{^remark:}}

// Test that -Weverything does not trigger any backend remarks.
//
// This was triggering backend remarks for which there were no frontend
// flags to filter them. The handler in BackendConsumer::DiagnosticHandlerImpl
// should not emitting diagnostics for unhandled kinds.

// RUN: %clang -c -S -Weverything -O0 -o /dev/null %s 2> %t.err
// RUN: FileCheck < %t.err %s

typedef __char32_t char32_t;
typedef long unsigned int size_t;
template <class _CharT>
struct __attribute__((__type_visibility__("default"))) char_traits;

template <>
struct __attribute__((__type_visibility__("default"))) char_traits<char32_t> {
  typedef char32_t char_type;
  static void assign(char_type& __c1, const char_type& __c2) throw() {
    __c1 = __c2;
  }
  static char_type* move(char_type* __s1, const char_type* __s2, size_t __n);
};
char32_t* char_traits<char32_t>::move(char_type* __s1, const char_type* __s2,
                                      size_t __n) {
  { assign(*--__s1, *--__s2); }
}

// CHECK-NOT: {{^remark:}}

Add missing -S to avoid invoking assembler unnecessarily.

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


#include "agent_based_epidemic_sim/util/records.h"

namespace abesim {

constexpr int kReadFlag = O_RDONLY;
constexpr int kWriteFlag = O_CREAT | O_WRONLY;

riegeli::RecordReader<RiegeliBytesSource> MakeRecordReader(
    absl::string_view filename) {
  return riegeli::RecordReader<RiegeliBytesSource>(
      std::forward_as_tuple(filename, kReadFlag));
}
riegeli::RecordWriter<RiegeliBytesSink> MakeRecordWriter(
    absl::string_view filename, const int parallelism) {
  return riegeli::RecordWriter<RiegeliBytesSink>(
      std::forward_as_tuple(filename, kWriteFlag),
      riegeli::RecordWriterBase::Options().set_parallelism(parallelism));
}

}  // namespace abesim

#include "agent_based_epidemic_sim/util/records.h"

namespace abesim {

constexpr int kReadFlag = O_RDONLY;
constexpr int kWriteFlag = O_CREAT | O_WRONLY;

riegeli::RecordReader<RiegeliBytesSource> MakeRecordReader(
    absl::string_view filename) {
  return riegeli::RecordReader(RiegeliBytesSource(filename, kReadFlag));
}
riegeli::RecordWriter<RiegeliBytesSink> MakeRecordWriter(
    absl::string_view filename, const int parallelism) {
  return riegeli::RecordWriter(
      RiegeliBytesSink(filename, kWriteFlag),
      riegeli::RecordWriterBase::Options().set_parallelism(parallelism));
}

}  // namespace abesim

Improve readability of constructor calls of Riegeli classes.

Write the type name instead of `std::forward_as_tuple` for construction of
dependencies of these classes. This looks better, at the cost of a tiny
performance hit: the dependency is constructed as a temporary and then moved,
instead of being constructed in place.

Rely on CTAD
(https://en.cppreference.com/w/cpp/language/class_template_argument_deduction)
for Riegeli classes to avoid writing the class template argument, in cases the
template argument reflects the type of the first constructor argument. Riegeli
classes provide deduction guides to make it clear that this is supported.

CTAD requires C++17.

PiperOrigin-RevId: 364632707


/**
 * \file
 * \brief chip::lowLevelInitialization() implementation for STM32L0
 *
 * \author Copyright (C) 2017 Cezary Gapinski cezary.gapinski@gmail.com
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/chip/lowLevelInitialization.hpp"

namespace distortos
{

namespace chip
{

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

void lowLevelInitialization()
{

}

}	// namespace chip

}	// namespace distortos

/**
 * \file
 * \brief chip::lowLevelInitialization() implementation for STM32L0
 *
 * \author Copyright (C) 2017 Cezary Gapinski cezary.gapinski@gmail.com
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "distortos/chip/lowLevelInitialization.hpp"

#include "distortos/chip/STM32L0-FLASH.hpp"

namespace distortos
{

namespace chip
{

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

void lowLevelInitialization()
{
#ifdef CONFIG_CHIP_STM32L0_FLASH_PREFETCH_ENABLE
	configurePrefetchBuffer(true);
#else	// !def CONFIG_CHIP_STM32L0_FLASH_PREFETCH_ENABLE
	configurePrefetchBuffer(false);
#endif	// !def CONFIG_CHIP_STM32L0_FLASH_PREFETCH_ENABLE
}

}	// namespace chip

}	// namespace distortos

Handle flash options in chip::lowLevelInitialization() for STM32L0


// Copyright (c) 2008-2009 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/history/history_publisher.h"

#include "base/utf_string_conversions.h"

namespace history {

const char* const HistoryPublisher::kThumbnailImageFormat = "image/jpeg";

void HistoryPublisher::PublishPageThumbnail(
    const std::vector<unsigned char>& thumbnail, const GURL& url,
    const base::Time& time) const {
  PageData page_data = {
    time,
    url,
    NULL,
    NULL,
    kThumbnailImageFormat,
    &thumbnail,
  };

  PublishDataToIndexers(page_data);
}

void HistoryPublisher::PublishPageContent(const base::Time& time,
                                          const GURL& url,
                                          const std::wstring& title,
                                          const string16& contents) const {
  PageData page_data = {
    time,
    url,
    UTF16ToWide(contents).c_str(),
    title.c_str(),
    NULL,
    NULL,
  };

  PublishDataToIndexers(page_data);
}

}  // namespace history

// Copyright (c) 2008-2009 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/history/history_publisher.h"

#include "base/utf_string_conversions.h"

namespace history {

const char* const HistoryPublisher::kThumbnailImageFormat = "image/jpeg";

void HistoryPublisher::PublishPageThumbnail(
    const std::vector<unsigned char>& thumbnail, const GURL& url,
    const base::Time& time) const {
  PageData page_data = {
    time,
    url,
    NULL,
    NULL,
    kThumbnailImageFormat,
    &thumbnail,
  };

  PublishDataToIndexers(page_data);
}

void HistoryPublisher::PublishPageContent(const base::Time& time,
                                          const GURL& url,
                                          const std::wstring& title,
                                          const string16& contents) const {
  std::wstring wide_contents = UTF16ToWide(contents);
  PageData page_data = {
    time,
    url,
    wide_contents.c_str(),
    title.c_str(),
    NULL,
    NULL,
  };

  PublishDataToIndexers(page_data);
}

}  // namespace history

Make sure the pointer in PageData::html remains valid while PageData is called.

BUG=46835

Review URL: http://codereview.chromium.org/2852014

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


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

#include <tao/pegtl.hpp>
#include <tao/pegtl/contrib/json.hpp>
#include <tao/pegtl/contrib/trace2.hpp>

namespace pegtl = TAO_PEGTL_NAMESPACE;

using grammar = pegtl::must< pegtl::json::text >;

int main( int argc, char** argv )  // NOLINT(bugprone-exception-escape)
{
   for( int i = 1; i < argc; ++i ) {
      std::cout << "Parsing " << argv[ i ] << std::endl;
      pegtl::argv_input in( argv, i );
      pegtl::trace< grammar >( in );
   }
   return 0;
}

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

#include <tao/pegtl.hpp>
#include <tao/pegtl/contrib/json.hpp>
#include <tao/pegtl/contrib/trace2.hpp>

namespace pegtl = TAO_PEGTL_NAMESPACE;

using grammar = pegtl::must< pegtl::json::text, pegtl::eof >;

int main( int argc, char** argv )  // NOLINT(bugprone-exception-escape)
{
   for( int i = 1; i < argc; ++i ) {
      std::cout << "Parsing " << argv[ i ] << std::endl;
      pegtl::argv_input in( argv, i );
      pegtl::trace< grammar >( in );
   }
   return 0;
}

Fix grammar to check for complete text

Fix grammar to check for complete text


// RUN: rm -rf %t

// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/modules.cache \
// RUN:  -I %S/Inputs/odr_hash-Friend \
// RUN:  -emit-obj -o /dev/null \
// RUN:  -fmodules \
// RUN:  -fimplicit-module-maps \
// RUN:  -fmodules-cache-path=%t/modules.cache \
// RUN:  -std=c++11 -x c++ %s -verify

// expected-no-diagnostics

#include "Box.h"
#include "M1.h"
#include "M3.h"

void Run() {
  Box<> Present;
}

// RUN: rm -rf %t

// RUN: %clang_cc1 -fmodules -fmodules-cache-path=%t/modules.cache \
// RUN:  -I %S/Inputs/odr_hash-Friend \
// RUN:  -emit-obj -o /dev/null \
// RUN:  -fmodules \
// RUN:  -fimplicit-module-maps \
// RUN:  -fmodules-cache-path=%t/modules.cache \
// RUN:  -std=c++11 -x c++ %s -verify

// UNSUPPORTED: windows

// expected-no-diagnostics

#include "Box.h"
#include "M1.h"
#include "M3.h"

void Run() {
  Box<> Present;
}

Disable test for Windows to fix Windows buildbots.

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


#include "stdafx.h"
#include "UserTypeToString.h"

UserTypeToString::UserTypeToString(std::string name, int age, double netWorth) : name(name), age(age), netWorth(netWorth)
{
}

UserTypeToString::~UserTypeToString()
{
}

std::ostream& operator<<(std::ostream& os, const UserTypeToString& obj)
{
    // write obj to stream
    os << "name - " << obj.name.c_str() << " age - " << obj.age << " netWorth - " << obj.netWorth;
    return os;
}

#include "stdafx.h"
#include "UserTypeToString.h"

UserTypeToString::UserTypeToString(std::string name, int age, double netWorth) : name(name), age(age), netWorth(netWorth)
{
}

UserTypeToString::~UserTypeToString()
{
}

/* when streaming an instance of this type to an ostream of any kind this function will build the string
   containing the state of the object.
*/
std::ostream& operator<<(std::ostream& os, const UserTypeToString& obj)
{
    // write obj to stream
    os << "name - " << obj.name.c_str() << " age - " << obj.age << " netWorth - " << obj.netWorth;
    return os;
}

Add function header to operator<< implementation


//===-- RISCVTargetInfo.cpp - RISCV Target Implementation -----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/TargetRegistry.h"
using namespace llvm;

namespace llvm {
Target &getTheRISCV32Target() {
  static Target TheRISCV32Target;
  return TheRISCV32Target;
}

Target &getTheRISCV64Target() {
  static Target TheRISCV64Target;
  return TheRISCV64Target;
}
}

extern "C" void LLVMInitializeRISCVTargetInfo() {
  RegisterTarget<Triple::riscv32> X(getTheRISCV32Target(), "riscv32",
                                    "32-bit RISC-V");
  RegisterTarget<Triple::riscv64> Y(getTheRISCV64Target(), "riscv64",
                                    "64-bit RISC-V");
}

//===-- RISCVTargetInfo.cpp - RISCV Target Implementation -----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/TargetRegistry.h"
using namespace llvm;

namespace llvm {
Target &getTheRISCV32Target() {
  static Target TheRISCV32Target;
  return TheRISCV32Target;
}

Target &getTheRISCV64Target() {
  static Target TheRISCV64Target;
  return TheRISCV64Target;
}
}

extern "C" void LLVMInitializeRISCVTargetInfo() {
  RegisterTarget<Triple::riscv32> X(getTheRISCV32Target(), "riscv32",
                                    "32-bit RISC-V", "RISCV");
  RegisterTarget<Triple::riscv64> Y(getTheRISCV64Target(), "riscv64",
                                    "64-bit RISC-V", "RISCV");
}

Fix RISCV build after r318352

Fix RISCV build after r318352

Reviewers: asb, apazos, mgrang

Reviewed By: mgrang

Subscribers: rbar, johnrusso, simoncook, jordy.potman.lists, llvm-commits

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

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


// When we link a binary without the -debug flag, ASan should print out VAs
// instead of RVAs. The frames for main and do_uaf should be above 0x400000,
// which is the default image base of an executable.

// RUN: rm -f %t.pdb
// RUN: %clangxx_asan -c -O2 %s -o %t.obj
// RUN: link /nologo /OUT:%t.exe %t.obj %asan_lib %asan_cxx_lib
// RUN: not %run %t.exe 2>&1 | FileCheck %s

#include <stdlib.h>
#include <stdio.h>
int __attribute__((noinline)) do_uaf(void);
int main() {
  int r = do_uaf();
  printf("r: %d\n", r);
  return r;
}
int do_uaf(void) {
  char *x = (char*)malloc(10 * sizeof(char));
  free(x);
  return x[5];
  // CHECK: AddressSanitizer: heap-use-after-free
  // CHECK: #0 {{0x[a-f0-9]+ \(.*[\\/]unsymbolized.cc.*.exe\+0x40[a-f0-9]{4}\)}}
  // CHECK: #1 {{0x[a-f0-9]+ \(.*[\\/]unsymbolized.cc.*.exe\+0x40[a-f0-9]{4}\)}}
}

// When we link a binary without the -debug flag, ASan should print out VAs
// instead of RVAs. The frames for main and do_uaf should be above 0x400000,
// which is the default image base of an executable.

// RUN: rm -f %t.pdb
// RUN: %clangxx_asan -c -O2 %s -o %t.obj
// RUN: link /nologo /OUT:%t.exe %t.obj %asan_lib %asan_cxx_lib
// RUN: not %run %t.exe 2>&1 | FileCheck %s

#include <stdlib.h>
#include <stdio.h>
int __attribute__((noinline)) do_uaf(void);
int main() {
  int r = do_uaf();
  printf("r: %d\n", r);
  return r;
}
int do_uaf(void) {
  char *x = (char*)malloc(10 * sizeof(char));
  free(x);
  return x[5];
  // CHECK: AddressSanitizer: heap-use-after-free
  // CHECK: #0 {{0x[a-f0-9]+ \(.*[\\/]unsymbolized.cc.*.exe\+(0x40|0x14000)[a-f0-9]{4}\)}}
  // CHECK: #1 {{0x[a-f0-9]+ \(.*[\\/]unsymbolized.cc.*.exe\+(0x40|0x14000)[a-f0-9]{4}\)}}
}

Fix unsymbolize unittest. Adding win64 address.

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


#include "../lib/shared_mem.hpp"
#include <iostream>

std::shared_ptr<cs477::shm_pool> pool;
std::shared_ptr<cs477::bounded_queue<cs477::message, 1024>> rq_queue;
std::shared_ptr<cs477::bounded_queue<cs477::message, 1024>> rp_queue;

int main(int argc, char **argv) {
	pool = std::make_shared<cs477::shm_pool>();
	pool->create("primes-pool", 4096, 16384);
	rq_queue = std::make_shared<cs477::bounded_queue<cs477::message, 1024>>();
	rq_queue->create("primes-rq-queue");
	rp_queue = std::make_shared<cs477::bounded_queue<cs477::message, 1024>>();
	rp_queue->create("primes-rp-queue");
	std::cout << "test" << std::endl;
	std::cin.get();
  return 0;
}

#include "../lib/shared_mem.hpp"
#include <iostream>

const int PROCESS_COUNT = 3;

std::shared_ptr<cs477::shm_pool> pool;
std::shared_ptr<cs477::bounded_queue<cs477::message, 1024>> rq_queue;
std::shared_ptr<cs477::bounded_queue<cs477::message, 1024>> rp_queue;

int main(int argc, char **argv) {
	pool = std::make_shared<cs477::shm_pool>();
	pool->create("primes-pool", 4096, 16384);
	rq_queue = std::make_shared<cs477::bounded_queue<cs477::message, 1024>>();
	rq_queue->create("primes-rq-queue");
	rp_queue = std::make_shared<cs477::bounded_queue<cs477::message, 1024>>();
	rp_queue->create("primes-rp-queue");

	for (auto i = 0; i < PROCESS_COUNT; ++i) {
		cs477::buffer prime_block{pool};
		prime_block.allocate(4);
		rq_queue->write(prime_block.make_message());
	}

	std::cout << "test" << std::endl;
	std::cin.get();
  return 0;
}

Add progress for the night

Add progress for the night


/* RTcmix  - Copyright (C) 2000  The RTcmix Development Team
   See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
   the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include "../sys/mixerr.h"

extern "C" double checkInsts(char*, double*, short);

extern "C" {
	double rtdispatch(char *fname, double *pp, short n_args)
	{
		double rv;

		rv = checkInsts(fname, pp, n_args);
		return rv;
	}
}

/* RTcmix  - Copyright (C) 2000  The RTcmix Development Team
   See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for
   the license to this software and for a DISCLAIMER OF ALL WARRANTIES.
*/
#include <prototypes.h>
#include "../sys/mixerr.h"

extern "C" {
	double rtdispatch(char *fname, double *pp, short n_args)
	{
		double rv;

		rv = checkInsts(fname, pp, n_args);
		return rv;
	}
}

Move some prototypes to prototypes.h.

Move some prototypes to prototypes.h.


#include <wtl/string.hpp>
#include <wtl/exception.hpp>

#include <iostream>

int main() {
    std::cout << "__cplusplus: " << __cplusplus << std::endl;
    WTL_ASSERT((wtl::split("a b\tc") == std::vector<std::string>{"a", "b", "c"}));
    WTL_ASSERT((wtl::split<int>("1 2\t3") == std::vector<int>{1, 2, 3}));
    WTL_ASSERT(wtl::strip("  str  ") == "str");
    WTL_ASSERT(wtl::startswith("prefix", "pre"));
    WTL_ASSERT(!wtl::startswith("prefix", "post"));
    WTL_ASSERT(wtl::endswith("suffix", "fix"));
    WTL_ASSERT(!wtl::endswith("suffix", "suf"));
    return 0;
}

#include <wtl/string.hpp>
#include <wtl/exception.hpp>

#include <iostream>

void test_sto() {
    WTL_ASSERT(wtl::sto<bool>("1"));
    WTL_ASSERT(wtl::sto<int>("42") == 42);
    WTL_ASSERT(wtl::sto<long>("1729") == 1729l);
    WTL_ASSERT(wtl::sto<long long>("24601") == 24601ll);
    WTL_ASSERT(wtl::sto<unsigned>("42") == 42u);
    WTL_ASSERT(wtl::sto<unsigned long>("1729") == 1729ul);
    WTL_ASSERT(wtl::sto<unsigned long long>("24601") == 24601ull);
    WTL_ASSERT(wtl::sto<double>("3.14") - 3.14 < 1e-9);
}

int main() {
    std::cout << "__cplusplus: " << __cplusplus << std::endl;
    test_sto();
    WTL_ASSERT((wtl::split("a b\tc") == std::vector<std::string>{"a", "b", "c"}));
    WTL_ASSERT((wtl::split<int>("1 2\t3") == std::vector<int>{1, 2, 3}));
    WTL_ASSERT(wtl::strip("  str  ") == "str");
    WTL_ASSERT(wtl::startswith("abracadabra", "abr"));
    WTL_ASSERT(!wtl::startswith("abracadabra", "bra"));
    WTL_ASSERT(wtl::endswith("abracadabra", "bra"));
    WTL_ASSERT(!wtl::endswith("abracadabra", "abr"));
    WTL_ASSERT(wtl::replace("abracadabra", "br", "_") == "a_acada_a");
    return 0;
}

Add tests for sto() and replace()

:white_check_mark: Add tests for sto() and replace()


#include "llvm/runner.hpp"

Runner::Runner(CompileVisitor::Link v): v(v) {
  llvm::InitializeNativeTarget();
  llvm::InitializeNativeTargetAsmPrinter();
  llvm::InitializeNativeTargetAsmParser();

  std::string onError = "";
  auto eb = new llvm::EngineBuilder(std::unique_ptr<llvm::Module>(v->getModule()));
  engine = eb
    ->setErrorStr(&onError)
    .setEngineKind(llvm::EngineKind::JIT)
    .create();
  for (const auto& pair : nameToFunPtr) {
    engine->addGlobalMapping(v->getModule()->getFunction(pair.first), pair.second);
  }
  engine->finalizeObject();
  if (onError != "") throw InternalError("ExecutionEngine error", {
    METADATA_PAIRS,
    {"supplied error string", onError}
  });
}

int Runner::run() {
  return engine->runFunctionAsMain(v->getEntryPoint(), {}, {});
}

ProgramResult Runner::runAndCapture() {
  // Capture stdout
  char buf[8192];
  std::fflush(stdout);
  std::freopen("/dev/null", "a", stdout);
  std::setbuf(stdout, buf);
  // Run program
  int exitCode = run();
  // Stop capturing stdout
  std::freopen("/dev/tty", "a", stdout);
  return {exitCode, buf};
}

#include "llvm/runner.hpp"

Runner::Runner(CompileVisitor::Link v): v(v) {
  llvm::InitializeNativeTarget();
  llvm::InitializeNativeTargetAsmPrinter();
  llvm::InitializeNativeTargetAsmParser();

  std::string onError = "";
  auto eb = new llvm::EngineBuilder(std::unique_ptr<llvm::Module>(v->getModule()));
  engine = eb
    ->setErrorStr(&onError)
    .setEngineKind(llvm::EngineKind::JIT)
    .create();
  for (const auto& pair : nameToFunPtr) {
    auto funPtr = v->getModule()->getFunction(pair.first);
    if (funPtr == nullptr) continue; // Function not used
    engine->addGlobalMapping(funPtr, pair.second);
  }
  engine->finalizeObject();
  if (onError != "") throw InternalError("ExecutionEngine error", {
    METADATA_PAIRS,
    {"supplied error string", onError}
  });
}

int Runner::run() {
  return engine->runFunctionAsMain(v->getEntryPoint(), {}, {});
}

ProgramResult Runner::runAndCapture() {
  // Capture stdout
  char buf[8192];
  std::fflush(stdout);
  std::freopen("/dev/null", "a", stdout);
  std::setbuf(stdout, buf);
  // Run program
  int exitCode = run();
  // Stop capturing stdout
  std::freopen("/dev/tty", "a", stdout);
  return {exitCode, buf};
}

Fix segfault with foreign function mappings


/*
 * ModSecurity, http://www.modsecurity.org/
 * Copyright (c) 2015 - 2021 Trustwave Holdings, Inc. (http://www.trustwave.com/)
 *
 * 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
 *
 * If any of the files related to licensing are missing or if you have any
 * other questions related to licensing please contact Trustwave Holdings, Inc.
 * directly using the email address security@modsecurity.org.
 *
 */

#include "src/actions/set_env.h"

#include <iostream>
#include <string>

#include "modsecurity/transaction.h"
#include "modsecurity/rule.h"
#include "src/utils/string.h"

namespace modsecurity {
namespace actions {

bool SetENV::init(std::string *error) {
    return true;
}

bool SetENV::evaluate(RuleWithActions *rule, Transaction *t) {
    std::string colNameExpanded(m_string->evaluate(t));

    auto pair = utils::string::ssplit_pair(colNameExpanded, '=');
    ms_dbg_a(t, 8, "Setting envoriment variable: "
        + pair.first + " to " + pair.second);
    setenv(pair.first.c_str(), pair.second.c_str(), /*overwrite*/ 1);

    return true;
}

}  // namespace actions
}  // namespace modsecurity

/*
 * ModSecurity, http://www.modsecurity.org/
 * Copyright (c) 2015 - 2021 Trustwave Holdings, Inc. (http://www.trustwave.com/)
 *
 * 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
 *
 * If any of the files related to licensing are missing or if you have any
 * other questions related to licensing please contact Trustwave Holdings, Inc.
 * directly using the email address security@modsecurity.org.
 *
 */

#include "src/actions/set_env.h"

#include <iostream>
#include <string>

#include "modsecurity/transaction.h"
#include "modsecurity/rule.h"
#include "src/utils/string.h"

namespace modsecurity {
namespace actions {

bool SetENV::init(std::string *error) {
    return true;
}

bool SetENV::evaluate(RuleWithActions *rule, Transaction *t) {
    std::string colNameExpanded(m_string->evaluate(t));

    auto pair = utils::string::ssplit_pair(colNameExpanded, '=');
    ms_dbg_a(t, 8, "Setting environment variable: "
        + pair.first + " to " + pair.second);
    setenv(pair.first.c_str(), pair.second.c_str(), /*overwrite*/ 1);

    return true;
}

}  // namespace actions
}  // namespace modsecurity

Fix typo in debug log text

Fix typo in debug log text


// Check that stores in signal handlers are not recorded in origin history.
// This is, in fact, undesired behavior caused by our chained origins
// implementation being not async-signal-safe.

// RUN: %clangxx_msan -fsanitize-memory-track-origins=2 -m64 -O3 %s -o %t && \
// RUN:     not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out

// RUN: %clangxx_msan -mllvm -msan-instrumentation-with-call-threshold=0 -fsanitize-memory-track-origins=2 -m64 -O3 %s -o %t && \
// RUN:     not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out

#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

volatile int x, y;

void SignalHandler(int signo) {
  y = x;
}

int main(int argc, char *argv[]) {
  int volatile z;
  x = z;

  signal(SIGUSR1, SignalHandler);
  kill(getpid(), SIGUSR1);
  signal(SIGUSR1, SIG_DFL);

  return y;
}

// CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value
// CHECK-NOT: in SignalHandler

// Check that stores in signal handlers are not recorded in origin history.
// This is, in fact, undesired behavior caused by our chained origins
// implementation being not async-signal-safe.

// RUN: %clangxx_msan -fsanitize-memory-track-origins=2 -m64 -O3 %s -o %t && \
// RUN:     not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out

// RUN: %clangxx_msan -mllvm -msan-instrumentation-with-call-threshold=0 -fsanitize-memory-track-origins=2 -m64 -O3 %s -o %t && \
// RUN:     not %run %t >%t.out 2>&1
// RUN: FileCheck %s < %t.out

#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

volatile int x, y;

void SignalHandler(int signo) {
  y = x;
}

int main(int argc, char *argv[]) {
  int volatile z;
  x = z;

  signal(SIGHUP, SignalHandler);
  kill(getpid(), SIGHUP);
  signal(SIGHUP, SIG_DFL);

  return y;
}

// CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value
// CHECK-NOT: in SignalHandler

Use SIGHUP instead of SIGUSR1 in test.

[msan] Use SIGHUP instead of SIGUSR1 in test.

Apparently, SIGUSR1 does not work on x86_64+ArchLinux for some reason.

For more details, see:
https://groups.google.com/forum/#!topic/llvm-dev/4Ag1FF4M2Dw

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


// Copyright (c) 2010 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 "views/controls/menu/menu_config.h"

#include "grit/app_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/resource/resource_bundle.h"

namespace views {

// static
MenuConfig* MenuConfig::Create() {
  MenuConfig* config = new MenuConfig();
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  config->font = rb.GetFont(ResourceBundle::BaseFont);
  config->arrow_width = rb.GetBitmapNamed(IDR_MENU_ARROW)->width();
  // Add 4 to force some padding between check and label.
  config->check_width = rb.GetBitmapNamed(IDR_MENU_CHECK)->width() + 4;
  config->check_height = rb.GetBitmapNamed(IDR_MENU_CHECK)->height();
  return config;
}

}  // namespace views

// Copyright (c) 2010 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 "views/controls/menu/menu_config.h"

#include "grit/app_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/resource/resource_bundle.h"

namespace views {

// static
MenuConfig* MenuConfig::Create() {
  MenuConfig* config = new MenuConfig();
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
#if defined(TOUCH_UI)
  config->font = rb.GetFont(ResourceBundle::LargeFont);
#else
  config->font = rb.GetFont(ResourceBundle::BaseFont);
#endif
  config->arrow_width = rb.GetBitmapNamed(IDR_MENU_ARROW)->width();
  // Add 4 to force some padding between check and label.
  config->check_width = rb.GetBitmapNamed(IDR_MENU_CHECK)->width() + 4;
  config->check_height = rb.GetBitmapNamed(IDR_MENU_CHECK)->height();
  return config;
}

}  // namespace views

Increase the base font size for touch ui

BUG=none
TEST=none

Review URL: http://codereview.chromium.org/6519034

git-svn-id: http://src.chromium.org/svn/trunk/src@77349 4ff67af0-8c30-449e-8e8b-ad334ec8d88c

Former-commit-id: 769188b051f6abb22b6e4a51e926b757e5fcf477


/*
 * SimNetworkFunctions.cpp
 *
 *  Created on: 18.04.2016
 *      Author: Marc Hartung
 */

#include "../../include/network_impl/SimNetworkFunctions.hpp"

#include <iostream>

namespace NetOff
{
    std::string createStringFromData(const char * data)
    {
        size_t num = getIntegralFromData<size_t>(data);
        const char * start = shift<size_t>(data);
        std::string res(start, num);
        return res;
    }

    size_t getStringDataSize(const std::string & str)
    {
        return sizeof(size_t) + sizeof(char) * (str.size() + 1);  // first is for saving how many chars will be there
    }

    size_t saveStringInData(const std::string & str, char * data)
    {
        char * p = saveShiftIntegralInData<size_t>(str.size(),data);
        for (size_t i = 0; i < str.size(); ++i)
        {
            *p = str[i];
            ++p;
        }
        return getStringDataSize(str);
    }

}

/*
 * SimNetworkFunctions.cpp
 *
 *  Created on: 18.04.2016
 *      Author: Marc Hartung
 */

#include "network_impl/SimNetworkFunctions.hpp"

#include <iostream>

namespace NetOff
{

    std::string createStringFromData(const char * data)
    {
        size_t num = getIntegralFromData<size_t>(data);
        const char * start = shift<size_t>(data);
        std::string res(start, num);
        return res;
    }

    size_t getStringDataSize(const std::string & str)
    {
        return sizeof(size_t) + sizeof(char) * (str.size() + 1);  // first is for saving how many chars will be there
    }

    size_t saveStringInData(const std::string & str, char * data)
    {
        char * p = saveShiftIntegralInData<size_t>(str.size(), data);
        for (auto& elem : str)
        {
            *p = elem;
            ++p;
        }
        return getStringDataSize(str);
    }

} /* End namespace NetOff */

Make use of range based for loop

Make use of range based for loop


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

#include "chrome/browser/ui/webui/options2/chromeos/stats_options_handler.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/user_metrics.h"

namespace chromeos {

StatsOptionsHandler::StatsOptionsHandler() {
}

// OptionsPageUIHandler implementation.
void StatsOptionsHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
}

void StatsOptionsHandler::Initialize() {
}

// WebUIMessageHandler implementation.
void StatsOptionsHandler::RegisterMessages() {
  web_ui_->RegisterMessageCallback("metricsReportingCheckboxAction",
      base::Bind(&StatsOptionsHandler::HandleMetricsReportingCheckbox,
                 base::Unretained(this)));
}

void StatsOptionsHandler::HandleMetricsReportingCheckbox(
    const ListValue* args) {
#if defined(GOOGLE_CHROME_BUILD)
  const std::string checked_str = UTF16ToUTF8(ExtractStringValue(args));
  const bool enabled = (checked_str == "true");
  UserMetrics::RecordAction(
      enabled ?
      UserMetricsAction("Options_MetricsReportingCheckbox_Enable") :
      UserMetricsAction("Options_MetricsReportingCheckbox_Disable"));
#endif
}

}  // namespace chromeos

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

#include "chrome/browser/ui/webui/options2/chromeos/stats_options_handler.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/user_metrics.h"

using content::UserMetricsAction;

namespace chromeos {

StatsOptionsHandler::StatsOptionsHandler() {
}

// OptionsPageUIHandler implementation.
void StatsOptionsHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
}

void StatsOptionsHandler::Initialize() {
}

// WebUIMessageHandler implementation.
void StatsOptionsHandler::RegisterMessages() {
  web_ui_->RegisterMessageCallback("metricsReportingCheckboxAction",
      base::Bind(&StatsOptionsHandler::HandleMetricsReportingCheckbox,
                 base::Unretained(this)));
}

void StatsOptionsHandler::HandleMetricsReportingCheckbox(
    const ListValue* args) {
#if defined(GOOGLE_CHROME_BUILD)
  const std::string checked_str = UTF16ToUTF8(ExtractStringValue(args));
  const bool enabled = (checked_str == "true");
  content::RecordAction(
      enabled ?
      UserMetricsAction("Options_MetricsReportingCheckbox_Enable") :
      UserMetricsAction("Options_MetricsReportingCheckbox_Disable"));
#endif
}

}  // namespace chromeos

Fix CrOS Official build from options2 copy.

BUG=none
TEST=none
TBR=csilv

Review URL: http://codereview.chromium.org/8907049

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


#include "Limiter.h"
#include "Testing.h"

#include <iostream>

auto TestWithPeakLoadInTheBeginning(int maxAllowedRps)
{
	const auto startTime = std::chrono::steady_clock::now();
	int sentRequestsCount = 0;

	Limiter limiter(maxAllowedRps, 100);
	for (; sentRequestsCount < maxAllowedRps; ++sentRequestsCount)
	{
		ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
	}
	if (std::chrono::steady_clock::now() < startTime + std::chrono::seconds())
	{
		ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests);
	}
}

namespace LimiterSpecs
{
	static constexpr int minRPS = 1;
	static constexpr int maxRPS = 100'000;
};

int main()
{
	try
	{
		TestWithPeakLoadInTheBeginning(LimiterSpecs::maxRPS);
		std::cout << "All Tests passed successfully\n";
	}
	catch (AssertionException& e)
	{
		std::cout << "One or more of tests failed: " << e.what() << '\n';
	}
	system("pause");
	return 0;
}

#include "Limiter.h"
#include "Testing.h"

#include <iostream>

auto TestWithPeakLoadInTheBeginning(int maxAllowedRps)
{
	const auto startTime = std::chrono::steady_clock::now();
	int sentRequestsCount = 0;

	Limiter limiter(maxAllowedRps, 10000);
	for (; sentRequestsCount < maxAllowedRps; ++sentRequestsCount)
	{
		ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::Ok);
	}
	auto expectedEndResult = std::chrono::steady_clock::now() < startTime + std::chrono::milliseconds(500)
		? HttpResult::Code::Ok
		: HttpResult::Code::TooManyRequests;

	while (std::chrono::steady_clock::now() < startTime + std::chrono::seconds(1))
	{
		ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests);
	}
	ASSERT_EQUAL(limiter.ValidateRequest(), HttpResult::Code::TooManyRequests);

	std::this_thread::sleep_until(startTime + std::chrono::milliseconds(1500));
	ASSERT_EQUAL(limiter.ValidateRequest(), expectedEndResult);
}

namespace LimiterSpecs
{
	static constexpr int minRPS = 1;
	static constexpr int maxRPS = 100'000;
};

int main()
{
	try
	{
		TestWithPeakLoadInTheBeginning(LimiterSpecs::maxRPS);
		std::cout << "All Tests passed successfully\n";
	}
	catch (AssertionException& e)
	{
		std::cout << "One or more of tests failed: " << e.what() << '\n';
	}
	system("pause");
	return 0;
}

Fix final condition in test

Fix final condition in test


#include<iostream>
#include<boost/filesystem.hpp>
using namespace boost::filesystem;

//bool CopyDir(path const & source_path, path const & destination_path);

int main(int argc, char *argv[])
{
     if(argc < 3)
     {
          std::cout << "USAGE " << argv[0] << " source destination" << std::endl;
          return 1;
     }
     else
     {
          path source_path = argv[1];
          path destination_path = argv[2];
          if(exists(source_path))
          {
               if(is_regular_file(source_path) == true)
               {
                    copy_file(source_path, destination_path);
                    std::cout << "File has been copied" << std::endl;
               }
               else if(is_directory(source_path) == true)
               {
                    copy_directory(source_path, destination_path);
                    std::cout << "Directory has been copied" << std::endl;
               }
               else
               {
                    std::cerr << "It seems like the specified directory does not exist." << std::endl;
               }
          }
          else
          {
               std::cerr << "The specified directory could not be found" << std::endl;
          }
     }
     return 0;
}

#include<iostream>
#include<boost/filesystem.hpp>
using namespace boost::filesystem;

//bool CopyDir(path const & source_path, path const & destination_path);

int main(int argc, char *argv[])
{
     if(argc < 3)
     {
          std::cout << "USAGE " << argv[0] << " source destination" << std::endl;
          return 1;
     }
     else
     {
          path source_path = argv[1];
          path destination_path = argv[2];
          if(exists(source_path))
          {
               if(is_regular_file(source_path) == true)
               {
                    copy_file(source_path, destination_path); //Link dest path to buffer
                    std::cout << "File has been copied" << std::endl;
               }
               else if(is_directory(source_path) == true)
               {
                    copy_directory(source_path, destination_path);
                    std::cout << "Directory has been copied" << std::endl;
               }
               else
               {
                    std::cerr << "It seems like the specified directory does not exist." << std::endl;
               }
          }
          else
          {
               std::cerr << "The specified directory could not be found" << std::endl;
          }
     }
     return 0;
}

Add comment about linking place

Add comment about linking place


// RUN: %clang_cc1 %s -triple i386-pc-windows-msvc19.0.0 -emit-obj \
// RUN:     -debug-info-kind=line-tables-only -fms-extensions
class __declspec(dllexport) A {
  A(int * = new int) {}
};
// CHECK: define {{.*}}void @"\01??_FA@@AAEXXZ"
// CHECK-SAME: !dbg ![[SP:[0-9]+]]
// CHECK-NOT: {{ret }}
// CHECK: call x86_thiscallcc %class.A* @"\01??0A@@AAE@PAH@Z"(%class.A* %this1, i32* %0)
// CHECK-SAME: !dbg ![[DBG:[0-9]+]]
// CHECK: ret void, !dbg ![[DBG]]
//
// CHECK: ![[SP]] = distinct !DISubprogram(
// CHECK-SAME:          line: 3
// CHECK-SAME:          isDefinition: true
// CHECK-SAME:          DIFlagArtificial
// CHECK-SAME:          ){{$}}
//
// CHECK: ![[DBG]] = !DILocation(line: 0

// RUN: %clang_cc1 %s -triple i386-pc-windows-msvc19.0.0 -emit-llvm \
// RUN:     -debug-info-kind=line-tables-only -fms-extensions -o - | FileCheck %s
class __declspec(dllexport) A {
  A(int * = new int) {}
};
// CHECK: define {{.*}}void @"\01??_FA@@AAEXXZ"
// CHECK-SAME: !dbg ![[SP:[0-9]+]]
// CHECK-NOT: {{ret }}
// CHECK: call x86_thiscallcc %class.A* @"\01??0A@@AAE@PAH@Z"(%class.A* %this1, i32* %0)
// CHECK-SAME: !dbg ![[DBG:[0-9]+]]
// CHECK: ret void, !dbg ![[DBG1:[0-9]+]]
//
// CHECK: ![[SP]] = distinct !DISubprogram(
// CHECK-SAME:          line: 4
// CHECK-SAME:          isDefinition: true
// CHECK-SAME:          DIFlagArtificial
// CHECK-SAME:          ){{$}}
//
// CHECK: ![[DBG1]] = !DILocation(line: 0
// CHECK: ![[DBG]] = !DILocation(line: 0

Add the missing FileCheck invocation to this testcase.

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


int main()
{
    int *a;
    int *n = a;
    a = n;
    *n = 5;
    return 0;
}

#include <stdio.h>

int main()
{
    int input;
    if (scanf("%d", &input) == 1)
    {
        if (input == 2)
        {
            int *a;
            int *n = a;
            a = n;
            *n = 5;
        }
        else
        {
            printf("OK\n");
        }
    }
    return 0;
}

Add a special condition so that static analyzers could write the exact condition when problem happens


extern "C"
{
    #include "packet_queue.h"
    #include "error.h"
    #include "nrf51.h"
    #include "nrf51_bitfields.h"
}

#include "CppUTest/TestHarness.h"

TEST_GROUP(packet_queue)
{

    void setup(void)
    {
    }

    void teardown(void)
    {
    }
};

TEST(packet_queue, test_packet_queue_init_succeed)
{
    packet_queue_t queue;
    LONGS_EQUAL(SUCCESS, packet_queue_init(&queue));
}

extern "C"
{
    #include "packet_queue.h"
    #include "error.h"
    #include "nrf51.h"
    #include "nrf51_bitfields.h"
}

#include "CppUTest/TestHarness.h"

TEST_GROUP(packet_queue)
{
    packet_queue_t queue;

    void setup(void)
    {
        packet_queue_init(&queue);
    }

    void teardown(void)
    {
    }
};

TEST(packet_queue, test_queue_init_succeed)
{
    packet_queue_t queue;
    LONGS_EQUAL(SUCCESS, packet_queue_init(&queue));
}

TEST(packet_queue, test_queue_new_queue_is_empty)
{
    LONGS_EQUAL(true, packet_queue_is_empty(&queue));
}

TEST(packet_queue, test_queue_add_queue_is_not_empty)
{
    radio_packet_t packet;
    packet_queue_add(&queue, &packet);

    LONGS_EQUAL(false, packet_queue_is_empty(&queue));
}

Test empty and non-empty queue.

Test empty and non-empty queue.


#include <osgDB/ImageOptions>

using namespace osgDB;

ImageOptions::ImageOptions()
{
    init();
}

ImageOptions::ImageOptions(const std::string& str)
{
    init();
    _str = str;
}

void ImageOptions::init()
{
    _sourceImageSamplingMode = NEAREST;
    _sourceImageWindowMode = ALL_IMAGE;

    _destinationImageWindowMode = ALL_IMAGE;
}

#include <osgDB/ImageOptions>

using namespace osgDB;

ImageOptions::ImageOptions()
{
    init();
}

ImageOptions::ImageOptions(const std::string& str)
{
    init();
    _str = str;
}

void ImageOptions::init()
{
    _sourceImageSamplingMode = NEAREST;
    _sourceImageWindowMode = ALL_IMAGE;

    _destinationImageWindowMode = ALL_IMAGE;

    _destinationDataType = GL_NONE;
    _destinationPixelFormat = GL_NONE;
}

Set default values for datatype & pixelformat.

git-svn-id: 23b6355f2bb369032457de4eb5f713ee134f73a8@2384 16af8721-9629-0410-8352-f15c8da7e697


#pragma once

#include <threadingzeug/parallelfor.h>

namespace threadingzeug
{

int getNumberOfThreads()
{
	return std::max(static_cast<size_t>(2), static_cast<size_t>(std::thread::hardware_concurrency()));
}

} // namespace threadingzeug

Remove pragma from source file

Remove pragma from source file


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

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

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

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

#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/kernels/mlir_generated/unranked_op_gpu_base.h"

namespace tensorflow {

GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, f16, DT_HALF, Eigen::half);
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, f32, DT_FLOAT, float);
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, f64, DT_DOUBLE, double);
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, i8, DT_INT8, int8);
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, i16, DT_DOUBLE, int16);
// TODO(b/25387198): We cannot use a regular GPU kernel for int32.
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, i64, DT_DOUBLE, int64);

}  // namespace tensorflow

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

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

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

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

#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/kernels/mlir_generated/unranked_op_gpu_base.h"

namespace tensorflow {

GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, f16, DT_HALF, Eigen::half);
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, f32, DT_FLOAT, float);
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, f64, DT_DOUBLE, double);
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, i8, DT_INT8, int8);
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, i16, DT_INT16, int16);
// TODO(b/25387198): We cannot use a regular GPU kernel for int32.
GENERATE_AND_REGISTER_UNARY_KERNEL(Neg, i64, DT_INT64, int64);

}  // namespace tensorflow

Fix registration for Neg kernel.

Fix registration for Neg kernel.

There was a copy/paste bug here which was only caught with the python-based
tests. Now tensorflow/python/kernel_tests:cwise_ops_unary_test_gpu passes with
unranked kernels enabled.

PiperOrigin-RevId: 346947580
Change-Id: I5195c6b5f44deb11469d50e925cf460c3944014d


#include "thread_checker.h"

#include <windows.h>
#include "Processthreadsapi.h"

namespace dux {

#ifdef _WIN32

ThreadChecker::ThreadChecker() : thread_id_(GetCurrentThreadId()) {}

bool ThreadChecker::IsCreationThreadCurrent() const {
  return GetCurrentThreadId() == thread_id_;
}

#endif

}  // namespace dux

#include "thread_checker.h"

#ifdef _WIN32

#include <windows.h>
#include "Processthreadsapi.h"

namespace dux {

ThreadChecker::ThreadChecker() : thread_id_(GetCurrentThreadId()) {}

bool ThreadChecker::IsCreationThreadCurrent() const {
  return GetCurrentThreadId() == thread_id_;
}

}  // namespace dux

#endif

Fix build on non-windows platforms.

Fix build on non-windows platforms.


Add an XFAIL for Newlib's missing uchar.h

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


#include <iostream>
#include <ccspec/core/formatters/text_formatter.h>

namespace ccspec {
namespace core {
namespace formatters {

using std::endl;
using std::exception;
using std::exception_ptr;
using std::list;
using std::ostream;
using std::rethrow_exception;

// Public methods.

void TextFormatter::afterEachHookFailed(exception_ptr failure) const {
    output_ << "An error occurred in an `after(:example)` hook" << endl;
    outputException(failure);
}

void TextFormatter::afterAllHookFailed(exception_ptr failure) const {
    output_ << "An error occurred in an `after(:context)` hook" << endl;
    outputException(failure);
}

void TextFormatter::aroundHookFailed(exception_ptr failure) const {
    output_ << "An error occurred in an `around(:example)` hook" << endl;
    outputException(failure);
}

void TextFormatter::dumpFailures(const list<exception_ptr>& failures) const {
    if (failures.empty())
        return;

    output_ << "Failures:" << endl;
    for (auto failure : failures)
        outputException(failure);
}

// Protected methods.

TextFormatter::TextFormatter(ostream& output) : Formatter(output) {}

// Private methods.

void TextFormatter::outputException(exception_ptr failure) const {
    try {
        rethrow_exception(failure);
    } catch (const exception& e) {
        output_ << e.what() << endl;
    }
}

} // namespace formatters
} // namespace core
} // namespace ccspec

#include <iostream>
#include <ccspec/core/formatters/text_formatter.h>

namespace ccspec {
namespace core {
namespace formatters {

using std::endl;
using std::exception;
using std::exception_ptr;
using std::list;
using std::ostream;
using std::rethrow_exception;

// Public methods.

void TextFormatter::afterEachHookFailed(exception_ptr failure) const {
    output_ << "An error occurred in an `after(:example)` hook" << endl;
    outputException(failure);
}

void TextFormatter::afterAllHookFailed(exception_ptr failure) const {
    output_ << "An error occurred in an `after(:context)` hook" << endl;
    outputException(failure);
}

void TextFormatter::aroundHookFailed(exception_ptr failure) const {
    output_ << "An error occurred in an `around(:example)` hook" << endl;
    outputException(failure);
}

void TextFormatter::dumpFailures(const list<exception_ptr>& failures) const {
    if (failures.empty())
        return;

    output_ << endl << "Failures:" << endl;
    for (auto failure : failures)
        outputException(failure);
}

// Protected methods.

TextFormatter::TextFormatter(ostream& output) : Formatter(output) {}

// Private methods.

void TextFormatter::outputException(exception_ptr failure) const {
    try {
        rethrow_exception(failure);
    } catch (const exception& e) {
        output_ << e.what() << endl;
    }
}

} // namespace formatters
} // namespace core
} // namespace ccspec

Add line break before "Failures:"

Add line break before "Failures:"


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

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, SessionRestoreApis) {
  ASSERT_TRUE(RunExtensionSubtest("session_restore",
                                  "session_restore.html")) << 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"

// Flaky on ChromeOS http://crbug.com/251199
#if defined(OS_CHROMEOS)
#define MAYBE_SessionRestoreApis DISABLED_SessionRestoreApis
#else
#define MAYBE_SessionRestoreApis SessionRestoreApis
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_SessionRestoreApis) {
  ASSERT_TRUE(RunExtensionSubtest("session_restore",
                                  "session_restore.html")) << message_;
}

Mark SessionRestoureApis as flaky on chromium os

BUG=251199
TBR=kalman@chromium.org

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

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


// Copyright 2004-present Facebook. All Rights Reserved.

#include "ApkManager.h"

#include <boost/filesystem.hpp>
#include <iostream>
#include <sstream>

namespace {

bool check_directory(std::string& apkdir) {
  if (!boost::filesystem::is_directory(apkdir.c_str())) {
    std::cerr << "error: apkdir is not a writable directory: " << apkdir
              << std::endl;
    exit(EXIT_FAILURE);
  }
}

}

FILE* ApkManager::new_asset_file(const char* filename) {
  check_directory(m_apk_dir);
  std::ostringstream path;
  path << m_apk_dir << "/assets/";
  if (!boost::filesystem::is_directory(path.str().c_str())) {
    std::cerr << "error: assets dir is not a writable directory: " << path.str()
              << std::endl;
    exit(EXIT_FAILURE);
  }
  path << filename;

  FILE* fd = fopen(path.str().c_str(), "w");
  if (fd != nullptr) {
    m_files.emplace_back(fd);
  } else {
    perror("Error creating new asset file");
  }
  return fd;
}

// Copyright 2004-present Facebook. All Rights Reserved.

#include "ApkManager.h"

#include <boost/filesystem.hpp>
#include <iostream>
#include <sstream>

namespace {

void check_directory(std::string& dir) {
  if (!boost::filesystem::is_directory(dir.c_str())) {
    std::cerr << "error: not a writable directory: " << dir
              << std::endl;
    exit(EXIT_FAILURE);
  }
}

}

FILE* ApkManager::new_asset_file(const char* filename) {
  check_directory(m_apk_dir);
  std::ostringstream path;
  path << m_apk_dir << "/assets/";
  std::string assets_dir = path.str();
  check_directory(assets_dir);
  path << filename;

  FILE* fd = fopen(path.str().c_str(), "w");
  if (fd != nullptr) {
    m_files.emplace_back(fd);
  } else {
    perror("Error creating new asset file");
  }
  return fd;
}

Fix compilation warning when checking for writable directory

Summary:
As title. Fixes code introduced in previous diff.

Fixes https://github.com/facebook/redex/issues/312

Reviewed By: thezhangwei

Differential Revision: D7487716

fbshipit-source-id: 12d1fa38b4cc9b10b31991a9875731b19988c96d


#include <iostream>
#include <string>

std::string parse_command(const std::string& input) {
  return input.substr(0, input.find(' '));
}

int main() {
  std::cout << "PUCRS FAT16 SHELL\n";
  std::cout << "$ ";

  std::string cmd;
  getline (std::cin, cmd);
  std::cout << "-> Will execute: " << parse_command(cmd) << "\n";
}

#include <iostream>
#include <string>

std::string parse_command(const std::string& input) {
  return input.substr(0, input.find(' '));
}

int main() {
  std::cout << "PUCRS FAT16 SHELL\n";
  while (true) {
    std::cout << "$ ";
    std::string cmd;
    getline (std::cin, cmd);
    std::cout << "-> Will execute: " << parse_command(cmd) << "\n";
  }
}

Read commands from stdin "forever"

Read commands from stdin "forever"


#include <dns_sd.h>
#include <ev++.h>

int main(int argc, char *argv[]) {
    (void)argc;
    (void)argv;
    return 0;
}

#include <iostream>
#include <dns_sd.h>
#include <ev++.h>

#include "build_version.h"

int main(int argc, char *argv[]) {
    if (2 != argc) {
        std::cerr << argv[0] << " <announce file>" << std::endl;
        std::cerr << "Version: " << VERSION << std::endl;
        return -1;
    }
    return 0;
}

Check if we have enough arguments

Check if we have enough arguments


// Copyright 2017, Dawid Kurek, <dawikur@gmail.com>

#include "lel/operation/increment_decrement.hpp"

#include "gtest/gtest.h"

TEST(increment_decrement_test, TODO) {}

// Copyright 2017, Dawid Kurek, <dawikur@gmail.com>

#include "lel/operation/increment_decrement.hpp"

#include "gtest/gtest.h"

TEST(increment_decrement_test, preincrement) {
  LeL::Operation::__PreIncrement pre_increment;

  int i = 5;

  ASSERT_EQ(6, pre_increment(i));
}

TEST(increment_decrement_test, postincrement) {
  LeL::Operation::__PostIncrement post_increment;

  int i = 5;

  ASSERT_EQ(5, post_increment(i));
}

TEST(increment_decrement_test, predecrement) {
  LeL::Operation::__PreDecrement pre_decrement;

  int i = 5;

  ASSERT_EQ(4, pre_decrement(i));
}

TEST(increment_decrement_test, postdecrement) {
  LeL::Operation::__PostDecrement post_decrement;

  int i = 5;

  ASSERT_EQ(5, post_decrement(i));
}

Add tests for pre/post inc/decrement

Add tests for pre/post inc/decrement


#include "Assignment.h"
#include "Course.h"

#include <cstdio>
#include <iostream>

using namespace std;

int main() {
  if (remove("test-0.sqlite") != 0) {
    cout << "Error with deletion of database file\n";
  } else {
    cout << "Database file successfully deleted\n";
  }

  // test instantiation of a Course object.
  cout << "Testing instantiation of a Course object:" << endl;
  Course course("test-0");
  cout << "Created " << course.getName() << endl;

  cout << "All Assignments: " << course.assignments.size() << endl;
  cout << "All Categories: " << course.categories.size() << endl;
  cout << "All Students: " << course.students.size() << endl;
  cout << "All Submitted: " << course.submitted.size() << endl;

  // Test adding items to the db
  Category c1(0, "Homework", 20, course.getDb());
  Category c2(0, "Labs", 30, course.getDb());
  Category c3(0, "Exams", 50, course.getDb());
  c1.insert();
  c2.insert();
  c3.insert();

  course.categories[c1.getId()] = &c1;
  course.categories[c2.getId()] = &c2;
  course.categories[c3.getId()] = &c3;

  for (auto it : course.categories) {
    cout << it.first << " " << it.second->getName() << endl;
  }
}

#include "Assignment.h"
#include "Course.h"

#include <cstdio>
#include <iostream>

using namespace std;

int main() {
  if (remove("test-0.sqlite") != 0) {
    cout << "Error with deletion of database file\n";
  } else {
    cout << "Database file successfully deleted\n";
  }

  // test instantiation of a Course object.
  cout << "Testing instantiation of a Course object:" << endl;
  Course course("test-0");
  cout << "Created " << course.getName() << endl;

  // cout << "All Assignments: " << course.assignments.size() << endl;
  // cout << "All Categories: " << course.categories.size() << endl;
  // cout << "All Students: " << course.students.size() << endl;
  // cout << "All Submitted: " << course.submitted.size() << endl;

  // // Test adding items to the db
  // Category c1(0, "Homework", 20, course.getDb());
  // Category c2(0, "Labs", 30, course.getDb());
  // Category c3(0, "Exams", 50, course.getDb());
  // c1.insert();
  // c2.insert();
  // c3.insert();

  // course.categories[c1.getId()] = &c1;
  // course.categories[c2.getId()] = &c2;
  // course.categories[c3.getId()] = &c3;

  // for (auto it : course.categories) {
  //   cout << it.first << " " << it.second->getName() << endl;
  // }
}

Comment out test, need to refactor

Comment out test, need to refactor


/* ***** BEGIN LICENSE BLOCK *****
 * Sconspiracy - Copyright (C) IRCAD, 2004-2010.
 * Distributed under the terms of the BSD Licence as
 * published by the Open Source Initiative.
 * ****** END LICENSE BLOCK ****** */

MiniLauncher::MiniLauncher( ::boost::filesystem::path profilePath )
{
    ::boost::filesystem::path cwd = ::boost::filesystem::current_path();
    ::boost::filesystem::path bundlePath = cwd / "Bundles";

    ::fwRuntime::addBundles(bundlePath);

    if (!::boost::filesystem::exists( profilePath ))
    {
        profilePath = cwd / profilePath;
    }

    if (!::boost::filesystem::exists( profilePath ))
    {
        throw (std::invalid_argument("<" + profilePath.string() + "> not found." ));
    }

    m_profile = ::fwRuntime::io::ProfileReader::createProfile(profilePath);
    ::fwRuntime::profile::setCurrentProfile(m_profile);

    m_profile->setParams(0, NULL);
    m_profile->start();
    // m_profile->run();

}

MiniLauncher::~MiniLauncher()
{
    m_profile->stop();
    m_profile.reset();
    ::fwRuntime::profile::setCurrentProfile(m_profile);
}

/* ***** BEGIN LICENSE BLOCK *****
 * Sconspiracy - Copyright (C) IRCAD, 2004-2010.
 * Distributed under the terms of the BSD Licence as
 * published by the Open Source Initiative.
 * ****** END LICENSE BLOCK ****** */

MiniLauncher::MiniLauncher( ::boost::filesystem::path profilePath )
{
    ::boost::filesystem::path cwd = ::boost::filesystem::current_path();
    ::boost::filesystem::path bundlePath = cwd / "Bundles";

    ::fwRuntime::addBundles(bundlePath);

    if (!::boost::filesystem::exists( profilePath ))
    {
        profilePath = cwd / profilePath;
    }

    if (!::boost::filesystem::exists( profilePath ))
    {
        throw (std::invalid_argument("<" + profilePath.string() + "> not found." ));
    }

    m_profile = ::fwRuntime::io::ProfileReader::createProfile(profilePath);
    ::fwRuntime::profile::setCurrentProfile(m_profile);

    m_profile->setParams(0, NULL);
    m_profile->start();
    ::fwRuntime::profile::getCurrentProfile()->setup();
    // m_profile->run();
}

MiniLauncher::~MiniLauncher()
{
    ::fwRuntime::profile::getCurrentProfile()->cleanup();
    m_profile->stop();
    m_profile.reset();
    ::fwRuntime::profile::setCurrentProfile(m_profile);
}

Add setup/cleanup for bundle test unit

Add setup/cleanup for bundle test unit

--HG--
branch : experimental


#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include "System/management.h"

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

    QQmlApplicationEngine engine;
    // Create management object and register it as context property
    Management *man = new Management();
    engine.rootContext()->setContextProperty("management", man);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    QObject *canvas = engine.rootObjects().first()->findChild<QObject*>("canvas");
    man->initialize(&engine, canvas);

    return app.exec();
}

#include <ctime>

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include "System/management.h"

int main(int argc, char *argv[]) {
    srand((unsigned)time(NULL));

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    // Create management object and register it as context property
    Management *man = new Management();
    engine.rootContext()->setContextProperty("management", man);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    QObject *canvas = engine.rootObjects().first()->findChild<QObject*>("canvas");
    man->initialize(&engine, canvas);

    return app.exec();
}

Initialize seed for better random numbers.

Signed-off-by: TheSniperFan <db7563122c08a03c83ae47e44bdc9bc661a824b1@gmail.com>


#include <iomanip>
#include <iostream>

#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/console.hpp>

static void color_fmt(boost::log::record_view const& rec, boost::log::formatting_ostream& strm) {
  auto severity = rec[boost::log::trivial::severity];
  bool color = false;
  if (severity) {
    switch (severity.get()) {
      case boost::log::trivial::warning:
        strm << "\033[33m";
        color = true;
        break;
      case boost::log::trivial::error:
      case boost::log::trivial::fatal:
        strm << "\033[31m";
        color = true;
        break;
      default:
        break;
    }
  }
  // setw(7) = the longest log level. eg "warning"
  strm << std::setw(7) << std::setfill(' ') << severity << ": " << rec[boost::log::expressions::smessage];
  if (color) {
    strm << "\033[0m";
  }
}

void logger_init_sink(bool use_colors = false) {
  auto sink = boost::log::add_console_log(std::cout, boost::log::keywords::format = "%Message%",
                                          boost::log::keywords::auto_flush = true);
  if (use_colors) {
    sink->set_formatter(&color_fmt);
  }
}

#include <iomanip>
#include <iostream>

#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/console.hpp>

static void color_fmt(boost::log::record_view const& rec, boost::log::formatting_ostream& strm) {
  auto severity = rec[boost::log::trivial::severity];
  bool color = false;
  if (severity) {
    switch (severity.get()) {
      case boost::log::trivial::warning:
        strm << "\033[33m";
        color = true;
        break;
      case boost::log::trivial::error:
      case boost::log::trivial::fatal:
        strm << "\033[31m";
        color = true;
        break;
      default:
        break;
    }
  }
  // setw(7) = the longest log level. eg "warning"
  strm << std::setw(7) << std::setfill(' ') << severity << ": " << rec[boost::log::expressions::smessage];
  if (color) {
    strm << "\033[0m";
  }
}

void logger_init_sink(bool use_colors = false) {
  auto stream = &std::cerr;
  if (getenv("LOG_STDERR") == nullptr) {
    stream = &std::cout;
  }
  auto sink = boost::log::add_console_log(*stream, boost::log::keywords::format = "%Message%",
                                          boost::log::keywords::auto_flush = true);
  if (use_colors) {
    sink->set_formatter(&color_fmt);
  }
}

Allow logger to use STDERR

logging: Allow logger to use STDERR

This allows libaktualizr to log to STDERR if LOG_STDERR is defined
in the environment. A handy way this can be used is for something
like aktualizr-get:

 LOG_STDERR=1 aktualizr-get ....

This allows you to understand what is logging (stderr's fd) and what
is the output (stdout's fd).

Signed-off-by: Andy Doan <e3579b1e47f273529f0f929453e939a68ede9fd1@foundries.io>


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

#include <realm.hpp>
#include "error_handling.hpp"
#include "marshalling.hpp"
#include "realm_export_decls.hpp"

using namespace realm;
using namespace realm::binding;

extern "C" {

REALM_EXPORT void row_destroy(Row* row_ptr)
{
    handle_errors([&]() {
        delete row_ptr;
    });
}

REALM_EXPORT size_t row_get_row_index(const Row* row_ptr)
{
    return handle_errors([&]() {
        return row_ptr->get_index();
    });
}

REALM_EXPORT size_t row_get_is_attached(const Row* row_ptr)
{
    return handle_errors([&]() {
        return bool_to_size_t(row_ptr->is_attached());
    });
}

}   // extern "C"

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

#include <realm.hpp>
#include "error_handling.hpp"
#include "marshalling.hpp"
#include "realm_export_decls.hpp"

using namespace realm;
using namespace realm::binding;

extern "C" {

REALM_EXPORT void row_destroy(Row* row_ptr)
{
    handle_errors([&]() {
        delete row_ptr;
    });
}

REALM_EXPORT size_t row_get_row_index(const Row* row_ptr)
{
    return handle_errors([&]() {
        if (!row_ptr->is_attached())
            throw std::exception();
        return row_ptr->get_index();
    });
}

REALM_EXPORT size_t row_get_is_attached(const Row* row_ptr)
{
    return handle_errors([&]() {
        return bool_to_size_t(row_ptr->is_attached());
    });
}

}   // extern "C"

Throw standard exception on illegal row access


#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main() {
  VideoCapture cap(0);
  if (!cap.isOpened()) {
    cout << "Error opening webcam" << endl;
    return -1;
  }

  int frame_width  = cap.get(CV_CAP_PROP_FRAME_WIDTH);
  int frame_height = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
  VideoWriter video("out.avi", CV_FOURCC('M', 'J', 'P', 'G'), 10, Size(frame_width, frame_height), true);

  for (;;) {
    Mat frame;
    cap >> frame;
    video.write(frame);
    // imshow("Frame", frame);
    if (waitKey(1) == 27) {
      break;
    }
  }
  return 0;
}

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main() {
  VideoCapture cap(0);
  if (!cap.isOpened()) {
    cout << "Error opening webcam" << endl;
    return -1;
  }

  int frame_width  = cap.get(CV_CAP_PROP_FRAME_WIDTH);
  int frame_height = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
  int four_cc = CV_FOURCC('F', 'M', 'P', '4');
  VideoWriter video("out.avi", four_cc, 10, Size(frame_width, frame_height), true);

  for (;;) {
    Mat frame;
    cap >> frame;
    video.write(frame);
    // imshow("Frame", frame);
    if (waitKey(1) == 27) {
      break;
    }
  }
  return 0;
}

Use FFmpeg mp4 codec for output

Use FFmpeg mp4 codec for output


#include "gtest/gtest.h"
#include "motor_shield.h"

MotorShield mshield(1, 3, 4, 5);

TEST(MotorShield, Initialization) {
  ASSERT_TRUE(1 == 1);
}

#include "gtest/gtest.h"
#include "motor_shield.h"

#define SPEED_L 1
#define DIR_L 2

#define SPEED_R 3
#define DIR_R 4

MotorShield mshield(SPEED_L, DIR_L, SPEED_R, DIR_R);

TEST(MotorShield, Initialization) {
  ASSERT_EQ(0, mshield.getMinSpeed());
  ASSERT_EQ(255, mshield.getMaxSpeed());

  ASSERT_EQ(SPEED_L, mshield.getLeftSpeedPin());
  ASSERT_EQ(SPEED_R, mshield.getRightSpeedPin());

  ASSERT_EQ(DIR_L, mshield.getLeftDirPin());
  ASSERT_EQ(DIR_R, mshield.getRightDirPin());
}

Add a test for MotorShield constructor

Add a test for MotorShield constructor


/*
 * msg - user messages - implementation
 * Copyright(c) 2004 of wave++ (Yuri D'Elia) <wavexx@users.sf.net>
 * Distributed under GNU LGPL without ANY warranty.
 */

// c system headers
#include <stdarg.h>
#include <cstdio>
using std::vfprintf;
using std::fprintf;

// data
const char* prg;
bool verbose = false;

// implementation
void
err(const char* fmt, ...)
{
  va_list params;

  fprintf(stderr, "%s: ", prg);

  va_start(params, fmt);
  vfprintf(stderr, fmt, params);
  va_end(params);

  fprintf(stderr, "\n");
}

void
msg(const char* fmt, ...)
{
  if(!verbose)
    return;

  va_list params;

  fprintf(stderr, "%s: ", prg);

  va_start(params, fmt);
  vfprintf(stderr, fmt, params);
  va_end(params);

  fprintf(stderr, "\n");
}

/*
 * msg - user messages - implementation
 * Copyright(c) 2004 of wave++ (Yuri D'Elia) <wavexx@users.sf.net>
 * Distributed under GNU LGPL without ANY warranty.
 */

// local headers
#include "msg.hh"

// c system headers
#include <stdarg.h>
#include <cstdio>
using std::vfprintf;
using std::fprintf;

// data
const char* prg;
bool verbose = false;

// implementation
void
err(const char* fmt, ...)
{
  va_list params;

  fprintf(stderr, "%s: ", prg);

  va_start(params, fmt);
  vfprintf(stderr, fmt, params);
  va_end(params);

  fprintf(stderr, "\n");
}

void
msg(const char* fmt, ...)
{
  if(!verbose)
    return;

  va_list params;

  fprintf(stderr, "%s: ", prg);

  va_start(params, fmt);
  vfprintf(stderr, fmt, params);
  va_end(params);

  fprintf(stderr, "\n");
}

Include the header for safety.

Include the header for safety.

[git-p4: depot-paths = "//depot/fIcy/main/": change = 544]


#include "Graph.h"
#include <fstream>

using namespace std;

void main()
{
	setlocale(LC_ALL, "Russian");
	ifstream inputFile("inputfile.txt");
	int numberOfCountries = 0;
	List **mapOfWorld = creatingCoutries(inputFile);
	printMap(mapOfWorld);
	deleteMap(mapOfWorld);
	system("pause");
}

Add new functions and finished module Graph.h


//
// Created by Konstantin Gredeskoul on 1/23/16.
//

#include "gtest/gtest.h"
#include "macros_color_test.h"

TEST(rgb_pixel, set_color) {
    pixel.setColor(purple);

    EXPECT_EQ_COLORS(pixel.getColor(), purple);
    wait_for(10);
    EXPECT_EQ_COLORS(pixel.getColor(), purple);
}

TEST(rgb_pixel, fade_same_colors) {
    pixel.fade(purple, purple, 100);
    EXPECT_EQ_COLORS(pixel.getColor(), purple);
    wait_for(90);
    EXPECT_EQ_COLORS(pixel.getColor(), purple);
}

TEST(rgb_pixel, tick_100ms) {
    pixel.fade(purple, orange, 200);
    wait_for(100);
    RGBColor dark_grey = (orange - purple) / 2;
    EXPECT_EQ_COLORS(dark_grey, pixel.getColor());
}

//
// Created by Konstantin Gredeskoul on 1/23/16.
//

#include "gtest/gtest.h"
#include "macros_color_test.h"

TEST(rgb_pixel, set_color) {
    pixel.setColor(purple);

    EXPECT_EQ_COLORS(pixel.getColor(), purple);
    wait_for(10);
    EXPECT_EQ_COLORS(pixel.getColor(), purple);
}

//TEST(rgb_pixel, fade_same_colors) {
//    pixel.fade(purple, purple, 100);
//    EXPECT_EQ_COLORS(pixel.getColor(), purple);
//    wait_for(90);
//    EXPECT_EQ_COLORS(pixel.getColor(), purple);
//}
//
//TEST(rgb_pixel, tick_100ms) {
//    pixel.fade(purple, orange, 200);
//    wait_for(100);
//    RGBColor dark_grey = (orange - purple) / 2;
//    EXPECT_EQ_COLORS(dark_grey, pixel.getColor());
//}

Comment out broken tests for now

Comment out broken tests for now


/*
    googletalkcalldialog.cpp - Google Talk and Google libjingle support

    Copyright (c) 2009 by Pali Rohár <pali.rohar@gmail.com>

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

#include <QCloseEvent>

#include "googletalkcalldialog.h"

GoogleTalkCallDialog::GoogleTalkCallDialog(QWidget *parent): QDialog(parent) {
	setupUi(this);
}

void GoogleTalkCallDialog::closeEvent(QCloseEvent * e) {
	e->ignore();
	emit(closed());
}

#include "googletalkcalldialog.moc"

/*
    googletalkcalldialog.cpp - Google Talk and Google libjingle support

    Copyright (c) 2009 by Pali Rohár <pali.rohar@gmail.com>

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

#include "googletalkcalldialog.h"

#include <QCloseEvent>

GoogleTalkCallDialog::GoogleTalkCallDialog(QWidget *parent): QDialog(parent) {
	setupUi(this);
}

void GoogleTalkCallDialog::closeEvent(QCloseEvent * e) {
	e->ignore();
	emit(closed());
}

#include "googletalkcalldialog.moc"

protocols/jabber: Include missing headers & own header as first

This makes header files standalone and fixing krazy issues.


// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
// RUN: not cpp11-migrate -format-style=non_existent_file.yaml -use-auto %t.cpp -- -std=c++11
// RUN: touch %T/non_format_config.yaml
// RUN: not cpp11-migrate -format-style=%T/non_format_config.yaml -use-auto %t.cpp -- -std=c++11
// RUN: cpp11-migrate -format-style=LLVM -use-auto %t.cpp -- -std=c++11
// RUN: FileCheck --strict-whitespace -input-file=%t.cpp %s

class MyType012345678901234567890123456789 {};

int f() {
  MyType012345678901234567890123456789 *a =
      new MyType012345678901234567890123456789();
  // CHECK: {{^\ \ auto\ a\ \=\ new\ MyType012345678901234567890123456789\(\);}}

  delete a;
}

cpp11-migrate: Tweak lit tests to avoid false negatives

Recent failures on a freebsd buildbot indicated a weakness in the
Reformatting.cpp lit test. Tweaking the test to avoid false negatives and
hopefully make the buildbot happy.

git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@187153 91177308-0d34-0410-b5e6-96231b3b80d8


#include "cvd/colourspace.h"

namespace CVD {
	namespace ColourSpace {

		inline void yuv420p_to_rgb_c(const unsigned char* y, const unsigned char* u, const unsigned char* v, unsigned char* rgb, unsigned int width, unsigned int height);

		extern "C"{
			void cvd_asm_yuv420p_to_rgb(const unsigned char*, unsigned char*, int);
		}

		void yuv420p_to_rgb(const unsigned char* y, const unsigned char* u, const unsigned char* v, unsigned char* rgb, unsigned int width, unsigned int height) {
			if (is_aligned<8>(y) && (u == y + width*height) && is_aligned<8>(u) && (v == u + width*height/4) && is_aligned<8>(v) &&
			                                                             is_aligned<8>(rgb) && ((width&4) == 0) && ((height&1)==0))
				cvd_asm_yuv420p_to_rgb(y,rgb,width,height);
			else
				yuv420p_to_rgb_c(y, u, v, rgb, width, height);
		}
	}
}

#include "cvd/colourspace.h"
#include "cvd/utility.h"

namespace CVD {
	namespace ColourSpace {

		inline void yuv420p_to_rgb_c(const unsigned char* y, const unsigned char* u, const unsigned char* v, unsigned char* rgb, unsigned int width, unsigned int height);

		extern "C"{
			void cvd_asm_yuv420p_to_rgb(const unsigned char*, unsigned char*, int, int);
		}

		void yuv420p_to_rgb(const unsigned char* y, const unsigned char* u, const unsigned char* v, unsigned char* rgb, unsigned int width, unsigned int height) {
			if (is_aligned<8>(y) && (u == y + width*height) && is_aligned<8>(u) && (v == u + width*height/4) && is_aligned<8>(v) &&
			                                                             is_aligned<8>(rgb) && ((width&4) == 0) && ((height&1)==0))
				cvd_asm_yuv420p_to_rgb(y,rgb,width,height);
			else
				yuv420p_to_rgb_c(y, u, v, rgb, width, height);
		}
	}
}

Patch from Achtelik Markus to fix compile error on 32bit builds.


//
//  MathsUtilities.cpp
//  TimGameLib
//
//  Created by Tim Brier on 10/04/2015.
//  Copyright (c) 2015 tbrier. All rights reserved.
//

#include "MathsUtilities.hpp"
#include <random>
#include <functional>

namespace MathsUtilities
{

std::function<int()> GetRandomGeneratorFunctionForRange(int min, int max)
{
    std::random_device device;
    std::default_random_engine generator(device());
    std::uniform_int_distribution<int> distribution(min, max);
    auto result = std::bind(distribution, generator);
    return result;
}

std::function<float()> GetRandomGeneratorFunctionForRange(float min, float max)
{
    std::random_device device;
    std::default_random_engine generator(device());
    std::uniform_int_distribution<float> distribution(min, max);
    auto result = std::bind(distribution, generator);
    return result;
}

} // namespace MathsUtilities

//
//  MathsUtilities.cpp
//  TimGameLib
//
//  Created by Tim Brier on 10/04/2015.
//  Copyright (c) 2015 tbrier. All rights reserved.
//

#include "MathsUtilities.hpp"
#include <random>
#include <functional>

namespace MathsUtilities
{

std::function<int()> GetRandomGeneratorFunctionForRange(int min, int max)
{
    std::random_device device;
    std::default_random_engine generator(device());
    std::uniform_int_distribution<int> distribution(min, max);
    auto result = std::bind(distribution, generator);
    return result;
}

std::function<float()> GetRandomGeneratorFunctionForRange(float min, float max)
{
    std::random_device device;
    std::default_random_engine generator(device());
    std::uniform_real_distribution<float> distribution(min, max);
    auto result = std::bind(distribution, generator);
    return result;
}

} // namespace MathsUtilities

Use real distribution for random float generator


#include "Control.h"

#include <sstream>

Control::Control() {

}

Control::Control(int id, HWND parent) :
_id(id),
_parent(parent) {
    _hWnd = GetDlgItem(parent, id);
}

Control::~Control() {

}

bool Control::Text(std::wstring text) {
    return SetDlgItemText(_parent, _id, text.c_str()) == TRUE;
}

bool Control::Text(int value) {
    return Text(std::to_wstring(value));
}

std::wstring Control::Text() {
    wchar_t text[MAX_EDITSTR];
    GetDlgItemText(_parent, _id, text, MAX_EDITSTR);
    return std::wstring(text);
}

int Control::TextAsInt() {
    std::wstring str = Text();
    int num;
    std::wistringstream wistr(str);
    wistr >> num;
    return num;
}

void Control::AddWindowExStyle(long exStyle) {
    long exs = GetWindowLongPtr(_hWnd, GWL_EXSTYLE);
    exs |= exStyle;
    SetWindowLongPtr(_hWnd, GWL_EXSTYLE, exs);
}

RECT Control::Dimensions() {
    RECT r;
    GetWindowRect(_hWnd, &r);
    return r;
}

#include "Control.h"

#include <sstream>

Control::Control() {

}

Control::Control(int id, HWND parent) :
_id(id),
_parent(parent) {
    _hWnd = GetDlgItem(parent, id);
}

Control::~Control() {

}

bool Control::Text(std::wstring text) {
    return SetDlgItemText(_parent, _id, text.c_str()) == TRUE;
}

bool Control::Text(int value) {
    return SetDlgItemInt(_parent, _id, value, TRUE) == TRUE;
}

std::wstring Control::Text() {
    wchar_t text[MAX_EDITSTR];
    GetDlgItemText(_parent, _id, text, MAX_EDITSTR);
    return std::wstring(text);
}

int Control::TextAsInt() {
    std::wstring str = Text();
    int num;
    std::wistringstream wistr(str);
    wistr >> num;
    return num;
}

void Control::AddWindowExStyle(long exStyle) {
    long exs = GetWindowLongPtr(_hWnd, GWL_EXSTYLE);
    exs |= exStyle;
    SetWindowLongPtr(_hWnd, GWL_EXSTYLE, exs);
}

RECT Control::Dimensions() {
    RECT r;
    GetWindowRect(_hWnd, &r);
    return r;
}

Use Win32 function instead of rolling our own


//===--- DriverOptions.cpp - Driver Options Table -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/Options.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"

using namespace clang::driver;
using namespace clang::driver::options;
using namespace llvm::opt;

#define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE;
#include "clang/Driver/Options.inc"
#undef PREFIX

static const OptTable::Info InfoTable[] = {
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
               HELPTEXT, METAVAR)   \
  { PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, PARAM, \
    FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS },
#include "clang/Driver/Options.inc"
#undef OPTION
};

namespace {

class DriverOptTable : public OptTable {
public:
  DriverOptTable()
    : OptTable(InfoTable, llvm::array_lengthof(InfoTable)) {}
};

}

OptTable *clang::driver::createDriverOptTable() {
  return new DriverOptTable();
}

//===--- DriverOptions.cpp - Driver Options Table -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/Options.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Option/Option.h"

using namespace clang::driver;
using namespace clang::driver::options;
using namespace llvm::opt;

#define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE;
#include "clang/Driver/Options.inc"
#undef PREFIX

static const OptTable::Info InfoTable[] = {
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
               HELPTEXT, METAVAR)   \
  { PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, PARAM, \
    FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS },
#include "clang/Driver/Options.inc"
#undef OPTION
};

namespace {

class DriverOptTable : public OptTable {
public:
  DriverOptTable()
    : OptTable(InfoTable) {}
};

}

OptTable *clang::driver::createDriverOptTable() {
  return new DriverOptTable();
}

Update clang to match llvm r250901. OptTable constructor now takes an ArrayRef. NFC

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


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

#include "chrome/browser/chromeos/login/textfield_with_margin.h"

#include "chrome/browser/chromeos/login/helper.h"
#include "ui/base/keycodes/keyboard_codes.h"

namespace {

// Holds ratio of the margin to the preferred text height.
const double kTextMarginRate = 0.33;

// Size of each vertical margin (top, bottom).
const int kVerticalMargin = 3;

}  // namespace

namespace chromeos {

TextfieldWithMargin::TextfieldWithMargin() {
  CorrectTextfieldFontSize(this);
}

TextfieldWithMargin::TextfieldWithMargin(views::Textfield::StyleFlags style)
    : Textfield(style) {
  CorrectTextfieldFontSize(this);
}

void TextfieldWithMargin::Layout() {
  int margin = GetPreferredSize().height() * kTextMarginRate;
  SetHorizontalMargins(margin, margin);
  SetVerticalMargins(kVerticalMargin, kVerticalMargin);
  views::Textfield::Layout();
}

bool TextfieldWithMargin::OnKeyPressed(const views::KeyEvent& e) {
  if (e.key_code() == ui::VKEY_ESCAPE && !text().empty()) {
    SetText(string16());
    return true;
  }
  return false;
}

}  // namespace chromeos

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

#include "chrome/browser/chromeos/login/textfield_with_margin.h"

#include "chrome/browser/chromeos/login/helper.h"
#include "ui/base/keycodes/keyboard_codes.h"

namespace {

// Holds ratio of the margin to the preferred text height.
const double kTextMarginRate = 0.33;

// Size of each vertical margin (top, bottom).
const int kVerticalMargin = 3;

}  // namespace

namespace chromeos {

TextfieldWithMargin::TextfieldWithMargin() {
  CorrectTextfieldFontSize(this);
}

TextfieldWithMargin::TextfieldWithMargin(views::Textfield::StyleFlags style)
    : Textfield(style) {
  CorrectTextfieldFontSize(this);
}

void TextfieldWithMargin::Layout() {
  int margin = GetPreferredSize().height() * kTextMarginRate;
  SetHorizontalMargins(margin, margin);
  SetVerticalMargins(kVerticalMargin, kVerticalMargin);
  views::Textfield::Layout();
}

bool TextfieldWithMargin::OnKeyPressed(const views::KeyEvent& e) {
  if (e.key_code() == ui::VKEY_ESCAPE && !text().empty()) {
    SetText(string16());
    return true;
  }
  return views::Textfield::OnKeyPressed(e);
}

}  // namespace chromeos

Fix to make the behavior of TextfieldWithMargin consistent with Textfield

Add call to views::Textfield::OnKeyPressed in TextfieldWithMargin::OnKeyPressed
Without this call, HandleKeyEvent of controller will not be called by NativeTextfieldViews.

BUG=None
TEST=None

Review URL: http://codereview.chromium.org/7284001

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


VectorXf v;
v.setLinSpaced(5,0.5f,1.5f).transpose();
cout << v << endl;

VectorXf v;
v.setLinSpaced(5,0.5f,1.5f);
cout << v << endl;

Remove confusing transpose() in setLinSpaced() docs.


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

#include "atom/common/api/event_emitter_caller.h"

#include "atom/common/api/locker.h"
#include "atom/common/node_includes.h"

namespace mate {

namespace internal {

v8::Local<v8::Value> CallMethodWithArgs(v8::Isolate* isolate,
                                        v8::Local<v8::Object> obj,
                                        const char* method,
                                        ValueVector* args) {
  // Perform microtask checkpoint after running JavaScript.
  v8::MicrotasksScope script_scope(isolate,
                                   v8::MicrotasksScope::kRunMicrotasks);
  // Use node::MakeCallback to call the callback, and it will also run pending
  // tasks in Node.js.
  v8::MaybeLocal<v8::Value> ret = node::MakeCallback(isolate, obj, method, args->size(), &args->front(),
                            {0, 0});
  if (ret.IsEmpty()) {
    return v8::Boolean::New(isolate, false);
  }
  return ret.ToLocalChecked();
}

}  // namespace internal

}  // namespace mate

Fix line length in caller.cc

Fix line length in caller.cc


// RUN: %clang_cc1 -verify %s
// REQUIRES: thread_support

// expected-warning@* 0-1{{stack nearly exhausted}}
// expected-note@* 0+{{}}

template<int N> struct X : X<N-1> {};
template<> struct X<0> {};
X<1000> x;

template<typename ...T> struct tuple {};
template<typename ...T> auto f(tuple<T...> t) -> decltype(f(tuple<T...>(t))) {} // expected-error {{exceeded maximum depth}}
void g() { f(tuple<int, int>()); }

int f(X<0>);
template<int N> auto f(X<N>) -> f(X<N-1>());

int k = f(X<1000>());

// RUN: %clang_cc1 -verify %s
// REQUIRES: thread_support

// FIXME: Detection of, or recovery from, stack exhaustion does not work on
// NetBSD at the moment. Since this is a best-effort mitigation for exceeding
// implementation limits, just disable the test.
// UNSUPPORTED: system-netbsd

// expected-warning@* 0-1{{stack nearly exhausted}}
// expected-note@* 0+{{}}

template<int N> struct X : X<N-1> {};
template<> struct X<0> {};
X<1000> x;

template<typename ...T> struct tuple {};
template<typename ...T> auto f(tuple<T...> t) -> decltype(f(tuple<T...>(t))) {} // expected-error {{exceeded maximum depth}}
void g() { f(tuple<int, int>()); }

int f(X<0>);
template<int N> auto f(X<N>) -> f(X<N-1>());

int k = f(X<1000>());

Disable stack exhaustion test on NetBSD, where either the detection or
recovery mechanism does not appear to work.

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


// Copyright (c) 2006-2008 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/app_modal_dialog_queue.h"

#include "chrome/browser/browser_list.h"

void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {
  if (!active_dialog_) {
    ShowModalDialog(dialog);
    return;
  }
  app_modal_dialog_queue_.push(dialog);
}

void AppModalDialogQueue::ShowNextDialog() {
  if (!app_modal_dialog_queue_.empty()) {
    AppModalDialog* dialog = app_modal_dialog_queue_.front();
    app_modal_dialog_queue_.pop();
    ShowModalDialog(dialog);
  } else {
    active_dialog_ = NULL;
  }
}

void AppModalDialogQueue::ActivateModalDialog() {
  if (active_dialog_)
    active_dialog_->ActivateModalDialog();
}

void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {
  dialog->ShowModalDialog();
  active_dialog_ = dialog;
}

// Copyright (c) 2006-2008 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/app_modal_dialog_queue.h"

#include "chrome/browser/browser_list.h"

void AppModalDialogQueue::AddDialog(AppModalDialog* dialog) {
  if (!active_dialog_) {
    ShowModalDialog(dialog);
    return;
  }
  app_modal_dialog_queue_.push(dialog);
}

void AppModalDialogQueue::ShowNextDialog() {
  if (!app_modal_dialog_queue_.empty()) {
    AppModalDialog* dialog = app_modal_dialog_queue_.front();
    app_modal_dialog_queue_.pop();
    ShowModalDialog(dialog);
  } else {
    active_dialog_ = NULL;
  }
}

void AppModalDialogQueue::ActivateModalDialog() {
  if (active_dialog_)
    active_dialog_->ActivateModalDialog();
}

void AppModalDialogQueue::ShowModalDialog(AppModalDialog* dialog) {
  // Set active_dialog_ before showing it, because ShowModalDialog can wind up
  // calling ShowNextDialog in some cases, which will change active_dialog_.
  active_dialog_ = dialog;
  dialog->ShowModalDialog();
}

Set active_dialog_ before showing it, since showing a dialog can sometimes
actually move to the next one in the queue instead.

BUG=26398
TEST=Make sure alert/confirm boxes work properly. Make sure a background
    tab that shows a (delayed) alert box works. Same with a background
    browser. Especially make sure http://crbug.com/10699 doesn't recur.
Review URL: http://codereview.chromium.org/339094

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


#include <immintrin.h>

bool is_sorted_avx512(int32_t* a, size_t n) {

    const __m512i shuffle_pattern = _mm512_setr_epi32(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15);

    size_t i = 0;
    while (i < n - 16) {
        const __m512i curr = _mm512_loadu_si512(reinterpret_cast<const __m512i*>(a + i));
        const __m512i next = _mm512_permutexvar_epi32(shuffle_pattern, curr);

        const __mmask16 mask = _mm512_cmpgt_epi32_mask(curr, next);
        if (mask != 0) {
            return false;
        }

        i += 15;
    }

    for (/**/; i + 1 < n; i++) {
        if (a[i] > a[i + 1])
            return false;
    }

    return true;
}

#include <immintrin.h>

bool is_sorted_avx512(int32_t* a, size_t n) {

    static const __m512i shuffle_pattern = _mm512_setr_epi32(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15);

    size_t i = 0;
    while (i < n - 16) {
        const __m512i curr = _mm512_loadu_si512(reinterpret_cast<const __m512i*>(a + i));
        const __m512i next = _mm512_permutexvar_epi32(shuffle_pattern, curr);

        const __mmask16 mask = _mm512_cmpgt_epi32_mask(curr, next);
        if (mask != 0) {
            return false;
        }

        i += 15;
    }

    for (/**/; i + 1 < n; i++) {
        if (a[i] > a[i + 1])
            return false;
    }

    return true;
}

Use static array --- const may not be sufficient