<commit_before>/*
	This file is part of cpp-ethereum.

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

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

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file EthashAux.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 */

#include "EthashAux.h"

#include <boost/detail/endian.hpp>
#include <boost/filesystem.hpp>
#include <chrono>
#include <array>
#include <random>
#include <thread>
#include <libdevcore/Common.h>
#include <libdevcore/Guards.h>
#include <libdevcore/Log.h>
#include <libdevcrypto/CryptoPP.h>
#include <libdevcrypto/SHA3.h>
#include <libdevcrypto/FileSystem.h>
#include <libethash/internal.h>
#include "BlockInfo.h"
#include "Exceptions.h"
using namespace std;
using namespace chrono;
using namespace dev;
using namespace eth;

EthashAux* dev::eth::EthashAux::s_this = nullptr;

EthashAux::~EthashAux()
{
}

uint64_t EthashAux::cacheSize(BlockInfo const& _header)
{
	return ethash_get_cachesize((uint64_t)_header.number);
}

h256 EthashAux::seedHash(unsigned _number)
{
	unsigned epoch = _number / ETHASH_EPOCH_LENGTH;
	Guard l(get()->x_epochs);
	if (epoch >= get()->m_seedHashes.size())
	{
		h256 ret;
		unsigned n = 0;
		if (!get()->m_seedHashes.empty())
		{
			ret = get()->m_seedHashes.back();
			n = get()->m_seedHashes.size() - 1;
		}
		get()->m_seedHashes.resize(epoch + 1);
//		cdebug << "Searching for seedHash of epoch " << epoch;
		for (; n <= epoch; ++n, ret = sha3(ret))
		{
			get()->m_seedHashes[n] = ret;
//			cdebug << "Epoch" << n << "is" << ret;
		}
	}
	return get()->m_seedHashes[epoch];
}

void EthashAux::killCache(h256 const& _s)
{
	RecursiveGuard l(x_this);
	m_lights.erase(_s);
}

EthashAux::LightType EthashAux::light(BlockInfo const& _header)
{
	return light((uint64_t)_header.number);
}

EthashAux::LightType EthashAux::light(uint64_t _blockNumber)
{
	RecursiveGuard l(get()->x_this);
	h256 seedHash = EthashAux::seedHash(_blockNumber);
	LightType ret = get()->m_lights[seedHash];
	return ret ? ret : (get()->m_lights[seedHash] = make_shared<LightAllocation>(_blockNumber));
}

EthashAux::LightAllocation::LightAllocation(uint64_t _blockNumber)
{
	light = ethash_light_new(_blockNumber);
	size = ethash_get_cachesize(_blockNumber);
}

EthashAux::LightAllocation::~LightAllocation()
{
	ethash_light_delete(light);
}

bytesConstRef EthashAux::LightAllocation::data() const
{
	return bytesConstRef((byte const*)light->cache, size);
}

EthashAux::FullAllocation::FullAllocation(ethash_light_t _light, ethash_callback_t _cb)
{
	full = ethash_full_new(_light, _cb);
}

EthashAux::FullAllocation::~FullAllocation()
{
	ethash_full_delete(full);
}

bytesConstRef EthashAux::FullAllocation::data() const
{
	return bytesConstRef((byte const*)ethash_full_dag(full), size());
}

EthashAux::FullType EthashAux::full(BlockInfo const& _header)
{
	return full((uint64_t) _header.number);
}

EthashAux::FullType EthashAux::full(uint64_t _blockNumber)
{
	RecursiveGuard l(get()->x_this);
	h256 seedHash = EthashAux::seedHash(_blockNumber);
	FullType ret = get()->m_fulls[seedHash].lock();
	if (ret) {
		get()->m_lastUsedFull = ret;
		return ret;
	}
	ret = get()->m_lastUsedFull = make_shared<FullAllocation>(light(_blockNumber)->light, nullptr);
	get()->m_fulls[seedHash] = ret;
	return ret;
}

Ethash::Result EthashAux::FullAllocation::compute(h256 const& _headerHash, Nonce const& _nonce) const
{
	ethash_return_value_t r = ethash_full_compute(full, *(ethash_h256_t*)_headerHash.data(), (uint64_t)(u64)_nonce);
	if (!r.success)
		BOOST_THROW_EXCEPTION(DAGCreationFailure());
	return Ethash::Result{h256((uint8_t*)&r.result, h256::ConstructFromPointer), h256((uint8_t*)&r.mix_hash, h256::ConstructFromPointer)};
}

Ethash::Result EthashAux::LightAllocation::compute(h256 const& _headerHash, Nonce const& _nonce) const
{
	ethash_return_value r = ethash_light_compute(light, *(ethash_h256_t*)_headerHash.data(), (uint64_t)(u64)_nonce);
	if (!r.success)
		BOOST_THROW_EXCEPTION(DAGCreationFailure());
	return Ethash::Result{h256((uint8_t*)&r.result, h256::ConstructFromPointer), h256((uint8_t*)&r.mix_hash, h256::ConstructFromPointer)};
}

Ethash::Result EthashAux::eval(BlockInfo const& _header, Nonce const& _nonce)
{
	return eval((uint64_t)_header.number, _header.headerHash(WithoutNonce), _nonce);
}

Ethash::Result EthashAux::eval(uint64_t _blockNumber, h256 const& _headerHash, Nonce const& _nonce)
{
	if (auto dag = EthashAux::get()->full(_blockNumber))
		return dag->compute(_headerHash, _nonce);
	return EthashAux::get()->light(_blockNumber)->compute(_headerHash, _nonce);
}
<commit_msg>Fix EthashAux eval(). Dagger tests now pass<commit_after>/*
	This file is part of cpp-ethereum.

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

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

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file EthashAux.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 */

#include "EthashAux.h"

#include <boost/detail/endian.hpp>
#include <boost/filesystem.hpp>
#include <chrono>
#include <array>
#include <random>
#include <thread>
#include <libdevcore/Common.h>
#include <libdevcore/Guards.h>
#include <libdevcore/Log.h>
#include <libdevcrypto/CryptoPP.h>
#include <libdevcrypto/SHA3.h>
#include <libdevcrypto/FileSystem.h>
#include <libethash/internal.h>
#include "BlockInfo.h"
#include "Exceptions.h"
using namespace std;
using namespace chrono;
using namespace dev;
using namespace eth;

EthashAux* dev::eth::EthashAux::s_this = nullptr;

EthashAux::~EthashAux()
{
}

uint64_t EthashAux::cacheSize(BlockInfo const& _header)
{
	return ethash_get_cachesize((uint64_t)_header.number);
}

h256 EthashAux::seedHash(unsigned _number)
{
	unsigned epoch = _number / ETHASH_EPOCH_LENGTH;
	Guard l(get()->x_epochs);
	if (epoch >= get()->m_seedHashes.size())
	{
		h256 ret;
		unsigned n = 0;
		if (!get()->m_seedHashes.empty())
		{
			ret = get()->m_seedHashes.back();
			n = get()->m_seedHashes.size() - 1;
		}
		get()->m_seedHashes.resize(epoch + 1);
//		cdebug << "Searching for seedHash of epoch " << epoch;
		for (; n <= epoch; ++n, ret = sha3(ret))
		{
			get()->m_seedHashes[n] = ret;
//			cdebug << "Epoch" << n << "is" << ret;
		}
	}
	return get()->m_seedHashes[epoch];
}

void EthashAux::killCache(h256 const& _s)
{
	RecursiveGuard l(x_this);
	m_lights.erase(_s);
}

EthashAux::LightType EthashAux::light(BlockInfo const& _header)
{
	return light((uint64_t)_header.number);
}

EthashAux::LightType EthashAux::light(uint64_t _blockNumber)
{
	RecursiveGuard l(get()->x_this);
	h256 seedHash = EthashAux::seedHash(_blockNumber);
	LightType ret = get()->m_lights[seedHash];
	return ret ? ret : (get()->m_lights[seedHash] = make_shared<LightAllocation>(_blockNumber));
}

EthashAux::LightAllocation::LightAllocation(uint64_t _blockNumber)
{
	light = ethash_light_new(_blockNumber);
	size = ethash_get_cachesize(_blockNumber);
}

EthashAux::LightAllocation::~LightAllocation()
{
	ethash_light_delete(light);
}

bytesConstRef EthashAux::LightAllocation::data() const
{
	return bytesConstRef((byte const*)light->cache, size);
}

EthashAux::FullAllocation::FullAllocation(ethash_light_t _light, ethash_callback_t _cb)
{
	full = ethash_full_new(_light, _cb);
}

EthashAux::FullAllocation::~FullAllocation()
{
	ethash_full_delete(full);
}

bytesConstRef EthashAux::FullAllocation::data() const
{
	return bytesConstRef((byte const*)ethash_full_dag(full), size());
}

EthashAux::FullType EthashAux::full(BlockInfo const& _header)
{
	return full((uint64_t) _header.number);
}

EthashAux::FullType EthashAux::full(uint64_t _blockNumber)
{
	RecursiveGuard l(get()->x_this);
	h256 seedHash = EthashAux::seedHash(_blockNumber);
	FullType ret;
	if ((ret = get()->m_fulls[seedHash].lock()))
	{
		get()->m_lastUsedFull = ret;
		return ret;
	}
	ret = get()->m_lastUsedFull = make_shared<FullAllocation>(light(_blockNumber)->light, nullptr);
	get()->m_fulls[seedHash] = ret;
	return ret;
}

Ethash::Result EthashAux::FullAllocation::compute(h256 const& _headerHash, Nonce const& _nonce) const
{
	ethash_return_value_t r = ethash_full_compute(full, *(ethash_h256_t*)_headerHash.data(), (uint64_t)(u64)_nonce);
	if (!r.success)
		BOOST_THROW_EXCEPTION(DAGCreationFailure());
	return Ethash::Result{h256((uint8_t*)&r.result, h256::ConstructFromPointer), h256((uint8_t*)&r.mix_hash, h256::ConstructFromPointer)};
}

Ethash::Result EthashAux::LightAllocation::compute(h256 const& _headerHash, Nonce const& _nonce) const
{
	ethash_return_value r = ethash_light_compute(light, *(ethash_h256_t*)_headerHash.data(), (uint64_t)(u64)_nonce);
	if (!r.success)
		BOOST_THROW_EXCEPTION(DAGCreationFailure());
	return Ethash::Result{h256((uint8_t*)&r.result, h256::ConstructFromPointer), h256((uint8_t*)&r.mix_hash, h256::ConstructFromPointer)};
}

Ethash::Result EthashAux::eval(BlockInfo const& _header, Nonce const& _nonce)
{
	return eval((uint64_t)_header.number, _header.headerHash(WithoutNonce), _nonce);
}

Ethash::Result EthashAux::eval(uint64_t _blockNumber, h256 const& _headerHash, Nonce const& _nonce)
{
	h256 seedHash = EthashAux::seedHash(_blockNumber);
	if (FullType dag = get()->m_fulls[seedHash].lock())
		return dag->compute(_headerHash, _nonce);
	return EthashAux::get()->light(_blockNumber)->compute(_headerHash, _nonce);
}
<|endoftext|>


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

#include "components/password_manager/core/browser/password_store_default.h"

#include <set>

#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "base/stl_util.h"
#include "components/password_manager/core/browser/password_store_change.h"

using autofill::PasswordForm;

namespace password_manager {

PasswordStoreDefault::PasswordStoreDefault(
    scoped_refptr<base::SingleThreadTaskRunner> main_thread_runner,
    scoped_refptr<base::SingleThreadTaskRunner> db_thread_runner,
    scoped_ptr<LoginDatabase> login_db)
    : PasswordStore(main_thread_runner, db_thread_runner),
      login_db_(login_db.Pass()) {
}

PasswordStoreDefault::~PasswordStoreDefault() {
}

bool PasswordStoreDefault::Init(
    const syncer::SyncableService::StartSyncFlare& flare) {
  ScheduleTask(base::Bind(&PasswordStoreDefault::InitOnDBThread, this));
  return PasswordStore::Init(flare);
}

void PasswordStoreDefault::InitOnDBThread() {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  DCHECK(login_db_);
  if (!login_db_->Init()) {
    login_db_.reset();
    LOG(ERROR) << "Could not create/open login database.";
  }
}

void PasswordStoreDefault::ReportMetricsImpl(
    const std::string& sync_username,
    bool custom_passphrase_sync_enabled) {
  if (!login_db_)
    return;
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  login_db_->ReportMetrics(sync_username, custom_passphrase_sync_enabled);
}

PasswordStoreChangeList PasswordStoreDefault::AddLoginImpl(
    const PasswordForm& form) {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  if (!login_db_)
    return PasswordStoreChangeList();
  return login_db_->AddLogin(form);
}

PasswordStoreChangeList PasswordStoreDefault::UpdateLoginImpl(
    const PasswordForm& form) {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  if (!login_db_)
    return PasswordStoreChangeList();
  return login_db_->UpdateLogin(form);
}

PasswordStoreChangeList PasswordStoreDefault::RemoveLoginImpl(
    const PasswordForm& form) {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  PasswordStoreChangeList changes;
  if (login_db_ && login_db_->RemoveLogin(form))
    changes.push_back(PasswordStoreChange(PasswordStoreChange::REMOVE, form));
  return changes;
}

PasswordStoreChangeList PasswordStoreDefault::RemoveLoginsCreatedBetweenImpl(
    base::Time delete_begin,
    base::Time delete_end) {
  ScopedVector<autofill::PasswordForm> forms;
  PasswordStoreChangeList changes;
  if (login_db_ &&
      login_db_->GetLoginsCreatedBetween(delete_begin, delete_end, &forms)) {
    if (login_db_->RemoveLoginsCreatedBetween(delete_begin, delete_end)) {
      for (const auto* form : forms) {
        changes.push_back(
            PasswordStoreChange(PasswordStoreChange::REMOVE, *form));
      }
      LogStatsForBulkDeletion(changes.size());
    }
  }
  return changes;
}

PasswordStoreChangeList PasswordStoreDefault::RemoveLoginsSyncedBetweenImpl(
    base::Time delete_begin,
    base::Time delete_end) {
  ScopedVector<autofill::PasswordForm> forms;
  PasswordStoreChangeList changes;
  if (login_db_ &&
      login_db_->GetLoginsSyncedBetween(delete_begin, delete_end, &forms)) {
    if (login_db_->RemoveLoginsSyncedBetween(delete_begin, delete_end)) {
      for (const auto* form : forms) {
        changes.push_back(
            PasswordStoreChange(PasswordStoreChange::REMOVE, *form));
      }
      LogStatsForBulkDeletionDuringRollback(changes.size());
    }
  }
  return changes;
}

ScopedVector<autofill::PasswordForm> PasswordStoreDefault::FillMatchingLogins(
    const autofill::PasswordForm& form,
    AuthorizationPromptPolicy prompt_policy) {
  ScopedVector<autofill::PasswordForm> matched_forms;
  if (login_db_ && !login_db_->GetLogins(form, &matched_forms))
    return ScopedVector<autofill::PasswordForm>();
  return matched_forms.Pass();
}

void PasswordStoreDefault::GetAutofillableLoginsImpl(
    scoped_ptr<GetLoginsRequest> request) {
  ScopedVector<PasswordForm> logins;
  if (!FillAutofillableLogins(&logins))
    logins.clear();
  request->NotifyConsumerWithResults(logins.Pass());
}

void PasswordStoreDefault::GetBlacklistLoginsImpl(
    scoped_ptr<GetLoginsRequest> request) {
  ScopedVector<PasswordForm> logins;
  if (!FillBlacklistLogins(&logins))
    logins.clear();
  request->NotifyConsumerWithResults(logins.Pass());
}

bool PasswordStoreDefault::FillAutofillableLogins(
    ScopedVector<PasswordForm>* forms) {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  return login_db_ && login_db_->GetAutofillableLogins(forms);
}

bool PasswordStoreDefault::FillBlacklistLogins(
    ScopedVector<PasswordForm>* forms) {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  return login_db_ && login_db_->GetBlacklistLogins(forms);
}

void PasswordStoreDefault::AddSiteStatsImpl(const InteractionsStats& stats) {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  if (login_db_)
    login_db_->stats_table().AddRow(stats);
}

void PasswordStoreDefault::RemoveSiteStatsImpl(const GURL& origin_domain) {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  if (login_db_)
    login_db_->stats_table().RemoveRow(origin_domain);
}

scoped_ptr<InteractionsStats> PasswordStoreDefault::GetSiteStatsImpl(
    const GURL& origin_domain) {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  return login_db_ ? login_db_->stats_table().GetRow(origin_domain)
                   : scoped_ptr<InteractionsStats>();
}

}  // namespace password_manager
<commit_msg>Stop deleting LoginDatabase on the UI thread during shutdown<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/password_manager/core/browser/password_store_default.h"

#include <set>

#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "base/stl_util.h"
#include "components/password_manager/core/browser/password_store_change.h"

using autofill::PasswordForm;

namespace password_manager {

PasswordStoreDefault::PasswordStoreDefault(
    scoped_refptr<base::SingleThreadTaskRunner> main_thread_runner,
    scoped_refptr<base::SingleThreadTaskRunner> db_thread_runner,
    scoped_ptr<LoginDatabase> login_db)
    : PasswordStore(main_thread_runner, db_thread_runner),
      login_db_(login_db.Pass()) {
}

PasswordStoreDefault::~PasswordStoreDefault() {
  if (!GetBackgroundTaskRunner()->BelongsToCurrentThread())
    GetBackgroundTaskRunner()->DeleteSoon(FROM_HERE, login_db_.release());
}

bool PasswordStoreDefault::Init(
    const syncer::SyncableService::StartSyncFlare& flare) {
  ScheduleTask(base::Bind(&PasswordStoreDefault::InitOnDBThread, this));
  return PasswordStore::Init(flare);
}

void PasswordStoreDefault::InitOnDBThread() {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  DCHECK(login_db_);
  if (!login_db_->Init()) {
    login_db_.reset();
    LOG(ERROR) << "Could not create/open login database.";
  }
}

void PasswordStoreDefault::ReportMetricsImpl(
    const std::string& sync_username,
    bool custom_passphrase_sync_enabled) {
  if (!login_db_)
    return;
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  login_db_->ReportMetrics(sync_username, custom_passphrase_sync_enabled);
}

PasswordStoreChangeList PasswordStoreDefault::AddLoginImpl(
    const PasswordForm& form) {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  if (!login_db_)
    return PasswordStoreChangeList();
  return login_db_->AddLogin(form);
}

PasswordStoreChangeList PasswordStoreDefault::UpdateLoginImpl(
    const PasswordForm& form) {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  if (!login_db_)
    return PasswordStoreChangeList();
  return login_db_->UpdateLogin(form);
}

PasswordStoreChangeList PasswordStoreDefault::RemoveLoginImpl(
    const PasswordForm& form) {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  PasswordStoreChangeList changes;
  if (login_db_ && login_db_->RemoveLogin(form))
    changes.push_back(PasswordStoreChange(PasswordStoreChange::REMOVE, form));
  return changes;
}

PasswordStoreChangeList PasswordStoreDefault::RemoveLoginsCreatedBetweenImpl(
    base::Time delete_begin,
    base::Time delete_end) {
  ScopedVector<autofill::PasswordForm> forms;
  PasswordStoreChangeList changes;
  if (login_db_ &&
      login_db_->GetLoginsCreatedBetween(delete_begin, delete_end, &forms)) {
    if (login_db_->RemoveLoginsCreatedBetween(delete_begin, delete_end)) {
      for (const auto* form : forms) {
        changes.push_back(
            PasswordStoreChange(PasswordStoreChange::REMOVE, *form));
      }
      LogStatsForBulkDeletion(changes.size());
    }
  }
  return changes;
}

PasswordStoreChangeList PasswordStoreDefault::RemoveLoginsSyncedBetweenImpl(
    base::Time delete_begin,
    base::Time delete_end) {
  ScopedVector<autofill::PasswordForm> forms;
  PasswordStoreChangeList changes;
  if (login_db_ &&
      login_db_->GetLoginsSyncedBetween(delete_begin, delete_end, &forms)) {
    if (login_db_->RemoveLoginsSyncedBetween(delete_begin, delete_end)) {
      for (const auto* form : forms) {
        changes.push_back(
            PasswordStoreChange(PasswordStoreChange::REMOVE, *form));
      }
      LogStatsForBulkDeletionDuringRollback(changes.size());
    }
  }
  return changes;
}

ScopedVector<autofill::PasswordForm> PasswordStoreDefault::FillMatchingLogins(
    const autofill::PasswordForm& form,
    AuthorizationPromptPolicy prompt_policy) {
  ScopedVector<autofill::PasswordForm> matched_forms;
  if (login_db_ && !login_db_->GetLogins(form, &matched_forms))
    return ScopedVector<autofill::PasswordForm>();
  return matched_forms.Pass();
}

void PasswordStoreDefault::GetAutofillableLoginsImpl(
    scoped_ptr<GetLoginsRequest> request) {
  ScopedVector<PasswordForm> logins;
  if (!FillAutofillableLogins(&logins))
    logins.clear();
  request->NotifyConsumerWithResults(logins.Pass());
}

void PasswordStoreDefault::GetBlacklistLoginsImpl(
    scoped_ptr<GetLoginsRequest> request) {
  ScopedVector<PasswordForm> logins;
  if (!FillBlacklistLogins(&logins))
    logins.clear();
  request->NotifyConsumerWithResults(logins.Pass());
}

bool PasswordStoreDefault::FillAutofillableLogins(
    ScopedVector<PasswordForm>* forms) {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  return login_db_ && login_db_->GetAutofillableLogins(forms);
}

bool PasswordStoreDefault::FillBlacklistLogins(
    ScopedVector<PasswordForm>* forms) {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  return login_db_ && login_db_->GetBlacklistLogins(forms);
}

void PasswordStoreDefault::AddSiteStatsImpl(const InteractionsStats& stats) {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  if (login_db_)
    login_db_->stats_table().AddRow(stats);
}

void PasswordStoreDefault::RemoveSiteStatsImpl(const GURL& origin_domain) {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  if (login_db_)
    login_db_->stats_table().RemoveRow(origin_domain);
}

scoped_ptr<InteractionsStats> PasswordStoreDefault::GetSiteStatsImpl(
    const GURL& origin_domain) {
  DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread());
  return login_db_ ? login_db_->stats_table().GetRow(origin_domain)
                   : scoped_ptr<InteractionsStats>();
}

}  // namespace password_manager
<|endoftext|>


<commit_before>#include <cstdio>
#include <iostream>

#include <pqxx/connection>
#include <pqxx/transaction>
#include <pqxx/result>

using namespace PGSTD;
using namespace pqxx;

// Test program for libpqxx.  Query a table and report its metadata.
//
// Usage: test011 [connect-string] [table]
//
// Where table is the table to be queried; if none is given, pg_tables is
// queried by default.
//
// The connect-string is a set of connection options in Postgresql's
// PQconnectdb() format, eg. "dbname=template1" to select from a database
// called template1, or "host=foo.bar.net user=smith" to connect to a
// backend running on host foo.bar.net, logging in as user smith.
int main(int argc, char *argv[])
{
  try
  {
    const string Table = ((argc >= 3) ? argv[2] : "pg_tables");

    connection C(argv[1]);
    work T(C, "test11");

    result R( T.exec("SELECT * FROM " + Table) );

    // Print column names
    for (result::tuple::size_type c = 0; c < R.columns(); ++c)
    {
      string N= R.column_name(c);
      cout << c << ":\t" << N << endl;
      if (R.column_number(N) != c)
	throw logic_error("Expected column '" + N +
			  "' to be no. " + to_string(c) + ", "
			  "but it was no. " + to_string(R.column_number(N)));
    }

    // If there are rows in R, compare their metadata to R's.
    if (!R.empty())
    {
      if (R[0].rownumber() != 0)
	throw logic_error("Row 0 said it was row " + R[0].rownumber());

      if (R.size() < 2)
	cout << "(Only one row in table.)" << endl;
      else if (R[1].rownumber() != 1)
        throw logic_error("Row 1 said it was row " + R[1].rownumber());

      for (result::tuple::size_type c = 0; c < R[0].size(); ++c)
      {
	string N = R.column_name(c);

	if (string(R[0].at(c).c_str()) != R[0].at(N).c_str())
          throw logic_error("Field " + to_string(c) + " contains "
			    "'" + R[0].at(c).c_str() + "'; "
			    "field '" + N + "' "
			    "contains '" + R[0].at(N).c_str() + "'");
	if (string(R[0][c].c_str()) != R[0][N].c_str())
          throw logic_error("Field " + to_string(c) + " ('" + N + "'): "
			    "at() inconsistent with operator[]!");

	if (R[0][c].name() != N)
	  throw logic_error("Field " + to_string(c) + " "
			    "called '" + N + "' by result, "
			    "but '" + R[0][c].name() + "' by Field object");

	if (size_t(R[0][c].size()) != strlen(R[0][c].c_str()))
	  throw logic_error("Field '" + N + "' "
			    "says its length is " + to_string(R[0][c].size()) +
			    ", "
			    "but its value is '" + R[0][c].c_str() + "' "
			    "(" + to_string(strlen(R[0][c].c_str())) + " "
			    "chars)");
      }
    }
    else
    {
      cout << "(Table is empty.)" << endl;
    }
  }
  catch (const sql_error &e)
  {
    // If we're interested in the text of a failed query, we can write separate
    // exception handling code for this type of exception
    cerr << "SQL error: " << e.what() << endl
         << "Query was: '" << e.query() << "'" << endl;
    return 1;
  }
  catch (const exception &e)
  {
    // All exceptions thrown by libpqxx are derived from std::exception
    cerr << "Exception: " << e.what() << endl;
    return 2;
  }
  catch (...)
  {
    // This is really unexpected (see above)
    cerr << "Unhandled exception" << endl;
    return 100;
  }

  return 0;
}

<commit_msg>Test result::tuple::swap() and equality<commit_after>#include <cstdio>
#include <iostream>

#include <pqxx/connection>
#include <pqxx/transaction>
#include <pqxx/result>

using namespace PGSTD;
using namespace pqxx;

// Test program for libpqxx.  Query a table and report its metadata.
//
// Usage: test011 [connect-string] [table]
//
// Where table is the table to be queried; if none is given, pg_tables is
// queried by default.
//
// The connect-string is a set of connection options in Postgresql's
// PQconnectdb() format, eg. "dbname=template1" to select from a database
// called template1, or "host=foo.bar.net user=smith" to connect to a
// backend running on host foo.bar.net, logging in as user smith.
int main(int argc, char *argv[])
{
  try
  {
    const string Table = ((argc >= 3) ? argv[2] : "pg_tables");

    connection C(argv[1]);
    work T(C, "test11");

    result R( T.exec("SELECT * FROM " + Table) );

    // Print column names
    for (result::tuple::size_type c = 0; c < R.columns(); ++c)
    {
      string N= R.column_name(c);
      cout << c << ":\t" << N << endl;
      if (R.column_number(N) != c)
	throw logic_error("Expected column '" + N +
			  "' to be no. " + to_string(c) + ", "
			  "but it was no. " + to_string(R.column_number(N)));
    }

    // If there are rows in R, compare their metadata to R's.
    if (!R.empty())
    {
      if (R[0].rownumber() != 0)
	throw logic_error("Row 0 said it was row " + R[0].rownumber());

      if (R.size() < 2)
	cout << "(Only one row in table.)" << endl;
      else if (R[1].rownumber() != 1)
        throw logic_error("Row 1 said it was row " + R[1].rownumber());

      // Test tuple::swap()
      const result::tuple T1(R[0]), T2(R[1]);
      if (T2 == T1)
	throw runtime_error("Values are identical, can't test swap()!");
      result::tuple T1s(T1), T2s(T2);
      if (T1s != T1 || !(T2s == T2))
	throw logic_error("Tuple copy-construction incorrect");
      T1s.swap(T2s);
      if (T1s == T1 || !(T2s != T2))
	throw logic_error("Tuple swap doesn't work");
      if (T2s != T1 || !(T1s == T2))
	throw logic_error("Tuple swap is asymmetric");

      for (result::tuple::size_type c = 0; c < R[0].size(); ++c)
      {
	string N = R.column_name(c);

	if (string(R[0].at(c).c_str()) != R[0].at(N).c_str())
          throw logic_error("Field " + to_string(c) + " contains "
			    "'" + R[0].at(c).c_str() + "'; "
			    "field '" + N + "' "
			    "contains '" + R[0].at(N).c_str() + "'");
	if (string(R[0][c].c_str()) != R[0][N].c_str())
          throw logic_error("Field " + to_string(c) + " ('" + N + "'): "
			    "at() inconsistent with operator[]!");

	if (R[0][c].name() != N)
	  throw logic_error("Field " + to_string(c) + " "
			    "called '" + N + "' by result, "
			    "but '" + R[0][c].name() + "' by Field object");

	if (size_t(R[0][c].size()) != strlen(R[0][c].c_str()))
	  throw logic_error("Field '" + N + "' "
			    "says its length is " + to_string(R[0][c].size()) +
			    ", "
			    "but its value is '" + R[0][c].c_str() + "' "
			    "(" + to_string(strlen(R[0][c].c_str())) + " "
			    "chars)");
      }
    }
    else
    {
      cout << "(Table is empty.)" << endl;
    }
  }
  catch (const sql_error &e)
  {
    // If we're interested in the text of a failed query, we can write separate
    // exception handling code for this type of exception
    cerr << "SQL error: " << e.what() << endl
         << "Query was: '" << e.query() << "'" << endl;
    return 1;
  }
  catch (const exception &e)
  {
    // All exceptions thrown by libpqxx are derived from std::exception
    cerr << "Exception: " << e.what() << endl;
    return 2;
  }
  catch (...)
  {
    // This is really unexpected (see above)
    cerr << "Unhandled exception" << endl;
    return 100;
  }

  return 0;
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "JsonWrapper.h"

#include <algorithm>
#include <json/value.h>

JsonWrapper::JsonWrapper() : JsonWrapper(Json::nullValue) {}
JsonWrapper::JsonWrapper(const Json::Value& config)
    : m_config(new Json::Value(config)) {}

JsonWrapper::~JsonWrapper() {}

JsonWrapper::JsonWrapper(JsonWrapper&& other) noexcept
    : m_config(std::move(other.m_config)) {}
JsonWrapper& JsonWrapper::operator=(JsonWrapper&& rhs) noexcept {
  m_config = std::move(rhs.m_config);
  return *this;
}

void JsonWrapper::get(const char* name, int64_t dflt, int64_t& param) const {
  param = m_config->get(name, (Json::Int64)dflt).asInt();
}

void JsonWrapper::get(const char* name, size_t dflt, size_t& param) const {
  param = m_config->get(name, (Json::UInt)dflt).asUInt();
}

void JsonWrapper::get(const char* name,
                      const std::string& dflt,
                      std::string& param) const {
  param = m_config->get(name, dflt).asString();
}

std::string JsonWrapper::get(const char* name, const std::string& dflt) const {
  return m_config->get(name, dflt).asString();
}

void JsonWrapper::get(const char* name, bool dflt, bool& param) const {
  auto val = m_config->get(name, dflt);

  // Do some simple type conversions that folly used to do
  if (val.isBool()) {
    param = val.asBool();
    return;
  } else if (val.isInt()) {
    auto valInt = val.asInt();
    if (valInt == 0 || valInt == 1) {
      param = (val.asInt() != 0);
      return;
    }
  } else if (val.isString()) {
    auto str = val.asString();
    std::transform(str.begin(), str.end(), str.begin(),
                   [](auto c) { return ::tolower(c); });
    if (str == "0" || str == "false" || str == "off" || str == "no") {
      param = false;
      return;
    } else if (str == "1" || str == "true" || str == "on" || str == "yes") {
      param = true;
      return;
    }
  }
  throw std::runtime_error("Cannot convert JSON value to bool: " +
                           val.asString());
}

bool JsonWrapper::get(const char* name, bool dflt) const {
  bool res;
  get(name, dflt, res);
  return res;
}

void JsonWrapper::get(const char* name,
                      const std::vector<std::string>& dflt,
                      std::vector<std::string>& param) const {
  auto it = (*m_config)[name];
  // NOLINTNEXTLINE(readability-container-size-empty)
  if (it == Json::nullValue) {
    param = dflt;
  } else {
    param.clear();
    for (auto const& str : it) {
      param.emplace_back(str.asString());
    }
  }
}

void JsonWrapper::get(const char* name,
                      const std::vector<std::string>& dflt,
                      std::unordered_set<std::string>& param) const {
  auto it = (*m_config)[name];
  param.clear();
  // NOLINTNEXTLINE(readability-container-size-empty)
  if (it == Json::nullValue) {
    param.insert(dflt.begin(), dflt.end());
  } else {
    for (auto const& str : it) {
      param.emplace(str.asString());
    }
  }
}

void JsonWrapper::get(
    const char* name,
    const std::unordered_map<std::string, std::vector<std::string>>& dflt,
    std::unordered_map<std::string, std::vector<std::string>>& param) const {
  auto cfg = (*m_config)[name];
  param.clear();
  // NOLINTNEXTLINE(readability-container-size-empty)
  if (cfg == Json::nullValue) {
    param = dflt;
  } else {
    if (!cfg.isObject()) {
      throw std::runtime_error("Cannot convert JSON value to object: " +
                               cfg.asString());
    }
    for (auto it = cfg.begin(); it != cfg.end(); ++it) {
      auto key = it.key();
      if (!key.isString()) {
        throw std::runtime_error("Cannot convert JSON value to string: " +
                                 key.asString());
      }
      auto& val = *it;
      if (!val.isArray()) {
        throw std::runtime_error("Cannot convert JSON value to array: " +
                                 val.asString());
      }
      for (auto& str : val) {
        if (!str.isString()) {
          throw std::runtime_error("Cannot convert JSON value to string: " +
                                   str.asString());
        }
        param[key.asString()].push_back(str.asString());
      }
    }
  }
}

void JsonWrapper::get(const char* name,
                      const Json::Value& dflt,
                      Json::Value& param) const {
  param = m_config->get(name, dflt);
}

Json::Value JsonWrapper::get(const char* name, const Json::Value& dflt) const {
  return m_config->get(name, dflt);
}

const Json::Value& JsonWrapper::operator[](const char* name) const {
  return (*m_config)[name];
}

bool JsonWrapper::contains(const char* name) const {
  return m_config->isMember(name);
}
<commit_msg>Fix CI error (#550)<commit_after>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "JsonWrapper.h"

#include <algorithm>
#include <json/value.h>
#include <stdexcept>

JsonWrapper::JsonWrapper() : JsonWrapper(Json::nullValue) {}
JsonWrapper::JsonWrapper(const Json::Value& config)
    : m_config(new Json::Value(config)) {}

JsonWrapper::~JsonWrapper() {}

JsonWrapper::JsonWrapper(JsonWrapper&& other) noexcept
    : m_config(std::move(other.m_config)) {}
JsonWrapper& JsonWrapper::operator=(JsonWrapper&& rhs) noexcept {
  m_config = std::move(rhs.m_config);
  return *this;
}

void JsonWrapper::get(const char* name, int64_t dflt, int64_t& param) const {
  param = m_config->get(name, (Json::Int64)dflt).asInt();
}

void JsonWrapper::get(const char* name, size_t dflt, size_t& param) const {
  param = m_config->get(name, (Json::UInt)dflt).asUInt();
}

void JsonWrapper::get(const char* name,
                      const std::string& dflt,
                      std::string& param) const {
  param = m_config->get(name, dflt).asString();
}

std::string JsonWrapper::get(const char* name, const std::string& dflt) const {
  return m_config->get(name, dflt).asString();
}

void JsonWrapper::get(const char* name, bool dflt, bool& param) const {
  auto val = m_config->get(name, dflt);

  // Do some simple type conversions that folly used to do
  if (val.isBool()) {
    param = val.asBool();
    return;
  } else if (val.isInt()) {
    auto valInt = val.asInt();
    if (valInt == 0 || valInt == 1) {
      param = (val.asInt() != 0);
      return;
    }
  } else if (val.isString()) {
    auto str = val.asString();
    std::transform(str.begin(), str.end(), str.begin(),
                   [](auto c) { return ::tolower(c); });
    if (str == "0" || str == "false" || str == "off" || str == "no") {
      param = false;
      return;
    } else if (str == "1" || str == "true" || str == "on" || str == "yes") {
      param = true;
      return;
    }
  }
  throw std::runtime_error("Cannot convert JSON value to bool: " +
                           val.asString());
}

bool JsonWrapper::get(const char* name, bool dflt) const {
  bool res;
  get(name, dflt, res);
  return res;
}

void JsonWrapper::get(const char* name,
                      const std::vector<std::string>& dflt,
                      std::vector<std::string>& param) const {
  auto it = (*m_config)[name];
  // NOLINTNEXTLINE(readability-container-size-empty)
  if (it == Json::nullValue) {
    param = dflt;
  } else {
    param.clear();
    for (auto const& str : it) {
      param.emplace_back(str.asString());
    }
  }
}

void JsonWrapper::get(const char* name,
                      const std::vector<std::string>& dflt,
                      std::unordered_set<std::string>& param) const {
  auto it = (*m_config)[name];
  param.clear();
  // NOLINTNEXTLINE(readability-container-size-empty)
  if (it == Json::nullValue) {
    param.insert(dflt.begin(), dflt.end());
  } else {
    for (auto const& str : it) {
      param.emplace(str.asString());
    }
  }
}

void JsonWrapper::get(
    const char* name,
    const std::unordered_map<std::string, std::vector<std::string>>& dflt,
    std::unordered_map<std::string, std::vector<std::string>>& param) const {
  auto cfg = (*m_config)[name];
  param.clear();
  // NOLINTNEXTLINE(readability-container-size-empty)
  if (cfg == Json::nullValue) {
    param = dflt;
  } else {
    if (!cfg.isObject()) {
      throw std::runtime_error("Cannot convert JSON value to object: " +
                               cfg.asString());
    }
    for (auto it = cfg.begin(); it != cfg.end(); ++it) {
      auto key = it.key();
      if (!key.isString()) {
        throw std::runtime_error("Cannot convert JSON value to string: " +
                                 key.asString());
      }
      auto& val = *it;
      if (!val.isArray()) {
        throw std::runtime_error("Cannot convert JSON value to array: " +
                                 val.asString());
      }
      for (auto& str : val) {
        if (!str.isString()) {
          throw std::runtime_error("Cannot convert JSON value to string: " +
                                   str.asString());
        }
        param[key.asString()].push_back(str.asString());
      }
    }
  }
}

void JsonWrapper::get(const char* name,
                      const Json::Value& dflt,
                      Json::Value& param) const {
  param = m_config->get(name, dflt);
}

Json::Value JsonWrapper::get(const char* name, const Json::Value& dflt) const {
  return m_config->get(name, dflt);
}

const Json::Value& JsonWrapper::operator[](const char* name) const {
  return (*m_config)[name];
}

bool JsonWrapper::contains(const char* name) const {
  return m_config->isMember(name);
}
<|endoftext|>


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

#include "atom/browser/atom_browser_client.h"

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

#include "atom/browser/atom_access_token_store.h"
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/atom_quota_permission_context.h"
#include "atom/browser/atom_speech_recognition_manager_delegate.h"
#include "atom/browser/browser.h"
#include "atom/browser/native_window.h"
#include "atom/browser/web_view_manager.h"
#include "atom/browser/window_list.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/strings/string_util.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/printing/printing_message_filter.h"
#include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h"
#include "chrome/browser/speech/tts_message_filter.h"
#include "content/public/browser/browser_ppapi_host.h"
#include "content/public/browser/client_certificate_delegate.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/web_preferences.h"
#include "net/cert/x509_certificate.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "ppapi/host/ppapi_host.h"
#include "ui/base/l10n/l10n_util.h"

namespace atom {

namespace {

// The default routing id of WebContents.
// In Electron each RenderProcessHost only has one WebContents, so this ID is
// same for every WebContents.
int kDefaultRoutingID = 2;

// Next navigation should not restart renderer process.
bool g_suppress_renderer_process_restart = false;

// Custom schemes to be registered to standard.
std::string g_custom_schemes = "";

// Find out the owner of the child process according to |process_id|.
enum ProcessOwner {
  OWNER_NATIVE_WINDOW,
  OWNER_GUEST_WEB_CONTENTS,
  OWNER_NONE,  // it might be devtools though.
};
ProcessOwner GetProcessOwner(int process_id,
                             NativeWindow** window,
                             WebViewManager::WebViewInfo* info) {
  auto web_contents = content::WebContents::FromRenderViewHost(
      content::RenderViewHost::FromID(process_id, kDefaultRoutingID));
  if (!web_contents)
    return OWNER_NONE;

  // First search for NativeWindow.
  for (auto native_window : *WindowList::GetInstance())
    if (web_contents == native_window->web_contents()) {
      *window = native_window;
      return OWNER_NATIVE_WINDOW;
    }

  // Then search for guest WebContents.
  if (WebViewManager::GetInfoForWebContents(web_contents, info))
    return OWNER_GUEST_WEB_CONTENTS;

  return OWNER_NONE;
}

scoped_refptr<net::X509Certificate> ImportCertFromFile(
    const base::FilePath& path) {
  if (path.empty())
    return nullptr;

  std::string cert_data;
  if (!base::ReadFileToString(path, &cert_data))
    return nullptr;

  net::CertificateList certs =
      net::X509Certificate::CreateCertificateListFromBytes(
          cert_data.data(), cert_data.size(),
          net::X509Certificate::FORMAT_AUTO);

  if (certs.empty())
    return nullptr;

  return certs[0];
}

}  // namespace

// static
void AtomBrowserClient::SuppressRendererProcessRestartForOnce() {
  g_suppress_renderer_process_restart = true;
}

void AtomBrowserClient::SetCustomSchemes(
    const std::vector<std::string>& schemes) {
  g_custom_schemes = JoinString(schemes, ',');
}

AtomBrowserClient::AtomBrowserClient() {
}

AtomBrowserClient::~AtomBrowserClient() {
}

void AtomBrowserClient::RenderProcessWillLaunch(
    content::RenderProcessHost* host) {
  int process_id = host->GetID();
  host->AddFilter(new printing::PrintingMessageFilter(process_id));
  host->AddFilter(new TtsMessageFilter(process_id, host->GetBrowserContext()));
}

content::SpeechRecognitionManagerDelegate*
    AtomBrowserClient::CreateSpeechRecognitionManagerDelegate() {
  return new AtomSpeechRecognitionManagerDelegate;
}

content::AccessTokenStore* AtomBrowserClient::CreateAccessTokenStore() {
  return new AtomAccessTokenStore;
}

void AtomBrowserClient::OverrideWebkitPrefs(
    content::RenderViewHost* host, content::WebPreferences* prefs) {
  prefs->javascript_enabled = true;
  prefs->web_security_enabled = true;
  prefs->javascript_can_open_windows_automatically = true;
  prefs->plugins_enabled = true;
  prefs->dom_paste_enabled = true;
  prefs->java_enabled = false;
  prefs->allow_scripts_to_close_windows = true;
  prefs->javascript_can_access_clipboard = true;
  prefs->local_storage_enabled = true;
  prefs->databases_enabled = true;
  prefs->application_cache_enabled = true;
  prefs->allow_universal_access_from_file_urls = true;
  prefs->allow_file_access_from_file_urls = true;
  prefs->experimental_webgl_enabled = true;
  prefs->allow_displaying_insecure_content = false;
  prefs->allow_running_insecure_content = false;

  // Custom preferences of guest page.
  auto web_contents = content::WebContents::FromRenderViewHost(host);
  WebViewManager::WebViewInfo info;
  if (WebViewManager::GetInfoForWebContents(web_contents, &info)) {
    prefs->web_security_enabled = !info.disable_web_security;
    return;
  }

  NativeWindow* window = NativeWindow::FromWebContents(web_contents);
  if (window)
    window->OverrideWebkitPrefs(prefs);
}

std::string AtomBrowserClient::GetApplicationLocale() {
  return l10n_util::GetApplicationLocale("");
}

void AtomBrowserClient::OverrideSiteInstanceForNavigation(
    content::BrowserContext* browser_context,
    content::SiteInstance* current_instance,
    const GURL& url,
    content::SiteInstance** new_instance) {
  if (g_suppress_renderer_process_restart) {
    g_suppress_renderer_process_restart = false;
    return;
  }

  // Restart renderer process for all navigations except "javacript:" scheme.
  if (url.SchemeIs(url::kJavaScriptScheme))
    return;

  *new_instance = content::SiteInstance::CreateForURL(browser_context, url);
}

void AtomBrowserClient::AppendExtraCommandLineSwitches(
    base::CommandLine* command_line,
    int process_id) {
  std::string process_type = command_line->GetSwitchValueASCII("type");
  if (process_type != "renderer")
    return;

  // The registered standard schemes.
  if (!g_custom_schemes.empty())
    command_line->AppendSwitchASCII(switches::kRegisterStandardSchemes,
                                    g_custom_schemes);

#if defined(OS_WIN)
  // Append --app-user-model-id.
  PWSTR current_app_id;
  if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&current_app_id))) {
    command_line->AppendSwitchNative(switches::kAppUserModelId, current_app_id);
    CoTaskMemFree(current_app_id);
  }
#endif

  NativeWindow* window;
  WebViewManager::WebViewInfo info;
  ProcessOwner owner = GetProcessOwner(process_id, &window, &info);

  if (owner == OWNER_NATIVE_WINDOW) {
    window->AppendExtraCommandLineSwitches(command_line);
  } else if (owner == OWNER_GUEST_WEB_CONTENTS) {
    command_line->AppendSwitchASCII(
        switches::kGuestInstanceID, base::IntToString(info.guest_instance_id));
    command_line->AppendSwitchASCII(
        switches::kNodeIntegration, info.node_integration ? "true" : "false");
    if (info.plugins)
      command_line->AppendSwitch(switches::kEnablePlugins);
    if (!info.preload_script.empty())
      command_line->AppendSwitchPath(
          switches::kPreloadScript, info.preload_script);
  }
}

void AtomBrowserClient::DidCreatePpapiPlugin(
    content::BrowserPpapiHost* host) {
  host->GetPpapiHost()->AddHostFactoryFilter(
      make_scoped_ptr(new chrome::ChromeBrowserPepperHostFactory(host)));
}

content::QuotaPermissionContext*
    AtomBrowserClient::CreateQuotaPermissionContext() {
  return new AtomQuotaPermissionContext;
}

void AtomBrowserClient::SelectClientCertificate(
    content::WebContents* web_contents,
    net::SSLCertRequestInfo* cert_request_info,
    scoped_ptr<content::ClientCertificateDelegate> delegate) {
  // --client-certificate=`path`
  auto cmd = base::CommandLine::ForCurrentProcess();
  if (cmd->HasSwitch(switches::kClientCertificate)) {
    auto cert_path = cmd->GetSwitchValuePath(switches::kClientCertificate);
    auto certificate = ImportCertFromFile(cert_path);
    if (certificate.get())
      delegate->ContinueWithCertificate(certificate.get());
    return;
  }

  if (!cert_request_info->client_certs.empty())
    Browser::Get()->ClientCertificateSelector(web_contents,
                                              cert_request_info,
                                              delegate.Pass());
}

brightray::BrowserMainParts* AtomBrowserClient::OverrideCreateBrowserMainParts(
    const content::MainFunctionParams&) {
  v8::V8::Initialize();  // Init V8 before creating main parts.
  return new AtomBrowserMainParts;
}

}  // namespace atom
<commit_msg>Fix a crash issue in GetProcessOwner if no renderer view host is found.<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/atom_browser_client.h"

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

#include "atom/browser/atom_access_token_store.h"
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/atom_quota_permission_context.h"
#include "atom/browser/atom_speech_recognition_manager_delegate.h"
#include "atom/browser/browser.h"
#include "atom/browser/native_window.h"
#include "atom/browser/web_view_manager.h"
#include "atom/browser/window_list.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/strings/string_util.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/printing/printing_message_filter.h"
#include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h"
#include "chrome/browser/speech/tts_message_filter.h"
#include "content/public/browser/browser_ppapi_host.h"
#include "content/public/browser/client_certificate_delegate.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/web_preferences.h"
#include "net/cert/x509_certificate.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "ppapi/host/ppapi_host.h"
#include "ui/base/l10n/l10n_util.h"

namespace atom {

namespace {

// The default routing id of WebContents.
// In Electron each RenderProcessHost only has one WebContents, so this ID is
// same for every WebContents.
int kDefaultRoutingID = 2;

// Next navigation should not restart renderer process.
bool g_suppress_renderer_process_restart = false;

// Custom schemes to be registered to standard.
std::string g_custom_schemes = "";

// Find out the owner of the child process according to |process_id|.
enum ProcessOwner {
  OWNER_NATIVE_WINDOW,
  OWNER_GUEST_WEB_CONTENTS,
  OWNER_NONE,  // it might be devtools though.
};

ProcessOwner GetProcessOwner(int process_id,
                             NativeWindow** window,
                             WebViewManager::WebViewInfo* info) {
  content::RenderViewHost* rvh = content::RenderViewHost::FromID(
      process_id, kDefaultRoutingID);
  if (!rvh)
    return OWNER_NONE;
  auto web_contents = content::WebContents::FromRenderViewHost(rvh);
  if (!web_contents)
    return OWNER_NONE;

  // First search for NativeWindow.
  for (auto native_window : *WindowList::GetInstance())
    if (web_contents == native_window->web_contents()) {
      *window = native_window;
      return OWNER_NATIVE_WINDOW;
    }

  // Then search for guest WebContents.
  if (WebViewManager::GetInfoForWebContents(web_contents, info))
    return OWNER_GUEST_WEB_CONTENTS;

  return OWNER_NONE;
}

scoped_refptr<net::X509Certificate> ImportCertFromFile(
    const base::FilePath& path) {
  if (path.empty())
    return nullptr;

  std::string cert_data;
  if (!base::ReadFileToString(path, &cert_data))
    return nullptr;

  net::CertificateList certs =
      net::X509Certificate::CreateCertificateListFromBytes(
          cert_data.data(), cert_data.size(),
          net::X509Certificate::FORMAT_AUTO);

  if (certs.empty())
    return nullptr;

  return certs[0];
}

}  // namespace

// static
void AtomBrowserClient::SuppressRendererProcessRestartForOnce() {
  g_suppress_renderer_process_restart = true;
}

void AtomBrowserClient::SetCustomSchemes(
    const std::vector<std::string>& schemes) {
  g_custom_schemes = JoinString(schemes, ',');
}

AtomBrowserClient::AtomBrowserClient() {
}

AtomBrowserClient::~AtomBrowserClient() {
}

void AtomBrowserClient::RenderProcessWillLaunch(
    content::RenderProcessHost* host) {
  int process_id = host->GetID();
  host->AddFilter(new printing::PrintingMessageFilter(process_id));
  host->AddFilter(new TtsMessageFilter(process_id, host->GetBrowserContext()));
}

content::SpeechRecognitionManagerDelegate*
    AtomBrowserClient::CreateSpeechRecognitionManagerDelegate() {
  return new AtomSpeechRecognitionManagerDelegate;
}

content::AccessTokenStore* AtomBrowserClient::CreateAccessTokenStore() {
  return new AtomAccessTokenStore;
}

void AtomBrowserClient::OverrideWebkitPrefs(
    content::RenderViewHost* host, content::WebPreferences* prefs) {
  prefs->javascript_enabled = true;
  prefs->web_security_enabled = true;
  prefs->javascript_can_open_windows_automatically = true;
  prefs->plugins_enabled = true;
  prefs->dom_paste_enabled = true;
  prefs->java_enabled = false;
  prefs->allow_scripts_to_close_windows = true;
  prefs->javascript_can_access_clipboard = true;
  prefs->local_storage_enabled = true;
  prefs->databases_enabled = true;
  prefs->application_cache_enabled = true;
  prefs->allow_universal_access_from_file_urls = true;
  prefs->allow_file_access_from_file_urls = true;
  prefs->experimental_webgl_enabled = true;
  prefs->allow_displaying_insecure_content = false;
  prefs->allow_running_insecure_content = false;

  // Custom preferences of guest page.
  auto web_contents = content::WebContents::FromRenderViewHost(host);
  WebViewManager::WebViewInfo info;
  if (WebViewManager::GetInfoForWebContents(web_contents, &info)) {
    prefs->web_security_enabled = !info.disable_web_security;
    return;
  }

  NativeWindow* window = NativeWindow::FromWebContents(web_contents);
  if (window)
    window->OverrideWebkitPrefs(prefs);
}

std::string AtomBrowserClient::GetApplicationLocale() {
  return l10n_util::GetApplicationLocale("");
}

void AtomBrowserClient::OverrideSiteInstanceForNavigation(
    content::BrowserContext* browser_context,
    content::SiteInstance* current_instance,
    const GURL& url,
    content::SiteInstance** new_instance) {
  if (g_suppress_renderer_process_restart) {
    g_suppress_renderer_process_restart = false;
    return;
  }

  // Restart renderer process for all navigations except "javacript:" scheme.
  if (url.SchemeIs(url::kJavaScriptScheme))
    return;

  *new_instance = content::SiteInstance::CreateForURL(browser_context, url);
}

void AtomBrowserClient::AppendExtraCommandLineSwitches(
    base::CommandLine* command_line,
    int process_id) {
  std::string process_type = command_line->GetSwitchValueASCII("type");
  if (process_type != "renderer")
    return;

  // The registered standard schemes.
  if (!g_custom_schemes.empty())
    command_line->AppendSwitchASCII(switches::kRegisterStandardSchemes,
                                    g_custom_schemes);

#if defined(OS_WIN)
  // Append --app-user-model-id.
  PWSTR current_app_id;
  if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&current_app_id))) {
    command_line->AppendSwitchNative(switches::kAppUserModelId, current_app_id);
    CoTaskMemFree(current_app_id);
  }
#endif

  NativeWindow* window;
  WebViewManager::WebViewInfo info;
  ProcessOwner owner = GetProcessOwner(process_id, &window, &info);

  if (owner == OWNER_NATIVE_WINDOW) {
    window->AppendExtraCommandLineSwitches(command_line);
  } else if (owner == OWNER_GUEST_WEB_CONTENTS) {
    command_line->AppendSwitchASCII(
        switches::kGuestInstanceID, base::IntToString(info.guest_instance_id));
    command_line->AppendSwitchASCII(
        switches::kNodeIntegration, info.node_integration ? "true" : "false");
    if (info.plugins)
      command_line->AppendSwitch(switches::kEnablePlugins);
    if (!info.preload_script.empty())
      command_line->AppendSwitchPath(
          switches::kPreloadScript, info.preload_script);
  }
}

void AtomBrowserClient::DidCreatePpapiPlugin(
    content::BrowserPpapiHost* host) {
  host->GetPpapiHost()->AddHostFactoryFilter(
      make_scoped_ptr(new chrome::ChromeBrowserPepperHostFactory(host)));
}

content::QuotaPermissionContext*
    AtomBrowserClient::CreateQuotaPermissionContext() {
  return new AtomQuotaPermissionContext;
}

void AtomBrowserClient::SelectClientCertificate(
    content::WebContents* web_contents,
    net::SSLCertRequestInfo* cert_request_info,
    scoped_ptr<content::ClientCertificateDelegate> delegate) {
  // --client-certificate=`path`
  auto cmd = base::CommandLine::ForCurrentProcess();
  if (cmd->HasSwitch(switches::kClientCertificate)) {
    auto cert_path = cmd->GetSwitchValuePath(switches::kClientCertificate);
    auto certificate = ImportCertFromFile(cert_path);
    if (certificate.get())
      delegate->ContinueWithCertificate(certificate.get());
    return;
  }

  if (!cert_request_info->client_certs.empty())
    Browser::Get()->ClientCertificateSelector(web_contents,
                                              cert_request_info,
                                              delegate.Pass());
}

brightray::BrowserMainParts* AtomBrowserClient::OverrideCreateBrowserMainParts(
    const content::MainFunctionParams&) {
  v8::V8::Initialize();  // Init V8 before creating main parts.
  return new AtomBrowserMainParts;
}

}  // namespace atom
<|endoftext|>


<commit_before>/*
    Crystal Space utility library: string class
    Copyright (C) 1999,2000 by Andrew Zabolotny <bit@eltech.ru>

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

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

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

extern "C" {
#include <ctype.h>
#include <stdarg.h>
}
#include "cssysdef.h"
#include "csutil/csstring.h"
#include "csutil/snprintf.h"

csString::~csString ()
{
  Free ();
}

void csString::SetCapacity (size_t NewSize)
{
  NewSize++;
  if (NewSize == MaxSize)
    return;

  MaxSize = NewSize;
  Data = (char *)realloc (Data, MaxSize);

  if (Size >= MaxSize)
  {
    Size = MaxSize - 1;
    Data [Size] = 0;
  }
}

csString &csString::Truncate (size_t iPos)
{
  if (iPos < Size)
  {
    Size = iPos;
    Data [Size] = 0;
  }
  return *this;
}

csString &csString::DeleteAt (size_t iPos, size_t iCount)
{
#ifdef CS_DEBUG
  if (iPos > Size || iPos + iCount > Size)
    STR_FATAL (("Tried to delete characters beyond the end of the string!\n"))
#endif
  memmove(Data + iPos, Data + iPos + iCount, Size - (iPos + iCount));
  Size = Size - iCount;
  Data[Size] = 0;
  return *this;
}

csString &csString::Insert (size_t iPos, const csString &iStr)
{
#ifdef CS_DEBUG
  if (iPos > Size)
    STR_FATAL (("Inserting `%s' into `%s' at position %lu\n",
      iStr.GetData (), Data, (unsigned long)iPos))
#endif

  if (Data == NULL)
  {
    Append (iStr);
    return *this;
  }

  size_t sl = iStr.Length ();
  size_t NewSize = sl + Length ();
  if (NewSize >= MaxSize)
    SetCapacity (NewSize);
  memmove (Data + iPos + sl, Data + iPos, Size - iPos);
  memcpy (Data + iPos, iStr.GetData (), sl);
  Data [Size = NewSize] = 0;

  return *this;
}

csString &csString::Insert (size_t iPos, const char iChar)
{
#ifdef CS_DEBUG
  if (iPos > Size)
    STR_FATAL (("Inserting `%c' into `%s' at position %lu\n",
      iChar, Data, (unsigned long)iPos))
#endif

  if (Data == NULL)
  {
    Append (iChar);
    return *this;
  }

  size_t NewSize = 1 + Length ();
  if (NewSize >= MaxSize)
    SetCapacity (NewSize);
  memmove (Data + iPos + 1, Data + iPos, Size - iPos);
  Data[iPos] = iChar;
  Data [Size = NewSize] = 0;

  return *this;
}

csString &csString::Overwrite (size_t iPos, const csString &iStr)
{
#ifdef CS_DEBUG
  if (iPos > Size)
    STR_FATAL (("Overwriting `%s' into `%s' at position %lu\n",
      iStr.GetData (), Data, (unsigned long)iPos))
#endif

  if (Data == NULL)
  {
    Append (iStr);
    return *this;
  }

  size_t sl = iStr.Length ();
  size_t NewSize = iPos + sl;
  if (NewSize >= MaxSize)
    SetCapacity (NewSize);
  memcpy (Data + iPos, iStr.GetData (), sl);
  Data [Size = NewSize] = 0;

  return *this;
}

csString &csString::Append (const csString &iStr, size_t iCount)
{
  if (iCount == (size_t)-1)
    iCount = iStr.Length ();

  if (!iCount)
    return *this;

  size_t NewSize = Size + iCount;
  if (NewSize >= MaxSize)
    SetCapacity (NewSize);

  memcpy (Data + Size, iStr.GetData (), iCount);
  Data [Size = NewSize] = 0;

  return *this;
}

csString &csString::Append (const char *iStr, size_t iCount)
{
  if (!iStr) return *this;
  if (iCount == (size_t)-1)
    iCount = strlen (iStr);

  if (!iCount)
    return *this;

  size_t NewSize = Size + iCount;
  if (NewSize >= MaxSize)
    SetCapacity (NewSize);

  memcpy (Data + Size, iStr, iCount);
  Data [Size = NewSize] = 0;

  return *this;
}

csString &csString::LTrim()
{
  size_t i;
  for (i = 0; i < Size; i++)
  {
    if (!isspace (Data[i]))
      return DeleteAt (0, i);
  }
  return *this;
}

csString &csString::RTrim()
{
  if (Size == 0) return *this;

  int i;
  for(i = Size - 1; i >= 0; i--)
  {
    if (!isspace (Data[i]))
    {
      i++;
      return DeleteAt (i, Size - i);
    }
  }
  return *this;
}

csString &csString::Trim()
{
  return LTrim().RTrim();
}

csString &csString::Collapse()
{
  if (Size == 0) return *this;

  size_t start = (size_t) -1;
  Trim();
  size_t i;
  for (i = 1; i < Size - 1; i++)
  {
    if (isspace (Data[i]))
    {
      if (start==(size_t) -1)
      {
		start = i + 1;
		Data[i] = ' '; // Force 'space' as opposed to anything isspace()able.
      }
    }
    else
    {
      // Delete any extra whitespace
      if (start != (size_t)-1 && start != i)
      {
		DeleteAt (start, i - start);
		i -= i - start;
      }
      start = (size_t) -1;
    }
  }
  return *this;
}

csString &csString::Format(const char *format, ...)
{
  va_list args;
  int NewSize = -1;

  va_start(args, format);

  // Keep trying until the buffer is big enough to hold the entire string
  while(NewSize < 0)
  {
    NewSize = cs_vsnprintf(Data, MaxSize, format, args);
    // Increasing by the size of the format streams seems logical enough
    if(NewSize < 0)
      SetCapacity(MaxSize + strlen(format));
    // In this case we know what size it wants
    if((size_t) NewSize>=MaxSize)
    {
      SetCapacity(NewSize + 1);
      NewSize = -1; // Don't break the while loop just yet!
    }
  }

  // Add in the terminating NULL
  Size = NewSize + 1;
  va_end(args);
  return *this;

}

#define STR_FORMAT(TYPE,FMT,SZ) \
csString csString::Format (TYPE v) \
{ char s[SZ]; cs_snprintf (s, SZ, #FMT, v); return csString ().Append (s); }
  STR_FORMAT(short, %hd, 32)
  STR_FORMAT(unsigned short, %hu, 32)
  STR_FORMAT(int, %d, 32)
  STR_FORMAT(unsigned int, %u, 32)
  STR_FORMAT(long, %ld, 32)
  STR_FORMAT(unsigned long, %lu, 32)
  STR_FORMAT(float, %g, 64)
  STR_FORMAT(double, %g, 64)
#undef STR_FORMAT

#define STR_FORMAT_INT(TYPE,FMT) \
csString csString::Format (TYPE v, int width, int prec/*=0*/) \
{ char s[32], s1[32]; \
  cs_snprintf (s1, 32, "%%%d.%d"#FMT, width, prec); cs_snprintf (s, 32, s1, v); \
  return csString ().Append (s); }
  STR_FORMAT_INT(short, hd)
  STR_FORMAT_INT(unsigned short, hu)
  STR_FORMAT_INT(int, d)
  STR_FORMAT_INT(unsigned int, u)
  STR_FORMAT_INT(long, ld)
  STR_FORMAT_INT(unsigned long, lu)
#undef STR_FORMAT_INT

#define STR_FORMAT_FLOAT(TYPE) \
csString csString::Format (TYPE v, int width, int prec/*=6*/) \
{ char s[64], s1[32]; \
  cs_snprintf (s1, 32, "%%%d.%dg", width, prec); cs_snprintf (s, 64, s1, v); \
  return csString ().Append (s); }
  STR_FORMAT_FLOAT(float)
  STR_FORMAT_FLOAT(double)
#undef STR_FORMAT_FLOAT

csString &csString::PadLeft (size_t iNewSize, char iChar)
{
  if (Size < iNewSize)
  {
    SetCapacity (iNewSize);
    if (Size == 0) return *this;
    const size_t toInsert = iNewSize - Size;

    memmove (Data + toInsert, Data, Size);
    size_t x;
    for (x = 0; x < toInsert; x++)
    {
      Data [x] = iChar;
    }
    Data [iNewSize] = '\0';
    Size = iNewSize;
  }
  return *this;
}

csString csString::AsPadLeft (size_t iNewSize, char iChar)
{
  csString newStr = Clone ();
  newStr.PadLeft (iChar, iNewSize);
  return newStr;
}

#define STR_PADLEFT(TYPE) \
csString csString::PadLeft (TYPE v, size_t iNewSize, char iChar) \
{ csString newStr; return newStr.Append (v).PadLeft (iNewSize, iChar); }
  STR_PADLEFT(const csString&)
  STR_PADLEFT(const char*)
  STR_PADLEFT(char)
  STR_PADLEFT(unsigned char)
  STR_PADLEFT(short)
  STR_PADLEFT(unsigned short)
  STR_PADLEFT(int)
  STR_PADLEFT(unsigned int)
  STR_PADLEFT(long)
  STR_PADLEFT(unsigned long)
  STR_PADLEFT(float)
  STR_PADLEFT(double)
#if !defined(CS_USE_FAKE_BOOL_TYPE)
  STR_PADLEFT(bool)
#endif
#undef STR_PADLEFT

csString& csString::PadRight (size_t iNewSize, char iChar)
{
  if (Size < iNewSize)
  {
    SetCapacity (iNewSize);
    size_t x;
    for (x = Size; x < iNewSize; x++)
      Data [x] = iChar;
    Data [iNewSize] = '\0';
    Size = iNewSize;
  }
  return *this;
}

csString csString::AsPadRight (size_t iNewSize, char iChar)
{
  csString newStr = Clone ();
  newStr.PadRight (iChar, iNewSize);
  return newStr;
}

#define STR_PADRIGHT(TYPE) \
csString csString::PadRight (TYPE v, size_t iNewSize, char iChar) \
{ csString newStr; return newStr.Append (v).PadRight (iNewSize, iChar); }
  STR_PADRIGHT(const csString&)
  STR_PADRIGHT(const char*)
  STR_PADRIGHT(char)
  STR_PADRIGHT(unsigned char)
  STR_PADRIGHT(short)
  STR_PADRIGHT(unsigned short)
  STR_PADRIGHT(int)
  STR_PADRIGHT(unsigned int)
  STR_PADRIGHT(long)
  STR_PADRIGHT(unsigned long)
  STR_PADRIGHT(float)
  STR_PADRIGHT(double)
#if !defined(CS_USE_FAKE_BOOL_TYPE)
  STR_PADRIGHT(bool)
#endif
#undef STR_PADRIGHT

csString& csString::PadCenter (size_t iNewSize, char iChar)
{
  if (Size < iNewSize)
  {
    SetCapacity (iNewSize);
    if (Size == 0) return *this;
    const size_t toInsert = iNewSize - Size;

    memmove (Data + toInsert / 2 + toInsert % 2, Data, Size);

    size_t x;
    for (x = 0; x < toInsert / 2 + toInsert % 2; x++)
    {
      Data [x] = iChar;
    }
    for (x = iNewSize - toInsert / 2; x < iNewSize; x++)
    {
      Data [x] = iChar;
    }
    Data [iNewSize] = '\0';
    Size = iNewSize;
  }
  return *this;
}

csString csString::AsPadCenter (size_t iNewSize, char iChar)
{
  csString newStr = Clone ();
  newStr.PadCenter (iChar, iNewSize);
  return newStr;
}

#define STR_PADCENTER(TYPE) \
csString csString::PadCenter (TYPE v, size_t iNewSize, char iChar) \
{ csString newStr; return newStr.Append (v).PadCenter (iNewSize, iChar); }
  STR_PADCENTER(const csString&)
  STR_PADCENTER(const char*)
  STR_PADCENTER(char)
  STR_PADCENTER(unsigned char)
  STR_PADCENTER(short)
  STR_PADCENTER(unsigned short)
  STR_PADCENTER(int)
  STR_PADCENTER(unsigned int)
  STR_PADCENTER(long)
  STR_PADCENTER(unsigned long)
  STR_PADCENTER(float)
  STR_PADCENTER(double)
#if !defined(CS_USE_FAKE_BOOL_TYPE)
  STR_PADCENTER(bool)
#endif
#undef STR_PADCENTER
<commit_msg>Reverted nonworking sprintf()-to-cs_snprintf() changes to Format() methods.<commit_after>/*
    Crystal Space utility library: string class
    Copyright (C) 1999,2000 by Andrew Zabolotny <bit@eltech.ru>

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

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

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

extern "C" {
#include <ctype.h>
#include <stdarg.h>
}
#include "cssysdef.h"
#include "csutil/csstring.h"
#include "csutil/snprintf.h"

csString::~csString ()
{
  Free ();
}

void csString::SetCapacity (size_t NewSize)
{
  NewSize++;
  if (NewSize == MaxSize)
    return;

  MaxSize = NewSize;
  Data = (char *)realloc (Data, MaxSize);

  if (Size >= MaxSize)
  {
    Size = MaxSize - 1;
    Data [Size] = 0;
  }
}

csString &csString::Truncate (size_t iPos)
{
  if (iPos < Size)
  {
    Size = iPos;
    Data [Size] = 0;
  }
  return *this;
}

csString &csString::DeleteAt (size_t iPos, size_t iCount)
{
#ifdef CS_DEBUG
  if (iPos > Size || iPos + iCount > Size)
    STR_FATAL (("Tried to delete characters beyond the end of the string!\n"))
#endif
  memmove(Data + iPos, Data + iPos + iCount, Size - (iPos + iCount));
  Size = Size - iCount;
  Data[Size] = 0;
  return *this;
}

csString &csString::Insert (size_t iPos, const csString &iStr)
{
#ifdef CS_DEBUG
  if (iPos > Size)
    STR_FATAL (("Inserting `%s' into `%s' at position %lu\n",
      iStr.GetData (), Data, (unsigned long)iPos))
#endif

  if (Data == NULL)
  {
    Append (iStr);
    return *this;
  }

  size_t sl = iStr.Length ();
  size_t NewSize = sl + Length ();
  if (NewSize >= MaxSize)
    SetCapacity (NewSize);
  memmove (Data + iPos + sl, Data + iPos, Size - iPos);
  memcpy (Data + iPos, iStr.GetData (), sl);
  Data [Size = NewSize] = 0;

  return *this;
}

csString &csString::Insert (size_t iPos, const char iChar)
{
#ifdef CS_DEBUG
  if (iPos > Size)
    STR_FATAL (("Inserting `%c' into `%s' at position %lu\n",
      iChar, Data, (unsigned long)iPos))
#endif

  if (Data == NULL)
  {
    Append (iChar);
    return *this;
  }

  size_t NewSize = 1 + Length ();
  if (NewSize >= MaxSize)
    SetCapacity (NewSize);
  memmove (Data + iPos + 1, Data + iPos, Size - iPos);
  Data[iPos] = iChar;
  Data [Size = NewSize] = 0;

  return *this;
}

csString &csString::Overwrite (size_t iPos, const csString &iStr)
{
#ifdef CS_DEBUG
  if (iPos > Size)
    STR_FATAL (("Overwriting `%s' into `%s' at position %lu\n",
      iStr.GetData (), Data, (unsigned long)iPos))
#endif

  if (Data == NULL)
  {
    Append (iStr);
    return *this;
  }

  size_t sl = iStr.Length ();
  size_t NewSize = iPos + sl;
  if (NewSize >= MaxSize)
    SetCapacity (NewSize);
  memcpy (Data + iPos, iStr.GetData (), sl);
  Data [Size = NewSize] = 0;

  return *this;
}

csString &csString::Append (const csString &iStr, size_t iCount)
{
  if (iCount == (size_t)-1)
    iCount = iStr.Length ();

  if (!iCount)
    return *this;

  size_t NewSize = Size + iCount;
  if (NewSize >= MaxSize)
    SetCapacity (NewSize);

  memcpy (Data + Size, iStr.GetData (), iCount);
  Data [Size = NewSize] = 0;

  return *this;
}

csString &csString::Append (const char *iStr, size_t iCount)
{
  if (!iStr) return *this;
  if (iCount == (size_t)-1)
    iCount = strlen (iStr);

  if (!iCount)
    return *this;

  size_t NewSize = Size + iCount;
  if (NewSize >= MaxSize)
    SetCapacity (NewSize);

  memcpy (Data + Size, iStr, iCount);
  Data [Size = NewSize] = 0;

  return *this;
}

csString &csString::LTrim()
{
  size_t i;
  for (i = 0; i < Size; i++)
  {
    if (!isspace (Data[i]))
      return DeleteAt (0, i);
  }
  return *this;
}

csString &csString::RTrim()
{
  if (Size == 0) return *this;

  int i;
  for(i = Size - 1; i >= 0; i--)
  {
    if (!isspace (Data[i]))
    {
      i++;
      return DeleteAt (i, Size - i);
    }
  }
  return *this;
}

csString &csString::Trim()
{
  return LTrim().RTrim();
}

csString &csString::Collapse()
{
  if (Size == 0) return *this;

  size_t start = (size_t) -1;
  Trim();
  size_t i;
  for (i = 1; i < Size - 1; i++)
  {
    if (isspace (Data[i]))
    {
      if (start==(size_t) -1)
      {
		start = i + 1;
		Data[i] = ' '; // Force 'space' as opposed to anything isspace()able.
      }
    }
    else
    {
      // Delete any extra whitespace
      if (start != (size_t)-1 && start != i)
      {
		DeleteAt (start, i - start);
		i -= i - start;
      }
      start = (size_t) -1;
    }
  }
  return *this;
}

csString &csString::Format(const char *format, ...)
{
  va_list args;
  int NewSize = -1;

  va_start(args, format);

  // Keep trying until the buffer is big enough to hold the entire string
  while(NewSize < 0)
  {
    NewSize = cs_vsnprintf(Data, MaxSize, format, args);
    // Increasing by the size of the format streams seems logical enough
    if(NewSize < 0)
      SetCapacity(MaxSize + strlen(format));
    // In this case we know what size it wants
    if((size_t) NewSize>=MaxSize)
    {
      SetCapacity(NewSize + 1);
      NewSize = -1; // Don't break the while loop just yet!
    }
  }

  // Add in the terminating NULL
  Size = NewSize + 1;
  va_end(args);
  return *this;

}

#define STR_FORMAT(TYPE,FMT,SZ) \
csString csString::Format (TYPE v) \
{ char s[SZ]; sprintf (s, #FMT, v); return csString ().Append (s); }
  STR_FORMAT(short, %hd, 32)
  STR_FORMAT(unsigned short, %hu, 32)
  STR_FORMAT(int, %d, 32)
  STR_FORMAT(unsigned int, %u, 32)
  STR_FORMAT(long, %ld, 32)
  STR_FORMAT(unsigned long, %lu, 32)
  STR_FORMAT(float, %g, 64)
  STR_FORMAT(double, %g, 64)
#undef STR_FORMAT

#define STR_FORMAT_INT(TYPE,FMT) \
csString csString::Format (TYPE v, int width, int prec/*=0*/) \
{ char s[32], s1[32]; \
  sprintf (s1, "%%%d.%d"#FMT, width, prec); sprintf (s, s1, v); \
  return csString ().Append (s); }
  STR_FORMAT_INT(short, hd)
  STR_FORMAT_INT(unsigned short, hu)
  STR_FORMAT_INT(int, d)
  STR_FORMAT_INT(unsigned int, u)
  STR_FORMAT_INT(long, ld)
  STR_FORMAT_INT(unsigned long, lu)
#undef STR_FORMAT_INT

#define STR_FORMAT_FLOAT(TYPE) \
csString csString::Format (TYPE v, int width, int prec/*=6*/) \
{ char s[64], s1[32]; \
  sprintf (s1, "%%%d.%dg", width, prec); sprintf (s, s1, v); \
  return csString ().Append (s); }
  STR_FORMAT_FLOAT(float)
  STR_FORMAT_FLOAT(double)
#undef STR_FORMAT_FLOAT

csString &csString::PadLeft (size_t iNewSize, char iChar)
{
  if (Size < iNewSize)
  {
    SetCapacity (iNewSize);
    if (Size == 0) return *this;
    const size_t toInsert = iNewSize - Size;

    memmove (Data + toInsert, Data, Size);
    size_t x;
    for (x = 0; x < toInsert; x++)
    {
      Data [x] = iChar;
    }
    Data [iNewSize] = '\0';
    Size = iNewSize;
  }
  return *this;
}

csString csString::AsPadLeft (size_t iNewSize, char iChar)
{
  csString newStr = Clone ();
  newStr.PadLeft (iChar, iNewSize);
  return newStr;
}

#define STR_PADLEFT(TYPE) \
csString csString::PadLeft (TYPE v, size_t iNewSize, char iChar) \
{ csString newStr; return newStr.Append (v).PadLeft (iNewSize, iChar); }
  STR_PADLEFT(const csString&)
  STR_PADLEFT(const char*)
  STR_PADLEFT(char)
  STR_PADLEFT(unsigned char)
  STR_PADLEFT(short)
  STR_PADLEFT(unsigned short)
  STR_PADLEFT(int)
  STR_PADLEFT(unsigned int)
  STR_PADLEFT(long)
  STR_PADLEFT(unsigned long)
  STR_PADLEFT(float)
  STR_PADLEFT(double)
#if !defined(CS_USE_FAKE_BOOL_TYPE)
  STR_PADLEFT(bool)
#endif
#undef STR_PADLEFT

csString& csString::PadRight (size_t iNewSize, char iChar)
{
  if (Size < iNewSize)
  {
    SetCapacity (iNewSize);
    size_t x;
    for (x = Size; x < iNewSize; x++)
      Data [x] = iChar;
    Data [iNewSize] = '\0';
    Size = iNewSize;
  }
  return *this;
}

csString csString::AsPadRight (size_t iNewSize, char iChar)
{
  csString newStr = Clone ();
  newStr.PadRight (iChar, iNewSize);
  return newStr;
}

#define STR_PADRIGHT(TYPE) \
csString csString::PadRight (TYPE v, size_t iNewSize, char iChar) \
{ csString newStr; return newStr.Append (v).PadRight (iNewSize, iChar); }
  STR_PADRIGHT(const csString&)
  STR_PADRIGHT(const char*)
  STR_PADRIGHT(char)
  STR_PADRIGHT(unsigned char)
  STR_PADRIGHT(short)
  STR_PADRIGHT(unsigned short)
  STR_PADRIGHT(int)
  STR_PADRIGHT(unsigned int)
  STR_PADRIGHT(long)
  STR_PADRIGHT(unsigned long)
  STR_PADRIGHT(float)
  STR_PADRIGHT(double)
#if !defined(CS_USE_FAKE_BOOL_TYPE)
  STR_PADRIGHT(bool)
#endif
#undef STR_PADRIGHT

csString& csString::PadCenter (size_t iNewSize, char iChar)
{
  if (Size < iNewSize)
  {
    SetCapacity (iNewSize);
    if (Size == 0) return *this;
    const size_t toInsert = iNewSize - Size;

    memmove (Data + toInsert / 2 + toInsert % 2, Data, Size);

    size_t x;
    for (x = 0; x < toInsert / 2 + toInsert % 2; x++)
    {
      Data [x] = iChar;
    }
    for (x = iNewSize - toInsert / 2; x < iNewSize; x++)
    {
      Data [x] = iChar;
    }
    Data [iNewSize] = '\0';
    Size = iNewSize;
  }
  return *this;
}

csString csString::AsPadCenter (size_t iNewSize, char iChar)
{
  csString newStr = Clone ();
  newStr.PadCenter (iChar, iNewSize);
  return newStr;
}

#define STR_PADCENTER(TYPE) \
csString csString::PadCenter (TYPE v, size_t iNewSize, char iChar) \
{ csString newStr; return newStr.Append (v).PadCenter (iNewSize, iChar); }
  STR_PADCENTER(const csString&)
  STR_PADCENTER(const char*)
  STR_PADCENTER(char)
  STR_PADCENTER(unsigned char)
  STR_PADCENTER(short)
  STR_PADCENTER(unsigned short)
  STR_PADCENTER(int)
  STR_PADCENTER(unsigned int)
  STR_PADCENTER(long)
  STR_PADCENTER(unsigned long)
  STR_PADCENTER(float)
  STR_PADCENTER(double)
#if !defined(CS_USE_FAKE_BOOL_TYPE)
  STR_PADCENTER(bool)
#endif
#undef STR_PADCENTER
<|endoftext|>


<commit_before><commit_msg>glTF: Removing one model breaks an other model<commit_after><|endoftext|>


<commit_before><commit_msg>GSOC work, small code fixes<commit_after><|endoftext|>


<commit_before><commit_msg>Isilon: don't warn for multiple remote parquet blocks<commit_after><|endoftext|>


<commit_before>#include <JointPythonCore.h>

#include <memory>
#include <string>

#include <binding/Binding.hpp>
#include <pyjoint/Array.hpp>
#include <pyjoint/Globals.hpp>
#include <pyjoint/InterfaceDescriptor.hpp>
#include <pyjoint/Module.hpp>
#include <pyjoint/ProxyBase.hpp>
#include <pyjoint/TypeDescriptor.hpp>
#include <utils/PyObjectHolder.hpp>

JOINT_DEVKIT_LOGGER("Joint.Python.Core")

extern "C"
{

	Joint_Error JointPythonCore_MakeBinding(Joint_BindingHandle* outBinding)
	{
		using namespace joint_python::binding;

		GetLogger().Info() << "MakeBinding";

		Joint_BindingDesc binding_desc = { };
		binding_desc.name            = "python";
		binding_desc.deinitBinding   = &Binding::Deinit;
		binding_desc.loadModule      = &Binding::LoadModule;
		binding_desc.unloadModule    = &Binding::UnloadModule;
		binding_desc.getRootObject   = &Binding::GetRootObject;
		binding_desc.invokeMethod    = &Binding::InvokeMethod;
		binding_desc.releaseObject   = &Binding::ReleaseObject;
		binding_desc.castObject      = &Binding::CastObject;

		std::unique_ptr<Binding> binding(new Binding);

		Joint_Error ret = Joint_MakeBinding(binding_desc, binding.get(), outBinding);
		if (ret != JOINT_ERROR_NONE)
			GetLogger().Error() << "Joint_MakeBinding failed: " << ret;
		else
			binding.release();

		return ret;
	}

}

static PyMethodDef g_methods[] = {
	{"Cast", (PyCFunction)joint_python::pyjoint::Cast, METH_VARARGS, "Cast" },
	{NULL, NULL, 0, NULL}
};

#if PY_VERSION_HEX >= 0x03000000
static struct PyModuleDef g_module = {
# if PY_VERSION_HEX >= 0x03020000
	PyModuleDef_HEAD_INIT,
# else
	{
		PyObject_HEAD_INIT(NULL)
		NULL, /* m_init */
		0,    /* m_index */
		NULL, /* m_copy */
	},
# endif
   "pyjoint",
   NULL,
   -1,
   g_methods
};
#endif

#define ADD_TYPE_TO_PYTHON_MODULE(Type_) \
	if (!Type_##_type.tp_new) \
		Type_##_type.tp_new = PyType_GenericNew; \
	if (PyType_Ready(&Type_##_type) < 0) \
	{ \
		PyErr_SetString(PyExc_RuntimeError, "Import error: Could not initialize pyjoint." #Type_ " type!"); \
		RETURN_ERROR; \
	} \
	Py_INCREF(&Type_##_type); \
	if (PyModule_AddObject(m, #Type_, reinterpret_cast<PyObject*>(&Type_##_type)) != 0) \
	{ \
		Py_DECREF(&Type_##_type); \
		PyErr_SetString(PyExc_RuntimeError, "Import error: Could not add pyjoint." #Type_ " type to the module!"); \
		RETURN_ERROR; \
	}

#if PY_VERSION_HEX >= 0x03000000
#	define STR_LITERAL_TYPE const char*
#	define RETURN_ERROR return NULL
PyMODINIT_FUNC JointPythonCore_InitModule_py3(void)
#else
#	define STR_LITERAL_TYPE char*
#	define RETURN_ERROR return
PyMODINIT_FUNC JointPythonCore_InitModule_py2(void)
#endif
{
	using namespace joint_python;
	using namespace joint_python::pyjoint;

#if PY_VERSION_HEX >= 0x03000000
	PyObjectHolder m(PyModule_Create(&g_module));
#else
	PyObjectHolder m(Py_InitModule((STR_LITERAL_TYPE) "pyjoint", g_methods));
#endif
	if (!m)
	{
		PyErr_SetString(PyExc_RuntimeError, "Import error: Could not initialize module object!");
		RETURN_ERROR;
	}

	ADD_TYPE_TO_PYTHON_MODULE(Array);
	ADD_TYPE_TO_PYTHON_MODULE(InterfaceDescriptor);
	ADD_TYPE_TO_PYTHON_MODULE(JointException);
	ADD_TYPE_TO_PYTHON_MODULE(Module);
	ADD_TYPE_TO_PYTHON_MODULE(ProxyBase);
	ADD_TYPE_TO_PYTHON_MODULE(TypeDescriptor);

    InvalidInterfaceChecksumException = PyErr_NewException("pyjoint.InvalidInterfaceChecksumException", NULL, NULL);
    Py_INCREF(InvalidInterfaceChecksumException);
    PyModule_AddObject(m, "InvalidInterfaceChecksumException", InvalidInterfaceChecksumException);

#if PY_VERSION_HEX >= 0x03000000
	return m.Release();
#else
	m.Release();
#endif
}
<commit_msg>Fixed a warning<commit_after>#include <JointPythonCore.h>

#include <memory>
#include <string>

#include <binding/Binding.hpp>
#include <pyjoint/Array.hpp>
#include <pyjoint/Globals.hpp>
#include <pyjoint/InterfaceDescriptor.hpp>
#include <pyjoint/Module.hpp>
#include <pyjoint/ProxyBase.hpp>
#include <pyjoint/TypeDescriptor.hpp>
#include <utils/PyObjectHolder.hpp>

JOINT_DEVKIT_LOGGER("Joint.Python.Core")

extern "C"
{

	Joint_Error JointPythonCore_MakeBinding(Joint_BindingHandle* outBinding)
	{
		using namespace joint_python::binding;

		GetLogger().Info() << "MakeBinding";

		Joint_BindingDesc binding_desc = { };
		binding_desc.name            = "python";
		binding_desc.deinitBinding   = &Binding::Deinit;
		binding_desc.loadModule      = &Binding::LoadModule;
		binding_desc.unloadModule    = &Binding::UnloadModule;
		binding_desc.getRootObject   = &Binding::GetRootObject;
		binding_desc.invokeMethod    = &Binding::InvokeMethod;
		binding_desc.releaseObject   = &Binding::ReleaseObject;
		binding_desc.castObject      = &Binding::CastObject;

		std::unique_ptr<Binding> binding(new Binding);

		Joint_Error ret = Joint_MakeBinding(binding_desc, binding.get(), outBinding);
		if (ret != JOINT_ERROR_NONE)
			GetLogger().Error() << "Joint_MakeBinding failed: " << ret;
		else
			binding.release();

		return ret;
	}

}

static PyMethodDef g_methods[] = {
	{"Cast", (PyCFunction)joint_python::pyjoint::Cast, METH_VARARGS, "Cast" },
	{NULL, NULL, 0, NULL}
};

#if PY_VERSION_HEX >= 0x03000000
static struct PyModuleDef g_module = {
# if PY_VERSION_HEX >= 0x03020000
	PyModuleDef_HEAD_INIT,
# else
	{
		PyObject_HEAD_INIT(NULL)
		NULL, /* m_init */
		0,    /* m_index */
		NULL, /* m_copy */
	},
# endif
   "pyjoint",
   NULL,
   -1,
   g_methods
};
#endif

#define ADD_TYPE_TO_PYTHON_MODULE(Type_) \
	if (!Type_##_type.tp_new) \
		Type_##_type.tp_new = PyType_GenericNew; \
	if (PyType_Ready(&Type_##_type) < 0) \
	{ \
		PyErr_SetString(PyExc_RuntimeError, "Import error: Could not initialize pyjoint." #Type_ " type!"); \
		RETURN_ERROR; \
	} \
	Py_INCREF(&Type_##_type); \
	if (PyModule_AddObject(m, #Type_, reinterpret_cast<PyObject*>(&Type_##_type)) != 0) \
	{ \
		Py_DECREF(&Type_##_type); \
		PyErr_SetString(PyExc_RuntimeError, "Import error: Could not add pyjoint." #Type_ " type to the module!"); \
		RETURN_ERROR; \
	}

#if PY_VERSION_HEX >= 0x03000000
#	define STR_LITERAL_TYPE const char*
#	define RETURN_ERROR return NULL
PyMODINIT_FUNC JointPythonCore_InitModule_py3(void)
#else
#	define STR_LITERAL_TYPE char*
#	define RETURN_ERROR return
PyMODINIT_FUNC JointPythonCore_InitModule_py2(void)
#endif
{
	using namespace joint_python;
	using namespace joint_python::pyjoint;

#if PY_VERSION_HEX >= 0x03000000
	PyObjectHolder m(PyModule_Create(&g_module));
#else
	PyObjectHolder m(Py_InitModule((STR_LITERAL_TYPE) "pyjoint", g_methods));
#endif
	if (!m)
	{
		PyErr_SetString(PyExc_RuntimeError, "Import error: Could not initialize module object!");
		RETURN_ERROR;
	}

	ADD_TYPE_TO_PYTHON_MODULE(Array);
	ADD_TYPE_TO_PYTHON_MODULE(InterfaceDescriptor);
	ADD_TYPE_TO_PYTHON_MODULE(JointException);
	ADD_TYPE_TO_PYTHON_MODULE(Module);
	ADD_TYPE_TO_PYTHON_MODULE(ProxyBase);
	ADD_TYPE_TO_PYTHON_MODULE(TypeDescriptor);

    InvalidInterfaceChecksumException = PyErr_NewException((STR_LITERAL_TYPE)"pyjoint.InvalidInterfaceChecksumException", NULL, NULL);
    Py_INCREF(InvalidInterfaceChecksumException);
    PyModule_AddObject(m, "InvalidInterfaceChecksumException", InvalidInterfaceChecksumException);

#if PY_VERSION_HEX >= 0x03000000
	return m.Release();
#else
	m.Release();
#endif
}
<|endoftext|>


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

// boost
#include <boost/python.hpp>
#include <boost/python/def.hpp>

// mapnik
#include <mapnik/geometry.hpp>

void export_geometry()
{
    using namespace boost::python;
    using mapnik::geometry_type;

    class_<geometry_type, boost::noncopyable>("GeometryType",no_init)
        .def("envelope",&geometry_type::envelope)
        // .def("__str__",&geometry_type::to_string)
        .def("type",&geometry_type::type)
        // TODO add other geometry_type methods
        ;
}
<commit_msg>+ use Geometry2d to be compatible<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

// boost
#include <boost/python.hpp>
#include <boost/python/def.hpp>

// mapnik
#include <mapnik/geometry.hpp>

void export_geometry()
{
    using namespace boost::python;
    using mapnik::geometry_type;

    class_<geometry_type, boost::noncopyable>("Geometry2d",no_init)
        .def("envelope",&geometry_type::envelope)
        // .def("__str__",&geometry_type::to_string)
        .def("type",&geometry_type::type)
        // TODO add other geometry_type methods
        ;
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015, 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 "bistro/bistro/remote/RemoteWorker.h"

DEFINE_int32(
  heartbeat_grace_period, 60,
  "Each remote worker tells us their heartbeat period. If the time since "
  "the last heartbeat exceeds that period, plus the grace period in seconds, "
  "the worker is marked unhealthy. Values below 1 get bumped to 1."
);
DEFINE_int32(
  healthcheck_period, 60,
  "Every how many seconds should the scheduler send a healthcheck to each "
  "remote worker? Values below 1 get bumped to 1."
);
DEFINE_int32(
  healthcheck_grace_period, 60,
  "If the time since we **sent** the last successful healthcheck exceeds "
  "healthcheck_period + healtcheck_grace_period, we mark the remote worker "
  "unhealthy. Values below 1 get bumped to 1."
);
DEFINE_int32(
  lose_unhealthy_worker_after, 180,
  "If a remote worker is unhealthy for this many seconds, consider it lost. "
  "This means we decide that its tasks failed, and start to send it suicide "
  "commands. On startup, a scheduler waits for healthcheck_period + "
  "healthcheck_grace_period + worker_check_interval + "
  "lose_unhealthy_worker_after to ensure all live workers have connected "
  "before running tasks. This value should low enough to be tolerable but "
  "high enough that heavy worker load does not typically cause it to be lost. "
  "In particular, aim for over 2*healthcheck_period + worker_check_interval "
  "to avoid losing workers due to one missed healthcheck. Values below 1 "
  "get bumped to 1."
);
DEFINE_int32(worker_check_interval, 5,
  "How often to check if a worker is due for a healthcheck, became unhealthy "
  "or lost, etc. Keep this low to keep worker state up-to-date. Checks have "
  "a cost for each worker, so large deployments will need to increase this. "
  "Values below 1 get bumped to 1."
);
<commit_msg>Bump the default value of --lose_unhealthy_worker_after<commit_after>/*
 *  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 "bistro/bistro/remote/RemoteWorker.h"

DEFINE_int32(
  heartbeat_grace_period, 60,
  "Each remote worker tells us their heartbeat period. If the time since "
  "the last heartbeat exceeds that period, plus the grace period in seconds, "
  "the worker is marked unhealthy. Values below 1 get bumped to 1."
);
DEFINE_int32(
  healthcheck_period, 60,
  "Every how many seconds should the scheduler send a healthcheck to each "
  "remote worker? Values below 1 get bumped to 1."
);
DEFINE_int32(
  healthcheck_grace_period, 60,
  "If the time since we **sent** the last successful healthcheck exceeds "
  "healthcheck_period + healtcheck_grace_period, we mark the remote worker "
  "unhealthy. Values below 1 get bumped to 1."
);
DEFINE_int32(
  lose_unhealthy_worker_after, 500,
  "If a remote worker is unhealthy for this many seconds, consider it lost. "
  "This means we decide that its tasks failed, and start to send it suicide "
  "commands. On startup, a scheduler waits for lose_unhealthy_worker_after + "
  "healthcheck_period + healthcheck_grace_period + worker_check_interval + "
  "lose_unhealthy_worker_after + worker_suicide_* to ensure all live workers "
  "have connected before running tasks. This flag should low enough to keep "
  "this wait tolerable but high enough that heavy IO on workers does not "
  "cause them to be lost. In principle, a value over 2*healthcheck_period + "
  "4*heartbeat_period + 2*worker_check_interval should suffice, but in "
  "practice a higher safety factor reduces the frequency of restarts of a "
  "crash-looping worker, which in turn makes it less disruptive to reaching "
  "a worker-set consensus among the other workers -- see the note on worker "
  "turnover in README.worker_set_consensus. Values below 1 get bumped to 1."
);
DEFINE_int32(worker_check_interval, 5,
  "How often to check if a worker is due for a healthcheck, became unhealthy "
  "or lost, etc. Keep this low to keep worker state up-to-date. Checks have "
  "a cost for each worker, so large deployments will need to increase this. "
  "Values below 1 get bumped to 1."
);
<|endoftext|>