<commit_before>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.

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

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

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

// Implementation of HostExecutor class [of those methods not defined in the
// class declaration].
#include "tensorflow/stream_executor/host/host_gpu_executor.h"

#include <string.h>

#include "tensorflow/core/platform/profile_utils/cpu_utils.h"
#include "tensorflow/stream_executor/host/host_platform_id.h"
#include "tensorflow/stream_executor/host/host_stream.h"
#include "tensorflow/stream_executor/host/host_timer.h"
#include "tensorflow/stream_executor/lib/statusor.h"
#include "tensorflow/stream_executor/plugin_registry.h"

namespace gpu = ::perftools::gputools;

namespace perftools {
namespace gputools {
namespace host {

HostStream *AsHostStream(Stream *stream) {
  DCHECK(stream != nullptr);
  return dynamic_cast<HostStream *>(stream->implementation());
}

HostExecutor::HostExecutor(const PluginConfig &plugin_config)
    : plugin_config_(plugin_config) {}

HostExecutor::~HostExecutor() {}

void *HostExecutor::Allocate(uint64 size) { return new char[size]; }

void *HostExecutor::AllocateSubBuffer(DeviceMemoryBase *parent,
                                      uint64 offset_bytes, uint64 size_bytes) {
  return reinterpret_cast<char *>(parent->opaque()) + offset_bytes;
}

void HostExecutor::Deallocate(DeviceMemoryBase *mem) {
  if (!mem->is_sub_buffer()) {
    delete[] static_cast<char *>(mem->opaque());
  }
}

bool HostExecutor::SynchronousMemZero(DeviceMemoryBase *location, uint64 size) {
  memset(location->opaque(), 0, size);
  return true;
}

bool HostExecutor::SynchronousMemSet(DeviceMemoryBase *location, int value,
                                     uint64 size) {
  memset(location->opaque(), value, size);
  return true;
}

bool HostExecutor::Memcpy(Stream *stream, void *host_dst,
                          const DeviceMemoryBase &gpu_src, uint64 size) {
  // Enqueue the [asynchronous] memcpy on the stream (HostStream) associated
  // with the HostExecutor.
  void *src_mem = const_cast<void *>(gpu_src.opaque());
  AsHostStream(stream)->EnqueueTask(
      [host_dst, src_mem, size]() { memcpy(host_dst, src_mem, size); });
  return true;
}

bool HostExecutor::Memcpy(Stream *stream, DeviceMemoryBase *gpu_dst,
                          const void *host_src, uint64 size) {
  void *dst_mem = gpu_dst->opaque();
  // Enqueue the [asynchronous] memcpy on the stream (HostStream) associated
  // with the HostExecutor.
  AsHostStream(stream)->EnqueueTask(
      [dst_mem, host_src, size]() { memcpy(dst_mem, host_src, size); });
  return true;
}

bool HostExecutor::MemcpyDeviceToDevice(Stream *stream,
                                        DeviceMemoryBase *gpu_dst,
                                        const DeviceMemoryBase &gpu_src,
                                        uint64 size) {
  void *dst_mem = gpu_dst->opaque();
  void *src_mem = const_cast<void *>(gpu_src.opaque());
  // Enqueue this [asynchronous] "device-to-device" (i.e., host-to-host, given
  // the nature of the HostExecutor) memcpy  on the stream (HostStream)
  // associated with the HostExecutor.
  AsHostStream(stream)->EnqueueTask(
      [src_mem, dst_mem, size]() { memcpy(src_mem, dst_mem, size); });
  return true;
}

bool HostExecutor::MemZero(Stream *stream, DeviceMemoryBase *location,
                           uint64 size) {
  void *gpu_mem = location->opaque();
  // Enqueue the [asynchronous] memzero on the stream (HostStream) associated
  // with the HostExecutor.
  AsHostStream(stream)->EnqueueTask(
      [gpu_mem, size]() { memset(gpu_mem, 0, size); });
  return true;
}

bool HostExecutor::Memset(Stream *stream, DeviceMemoryBase *location,
                          uint8 pattern, uint64 size) {
  void *gpu_mem = location->opaque();
  // Enqueue the [asynchronous] memzero on the stream (HostStream) associated
  // with the HostExecutor.
  AsHostStream(stream)->EnqueueTask(
      [gpu_mem, size, pattern]() { memset(gpu_mem, pattern, size); });
  return true;
}

bool HostExecutor::Memset32(Stream *stream, DeviceMemoryBase *location,
                            uint32 pattern, uint64 size) {
  void *gpu_mem = location->opaque();
  // Enqueue the [asynchronous] memzero on the stream (HostStream) associated
  // with the HostExecutor.
  AsHostStream(stream)->EnqueueTask(
      [gpu_mem, size, pattern]() { memset(gpu_mem, pattern, size); });
  return true;
}

port::Status HostExecutor::SynchronousMemcpy(DeviceMemoryBase *gpu_dst,
                                             const void *host_src,
                                             uint64 size) {
  memcpy(gpu_dst->opaque(), host_src, size);
  return port::Status::OK();
}

port::Status HostExecutor::SynchronousMemcpy(void *host_dst,
                                             const DeviceMemoryBase &gpu_src,
                                             uint64 size) {
  memcpy(host_dst, gpu_src.opaque(), size);
  return port::Status::OK();
}

port::Status HostExecutor::SynchronousMemcpyDeviceToDevice(
    DeviceMemoryBase *gpu_dst, const DeviceMemoryBase &gpu_src, uint64 size) {
  memcpy(gpu_dst->opaque(), gpu_src.opaque(), size);
  return port::Status::OK();
}

bool HostExecutor::HostCallback(Stream *stream,
                                std::function<void()> callback) {
  AsHostStream(stream)->EnqueueTask(callback);
  return true;
}

bool HostExecutor::AllocateStream(Stream *stream) { return true; }

void HostExecutor::DeallocateStream(Stream *stream) {}

bool HostExecutor::CreateStreamDependency(Stream *dependent, Stream *other) {
  AsHostStream(dependent)->EnqueueTask(
      [other]() { other->BlockHostUntilDone(); });
  AsHostStream(dependent)->BlockUntilDone();
  return true;
}

bool HostExecutor::StartTimer(Stream *stream, Timer *timer) {
  dynamic_cast<HostTimer *>(timer->implementation())->Start(stream);
  return true;
}

bool HostExecutor::StopTimer(Stream *stream, Timer *timer) {
  dynamic_cast<HostTimer *>(timer->implementation())->Stop(stream);
  return true;
}

bool HostExecutor::BlockHostUntilDone(Stream *stream) {
  AsHostStream(stream)->BlockUntilDone();
  return true;
}

DeviceDescription *HostExecutor::PopulateDeviceDescription() const {
  internal::DeviceDescriptionBuilder builder;

  builder.set_device_address_bits(64);

  // TODO(rspringer): How to report a value that's based in reality but that
  // doesn't result in thrashing or other badness? 4GiB chosen arbitrarily.
  builder.set_device_memory_size(static_cast<uint64>(4) * 1024 * 1024 * 1024);

  builder.set_clock_rate_ghz(
      static_cast<float>(
          tensorflow::profile_utils::CpuUtils::GetCycleCounterFrequency()) /
      1e9);

  auto built = builder.Build();
  return built.release();
}

bool HostExecutor::SupportsBlas() const {
  return PluginRegistry::Instance()
      ->GetFactory<PluginRegistry::BlasFactory>(kHostPlatformId,
                                                plugin_config_.blas())
      .ok();
}

blas::BlasSupport *HostExecutor::CreateBlas() {
  PluginRegistry *registry = PluginRegistry::Instance();
  port::StatusOr<PluginRegistry::BlasFactory> status =
      registry->GetFactory<PluginRegistry::BlasFactory>(kHostPlatformId,
                                                        plugin_config_.blas());
  if (!status.ok()) {
    LOG(ERROR) << "Unable to retrieve BLAS factory: "
               << status.status().error_message();
    return nullptr;
  }

  return status.ValueOrDie()(this);
}

bool HostExecutor::SupportsFft() const {
  return PluginRegistry::Instance()
      ->GetFactory<PluginRegistry::FftFactory>(kHostPlatformId,
                                               plugin_config_.fft())
      .ok();
}

fft::FftSupport *HostExecutor::CreateFft() {
  PluginRegistry *registry = PluginRegistry::Instance();
  port::StatusOr<PluginRegistry::FftFactory> status =
      registry->GetFactory<PluginRegistry::FftFactory>(kHostPlatformId,
                                                       plugin_config_.fft());
  if (!status.ok()) {
    LOG(ERROR) << "Unable to retrieve FFT factory: "
               << status.status().error_message();
    return nullptr;
  }

  return status.ValueOrDie()(this);
}

bool HostExecutor::SupportsRng() const {
  return PluginRegistry::Instance()
      ->GetFactory<PluginRegistry::RngFactory>(kHostPlatformId,
                                               plugin_config_.rng())
      .ok();
}

rng::RngSupport *HostExecutor::CreateRng() {
  PluginRegistry *registry = PluginRegistry::Instance();
  port::StatusOr<PluginRegistry::RngFactory> status =
      registry->GetFactory<PluginRegistry::RngFactory>(kHostPlatformId,
                                                       plugin_config_.rng());
  if (!status.ok()) {
    LOG(ERROR) << "Unable to retrieve RNG factory: "
               << status.status().error_message();
    return nullptr;
  }

  return status.ValueOrDie()(this);
}

}  // namespace host
}  // namespace gputools
}  // namespace perftools
<commit_msg>[SE:Host] Temporarily revert the determination of host frequency.<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.

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

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

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

// Implementation of HostExecutor class [of those methods not defined in the
// class declaration].
#include "tensorflow/stream_executor/host/host_gpu_executor.h"

#include <string.h>

#include "tensorflow/core/platform/profile_utils/cpu_utils.h"
#include "tensorflow/stream_executor/host/host_platform_id.h"
#include "tensorflow/stream_executor/host/host_stream.h"
#include "tensorflow/stream_executor/host/host_timer.h"
#include "tensorflow/stream_executor/lib/statusor.h"
#include "tensorflow/stream_executor/plugin_registry.h"

namespace gpu = ::perftools::gputools;

bool FLAGS_stream_executor_cpu_real_clock_rate = false;

namespace perftools {
namespace gputools {
namespace host {

HostStream *AsHostStream(Stream *stream) {
  DCHECK(stream != nullptr);
  return dynamic_cast<HostStream *>(stream->implementation());
}

HostExecutor::HostExecutor(const PluginConfig &plugin_config)
    : plugin_config_(plugin_config) {}

HostExecutor::~HostExecutor() {}

void *HostExecutor::Allocate(uint64 size) { return new char[size]; }

void *HostExecutor::AllocateSubBuffer(DeviceMemoryBase *parent,
                                      uint64 offset_bytes, uint64 size_bytes) {
  return reinterpret_cast<char *>(parent->opaque()) + offset_bytes;
}

void HostExecutor::Deallocate(DeviceMemoryBase *mem) {
  if (!mem->is_sub_buffer()) {
    delete[] static_cast<char *>(mem->opaque());
  }
}

bool HostExecutor::SynchronousMemZero(DeviceMemoryBase *location, uint64 size) {
  memset(location->opaque(), 0, size);
  return true;
}

bool HostExecutor::SynchronousMemSet(DeviceMemoryBase *location, int value,
                                     uint64 size) {
  memset(location->opaque(), value, size);
  return true;
}

bool HostExecutor::Memcpy(Stream *stream, void *host_dst,
                          const DeviceMemoryBase &gpu_src, uint64 size) {
  // Enqueue the [asynchronous] memcpy on the stream (HostStream) associated
  // with the HostExecutor.
  void *src_mem = const_cast<void *>(gpu_src.opaque());
  AsHostStream(stream)->EnqueueTask(
      [host_dst, src_mem, size]() { memcpy(host_dst, src_mem, size); });
  return true;
}

bool HostExecutor::Memcpy(Stream *stream, DeviceMemoryBase *gpu_dst,
                          const void *host_src, uint64 size) {
  void *dst_mem = gpu_dst->opaque();
  // Enqueue the [asynchronous] memcpy on the stream (HostStream) associated
  // with the HostExecutor.
  AsHostStream(stream)->EnqueueTask(
      [dst_mem, host_src, size]() { memcpy(dst_mem, host_src, size); });
  return true;
}

bool HostExecutor::MemcpyDeviceToDevice(Stream *stream,
                                        DeviceMemoryBase *gpu_dst,
                                        const DeviceMemoryBase &gpu_src,
                                        uint64 size) {
  void *dst_mem = gpu_dst->opaque();
  void *src_mem = const_cast<void *>(gpu_src.opaque());
  // Enqueue this [asynchronous] "device-to-device" (i.e., host-to-host, given
  // the nature of the HostExecutor) memcpy  on the stream (HostStream)
  // associated with the HostExecutor.
  AsHostStream(stream)->EnqueueTask(
      [src_mem, dst_mem, size]() { memcpy(src_mem, dst_mem, size); });
  return true;
}

bool HostExecutor::MemZero(Stream *stream, DeviceMemoryBase *location,
                           uint64 size) {
  void *gpu_mem = location->opaque();
  // Enqueue the [asynchronous] memzero on the stream (HostStream) associated
  // with the HostExecutor.
  AsHostStream(stream)->EnqueueTask(
      [gpu_mem, size]() { memset(gpu_mem, 0, size); });
  return true;
}

bool HostExecutor::Memset(Stream *stream, DeviceMemoryBase *location,
                          uint8 pattern, uint64 size) {
  void *gpu_mem = location->opaque();
  // Enqueue the [asynchronous] memzero on the stream (HostStream) associated
  // with the HostExecutor.
  AsHostStream(stream)->EnqueueTask(
      [gpu_mem, size, pattern]() { memset(gpu_mem, pattern, size); });
  return true;
}

bool HostExecutor::Memset32(Stream *stream, DeviceMemoryBase *location,
                            uint32 pattern, uint64 size) {
  void *gpu_mem = location->opaque();
  // Enqueue the [asynchronous] memzero on the stream (HostStream) associated
  // with the HostExecutor.
  AsHostStream(stream)->EnqueueTask(
      [gpu_mem, size, pattern]() { memset(gpu_mem, pattern, size); });
  return true;
}

port::Status HostExecutor::SynchronousMemcpy(DeviceMemoryBase *gpu_dst,
                                             const void *host_src,
                                             uint64 size) {
  memcpy(gpu_dst->opaque(), host_src, size);
  return port::Status::OK();
}

port::Status HostExecutor::SynchronousMemcpy(void *host_dst,
                                             const DeviceMemoryBase &gpu_src,
                                             uint64 size) {
  memcpy(host_dst, gpu_src.opaque(), size);
  return port::Status::OK();
}

port::Status HostExecutor::SynchronousMemcpyDeviceToDevice(
    DeviceMemoryBase *gpu_dst, const DeviceMemoryBase &gpu_src, uint64 size) {
  memcpy(gpu_dst->opaque(), gpu_src.opaque(), size);
  return port::Status::OK();
}

bool HostExecutor::HostCallback(Stream *stream,
                                std::function<void()> callback) {
  AsHostStream(stream)->EnqueueTask(callback);
  return true;
}

bool HostExecutor::AllocateStream(Stream *stream) { return true; }

void HostExecutor::DeallocateStream(Stream *stream) {}

bool HostExecutor::CreateStreamDependency(Stream *dependent, Stream *other) {
  AsHostStream(dependent)->EnqueueTask(
      [other]() { other->BlockHostUntilDone(); });
  AsHostStream(dependent)->BlockUntilDone();
  return true;
}

bool HostExecutor::StartTimer(Stream *stream, Timer *timer) {
  dynamic_cast<HostTimer *>(timer->implementation())->Start(stream);
  return true;
}

bool HostExecutor::StopTimer(Stream *stream, Timer *timer) {
  dynamic_cast<HostTimer *>(timer->implementation())->Stop(stream);
  return true;
}

bool HostExecutor::BlockHostUntilDone(Stream *stream) {
  AsHostStream(stream)->BlockUntilDone();
  return true;
}

DeviceDescription *HostExecutor::PopulateDeviceDescription() const {
  internal::DeviceDescriptionBuilder builder;

  builder.set_device_address_bits(64);

  // TODO(rspringer): How to report a value that's based in reality but that
  // doesn't result in thrashing or other badness? 4GiB chosen arbitrarily.
  builder.set_device_memory_size(static_cast<uint64>(4) * 1024 * 1024 * 1024);

  float cycle_counter_frequency = 1e9;
  if (FLAGS_stream_executor_cpu_real_clock_rate) {
    cycle_counter_frequency = static_cast<float>(
        tensorflow::profile_utils::CpuUtils::GetCycleCounterFrequency());
  }
  builder.set_clock_rate_ghz(cycle_counter_frequency / 1e9);

  auto built = builder.Build();
  return built.release();
}

bool HostExecutor::SupportsBlas() const {
  return PluginRegistry::Instance()
      ->GetFactory<PluginRegistry::BlasFactory>(kHostPlatformId,
                                                plugin_config_.blas())
      .ok();
}

blas::BlasSupport *HostExecutor::CreateBlas() {
  PluginRegistry *registry = PluginRegistry::Instance();
  port::StatusOr<PluginRegistry::BlasFactory> status =
      registry->GetFactory<PluginRegistry::BlasFactory>(kHostPlatformId,
                                                        plugin_config_.blas());
  if (!status.ok()) {
    LOG(ERROR) << "Unable to retrieve BLAS factory: "
               << status.status().error_message();
    return nullptr;
  }

  return status.ValueOrDie()(this);
}

bool HostExecutor::SupportsFft() const {
  return PluginRegistry::Instance()
      ->GetFactory<PluginRegistry::FftFactory>(kHostPlatformId,
                                               plugin_config_.fft())
      .ok();
}

fft::FftSupport *HostExecutor::CreateFft() {
  PluginRegistry *registry = PluginRegistry::Instance();
  port::StatusOr<PluginRegistry::FftFactory> status =
      registry->GetFactory<PluginRegistry::FftFactory>(kHostPlatformId,
                                                       plugin_config_.fft());
  if (!status.ok()) {
    LOG(ERROR) << "Unable to retrieve FFT factory: "
               << status.status().error_message();
    return nullptr;
  }

  return status.ValueOrDie()(this);
}

bool HostExecutor::SupportsRng() const {
  return PluginRegistry::Instance()
      ->GetFactory<PluginRegistry::RngFactory>(kHostPlatformId,
                                               plugin_config_.rng())
      .ok();
}

rng::RngSupport *HostExecutor::CreateRng() {
  PluginRegistry *registry = PluginRegistry::Instance();
  port::StatusOr<PluginRegistry::RngFactory> status =
      registry->GetFactory<PluginRegistry::RngFactory>(kHostPlatformId,
                                                       plugin_config_.rng());
  if (!status.ok()) {
    LOG(ERROR) << "Unable to retrieve RNG factory: "
               << status.status().error_message();
    return nullptr;
  }

  return status.ValueOrDie()(this);
}

}  // namespace host
}  // namespace gputools
}  // namespace perftools
<|endoftext|>


<commit_before>//2014.03.21 Gustaf - CTG.

/* P R O B L E M : T R A C K I N G  A N  U N K N O W N  Q U A N T I T Y  O F  S T U D E N T  R E C O R D S

In this problem, you will write functions to store and manipulate a collection of student records.
  A student record contains a student number and a grade, both integers.

The following functions are to be implemented:

  addRecord
  This function takes a pointer to a collection of student records (a student
  number and a grade), and it adds a new record with this data to the collection.

  averageRecord
  This function takes a pointer to a collection of student records
  and returns the simple average of student grades in the collection as a double.

The collection can be of any size.
The addRecord operation is expected to be called frequently,
so it must be implemented efficiently.

=== PLAN ===

-
-

*/

#include <iostream>

using namespace std;

struct listNode
{
  int studentNum;
  int grade;

  // To make a linked list, you need a struct that contains a pointer to the same struct.
  listNode *next;
};

typedef listNode *studentCollection;
  // For readability we are using the studentCollection type
  // only for variables that will refer to the whole list structure.

int main()
{
  cout << "Hello world - Linux Mint." << endl;

  // the -> notation is used to indicate the field of a pointed-to struct (or class).

  // ---
  studentCollection sc;

  // Creating the nodes
  listNode *node1 = new listNode;
  node1->studentNum = 1001; node1->grade = 78;

  listNode *node2 = new listNode;
  node2->studentNum = 1012; node2->grade = 93;

  listNode *node3 = new listNode;
  node3->studentNum = 1076; node3->grade = 85;

  // Creating the linked list
  sc = node1;
  node1->next = node2;
  node2->next = node3;
  node3->next = NULL;

  node1 = node2 = node3 = NULL; // NOTICE: to clean things up and avoid potential cross-linking problems.

  // ---

  cout << endl;
  return 0;
}
<commit_msg>Chapter 04 examples completed. Linked lists.<commit_after>//2014.03.21 - 2014.03.23 Gustaf - CTG.

/* P R O B L E M : T R A C K I N G  A N  U N K N O W N  Q U A N T I T Y  O F  S T U D E N T  R E C O R D S

In this problem, you will write functions to store and manipulate a collection of student records.
  A student record contains a student number and a grade, both integers.

The following functions are to be implemented:

  addRecord
  This function takes a pointer to a collection of student records (a student
  number and a grade), and it adds a new record with this data to the collection.

  averageRecord
  This function takes a pointer to a collection of student records
  and returns the simple average of student grades in the collection as a double.

The collection can be of any size.
The addRecord operation is expected to be called frequently,
so it must be implemented efficiently.

=== PLAN ===

-
-

*/

#include <iostream>

using namespace std;

struct listNode
{
  int studentNum;
  int grade;

  // To make a linked list, you need a struct that contains a pointer to the same struct.
  listNode *next;
};

typedef listNode *studentCollection;
// For readability we are using the studentCollection type
// only for variables that will refer to the whole list structure.

void addRecord(studentCollection &sc, int stuNum, int gr)
{
  // After the new node is created, it is linked into the list at the beginning.

  // New node
  listNode *newNode = new listNode;
  newNode->studentNum = stuNum;
  newNode->grade = gr;

  newNode->next = sc; // linked at the beginning of the list
  sc = newNode; // new head pointer
}

double averageRecord(studentCollection sc)
{
  // Special case: empty list.
  if (sc == NULL)
    return 0;

  // ---
  int count = 0;
  double sum = 0;

  listNode *loopPtr = sc;
  while (loopPtr != NULL)
  {
    sum += loopPtr->grade;
    count++;
    loopPtr = loopPtr->next;
  }

  double average = sum / count;
  return average;
}

int main()
{
  cout << "Hello world - Linux Mint." << endl;

  // the -> notation is used to indicate the field of a pointed-to struct (or class).

  // ---
  studentCollection sc; // First node or head pointer.

  // Creating the nodes
  listNode *node1 = new listNode;
  node1->studentNum = 1001; node1->grade = 78;

  listNode *node2 = new listNode;
  node2->studentNum = 1012; node2->grade = 93;

  listNode *node3 = new listNode;
  node3->studentNum = 1076; node3->grade = 85;

  // Creating the linked list
  sc = node1;
  node1->next = node2;
  node2->next = node3;
  node3->next = NULL;

  node1 = node2 = node3 = NULL; // NOTICE: to clean things up and avoid potential cross-linking problems.

  // ---
  addRecord(sc, 1274, 91);

  // ---
  int avg = averageRecord(sc);
  cout << "Promedio: " << avg << endl;

  cout << endl;
  return 0;
}
<|endoftext|>


<commit_before>// Copyright (C) 2019 Egor Pugin <egor.pugin@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <primitives/git_rev.h>
#include <gitrev.h>

#include <chrono>
#include <iomanip>
#include <sstream>
#include <string>

namespace primitives::git_rev
{

std::string getBuildTime()
{
    time_t t = SW_BUILD_TIME_T;
    std::ostringstream ss2;
    ss2 << "assembled on " << std::put_time(gmtime   (&t), "%d.%m.%Y %H:%M:%S UTC") << "\n";
    ss2 << "             " << std::put_time(localtime(&t), "%d.%m.%Y %H:%M:%S %Z" ) << "\n";
    return ss2.str();
}

std::string getGitRevision()
{
    std::string gitrev = SW_GIT_REV;
    if (!gitrev.empty())
    {
        gitrev = "git revision " + gitrev;
        if (SW_GIT_CHANGED_FILES)
            gitrev += " plus " + std::to_string(SW_GIT_CHANGED_FILES) + " modified files";
        gitrev += "\n";
    }
    return gitrev;
}

}
<commit_msg>[gitrev] Improve assembled output.<commit_after>// Copyright (C) 2019 Egor Pugin <egor.pugin@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <primitives/git_rev.h>
#include <gitrev.h>

#include <chrono>
#include <iomanip>
#include <sstream>
#include <string>

namespace primitives::git_rev
{

std::string getBuildTime()
{
    time_t t = SW_BUILD_TIME_T;
    std::ostringstream ss2;
    ss2 << "assembled on\n";
    ss2 << std::put_time(gmtime(&t), "%d.%m.%Y %H:%M:%S UTC") << "\n";
    ss2 << std::put_time(localtime(&t), "%d.%m.%Y %H:%M:%S %Z");
    return ss2.str();
}

std::string getGitRevision()
{
    std::string gitrev = SW_GIT_REV;
    if (!gitrev.empty())
    {
        gitrev = "git revision " + gitrev;
        if (SW_GIT_CHANGED_FILES)
            gitrev += " plus " + std::to_string(SW_GIT_CHANGED_FILES) + " modified files";
    }
    return gitrev;
}

}
<|endoftext|>


<commit_before>/**
*  Copyright (C) 2015 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <cstdlib>

#include <gtest/gtest.h>

#include <repo/core/model/bson/repo_bson_builder.h>

using namespace repo::core::model;

TEST(RepoBSONBuilderTest, ConstructBuilder)
{
	RepoBSONBuilder b;
	RepoBSONBuilder *b_ptr = new RepoBSONBuilder();
	delete b_ptr;
}<commit_msg>append array tested<commit_after>/**
*  Copyright (C) 2015 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <cstdlib>

#include <gtest/gtest.h>

#include <repo/core/model/bson/repo_bson_builder.h>

using namespace repo::core::model;

RepoBSON emptyBSON;

TEST(RepoBSONBuilderTest, ConstructBuilder)
{
	RepoBSONBuilder b;
	RepoBSONBuilder *b_ptr = new RepoBSONBuilder();
	delete b_ptr;
}

TEST(RepoBSONBuilderTest, appendArray)
{
	std::vector<std::string> arr({"hello", "bye"});
	RepoBSON arrBson = BSON("1" << arr[0] << "2" << arr[1]);
	mongo::BSONObjBuilder mbuilder;
	mbuilder.appendArray("arrayTest", arrBson);
	RepoBSON b(mbuilder.obj());

	RepoBSONBuilder builder, builder2;
	builder.appendArray("arrayTest", arr);
	builder2.appendArray("arrayTest", RepoBSON(arrBson));

	RepoBSON arrayRepoBson = builder.obj();
	RepoBSON arrayRepoBson2 = builder2.obj();

	EXPECT_EQ(arrayRepoBson.toString(), b.toString());
	EXPECT_EQ(arrayRepoBson2.toString(), b.toString());

	//Sanity check: make sure everything is not equal to empty bson.
	EXPECT_NE(emptyBSON.toString(), arrayRepoBson.toString());
	//Sanity check: make sure appending an empty bson/vector doesn't crash
	RepoBSONBuilder testBuilder;

	testBuilder.appendArray("emptyTest", emptyBSON);
	testBuilder.appendArray("emptyTest", std::vector<std::string>());

}<|endoftext|>


<commit_before>/*
    Copyright (C) 2011 vlc-phonon AUTHORS

    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, see <http://www.gnu.org/licenses/>.
*/

#include "libvlc.h"

#include <QtCore/QByteArray>
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QLibrary>
#include <QtCore/QSettings>
#include <QtCore/QString>
#include <QtCore/QStringBuilder>

#include <vlc/libvlc.h>

#include "debug.h"

LibVLC *LibVLC::self;

LibVLC::LibVLC() :
    m_vlcInstance(0)
{
}

LibVLC::~LibVLC()
{
    libvlc_release(m_vlcInstance);
    vlcUnload();
    self = 0;
}

bool LibVLC::init()
{
    Q_ASSERT_X(!self, "LibVLC", "there should be only one LibVLC object");
    LibVLC::self = new LibVLC;

    QString path = self->vlcPath();
    if (!path.isEmpty()) {
        QList<QByteArray> args;

        args << QFile::encodeName(path);

        QString pluginsPath = QLatin1Literal("--plugin-path=") %
                QDir::toNativeSeparators(QFileInfo(self->vlcPath()).dir().path());
#if defined(Q_OS_UNIX)
        pluginsPath.append("/vlc");
#elif defined(Q_OS_WIN)
        pluginsPath.append("\\plugins");
#endif
        args << QFile::encodeName(pluginsPath);

        // Ends up as something like $HOME/.config/Phonon/vlc.conf
        const QString configFileName = QSettings("Phonon", "vlc").fileName();
        if (QFile::exists(configFileName)) {
            args << QByteArray("--config=").append(QFile::encodeName(configFileName));
        }

        int debugLevel = 3 - (int) Debug::minimumDebugLevel();
        if (debugLevel > 0) {
            args << QByteArray("--verbose=").append(QString::number(debugLevel));
            args << QByteArray("--extraintf=logger");
#ifdef Q_WS_WIN
            QDir logFilePath(QString(qgetenv("APPDATA")).append("/vlc"));
#else
            QDir logFilePath(QDir::homePath().append("/.vlc"));
#endif //Q_WS_WIN
            logFilePath.mkdir("log");
            const QString logFile = logFilePath.path()
                    .append("/log/vlc-log-")
                    .append(QString::number(qApp->applicationPid()))
                    .append(".txt");
            args << QByteArray("--logfile=").append(QFile::encodeName(QDir::toNativeSeparators(logFile)));
        }

        args << "--reset-plugins-cache";
        args << "--no-media-library";
        args << "--no-osd";
        args << "--no-stats";
        args << "--no-video-title-show";
        args << "--album-art=0";

#ifndef Q_OS_MAC
        args << "--no-one-instance";
#endif

        // Build const char* array
        // MSVC does not support dynamic arrays, so we assume a fixed size
        // of 64 as sufficient.
        Q_ASSERT_X(         64 > args.size(), "libvlc init",
                                               "maximum amount of arguments exceeded, "
                                               "increase size of char**");
        const char *vlcArgs[64];
        for (int i = 0; i < args.size(); ++i) {
            vlcArgs[i] = args.at(i).constData();
        }

        // Create and initialize a libvlc instance (it should be done only once)
        self->m_vlcInstance = libvlc_new(args.size()-1, vlcArgs);
        if (!self->m_vlcInstance) {
            fatal() << "libVLC:" << LibVLC::errorMessage();
            return false;
        }
        return true;
    }
    return false;
}

const char *LibVLC::errorMessage()
{
    return libvlc_errmsg();
}

#if defined(Q_OS_UNIX)
bool LibVLC::libGreaterThan(const QString &lhs, const QString &rhs)
{
    const QStringList lhsparts = lhs.split(QLatin1Char('.'));
    const QStringList rhsparts = rhs.split(QLatin1Char('.'));
    Q_ASSERT(lhsparts.count() > 1 && rhsparts.count() > 1);

    for (int i = 1; i < rhsparts.count(); ++i) {
        if (lhsparts.count() <= i) {
            // left hand side is shorter, so it's less than rhs
            return false;
        }

        bool ok = false;
        int b = 0;
        int a = lhsparts.at(i).toInt(&ok);
        if (ok) {
            b = rhsparts.at(i).toInt(&ok);
        }
        if (ok) {
            // both toInt succeeded
            if (a == b) {
                continue;
            }
            return a > b;
        } else {
            // compare as strings;
            if (lhsparts.at(i) == rhsparts.at(i)) {
                continue;
            }
            return lhsparts.at(i) > rhsparts.at(i);
        }
    }

    // they compared strictly equally so far
    // lhs cannot be less than rhs
    return true;
}
#endif

QStringList LibVLC::findAllLibVlcPaths()
{
    QStringList paths;

#ifdef Q_OS_UNIX
    paths = QString::fromLatin1(qgetenv("LD_LIBRARY_PATH"))
            .split(QLatin1Char(':'), QString::SkipEmptyParts);
    paths << QLatin1String(PHONON_LIB_INSTALL_DIR) << QLatin1String("/usr/lib") << QLatin1String("/usr/local/lib");

#if defined(Q_WS_MAC)
    paths
            << QCoreApplication::applicationDirPath()
            << QCoreApplication::applicationDirPath() % QLatin1Literal("/../Frameworks")
            << QCoreApplication::applicationDirPath() % QLatin1Literal("/../PlugIns")
            << QCoreApplication::applicationDirPath() % QLatin1Literal("/lib");
#endif

    QStringList foundVlcs;
    foreach (const QString & path, paths) {
        QDir dir = QDir(path);
        QStringList entryList = dir.entryList(QStringList() << QLatin1String("libvlc.*"), QDir::Files);

        qSort(entryList.begin(), entryList.end(), LibVLC::libGreaterThan);
        foreach(const QString & entry, entryList) {
            if (entry.contains(".debug")) {
                continue;
            }
            foundVlcs << path % QLatin1Char('/') % entry;
        }
    }

    return foundVlcs;
#elif defined(Q_OS_WIN)
    // Current application path has highest priority.
    // Application could be delivered with own copy of qt, phonon, LibVLC, vlc and vlc plugins.
    QString appDirVlc =
            QDir::toNativeSeparators(QCoreApplication::applicationDirPath()
                                     % QLatin1Char('\\')
                                     % QLatin1Literal("libvlc.dll"));
    if (QFile::exists(appDirVlc)) {
        paths << appDirVlc;
    }

    // Read VLC version and installation directory from Windows registry
    QSettings settings(QSettings::SystemScope, "VideoLAN", "VLC");
    QString vlcVersion = settings.value("Version").toString();
    QString vlcInstallDir = settings.value("InstallDir").toString();
    if (vlcVersion.startsWith("1.1") && !vlcInstallDir.isEmpty()) {
        paths << vlcInstallDir % QLatin1Char('\\') % QLatin1Literal("libvlc.dll");
        return paths;
    } else {
        //If nothing is found in the registry try %PATH%
        QStringList searchPaths = QString::fromLatin1(qgetenv("PATH"))
                                  .split(QLatin1Char(';'), QString::SkipEmptyParts);

        QStringList foundVlcs;
        foreach(const QString & sp, searchPaths) {
            QDir dir = QDir(sp);
            QStringList entryList = dir.entryList(QStringList() << QLatin1String("libvlc.dll"), QDir::Files);
            foreach(const QString & entry, entryList){
                foundVlcs << sp % QLatin1Char('\\') % entry;
            }
        }
        paths << foundVlcs;
        return paths;
    }
#endif
}

QString LibVLC::vlcPath()
{
    static QString path;
    if (!path.isEmpty()) {
        return path;
    }

    m_vlcLibrary = new QLibrary();
    QStringList paths = LibVLC::findAllLibVlcPaths();
    foreach(path, paths) {
        m_vlcLibrary->setFileName(path);

        if (!m_vlcLibrary->resolve("libvlc_exception_init")) { //"libvlc_exception_init" not contained in 1.1+
            return path;
        } else {
            debug() << "Cannot resolve the symbol or load VLC library";
        }
        warning() << m_vlcLibrary->errorString();
    }

    vlcUnload();

    return QString();
}

void LibVLC::vlcUnload()
{
    m_vlcLibrary->unload();
    delete m_vlcLibrary;
    m_vlcLibrary = 0;
}
<commit_msg>use QVarLengthArray as suggested by Pino<commit_after>/*
    Copyright (C) 2011 vlc-phonon AUTHORS

    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, see <http://www.gnu.org/licenses/>.
*/

#include "libvlc.h"

#include <QtCore/QByteArray>
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QLibrary>
#include <QtCore/QSettings>
#include <QtCore/QString>
#include <QtCore/QStringBuilder>
#include <QtCore/QVarLengthArray>

#include <vlc/libvlc.h>

#include "debug.h"

LibVLC *LibVLC::self;

LibVLC::LibVLC() :
    m_vlcInstance(0)
{
}

LibVLC::~LibVLC()
{
    libvlc_release(m_vlcInstance);
    vlcUnload();
    self = 0;
}

bool LibVLC::init()
{
    Q_ASSERT_X(!self, "LibVLC", "there should be only one LibVLC object");
    LibVLC::self = new LibVLC;

    QString path = self->vlcPath();
    if (!path.isEmpty()) {
        QList<QByteArray> args;

        args << QFile::encodeName(path);

        QString pluginsPath = QLatin1Literal("--plugin-path=") %
                QDir::toNativeSeparators(QFileInfo(self->vlcPath()).dir().path());
#if defined(Q_OS_UNIX)
        pluginsPath.append("/vlc");
#elif defined(Q_OS_WIN)
        pluginsPath.append("\\plugins");
#endif
        args << QFile::encodeName(pluginsPath);

        // Ends up as something like $HOME/.config/Phonon/vlc.conf
        const QString configFileName = QSettings("Phonon", "vlc").fileName();
        if (QFile::exists(configFileName)) {
            args << QByteArray("--config=").append(QFile::encodeName(configFileName));
        }

        int debugLevel = 3 - (int) Debug::minimumDebugLevel();
        if (debugLevel > 0) {
            args << QByteArray("--verbose=").append(QString::number(debugLevel));
            args << QByteArray("--extraintf=logger");
#ifdef Q_WS_WIN
            QDir logFilePath(QString(qgetenv("APPDATA")).append("/vlc"));
#else
            QDir logFilePath(QDir::homePath().append("/.vlc"));
#endif //Q_WS_WIN
            logFilePath.mkdir("log");
            const QString logFile = logFilePath.path()
                    .append("/log/vlc-log-")
                    .append(QString::number(qApp->applicationPid()))
                    .append(".txt");
            args << QByteArray("--logfile=").append(QFile::encodeName(QDir::toNativeSeparators(logFile)));
        }

        args << "--reset-plugins-cache";
        args << "--no-media-library";
        args << "--no-osd";
        args << "--no-stats";
        args << "--no-video-title-show";
        args << "--album-art=0";

#ifndef Q_OS_MAC
        args << "--no-one-instance";
#endif

        // Build const char* array
        QVarLengthArray<const char*, 64> vlcArgs(args.size());
        for (int i = 0; i < args.size(); ++i) {
            vlcArgs[i] = args.at(i).constData();
        }

        // Create and initialize a libvlc instance (it should be done only once)
        self->m_vlcInstance = libvlc_new(vlcArgs.size(), vlcArgs.constData());
        if (!self->m_vlcInstance) {
            fatal() << "libVLC:" << LibVLC::errorMessage();
            return false;
        }
        return true;
    }
    return false;
}

const char *LibVLC::errorMessage()
{
    return libvlc_errmsg();
}

#if defined(Q_OS_UNIX)
bool LibVLC::libGreaterThan(const QString &lhs, const QString &rhs)
{
    const QStringList lhsparts = lhs.split(QLatin1Char('.'));
    const QStringList rhsparts = rhs.split(QLatin1Char('.'));
    Q_ASSERT(lhsparts.count() > 1 && rhsparts.count() > 1);

    for (int i = 1; i < rhsparts.count(); ++i) {
        if (lhsparts.count() <= i) {
            // left hand side is shorter, so it's less than rhs
            return false;
        }

        bool ok = false;
        int b = 0;
        int a = lhsparts.at(i).toInt(&ok);
        if (ok) {
            b = rhsparts.at(i).toInt(&ok);
        }
        if (ok) {
            // both toInt succeeded
            if (a == b) {
                continue;
            }
            return a > b;
        } else {
            // compare as strings;
            if (lhsparts.at(i) == rhsparts.at(i)) {
                continue;
            }
            return lhsparts.at(i) > rhsparts.at(i);
        }
    }

    // they compared strictly equally so far
    // lhs cannot be less than rhs
    return true;
}
#endif

QStringList LibVLC::findAllLibVlcPaths()
{
    QStringList paths;

#ifdef Q_OS_UNIX
    paths = QString::fromLatin1(qgetenv("LD_LIBRARY_PATH"))
            .split(QLatin1Char(':'), QString::SkipEmptyParts);
    paths << QLatin1String(PHONON_LIB_INSTALL_DIR) << QLatin1String("/usr/lib") << QLatin1String("/usr/local/lib");

#if defined(Q_WS_MAC)
    paths
            << QCoreApplication::applicationDirPath()
            << QCoreApplication::applicationDirPath() % QLatin1Literal("/../Frameworks")
            << QCoreApplication::applicationDirPath() % QLatin1Literal("/../PlugIns")
            << QCoreApplication::applicationDirPath() % QLatin1Literal("/lib");
#endif

    QStringList foundVlcs;
    foreach (const QString & path, paths) {
        QDir dir = QDir(path);
        QStringList entryList = dir.entryList(QStringList() << QLatin1String("libvlc.*"), QDir::Files);

        qSort(entryList.begin(), entryList.end(), LibVLC::libGreaterThan);
        foreach(const QString & entry, entryList) {
            if (entry.contains(".debug")) {
                continue;
            }
            foundVlcs << path % QLatin1Char('/') % entry;
        }
    }

    return foundVlcs;
#elif defined(Q_OS_WIN)
    // Current application path has highest priority.
    // Application could be delivered with own copy of qt, phonon, LibVLC, vlc and vlc plugins.
    QString appDirVlc =
            QDir::toNativeSeparators(QCoreApplication::applicationDirPath()
                                     % QLatin1Char('\\')
                                     % QLatin1Literal("libvlc.dll"));
    if (QFile::exists(appDirVlc)) {
        paths << appDirVlc;
    }

    // Read VLC version and installation directory from Windows registry
    QSettings settings(QSettings::SystemScope, "VideoLAN", "VLC");
    QString vlcVersion = settings.value("Version").toString();
    QString vlcInstallDir = settings.value("InstallDir").toString();
    if (vlcVersion.startsWith("1.1") && !vlcInstallDir.isEmpty()) {
        paths << vlcInstallDir % QLatin1Char('\\') % QLatin1Literal("libvlc.dll");
        return paths;
    } else {
        //If nothing is found in the registry try %PATH%
        QStringList searchPaths = QString::fromLatin1(qgetenv("PATH"))
                                  .split(QLatin1Char(';'), QString::SkipEmptyParts);

        QStringList foundVlcs;
        foreach(const QString & sp, searchPaths) {
            QDir dir = QDir(sp);
            QStringList entryList = dir.entryList(QStringList() << QLatin1String("libvlc.dll"), QDir::Files);
            foreach(const QString & entry, entryList){
                foundVlcs << sp % QLatin1Char('\\') % entry;
            }
        }
        paths << foundVlcs;
        return paths;
    }
#endif
}

QString LibVLC::vlcPath()
{
    static QString path;
    if (!path.isEmpty()) {
        return path;
    }

    m_vlcLibrary = new QLibrary();
    QStringList paths = LibVLC::findAllLibVlcPaths();
    foreach(path, paths) {
        m_vlcLibrary->setFileName(path);

        if (!m_vlcLibrary->resolve("libvlc_exception_init")) { //"libvlc_exception_init" not contained in 1.1+
            return path;
        } else {
            debug() << "Cannot resolve the symbol or load VLC library";
        }
        warning() << m_vlcLibrary->errorString();
    }

    vlcUnload();

    return QString();
}

void LibVLC::vlcUnload()
{
    m_vlcLibrary->unload();
    delete m_vlcLibrary;
    m_vlcLibrary = 0;
}
<|endoftext|>


<commit_before>/*
*
* Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Orion dev team
*/
#include <string>

#include "common/statistics.h"
#include "common/clockFunctions.h"

#include "rest/ConnectionInfo.h"
#include "ngsi/ParseData.h"
#include "rest/OrionError.h"
#include "apiTypesV2/ErrorCode.h"
#include "mongoBackend/mongoUnsubscribeContext.h"
#include "ngsi10/UnsubscribeContextResponse.h"

#include "serviceRoutinesV2/deleteSubscription.h"

/* ****************************************************************************
*
* deleteSubscription -
*
* DELETE /v2/subscriptions/{entityId}
*
* Payload In:  None
* Payload Out: None
*
* URI parameters:
*   -
*/

std::string deleteSubscription
(
    ConnectionInfo*            ciP,
    int                        components,
    std::vector<std::string>&  compV,
    ParseData*                 parseDataP
)
{
  std::string                 answer;
  std::string                 subscriptionId =  compV[2];
  UnsubscribeContextResponse  uncr;

  // 'Fill In' UnsubscribeContextRequest
  parseDataP->uncr.res.subscriptionId.set(subscriptionId);

  TIMED_MONGO(ciP->httpStatusCode = mongoUnsubscribeContext(&parseDataP->uncr.res, &uncr, ciP->tenant));

  StatusCode      sc  = uncr.statusCode;
  HttpStatusCode  scc = sc.code;

  if (scc != SccOk)
  {
    OrionError oe;

    ciP->httpStatusCode = scc;
    oe.code             = scc;
    oe.reasonPhrase     = sc.reasonPhrase;

    if (scc == SccContextElementNotFound)
    {
      oe.details = "The requested subscription has not been found. Check id";
    }

    TIMED_RENDER(answer = oe.render(ciP, ""));

    return answer;
  }

  ciP->httpStatusCode = SccNoContent;

  return "";
}

<commit_msg>Fix style<commit_after>/*
*
* Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Orion dev team
*/
#include <string>

#include "common/statistics.h"
#include "common/clockFunctions.h"

#include "rest/ConnectionInfo.h"
#include "ngsi/ParseData.h"
#include "rest/OrionError.h"
#include "apiTypesV2/ErrorCode.h"
#include "mongoBackend/mongoUnsubscribeContext.h"
#include "ngsi10/UnsubscribeContextResponse.h"

#include "serviceRoutinesV2/deleteSubscription.h"

/* ****************************************************************************
*
* deleteSubscription -
*
* DELETE /v2/subscriptions/{entityId}
*
* Payload In:  None
* Payload Out: None
*
* URI parameters:
*   -
*/

std::string deleteSubscription
(
    ConnectionInfo*            ciP,
    int                        components,
    std::vector<std::string>&  compV,
    ParseData*                 parseDataP
)
{
  std::string                 answer;
  std::string                 subscriptionId =  compV[2];
  UnsubscribeContextResponse  uncr;

  // 'Fill In' UnsubscribeContextRequest
  parseDataP->uncr.res.subscriptionId.set(subscriptionId);

  TIMED_MONGO(ciP->httpStatusCode = mongoUnsubscribeContext(&parseDataP->uncr.res, &uncr, ciP->tenant));

  if (uncr.statusCode.code != SccOk)
  {
    OrionError oe(uncr.statusCode);

    ciP->httpStatusCode = uncr.statusCode.code;
    oe.reasonPhrase     = uncr.statusCode.reasonPhrase;

    if (uncr.statusCode.code == SccContextElementNotFound)
    {
      oe.details = "The requested subscription has not been found. Check id";
    }

    TIMED_RENDER(answer = oe.render(ciP, ""));

    return answer;
  }

  ciP->httpStatusCode = SccNoContent;

  return "";
}

<|endoftext|>


<commit_before>#include "exprcalc.h"
#include "lstack.cpp"
#include <cstdlib>
#include <sstream>

int priority(char op)
{
	switch (op)
    {
        case '+': case '-':           return 1;
        case '*': case '/': case '%': return 2;
        case '^':                     return 3;
        default:                      return -1;
	}
}

int ipow(int a, int n)
{
    if (a == 0)
        return 0;
    else if (a == 1 || n <= 0)
        return 1;
    else if (n % 2)
        return a * ipow(a, n - 1);
    else
    {
        int b = ipow(a, n / 2);
        return b * b;
    }
}

void apply_operation(LinkedStack<int>& rstack, char op)
{
	int r = rstack.pop();
    int l = rstack.pop();

	switch (op)
    {
        case '+': rstack.push(l + r);    break;
        case '-': rstack.push(l - r);    break;
        case '*': rstack.push(l * r);    break;
        case '/': rstack.push(l / r);    break;
        case '^': rstack.push(ipow(l,r)); break;
	}
}

int calculate_expr(const char* expr)
{
	LinkedStack<char> opstack;
	LinkedStack<int> rstack;

	while (*expr)
    {
		if (    *expr >= '0' && *expr <= '9' ||
                *expr == '-' && *(expr + 1) >= '0' && *(expr + 1) <= '9'    )
        {
			rstack.push(atoi(expr));

            while (*expr && *(expr + 1) >= '0' && *(expr + 1) <= '9')
                expr++;
        }
		else if (*expr == '(')
			opstack.push(*expr);
		else if (*expr == ')')
        {
			char op = opstack.pop();

			while (op != '(') {
				apply_operation(rstack, op);
				op = opstack.pop();
			}

			/*
			while ((op = opstack.pop()) != '(')
				*rpn++ = op;
		    */
		}
        else if (*expr != ' ' && *expr != '\t')
        {
			// *expr е операция
			// първо: вадим всички операции
			// с по-висок или равен приоритет
			while (!opstack.empty() &&
				   priority(opstack.last()) >=
				   priority(*expr))
				apply_operation(rstack,opstack.pop());

			opstack.push(*expr);
		}
		expr++;
	}

	while (!opstack.empty())
		apply_operation(rstack, opstack.pop());

	return rstack.pop();
}

char* strshift(char* str, size_t n)
{
    if (!str || !*str)
        return str;

    char* i = str;

    while (*i)
        i++;

    while (i != str - 1)
    {
        *(i + n) = *i;
        i--;
    }

    return str + n;
}

char* itonstr(int n, char* str)
{
    if (n == 0)
        *str = '0';
    else
    {
        size_t len = 0;
        int t = n;

        while (t)
        {
            t /= 10;
            len++;
        }

        if (n < 0)
        {
            *str = '-';
            len++;
        }

        strshift(str, len);
        char* i = str + len - 1;

        while (i >= str && n)
        {
            *i = '0' + n % 10;
            n /= 10;
            i--;
        }
    }

    return str;
}

char* strsubst(char* str, char ch, int subst)
{
    char* i = str;

    while (*i)
    {
        if (*i == ch)
            itonstr(subst, str);

        i++;
    }

    return str;
}

std::string& substitute(std::string& s, char ch, const std::string& subst)
{
    size_t pos = s.find(ch);

    while (pos != std::string::npos)
    {
        s.replace(pos, 1, subst);
        pos = s.find(ch, pos + 1);
    }

    return s;
}

std::string& interpolate(std::string& s, char ch, int arg)
{
    std::ostringstream argout;
    argout << arg;
    return substitute(s, ch, argout.str());
}

const char* find_token(const char* str)
{
    if (!str)
        return NULL;

    while (*str && (*str == ' ' || *str == '\t'))
        str++;

    return *str && *str != ' ' && *str != '\t' ? str : NULL;
}

bool is_alpha(char ch)
{
    return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z';
}
<commit_msg>fixed formatting issue<commit_after>#include "exprcalc.h"
#include "lstack.cpp"
#include <cstdlib>
#include <sstream>

int priority(char op)
{
	switch (op)
    {
        case '+': case '-':           return 1;
        case '*': case '/': case '%': return 2;
        case '^':                     return 3;
        default:                      return -1;
	}
}

int ipow(int a, int n)
{
    if (a == 0)
        return 0;
    else if (a == 1 || n <= 0)
        return 1;
    else if (n % 2)
        return a * ipow(a, n - 1);
    else
    {
        int b = ipow(a, n / 2);
        return b * b;
    }
}

void apply_operation(LinkedStack<int>& rstack, char op)
{
	int r = rstack.pop();
    int l = rstack.pop();

	switch (op)
    {
        case '+': rstack.push(l + r);     break;
        case '-': rstack.push(l - r);     break;
        case '*': rstack.push(l * r);     break;
        case '/': rstack.push(l / r);     break;
        case '^': rstack.push(ipow(l,r)); break;
	}
}

int calculate_expr(const char* expr)
{
	LinkedStack<char> opstack;
	LinkedStack<int> rstack;

	while (*expr)
    {
		if (    *expr >= '0' && *expr <= '9' ||
                *expr == '-' && *(expr + 1) >= '0' && *(expr + 1) <= '9'    )
        {
			rstack.push(atoi(expr));

            while (*expr && *(expr + 1) >= '0' && *(expr + 1) <= '9')
                expr++;
        }
		else if (*expr == '(')
			opstack.push(*expr);
		else if (*expr == ')')
        {
			char op = opstack.pop();

			while (op != '(') {
				apply_operation(rstack, op);
				op = opstack.pop();
			}

			/*
			while ((op = opstack.pop()) != '(')
				*rpn++ = op;
		    */
		}
        else if (*expr != ' ' && *expr != '\t')
        {
			// *expr е операция
			// първо: вадим всички операции
			// с по-висок или равен приоритет
			while (!opstack.empty() &&
				   priority(opstack.last()) >=
				   priority(*expr))
				apply_operation(rstack,opstack.pop());

			opstack.push(*expr);
		}
		expr++;
	}

	while (!opstack.empty())
		apply_operation(rstack, opstack.pop());

	return rstack.pop();
}

char* strshift(char* str, size_t n)
{
    if (!str || !*str)
        return str;

    char* i = str;

    while (*i)
        i++;

    while (i != str - 1)
    {
        *(i + n) = *i;
        i--;
    }

    return str + n;
}

char* itonstr(int n, char* str)
{
    if (n == 0)
        *str = '0';
    else
    {
        size_t len = 0;
        int t = n;

        while (t)
        {
            t /= 10;
            len++;
        }

        if (n < 0)
        {
            *str = '-';
            len++;
        }

        strshift(str, len);
        char* i = str + len - 1;

        while (i >= str && n)
        {
            *i = '0' + n % 10;
            n /= 10;
            i--;
        }
    }

    return str;
}

char* strsubst(char* str, char ch, int subst)
{
    char* i = str;

    while (*i)
    {
        if (*i == ch)
            itonstr(subst, str);

        i++;
    }

    return str;
}

std::string& substitute(std::string& s, char ch, const std::string& subst)
{
    size_t pos = s.find(ch);

    while (pos != std::string::npos)
    {
        s.replace(pos, 1, subst);
        pos = s.find(ch, pos + 1);
    }

    return s;
}

std::string& interpolate(std::string& s, char ch, int arg)
{
    std::ostringstream argout;
    argout << arg;
    return substitute(s, ch, argout.str());
}

const char* find_token(const char* str)
{
    if (!str)
        return NULL;

    while (*str && (*str == ' ' || *str == '\t'))
        str++;

    return *str && *str != ' ' && *str != '\t' ? str : NULL;
}

bool is_alpha(char ch)
{
    return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z';
}
<|endoftext|>


<commit_before>#include "UIContext.h"
#include <windowsx.h>

#define MAX_COMBOSTR 1024

UIContext::UIContext(HWND hWnd) :
_hWnd(hWnd) {

}

bool UIContext::SetCheck(int chkId, bool checked) {
    return CheckDlgButton(
        _hWnd, chkId, checked ? BST_CHECKED : BST_UNCHECKED) == TRUE;
}

void UIContext::AddComboItem(int cmbId, std::wstring item) {
    SendDlgItemMessage(_hWnd, cmbId, CB_ADDSTRING, NULL, (LPARAM) item.c_str());
}

int UIContext::SelectComboItem(int cmbId, std::wstring item) {
    HWND cmbWnd = GetDlgItem(_hWnd, cmbId);
    return ComboBox_SelectString(cmbWnd, -1, item.c_str());
}

std::wstring GetComboSelection(int cmbId) {
}

void UIContext::Enable(int id) {
    HWND wnd = GetDlgItem(_hWnd, id);
    EnableWindow(wnd, TRUE);
}

void UIContext::Disable(int id) {
    HWND wnd = GetDlgItem(_hWnd, id);
    EnableWindow(wnd, FALSE);
}
<commit_msg>Update GetcomboSelection()<commit_after>#include "UIContext.h"
#include <windowsx.h>

#define MAX_COMBOSTR 1024

UIContext::UIContext(HWND hWnd) :
_hWnd(hWnd) {

}

bool UIContext::SetCheck(int chkId, bool checked) {
    return CheckDlgButton(
        _hWnd, chkId, checked ? BST_CHECKED : BST_UNCHECKED) == TRUE;
}

void UIContext::AddComboItem(int cmbId, std::wstring item) {
    SendDlgItemMessage(_hWnd, cmbId, CB_ADDSTRING, NULL, (LPARAM) item.c_str());
}

int UIContext::SelectComboItem(int cmbId, std::wstring item) {
    HWND cmbWnd = GetDlgItem(_hWnd, cmbId);
    return ComboBox_SelectString(cmbWnd, -1, item.c_str());
}

std::wstring UIContext::GetComboSelection(int cmbId) {
    HWND cmbWnd = GetDlgItem(_hWnd, cmbId);
    wchar_t text[MAX_COMBOSTR];
    ComboBox_GetText(cmbWnd, text, MAX_COMBOSTR);
    return std::wstring(text);
}

bool UIContext::SetText(int id, std::wstring text) {
    HWND wnd = GetDlgItem(_hWnd, id);
    return SetWindowText(wnd, text.c_str()) == TRUE;
}

void UIContext::Enable(int id) {
    HWND wnd = GetDlgItem(_hWnd, id);
    EnableWindow(wnd, TRUE);
}

void UIContext::Disable(int id) {
    HWND wnd = GetDlgItem(_hWnd, id);
    EnableWindow(wnd, FALSE);
}
<|endoftext|>


<commit_before>/* MULTIWAVE - additive synthesis instrument

      p0 = output start time
      p1 = duration
      p2 = overall amplitude (0-32767, as in WAVETABLE)
      p3 = wavetable (use maketable("wave", ...) for this)

      Then any number of quadruplets defining the frequency, amplitude,
      phase and panning of individual partials.

      p4 = frequency (Hz)
      p5 = amplitude (0-1)
      p6 = initial phase (0-360 degrees, not updateable)
      p7 = pan (pctleft: 0-1)

   p2 (amplitude), p4 (freq), p5 (partial amp), p7 (pan), and the same
   parameters for additional partials, can receive updates from a table
   or real-time control source.

   John Gibson, 3/9/06
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ugens.h>
#include <Ougens.h>
#include <Instrument.h>
#include <PField.h>
#include "MULTIWAVE.h"
#include <rt.h>
#include <rtdefs.h>

//#define DEBUG

#define FIRST_FREQ_ARG  4

MULTIWAVE::MULTIWAVE() : Instrument()
{
   branch = 0;
   numpartials = 0;
   oscil = NULL;
   amp = NULL;
   pan = NULL;
}

MULTIWAVE::~MULTIWAVE()
{
   for (int i = 0; i < numpartials; i++)
      delete oscil[i];
   delete [] oscil;
   delete [] amp;
   delete [] pan;
}

int MULTIWAVE::usage()
{
   return die("MULTIWAVE",
              "Usage: MULTIWAVE(start, dur, amp, wavetable,\n"
              "                 freq1, amp1, phase1, pan1\n"
              "                 [, freq2, amp2, phase2, pan2, ...]");
}

int MULTIWAVE::init(double p[], int n_args)
{
   if (n_args < 8)
      return usage();
   float outskip = p[0];
   float dur = p[1];
   nargs = n_args;

   if (rtsetoutput(outskip, dur, this) == -1)
      return DONT_SCHEDULE;
   if (outputChannels() < 1 || outputChannels() > 2)
      return die("MULTIWAVE", "Must have mono or stereo output only.");

   int wavelen;
   double *wavet = (double *) getPFieldTable(3, &wavelen);
   if (wavet == NULL)
      return die("MULTIWAVE", "p3 must be wavetable (use maketable)");

   numpartials = (nargs - FIRST_FREQ_ARG) / 4;
   oscil = new Ooscili * [numpartials];
   amp = new double [numpartials];
   pan = new double [numpartials];

   for (int i = 0; i < numpartials; i++) {
      oscil[i] = new Ooscili(SR, 440.0, wavet, wavelen);
      amp[i] = 0.0;
      pan[i] = 0.0;
   }

   skip = (int) (SR / (float) resetval);

   return nSamps();
}

void MULTIWAVE::doupdate()
{
   double p[nargs];
   update(p, nargs);

   overall_amp = p[2];

   for (int i = 0; i < numpartials; i++) {
      const int index = FIRST_FREQ_ARG + (4 * i);
      oscil[i]->setfreq(p[index]);
      amp[i] = p[index + 1];
      pan[i] = p[index + 3];
   }
}

int MULTIWAVE::run()
{
   const int samps = framesToRun();
   const int chans = outputChannels();
   float out[chans];

   for (int i = 0; i < samps; i += inputChannels()) {
      if (--branch <= 0) {
         doupdate();
         branch = skip;
      }

      for (int j = 0; j < chans; j++)
         out[j] = 0.0f;

      for (int j = 0; j < numpartials; j++) {
         float sig = oscil[j]->next() * amp[j];
         if (chans == 1)
            out[0] += sig;
         else {
            out[0] += sig * pan[j];
            out[1] += sig * (1.0 - pan[j]);
         }
      }
      float scale = (1.0 / float(numpartials)) * overall_amp;
      for (int j = 0; j < chans; j++)
         out[j] *= scale;

      rtaddout(out);
      increment();
   }

   return framesToRun();
}

Instrument *makeMULTIWAVE()
{
   MULTIWAVE *inst;

   inst = new MULTIWAVE();
   inst->set_bus_config("MULTIWAVE");

   return inst;
}

void rtprofile()
{
   RT_INTRO("MULTIWAVE", makeMULTIWAVE);
}

<commit_msg>Fix crasher.<commit_after>/* MULTIWAVE - additive synthesis instrument

      p0 = output start time
      p1 = duration
      p2 = overall amplitude (0-32767, as in WAVETABLE)
      p3 = wavetable (use maketable("wave", ...) for this)

      Then any number of quadruplets defining the frequency, amplitude,
      phase and panning of individual partials.

      p4 = frequency (Hz)
      p5 = amplitude (0-1)
      p6 = initial phase (0-360 degrees, not updateable)
      p7 = pan (pctleft: 0-1)

   p2 (amplitude), p4 (freq), p5 (partial amp), p7 (pan), and the same
   parameters for additional partials, can receive updates from a table
   or real-time control source.

   John Gibson, 3/9/06
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ugens.h>
#include <Ougens.h>
#include <Instrument.h>
#include <PField.h>
#include "MULTIWAVE.h"
#include <rt.h>
#include <rtdefs.h>

//#define DEBUG

#define FIRST_FREQ_ARG  4

MULTIWAVE::MULTIWAVE() : Instrument()
{
   branch = 0;
   numpartials = 0;
   oscil = NULL;
   amp = NULL;
   pan = NULL;
}

MULTIWAVE::~MULTIWAVE()
{
   for (int i = 0; i < numpartials; i++)
      delete oscil[i];
   delete [] oscil;
   delete [] amp;
   delete [] pan;
}

int MULTIWAVE::usage()
{
   return die("MULTIWAVE",
              "Usage: MULTIWAVE(start, dur, amp, wavetable,\n"
              "                 freq1, amp1, phase1, pan1\n"
              "                 [, freq2, amp2, phase2, pan2, ...]");
}

int MULTIWAVE::init(double p[], int n_args)
{
   if (n_args < 8)
      return usage();
   float outskip = p[0];
   float dur = p[1];
   nargs = n_args;

   if (rtsetoutput(outskip, dur, this) == -1)
      return DONT_SCHEDULE;
   if (outputChannels() < 1 || outputChannels() > 2)
      return die("MULTIWAVE", "Must have mono or stereo output only.");

   int wavelen;
   double *wavet = (double *) getPFieldTable(3, &wavelen);
   if (wavet == NULL)
      return die("MULTIWAVE", "p3 must be wavetable (use maketable)");

   numpartials = (nargs - FIRST_FREQ_ARG) / 4;
   oscil = new Ooscili * [numpartials];
   amp = new double [numpartials];
   pan = new double [numpartials];

   for (int i = 0; i < numpartials; i++) {
      oscil[i] = new Ooscili(SR, 440.0, wavet, wavelen);
      amp[i] = 0.0;
      pan[i] = 0.0;
   }

   skip = (int) (SR / (float) resetval);

   return nSamps();
}

void MULTIWAVE::doupdate()
{
   double p[nargs];
   update(p, nargs);

   overall_amp = p[2];

   for (int i = 0; i < numpartials; i++) {
      const int index = FIRST_FREQ_ARG + (4 * i);
      oscil[i]->setfreq(p[index]);
      amp[i] = p[index + 1];
      pan[i] = p[index + 3];
   }
}

int MULTIWAVE::run()
{
   const int samps = framesToRun();
   const int chans = outputChannels();
   float out[chans];

   for (int i = 0; i < samps; i++) {
      if (--branch <= 0) {
         doupdate();
         branch = skip;
      }

      for (int j = 0; j < chans; j++)
         out[j] = 0.0f;

      for (int j = 0; j < numpartials; j++) {
         float sig = oscil[j]->next() * amp[j];
         if (chans == 1)
            out[0] += sig;
         else {
            out[0] += sig * pan[j];
            out[1] += sig * (1.0 - pan[j]);
         }
      }
      float scale = (1.0 / float(numpartials)) * overall_amp;
      for (int j = 0; j < chans; j++)
         out[j] *= scale;

      rtaddout(out);
      increment();
   }

   return framesToRun();
}

Instrument *makeMULTIWAVE()
{
   MULTIWAVE *inst;

   inst = new MULTIWAVE();
   inst->set_bus_config("MULTIWAVE");

   return inst;
}

void rtprofile()
{
   RT_INTRO("MULTIWAVE", makeMULTIWAVE);
}

<|endoftext|>


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

#include "base/command_line.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"

namespace {

// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
 public:
  explicit BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
                   Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    MessageLoopForUI::current()->Quit();
  }

 private:
  NotificationRegistrar registrar_;
  DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};

// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;

const char kConsoleTestPage[] = "files/devtools/console_test_page.html";
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kJsPage[] = "files/devtools/js_page.html";
const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html";
const char kPauseWhenLoadingDevTools[] =
    "files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
    "files/devtools/pause_when_script_is_running.html";
const char kResourceContentLengthTestPage[] = "files/devtools/image.html";
const char kResourceTestPage[] = "files/devtools/resource_test_page.html";
const char kSimplePage[] = "files/devtools/simple_page.html";
const char kCompletionOnPause[] =
    "files/devtools/completion_on_pause.html";
const char kPageWithContentScript[] =
    "files/devtools/page_with_content_script.html";

class DevToolsSanityTest : public InProcessBrowserTest {
 public:
  DevToolsSanityTest() {
    set_show_window(true);
    EnableDOMAutomation();
  }

 protected:
  void RunTest(const std::string& test_name, const std::string& test_page) {
    OpenDevToolsWindow(test_page);
    std::string result;

    // At first check that JavaScript part of the front-end is loaded by
    // checking that global variable uiTests exists(it's created after all js
    // files have been loaded) and has runTest method.
    ASSERT_TRUE(
        ui_test_utils::ExecuteJavaScriptAndExtractString(
            client_contents_->render_view_host(),
            L"",
            L"window.domAutomationController.send("
            L"'' + (window.uiTests && (typeof uiTests.runTest)));",
            &result));

    if (result == "function") {
      ASSERT_TRUE(
          ui_test_utils::ExecuteJavaScriptAndExtractString(
              client_contents_->render_view_host(),
              L"",
              UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
                                      test_name.c_str())),
              &result));
      EXPECT_EQ("[OK]", result);
    } else {
      FAIL() << "DevTools front-end is broken.";
    }
    CloseDevToolsWindow();
  }

  void OpenDevToolsWindow(const std::string& test_page) {
    ASSERT_TRUE(test_server()->Start());
    GURL url = test_server()->GetURL(test_page);
    ui_test_utils::NavigateToURL(browser(), url);

    inspected_rvh_ = GetInspectedTab()->render_view_host();
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    devtools_manager->OpenDevToolsWindow(inspected_rvh_);

    DevToolsClientHost* client_host =
        devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
    window_ = client_host->AsDevToolsWindow();
    RenderViewHost* client_rvh = window_->GetRenderViewHost();
    client_contents_ = client_rvh->delegate()->GetAsTabContents();
    ui_test_utils::WaitForNavigation(&client_contents_->controller());
  }

  TabContents* GetInspectedTab() {
    return browser()->GetTabContentsAt(0);
  }

  void CloseDevToolsWindow() {
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    // UnregisterDevToolsClientHostFor may destroy window_ so store the browser
    // first.
    Browser* browser = window_->browser();
    devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);

    // Wait only when DevToolsWindow has a browser. For docked DevTools, this
    // is NULL and we skip the wait.
    if (browser)
      BrowserClosedObserver close_observer(browser);
  }

  TabContents* client_contents_;
  DevToolsWindow* window_;
  RenderViewHost* inspected_rvh_;
};

class CancelableQuitTask : public Task {
 public:
  explicit CancelableQuitTask(const std::string& timeout_message)
      : timeout_message_(timeout_message),
        cancelled_(false) {
  }

  void cancel() {
    cancelled_ = true;
  }

  virtual void Run() {
    if (cancelled_) {
      return;
    }
    FAIL() << timeout_message_;
    MessageLoop::current()->Quit();
  }

 private:
  std::string timeout_message_;
  bool cancelled_;
};

// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
                                   public NotificationObserver {
 public:
  DevToolsExtensionDebugTest() : DevToolsSanityTest() {
    PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
    test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
    test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
  }

 protected:
  // Load an extention from test\data\devtools\extensions\<extension_name>
  void LoadExtension(const char* extension_name) {
    FilePath path = test_extensions_dir_.AppendASCII(extension_name);
    ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
  }

 private:
  bool LoadExtensionFromPath(const FilePath& path) {
    ExtensionsService* service = browser()->profile()->GetExtensionsService();
    size_t num_before = service->extensions()->size();
    {
      NotificationRegistrar registrar;
      registrar.Add(this, NotificationType::EXTENSION_LOADED,
                    NotificationService::AllSources());
      CancelableQuitTask* delayed_quit =
          new CancelableQuitTask("Extension load timed out.");
      MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
          4*1000);
      service->LoadExtension(path);
      ui_test_utils::RunMessageLoop();
      delayed_quit->cancel();
    }
    size_t num_after = service->extensions()->size();
    if (num_after != (num_before + 1))
      return false;

    return WaitForExtensionHostsToLoad();
  }

  bool WaitForExtensionHostsToLoad() {
    // Wait for all the extension hosts that exist to finish loading.
    // NOTE: This assumes that the extension host list is not changing while
    // this method is running.

    NotificationRegistrar registrar;
    registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
                  NotificationService::AllSources());
    CancelableQuitTask* delayed_quit =
        new CancelableQuitTask("Extension host load timed out.");
    MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
        4*1000);

    ExtensionProcessManager* manager =
          browser()->profile()->GetExtensionProcessManager();
    for (ExtensionProcessManager::const_iterator iter = manager->begin();
         iter != manager->end();) {
      if ((*iter)->did_stop_loading())
        ++iter;
      else
        ui_test_utils::RunMessageLoop();
    }

    delayed_quit->cancel();
    return true;
  }

  void Observe(NotificationType type,
               const NotificationSource& source,
               const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::EXTENSION_LOADED:
      case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
        MessageLoopForUI::current()->Quit();
        break;
      default:
        NOTREACHED();
        break;
    }
  }

  FilePath test_extensions_dir_;
};

// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
  RunTest("testEnableResourcesTab", kSimplePage);
}

// Fails after WebKit roll 59365:59477, http://crbug.com/44202.
#if defined(OS_LINUX)
#define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength
#else
#define MAYBE_TestResourceContentLength TestResourceContentLength
#endif  // defined(OS_LINUX)

// Tests resources have correct sizes.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestResourceContentLength) {
  RunTest("testResourceContentLength", kResourceContentLengthTestPage);
}

// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
  RunTest("testResourceHeaders", kResourceTestPage);
}

// Tests cached resource mime type.
// @see http://crbug.com/27364
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) {
  RunTest("testCachedResourceMimeType", kResourceTestPage);
}

// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
  RunTest("testProfilerTab", kJsPage);
}

// Tests heap profiler.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {
  RunTest("testHeapProfiler", kHeapProfilerPage);
}

// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
  RunTest("testShowScriptsTab", kDebuggerTestPage);
}

// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
  // Clear inspector settings to ensure that Elements will be
  // current panel when DevTools window is open.
  GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
  RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
          kDebuggerTestPage);
}

// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
                       TestContentScriptIsPresent) {
  LoadExtension("simple_content_script");
  RunTest("testContentScriptIsPresent", kPageWithContentScript);
}

// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       TestNoScriptDuplicatesOnPanelSwitch) {
  RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}

// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
// Disabled. See http://code.google.com/p/chromium/issues/detail?id=53406
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       DISABLED_TestPauseWhenLoadingDevTools) {
  RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}

// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
// The test fails on linux and should be related to Webkit patch
// http://trac.webkit.org/changeset/64124/trunk.
// Disabled. See http://code.google.com/p/chromium/issues/detail?id=53406
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       DISABLED_TestPauseWhenScriptIsRunning) {
  RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}

// Fails after WebKit roll 66724:66804, http://crbug.com/54592
#if defined(OS_LINUX) || defined(OS_WIN)
#define MAYBE_TestCompletionOnPause FAILS_TestCompletionOnPause
#else
#define MAYBE_TestCompletionOnPause TestCompletionOnPause
#endif  // defined(OS_LINUX) || defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestCompletionOnPause) {
  RunTest("testCompletionOnPause", kCompletionOnPause);
}

// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
  RunTest("testPauseInEval", kDebuggerTestPage);
}

// Test that Storage panel can be shown.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowStoragePanel) {
  RunTest("testShowStoragePanel", kDebuggerTestPage);
}

}  // namespace
<commit_msg>DevTools: delete TestStoragePanel which has been superseded by storage-panel-show.html<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"

namespace {

// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
 public:
  explicit BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
                   Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    MessageLoopForUI::current()->Quit();
  }

 private:
  NotificationRegistrar registrar_;
  DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};

// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;

const char kConsoleTestPage[] = "files/devtools/console_test_page.html";
const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html";
const char kJsPage[] = "files/devtools/js_page.html";
const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html";
const char kPauseWhenLoadingDevTools[] =
    "files/devtools/pause_when_loading_devtools.html";
const char kPauseWhenScriptIsRunning[] =
    "files/devtools/pause_when_script_is_running.html";
const char kResourceContentLengthTestPage[] = "files/devtools/image.html";
const char kResourceTestPage[] = "files/devtools/resource_test_page.html";
const char kSimplePage[] = "files/devtools/simple_page.html";
const char kCompletionOnPause[] =
    "files/devtools/completion_on_pause.html";
const char kPageWithContentScript[] =
    "files/devtools/page_with_content_script.html";

class DevToolsSanityTest : public InProcessBrowserTest {
 public:
  DevToolsSanityTest() {
    set_show_window(true);
    EnableDOMAutomation();
  }

 protected:
  void RunTest(const std::string& test_name, const std::string& test_page) {
    OpenDevToolsWindow(test_page);
    std::string result;

    // At first check that JavaScript part of the front-end is loaded by
    // checking that global variable uiTests exists(it's created after all js
    // files have been loaded) and has runTest method.
    ASSERT_TRUE(
        ui_test_utils::ExecuteJavaScriptAndExtractString(
            client_contents_->render_view_host(),
            L"",
            L"window.domAutomationController.send("
            L"'' + (window.uiTests && (typeof uiTests.runTest)));",
            &result));

    if (result == "function") {
      ASSERT_TRUE(
          ui_test_utils::ExecuteJavaScriptAndExtractString(
              client_contents_->render_view_host(),
              L"",
              UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
                                      test_name.c_str())),
              &result));
      EXPECT_EQ("[OK]", result);
    } else {
      FAIL() << "DevTools front-end is broken.";
    }
    CloseDevToolsWindow();
  }

  void OpenDevToolsWindow(const std::string& test_page) {
    ASSERT_TRUE(test_server()->Start());
    GURL url = test_server()->GetURL(test_page);
    ui_test_utils::NavigateToURL(browser(), url);

    inspected_rvh_ = GetInspectedTab()->render_view_host();
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    devtools_manager->OpenDevToolsWindow(inspected_rvh_);

    DevToolsClientHost* client_host =
        devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
    window_ = client_host->AsDevToolsWindow();
    RenderViewHost* client_rvh = window_->GetRenderViewHost();
    client_contents_ = client_rvh->delegate()->GetAsTabContents();
    ui_test_utils::WaitForNavigation(&client_contents_->controller());
  }

  TabContents* GetInspectedTab() {
    return browser()->GetTabContentsAt(0);
  }

  void CloseDevToolsWindow() {
    DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
    // UnregisterDevToolsClientHostFor may destroy window_ so store the browser
    // first.
    Browser* browser = window_->browser();
    devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);

    // Wait only when DevToolsWindow has a browser. For docked DevTools, this
    // is NULL and we skip the wait.
    if (browser)
      BrowserClosedObserver close_observer(browser);
  }

  TabContents* client_contents_;
  DevToolsWindow* window_;
  RenderViewHost* inspected_rvh_;
};

class CancelableQuitTask : public Task {
 public:
  explicit CancelableQuitTask(const std::string& timeout_message)
      : timeout_message_(timeout_message),
        cancelled_(false) {
  }

  void cancel() {
    cancelled_ = true;
  }

  virtual void Run() {
    if (cancelled_) {
      return;
    }
    FAIL() << timeout_message_;
    MessageLoop::current()->Quit();
  }

 private:
  std::string timeout_message_;
  bool cancelled_;
};

// Base class for DevTools tests that test devtools functionality for
// extensions and content scripts.
class DevToolsExtensionDebugTest : public DevToolsSanityTest,
                                   public NotificationObserver {
 public:
  DevToolsExtensionDebugTest() : DevToolsSanityTest() {
    PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_);
    test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools");
    test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions");
  }

 protected:
  // Load an extention from test\data\devtools\extensions\<extension_name>
  void LoadExtension(const char* extension_name) {
    FilePath path = test_extensions_dir_.AppendASCII(extension_name);
    ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension.";
  }

 private:
  bool LoadExtensionFromPath(const FilePath& path) {
    ExtensionsService* service = browser()->profile()->GetExtensionsService();
    size_t num_before = service->extensions()->size();
    {
      NotificationRegistrar registrar;
      registrar.Add(this, NotificationType::EXTENSION_LOADED,
                    NotificationService::AllSources());
      CancelableQuitTask* delayed_quit =
          new CancelableQuitTask("Extension load timed out.");
      MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
          4*1000);
      service->LoadExtension(path);
      ui_test_utils::RunMessageLoop();
      delayed_quit->cancel();
    }
    size_t num_after = service->extensions()->size();
    if (num_after != (num_before + 1))
      return false;

    return WaitForExtensionHostsToLoad();
  }

  bool WaitForExtensionHostsToLoad() {
    // Wait for all the extension hosts that exist to finish loading.
    // NOTE: This assumes that the extension host list is not changing while
    // this method is running.

    NotificationRegistrar registrar;
    registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
                  NotificationService::AllSources());
    CancelableQuitTask* delayed_quit =
        new CancelableQuitTask("Extension host load timed out.");
    MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit,
        4*1000);

    ExtensionProcessManager* manager =
          browser()->profile()->GetExtensionProcessManager();
    for (ExtensionProcessManager::const_iterator iter = manager->begin();
         iter != manager->end();) {
      if ((*iter)->did_stop_loading())
        ++iter;
      else
        ui_test_utils::RunMessageLoop();
    }

    delayed_quit->cancel();
    return true;
  }

  void Observe(NotificationType type,
               const NotificationSource& source,
               const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::EXTENSION_LOADED:
      case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
        MessageLoopForUI::current()->Quit();
        break;
      default:
        NOTREACHED();
        break;
    }
  }

  FilePath test_extensions_dir_;
};

// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) {
  RunTest("testEnableResourcesTab", kSimplePage);
}

// Fails after WebKit roll 59365:59477, http://crbug.com/44202.
#if defined(OS_LINUX)
#define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength
#else
#define MAYBE_TestResourceContentLength TestResourceContentLength
#endif  // defined(OS_LINUX)

// Tests resources have correct sizes.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestResourceContentLength) {
  RunTest("testResourceContentLength", kResourceContentLengthTestPage);
}

// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) {
  RunTest("testResourceHeaders", kResourceTestPage);
}

// Tests cached resource mime type.
// @see http://crbug.com/27364
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) {
  RunTest("testCachedResourceMimeType", kResourceTestPage);
}

// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) {
  RunTest("testProfilerTab", kJsPage);
}

// Tests heap profiler.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) {
  RunTest("testHeapProfiler", kHeapProfilerPage);
}

// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) {
  RunTest("testShowScriptsTab", kDebuggerTestPage);
}

// Tests that scripts tab is populated with inspected scripts even if it
// hadn't been shown by the moment inspected paged refreshed.
// @see http://crbug.com/26312
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       TestScriptsTabIsPopulatedOnInspectedPageRefresh) {
  // Clear inspector settings to ensure that Elements will be
  // current panel when DevTools window is open.
  GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings();
  RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh",
          kDebuggerTestPage);
}

// Tests that a content script is in the scripts list.
// This test is disabled, see bug 28961.
IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest,
                       TestContentScriptIsPresent) {
  LoadExtension("simple_content_script");
  RunTest("testContentScriptIsPresent", kPageWithContentScript);
}

// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       TestNoScriptDuplicatesOnPanelSwitch) {
  RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}

// Tests that debugger works correctly if pause event occurs when DevTools
// frontend is being loaded.
// Disabled. See http://code.google.com/p/chromium/issues/detail?id=53406
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       DISABLED_TestPauseWhenLoadingDevTools) {
  RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools);
}

// Tests that pressing 'Pause' will pause script execution if the script
// is already running.
// The test fails on linux and should be related to Webkit patch
// http://trac.webkit.org/changeset/64124/trunk.
// Disabled. See http://code.google.com/p/chromium/issues/detail?id=53406
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
                       DISABLED_TestPauseWhenScriptIsRunning) {
  RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning);
}

// Fails after WebKit roll 66724:66804, http://crbug.com/54592
#if defined(OS_LINUX) || defined(OS_WIN)
#define MAYBE_TestCompletionOnPause FAILS_TestCompletionOnPause
#else
#define MAYBE_TestCompletionOnPause TestCompletionOnPause
#endif  // defined(OS_LINUX) || defined(OS_WIN)
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestCompletionOnPause) {
  RunTest("testCompletionOnPause", kCompletionOnPause);
}

// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
  RunTest("testPauseInEval", kDebuggerTestPage);
}

}  // namespace
<|endoftext|>