/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * 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 <folly/executors/GlobalExecutor.h>

#include <folly/executors/CPUThreadPoolExecutor.h>
#include <folly/executors/IOExecutor.h>
#include <folly/executors/IOThreadPoolExecutor.h>
#include <folly/portability/GTest.h>
#include <folly/synchronization/Baton.h>
#include <folly/system/HardwareConcurrency.h>

using namespace folly;

DECLARE_uint32(folly_global_cpu_executor_threads);

TEST(GlobalCPUExecutorTest, CPUThreadCountFlagSet) {
  gflags::FlagSaver flagsaver;

  FLAGS_folly_global_cpu_executor_threads = 100;
  auto cpu_threadpool = dynamic_cast<folly::CPUThreadPoolExecutor*>(
      folly::getGlobalCPUExecutor().get());

  EXPECT_EQ(cpu_threadpool->numThreads(), 100);
}

/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * 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 <folly/executors/GlobalExecutor.h>

#include <folly/executors/CPUThreadPoolExecutor.h>
#include <folly/executors/IOExecutor.h>
#include <folly/executors/IOThreadPoolExecutor.h>
#include <folly/portability/GTest.h>
#include <folly/synchronization/Baton.h>

DECLARE_uint32(folly_global_cpu_executor_threads);

TEST(GlobalCPUExecutorTest, CPUThreadCountFlagSet) {
  gflags::FlagSaver flagsaver;

  FLAGS_folly_global_cpu_executor_threads = 100;
  auto cpu_threadpool = dynamic_cast<folly::CPUThreadPoolExecutor*>(
      folly::getGlobalCPUExecutor().get());

  EXPECT_EQ(cpu_threadpool->numThreads(), 100);
}

Remove dead includes in folly/executors

Remove dead includes in folly/executors

Reviewed By: Orvid

Differential Revision: D38385209

fbshipit-source-id: 1d962f7b7f21ef7892727ec5d3ed315dfba06951


// Copyright (c) 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/extensions/extension_apitest.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Cookies) {
  ASSERT_TRUE(RunExtensionTest("cookies")) << message_;
}

// Copyright (c) 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/extensions/extension_apitest.h"

#if defined(OS_LINUX)
// See http://crbug.com/42943.
#define MAYBE_Storage FLAKY_Storage
#else
#define MAYBE_Storage Storage
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Cookies) {
  ASSERT_TRUE(RunExtensionTest("cookies")) << message_;
}

[Linux] Mark ExtensionApiTest.Storage as flaky.
BUG=42943
TEST=none
TBR=rafaelw

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

git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@46083 4ff67af0-8c30-449e-8e8b-ad334ec8d88c


// Copyright (c) 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/extensions/extension_apitest.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}

// Copyright (c) 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/extensions/extension_apitest.h"

#if defined(OS_WIN)
// Always fails on Windows after r110181: http://crbug.com/104419.
#define MAYBE_Storage FAILS_Storage
#else
#define MAYBE_Storage Storage
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}

Mark ExtensionApiTest.Storage as failing, it always fails on Windows after r110181.

BUG=104419
TEST=none
Review URL: http://codereview.chromium.org/8573032

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


/*
 * Copyright Regents of the University of Minnesota, 2016.  This software is released under the following license: http://opensource.org/licenses/
 * Source code originally developed at the University of Minnesota Interactive Visualization Lab (http://ivlab.cs.umn.edu).
 *
 * Code author(s):
 * 		Dan Orban (dtorban)
 */

#include <display/graphics/VRGraphicsWindowNode.h>

namespace MinVR {

VRGraphicsWindowNode::~VRGraphicsWindowNode() {
}

void VRGraphicsWindowNode::render() {
	startRender();
	waitForRenderComplete();
	synchronize();
}

void VRGraphicsWindowNode::startRender() {
	setCurrentContext();
	//TODO: load data
	VRDisplayNode::render();
	flush();
}

void VRGraphicsWindowNode::waitForRenderComplete() {
	finish();
}

void VRGraphicsWindowNode::synchronize() {
	swapBuffers();
}

void VRGraphicsWindowNode::addChild(VRGraphicsWindowChild* child) {
	VRDisplayNode::addChild(child);
}

} /* namespace MinVR */

/*
 * Copyright Regents of the University of Minnesota, 2016.  This software is released under the following license: http://opensource.org/licenses/
 * Source code originally developed at the University of Minnesota Interactive Visualization Lab (http://ivlab.cs.umn.edu).
 *
 * Code author(s):
 * 		Dan Orban (dtorban)
 */

#include <display/graphics/VRGraphicsWindowNode.h>

namespace MinVR {

VRGraphicsWindowNode::~VRGraphicsWindowNode() {
}

void VRGraphicsWindowNode::render() {
	startRender();
	waitForRenderComplete();
	synchronize();
}

void VRGraphicsWindowNode::startRender() {
	setCurrentContext();
	//TODO: load data
	VRDisplayNode::render();
	flush();
}

void VRGraphicsWindowNode::waitForRenderComplete() {
	finish();
}

void VRGraphicsWindowNode::synchronize() {
	swapBuffers();
	clearCurrentContext();
}

void VRGraphicsWindowNode::addChild(VRGraphicsWindowChild* child) {
	VRDisplayNode::addChild(child);
}

} /* namespace MinVR */

Clear current context for window.

Clear current context for window.


#include <iostream>
using namespace std;
struct node {
  int val = 0;
  node * l = nullptr;
  node * r = nullptr;
};
inline node* build(node *head, int value){
  node *son = new node;
  son->val = value;
  if (head == nullptr) return son;
  node * aux = head, * nxt = head;
  while(nxt != nullptr){
    aux = nxt;
    if (value > nxt->val) nxt = nxt->r;
      else nxt = nxt->l;
  }
  if(value > aux-> val) aux->r = son;
  else aux->l = son;
  return head;
}
inline void show(node* head){
  if (head==nullptr) return;
  show(head->l);
  cout << head->val << endl;
  show(head->r);
}
int main(){
  node *head = new node;
  head->val = 5;
  head = build(head, 45);
  head = build(head, 20);
  show(head);
  return 0;
}

#include <bits/stdc++.h>
using namespace std;
struct node{
	int val;
	node *left;
	node *right;
	node( int v ){
		val = v;
		left = nullptr;
		right = nullptr;
	}
	node* insert(node *n, int val){
		if(n == nullptr ) return new node(val);
		if(n->val > val) n->left = insert(n->left, val);
		else n->right = insert(n->right, val);
	}
	void show(node *n){
		if(n!=nullptr){
			show(n->left);
			cout << n->val << " ";
			show(n->right);
		}
	}
	string gHash(node *n) {
	 	string hash="";
	 	if(n->right!=nullptr)
	 		hash += "R"+gHash(n->right);
		if(n->left!=nullptr)
	 		hash += "L"+gHash(n->left);
		return hash+"!";
	 }
};

int main(){
	node * root = new node(7);
	root->insert(root,1);
	root->insert(root,-1);
	root->show(root);

	cout << endl<<root->gHash(root) <<endl;
	return 0;
}

Create useful binary tree, add some assets.


#include <gloperate/input/AbstractEventProvider.h>

#include <gloperate/input/AbstractEvent.h>
#include <gloperate/navigation/AbstractMapping.h>

namespace gloperate
{

AbstractEventProvider::AbstractEventProvider()
{
}

AbstractEventProvider::~AbstractEventProvider()
{
    for (AbstractMapping * mapping : m_mappings)
    {
        mapping->removeProvider(this);
    }
}

void AbstractEventProvider::registerMapping(AbstractMapping * mapping)
{
    m_mappings.push_back(mapping);
}

void AbstractEventProvider::deregisterMapping(AbstractMapping * mapping)
{
    m_mappings.remove(mapping);
}

void AbstractEventProvider::passEvent(AbstractEvent * event)
{
    for (AbstractMapping * mapping : m_mappings)
    {
        mapping->processEvent(event);
    }
}

} // namespace gloperate

#include <gloperate/input/AbstractEventProvider.h>

#include <gloperate/input/AbstractEvent.h>
#include <gloperate/navigation/AbstractMapping.h>

namespace gloperate
{

AbstractEventProvider::AbstractEventProvider()
{
}

AbstractEventProvider::~AbstractEventProvider()
{
    // Unregister from mappings

    // Note: removeProvider calls registerMapping in turn, which removes the mapping
    // from m_mappings. Therefore, a for-loop would get into trouble, so we iterate
    // like this until the list is empty.

    while (!m_mappings.empty()) {
        AbstractMapping * mapping = m_mappings.front();
        mapping->removeProvider(this);
    }
}

void AbstractEventProvider::registerMapping(AbstractMapping * mapping)
{
    m_mappings.push_back(mapping);
}

void AbstractEventProvider::deregisterMapping(AbstractMapping * mapping)
{
    m_mappings.remove(mapping);
}

void AbstractEventProvider::passEvent(AbstractEvent * event)
{
    for (AbstractMapping * mapping : m_mappings)
    {
        mapping->processEvent(event);
    }
}

} // namespace gloperate

Fix crash on shutdown caused by a dependency loop


//===- tools/seec-trace-view/Annotations.cpp ------------------------------===//
//
//                                    SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//

#include "seec/Util/MakeUnique.hpp"

#include <wx/archive.h>
#include <wx/xml/xml.h>

#include "Annotations.hpp"

AnnotationCollection::
AnnotationCollection(std::unique_ptr<wxXmlDocument> XmlDocument)
: m_XmlDocument(std::move(XmlDocument))
{}

AnnotationCollection::AnnotationCollection()
{
  m_XmlDocument = seec::makeUnique<wxXmlDocument>();

  auto const Root = new wxXmlNode(nullptr, wxXML_ELEMENT_NODE, "annotations");

  m_XmlDocument->SetRoot(Root);
}

AnnotationCollection::~AnnotationCollection() = default;

seec::Maybe<AnnotationCollection>
AnnotationCollection::fromDoc(std::unique_ptr<wxXmlDocument> Doc)
{
  return AnnotationCollection(std::move(Doc));
}

bool AnnotationCollection::writeToArchive(wxArchiveOutputStream &Stream)
{
  return Stream.PutNextEntry("annotations.xml")
      && m_XmlDocument->Save(Stream);
}

//===- tools/seec-trace-view/Annotations.cpp ------------------------------===//
//
//                                    SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//

#include "seec/Util/MakeUnique.hpp"

#include <wx/archive.h>
#include <wx/xml/xml.h>

#include "Annotations.hpp"

namespace {

bool isAnnotationCollection(wxXmlDocument &Doc)
{
  if (!Doc.IsOk())
    return false;

  auto const RootNode = Doc.GetRoot();
  if (!RootNode || RootNode->GetName() != "annotations")
    return false;

  return true;
}

} // anonymous namespace

AnnotationCollection::
AnnotationCollection(std::unique_ptr<wxXmlDocument> XmlDocument)
: m_XmlDocument(std::move(XmlDocument))
{}

AnnotationCollection::AnnotationCollection()
{
  m_XmlDocument = seec::makeUnique<wxXmlDocument>();

  auto const Root = new wxXmlNode(nullptr, wxXML_ELEMENT_NODE, "annotations");

  m_XmlDocument->SetRoot(Root);
}

AnnotationCollection::~AnnotationCollection() = default;

seec::Maybe<AnnotationCollection>
AnnotationCollection::fromDoc(std::unique_ptr<wxXmlDocument> Doc)
{
  if (!isAnnotationCollection(*Doc))
    return seec::Maybe<AnnotationCollection>();

  return AnnotationCollection(std::move(Doc));
}

bool AnnotationCollection::writeToArchive(wxArchiveOutputStream &Stream)
{
  return Stream.PutNextEntry("annotations.xml")
      && m_XmlDocument->Save(Stream);
}

Check that annotations.xml documents match our expectations.


/*
 * Copyright © 2017 Collabora Ltd.
 *
 * This file is part of vkmark.
 *
 * vkmark is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * vkmark is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with vkmark. If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *   Alexandros Frantzis <alexandros.frantzis@collabora.com>
 */

#include "default_benchmarks.h"

std::vector<std::string> DefaultBenchmarks::get()
{
    return std::vector<std::string>{
        "vertex",
        "shading:shading=gouraud",
        "shading:shading=blinn-phong-inf",
        "shading:shading=phong",
        "cube",
        "clear"
    };
}

/*
 * Copyright © 2017 Collabora Ltd.
 *
 * This file is part of vkmark.
 *
 * vkmark is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * vkmark is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with vkmark. If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *   Alexandros Frantzis <alexandros.frantzis@collabora.com>
 */

#include "default_benchmarks.h"

std::vector<std::string> DefaultBenchmarks::get()
{
    return std::vector<std::string>{
        "vertex",
        "shading:shading=gouraud",
        "shading:shading=blinn-phong-inf",
        "shading:shading=phong",
        "shading:shading=cel",
        "cube",
        "clear"
    };
}

main: Add cel shading scene to default bencharks


#include "webview.h"

#include <QPaintEvent>

WebView::WebView(QWidget *parent)
    : QWebView(parent)
    , inLoading(false)
{
    connect(this, SIGNAL(loadStarted()), this, SLOT(newPageLoading()));
    connect(this, SIGNAL(loadFinished(bool)), this, SLOT(pageLoaded(bool)));
}

void WebView::paintEvent(QPaintEvent *event)
{
    if (inLoading && loadingTime.elapsed() < 750) {
        QPainter painter(this);
        painter.setBrush(Qt::white);
        painter.setPen(Qt::NoPen);
        foreach (const QRect &rect, event->region().rects()) {
            painter.drawRect(rect);
        }
    } else {
        QWebView::paintEvent(event);
    }
}

void WebView::newPageLoading()
{
    inLoading = true;
    loadingTime.start();
}

void WebView::pageLoaded(bool)
{
    inLoading = false;
    update();
}

#include "webview.h"

#include <QPaintEvent>
#include <QWebFrame>

WebView::WebView(QWidget *parent)
    : QWebView(parent)
    , inLoading(false)
{
    connect(this, SIGNAL(loadStarted()), this, SLOT(newPageLoading()));
    connect(this, SIGNAL(loadFinished(bool)), this, SLOT(pageLoaded(bool)));
    page()->setPreferredContentsSize(QSize(1024, 768));
}

void WebView::paintEvent(QPaintEvent *event)
{
    if (inLoading && loadingTime.elapsed() < 750) {
        QPainter painter(this);
        painter.setBrush(Qt::white);
        painter.setPen(Qt::NoPen);
        foreach (const QRect &rect, event->region().rects()) {
            painter.drawRect(rect);
        }
    } else {
        QWebView::paintEvent(event);
    }
}

void WebView::newPageLoading()
{
    inLoading = true;
    loadingTime.start();
}

void WebView::pageLoaded(bool)
{
    inLoading = false;
    update();
}

Change the prefered content size of the anomaly browser

Having the prefered content size equals to the screen size gives
some bad layout on devices.


#include <iostream>
#include <vector>
#include <assert.h>
using namespace std;

class ImageDithering {
public:
  int count(string dithered, vector<string> screen) {
    unsigned d[26];
    for (int i = 0; i < 26; i++) {
      d[i] = 0;
    }
    for (unsigned i = 0; i < dithered.length(); i++) {
      d[dithered[i] - '0'] = 1;
    }
    int count = 0;

    for (vector<string>::iterator str = screen.begin(); str != screen.end(); ++str) {
      for (unsigned i = 0; i < str->length(); i++) {
        count += d[(*str)[i] - '0'];
      }
    }

    return count;
  }
};

int main()
{
  ImageDithering id;
  string sc[] = {
    "AAAAAAAA",
    "ABWBWBWA",
    "AWBWBWBA",
    "ABWBWBWA",
    "AWBWBWBA",
    "AAAAAAAA"
  };
  vector<string> scr1(sc, sc + 6);
  assert( id.count("BW", scr1) == 24);

  return 0;
}

#include <iostream>
#include <vector>
#include <assert.h>
using namespace std;

class ImageDithering {
public:
  int count(string dithered, vector<string> screen) {
    unsigned d[26];
    for (int i = 0; i < 26; i++) {
      d[i] = 0;
    }
    for (unsigned i = 0; i < dithered.length(); i++) {
      d[dithered[i] - 'A'] = 1;
    }
    int count = 0;

    for (vector<string>::iterator str = screen.begin(); str != screen.end(); ++str) {
      for (unsigned i = 0; i < str->length(); i++) {
        count += d[(*str)[i] - 'A'];
      }
    }

    return count;
  }
};

int main()
{
  ImageDithering id;
  string sc1[] = {
    "AAAAAAAA",
    "ABWBWBWA",
    "AWBWBWBA",
    "ABWBWBWA",
    "AWBWBWBA",
    "AAAAAAAA"
  };
  vector<string> scr1(sc1, sc1 + 6);
  assert( id.count("BW", scr1) == 24);

  string sc2[] = {"OT", "QF", "KD", "HR", "VV", "XB"};
  vector<string> scr2(sc2, sc2 + 6);
  assert( id.count("JSPQKYRME", scr2) == 3);
  cout << id.count("JSPQKYRME", scr2);

  return 0;
}

Fix SRM 144, Div 2, Problem ImageDithering

- previously without system test checks
- replaced '0' with 'A' for dithered variable


#include <libclientserver.h>

ScopedLock::ScopedLock(Mutex *m) {
    m_mutex = m;
    m_mutex->Lock();
    m_locked = true;
}

ScopedLock::ScopedLock(Mutex *m, std::function<void()> ErrorHandler) :
    m_mutex(m)
{
    if (m->TryLock()) {
        ErrorHandler();
    }
    m_locked = true;
}

ScopedLock::~ScopedLock() {
    if (m_locked)
    {
        m_mutex->Unlock();
        m_locked = false;
    }
}

void ScopedLock::Lock()
{
    if (m_locked)
        abort();
    m_mutex->Lock();
    m_locked = true;
}

void ScopedLock::Unlock()
{
    if (m_locked == false)
        abort();
    m_mutex->Unlock();
    m_locked = false;
}

#include <libclientserver.h>

ScopedLock::ScopedLock(Mutex *m) :
    m_mutex(m)
{
    m_mutex->Lock();
    m_locked = true;
}

ScopedLock::ScopedLock(Mutex *m, std::function<void()> ErrorHandler) :
    m_mutex(m)
{
    if (m->TryLock()) {
        ErrorHandler();
    }
    m_locked = true;
}

ScopedLock::~ScopedLock() {
    if (m_locked)
    {
        m_mutex->Unlock();
        m_locked = false;
    }
}

void ScopedLock::Lock()
{
    if (m_locked)
        abort();
    m_mutex->Lock();
    m_locked = true;
}

void ScopedLock::Unlock()
{
    if (m_locked == false)
        abort();
    m_mutex->Unlock();
    m_locked = false;
}

Move m_mutex to init list

Move m_mutex to init list


ll rotatingCalipers(){
	int ans = 0;

	int i = 0, j = dn.size()-1;

	while(i < (int)up.size() - 1 || j > 0){
		// Entrou aqui: up[i] e dn[j] eh um antipodal pair
		ans = max(ans, dist2(up[i],dn[j]));

		if(i == (int)up.size()-1) j--;
		else if(j == 0) i++;
		else{
			// Verifica qual o menor angulo a ser rotacionado p utilizar na rotacao
			if(ccw(point(0,0), toVec(up[i], up[i+1]), toVec(dn[j],dn[j-1])))
				i++;
			else
				j--;
		}
	}
	return ans;
}

ll rotatingCalipers(){
	int ans = 0;

	int i = 0, j = dn.size()-1;

	while(i < (int)up.size() - 1 || j > 0){
		// Entrou aqui: up[i] e dn[j] eh um antipodal pair
		ans = max(ans, dist2(up[i],dn[j]));

		if(i == (int)up.size()-1) j--;
		else if(j == 0) i++;
		else{
			// Verifica qual o menor angulo a ser rotacionado p utilizar na rotacao
			if((up[i+1].second - up[i].second) * (dn[j].first - dn[j-1].first)
				> (dn[j].second - dn[j-1].second) * (up[i+1].first - up[i].first ))
				i++;
			else
				j--;
		}
	}
	return ans;
}

Revert "Alterando uma func (usando funcoes do CP3)"

This reverts commit 746ce1d335d4c23920b02f56431817e9f72e4ffc.


/* mbed Microcontroller Library
 * Copyright (c) 2021 ARM Limited
 * Copyright (c) 2021 Embedded Planet, Inc.
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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 "USBSerial.h"
#include "platform/mbed_retarget.h"

#ifndef MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE
#define MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE 0
#endif

#if MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE

/* Retarget stdio to USBSerial */
mbed::FileHandle *mbed::mbed_target_override_console(int fd)
{
    static USBSerial usb_serial;
    return &usb_serial;
}

#endif

/* mbed Microcontroller Library
 * Copyright (c) 2021 ARM Limited
 * Copyright (c) 2021 Embedded Planet, Inc.
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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.
 */

#ifndef MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE
#define MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE 0
#endif

#if MBED_CONF_EP_ATLAS_ENABLE_USB_STDIO_CONSOLE

#include "USBSerial.h"
#include "platform/mbed_retarget.h"

/* Retarget stdio to USBSerial */
mbed::FileHandle *mbed::mbed_target_override_console(int fd)
{
    static USBSerial usb_serial;
    return &usb_serial;
}

#endif

EP_ATLAS: Remove requirement for USB library if not required

Move inclusion of USB header file within the existing
conditional pre-processor directive so the USB library
is not required if USB stdio console is disable


Fix case in name of included header

Fix case in name of included header


#include "capu/util/ConsoleLogAppender.h"
#include "capu/util/LogMessage.h"
#include "capu/os/Console.h"
#include <stdio.h>

namespace capu
{
    ConsoleLogAppender::~ConsoleLogAppender()
    {
    }

    void ConsoleLogAppender::logMessage(const LogMessage& logMessage)
    {
        m_logMutex.lock();

        switch(logMessage.getLogLevel())
        {
        case LL_TRACE:
            Console::Print(Console::WHITE, "[  Trace  ] ");
            break;
        default:
        case LL_DEBUG :
            Console::Print(Console::WHITE, "[  Debug  ] ");
            break;
        case LL_INFO :
            Console::Print(Console::GREEN, "[  Info   ] ");
            break;
        case LL_WARN :
            Console::Print(Console::YELLOW, "[  Warn   ] ");
            break;
        case LL_ERROR :
            Console::Print(Console::RED, "[  Error  ] ");
            break;
        case LL_FATAL :
            Console::Print(Console::RED, "[  Fatal  ] ");
            break;
        }

        Console::Print(Console::AQUA, logMessage.getContext().getContextName().c_str());
        Console::Print(" | %s\n", logMessage.getLogMessage());
        Console::Flush();
        m_logMutex.unlock();
    }
}

#include "capu/util/ConsoleLogAppender.h"
#include "capu/util/LogMessage.h"
#include "capu/os/Console.h"
#include "capu/os/Time.h"
#include <stdio.h>

namespace capu
{
    ConsoleLogAppender::~ConsoleLogAppender()
    {
    }

    void ConsoleLogAppender::logMessage(const LogMessage& logMessage)
    {
        m_logMutex.lock();

        const uint64_t now = Time::GetMilliseconds();
        Console::Print(Console::WHITE, "%.3f ", now/1000.0);

        switch(logMessage.getLogLevel())
        {
        case LL_TRACE:
            Console::Print(Console::WHITE, "[  Trace  ] ");
            break;
        default:
        case LL_DEBUG :
            Console::Print(Console::WHITE, "[  Debug  ] ");
            break;
        case LL_INFO :
            Console::Print(Console::GREEN, "[  Info   ] ");
            break;
        case LL_WARN :
            Console::Print(Console::YELLOW, "[  Warn   ] ");
            break;
        case LL_ERROR :
            Console::Print(Console::RED, "[  Error  ] ");
            break;
        case LL_FATAL :
            Console::Print(Console::RED, "[  Fatal  ] ");
            break;
        }

        Console::Print(Console::AQUA, logMessage.getContext().getContextName().c_str());
        Console::Print(" | %s\n", logMessage.getLogMessage());
        Console::Flush();
        m_logMutex.unlock();
    }
}

Add timestamp to console log output

Add timestamp to console log output

Print absolute system time in seconds as float with millisecond
precision

Change-Id: Ie81dcd0b2f9a1b38cbf6fb8965dc765535ea1c76


#include <cstdint>

#include <Magick++/Blob.h>
#include <Magick++/Image.h>

#include "utils.cc"

#define FUZZ_ENCODER_STRING_LITERAL_X(name) FUZZ_ENCODER_STRING_LITERAL(name)
#define FUZZ_ENCODER_STRING_LITERAL(name) #name
#ifndef FUZZ_ENCODER
#define FUZZ_ENCODER FUZZ_ENCODER_STRING_LITERAL_X(FUZZ_IMAGEMAGICK_ENCODER)
#endif

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  const Magick::Blob blob(Data, Size);
  Magick::Image image;
  image.magick(FUZZ_ENCODER);
  image.fileName(std::string(FUZZ_ENCODER) + ":");
  try {
    image.read(blob);
  }
  catch (Magick::Exception &e) {
    return 0;
  }

#if FUZZ_IMAGEMAGICK_ENCODER_WRITE || BUILD_MAIN

  Magick::Blob outBlob;
  try {
    image.write(&outBlob, FUZZ_ENCODER);
  }
  catch (Magick::Exception &e) {
  }
#endif
  return 0;
}

#include "travis.cc"

#include <cstdint>

#include <Magick++/Blob.h>
#include <Magick++/Image.h>

#include "utils.cc"

#define FUZZ_ENCODER_STRING_LITERAL_X(name) FUZZ_ENCODER_STRING_LITERAL(name)
#define FUZZ_ENCODER_STRING_LITERAL(name) #name
#ifndef FUZZ_ENCODER
#define FUZZ_ENCODER FUZZ_ENCODER_STRING_LITERAL_X(FUZZ_IMAGEMAGICK_ENCODER)
#endif

extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
  std::string encoder = FUZZ_ENCODER;
  // Due to macro foolishness, if we pass -DFUZZ_IMAGEMAGICK_ENCODER=NULL,
  // FUZZ_ENCODER ends up being "__null".
  if (encoder == "__null") {
    encoder = "NULL";
  }

  const Magick::Blob blob(Data, Size);
  Magick::Image image;
  image.magick(encoder);
  image.fileName(std::string(encoder) + ":");
  try {
    image.read(blob);
  }
  catch (Magick::Exception &e) {
    return 0;
  }

#if FUZZ_IMAGEMAGICK_ENCODER_WRITE || BUILD_MAIN

  Magick::Blob outBlob;
  try {
    image.write(&outBlob, encoder);
  }
  catch (Magick::Exception &e) {
  }
#endif
  return 0;
}

#include "travis.cc"

Handle the null encoder properly in the encoder fuzz

Credit OSS-Fuzz


#include <stdio.h>

#include "../excercise04/make_random_data/make_random_data.hpp"
#include "../excercise04/sort/quicksort.hpp"

int get_index_smallest(const int k, int *data, const int start, const int end)
{
    if(k < 0 || k > end) return -1; /* Base case */
    int p = partition(data, start, end);

    if(k == 0) return data[start];
    else if(p - start == k) return data[p];
    else if(p - start > k) return get_index_smallest(k, data, start, p - 1);
    else return get_index_smallest(k - p - 1, data, p + 1, end);
}

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

    const int size = 100000;
    int *data = make_random_data(size);
    printf("%d\n", get_index_smallest(k, data, 0, size - 1));

    free_random_data(data);
    return 0;
}

#include <stdio.h>

#include "../excercise04/make_random_data/make_random_data.hpp"
#include "../excercise04/sort/quicksort.hpp"

int quickselection(const int k, int *data, const int start, const int end)
{
    if(start >= end) return data[start];
    int pivot = partition(data, start, end);

    int p = pivot - start;
    if(p > k - 1) return quickselection(k, data, start, pivot - 1);
    if(p < k - 1) return quickselection(k - (p + 1), data, pivot + 1, end);
    return data[pivot];
}

int main(void)
{
    const int size = 100000;
    int *data = make_random_data(size);

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

    if(k <= 0 || k > size)
    {
        printf("Error: Out of range.\n");
        return 1;
    }

    printf("%d\n", quickselection(k, data, 0, size - 1));

    free_random_data(data);
    return 0;
}

Change the entire logic of Quickselect

Change the entire logic of Quickselect


/*
 *  Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "test/testsupport/perf_test_histogram_writer.h"

namespace webrtc {
namespace test {

PerfTestResultWriter* CreateHistogramWriter() {
  RTC_NOTREACHED() << "Cannot run perf tests with rtc_enable_protobuf = false. "
                      "Perf write results as protobufs.";
}

}  // namespace test
}  // namespace webrtc

/*
 *  Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "test/testsupport/perf_test_histogram_writer.h"

namespace webrtc {
namespace test {

PerfTestResultWriter* CreateHistogramWriter() {
  RTC_NOTREACHED() << "Cannot run perf tests with rtc_enable_protobuf = false. "
                      "Perf write results as protobufs.";
  return nullptr;
}

}  // namespace test
}  // namespace webrtc

Fix compile error when rtc_enable_protobuf is false

When configuring without protobuf this test fails to compile with the error:
perf_test_histogram_writer_no_protobuf.cc:20:1: error: non-void function does not return a value

Bug: None
Change-Id: I8e2676ee4b5284eac08e648fc43bdfc585fc5d64
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/182740
Reviewed-by: Taylor <f49cf6381e322b147053b74e4500af8533ac1e4c@webrtc.org>
Reviewed-by: Niels Moller <0057859e47d61d90529d0f66d9ef692cefedb46a@webrtc.org>
Commit-Queue: Taylor <f49cf6381e322b147053b74e4500af8533ac1e4c@webrtc.org>
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#32021}


#include "findTypeVariables.h"
#include "type.h"
#include "symbol.h"
#include "symtab.h"

FindVariableType::FindVariableType(Vec<VariableType*>* init_variableTypes) {
  variableTypes = init_variableTypes;
}

void FindVariableType::preProcessSymbol(Symbol* symbol) {
  if (dynamic_cast<TypeSymbol*>(symbol)) {
    forv_Vec(VariableType, variableType, *variableTypes) {
      if (variableType == symbol->type) {
        found = true;
      }
    }
  }
}

void FindVariableType::preProcessType(Type* type) {
  if (dynamic_cast<VariableType*>(type)) {
    forv_Vec(VariableType, variableType, *variableTypes) {
      if (variableType == type) {
        found = true;
      }
    }
  }
}

bool functionContainsVariableType(FnSymbol* fn,
                                  Vec<VariableType*>* variableTypes) {
  FindVariableType* traversal = new FindVariableType(variableTypes);
  TRAVERSE(fn, traversal, true);
  return traversal->found;
}

#include "findTypeVariables.h"
#include "type.h"
#include "symbol.h"
#include "symtab.h"

FindVariableType::FindVariableType(Vec<VariableType*>* init_variableTypes) {
  found = false;
  variableTypes = init_variableTypes;
}

void FindVariableType::preProcessSymbol(Symbol* symbol) {
  if (dynamic_cast<TypeSymbol*>(symbol)) {
    forv_Vec(VariableType, variableType, *variableTypes) {
      if (variableType == symbol->type) {
        found = true;
      }
    }
  }
}

void FindVariableType::preProcessType(Type* type) {
  if (dynamic_cast<VariableType*>(type)) {
    forv_Vec(VariableType, variableType, *variableTypes) {
      if (variableType == type) {
        found = true;
      }
    }
  }
}

bool functionContainsVariableType(FnSymbol* fn,
                                  Vec<VariableType*>* variableTypes) {
  FindVariableType* traversal = new FindVariableType(variableTypes);
  TRAVERSE(fn, traversal, true);
  return traversal->found;
}

Fix uninitialized variable which was causing valgrind failures.
(the "found" variable was not initialised to "false").

git-svn-id: 88467cb1fb04b8a755be7e1ee1026be4190196ef@3054 3a8e244f-b0f2-452b-bcba-4c88e055c3ca


#include "./SDACalculatePositions.h"

SDACalculatePositions::SDACalculatePositions(const char* name, const char* title,
               const char* in_file_suffix, const char* out_file_suffix, const double threshold,
	       const double positionCut)
: JPetCommonAnalysisModule( name, title, in_file_suffix, out_file_suffix), fCut(positionCut)
{
        fSelectedThreshold = threshold;
}

SDACalculatePositions::~SDACalculatePositions(){}

void SDACalculatePositions::begin()
{
}

void SDACalculatePositions::exec()
{
        fReader->getEntry(fEvent);

        JPetLOR& fLOR = dynamic_cast< JPetLOR& > ( fReader->getData() );

        JPetHit hit = fLOR.getFirstHit();
        hit.setPosAlongStrip( hit.getTimeDiff()/2.0 * 12.6/1000.0  );
        fLOR.setFirstHit( hit );

        hit = fLOR.getSecondHit();
        hit.setPosAlongStrip( hit.getTimeDiff()/2.0 * 12.6/1000.0  );
        fLOR.setSecondHit( hit );

	if( fLOR.getFirstHit().getPosAlongStrip() > fCut )
	{
	  fEvent++;
	  return;
	}

	fWriter->write(fLOR);

        fEvent++;
}

void SDACalculatePositions::end()
{
}

#include "./SDACalculatePositions.h"

SDACalculatePositions::SDACalculatePositions(const char* name, const char* title,
               const char* in_file_suffix, const char* out_file_suffix, const double threshold,
	       const double positionCut)
: JPetCommonAnalysisModule( name, title, in_file_suffix, out_file_suffix), fCut(positionCut)
{
        fSelectedThreshold = threshold;
}

SDACalculatePositions::~SDACalculatePositions(){}

void SDACalculatePositions::begin()
{
}

void SDACalculatePositions::exec()
{
        fReader->getEntry(fEvent);

        JPetLOR& fLOR = dynamic_cast< JPetLOR& > ( fReader->getData() );

        JPetHit hit = fLOR.getFirstHit();
        hit.setPosAlongStrip( hit.getTimeDiff()/2.0 * 12.6/1000.0  );
        fLOR.setFirstHit( hit );

        hit = fLOR.getSecondHit();
        hit.setPosAlongStrip( hit.getTimeDiff()/2.0 * 12.6/1000.0  );
        fLOR.setSecondHit( hit );

	if( fabs(fLOR.getFirstHit().getPosAlongStrip()) > fCut && fabs(fLOR.getSecondHit().getPosAlongStrip()) > fCut )
	{
	  fEvent++;
	  return;
	}

	fWriter->write(fLOR);

        fEvent++;
}

void SDACalculatePositions::end()
{
}

Add proper cut on position

Add proper cut on position


// 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-CHROMIUM file.

#include "browser/browser_main_parts.h"

#include "browser/browser_context.h"
#include "browser/web_ui_controller_factory.h"
#include "net/proxy/proxy_resolver_v8.h"

namespace brightray {

BrowserMainParts::BrowserMainParts() {
}

BrowserMainParts::~BrowserMainParts() {
}

void BrowserMainParts::PreMainMessageLoopRun() {
  browser_context_.reset(CreateBrowserContext());
  browser_context_->Initialize();

  web_ui_controller_factory_.reset(
      new WebUIControllerFactory(browser_context_.get()));
  content::WebUIControllerFactory::RegisterFactory(
      web_ui_controller_factory_.get());
}

void BrowserMainParts::PostMainMessageLoopRun() {
  browser_context_.reset();
}

int BrowserMainParts::PreCreateThreads() {
#if defined(OS_WIN)
  net::ProxyResolverV8::CreateIsolate();
#else
  net::ProxyResolverV8::RememberDefaultIsolate();
#endif
  return 0;
}

BrowserContext* BrowserMainParts::CreateBrowserContext() {
  return new BrowserContext;
}

}  // namespace brightray

// 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-CHROMIUM file.

#include "browser/browser_main_parts.h"

#include "browser/browser_context.h"
#include "browser/web_ui_controller_factory.h"
#include "net/proxy/proxy_resolver_v8.h"
#include "ui/gfx/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"

namespace brightray {

BrowserMainParts::BrowserMainParts() {
}

BrowserMainParts::~BrowserMainParts() {
}

void BrowserMainParts::PreMainMessageLoopRun() {
  browser_context_.reset(CreateBrowserContext());
  browser_context_->Initialize();

  web_ui_controller_factory_.reset(
      new WebUIControllerFactory(browser_context_.get()));
  content::WebUIControllerFactory::RegisterFactory(
      web_ui_controller_factory_.get());

#if defined(OS_WIN)
  gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, views::CreateDesktopScreen());
#endif
}

void BrowserMainParts::PostMainMessageLoopRun() {
  browser_context_.reset();
}

int BrowserMainParts::PreCreateThreads() {
#if defined(OS_WIN)
  net::ProxyResolverV8::CreateIsolate();
#else
  net::ProxyResolverV8::RememberDefaultIsolate();
#endif
  return 0;
}

BrowserContext* BrowserMainParts::CreateBrowserContext() {
  return new BrowserContext;
}

}  // namespace brightray

Set up a native screen on Windows

Set up a native screen on Windows

This is needed to prevent a crash inside aura::WindowTreeHost::InitCompositor.


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

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

// aligned allocation functions are not provided prior to macosx10.13
// XFAIL: availability=macosx10.12
// XFAIL: availability=macosx10.11
// XFAIL: availability=macosx10.10
// XFAIL: availability=macosx10.9
// XFAIL: availability=macosx10.8
// XFAIL: availability=macosx10.7

#include <new>

#ifdef _LIBCPP_HAS_NO_ALIGNED_ALLOCATION
#   error "libc++ should have aligned allocation in C++17 and up when targeting a platform that supports it"
#endif

int main() { }

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

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

// Aligned allocation functions are not provided prior to macosx10.13, but
// AppleClang <= 10 does not know about this restriction and always enables them.
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.12
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.11
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.10
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.9
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.8
// XFAIL: !(apple-clang-9 || apple-clang-10) && availability=macosx10.7

#include <new>

#ifdef _LIBCPP_HAS_NO_ALIGNED_ALLOCATION
#   error "libc++ should have aligned allocation in C++17 and up when targeting a platform that supports it"
#endif

int main() { }

[libcxx] Handle AppleClang 9 and 10 in XFAILs for aligned allocation tests

I forgot that those don't behave like Clang trunk, again.

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


#include "generator.h"

#include <iostream>
#include <fstream>

using namespace Mugen;

CharacterGenerator::CharacterGenerator(const std::string & filename):
filename(filename){
}

CharacterGenerator::~CharacterGenerator(){
}

void CharacterGenerator::output(const std::string & file){
    Mugen::PythonStream out;
    out.open(file);
    out << "import mugen" << PythonStream::endl;
    out <<  "class TestCharacter(mugen.Character):" << PythonStream::endl;
    out << PythonStream::indent;
    out << "def __init__(self):" << PythonStream::endl;
    out << PythonStream::indent;
    out << "self.setName('TestCharacter')" << PythonStream::endl;
    out.clearIndents();
    out << "char = TestCharacter()" << PythonStream::endl;
    out << "print char.name" << PythonStream::endl;
    out.close();
}

Indent code to more or less visualize the indentation of the outputed python code.

git-svn-id: 39e099a8ed5324aded674b764a67f7a08796d9a7@5819 662fdd30-d327-0410-a531-f549c87e1e9e


// Copyright 2019 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 "quic/masque/masque_utils.h"

namespace quic {

ParsedQuicVersionVector MasqueSupportedVersions() {
  QuicVersionInitializeSupportForIetfDraft();
  ParsedQuicVersion version = UnsupportedQuicVersion();
  for (const ParsedQuicVersion& vers : AllSupportedVersions()) {
    // Find the first version that supports IETF QUIC.
    if (vers.HasIetfQuicFrames() && vers.UsesTls()) {
      version = vers;
      break;
    }
  }
  QUICHE_CHECK(version.IsKnown());
  QuicEnableVersion(version);
  return {version};
}

QuicConfig MasqueEncapsulatedConfig() {
  QuicConfig config;
  config.SetMaxPacketSizeToSend(kMasqueMaxEncapsulatedPacketSize);
  return config;
}

std::string MasqueModeToString(MasqueMode masque_mode) {
  switch (masque_mode) {
    case MasqueMode::kInvalid:
      return "Invalid";
    case MasqueMode::kLegacy:
      return "Legacy";
    case MasqueMode::kOpen:
      return "Open";
  }
  return absl::StrCat("Unknown(", static_cast<int>(masque_mode), ")");
}

std::ostream& operator<<(std::ostream& os, const MasqueMode& masque_mode) {
  os << MasqueModeToString(masque_mode);
  return os;
}

}  // namespace quic

// Copyright 2019 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 "quic/masque/masque_utils.h"

namespace quic {

ParsedQuicVersionVector MasqueSupportedVersions() {
  QuicVersionInitializeSupportForIetfDraft();
  ParsedQuicVersionVector versions;
  for (const ParsedQuicVersion& version : AllSupportedVersions()) {
    // Use all versions that support IETF QUIC.
    if (version.UsesHttp3()) {
      QuicEnableVersion(version);
      versions.push_back(version);
    }
  }
  QUICHE_CHECK(!versions.empty());
  return versions;
}

QuicConfig MasqueEncapsulatedConfig() {
  QuicConfig config;
  config.SetMaxPacketSizeToSend(kMasqueMaxEncapsulatedPacketSize);
  return config;
}

std::string MasqueModeToString(MasqueMode masque_mode) {
  switch (masque_mode) {
    case MasqueMode::kInvalid:
      return "Invalid";
    case MasqueMode::kLegacy:
      return "Legacy";
    case MasqueMode::kOpen:
      return "Open";
  }
  return absl::StrCat("Unknown(", static_cast<int>(masque_mode), ")");
}

std::ostream& operator<<(std::ostream& os, const MasqueMode& masque_mode) {
  os << MasqueModeToString(masque_mode);
  return os;
}

}  // namespace quic

Support all HTTP/3 versions in MASQUE

Support all HTTP/3 versions in MASQUE

This means we'll use h3,h3-29 instead of just h3, and
that'll help simplify IETF MASQUE interop events.
This code is not used in production.

PiperOrigin-RevId: 360223566
Change-Id: I519f6785e130075cb1ed75fcc45f0b3160f3c1b2


// RUN: %clang_cc1 -pedantic -fixit %s -o - | %clang_cc1 -fsyntax-only -pedantic -Werror -x c++ -

/* This is a test of the various code modification hints that are
   provided as part of warning or extension diagnostics. All of the
   warnings will be fixed by -fixit, and the resulting file should
   compile cleanly with -Werror -pedantic. */

struct C1 {
  virtual void f();
  static void g();
};
struct C2 : virtual public virtual C1 { }; // expected-error{{duplicate}}

virtual void C1::f() { } // expected-error{{'virtual' can only be specified inside the class definition}}

static void C1::g() { } // expected-error{{'static' can only be specified inside the class definition}}

template<int Value> struct CT { }; // expected-note{{previous use is here}}

CT<10 >> 2> ct; // expected-warning{{require parentheses}}

class C3 {
public:
  C3(C3, int i = 0); // expected-error{{copy constructor must pass its first argument by reference}}
};

struct CT<0> { }; // expected-error{{'template<>'}}

template<> class CT<1> { }; // expected-error{{tag type}}

// PR5444
namespace PR5444 {
  void foo(int x, int y = 0);
  void foo(int x, int y = 0) { }

  void foo(int  = 0);
  void foo(int  = 0) { }
}

// RUN: %clang_cc1 -pedantic -Wall -fixit %s -o - | %clang_cc1 -fsyntax-only -pedantic -Wall -Werror -x c++ -

/* This is a test of the various code modification hints that are
   provided as part of warning or extension diagnostics. All of the
   warnings will be fixed by -fixit, and the resulting file should
   compile cleanly with -Werror -pedantic. */

struct C1 {
  virtual void f();
  static void g();
};
struct C2 : virtual public virtual C1 { }; // expected-error{{duplicate}}

virtual void C1::f() { } // expected-error{{'virtual' can only be specified inside the class definition}}

static void C1::g() { } // expected-error{{'static' can only be specified inside the class definition}}

template<int Value> struct CT { }; // expected-note{{previous use is here}}

CT<10 >> 2> ct; // expected-warning{{require parentheses}}

class C3 {
public:
  C3(C3, int i = 0); // expected-error{{copy constructor must pass its first argument by reference}}
};

struct CT<0> { }; // expected-error{{'template<>'}}

template<> class CT<1> { }; // expected-error{{tag type}}

// Access declarations
class A {
protected:
  int foo();
};

class B : public A {
  A::foo; // expected-warning{{access declarations are deprecated}}
};

Make this fix-it test case actually fail when there is a problem; add
a test for access declarations and remove a (broken) test for removal
of default arguments.

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


#include<ros/ros.h>
#include<ics3/ics>
#include<servo_msgs/IdBased.h>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  result.id = msg->id;
  try {
    result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    pub.publish(result);
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle n {};
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ics::ICS3 ics {path.c_str()};
  driver = &ics;
  ros::Subscriber sub = n.subscribe("cmd_krs", 100, move);
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

#include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  result.id = msg->id;
  try {
    result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    pub.publish(result);
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

Update servo_krs for runtime speed

Update servo_krs for runtime speed

あと使う時に変数を宣言しろの教えの通り、NodeHandleの宣言を遅らせた
ぶっちゃけ短すぎて最適化する余地がなくて悲しみ。


// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WatermarkDataFactory.h"

namespace ExampleApp
{
    namespace Watermark
    {
        namespace View
        {
            WatermarkDataFactory::WatermarkDataFactory(const std::string& appName,
                                                       const std::string& googleAnalyticsReferrerToken)
            : m_appName(appName)
            , m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken)
            {

            }

            WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl,
                                                       const std::string& popupTitle,
                                                       const std::string& popupBody,
                                                       const std::string& webUrl,
                                                       const bool shouldShowShadow)
            {
                return WatermarkData(imageAssetUrl,
                                     popupTitle,
                                     popupBody,
                                     webUrl,
                                     shouldShowShadow);
            }

            WatermarkData WatermarkDataFactory::CreateDefaultEegeo()
            {
                std::string imageAssetName = "eegeo_logo";
                std::string popupTitle = "Maps by eeGeo";
                std::string popupBody = "The " + m_appName + " app is open source. It's built using the eeGeo maps SDK, a cross platform API for building engaging, customizable apps.";
                std::string webUrl = "http://eegeo.com/?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo";

                return Create(imageAssetName,
                              popupTitle,
                              popupBody,
                              webUrl);
            }
        }
    }
}

// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WatermarkDataFactory.h"

namespace ExampleApp
{
    namespace Watermark
    {
        namespace View
        {
            WatermarkDataFactory::WatermarkDataFactory(const std::string& appName,
                                                       const std::string& googleAnalyticsReferrerToken)
            : m_appName(appName)
            , m_googleAnalyticsReferrerToken(googleAnalyticsReferrerToken)
            {

            }

            WatermarkData WatermarkDataFactory::Create(const std::string& imageAssetUrl,
                                                       const std::string& popupTitle,
                                                       const std::string& popupBody,
                                                       const std::string& webUrl,
                                                       const bool shouldShowShadow)
            {
                return WatermarkData(imageAssetUrl,
                                     popupTitle,
                                     popupBody,
                                     webUrl,
                                     shouldShowShadow);
            }

            WatermarkData WatermarkDataFactory::CreateDefaultEegeo()
            {
                std::string imageAssetName = "eegeo_logo";
                std::string popupTitle = "Maps by eeGeo";
                std::string popupBody = "This app is open source. It's built using the eeGeo maps SDK, a cross platform API for building engaging, customizable apps.";
                std::string webUrl = "http://eegeo.com/?utm_source=" + m_googleAnalyticsReferrerToken + "&utm_medium=referral&utm_campaign=eegeo";

                return Create(imageAssetName,
                              popupTitle,
                              popupBody,
                              webUrl);
            }
        }
    }
}

Fix for MPLY-7058. Buddy: Paul

Fix for MPLY-7058. Buddy: Paul


// 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<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  try {
    result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    result.id = msg->id;
    pub.publish(result);
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

#include<ros/ros.h>
#include<servo_msgs/IdBased.h>
#include<ics3/ics>

ics::ICS3* driver {nullptr};
ros::Publisher pub;

void move(const servo_msgs::IdBased::ConstPtr& msg) {
  servo_msgs::IdBased result;
  try {
    result.angle = driver->move(msg->id, ics::Angle::newDegree(msg->angle));
    result.id = msg->id;
    pub.publish(result);
  } catch (std::runtime_error e) {
    ROS_INFO("Communicate error: %s", e.what());
  }
}

int main(int argc, char** argv) {
  ros::init(argc, argv, "servo_krs_node");
  ros::NodeHandle pn {"~"};
  std::string path {"/dev/ttyUSB0"};
  pn.param<std::string>("path", path, path);
  ROS_INFO("Open servo motor path: %s", path.c_str());
  ics::ICS3 ics {std::move(path)};
  driver = &ics;
  ros::NodeHandle n {};
  ros::Subscriber sub {n.subscribe("cmd_krs", 100, move)};
  pub = n.advertise<servo_msgs::IdBased>("pose_krs", 10);
  ros::spin();
  return 0;
}

Add message of reading path

Add message of reading path


/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */

#include <kroll/kroll.h>
#include "../app_binding.h"

namespace ti
{

void AppBinding::Restart(const ValueList& args, KValueRef result)
{
	Host* host = Host::GetInstance();
	std::string cmdline(host->GetApplication()->arguments.at(0));

	// Remove all quotes.
	size_t i = cmdline.find('\"');
	while (i != std::string::npos)
	{
		cmdline.replace(i, 1, "");
		i = cmdline.find('\"');
	}

	std::string script = "\"" + cmdline + "\" &";
	system(script.c_str());

	host->Exit(0);
}

}

/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
 */

#include <kroll/kroll.h>
#include "../app_binding.h"

namespace ti
{

void AppBinding::Restart(const ValueList& args, KValueRef result)
{
	Host* host = Host::GetInstance();
	std::string cmdline(host->GetApplication()->arguments.at(0));

	// Remove all quotes.
	size_t i = cmdline.find('\"');
	while (i != std::string::npos)
	{
		cmdline.replace(i, 1, "");
		i = cmdline.find('\"');
	}

	std::string script = "\"" + cmdline + "\" &";
	if (system(script.c_str()) == -1)
		throw ValueException::FromString("Failed to start new process.");

	host->Exit(0);
}

}

Throw an exception when App.restart fails on Linux.


#include <wangle/client/persistence/test/TestUtil.h>

namespace wangle {

std::string getPersistentCacheFilename() {
  char filename[] = "/tmp/fbtls.XXXXXX";
  int fd = mkstemp(filename);
  close(fd);
  EXPECT_TRUE(unlink(filename) != -1);
  return std::string(filename);
}

}

/*
 *  Copyright (c) 2016, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */
#include <wangle/client/persistence/test/TestUtil.h>

#include <folly/experimental/TestUtil.h>

namespace wangle {

std::string getPersistentCacheFilename() {
  folly::test::TemporaryFile file("fbtls");
  return file.path().string();
}

}

Handle tmp dir on Android

Handle tmp dir on Android

Summary:
There is no universally accessible tmpdir on Android which
means mkstemp fails. This diff calls a function that the test runner
should provide to fill a valid temporary directory.

Reviewed By: yangchi

Differential Revision: D2842034

fb-gh-sync-id: 186c931ddf4424cb482c8fbd728ae37877017685


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

#include <pthread.h>

#include "base/logging.h"

namespace base {

// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
  int error = pthread_key_create(&slot, NULL);
  CHECK(error == 0);
}

// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
  int error = pthread_key_delete(slot);
  DCHECK(error == 0);
}

// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
  return pthread_getspecific(slot_);
}

// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
  int error = pthread_setspecific(slot, value);
  CHECK(error == 0);
}

}  // namespace base

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

#include <pthread.h>

#include "base/logging.h"

namespace base {

// static
void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
  int error = pthread_key_create(&slot, NULL);
  CHECK(error == 0);
}

// static
void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
  int error = pthread_key_delete(slot);
  DCHECK(error == 0);
}

// static
void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
  return pthread_getspecific(slot);
}

// static
void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
  int error = pthread_setspecific(slot, value);
  CHECK(error == 0);
}

}  // namespace base

Fix a typo that broke the posix build.

Fix a typo that broke the posix build.

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


#include <kernel/rng.hpp>
#include <kernel/cpuid.hpp>
#include <kernel/os.hpp>
#include <arch.hpp>
#include <kprint>
extern "C" void intel_rdrand(uint64_t*);
extern "C" void intel_rdseed(uint64_t*);

static void fallback_entropy(uint64_t* res)
{
  uint64_t clock = (uint64_t) res;
  // this is horrible, better solution needed here
  for (int i = 0; i < 64; ++i) {
    clock += OS::cycles_since_boot();
    asm volatile("cpuid" ::: "memory", "eax", "ebx", "ecx", "edx");
  }
  // here we need to add our own bits
  *res = clock;
}

// used to generate initial
// entropy for a cryptographic randomness generator
void RNG::init()
{
  if (CPUID::has_feature(CPUID::Feature::RDSEED)) {
    rng_reseed_init(intel_rdseed, 2);
  }
  else if (CPUID::has_feature(CPUID::Feature::RDRAND)) {
    rng_reseed_init(intel_rdrand, 65);
  }
  else {
    rng_reseed_init(fallback_entropy, 64*16);
    return;
  }
  assert(0 && "No randomness fallback");
}

#include <kernel/rng.hpp>
#include <kernel/cpuid.hpp>
#include <kernel/os.hpp>
#include <arch.hpp>
#include <kprint>
extern "C" void intel_rdrand(uint64_t*);
extern "C" void intel_rdseed(uint64_t*);

static void fallback_entropy(uint64_t* res)
{
  uint64_t clock = (uint64_t) res;
  // this is horrible, better solution needed here
  for (int i = 0; i < 64; ++i) {
    clock += OS::cycles_since_boot();
    asm volatile("cpuid" ::: "memory", "eax", "ebx", "ecx", "edx");
  }
  // here we need to add our own bits
  *res = clock;
}

// used to generate initial
// entropy for a cryptographic randomness generator
void RNG::init()
{
  if (CPUID::has_feature(CPUID::Feature::RDSEED)) {
    rng_reseed_init(intel_rdseed, 2);
    return;
  }
  else if (CPUID::has_feature(CPUID::Feature::RDRAND)) {
    rng_reseed_init(intel_rdrand, 65);
    return;
  }
#ifndef PLATFORM_x86_solo5
  rng_reseed_init(fallback_entropy, 64*16);
  return;
#endif
  assert(0 && "No randomness fallback");
}

x86: Add missing returns in RNG init, and fail avoid TSC with solo5


// RUN: clang -fsyntax-only -verify %s
namespace A { // expected-error {{error: previous definition is here}}
  int A;
  void f() { A = 0; }
}

void f() { A = 0; } // expected-error {{error: unexpected namespace name 'A': expected expression}}
int A; // expected-error {{error: redefinition of 'A' as different kind of symbol}}
class A; // expected-error {{error: redefinition of 'A' as different kind of symbol}}

class B; // expected-error {{error: previous definition is here}}
namespace B {} // expected-error {{error: redefinition of 'B' as different kind of symbol}}

void C(); // expected-error {{error: previous definition is here}}
namespace C {} // expected-error {{error: redefinition of 'C' as different kind of symbol}}

Convert CFLF to LF.  CRLF was causing this test to fail under Mac OS X.

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


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

TEST(GetUserName,simple)
{
	// allocate a WCHAR_T buffer to receive username
	DWORD lpnSize = 64;
	WCHAR_T lpBuffer[lpnSize];

	BOOL result = GetUserName(lpBuffer, &lpnSize);

	// GetUserName returns 1 on success
	ASSERT_EQ(1, result);

	// get expected username
	const char *username = getlogin();

	// GetUserName sets lpnSize to length of username including null
	ASSERT_EQ(strlen(username)+1, lpnSize);

	// TODO: ASSERT_STREQ(username, Utf16leToUtf8(lpBuffer))
}

#include <string>
#include <vector>
#include <unistd.h>
#include <gtest/gtest.h>
#include <scxcorelib/scxstrencodingconv.h>
#include "getusername.h"

using std::string;
using std::vector;
using SCXCoreLib::Utf16leToUtf8;

TEST(GetUserName,simple)
{
	// allocate a WCHAR_T buffer to receive username
	DWORD lpnSize = 64;
	WCHAR_T lpBuffer[lpnSize];

	BOOL result = GetUserName(lpBuffer, &lpnSize);

	// GetUserName returns 1 on success
	ASSERT_EQ(1, result);

	// get expected username
	string username = string(getlogin());

	// GetUserName sets lpnSize to length of username including null
	ASSERT_EQ(username.size()+1, lpnSize);

	// copy UTF-16 bytes from lpBuffer to vector for conversion
	vector<unsigned char> input(reinterpret_cast<unsigned char *>(&lpBuffer[0]),
	                            reinterpret_cast<unsigned char *>(&lpBuffer[lpnSize-1]));
	// convert to UTF-8 for assertion
	string output;
	Utf16leToUtf8(input, output);

	EXPECT_EQ(username, output);
}

Test UTF-16 output of GetUserName

Test UTF-16 output of GetUserName


//===-- ubsan_init_standalone.cc ------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Initialization of standalone UBSan runtime.
//
//===----------------------------------------------------------------------===//

#include "ubsan_platform.h"
#if !CAN_SANITIZE_UB
# error "UBSan is not supported on this platform!"
#endif

#include "ubsan_init.h"

#if SANITIZER_CAN_USE_PREINIT_ARRAY
__attribute__((section(".preinit_array"), used))
void (*__local_ubsan_preinit)(void) = __ubsan::InitAsStandalone;
#else
// Use a dynamic initializer.
class UbsanStandaloneInitializer {
 public:
  UbsanStandaloneInitializer() {
    __ubsan::InitAsStandalone();
  }
};
static UbsanStandaloneInitializer ubsan_standalone_initializer;
#endif  // SANITIZER_CAN_USE_PREINIT_ARRAY

//===-- ubsan_init_standalone.cc ------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Initialization of standalone UBSan runtime.
//
//===----------------------------------------------------------------------===//

#include "ubsan_platform.h"
#if !CAN_SANITIZE_UB
# error "UBSan is not supported on this platform!"
#endif

#include "sanitizer_common/sanitizer_internal_defs.h"
#include "ubsan_init.h"

#if SANITIZER_CAN_USE_PREINIT_ARRAY
__attribute__((section(".preinit_array"), used))
void (*__local_ubsan_preinit)(void) = __ubsan::InitAsStandalone;
#else
// Use a dynamic initializer.
class UbsanStandaloneInitializer {
 public:
  UbsanStandaloneInitializer() {
    __ubsan::InitAsStandalone();
  }
};
static UbsanStandaloneInitializer ubsan_standalone_initializer;
#endif  // SANITIZER_CAN_USE_PREINIT_ARRAY

[UBSan] Add missing header that defines SANITIZER_CAN_USE_PREINIT_ARRAY

Otherwise this compile definition was undefined, and .preinit_array
was never used on the platforms that support it.

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


#include "binary_threshold.h"

namespace TooManyPeeps {

  BinaryThreshold::BinaryThreshold(const cv::Mat& original, cv::Mat& result, int threshold)
    : ProcessFilter(original, result) {
    this->threshold = threshold;
  }

  BinaryThreshold::BinaryThreshold(cv::Mat& image, int threshold)
    : BinaryThreshold(original, result, threshold) {
  }

  void BinaryThreshold::execute(void) {
    cv::threshold(get_original(), get_result(), threshold, MAX_OUTPUT_VALUE, cv::THRESH_BINARY);
  }

};

#include "binary_threshold.h"

namespace TooManyPeeps {

  BinaryThreshold::BinaryThreshold(const cv::Mat& original, cv::Mat& result, int threshold)
    : ProcessFilter(original, result) {
    this->threshold = threshold;
  }

  BinaryThreshold::BinaryThreshold(cv::Mat& image, int threshold)
    : BinaryThreshold(image, image, threshold) {
  }

  void BinaryThreshold::execute(void) {
    cv::threshold(get_original(), get_result(), threshold, MAX_OUTPUT_VALUE, cv::THRESH_BINARY);
  }

};

Fix wrong constructor argument in binary thresh


/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009, 2010 Appcelerator, Inc. All Rights Reserved.
 */

#include "../network_status.h"
#include <SystemConfiguration/SCNetworkReachability.h>

namespace ti
{

void NetworkStatus::InitializeLoop()
{
}

void NetworkStatus::CleanupLoop()
{
}

bool NetworkStatus::GetStatus()
{
	static SCNetworkReachabilityRef primaryTarget =
		SCNetworkReachabilityCreateWithName(0, "www.google.com");
	if (!primaryTarget)
		return true;

	SCNetworkConnectionFlags flags;
	SCNetworkReachabilityGetFlags(primaryTarget, &flags);
	if ((flags & kSCNetworkFlagsReachable) &&
		!(flags & kSCNetworkFlagsConnectionRequired))
		return true;

	static SCNetworkReachabilityRef secondaryTarget =
		SCNetworkReachabilityCreateWithName(0, "www.yahoo.com");
	if (!secondaryTarget)
		return true;

	SCNetworkReachabilityGetFlags(secondaryTarget, &flags);
	if ((flags & kSCNetworkFlagsReachable) &&
		!(flags & kSCNetworkFlagsConnectionRequired))
		return true;

	return false;
}

}

/**
 * Appcelerator Titanium - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2009, 2010 Appcelerator, Inc. All Rights Reserved.
 */

#include "../network_status.h"
#include <SystemConfiguration/SCNetworkReachability.h>

namespace ti
{

static SCNetworkReachabilityRef primaryTarget = 0;
static SCNetworkReachabilityRef secondaryTarget = 0;

void NetworkStatus::InitializeLoop()
{
	primaryTarget = SCNetworkReachabilityCreateWithName(0, "www.google.com");
	secondaryTarget = SCNetworkReachabilityCreateWithName(0, "www.yahoo.com");
}

void NetworkStatus::CleanupLoop()
{
	if (primaryTarget)
		CFRelease(primaryTarget);
	if (secondaryTarget)
		CFRelease(secondaryTarget);
}

bool NetworkStatus::GetStatus()
{
	if (!primaryTarget)
		return true;

	SCNetworkConnectionFlags flags;
	SCNetworkReachabilityGetFlags(primaryTarget, &flags);
	if ((flags & kSCNetworkFlagsReachable) &&
		!(flags & kSCNetworkFlagsConnectionRequired))
		return true;

	if (!secondaryTarget)
		return true;

	SCNetworkReachabilityGetFlags(secondaryTarget, &flags);
	if ((flags & kSCNetworkFlagsReachable) &&
		!(flags & kSCNetworkFlagsConnectionRequired))
		return true;

	return false;
}

}

Clean up allocated memory during shutdown in OS X NetworkStatus.


// 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-CHROMIUM file.

#include "common/content_client.h"

#include "common/application_info.h"

#include "base/stringprintf.h"
#include "base/string_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/user_agent/user_agent_util.h"

namespace brightray {

ContentClient::ContentClient() {
}

ContentClient::~ContentClient() {
}

std::string ContentClient::GetProduct() const {
  auto name = GetApplicationName();
  RemoveChars(name, kWhitespaceASCII, &name);
  return base::StringPrintf("%s/%s", name.c_str(), GetApplicationVersion().c_str());
}

std::string ContentClient::GetUserAgent() const {
  return webkit_glue::BuildUserAgentFromProduct(GetProduct());
}

base::StringPiece ContentClient::GetDataResource(int resource_id, ui::ScaleFactor scale_factor) const {
  return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(resource_id, scale_factor);
}

gfx::Image& ContentClient::GetNativeImageNamed(int resource_id) const {
  return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
}

}

// 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-CHROMIUM file.

#include "common/content_client.h"

#include "common/application_info.h"

#include "base/stringprintf.h"
#include "base/string_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/common/user_agent/user_agent_util.h"

namespace brightray {

ContentClient::ContentClient() {
}

ContentClient::~ContentClient() {
}

std::string ContentClient::GetProduct() const {
  auto name = GetApplicationName();
  RemoveChars(name, kWhitespaceASCII, &name);
  return base::StringPrintf("%s/%s", name.c_str(), GetApplicationVersion().c_str());
}

std::string ContentClient::GetUserAgent() const {
  return webkit_glue::BuildUserAgentFromProduct(GetProduct());
}

base::StringPiece ContentClient::GetDataResource(int resource_id, ui::ScaleFactor scale_factor) const {
  return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale(resource_id, scale_factor);
}

gfx::Image& ContentClient::GetNativeImageNamed(int resource_id) const {
  return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id);
}

}

Update for webkit header moves

Update for webkit header moves


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

#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"

PrintPreviewUI::PrintPreviewUI(TabContents* contents)
    : WebUI(contents),
      html_source_(new PrintPreviewUIHTMLSource()) {
  // PrintPreviewUI owns |handler|.
  PrintPreviewHandler* handler = new PrintPreviewHandler();
  AddMessageHandler(handler->Attach(this));

  // Set up the chrome://print/ source.
  contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_);
}

PrintPreviewUI::~PrintPreviewUI() {
}

PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() {
  return html_source_.get();
}

void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) {
  FundamentalValue pages_count(expected_pages_count);
  CallJavascriptFunction("createPDFPlugin", pages_count);
}

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

#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/print_preview_handler.h"
#include "chrome/browser/ui/webui/print_preview_ui_html_source.h"
#include "content/browser/browser_thread.h"
#include "content/browser/tab_contents/tab_contents.h"

PrintPreviewUI::PrintPreviewUI(TabContents* contents)
    : WebUI(contents),
      html_source_(new PrintPreviewUIHTMLSource()) {
  // PrintPreviewUI owns |handler|.
  PrintPreviewHandler* handler = new PrintPreviewHandler();
  AddMessageHandler(handler->Attach(this));

  // Set up the chrome://print/ source.
  contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_);
}

PrintPreviewUI::~PrintPreviewUI() {
}

PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() {
  return html_source_.get();
}

void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) {
  FundamentalValue pages_count(expected_pages_count);
  CallJavascriptFunction("updatePrintPreview", pages_count);
}

Print Preview: Fix typo from r78639.

Print Preview: Fix typo from r78639.

BUG=76707
TEST=page count initialized correctly in print preview.
R=arv@chromium.org
Review URL: http://codereview.chromium.org/6688041

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


#include <patlms/util/remove_file.h>
#include <patlms/util/detail/cant_remove_file_exception.h>

#include <string>
#include <cstring>
#include <cerrno>
#include <boost/log/trivial.hpp>

using namespace std;

namespace util
{

void RemoveFile(const std::string &path, detail::SystemInterfacePtr system) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::util::RemovePidFile: Function call with (path=" << path << ")";

  int ret = system->unlink(path.c_str());
  if (ret < 0) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::util::RemovePidFile: Couldn't remove pid file: " << strerror(errno);
    throw detail::CantRemoveFileException();
  }

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::util::RemovePidFile: Done";
}

}

#include <patlms/util/remove_file.h>
#include <patlms/util/detail/cant_remove_file_exception.h>

#include <string>
#include <cstring>
#include <cerrno>
#include <boost/log/trivial.hpp>

using namespace std;

namespace util
{

void RemoveFile(const std::string &path, detail::SystemInterfacePtr system) {
  BOOST_LOG_TRIVIAL(debug) << "libpatlms::util::RemoveFile: Function call with (path=" << path << ")";

  int ret = system->unlink(path.c_str());
  if (ret < 0) {
    BOOST_LOG_TRIVIAL(error) << "libpatlms::util::RemoveFile: Couldn't remove file: " << strerror(errno);
    throw detail::CantRemoveFileException();
  }

  BOOST_LOG_TRIVIAL(debug) << "libpatlms::util::RemoveFile: Done";
}

}

Fix debug messages in library when removing file


// This file is part of MorphoDiTa <http://github.com/ufal/morphodita/>.
//
// Copyright 2016 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// 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 "generic_tokenizer.h"
#include "generic_tokenizer_factory.h"

namespace ufal {
namespace morphodita {

tokenizer* generic_tokenizer_factory::new_tokenizer() const {
  return new generic_tokenizer(version);
}

bool generic_tokenizer_factory::load(istream& is) {
  version = is.get();

  return is;
}

} // namespace morphodita
} // namespace ufal

// This file is part of MorphoDiTa <http://github.com/ufal/morphodita/>.
//
// Copyright 2016 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// 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 "generic_tokenizer.h"
#include "generic_tokenizer_factory.h"

namespace ufal {
namespace morphodita {

tokenizer* generic_tokenizer_factory::new_tokenizer() const {
  return new generic_tokenizer(version);
}

bool generic_tokenizer_factory::load(istream& is) {
  version = is.get();

  return bool(is);
}

} // namespace morphodita
} // namespace ufal

Add explicit conversion to bool.

Add explicit conversion to bool.

Required by standard and g++ 5.0.


#include "impl_send_posture.hpp"

#include "servo_msgs/KrsServoDegree.h"

std::map<std::string, const SendPosture*> SendPostureFactory::sends;

const SendPosture* SendPostureFactory::get(const std::string& name, ros::NodeHandle& nh) {
  std::map<std::string, const SendPosture*>::const_iterator found_it = sends.find(name);
  if (found_it != sends.end()) return create(name, nh);
  return found_it->second;
}

const SendPosture* SendPostureFactory::create(const std::string& name, ros::NodeHandle& nh) {
  if (name == "krs") {
    sends["krs"] = new KrsSendPosture(nh);
    return sends.at("krs");
  }
  return NULL;
}

KrsSendPosture::KrsSendPosture(ros::NodeHandle& nh) : nh(nh) {
  pub = nh.advertise<servo_msgs::KrsServoDegree>("cmd_krs", 16);
  nh.getParam("id_vec", id_vec);
}

void KrsSendPosture::sendPosture(std::vector<double>& posture) {

}

#include "impl_send_posture.hpp"

#include "algorithm"

#include "servo_msgs/KrsServoDegree.h"

std::map<std::string, const SendPosture*> SendPostureFactory::sends;

const SendPosture* SendPostureFactory::get(const std::string& name, ros::NodeHandle& nh) {
  std::map<std::string, const SendPosture*>::const_iterator found_it = sends.find(name);
  if (found_it != sends.end()) return create(name, nh);
  return found_it->second;
}

const SendPosture* SendPostureFactory::create(const std::string& name, ros::NodeHandle& nh) {
  if (name == "krs") {
    sends["krs"] = new KrsSendPosture(nh);
    return sends.at("krs");
  }
  return NULL;
}

KrsSendPosture::KrsSendPosture(ros::NodeHandle& nh) : nh(nh) {
  pub = nh.advertise<servo_msgs::KrsServoDegree>("cmd_krs", 16);
  nh.getParam("id_vec", id_vec);
}

void KrsSendPosture::sendPosture(std::vector<double>& posture) {
  servo_msgs::KrsServoDegree msg;
  std::vector<double>::size_type length = std::min(posture.size(), id_vec.size());
  for (std::vector<double>::size_type i = 0; i < length; i++) {
    msg.id = id_vec[i];
    msg.angle = posture[i];
    pub.publish(msg);
  }
}

Implement krs send posture method.

Implement krs send posture method.


#include "reg_language_translator.h"
#include "orz/types.h"

namespace Reg {
	namespace Internal {
		// TODO: Centralize (de)serialization the same way as for keyboard events

		boost::optional<LanguageTranslator::external_type> LanguageTranslator::get_value(internal_type const sval) {
			if (sval == "English") {
				return Intl::Language::English;
			}
			if (sval == "Swedish") {
				return Intl::Language::Swedish;
			}
			auto val = FromAString<int>(sval);
			if (val == 0) return Intl::Language::English;
			if (val == 1) return Intl::Language::Swedish;
			return boost::none;
		}

		boost::optional<LanguageTranslator::internal_type> LanguageTranslator::put_value(external_type const& val) {
			if (val == Intl::Language::English) {
				return "English";
			}
			if (val == Intl::Language::Swedish) {
				return "Swedish";
			}
			return boost::none;
		}
	}
}

#include "reg_language_translator.h"
#include "orz/types.h"

namespace Reg {
	namespace Internal {
		// TODO: Centralize (de)serialization the same way as for keyboard events

		boost::optional<LanguageTranslator::external_type> LanguageTranslator::get_value(internal_type const sval) {
			if (sval == "English") {
				return Intl::Language::English;
			}
			if (sval == "Swedish") {
				return Intl::Language::Swedish;
			}
			auto val = FromAString<int>(sval);
			if (val == 0) return Intl::Language::English;
			if (val == 1) return Intl::Language::Swedish;
			return boost::none;
		}

		boost::optional<LanguageTranslator::internal_type> LanguageTranslator::put_value(external_type const& val) {
			if (val == Intl::Language::English) {
				return std::string("English");
			}
			if (val == Intl::Language::Swedish) {
				return std::string("Swedish");
			}
			return boost::none;
		}
	}
}

Fix compile errors on Linux

Fix compile errors on Linux


#include "./mesh_node.h"
#include <string>
#include "./graphics/gl.h"

MeshNode::MeshNode(std::string assetFilename, int meshIndex,
                   std::shared_ptr<Graphics::Mesh> mesh,
                   Eigen::Matrix4f transformation)
  : assetFilename(assetFilename), meshIndex(meshIndex), mesh(mesh),
    transformation(transformation)
{
  obb = mesh->obb * transformation;
}

MeshNode::~MeshNode()
{
}

void MeshNode::render(Graphics::Gl *gl,
                      std::shared_ptr<Graphics::Managers> managers,
                      RenderData renderData)
{
  if (!isVisible)
    return;

  renderData.modelMatrix = transformation;
  mesh->render(gl, managers, renderData);
}

Eigen::Matrix4f MeshNode::getTransformation()
{
  return this->transformation;
}

void MeshNode::setTransformation(Eigen::Matrix4f transformation)
{
  this->transformation = transformation;
}

#include "./mesh_node.h"
#include <string>
#include "./graphics/gl.h"

MeshNode::MeshNode(std::string assetFilename, int meshIndex,
                   std::shared_ptr<Graphics::Mesh> mesh,
                   Eigen::Matrix4f transformation)
  : assetFilename(assetFilename), meshIndex(meshIndex), mesh(mesh),
    transformation(transformation)
{
  obb = mesh->obb * transformation;
}

MeshNode::~MeshNode()
{
}

void MeshNode::render(Graphics::Gl *gl,
                      std::shared_ptr<Graphics::Managers> managers,
                      RenderData renderData)
{
  if (!isVisible)
    return;

  renderData.modelMatrix = transformation;
  mesh->render(gl, managers, renderData);
}

Eigen::Matrix4f MeshNode::getTransformation()
{
  return this->transformation;
}

void MeshNode::setTransformation(Eigen::Matrix4f transformation)
{
  this->transformation = transformation;
  obb = mesh->obb * transformation;
}

Update bounding box in MeshNode::setTransformation.


#include <fstream>
#include <iostream>
#include "person.pb.h"
//#include "../pb2json.h"
#include <pb2json.h>

using namespace std;

int main(int argc,char *argv[])
{
 	// Test 1: read binary PB from a file and convert it to JSON
	ifstream fin("dump",ios::binary);
	fin.seekg(0,ios_base::end);
	size_t len = fin.tellg();
	fin.seekg(0,ios_base::beg);
	char *buf = new char [len];

	fin.read(buf,len);
	google::protobuf::Message *p = new Person();
	char *json = pb2json(p,buf,len);
	cout<<json<<endl;
	free(json);
	delete p;

	// Test 2: convert PB to JSON directly
	Person p2;
	char *json2 = pb2json(p2);
	cout<<json2<<endl;
	free(json2);

	return 0;
}

#include <fstream>
#include <iostream>
#include "person.pb.h"
//#include "../pb2json.h"
#include <pb2json.h>

using namespace std;

int main(int argc,char *argv[])
{
 	// Test 1: read binary PB from a file and convert it to JSON
	ifstream fin("dump",ios::binary);
	fin.seekg(0,ios_base::end);
	size_t len = fin.tellg();
	fin.seekg(0,ios_base::beg);
	char *buf = new char [len];

	fin.read(buf,len);
	google::protobuf::Message *p = new Person();
	char *json = pb2json(p,buf,len);
	cout<<json<<endl;
	free(json);
	delete p;

	// Test 2: convert PB to JSON directly
	Person p2;
    p2.set_name("Shafreeck Sea");
    p2.set_id(2);
    p2.set_email("renenglish@gmail.com");
	Person_PhoneNumber *pn1 = p2.add_phone();
	pn1->set_number("1234567");
	pn1->set_type(Person::HOME);
	char *json2 = pb2json(p2);
	cout<<json2<<endl;
	free(json2);

	return 0;
}

Add test translate protobuf object to json directly


#include "log4qt/dailyfileappender.h"

#include "log4qt/simplelayout.h"

#include <QTemporaryDir>
#include <QtTest/QtTest>

using Log4Qt::DailyFileAppender;

class DailyFileAppenderTest : public QObject
{
    Q_OBJECT

private Q_SLOTS:
    void init();
    void cleanup();

    void testFileCreation();

private:
    QTemporaryDir *mLogDirectory;
    DailyFileAppender *mAppender;
};

void DailyFileAppenderTest::init()
{
    mLogDirectory = new QTemporaryDir;

    mAppender = new DailyFileAppender;
    mAppender->setLayout(Log4Qt::LayoutSharedPtr(new Log4Qt::SimpleLayout));
}

void DailyFileAppenderTest::cleanup()
{
    delete mAppender;
    delete mLogDirectory;  // destructor will remove temporary directory
}

void DailyFileAppenderTest::testFileCreation()
{
    mAppender->setDatePattern(QStringLiteral("_yyyy_MM_dd"));
    mAppender->setFile(mLogDirectory->filePath(QStringLiteral("app.log")));

    mAppender->activateOptions();

    QVERIFY(QFileInfo::exists(mAppender->file()));
}

QTEST_GUILESS_MAIN(DailyFileAppenderTest)

#include "dailyfileappendertest.moc"

#include "log4qt/dailyfileappender.h"

#include "log4qt/loggingevent.h"
#include "log4qt/simplelayout.h"

#include <QTemporaryDir>
#include <QtTest/QtTest>

using Log4Qt::DailyFileAppender;

class DailyFileAppenderTest : public QObject
{
    Q_OBJECT

private Q_SLOTS:
    void init();
    void cleanup();

    void testFileCreation();
    void testAppend();

private:
    QTemporaryDir *mLogDirectory;
    DailyFileAppender *mAppender;
};

void DailyFileAppenderTest::init()
{
    mLogDirectory = new QTemporaryDir;

    mAppender = new DailyFileAppender;
    mAppender->setLayout(Log4Qt::LayoutSharedPtr(new Log4Qt::SimpleLayout));
}

void DailyFileAppenderTest::cleanup()
{
    delete mAppender;
    delete mLogDirectory;  // destructor will remove temporary directory
}

void DailyFileAppenderTest::testFileCreation()
{
    mAppender->setDatePattern(QStringLiteral("_yyyy_MM_dd"));
    mAppender->setFile(mLogDirectory->filePath(QStringLiteral("app.log")));

    mAppender->activateOptions();

    QVERIFY(QFileInfo::exists(mAppender->file()));
}

void DailyFileAppenderTest::testAppend()
{
    mAppender->setFile(mLogDirectory->filePath(QStringLiteral("app.log")));

    mAppender->activateOptions();

    const auto fileName = mAppender->file();

    QVERIFY(QFileInfo::exists(fileName));

    const QFile logFile(fileName);

    // nothing written yet
    QCOMPARE(logFile.size(), 0);

    mAppender->append(Log4Qt::LoggingEvent());

    QVERIFY(logFile.size() > 0);
}

QTEST_GUILESS_MAIN(DailyFileAppenderTest)

#include "dailyfileappendertest.moc"

Add test for simple append using DailyFileAppender


#include <fstream>
#include "rang.hpp"

int main()
{
	std::cout << rang::fg::blue << "\nShould be blue";
	std::ofstream out("out.txt");
	std::streambuf *coutbuf = std::cout.rdbuf();
	std::cout.rdbuf(out.rdbuf());

	std::string word = "not blue";
	std::cout << "START " << rang::fg::blue << word << " END";

	std::cout.rdbuf(coutbuf);
	std::cout << "\nShould again be blue" << rang::style::reset << std::endl;
	return 0;
}

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include "rang.hpp"

#include <fstream>
#include <string>

std::string RCB(std::string input)
{
	std::ofstream out("out.txt");
	std::streambuf *coutbuf = std::cout.rdbuf();
	std::cout.rdbuf(out.rdbuf());

	std::cout << rang::fg::blue << input << rang::style::reset;

	std::cout.rdbuf(coutbuf);
	out.close();

	std::ifstream in("out.txt");
	std::string output;
	std::getline(in,output);
	return output;

}

TEST_CASE("Redirected cout buffer", "RCB")
{
	REQUIRE(RCB("HelloWorld") == "HelloWorld");
}

Add a simple write-then-read test

Add a simple write-then-read test


// 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 "remoting/host/event_executor_mac.h"

namespace remoting {

EventExecutorMac::EventExecutorMac(Capturer* capturer)
  : EventExecutor(capturer) {
}

EventExecutorMac::~EventExecutorMac() {
}

void EventExecutorMac::HandleInputEvent(ChromotingClientMessage* message) {
  delete message;
}

}  // namespace remoting

// 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 "remoting/host/event_executor_mac.h"

#include "remoting/protocol/messages_decoder.h"

namespace remoting {

EventExecutorMac::EventExecutorMac(Capturer* capturer)
  : EventExecutor(capturer) {
}

EventExecutorMac::~EventExecutorMac() {
}

void EventExecutorMac::HandleInputEvent(ChromotingClientMessage* message) {
  delete message;
}

}  // namespace remoting

Fix build break on mac. TBR=ajwong

Fix build break on mac.
TBR=ajwong

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


// Copyright (c) 2011 The Native Client 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 "native_client/src/shared/platform/nacl_check.h"
#include "native_client/tests/ppapi_test_lib/test_interface.h"

namespace {

// This will crash a PPP_Messaging function.
void CrashViaExitCall() {
  printf("--- CrashViaExitCall\n");
  _exit(0);
}

}  // namespace

void SetupTests() {
  RegisterTest("CrashViaExitCall", CrashViaExitCall);
}

void SetupPluginInterfaces() {
  // none
}

// Copyright (c) 2011 The Native Client 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 <unistd.h>

#include "native_client/src/shared/platform/nacl_check.h"
#include "native_client/tests/ppapi_test_lib/test_interface.h"

namespace {

// This will crash a PPP_Messaging function.
void CrashViaExitCall() {
  printf("--- CrashViaExitCall\n");
  _exit(0);
}

}  // namespace

void SetupTests() {
  RegisterTest("CrashViaExitCall", CrashViaExitCall);
}

void SetupPluginInterfaces() {
  // none
}

Add include for unistd.h for _exit.
Otherwise, the exit test won't build w/ pnacl.

R= polina@google.com,dspringer@google.com
BUG=
TEST= ./scons platform=x86-32 bitcode=1 run_ppapi_crash_browser_test

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

git-svn-id: 721b910a23eff8a86f00c8fd261a7587cddf18f8@6282 fcba33aa-ac0c-11dd-b9e7-8d5594d729c2


//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// UNSUPPORTED: c++98, c++03

// <future>

// class packaged_task<R(ArgTypes...)>
// template <class F, class Allocator>
//   packaged_task(allocator_arg_t, const Allocator& a, F&& f);
// These constructors shall not participate in overload resolution if
//    decay<F>::type is the same type as std::packaged_task<R(ArgTypes...)>.

#include <future>
#include <cassert>

#include "test_allocator.h"

struct A {};
typedef std::packaged_task<A(int, char)> PT;
typedef volatile std::packaged_task<A(int, char)> VPT;

int main()
{
    PT p { std::allocator_arg_t{}, test_allocator<A>{}, VPT {}}; // expected-error {{no matching constructor for initialization of 'PT' (aka 'packaged_task<A (int, char)>')}}
    // expected-note@future:* 1 {{candidate template ignored: disabled by 'enable_if'}}
}

//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// UNSUPPORTED: c++98, c++03

// <future>

// class packaged_task<R(ArgTypes...)>
// template <class F, class Allocator>
//   packaged_task(allocator_arg_t, const Allocator& a, F&& f);
// These constructors shall not participate in overload resolution if
//    decay<F>::type is the same type as std::packaged_task<R(ArgTypes...)>.

#include <future>
#include <cassert>

#include "test_allocator.h"

struct A {};
typedef std::packaged_task<A(int, char)> PT;
typedef volatile std::packaged_task<A(int, char)> VPT;

int main()
{
    PT p { std::allocator_arg_t{}, test_allocator<A>{}, VPT {}}; // expected-error {{no matching constructor for initialization of 'PT' (aka 'packaged_task<A (int, char)>')}}
    // expected-note-re@future:* 1 {{candidate template ignored: {{(disabled by 'enable_if')|(requirement '.*' was not satisfied)}}}}
}

Fix diagnostic in verify test to match new Clang output

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