<commit_before>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * BP1Base.cpp
 *
 *  Created on: Feb 7, 2017
 *      Author: William F Godoy godoywf@ornl.gov
 */

#include "BP1Base.h"
#include "BP1Base.tcc"

#include "adios2/helper/adiosFunctions.h" //CreateDirectory, StringToTimeUnit

namespace adios
{
namespace format
{

BP1Base::BP1Base(MPI_Comm mpiComm, const bool debugMode)
: m_HeapBuffer(debugMode), m_BP1Aggregator(mpiComm, debugMode),
  m_DebugMode(debugMode)
{
}

void BP1Base::InitParameters(const Params &parameters)
{
    // flags for defaults that require constructors
    bool useDefaultInitialBufferSize = true;
    bool useDefaultProfileUnits = true;

    for (const auto &pair : parameters)
    {
        const std::string key(pair.first);
        const std::string value(pair.second);

        if (key == "Profile")
        {
            InitParameterProfile(value);
        }
        else if (key == "ProfileUnits")
        {
            InitParameterProfileUnits(value);
            useDefaultProfileUnits = false;
        }
        else if (key == "BufferGrowthFactor")
        {
            InitParameterBufferGrowth(value);
        }
        else if (key == "InitialBufferSize")
        {
            InitParameterInitBufferSize(value);
            useDefaultInitialBufferSize = false;
        }
        else if (key == "MaxBufferSize")
        {
            InitParameterMaxBufferSize(value);
        }
        else if (key == "Verbose")
        {
            InitParameterVerbose(value);
        }
    }

    // default timer for buffering
    if (m_Profiler.IsActive && useDefaultProfileUnits)
    {
        m_Profiler.Timers.emplace(
            "buffering",
            profiling::Timer("buffering", DefaultTimeUnitEnum, m_DebugMode));

        m_Profiler.Bytes.emplace("buffering", 0);
    }

    if (useDefaultInitialBufferSize)
    {
        m_HeapBuffer.ResizeData(DefaultInitialBufferSize);
    }
}

std::vector<std::string>
BP1Base::GetBPBaseNames(const std::vector<std::string> &names) const noexcept
{
    std::vector<std::string> bpBaseNames;
    bpBaseNames.reserve(names.size());

    for (const auto &name : names)
    {
        bpBaseNames.push_back(GetBPBaseName(name));
    }
    return bpBaseNames;
}

std::string BP1Base::GetBPBaseName(const std::string &name) const noexcept
{
    return AddExtension(name, ".bp");
}

std::vector<std::string>
BP1Base::GetBPNames(const std::vector<std::string> &names) const noexcept
{
    std::vector<std::string> bpNames;
    bpNames.reserve(names.size());

    for (const auto &name : names)
    {
        bpNames.push_back(GetBPName(name));
    }
    return bpNames;
}

std::string BP1Base::GetBPName(const std::string &name) const noexcept
{
    const std::string baseName = AddExtension(name, ".bp");
    // opens a file transport under name.bp/name.bp.rank
    const std::string bpName(baseName + "/" + baseName + "." +
                             std::to_string(m_BP1Aggregator.m_RankMPI));
    return bpName;
}

// PROTECTED
void BP1Base::InitParameterProfile(const std::string value)
{
    if (value == "off" || value == "Off")
    {
        m_Profiler.IsActive = false;
    }
    else if (value == "on" || value == "On")
    {
        m_Profiler.IsActive = true; // default
    }
    else
    {
        if (m_DebugMode)
        {
            throw std::invalid_argument("ERROR: IO SetParameters profile "
                                        "invalid value, valid: "
                                        "profile=on or "
                                        "profile=off, in call to Open\n");
        }
    }
}

void BP1Base::InitParameterProfileUnits(const std::string value)
{
    TimeUnit timeUnit = StringToTimeUnit(value, m_DebugMode);

    if (m_Profiler.Timers.count("buffering") == 1)
    {
        m_Profiler.Timers.erase("buffering");
    }

    m_Profiler.Timers.emplace(
        "buffering", profiling::Timer("buffering", timeUnit, m_DebugMode));

    m_Profiler.Bytes.emplace("buffering", 0);
}

void BP1Base::InitParameterBufferGrowth(const std::string value)
{
    if (m_DebugMode)
    {
        bool success = true;
        try
        {
            m_GrowthFactor = std::stof(value);
        }
        catch (std::exception &e)
        {
            success = false;
        }

        if (!success || m_GrowthFactor <= 1.f)
        {
            throw std::invalid_argument(
                "ERROR: IO SetParameter buffer_growth value "
                "can't be less or equal than 1 (default = 1.5), or couldn't "
                "convert number, in call to Open\n");
        }
    }
    else
    {
        m_GrowthFactor = std::stof(value);
    }
}

void BP1Base::InitParameterInitBufferSize(const std::string value)
{
    const std::string errorMessage(
        "ERROR: couldn't convert value of init_buffer_size IO "
        "SetParameter, valid syntax: InitialBufferSize=10Gb, "
        "InitialBufferSize=1000Mb, InitialBufferSize=16Kb (minimum default), "
        " in call to Open");

    if (m_DebugMode)
    {
        if (value.size() < 2)
        {
            throw std::invalid_argument(errorMessage);
        }
    }

    const std::string number(value.substr(0, value.size() - 2));
    const std::string units(value.substr(value.size() - 2));
    const size_t factor = BytesFactor(units, m_DebugMode);
    size_t bufferSize = DefaultInitialBufferSize; // from ADIOSTypes.h

    if (m_DebugMode)
    {
        bool success = true;
        try
        {
            bufferSize = static_cast<size_t>(std::stoul(number) * factor);
        }
        catch (std::exception &e)
        {
            success = false;
        }

        if (!success || bufferSize < DefaultInitialBufferSize) // 16384b
        {
            throw std::invalid_argument(errorMessage);
        }
    }
    else
    {
        bufferSize = static_cast<size_t>(std::stoul(number) * factor);
    }

    m_HeapBuffer.ResizeData(bufferSize);
}

void BP1Base::InitParameterMaxBufferSize(const std::string value)
{
    const std::string errorMessage(
        "ERROR: couldn't convert value of max_buffer_size IO "
        "SetParameter, valid syntax: MaxBufferSize=10Gb, "
        "MaxBufferSize=1000Mb, MaxBufferSize=16Kb (minimum default), "
        " in call to Open");

    if (m_DebugMode)
    {
        if (value.size() < 2)
        {
            throw std::invalid_argument(errorMessage);
        }
    }

    const std::string number(value.substr(0, value.size() - 2));
    const std::string units(value.substr(value.size() - 2));
    const size_t factor = BytesFactor(units, m_DebugMode);

    if (m_DebugMode)
    {
        bool success = true;
        try
        {
            m_MaxBufferSize = static_cast<size_t>(std::stoul(number) * factor);
        }
        catch (std::exception &e)
        {
            success = false;
        }

        if (!success || m_MaxBufferSize < 16 * 1024) // 16384b
        {
            throw std::invalid_argument(errorMessage);
        }
    }
    else
    {
        m_MaxBufferSize = static_cast<size_t>(std::stoul(number) * factor);
    }
}

void BP1Base::InitParameterVerbose(const std::string value)
{
    if (m_DebugMode)
    {
        bool success = true;
        try
        {
            m_Verbosity = static_cast<unsigned int>(std::stoi(value));
        }
        catch (std::exception &e)
        {
            success = false;
        }

        if (!success || m_Verbosity < 0 || m_Verbosity > 5)
        {
            throw std::invalid_argument(
                "ERROR: value in Verbose=value in IO SetParameters must be "
                "an integer in the range [0,5], in call to Open\n");
        }
    }
    else
    {
        m_Verbosity = static_cast<unsigned int>(std::stoi(value));
    }
}

std::vector<uint8_t>
BP1Base::GetTransportIDs(const std::vector<std::string> &transportsTypes) const
    noexcept
{
    auto lf_GetTransportID = [](const std::string method) -> uint8_t {

        int id = METHOD_UNKNOWN;
        if (method == "NULL")
        {
            id = METHOD_NULL;
        }
        else if (method == "FileDescriptor")
        {
            id = METHOD_POSIX;
        }
        else if (method == "FileStream")
        {
            id = METHOD_FSTREAM;
        }
        else if (method == "FilePointer")
        {
            id = METHOD_FILE;
        }

        return static_cast<uint8_t>(id);
    };

    std::vector<uint8_t> transportsIDs;
    transportsIDs.reserve(transportsTypes.size());

    for (const auto transportType : transportsTypes)
    {
        transportsIDs.push_back(lf_GetTransportID(transportType));
    }

    return transportsIDs;
}

size_t BP1Base::GetProcessGroupIndexSize(const std::string name,
                                         const std::string timeStepName,
                                         const size_t transportsSize) const
    noexcept
{
    // pgIndex + list of methods (transports)
    size_t pgSize =
        (name.length() + timeStepName.length() + 23) + (3 + transportsSize);

    return pgSize;
}

#define declare_template_instantiation(T)                                      \
    template BP1Base::ResizeResult BP1Base::ResizeBuffer(                      \
        const Variable<T> &variable);

ADIOS2_FOREACH_TYPE_1ARG(declare_template_instantiation)
#undef declare_template_instantiation

} // end namespace format
} // end namespace adios
<commit_msg>Correcting a warning from clang on Mac<commit_after>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * BP1Base.cpp
 *
 *  Created on: Feb 7, 2017
 *      Author: William F Godoy godoywf@ornl.gov
 */

#include "BP1Base.h"
#include "BP1Base.tcc"

#include "adios2/helper/adiosFunctions.h" //CreateDirectory, StringToTimeUnit

namespace adios
{
namespace format
{

BP1Base::BP1Base(MPI_Comm mpiComm, const bool debugMode)
: m_HeapBuffer(debugMode), m_BP1Aggregator(mpiComm, debugMode),
  m_DebugMode(debugMode)
{
}

void BP1Base::InitParameters(const Params &parameters)
{
    // flags for defaults that require constructors
    bool useDefaultInitialBufferSize = true;
    bool useDefaultProfileUnits = true;

    for (const auto &pair : parameters)
    {
        const std::string key(pair.first);
        const std::string value(pair.second);

        if (key == "Profile")
        {
            InitParameterProfile(value);
        }
        else if (key == "ProfileUnits")
        {
            InitParameterProfileUnits(value);
            useDefaultProfileUnits = false;
        }
        else if (key == "BufferGrowthFactor")
        {
            InitParameterBufferGrowth(value);
        }
        else if (key == "InitialBufferSize")
        {
            InitParameterInitBufferSize(value);
            useDefaultInitialBufferSize = false;
        }
        else if (key == "MaxBufferSize")
        {
            InitParameterMaxBufferSize(value);
        }
        else if (key == "Verbose")
        {
            InitParameterVerbose(value);
        }
    }

    // default timer for buffering
    if (m_Profiler.IsActive && useDefaultProfileUnits)
    {
        m_Profiler.Timers.emplace(
            "buffering",
            profiling::Timer("buffering", DefaultTimeUnitEnum, m_DebugMode));

        m_Profiler.Bytes.emplace("buffering", 0);
    }

    if (useDefaultInitialBufferSize)
    {
        m_HeapBuffer.ResizeData(DefaultInitialBufferSize);
    }
}

std::vector<std::string>
BP1Base::GetBPBaseNames(const std::vector<std::string> &names) const noexcept
{
    std::vector<std::string> bpBaseNames;
    bpBaseNames.reserve(names.size());

    for (const auto &name : names)
    {
        bpBaseNames.push_back(GetBPBaseName(name));
    }
    return bpBaseNames;
}

std::string BP1Base::GetBPBaseName(const std::string &name) const noexcept
{
    return AddExtension(name, ".bp");
}

std::vector<std::string>
BP1Base::GetBPNames(const std::vector<std::string> &names) const noexcept
{
    std::vector<std::string> bpNames;
    bpNames.reserve(names.size());

    for (const auto &name : names)
    {
        bpNames.push_back(GetBPName(name));
    }
    return bpNames;
}

std::string BP1Base::GetBPName(const std::string &name) const noexcept
{
    const std::string baseName = AddExtension(name, ".bp");
    // opens a file transport under name.bp/name.bp.rank
    const std::string bpName(baseName + "/" + baseName + "." +
                             std::to_string(m_BP1Aggregator.m_RankMPI));
    return bpName;
}

// PROTECTED
void BP1Base::InitParameterProfile(const std::string value)
{
    if (value == "off" || value == "Off")
    {
        m_Profiler.IsActive = false;
    }
    else if (value == "on" || value == "On")
    {
        m_Profiler.IsActive = true; // default
    }
    else
    {
        if (m_DebugMode)
        {
            throw std::invalid_argument("ERROR: IO SetParameters profile "
                                        "invalid value, valid: "
                                        "profile=on or "
                                        "profile=off, in call to Open\n");
        }
    }
}

void BP1Base::InitParameterProfileUnits(const std::string value)
{
    TimeUnit timeUnit = StringToTimeUnit(value, m_DebugMode);

    if (m_Profiler.Timers.count("buffering") == 1)
    {
        m_Profiler.Timers.erase("buffering");
    }

    m_Profiler.Timers.emplace(
        "buffering", profiling::Timer("buffering", timeUnit, m_DebugMode));

    m_Profiler.Bytes.emplace("buffering", 0);
}

void BP1Base::InitParameterBufferGrowth(const std::string value)
{
    if (m_DebugMode)
    {
        bool success = true;
        try
        {
            m_GrowthFactor = std::stof(value);
        }
        catch (std::exception &e)
        {
            success = false;
        }

        if (!success || m_GrowthFactor <= 1.f)
        {
            throw std::invalid_argument(
                "ERROR: IO SetParameter buffer_growth value "
                "can't be less or equal than 1 (default = 1.5), or couldn't "
                "convert number, in call to Open\n");
        }
    }
    else
    {
        m_GrowthFactor = std::stof(value);
    }
}

void BP1Base::InitParameterInitBufferSize(const std::string value)
{
    const std::string errorMessage(
        "ERROR: couldn't convert value of init_buffer_size IO "
        "SetParameter, valid syntax: InitialBufferSize=10Gb, "
        "InitialBufferSize=1000Mb, InitialBufferSize=16Kb (minimum default), "
        " in call to Open");

    if (m_DebugMode)
    {
        if (value.size() < 2)
        {
            throw std::invalid_argument(errorMessage);
        }
    }

    const std::string number(value.substr(0, value.size() - 2));
    const std::string units(value.substr(value.size() - 2));
    const size_t factor = BytesFactor(units, m_DebugMode);
    size_t bufferSize = DefaultInitialBufferSize; // from ADIOSTypes.h

    if (m_DebugMode)
    {
        bool success = true;
        try
        {
            bufferSize = static_cast<size_t>(std::stoul(number) * factor);
        }
        catch (std::exception &e)
        {
            success = false;
        }

        if (!success || bufferSize < DefaultInitialBufferSize) // 16384b
        {
            throw std::invalid_argument(errorMessage);
        }
    }
    else
    {
        bufferSize = static_cast<size_t>(std::stoul(number) * factor);
    }

    m_HeapBuffer.ResizeData(bufferSize);
}

void BP1Base::InitParameterMaxBufferSize(const std::string value)
{
    const std::string errorMessage(
        "ERROR: couldn't convert value of max_buffer_size IO "
        "SetParameter, valid syntax: MaxBufferSize=10Gb, "
        "MaxBufferSize=1000Mb, MaxBufferSize=16Kb (minimum default), "
        " in call to Open");

    if (m_DebugMode)
    {
        if (value.size() < 2)
        {
            throw std::invalid_argument(errorMessage);
        }
    }

    const std::string number(value.substr(0, value.size() - 2));
    const std::string units(value.substr(value.size() - 2));
    const size_t factor = BytesFactor(units, m_DebugMode);

    if (m_DebugMode)
    {
        bool success = true;
        try
        {
            m_MaxBufferSize = static_cast<size_t>(std::stoul(number) * factor);
        }
        catch (std::exception &e)
        {
            success = false;
        }

        if (!success || m_MaxBufferSize < 16 * 1024) // 16384b
        {
            throw std::invalid_argument(errorMessage);
        }
    }
    else
    {
        m_MaxBufferSize = static_cast<size_t>(std::stoul(number) * factor);
    }
}

void BP1Base::InitParameterVerbose(const std::string value)
{
    int verbosity = -1;

    if (m_DebugMode)
    {
        bool success = true;

        try
        {
            verbosity = std::stoi(value);
        }
        catch (std::exception &e)
        {
            success = false;
        }

        if (!success || verbosity < 0 || verbosity > 5)
        {
            throw std::invalid_argument(
                "ERROR: value in Verbose=value in IO SetParameters must be "
                "an integer in the range [0,5], in call to Open\n");
        }
    }
    else
    {
        verbosity = std::stoi(value);
    }

    m_Verbosity = static_cast<unsigned int>(verbosity);
}

std::vector<uint8_t>
BP1Base::GetTransportIDs(const std::vector<std::string> &transportsTypes) const
    noexcept
{
    auto lf_GetTransportID = [](const std::string method) -> uint8_t {

        int id = METHOD_UNKNOWN;
        if (method == "NULL")
        {
            id = METHOD_NULL;
        }
        else if (method == "FileDescriptor")
        {
            id = METHOD_POSIX;
        }
        else if (method == "FileStream")
        {
            id = METHOD_FSTREAM;
        }
        else if (method == "FilePointer")
        {
            id = METHOD_FILE;
        }

        return static_cast<uint8_t>(id);
    };

    std::vector<uint8_t> transportsIDs;
    transportsIDs.reserve(transportsTypes.size());

    for (const auto transportType : transportsTypes)
    {
        transportsIDs.push_back(lf_GetTransportID(transportType));
    }

    return transportsIDs;
}

size_t BP1Base::GetProcessGroupIndexSize(const std::string name,
                                         const std::string timeStepName,
                                         const size_t transportsSize) const
    noexcept
{
    // pgIndex + list of methods (transports)
    size_t pgSize =
        (name.length() + timeStepName.length() + 23) + (3 + transportsSize);

    return pgSize;
}

#define declare_template_instantiation(T)                                      \
    template BP1Base::ResizeResult BP1Base::ResizeBuffer(                      \
        const Variable<T> &variable);

ADIOS2_FOREACH_TYPE_1ARG(declare_template_instantiation)
#undef declare_template_instantiation

} // end namespace format
} // end namespace adios
<|endoftext|>


<commit_before><commit_msg>Add: a new file<commit_after><|endoftext|>


<commit_before>// -----------------------------------------------------------------------------
// Copyright  : (C) 2014 Andreas-C. Bernstein
// License    : MIT (see the file LICENSE)
// Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de>
// Stability  : experimental
//
// Renderer
// -----------------------------------------------------------------------------

#include "renderer.hpp"
#include "SDFloader.hpp"
#include "ray.hpp"

Renderer::Renderer(unsigned w, unsigned h, std::string const& file)
  : width_(w)
  , height_(h)
  , colorbuffer_(w*h, Color(0.0, 0.0, 0.0))
  , filename_(file)
  , ppm_(width_, height_)
{}

Renderer::Renderer(unsigned w, unsigned h, std::string const& file, std::string const& scenefile)
  : width_(w)
  , height_(h)
  , colorbuffer_(w*h, Color(0.0, 0.0, 0.0))
  , filename_(file)
  , scenefile_(scenefile)
  , ppm_(width_, height_)
{
   scene_ = SDFLoader::load(scenefile);
}

void Renderer::render() {
  //const std::size_t checkersize = 20;

  std::cout << "#####RENDERING####"<<std::endl;
  std::cout << "Resolution: "<<scene_.resX<<"x"<<scene_.resY<<std::endl;
  std::cout << "Camera: "<<scene_.camname<<std::endl;
  std::cout << "ambient light "<<scene_.amb<<std::endl;

  for (unsigned y = 0; y < scene_.resY; ++y) {
    for (unsigned x = 0; x < scene_.resX; ++x) {
        Pixel p(x,y);
        p.color = scene_.amb;

        //p.color = Color(0.0, 1.0, float(x)/scene_.resY);
        Ray ray = Ray();
        ray.origin = scene_.camera.GetOrigin();//ray starts at camera
        ray.direction = scene_.camera.GetN();//ray moves in cameras looking direction
        //apply camera fov, little different angle for each pixel
        ray.direction.x -= tan(scene_.camera.GetFovX()*x/scene_.resX-scene_.camera.GetFovX())*ray.direction.z;
        ray.direction.y -= tan(scene_.camera.GetFovX()*x/scene_.resY-scene_.camera.GetFovX())*ray.direction.z;

        typedef std::map<std::string, RenderObject*>::iterator it_type;
        for(it_type iterator = scene_.renderObjects.begin(); iterator != scene_.renderObjects.end(); iterator++) {
            auto intersection = iterator->second->intersect(ray);
            if (intersection.first)
                p.color += iterator->second->getMaterial().getKa();
        }
        write(p);
    }
  }
  //ppm_.save(filename_);
}

void Renderer::write(Pixel const& p) {
  // flip pixels, because of opengl glDrawPixels
  size_t buf_pos = (width_*p.y + p.x);
  if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) {
    std::cerr << "Fatal Error Renderer::write(Pixel p) : "
      << "pixel out of ppm_ : "
      << (int)p.x << "," << (int)p.y
      << std::endl;
  } else {
    colorbuffer_[buf_pos] = p.color;
  }

  ppm_.write(p);
}
<commit_msg>using namespace std<commit_after>// -----------------------------------------------------------------------------
// Copyright  : (C) 2014 Andreas-C. Bernstein
// License    : MIT (see the file LICENSE)
// Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de>
// Stability  : experimental
//
// Renderer
// -----------------------------------------------------------------------------

#include "renderer.hpp"
#include "SDFloader.hpp"
#include "ray.hpp"

using namespace std;

Renderer::Renderer(unsigned w, unsigned h, string const& file)
  : width_(w)
  , height_(h)
  , colorbuffer_(w*h, Color(0.0, 0.0, 0.0))
  , filename_(file)
  , ppm_(width_, height_)
{}

Renderer::Renderer(unsigned w, unsigned h, string const& file, string const& scenefile)
  : width_(w)
  , height_(h)
  , colorbuffer_(w*h, Color(0.0, 0.0, 0.0))
  , filename_(file)
  , scenefile_(scenefile)
  , ppm_(width_, height_)
{
   scene_ = SDFLoader::load(scenefile);
}

void Renderer::render() {
  //const size_t checkersize = 20;

  cout << "#####RENDERING####"<<endl;
  cout << "Resolution: "<<scene_.resX<<"x"<<scene_.resY<<endl;
  cout << "Camera: "<<scene_.camname<<endl;
  cout << "ambient light "<<scene_.amb<<endl;

  for (unsigned y = 0; y < scene_.resY; ++y) {
    for (unsigned x = 0; x < scene_.resX; ++x) {
        Pixel p(x,y);
        p.color = scene_.amb;

        //p.color = Color(0.0, 1.0, float(x)/scene_.resY);
        Ray ray = Ray();
        ray.origin = scene_.camera.GetOrigin();//ray starts at camera
        ray.direction = scene_.camera.GetN();//ray moves in cameras looking direction
        //apply camera fov, little different angle for each pixel
        ray.direction.x -= tan(scene_.camera.GetFovX()*x/scene_.resX-scene_.camera.GetFovX())*ray.direction.z;
        ray.direction.y -= tan(scene_.camera.GetFovX()*x/scene_.resY-scene_.camera.GetFovX())*ray.direction.z;

        for(auto iterator = scene_.renderObjects.begin(); iterator != scene_.renderObjects.end(); iterator++) {
            auto intersection = ((RenderObject*) iterator->second)->intersect(ray);
            if (intersection.first){
                cout << "Intersection with: "<<iterator->first<<endl;
                p.color += ((RenderObject*) iterator->second)->getMaterial().getKa()
                         + ((RenderObject*) iterator->second)->getMaterial().getKd()
                         + ((RenderObject*) iterator->second)->getMaterial().getKs();
            }
        }
        write(p);
    }
  }
  //ppm_.save(filename_);
}

void Renderer::write(Pixel const& p) {
  // flip pixels, because of opengl glDrawPixels
  size_t buf_pos = (width_*p.y + p.x);
  if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) {
    cerr << "Fatal Error Renderer::write(Pixel p) : "
      << "pixel out of ppm_ : "
      << (int)p.x << "," << (int)p.y
      << endl;
  } else {
    colorbuffer_[buf_pos] = p.color;
  }

  ppm_.write(p);
}
<|endoftext|>


<commit_before>// @(#)root/win32:$Name$:$Id$
// Author: Valery Fine   27/01/96

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TGWin32Marker.h"

//______________________________________________________________________________
TGWin32Marker::TGWin32Marker(int n, TPoint *xy, int type){
  fNumNode = n;
  fMarkerType = type;
  if (type >= 2)
     if (fChain = new POINT[n])
      for( int i = 0; i < n; i++ ) {
                 fChain[i].x = xy[i].GetX();
                 fChain[i].y = xy[i].GetY();
      }
  else
     fChain = NULL;
}
//______________________________________________________________________________
TGWin32Marker::~TGWin32Marker(){
//*-*-*-*-*-*-*-*-*-*-*-*Default Destructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*                    ==================
  if (fChain) delete fChain;
}

//______________________________________________________________________________
int    TGWin32Marker::GetNumber(){return fNumNode;}
//______________________________________________________________________________
POINT *TGWin32Marker::GetNodes(){return fChain;}
//______________________________________________________________________________
int  TGWin32Marker::GetType(){return fMarkerType;}

//______________________________________________________________________________
void TGWin32Marker::SetMarker(int n, TPoint *xy, int type){

//*-* Did we have a chain ?

if (fMarkerType >= 2 && fNumNode != n){    // Yes, we had chain
       if (fChain) delete fChain;  // Delete the obsolete chain
       fChain = NULL;
}

//*-*  Create the new shaped marker

if (type >= 2) {
    if (!fChain) fChain = new POINT[n];
    for( int i = 0; i < n; i++ ) {
      fChain[i].x = xy[i].GetX();
      fChain[i].y = xy[i].GetY();
    }
}
else if (fChain) { delete fChain; fChain = NULL; }

fNumNode = n;
fMarkerType = type;

}
<commit_msg>fChain was not always initialized in the constructor. Also fix a bracket problem. Thanks Philippe<commit_after>// @(#)root/win32:$Name:  $:$Id: TGWin32Marker.cxx,v 1.1.1.1 2000/05/16 17:00:46 rdm Exp $
// Author: Valery Fine   27/01/96

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TGWin32Marker.h"

//______________________________________________________________________________
TGWin32Marker::TGWin32Marker(int n, TPoint *xy, int type){
  fNumNode = n;
  fMarkerType = type;
  if (type >= 2) {
     if (fChain = new POINT[n]) {
        for( int i = 0; i < n; i++ ) {
           fChain[i].x = xy[i].GetX();
           fChain[i].y = xy[i].GetY();
        }
     } else {
        fChain = 0;
     }
  } else {
     fChain = 0;
  }
}
//______________________________________________________________________________
TGWin32Marker::~TGWin32Marker(){
//*-*-*-*-*-*-*-*-*-*-*-*Default Destructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*                    ==================
  if (fChain) delete fChain;
}

//______________________________________________________________________________
int    TGWin32Marker::GetNumber(){return fNumNode;}
//______________________________________________________________________________
POINT *TGWin32Marker::GetNodes(){return fChain;}
//______________________________________________________________________________
int  TGWin32Marker::GetType(){return fMarkerType;}

//______________________________________________________________________________
void TGWin32Marker::SetMarker(int n, TPoint *xy, int type){

//*-* Did we have a chain ?

if (fMarkerType >= 2 && fNumNode != n){    // Yes, we had chain
       if (fChain) delete fChain;  // Delete the obsolete chain
       fChain = NULL;
}

//*-*  Create the new shaped marker

if (type >= 2) {
    if (!fChain) fChain = new POINT[n];
    for( int i = 0; i < n; i++ ) {
      fChain[i].x = xy[i].GetX();
      fChain[i].y = xy[i].GetY();
    }
}
else if (fChain) { delete fChain; fChain = NULL; }

fNumNode = n;
fMarkerType = type;

}
<|endoftext|>


<commit_before>// -----------------------------------------------------------------------------
// Copyright  : (C) 2014 Andreas-C. Bernstein
// License    : MIT (see the file LICENSE)
// Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de>
// Stability  : experimental
//
// Renderer
// -----------------------------------------------------------------------------

#include "renderer.hpp"
//#include "optiHit.hpp"

Renderer::Renderer(Scene const& scene)
  :scene_(scene)
  , colorbuffer_(scene.width*scene.height, Color(0.0, 0.0, 0.0))
  , ppm_(scene.width, scene.height)
{}

Renderer::Renderer(Scene const& scene, unsigned w, unsigned h, std::string const& file)
  : scene_(scene)
  , width_(w)
  , height_(h)
  , colorbuffer_(w*h, Color(0.0, 0.0, 0.0))
  , filename_(file)
  , ppm_(width_, height_)
{}

void Renderer::render()
{
  const std::size_t checkersize = 20;

  for (unsigned y = 0; y < height_; ++y) {
    for (unsigned x = 0; x < width_; ++x) {
      Pixel p(x,y);

      Ray ray = scene_.camera.calc_eye_ray(x,y,scene_.height,scene_.width);

      OptiHit hit;
      for (auto const& shape : scene_.shapes)
      {
        hit = shape->intersect(ray,hit.distance);//hier noch abfragen ob nearest
      }

        if ( hit.closest_shape ) {
          //hit = hit.closest_shape->intersect(ray, 0);
          auto surface_pt= hit.closest_shape->calc_surface_pt(ray, hit.distance);
          auto n = hit.closest_shape->calc_n(hit);

          for (auto const& light : scene_.lights)
          {
            Ray pt_to_l{surface_pt, light->pos_};  // make ray: intersection to light sources

            /* generate shadow
            // #################### not working yet #######################################
            float t = 0.0f;
            bool lighted = true;  // initially with light
            for (auto const& shape : scene_.shapes)  // see if any other objects in the way?
            {
              if (shape.get() != hit.closest_shape ) {  // exclude intersection with self
                if (shape->intersect(pt_to_l, t) == true)  // in the way, then no light
                {
                    lighted = false;
                    p.color = Color{0,0,0};
                    break;
                }
              }
            }*/
            // ############################################################################

            glm::vec3 l = pt_to_l.direction_;
            float nl = glm::dot(n,l);
            // calculate light intensity and return color for the pixel
             p.color += Color{ (light->ld_.r) * (hit.closest_shape->get_mat().kd_.r) * nl,
                               (light->ld_.g) * (hit.closest_shape->get_mat().kd_.g) * nl,
                               (light->ld_.b) * (hit.closest_shape->get_mat().kd_.b) * nl };
          }

          // p.color = raytrace(ray, 3);
        } else {
          p.color = Color(0.1,0.1,0.1);
        }

      write(p);
    }
  }
  ppm_.save(filename_);
}
/*
Color raytrace(Ray const& ray) const
{

  return Color;
}
*/

void Renderer::write(Pixel const& p)
{
  // flip pixels, because of opengl glDrawPixels
  size_t buf_pos = (width_*p.y + p.x);
  if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) {
    std::cerr << "Fatal Error Renderer::write(Pixel p) : "
      << "pixel out of ppm_ : "
      << (int)p.x << "," << (int)p.y
      << std::endl;
  } else {
    colorbuffer_[buf_pos] = p.color;
  }

  ppm_.write(p);
}
<commit_msg>jetzt funktioniert es bestimmt<commit_after>// -----------------------------------------------------------------------------
// Copyright  : (C) 2014 Andreas-C. Bernstein
// License    : MIT (see the file LICENSE)
// Maintainer : Andreas-C. Bernstein <andreas.bernstein@uni-weimar.de>
// Stability  : experimental
//
// Renderer
// -----------------------------------------------------------------------------

#include "renderer.hpp"
//#include "optiHit.hpp"

Renderer::Renderer(Scene const& scene)
  :scene_(scene)
  , colorbuffer_(scene.width*scene.height, Color(0.0, 0.0, 0.0))
  , ppm_(scene.width, scene.height)
{}

Renderer::Renderer(Scene const& scene, unsigned w, unsigned h, std::string const& file)
  : scene_(scene)
  , width_(w)
  , height_(h)
  , colorbuffer_(w*h, Color(0.0, 0.0, 0.0))
  , filename_(file)
  , ppm_(width_, height_)
{}

void Renderer::render()
{
  const std::size_t checkersize = 20;

  for (unsigned y = 0; y < height_; ++y) {
    for (unsigned x = 0; x < width_; ++x) {
      Pixel p(x,y);

      Ray ray = scene_.camera.calc_eye_ray(x,y,scene_.height,scene_.width);

      OptiHit hit;
      for (auto const& shape : scene_.shapes)
      {
        hit = shape->intersect(ray,hit.distance);//hier noch abfragen ob nearest
      }

        if ( hit.closest_shape ) {
          hit = hit.closest_shape->intersect(ray, 0);
          auto surface_pt= hit.closest_shape->calc_surface_pt(ray, hit.distance);
          auto n = hit.closest_shape->calc_n(hit);

          for (auto const& light : scene_.lights)
          {
            Ray pt_to_l{surface_pt, light->pos_};  // make ray: intersection to light sources

            /* generate shadow
            // #################### not working yet #######################################
            float t = 0.0f;
            bool lighted = true;  // initially with light
            for (auto const& shape : scene_.shapes)  // see if any other objects in the way?
            {
              if (shape.get() != hit.closest_shape ) {  // exclude intersection with self
                if (shape->intersect(pt_to_l, t) == true)  // in the way, then no light
                {
                    lighted = false;
                    p.color = Color{0,0,0};
                    break;
                }
              }
            }*/
            // ############################################################################

            glm::vec3 l = pt_to_l.direction_;
            float nl = glm::dot(n,l);
            // calculate light intensity and return color for the pixel
             p.color += Color{ (light->ld_.r) * (hit.closest_shape->get_mat().kd_.r) * nl,
                               (light->ld_.g) * (hit.closest_shape->get_mat().kd_.g) * nl,
                               (light->ld_.b) * (hit.closest_shape->get_mat().kd_.b) * nl };
          }

          // p.color = raytrace(ray, 3);
        } else {
          p.color = Color(0.1,0.1,0.1);
        }

      write(p);
    }
  }
  ppm_.save(filename_);
}
/*
Color raytrace(Ray const& ray) const
{

  return Color;
}
*/

void Renderer::write(Pixel const& p)
{
  // flip pixels, because of opengl glDrawPixels
  size_t buf_pos = (width_*p.y + p.x);
  if (buf_pos >= colorbuffer_.size() || (int)buf_pos < 0) {
    std::cerr << "Fatal Error Renderer::write(Pixel p) : "
      << "pixel out of ppm_ : "
      << (int)p.x << "," << (int)p.y
      << std::endl;
  } else {
    colorbuffer_[buf_pos] = p.color;
  }

  ppm_.write(p);
}
<|endoftext|>


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

#include "acm_pcm16b.h"

#include "acm_codec_database.h"
#include "acm_common_defs.h"
#include "acm_neteq.h"
#include "trace.h"
#include "webrtc_neteq.h"
#include "webrtc_neteq_help_macros.h"

#ifdef WEBRTC_CODEC_PCM16
    #include "pcm16b.h"
#endif

namespace webrtc {

#ifndef WEBRTC_CODEC_PCM16

ACMPCM16B::ACMPCM16B(WebRtc_Word16 /* codecID */) {
  return;
}

ACMPCM16B::~ACMPCM16B() {
  return;
}

WebRtc_Word16 ACMPCM16B::InternalEncode(WebRtc_UWord8* /* bitStream */,
                                        WebRtc_Word16* /* bitStreamLenByte */) {
  return -1;
}

WebRtc_Word16 ACMPCM16B::DecodeSafe(WebRtc_UWord8* /* bitStream */,
                                    WebRtc_Word16 /* bitStreamLenByte */,
                                    WebRtc_Word16* /* audio */,
                                    WebRtc_Word16* /* audioSamples */,
                                    WebRtc_Word8* /* speechType */) {
  return -1;
}

WebRtc_Word16 ACMPCM16B::InternalInitEncoder(
    WebRtcACMCodecParams* /* codecParams */) {
  return -1;
}

WebRtc_Word16 ACMPCM16B::InternalInitDecoder(
    WebRtcACMCodecParams* /* codecParams */) {
  return -1;
}

WebRtc_Word32 ACMPCM16B::CodecDef(WebRtcNetEQ_CodecDef& /* codecDef */,
                                  const CodecInst& /* codecInst */) {
  return -1;
}

ACMGenericCodec* ACMPCM16B::CreateInstance(void) {
  return NULL;
}

WebRtc_Word16 ACMPCM16B::InternalCreateEncoder() {
  return -1;
}

WebRtc_Word16 ACMPCM16B::InternalCreateDec WEBRTC_CODEC_PCM16oder() {
  return -1;
}

void ACMPCM16B::InternalDestructEncoderInst(void* /* ptrInst */) {
  return;
}

void ACMPCM16B::DestructEncoderSafe() {
  return;
}

void ACMPCM16B::DestructDecoderSafe() {
  return;
}

void ACMPCM16B::SplitStereoPacket(uint8_t* /*payload*/,
                                  int32_t* /*payload_length*/) {
}

#else     //===================== Actual Implementation =======================

ACMPCM16B::ACMPCM16B(WebRtc_Word16 codecID) {
  _codecID = codecID;
  _samplingFreqHz = ACMCodecDB::CodecFreq(_codecID);
}

ACMPCM16B::~ACMPCM16B() {
  return;
}

WebRtc_Word16 ACMPCM16B::InternalEncode(WebRtc_UWord8* bitStream,
                                        WebRtc_Word16* bitStreamLenByte) {
  *bitStreamLenByte = WebRtcPcm16b_Encode(&_inAudio[_inAudioIxRead],
                                          _frameLenSmpl * _noChannels,
                                          bitStream);
  // Increment the read index to tell the caller that how far
  // we have gone forward in reading the audio buffer.
  _inAudioIxRead += _frameLenSmpl * _noChannels;
  return *bitStreamLenByte;
}

WebRtc_Word16 ACMPCM16B::DecodeSafe(WebRtc_UWord8* /* bitStream */,
                                    WebRtc_Word16 /* bitStreamLenByte */,
                                    WebRtc_Word16* /* audio */,
                                    WebRtc_Word16* /* audioSamples */,
                                    WebRtc_Word8* /* speechType */) {
  return 0;
}

WebRtc_Word16 ACMPCM16B::InternalInitEncoder(
    WebRtcACMCodecParams* /* codecParams */) {
  // This codec does not need initialization, PCM has no instance.
  return 0;
}

WebRtc_Word16 ACMPCM16B::InternalInitDecoder(
    WebRtcACMCodecParams* /* codecParams */) {
  // This codec does not need initialization, PCM has no instance.
  return 0;
}

WebRtc_Word32 ACMPCM16B::CodecDef(WebRtcNetEQ_CodecDef& codecDef,
                                  const CodecInst& codecInst) {
  // Fill up the structure by calling "SET_CODEC_PAR" & "SET_PCMU_FUNCTION".
  // Then call NetEQ to add the codec to it's database.
  if (codecInst.channels == 1) {
    switch(_samplingFreqHz) {
      case 8000: {
        SET_CODEC_PAR(codecDef, kDecoderPCM16B, codecInst.pltype, NULL, 8000);
        SET_PCM16B_FUNCTIONS(codecDef);
        break;
      }
      case 16000: {
        SET_CODEC_PAR(codecDef, kDecoderPCM16Bwb, codecInst.pltype, NULL,
                      16000);
        SET_PCM16B_WB_FUNCTIONS(codecDef);
        break;
      }
      case 32000: {
        SET_CODEC_PAR(codecDef, kDecoderPCM16Bswb32kHz, codecInst.pltype,
                      NULL, 32000);
        SET_PCM16B_SWB32_FUNCTIONS(codecDef);
        break;
      }
      default: {
        return -1;
      }
    }
  } else {
    switch(_samplingFreqHz) {
      case 8000: {
        SET_CODEC_PAR(codecDef, kDecoderPCM16B_2ch, codecInst.pltype, NULL,
                      8000);
        SET_PCM16B_FUNCTIONS(codecDef);
        break;
      }
      case 16000: {
        SET_CODEC_PAR(codecDef, kDecoderPCM16Bwb_2ch, codecInst.pltype,
                      NULL, 16000);
        SET_PCM16B_WB_FUNCTIONS(codecDef);
        break;
      }
      case 32000: {
        SET_CODEC_PAR(codecDef, kDecoderPCM16Bswb32kHz_2ch, codecInst.pltype,
                      NULL, 32000);
        SET_PCM16B_SWB32_FUNCTIONS(codecDef);
        break;
      }
      default: {
        return -1;
      }
    }
  }
  return 0;
}

ACMGenericCodec* ACMPCM16B::CreateInstance(void) {
  return NULL;
}

WebRtc_Word16 ACMPCM16B::InternalCreateEncoder() {
  // PCM has no instance.
  return 0;
}

WebRtc_Word16 ACMPCM16B::InternalCreateDecoder() {
  // PCM has no instance.
  return 0;
}

void ACMPCM16B::InternalDestructEncoderInst(void* /* ptrInst */) {
  // PCM has no instance.
  return;
}

void ACMPCM16B::DestructEncoderSafe() {
  // PCM has no instance.
  _encoderExist = false;
  _encoderInitialized = false;
  return;
}

void ACMPCM16B::DestructDecoderSafe() {
  // PCM has no instance.
  _decoderExist = false;
  _decoderInitialized = false;
  return;
}

// Split the stereo packet and place left and right channel after each other
// in the payload vector.
void ACMPCM16B::SplitStereoPacket(uint8_t* payload, int32_t* payload_length) {
  uint8_t right_byte_msb;
  uint8_t right_byte_lsb;

  // Check for valid inputs.
  assert(payload != NULL);
  assert(*payload_length > 0);

  // Move two bytes representing right channel each loop, and place it at the
  // end of the bytestream vector. After looping the data is reordered to:
  // l1 l2 l3 l4 ... l(N-1) lN r1 r2 r3 r4 ... r(N-1) r(N),
  // where N is the total number of samples.

  for (int i = 0; i < *payload_length / 2; i += 2) {
    right_byte_msb = payload[i + 2];
    right_byte_lsb = payload[i + 3];
    memmove(&payload[i + 2], &payload[i + 4], *payload_length - i - 4);
    payload[*payload_length - 2] = right_byte_msb;
    payload[*payload_length - 1] = right_byte_lsb;
  }
}
#endif

} // namespace webrtc
<commit_msg>ACM PCM16B, fixing a copy-and-paste error.<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "acm_pcm16b.h"

#include "acm_codec_database.h"
#include "acm_common_defs.h"
#include "acm_neteq.h"
#include "trace.h"
#include "webrtc_neteq.h"
#include "webrtc_neteq_help_macros.h"

#ifdef WEBRTC_CODEC_PCM16
    #include "pcm16b.h"
#endif

namespace webrtc {

#ifndef WEBRTC_CODEC_PCM16

ACMPCM16B::ACMPCM16B(WebRtc_Word16 /* codecID */) {
  return;
}

ACMPCM16B::~ACMPCM16B() {
  return;
}

WebRtc_Word16 ACMPCM16B::InternalEncode(WebRtc_UWord8* /* bitStream */,
                                        WebRtc_Word16* /* bitStreamLenByte */) {
  return -1;
}

WebRtc_Word16 ACMPCM16B::DecodeSafe(WebRtc_UWord8* /* bitStream */,
                                    WebRtc_Word16 /* bitStreamLenByte */,
                                    WebRtc_Word16* /* audio */,
                                    WebRtc_Word16* /* audioSamples */,
                                    WebRtc_Word8* /* speechType */) {
  return -1;
}

WebRtc_Word16 ACMPCM16B::InternalInitEncoder(
    WebRtcACMCodecParams* /* codecParams */) {
  return -1;
}

WebRtc_Word16 ACMPCM16B::InternalInitDecoder(
    WebRtcACMCodecParams* /* codecParams */) {
  return -1;
}

WebRtc_Word32 ACMPCM16B::CodecDef(WebRtcNetEQ_CodecDef& /* codecDef */,
                                  const CodecInst& /* codecInst */) {
  return -1;
}

ACMGenericCodec* ACMPCM16B::CreateInstance(void) {
  return NULL;
}

WebRtc_Word16 ACMPCM16B::InternalCreateEncoder() {
  return -1;
}

WebRtc_Word16 ACMPCM16B::InternalCreateDecoder() {
  return -1;
}

void ACMPCM16B::InternalDestructEncoderInst(void* /* ptrInst */) {
  return;
}

void ACMPCM16B::DestructEncoderSafe() {
  return;
}

void ACMPCM16B::DestructDecoderSafe() {
  return;
}

void ACMPCM16B::SplitStereoPacket(uint8_t* /*payload*/,
                                  int32_t* /*payload_length*/) {
}

#else     //===================== Actual Implementation =======================

ACMPCM16B::ACMPCM16B(WebRtc_Word16 codecID) {
  _codecID = codecID;
  _samplingFreqHz = ACMCodecDB::CodecFreq(_codecID);
}

ACMPCM16B::~ACMPCM16B() {
  return;
}

WebRtc_Word16 ACMPCM16B::InternalEncode(WebRtc_UWord8* bitStream,
                                        WebRtc_Word16* bitStreamLenByte) {
  *bitStreamLenByte = WebRtcPcm16b_Encode(&_inAudio[_inAudioIxRead],
                                          _frameLenSmpl * _noChannels,
                                          bitStream);
  // Increment the read index to tell the caller that how far
  // we have gone forward in reading the audio buffer.
  _inAudioIxRead += _frameLenSmpl * _noChannels;
  return *bitStreamLenByte;
}

WebRtc_Word16 ACMPCM16B::DecodeSafe(WebRtc_UWord8* /* bitStream */,
                                    WebRtc_Word16 /* bitStreamLenByte */,
                                    WebRtc_Word16* /* audio */,
                                    WebRtc_Word16* /* audioSamples */,
                                    WebRtc_Word8* /* speechType */) {
  return 0;
}

WebRtc_Word16 ACMPCM16B::InternalInitEncoder(
    WebRtcACMCodecParams* /* codecParams */) {
  // This codec does not need initialization, PCM has no instance.
  return 0;
}

WebRtc_Word16 ACMPCM16B::InternalInitDecoder(
    WebRtcACMCodecParams* /* codecParams */) {
  // This codec does not need initialization, PCM has no instance.
  return 0;
}

WebRtc_Word32 ACMPCM16B::CodecDef(WebRtcNetEQ_CodecDef& codecDef,
                                  const CodecInst& codecInst) {
  // Fill up the structure by calling "SET_CODEC_PAR" & "SET_PCMU_FUNCTION".
  // Then call NetEQ to add the codec to it's database.
  if (codecInst.channels == 1) {
    switch(_samplingFreqHz) {
      case 8000: {
        SET_CODEC_PAR(codecDef, kDecoderPCM16B, codecInst.pltype, NULL, 8000);
        SET_PCM16B_FUNCTIONS(codecDef);
        break;
      }
      case 16000: {
        SET_CODEC_PAR(codecDef, kDecoderPCM16Bwb, codecInst.pltype, NULL,
                      16000);
        SET_PCM16B_WB_FUNCTIONS(codecDef);
        break;
      }
      case 32000: {
        SET_CODEC_PAR(codecDef, kDecoderPCM16Bswb32kHz, codecInst.pltype,
                      NULL, 32000);
        SET_PCM16B_SWB32_FUNCTIONS(codecDef);
        break;
      }
      default: {
        return -1;
      }
    }
  } else {
    switch(_samplingFreqHz) {
      case 8000: {
        SET_CODEC_PAR(codecDef, kDecoderPCM16B_2ch, codecInst.pltype, NULL,
                      8000);
        SET_PCM16B_FUNCTIONS(codecDef);
        break;
      }
      case 16000: {
        SET_CODEC_PAR(codecDef, kDecoderPCM16Bwb_2ch, codecInst.pltype,
                      NULL, 16000);
        SET_PCM16B_WB_FUNCTIONS(codecDef);
        break;
      }
      case 32000: {
        SET_CODEC_PAR(codecDef, kDecoderPCM16Bswb32kHz_2ch, codecInst.pltype,
                      NULL, 32000);
        SET_PCM16B_SWB32_FUNCTIONS(codecDef);
        break;
      }
      default: {
        return -1;
      }
    }
  }
  return 0;
}

ACMGenericCodec* ACMPCM16B::CreateInstance(void) {
  return NULL;
}

WebRtc_Word16 ACMPCM16B::InternalCreateEncoder() {
  // PCM has no instance.
  return 0;
}

WebRtc_Word16 ACMPCM16B::InternalCreateDecoder() {
  // PCM has no instance.
  return 0;
}

void ACMPCM16B::InternalDestructEncoderInst(void* /* ptrInst */) {
  // PCM has no instance.
  return;
}

void ACMPCM16B::DestructEncoderSafe() {
  // PCM has no instance.
  _encoderExist = false;
  _encoderInitialized = false;
  return;
}

void ACMPCM16B::DestructDecoderSafe() {
  // PCM has no instance.
  _decoderExist = false;
  _decoderInitialized = false;
  return;
}

// Split the stereo packet and place left and right channel after each other
// in the payload vector.
void ACMPCM16B::SplitStereoPacket(uint8_t* payload, int32_t* payload_length) {
  uint8_t right_byte_msb;
  uint8_t right_byte_lsb;

  // Check for valid inputs.
  assert(payload != NULL);
  assert(*payload_length > 0);

  // Move two bytes representing right channel each loop, and place it at the
  // end of the bytestream vector. After looping the data is reordered to:
  // l1 l2 l3 l4 ... l(N-1) lN r1 r2 r3 r4 ... r(N-1) r(N),
  // where N is the total number of samples.

  for (int i = 0; i < *payload_length / 2; i += 2) {
    right_byte_msb = payload[i + 2];
    right_byte_lsb = payload[i + 3];
    memmove(&payload[i + 2], &payload[i + 4], *payload_length - i - 4);
    payload[*payload_length - 2] = right_byte_msb;
    payload[*payload_length - 1] = right_byte_lsb;
  }
}
#endif

} // namespace webrtc
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla 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.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "sets.hh"
#include "constants.hh"
#include "cql3_type.hh"

namespace cql3 {

shared_ptr<column_specification>
sets::value_spec_of(shared_ptr<column_specification> column) {
    return make_shared<column_specification>(column->ks_name, column->cf_name,
            ::make_shared<column_identifier>(sprint("value(%s)", *column->name), true),
            dynamic_pointer_cast<const set_type_impl>(column->type)->get_elements_type());
}

shared_ptr<term>
sets::literal::prepare(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) {
    validate_assignable_to(db, keyspace, receiver);

    // We've parsed empty maps as a set literal to break the ambiguity so
    // handle that case now
    if (_elements.empty() && dynamic_pointer_cast<const map_type_impl>(receiver->type)) {
        // use empty_type for comparator, set is empty anyway.
        std::map<bytes, bytes, serialized_compare> m(empty_type->as_less_comparator());
        return ::make_shared<maps::value>(std::move(m));
    }

    auto value_spec = value_spec_of(receiver);
    std::vector<shared_ptr<term>> values;
    values.reserve(_elements.size());
    bool all_terminal = true;
    for (shared_ptr<term::raw> rt : _elements)
    {
        auto t = rt->prepare(db, keyspace, value_spec);

        if (t->contains_bind_marker()) {
            throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s: bind variables are not supported inside collection literals", *receiver->name));
        }

        if (dynamic_pointer_cast<non_terminal>(t)) {
            all_terminal = false;
        }

        values.push_back(std::move(t));
    }
    auto compare = dynamic_pointer_cast<const set_type_impl>(receiver->type)->get_elements_type()->as_less_comparator();

    auto value = ::make_shared<delayed_value>(compare, std::move(values));
    if (all_terminal) {
        return value->bind(query_options::DEFAULT);
    } else {
        return value;
    }
}

void
sets::literal::validate_assignable_to(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) {
    if (!dynamic_pointer_cast<const set_type_impl>(receiver->type)) {
        // We've parsed empty maps as a set literal to break the ambiguity so
        // handle that case now
        if (dynamic_pointer_cast<const map_type_impl>(receiver->type) && _elements.empty()) {
            return;
        }

        throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s of type %s", *receiver->name, *receiver->type->as_cql3_type()));
    }

    auto&& value_spec = value_spec_of(receiver);
    for (shared_ptr<term::raw> rt : _elements) {
        if (!is_assignable(rt->test_assignment(db, keyspace, value_spec))) {
            throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s: value %s is not of type %s", *receiver->name, *rt, *value_spec->type->as_cql3_type()));
        }
    }
}

assignment_testable::test_result
sets::literal::test_assignment(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) {
    if (!dynamic_pointer_cast<const set_type_impl>(receiver->type)) {
        // We've parsed empty maps as a set literal to break the ambiguity so handle that case now
        if (dynamic_pointer_cast<const map_type_impl>(receiver->type) && _elements.empty()) {
            return assignment_testable::test_result::WEAKLY_ASSIGNABLE;
        }

        return assignment_testable::test_result::NOT_ASSIGNABLE;
    }

    // If there is no elements, we can't say it's an exact match (an empty set if fundamentally polymorphic).
    if (_elements.empty()) {
        return assignment_testable::test_result::WEAKLY_ASSIGNABLE;
    }

    auto&& value_spec = value_spec_of(receiver);
    // FIXME: make assignment_testable::test_all() accept ranges
    std::vector<shared_ptr<assignment_testable>> to_test(_elements.begin(), _elements.end());
    return assignment_testable::test_all(db, keyspace, value_spec, to_test);
}

sstring
sets::literal::to_string() const {
    return "{" + join(", ", _elements) + "}";
}

sets::value
sets::value::from_serialized(bytes_view v, set_type type, cql_serialization_format sf) {
    try {
        // Collections have this small hack that validate cannot be called on a serialized object,
        // but compose does the validation (so we're fine).
        // FIXME: deserializeForNativeProtocol?!
        auto s = value_cast<set_type_impl::native_type>(type->deserialize(v, sf));
        std::set<bytes, serialized_compare> elements(type->get_elements_type()->as_less_comparator());
        for (auto&& element : s) {
            elements.insert(elements.end(), type->get_elements_type()->decompose(element));
        }
        return value(std::move(elements));
    } catch (marshal_exception& e) {
        throw exceptions::invalid_request_exception(e.what());
    }
}

cql3::raw_value
sets::value::get(const query_options& options) {
    return cql3::raw_value::make_value(get_with_protocol_version(options.get_cql_serialization_format()));
}

bytes
sets::value::get_with_protocol_version(cql_serialization_format sf) {
    return collection_type_impl::pack(_elements.begin(), _elements.end(),
            _elements.size(), sf);
}

bool
sets::value::equals(set_type st, const value& v) {
    if (_elements.size() != v._elements.size()) {
        return false;
    }
    auto&& elements_type = st->get_elements_type();
    return std::equal(_elements.begin(), _elements.end(),
            v._elements.begin(),
            [elements_type] (bytes_view v1, bytes_view v2) {
                return elements_type->equal(v1, v2);
            });
}

sstring
sets::value::to_string() const {
    sstring result = "{";
    bool first = true;
    for (auto&& e : _elements) {
        if (!first) {
            result += ", ";
        }
        first = true;
        result += to_hex(e);
    }
    result += "}";
    return result;
}

bool
sets::delayed_value::contains_bind_marker() const {
    // False since we don't support them in collection
    return false;
}

void
sets::delayed_value::collect_marker_specification(shared_ptr<variable_specifications> bound_names) {
}

shared_ptr<terminal>
sets::delayed_value::bind(const query_options& options) {
    std::set<bytes, serialized_compare> buffers(_comparator);
    for (auto&& t : _elements) {
        auto b = t->bind_and_get(options);

        if (b.is_null()) {
            throw exceptions::invalid_request_exception("null is not supported inside collections");
        }
        if (b.is_unset_value()) {
            return constants::UNSET_VALUE;
        }
        // We don't support value > 64K because the serialization format encode the length as an unsigned short.
        if (b->size() > std::numeric_limits<uint16_t>::max()) {
            throw exceptions::invalid_request_exception(sprint("Set value is too long. Set values are limited to %d bytes but %d bytes value provided",
                    std::numeric_limits<uint16_t>::max(),
                    b->size()));
        }

        buffers.insert(buffers.end(), std::move(to_bytes(*b)));
    }
    return ::make_shared<value>(std::move(buffers));
}

::shared_ptr<terminal>
sets::marker::bind(const query_options& options) {
    const auto& value = options.get_value_at(_bind_index);
    if (value.is_null()) {
        return nullptr;
    } else if (value.is_unset_value()) {
        return constants::UNSET_VALUE;
    } else {
        auto as_set_type = static_pointer_cast<const set_type_impl>(_receiver->type);
        return make_shared(value::from_serialized(*value, as_set_type, options.get_cql_serialization_format()));
    }
}

void
sets::setter::execute(mutation& m, const clustering_key_prefix& row_key, const update_parameters& params) {
    auto value = _t->bind(params._options);
    execute(m, row_key, params, column, std::move(value));
}

void
sets::setter::execute(mutation& m, const clustering_key_prefix& row_key, const update_parameters& params, const column_definition& column, ::shared_ptr<terminal> value) {
    if (value == constants::UNSET_VALUE) {
        return;
    }
    if (column.type->is_multi_cell()) {
        // delete + add
        collection_type_impl::mutation mut;
        mut.tomb = params.make_tombstone_just_before();
        auto ctype = static_pointer_cast<const set_type_impl>(column.type);
        auto col_mut = ctype->serialize_mutation_form(std::move(mut));
        m.set_cell(row_key, column, std::move(col_mut));
    }
    adder::do_add(m, row_key, params, value, column);
}

void
sets::adder::execute(mutation& m, const clustering_key_prefix& row_key, const update_parameters& params) {
    const auto& value = _t->bind(params._options);
    if (value == constants::UNSET_VALUE) {
        return;
    }
    assert(column.type->is_multi_cell()); // "Attempted to add items to a frozen set";
    do_add(m, row_key, params, value, column);
}

void
sets::adder::do_add(mutation& m, const clustering_key_prefix& row_key, const update_parameters& params,
        shared_ptr<term> value, const column_definition& column) {
    auto set_value = dynamic_pointer_cast<sets::value>(std::move(value));
    auto set_type = dynamic_pointer_cast<const set_type_impl>(column.type);
    if (column.type->is_multi_cell()) {
        // FIXME: mutation_view? not compatible with params.make_cell().
        collection_type_impl::mutation mut;

        if (!set_value || set_value->_elements.empty()) {
            return;
        }

        for (auto&& e : set_value->_elements) {
            mut.cells.emplace_back(e, params.make_cell(*set_type->value_comparator(), {}, atomic_cell::collection_member::yes));
        }
        auto smut = set_type->serialize_mutation_form(mut);

        m.set_cell(row_key, column, std::move(smut));
    } else if (set_value != nullptr) {
        // for frozen sets, we're overwriting the whole cell
        auto v = set_type->serialize_partially_deserialized_form(
                {set_value->_elements.begin(), set_value->_elements.end()},
                cql_serialization_format::internal());
        m.set_cell(row_key, column, params.make_cell(*column.type, std::move(v)));
    } else {
        m.set_cell(row_key, column, params.make_dead_cell());
    }
}

void
sets::discarder::execute(mutation& m, const clustering_key_prefix& row_key, const update_parameters& params) {
    assert(column.type->is_multi_cell()); // "Attempted to remove items from a frozen set";

    auto&& value = _t->bind(params._options);
    if (!value) {
        return;
    }

    collection_type_impl::mutation mut;
    auto kill = [&] (bytes idx) {
        mut.cells.push_back({std::move(idx), params.make_dead_cell()});
    };
    auto svalue = dynamic_pointer_cast<sets::value>(value);
    assert(svalue);
    mut.cells.reserve(svalue->_elements.size());
    for (auto&& e : svalue->_elements) {
        kill(e);
    }
    auto ctype = static_pointer_cast<const collection_type_impl>(column.type);
    m.set_cell(row_key, column,
            atomic_cell_or_collection::from_collection_mutation(
                    ctype->serialize_mutation_form(mut)));
}

void sets::element_discarder::execute(mutation& m, const clustering_key_prefix& row_key, const update_parameters& params)
{
    assert(column.type->is_multi_cell() && "Attempted to remove items from a frozen set");
    auto elt = _t->bind(params._options);
    if (!elt) {
        throw exceptions::invalid_request_exception("Invalid null set element");
    }
    collection_type_impl::mutation mut;
    mut.cells.emplace_back(*elt->get(params._options), params.make_dead_cell());
    auto ctype = static_pointer_cast<const collection_type_impl>(column.type);
    m.set_cell(row_key, column, ctype->serialize_mutation_form(mut));
}

}
<commit_msg>cql3: avoid ambiguity in a call to update_parameters::make_cell()<commit_after>/*
 * Copyright (C) 2015 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla 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.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "sets.hh"
#include "constants.hh"
#include "cql3_type.hh"

namespace cql3 {

shared_ptr<column_specification>
sets::value_spec_of(shared_ptr<column_specification> column) {
    return make_shared<column_specification>(column->ks_name, column->cf_name,
            ::make_shared<column_identifier>(sprint("value(%s)", *column->name), true),
            dynamic_pointer_cast<const set_type_impl>(column->type)->get_elements_type());
}

shared_ptr<term>
sets::literal::prepare(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) {
    validate_assignable_to(db, keyspace, receiver);

    // We've parsed empty maps as a set literal to break the ambiguity so
    // handle that case now
    if (_elements.empty() && dynamic_pointer_cast<const map_type_impl>(receiver->type)) {
        // use empty_type for comparator, set is empty anyway.
        std::map<bytes, bytes, serialized_compare> m(empty_type->as_less_comparator());
        return ::make_shared<maps::value>(std::move(m));
    }

    auto value_spec = value_spec_of(receiver);
    std::vector<shared_ptr<term>> values;
    values.reserve(_elements.size());
    bool all_terminal = true;
    for (shared_ptr<term::raw> rt : _elements)
    {
        auto t = rt->prepare(db, keyspace, value_spec);

        if (t->contains_bind_marker()) {
            throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s: bind variables are not supported inside collection literals", *receiver->name));
        }

        if (dynamic_pointer_cast<non_terminal>(t)) {
            all_terminal = false;
        }

        values.push_back(std::move(t));
    }
    auto compare = dynamic_pointer_cast<const set_type_impl>(receiver->type)->get_elements_type()->as_less_comparator();

    auto value = ::make_shared<delayed_value>(compare, std::move(values));
    if (all_terminal) {
        return value->bind(query_options::DEFAULT);
    } else {
        return value;
    }
}

void
sets::literal::validate_assignable_to(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) {
    if (!dynamic_pointer_cast<const set_type_impl>(receiver->type)) {
        // We've parsed empty maps as a set literal to break the ambiguity so
        // handle that case now
        if (dynamic_pointer_cast<const map_type_impl>(receiver->type) && _elements.empty()) {
            return;
        }

        throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s of type %s", *receiver->name, *receiver->type->as_cql3_type()));
    }

    auto&& value_spec = value_spec_of(receiver);
    for (shared_ptr<term::raw> rt : _elements) {
        if (!is_assignable(rt->test_assignment(db, keyspace, value_spec))) {
            throw exceptions::invalid_request_exception(sprint("Invalid set literal for %s: value %s is not of type %s", *receiver->name, *rt, *value_spec->type->as_cql3_type()));
        }
    }
}

assignment_testable::test_result
sets::literal::test_assignment(database& db, const sstring& keyspace, shared_ptr<column_specification> receiver) {
    if (!dynamic_pointer_cast<const set_type_impl>(receiver->type)) {
        // We've parsed empty maps as a set literal to break the ambiguity so handle that case now
        if (dynamic_pointer_cast<const map_type_impl>(receiver->type) && _elements.empty()) {
            return assignment_testable::test_result::WEAKLY_ASSIGNABLE;
        }

        return assignment_testable::test_result::NOT_ASSIGNABLE;
    }

    // If there is no elements, we can't say it's an exact match (an empty set if fundamentally polymorphic).
    if (_elements.empty()) {
        return assignment_testable::test_result::WEAKLY_ASSIGNABLE;
    }

    auto&& value_spec = value_spec_of(receiver);
    // FIXME: make assignment_testable::test_all() accept ranges
    std::vector<shared_ptr<assignment_testable>> to_test(_elements.begin(), _elements.end());
    return assignment_testable::test_all(db, keyspace, value_spec, to_test);
}

sstring
sets::literal::to_string() const {
    return "{" + join(", ", _elements) + "}";
}

sets::value
sets::value::from_serialized(bytes_view v, set_type type, cql_serialization_format sf) {
    try {
        // Collections have this small hack that validate cannot be called on a serialized object,
        // but compose does the validation (so we're fine).
        // FIXME: deserializeForNativeProtocol?!
        auto s = value_cast<set_type_impl::native_type>(type->deserialize(v, sf));
        std::set<bytes, serialized_compare> elements(type->get_elements_type()->as_less_comparator());
        for (auto&& element : s) {
            elements.insert(elements.end(), type->get_elements_type()->decompose(element));
        }
        return value(std::move(elements));
    } catch (marshal_exception& e) {
        throw exceptions::invalid_request_exception(e.what());
    }
}

cql3::raw_value
sets::value::get(const query_options& options) {
    return cql3::raw_value::make_value(get_with_protocol_version(options.get_cql_serialization_format()));
}

bytes
sets::value::get_with_protocol_version(cql_serialization_format sf) {
    return collection_type_impl::pack(_elements.begin(), _elements.end(),
            _elements.size(), sf);
}

bool
sets::value::equals(set_type st, const value& v) {
    if (_elements.size() != v._elements.size()) {
        return false;
    }
    auto&& elements_type = st->get_elements_type();
    return std::equal(_elements.begin(), _elements.end(),
            v._elements.begin(),
            [elements_type] (bytes_view v1, bytes_view v2) {
                return elements_type->equal(v1, v2);
            });
}

sstring
sets::value::to_string() const {
    sstring result = "{";
    bool first = true;
    for (auto&& e : _elements) {
        if (!first) {
            result += ", ";
        }
        first = true;
        result += to_hex(e);
    }
    result += "}";
    return result;
}

bool
sets::delayed_value::contains_bind_marker() const {
    // False since we don't support them in collection
    return false;
}

void
sets::delayed_value::collect_marker_specification(shared_ptr<variable_specifications> bound_names) {
}

shared_ptr<terminal>
sets::delayed_value::bind(const query_options& options) {
    std::set<bytes, serialized_compare> buffers(_comparator);
    for (auto&& t : _elements) {
        auto b = t->bind_and_get(options);

        if (b.is_null()) {
            throw exceptions::invalid_request_exception("null is not supported inside collections");
        }
        if (b.is_unset_value()) {
            return constants::UNSET_VALUE;
        }
        // We don't support value > 64K because the serialization format encode the length as an unsigned short.
        if (b->size() > std::numeric_limits<uint16_t>::max()) {
            throw exceptions::invalid_request_exception(sprint("Set value is too long. Set values are limited to %d bytes but %d bytes value provided",
                    std::numeric_limits<uint16_t>::max(),
                    b->size()));
        }

        buffers.insert(buffers.end(), std::move(to_bytes(*b)));
    }
    return ::make_shared<value>(std::move(buffers));
}

::shared_ptr<terminal>
sets::marker::bind(const query_options& options) {
    const auto& value = options.get_value_at(_bind_index);
    if (value.is_null()) {
        return nullptr;
    } else if (value.is_unset_value()) {
        return constants::UNSET_VALUE;
    } else {
        auto as_set_type = static_pointer_cast<const set_type_impl>(_receiver->type);
        return make_shared(value::from_serialized(*value, as_set_type, options.get_cql_serialization_format()));
    }
}

void
sets::setter::execute(mutation& m, const clustering_key_prefix& row_key, const update_parameters& params) {
    auto value = _t->bind(params._options);
    execute(m, row_key, params, column, std::move(value));
}

void
sets::setter::execute(mutation& m, const clustering_key_prefix& row_key, const update_parameters& params, const column_definition& column, ::shared_ptr<terminal> value) {
    if (value == constants::UNSET_VALUE) {
        return;
    }
    if (column.type->is_multi_cell()) {
        // delete + add
        collection_type_impl::mutation mut;
        mut.tomb = params.make_tombstone_just_before();
        auto ctype = static_pointer_cast<const set_type_impl>(column.type);
        auto col_mut = ctype->serialize_mutation_form(std::move(mut));
        m.set_cell(row_key, column, std::move(col_mut));
    }
    adder::do_add(m, row_key, params, value, column);
}

void
sets::adder::execute(mutation& m, const clustering_key_prefix& row_key, const update_parameters& params) {
    const auto& value = _t->bind(params._options);
    if (value == constants::UNSET_VALUE) {
        return;
    }
    assert(column.type->is_multi_cell()); // "Attempted to add items to a frozen set";
    do_add(m, row_key, params, value, column);
}

void
sets::adder::do_add(mutation& m, const clustering_key_prefix& row_key, const update_parameters& params,
        shared_ptr<term> value, const column_definition& column) {
    auto set_value = dynamic_pointer_cast<sets::value>(std::move(value));
    auto set_type = dynamic_pointer_cast<const set_type_impl>(column.type);
    if (column.type->is_multi_cell()) {
        // FIXME: mutation_view? not compatible with params.make_cell().
        collection_type_impl::mutation mut;

        if (!set_value || set_value->_elements.empty()) {
            return;
        }

        for (auto&& e : set_value->_elements) {
            mut.cells.emplace_back(e, params.make_cell(*set_type->value_comparator(), bytes_view(), atomic_cell::collection_member::yes));
        }
        auto smut = set_type->serialize_mutation_form(mut);

        m.set_cell(row_key, column, std::move(smut));
    } else if (set_value != nullptr) {
        // for frozen sets, we're overwriting the whole cell
        auto v = set_type->serialize_partially_deserialized_form(
                {set_value->_elements.begin(), set_value->_elements.end()},
                cql_serialization_format::internal());
        m.set_cell(row_key, column, params.make_cell(*column.type, std::move(v)));
    } else {
        m.set_cell(row_key, column, params.make_dead_cell());
    }
}

void
sets::discarder::execute(mutation& m, const clustering_key_prefix& row_key, const update_parameters& params) {
    assert(column.type->is_multi_cell()); // "Attempted to remove items from a frozen set";

    auto&& value = _t->bind(params._options);
    if (!value) {
        return;
    }

    collection_type_impl::mutation mut;
    auto kill = [&] (bytes idx) {
        mut.cells.push_back({std::move(idx), params.make_dead_cell()});
    };
    auto svalue = dynamic_pointer_cast<sets::value>(value);
    assert(svalue);
    mut.cells.reserve(svalue->_elements.size());
    for (auto&& e : svalue->_elements) {
        kill(e);
    }
    auto ctype = static_pointer_cast<const collection_type_impl>(column.type);
    m.set_cell(row_key, column,
            atomic_cell_or_collection::from_collection_mutation(
                    ctype->serialize_mutation_form(mut)));
}

void sets::element_discarder::execute(mutation& m, const clustering_key_prefix& row_key, const update_parameters& params)
{
    assert(column.type->is_multi_cell() && "Attempted to remove items from a frozen set");
    auto elt = _t->bind(params._options);
    if (!elt) {
        throw exceptions::invalid_request_exception("Invalid null set element");
    }
    collection_type_impl::mutation mut;
    mut.cells.emplace_back(*elt->get(params._options), params.make_dead_cell());
    auto ctype = static_pointer_cast<const collection_type_impl>(column.type);
    m.set_cell(row_key, column, ctype->serialize_mutation_form(mut));
}

}
<|endoftext|>


<commit_before>/*
 * File:   main.cpp
 * Author: Luca Bettinelli
 *
 * Created on July 18, 2017, 3:20 PM
 */

#include <stdlib.h>
#include <core.hpp>
#include <imgproc.hpp>
#include <highgui.hpp>
#include <iostream>
#include <math.h>

using namespace std;
using namespace cv;

/*
 *
 */

Mat toBN(Mat img);

int main(int argc, char** argv) {
    Mat m = imread("lena.png", CV_LOAD_IMAGE_COLOR);
    namedWindow("Test", WINDOW_AUTOSIZE);
    imshow("Test", toBN(m));
    waitKey(0);
    return 0;
}

Mat toBN(Mat img){
    Mat res(img.rows, img.cols, CV_8UC1);
    for(int i = 0; i < img.rows; i++){
        for(int j = 0; j < img.cols; j++){
            int new_pixel = 0;
            Vec3b pixel = img.at<Vec3b>(i,j);
            for(int k = 0; k < 3; k++){
                new_pixel += (int)pixel.val[k];
            }
            new_pixel = (int)floor(((double)1/3) * new_pixel);
            res.at<uchar>(i,j) = (uchar) new_pixel;
        }
    }
    return res;
}
<commit_msg>Add method to get all files with a specific extension name, and show BW version of the image<commit_after>/*
 * File:   main.cpp
 * Author: Luca Bettinelli
 *
 * Created on July 18, 2017, 3:20 PM
 */

#include <stdlib.h>
#include <core.hpp>
#include <imgproc.hpp>
#include <highgui.hpp>
#include <iostream>
#include <math.h>

#include<string.h>
#include<fstream>
#include<dirent.h>

using namespace std;
using namespace cv;

/*
 *
 */

Mat toBN(Mat img);
vector<string> listFile(const char* dirPath);
bool has_suffix(const string& s, const string& suffix);

int main(int argc, char** argv) {
	vector<string> list = listFile(".");
	for(int i = 0; i < list.size(); i++)
	{
		    Mat m = imread(list[i], CV_LOAD_IMAGE_COLOR);
		    namedWindow(list[i], WINDOW_AUTOSIZE);
		    imshow(list[i], toBN(m));
		    waitKey(0);
	}

    return 0;
}

Mat toBN(Mat img){
    Mat res(img.rows, img.cols, CV_32FC1);
    for(int i = 0; i < img.rows; i++){
        for(int j = 0; j < img.cols; j++){
            float new_pixel = 0;
            Vec3b pixel = img.at<Vec3b>(i,j);
            for(int k = 0; k < 3; k++){
                new_pixel += (int)pixel.val[k];
            }
            new_pixel = (((double)1/3) * new_pixel)/255;
            cout << new_pixel << endl;
            res.at<float>(i,j) = (float) new_pixel;
        }
    }
    return res;
}

bool has_suffix(const string& s, const string& suffix)
{
    return (s.size() >= suffix.size()) && equal(suffix.rbegin(), suffix.rend(), s.rbegin());
}

vector<string> listFile(const char* dirPath){
        DIR *pDIR;
        vector<string> list;
        struct dirent *entry;
        if( pDIR=opendir(dirPath) ){
                while(entry = readdir(pDIR)){
                	if(has_suffix(entry->d_name, ".jpg"))
                	{
                		string s = entry->d_name;
						list.push_back(s);
                		cout << entry->d_name << "\n";
                	}
                }
                closedir(pDIR);
        }
        return list;
}
<|endoftext|>


<commit_before>#include <cpu/CPUDenseGraphBFSearcher.h>
#include <cpu/CPUDenseGraphAnnealer.h>
#include <cpu/CPUBipartiteGraphBFSearcher.h>
#include <cpu/CPUBipartiteGraphAnnealer.h>
#include <iostream>
#include <chrono>
#include <cuda_runtime.h>

namespace sq = sqaod;

#ifdef SQAOD_CUDA_ENABLED
#  include <cuda/CUDADenseGraphBFSearcher.h>
#  include <cuda/CUDADenseGraphAnnealer.h>
#  include <cuda/CUDABipartiteGraphBFSearcher.h>
#  include <cuda/CUDABipartiteGraphAnnealer.h>
namespace sqcuda = sqaod_cuda;
#endif

template<class T>
void showDuration(const T &duration) {
    std::cout << "elapsed time = "
              << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << " msec."
              << std::endl;
}

template<class real>
sq::MatrixType<real> symmetricMatrix(sq::SizeType dim) {
    sq::Random random;
    random.seed(0);
    sq::MatrixType<real> mat(dim, dim);
    for (sq::SizeType irow = 0; irow < dim; ++irow) {
        for (sq::SizeType icol = irow; icol < dim; ++icol) {
            mat(icol, irow) = mat(irow, icol) = random.random<real>() - 0.5f;
        }
    }
    return mat;
}

template<class real>
sq::MatrixType<real> matrix(const sq::Dim &dim) {
    sq::MatrixType<real> mat(dim.rows, dim.cols);
    for (sq::SizeType irow = 0; irow < dim.rows; ++irow) {
        for (sq::SizeType icol = 0; icol < dim.cols; ++icol) {
            mat(irow, icol) = sq::random.random<real>() - 0.5f;
        }
    }
    return mat;
}

template<class real>
sq::VectorType<real> vector(sq::SizeType size) {
    sq::VectorType<real> vec(size);
    for (sq::SizeType idx = 0; idx < size; ++idx) {
        vec(idx) = sq::random.random<real>() - 0.5f;
    }
    return vec;
}

template<class real>
void denseGraphBFSearch(int N) {
    sq::MatrixType<real> W = symmetricMatrix<real>(N);

    sq::CPUDenseGraphBFSearcher<real> cpuSolver;
    cpuSolver.setProblem(W);
    cpuSolver.setPreference(sq::Preference(sq::pnTileSize, 1 << std::min(N, 20)));

    auto start = std::chrono::system_clock::now();
    cpuSolver.search();
    auto end = std::chrono::system_clock::now();

    std::cout << cpuSolver.get_E().min() << std::endl;

    showDuration(end - start);

#ifdef SQAOD_CUDA_ENABLED
    sqcuda::Device device;
    device.initialize();

    sqcuda::CUDADenseGraphBFSearcher<real> cudaSolver(device);
    cudaSolver.setProblem(W);
    cudaSolver.setPreference(sq::Preference(pnTileSize, 1 << std::min(N, 18)));

    start = std::chrono::system_clock::now();
    cudaSolver.search();
    end = std::chrono::system_clock::now();

    std::cout << cudaSolver.get_E().min() << std::endl;
    device.finalize();

    showDuration(end - start);
#endif
}

template<class real>
void bipartiteGraphBFSearch(int N0, int N1) {
    sq::VectorType<real> b0 = vector<real>(N0);
    sq::VectorType<real> b1 = vector<real>(N1);
    sq::MatrixType<real> W = matrix<real>(sq::Dim(N1, N0));

    sq::CPUBipartiteGraphBFSearcher<real> cpuSolver;
    cpuSolver.setProblem(b0, b1, W);
//    cpuSolver.setTileSize(1 << std::min(N, 20));

    auto start = std::chrono::system_clock::now();
    cpuSolver.search();
    auto end = std::chrono::system_clock::now();

    std::cout << cpuSolver.get_E().min() << std::endl;

    showDuration(end - start);

#ifdef SQAOD_CUDA_ENABLED
    sqcuda::Device device;
    // device.useManagedMemory(true);
    // device.enableLocalStore(false);
    device.initialize();

    sqcuda::CUDABipartiteGraphBFSearcher<real> cudaSolver(device);
    cudaSolver.setProblem(b0, b1, W);
    // cudaSolver.setTileSize(1 << std::min(N, 20));

    start = std::chrono::system_clock::now();
    cudaSolver.search();
    end = std::chrono::system_clock::now();

    std::cout << cudaSolver.get_E().min() << std::endl;
    device.finalize();

    showDuration(end - start);
#endif
}

template<class real, template<class real> class A>
void anneal(A<real> &an, real Ginit, real Gfin, real kT, real tau) {

    an.initAnneal();
    an.randomize_q();
    real G = Ginit;
    while (Gfin < G) {
        an.annealOneStep(G, kT);
        G = G * tau;
        std::cerr << ".";
    }
    an.finAnneal();
    std::cerr << std::endl;
    const sq::VectorType<real> &E = an.get_E();
    std::cerr << "Energy : " << E.min() << std::endl;
}

template<class real>
void denseGraphAnnealer(int N) {

    real Ginit = 5.;
    real Gfin = 0.01;
    real kT = 0.02;
    real tau = 0.99;

    sq::MatrixType<real> W = symmetricMatrix<real>(N);

    sq::CPUDenseGraphAnnealer<real> cpuAnnealer;
    cpuAnnealer.seed(0);
    // cpuAnnealer.selectAlgorithm(sq::algoNaive);
    cpuAnnealer.setProblem(W);
    cpuAnnealer.setPreference(Preference(sq::pnNumTrotters, N / 2));
    // cpuAnnealer.setNumTrotters(N / 2); /* FIXME: add setNumTrotters for ease of use. */

    auto start = std::chrono::system_clock::now();
    anneal(cpuAnnealer, Ginit, Gfin, kT, tau);
    auto end = std::chrono::system_clock::now();

    std::cout << cpuAnnealer.get_E().min() << std::endl;

    showDuration(end - start);

#ifdef SQAOD_CUDA_ENABLED
    sqcuda::Device device;
    device.initialize();
    {
        sqcuda::CUDADenseGraphAnnealer<real> cudaAnnealer(device);
        cudaAnnealer.setProblem(W);
        cudaAnnealer.setPreference(sq::Preference(sq::pnNumTrotters, (N / 2)));
        cudaAnnealer.seed(1);

        auto start = std::chrono::system_clock::now();
        anneal(cudaAnnealer, Ginit, Gfin, kT, tau);
        auto end = std::chrono::system_clock::now();
        device.synchronize();
        std::cout << cudaAnnealer.get_E().min() << std::endl;
        showDuration(end - start);
    }
    device.finalize();

#endif
}

template<class real>
void bipartiteGraphAnnealer(int N0, int N1) {

    real Ginit = 5.;
    real Gfin = 0.01;
    real kT = 0.02;
    real tau = 0.9;

    sq::VectorType<real> b0 = vector<real>(N0);
    sq::VectorType<real> b1 = vector<real>(N1);
    sq::MatrixType<real> W = matrix<real>(sq::Dim(N1, N0));

    sq::CPUBipartiteGraphAnnealer<real> cpuAnnealer;
    cpuAnnealer.seed(0);
    // cpuAnnealer.selectAlgorithm(sq::algoNaive);
    cpuAnnealer.setProblem(b0, b1, W);
    sq::Preference pref(sq::pnNumTrotters, sq::SizeType((N0 + N1) / 2));
    cpuAnnealer.setPreference(pref);

    auto start = std::chrono::system_clock::now();
    anneal(cpuAnnealer, Ginit, Gfin, kT, tau);
    auto end = std::chrono::system_clock::now();

    std::cout << cpuAnnealer.get_E().min() << std::endl;

    showDuration(end - start);

#ifdef SQAOD_CUDA_ENABLED
    sqcuda::Device device;
    device.initialize();
    {
        sqcuda::CUDABipartiteGraphAnnealer<real> cudaAnnealer(device);
        cudaAnnealer.setProblem(b0, b1, W);
        cudaAnnealer.setPreference(sq::Preference(sq::pnNumTrotters, ((N0 + N1) / 2)));
        cudaAnnealer.seed(65743);

        auto start = std::chrono::system_clock::now();
        anneal(cudaAnnealer, Ginit, Gfin, kT, tau);
        auto end = std::chrono::system_clock::now();
        device.synchronize();
        std::cout << cudaAnnealer.get_E().min() << std::endl;
        showDuration(end - start);
    }
    device.finalize();

#endif
}

int main() {
    sq::random.seed(0);

    int N = 24;
    denseGraphBFSearch<double>(N);
    denseGraphBFSearch<float>(N);

    N = 1024;
    denseGraphAnnealer<double>(N);
    denseGraphAnnealer<float>(N);

    int N0 = 14, N1 = 14;
    bipartiteGraphBFSearch<float>(N0, N1);
    bipartiteGraphBFSearch<double>(N0, N1);

    bipartiteGraphAnnealer<float>(N0, N1);
    bipartiteGraphAnnealer<double>(N0, N1);

    cudaDeviceReset();
}
<commit_msg>Cleaning up perf app.<commit_after>#include <cpu/CPUDenseGraphBFSearcher.h>
#include <cpu/CPUDenseGraphAnnealer.h>
#include <cpu/CPUBipartiteGraphBFSearcher.h>
#include <cpu/CPUBipartiteGraphAnnealer.h>
#include <iostream>
#include <chrono>
#include <cuda_runtime.h>

namespace sq = sqaod;

#ifdef SQAOD_CUDA_ENABLED
#  include <cuda/CUDADenseGraphBFSearcher.h>
#  include <cuda/CUDADenseGraphAnnealer.h>
#  include <cuda/CUDABipartiteGraphBFSearcher.h>
#  include <cuda/CUDABipartiteGraphAnnealer.h>
namespace sqcuda = sqaod_cuda;

sqcuda::Device device;

#endif

template<class T>
void showDuration(const T &duration) {
    std::cout << "elapsed time = "
              << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << " msec."
              << std::endl;
}

template<class real>
sq::MatrixType<real> symmetricMatrix(sq::SizeType dim) {
    sq::Random random;
    random.seed(0);
    sq::MatrixType<real> mat(dim, dim);
    for (sq::SizeType irow = 0; irow < dim; ++irow) {
        for (sq::SizeType icol = irow; icol < dim; ++icol) {
            mat(icol, irow) = mat(irow, icol) = random.random<real>() - 0.5f;
        }
    }
    return mat;
}

template<class real>
sq::MatrixType<real> matrix(const sq::Dim &dim) {
    sq::MatrixType<real> mat(dim.rows, dim.cols);
    for (sq::SizeType irow = 0; irow < dim.rows; ++irow) {
        for (sq::SizeType icol = 0; icol < dim.cols; ++icol) {
            mat(irow, icol) = sq::random.random<real>() - 0.5f;
        }
    }
    return mat;
}

template<class real>
sq::VectorType<real> vector(sq::SizeType size) {
    sq::VectorType<real> vec(size);
    for (sq::SizeType idx = 0; idx < size; ++idx) {
        vec(idx) = sq::random.random<real>() - 0.5f;
    }
    return vec;
}

template<class real>
void createBipartiteGraph(sq::VectorType<real> *b0, sq::VectorType<real> *b1, sq::MatrixType<real> *W,
                          sq::SizeType N0, sq::SizeType N1) {
    *b0 = vector<real>(N0);
    *b1 = vector<real>(N1);
    *W = matrix<real>(sq::Dim(N1, N0));
}

template<class real, template<class real> class S>
void runSearch(S<real> &searcher) {
    auto start = std::chrono::system_clock::now();
    searcher.search();
    auto end = std::chrono::system_clock::now();

    const sq::VectorType<real> &E = searcher.get_E();
    std::cerr << "Energy : " << E.min() << std::endl << std::endl;
    showDuration(end - start);
}

template<class real, template<class real> class A>
void anneal(A<real> &an) {
    real Ginit = real(5.);
    real Gfin = real(0.01);
    real kT = real(0.02);
    real tau = real(0.99);
    tau = (real)0.9;

    int nSteps = 0;

    auto start = std::chrono::system_clock::now();
    an.initAnneal();
    an.randomize_q();
    real G = Ginit;
    while (Gfin < G) {
        an.annealOneStep(G, kT);
        G = G * tau;
        ++nSteps;
        std::cerr << ".";
    }
    an.finAnneal();
    auto end = std::chrono::system_clock::now();

    std::cerr << std::endl;
    const sq::VectorType<real> &E = an.get_E();
    std::cerr << "Energy : " << E.min() << std::endl;
    std::cerr << "# Steps : " << nSteps << std::endl << std::endl;

    showDuration(end - start);
}

template<class real>
void run(const char *precisionStr) {
    bool runDenseGraphBruteForceSearchers = true;
    bool runDenseGraphAnnealers = true;
    bool runBipartiteGraphBruteForceSearchers = true;
    bool runBipartiteGraphAnnealers = true;

    bool runCPUSolvers = true;
    bool runCUDASolvers = true;

    /* Dense graph brute-force searchers */
    if (runDenseGraphBruteForceSearchers) {
        int N = 24;
        sq::random.seed(0);
        sq::MatrixType<real> W = symmetricMatrix<real>(N);
        if (runCPUSolvers) {
            fprintf(stderr, "Dense graph brute-force searcher, CPU, %s\n", precisionStr);
            sq::CPUDenseGraphBFSearcher<real> searcher;
            searcher.setProblem(W);
            runSearch(searcher);
        }
        if (runCUDASolvers) {
            fprintf(stderr, "Dense graph brute-force searcher, CUDA, %s\n", precisionStr);
            sqcuda::CUDADenseGraphBFSearcher<real> searcher(device);
            searcher.setProblem(W);
            runSearch(searcher);
        }
    }

    /* Dense graph annealers */
    if (runDenseGraphAnnealers) {
        int N = 1024;
        sq::random.seed(0);
        sq::MatrixType<real> W = symmetricMatrix<real>(N);
        if (runCPUSolvers) {
            fprintf(stderr, "Dense graph annealer, CPU, %s\n", precisionStr);
            sq::CPUDenseGraphAnnealer<real> annealer;
            annealer.setProblem(W);
            sq::Preference pref(sq::pnNumTrotters, sq::SizeType(N / 2));
            annealer.setPreference(pref);
            anneal(annealer);
        }
        if (runCUDASolvers) {
            fprintf(stderr, "Dense graph annealer, CUDA, %s\n", precisionStr);
            sqcuda::CUDADenseGraphAnnealer<real> annealer(device);
            annealer.setProblem(W);
            sq::Preference pref(sq::pnNumTrotters, sq::SizeType(N / 2));
            annealer.setPreference(pref);
            anneal(annealer);
        }
    }

    /* Bipartite graph brute-force searchers */
    if (runBipartiteGraphBruteForceSearchers) {
        int N0 = 14, N1 = 14;
        sq::random.seed(0);
        sq::VectorType<real> b0, b1;
        sq::MatrixType<real> W;
        createBipartiteGraph(&b0, &b1, &W, N0, N1);
        if (runCPUSolvers) {
            fprintf(stderr, "Bipartite graph brute-force searcher, CPU, %s\n", precisionStr);
            sq::CPUBipartiteGraphBFSearcher<real> searcher;
            searcher.setProblem(b0, b1, W);
            runSearch(searcher);
        }
        if (runCUDASolvers) {
            fprintf(stderr, "Bipartite graph brute-force searcher, CUDA, %s\n", precisionStr);
            sqcuda::CUDABipartiteGraphBFSearcher<real> searcher(device);
            searcher.setProblem(b0, b1, W);
            runSearch(searcher);
        }
    }

    /* Bipartite graph annealers */
    if (runBipartiteGraphAnnealers) {
        int N0 = 384, N1 = 384;
        sq::random.seed(0);
        sq::VectorType<real> b0, b1;
        sq::MatrixType<real> W;
        createBipartiteGraph(&b0, &b1, &W, N0, N1);
        if (runCPUSolvers) {
            fprintf(stderr, "Bipartite graph annealer, CPU, %s\n", precisionStr);
            sq::CPUBipartiteGraphAnnealer<real> annealer;
            annealer.setProblem(b0, b1, W);
            sq::Preference pref(sq::pnNumTrotters, sq::SizeType((N0 + N1) / 2));
            annealer.setPreference(pref);
            anneal(annealer);
        }
        if (runCUDASolvers) {
            fprintf(stderr, "Bipartite graph annealer, CUDA, %s\n", precisionStr);
            sqcuda::CUDABipartiteGraphAnnealer<real> annealer(device);
            annealer.setProblem(b0, b1, W);
            sq::Preference pref(sq::pnNumTrotters, sq::SizeType((N0 + N1) / 2));
            annealer.setPreference(pref);
            anneal(annealer);
        }
    }
}

int main() {
    bool runFloatSolvers = true;
    bool runDoubleSolvers = true;

#ifdef SQAOD_CUDA_ENABLED
    device.initialize();
#endif

    if (runFloatSolvers)
        run<float>("float");
    if (runDoubleSolvers)
        run<double>("double");

#ifdef SQAOD_CUDA_ENABLED
    device.finalize();
    cudaDeviceReset();
#endif
}
<|endoftext|>


<commit_before>#include <iostream>

int main()
{
  int i = 0, &r = i;
  auto a = r;   // a is an int (r is an alias for i, which has type int)

  const int ci = i, &cr = ci;
  auto b = ci; // b is an int (top-level const in ci is dropped)
  auto c = cr; // c is an int (cr is an alias for ci whose const is top-level)
  auto d = &i; // d is an int* (& ofan int objectis int*)
  auto e = &ci; // e is const int*(& of a const object is low-level const)

  const auto f = ci; // deduced type of ci is int; f has type const int
  auto &g = ci; // g is a const int& that is bound to ci

  a=42; b=42; c=42; *d=42; e=&c;

  return 0;
}
<commit_msg>Update ex2_34.cpp<commit_after>#include <iostream>

int main()
{
    int i = 0, &r = i;
    auto a = r;   // a is an int (r is an alias for i, which has type int)

    const int ci = i, &cr = ci;
    auto b = ci; // b is an int (top-level const in ci is dropped)
    auto c = cr; // c is an int (cr is an alias for ci whose const is top-level)
    auto d = &i; // d is an int* (& ofan int objectis int*)
    auto e = &ci; // e is const int*(& of a const object is low-level const)

    const auto f = ci; // deduced type of ci is int; f has type const int
    auto &g = ci; // g is a const int& that is bound to ci

    a = 42; b = 42; c = 42; *d = 42; e = &c;

    return 0;
}
<|endoftext|>


<commit_before>// @Yue Wang @pezy
//
// Exercise 9.14:
// Write a program to assign the elements from a list of char* pointers
// to C-style character strings
//
// @Notice C-style character strings should use const char*, otherwise warning.
//

#include <iostream>
#include <string>
#include <vector>
#include <list>

int main()
{
    std::list<const char*> l{ "Mooophy", "pezy", "Queeuqueg" };
    std::vector<std::string> v;
    v.assign(l.cbegin(), l.cend());

    for (const auto &ch : v)
        std::cout << ch << std::endl;

    return 0;
}
<commit_msg>Update ex9_14.cpp<commit_after>// @Yue Wang @pezy
//
// Exercise 9.14:
// Write a program to assign the elements from a list of char* pointers
// to C-style character strings
//

#include <iostream>
#include <string>
#include <vector>
#include <list>

int main()
{
    std::list<const char*> l{ "Mooophy", "pezy", "Queeuqueg" };
    std::vector<std::string> v;
    v.assign(l.cbegin(), l.cend());
    for (auto ptr : v)
        std::cout << ptr << std::endl;

    return 0;
}
<|endoftext|>