ronantakizawa/codereview-bench huggingface dataset:
Repository: xbmc/xbmc
File: xbmc/platform/posix/filesystem/PosixDirectory.cpp (C++)

Code before:
      // In order to get a correct value we have to incur the cost of calling stat.
      bool isDir = entry->d_type == DT_DIR;
      if (entry->d_type == DT_UNKNOWN || entry->d_type == DT_LNK ||
          !(m_flags & DIR_FLAG_NO_FILE_INFO))
      {
        if (stat(itemPath.c_str(), &buffer) == 0)
        {
          isDir = S_ISDIR(buffer.st_mode);

          KODI::TIME::FileTime fileTime;
          KODI::TIME::FileTime localTime;
          KODI::TIME::TimeTToFileTime(buffer.st_mtime, &fileTime);
          KODI::TIME::FileTimeToLocalFileTime(&fileTime, &localTime);

          item->SetDateTime(localTime);
          item->SetSize(isDir ? 0 : buffer.st_size);
        }
      }

      if (isDir)
        itemPath += "/";

      item->SetFolder(isDir);
      item->SetPath(itemPath);

      if (StringUtils::StartsWith(name, "."))
        item->SetProperty("file:hidden", true);
    }
  }
  items.AddItems(std::move(fileItems));

  closedir(dir);
  return true;
}

bool CPosixDirectory::Create(const CURL& url)
{
  if (!Create(url.Get()))
    return Exists(url);

  return true;
}

bool CPosixDirectory::Create(const std::string& path)
{
  if (mkdir(path.c_str(), 0755) != 0)
  {
    if (errno == ENOENT)
    {
      auto sep = path.rfind('/');
      if (sep == std::string::npos)

Review comment (suggestion):
```suggestion
      if (name.starts_with('.'))
```

And you can remove `#include "utils/StringUtils.h"`

Code after:
      if (entry->d_type == DT_UNKNOWN || entry->d_type == DT_LNK ||
          !(m_flags & DIR_FLAG_NO_FILE_INFO))
      {
        if (stat(itemPath.c_str(), &buffer) == 0)
        {
          isDir = S_ISDIR(buffer.st_mode);

          KODI::TIME::FileTime fileTime;
          KODI::TIME::FileTime localTime;
          KODI::TIME::TimeTToFileTime(buffer.st_mtime, &fileTime);
          KODI::TIME::FileTimeToLocalFileTime(&fileTime, &localTime);

          item->SetDateTime(localTime);
          item->SetSize(isDir ? 0 : buffer.st_size);
        }
      }

      if (isDir)
        itemPath.push_back('/');

      item->SetFolder(isDir);
      item->SetPath(itemPath);

      if (name.starts_with('.'))
        item->SetProperty("file:hidden", true);
    }
  }
  items.AddItems(std::move(fileItems));

  closedir(dir);
  return true;
}

bool CPosixDirectory::Create(const CURL& url)
{
  if (!Create(url.Get()))
    return Exists(url);

  return true;
}

bool CPosixDirectory::Create(const std::string& path)
{
  if (mkdir(path.c_str(), 0755) != 0)
  {
    if (errno == ENOENT)
    {
      auto sep = path.rfind('/');
      if (sep == std::string::npos)
        return false;
Repository: xbmc/xbmc
File: xbmc/platform/posix/filesystem/PosixDirectory.cpp (C++)

Code before:
      // In order to get a correct value we have to incur the cost of calling stat.
      bool isDir = entry->d_type == DT_DIR;
      if (entry->d_type == DT_UNKNOWN || entry->d_type == DT_LNK ||
          !(m_flags & DIR_FLAG_NO_FILE_INFO))
      {
        if (stat(itemPath.c_str(), &buffer) == 0)
        {
          isDir = S_ISDIR(buffer.st_mode);

          KODI::TIME::FileTime fileTime;
          KODI::TIME::FileTime localTime;
          KODI::TIME::TimeTToFileTime(buffer.st_mtime, &fileTime);
          KODI::TIME::FileTimeToLocalFileTime(&fileTime, &localTime);

          item->SetDateTime(localTime);
          item->SetSize(isDir ? 0 : buffer.st_size);
        }
      }

      if (isDir)
        itemPath.push_back('/');

      item->SetFolder(isDir);
      item->SetPath(itemPath);

      if (name.starts_with("."))
        item->SetProperty("file:hidden", true);
    }
  }
  items.AddItems(std::move(fileItems));

  closedir(dir);
  return true;
}

bool CPosixDirectory::Create(const CURL& url)
{
  if (!Create(url.Get()))
    return Exists(url);

  return true;
}

bool CPosixDirectory::Create(const std::string& path)
{
  if (mkdir(path.c_str(), 0755) != 0)
  {
    if (errno == ENOENT)
    {
      auto sep = path.rfind('/');
      if (sep == std::string::npos)

Review comment (suggestion):
```suggestion
      if (name.starts_with('.'))
```

Code after:
      // In order to get a correct value we have to incur the cost of calling stat.
      bool isDir = entry->d_type == DT_DIR;
      if (entry->d_type == DT_UNKNOWN || entry->d_type == DT_LNK ||
          !(m_flags & DIR_FLAG_NO_FILE_INFO))
      {
        if (stat(itemPath.c_str(), &buffer) == 0)
        {
          isDir = S_ISDIR(buffer.st_mode);

          KODI::TIME::FileTime fileTime;
          KODI::TIME::FileTime localTime;
          KODI::TIME::TimeTToFileTime(buffer.st_mtime, &fileTime);
          KODI::TIME::FileTimeToLocalFileTime(&fileTime, &localTime);

          item->SetDateTime(localTime);
          item->SetSize(isDir ? 0 : buffer.st_size);
        }
      }

      if (isDir)
        itemPath.push_back('/');

      item->SetFolder(isDir);
      item->SetPath(itemPath);

      if (name.starts_with('.'))
        item->SetProperty("file:hidden", true);
    }
  }
  items.AddItems(std::move(fileItems));

  closedir(dir);
  return true;
}

bool CPosixDirectory::Create(const CURL& url)
{
  if (!Create(url.Get()))
    return Exists(url);

  return true;
}

bool CPosixDirectory::Create(const std::string& path)
{
  if (mkdir(path.c_str(), 0755) != 0)
  {
    if (errno == ENOENT)
    {
      auto sep = path.rfind('/');
      if (sep == std::string::npos)
Repository: xbmc/xbmc
File: xbmc/cores/VideoPlayer/MediaPipelineWebOS.cpp (C++)

Code before:

void CMediaPipelineWebOS::UpdateGUISounds(const bool playing)
{
  IAE* activeAE = CServiceBroker::GetActiveAE();
  const int guiSoundMode = CServiceBroker::GetSettingsComponent()->GetSettings()->GetInt(
      CSettings::SETTING_AUDIOOUTPUT_GUISOUNDMODE);

  if (guiSoundMode != AE_SOUND_IDLE)
    return;

  if (playing)
    activeAE->SetVolume(0.0);
  else
    activeAE->SetVolume(1.0);
}

std::string CMediaPipelineWebOS::GetAudioInfo()
{
  std::scoped_lock lock(m_audioInfoMutex);
  return m_audioInfo;
}

std::string CMediaPipelineWebOS::GetVideoInfo()
{
  std::scoped_lock lock(m_videoInfoMutex);
  return m_videoInfo;
}

bool CMediaPipelineWebOS::Supports(const AVCodecID codec, bool includeSecure)
{
  auto it = ms_codecMap.find(codec);
  if (it == ms_codecMap.end())
    return false;

  const CodecEntry& entry = it->second;
  return includeSecure || !entry.isSecure;
}

void CMediaPipelineWebOS::AcbCallback(
    long acbId, long taskId, long eventType, long appState, long playState, const char* reply)
{
  CLog::LogF(LOGDEBUG, "acbId={}, taskId={}, eventType={}, appState={}, playState={}, reply={}",
             acbId, taskId, eventType, appState, playState, reply);
}

void CMediaPipelineWebOS::FlushVideoMessages()
{
  m_processInfo.SetLevelVQ(0);
  m_messageQueueVideo.Flush();
}


Review comment (suggestion):
```suggestion
bool CMediaPipelineWebOS::Supports(const AVCodecID codec, const bool includeSecure)
{
  if (const auto it = ms_codecMap.find(codec); it != ms_codecMap.end())
    return includeSecure || !it->second.isSecure;
  return false;
}
```

Code after:
    return;

  if (playing)
    activeAE->SetVolume(0.0);
  else
    activeAE->SetVolume(1.0);
}

std::string CMediaPipelineWebOS::GetAudioInfo()
{
  std::scoped_lock lock(m_audioInfoMutex);
  return m_audioInfo;
}

std::string CMediaPipelineWebOS::GetVideoInfo()
{
  std::scoped_lock lock(m_videoInfoMutex);
  return m_videoInfo;
}

bool CMediaPipelineWebOS::Supports(const AVCodecID codec, const bool includeSecure)
{
  if (const auto it = ms_codecMap.find(codec); it != ms_codecMap.end())
    return includeSecure || !it->second.isSecure;
  return false;
}

void CMediaPipelineWebOS::AcbCallback(
    long acbId, long taskId, long eventType, long appState, long playState, const char* reply)
{
  CLog::LogF(LOGDEBUG, "acbId={}, taskId={}, eventType={}, appState={}, playState={}, reply={}",
             acbId, taskId, eventType, appState, playState, reply);
}

void CMediaPipelineWebOS::FlushVideoMessages()
{
  m_processInfo.SetLevelVQ(0);
  m_messageQueueVideo.Flush();
}

void CMediaPipelineWebOS::FlushAudioMessages()
{
  m_messageQueueAudio.Flush();
}

bool CMediaPipelineWebOS::OpenAudioStream(CDVDStreamInfo& audioHint)
{
  m_audioHint = audioHint;

  if (m_loaded)
  {
Repository: xbmc/xbmc
File: xbmc/cores/VideoPlayer/MediaPipelineWebOS.cpp (C++)

Code before:
    m_mediaAPIs = std::make_unique<StarfishMediaAPIs>();
  }

  if (m_audioHint.codec && m_videoHint.codec)
    return Load(m_videoHint, m_audioHint);
  return true;
}

bool CMediaPipelineWebOS::OpenVideoStream(CDVDStreamInfo hint)
{
  if (!Supports(hint.codec))
  {
    CLog::LogF(LOGERROR, "Unsupported codec: {}", hint.codec);
    return false;
  }

  if (m_loaded)
  {
    if (m_videoHint.codec == hint.codec)
    {
      std::scoped_lock lock(m_videoCriticalSection);
      SetupBitstreamConverter(hint);
      if (m_videoHint.uniqueId != hint.uniqueId ||
          (m_videoHint.width == hint.width && m_videoHint.height == hint.height))
      {
        Flush(true);
      }
      m_videoHint = hint;

      m_processInfo.SetVideoInterlaced(hint.interlaced);
      m_processInfo.SetVideoDimensions(hint.width, hint.height);
      m_processInfo.SetVideoDAR(static_cast<float>(hint.aspect));
      if (m_videoHint.fpsrate && m_videoHint.fpsscale)
      {
        m_processInfo.SetVideoFps(static_cast<float>(hint.fpsrate) /
                                  static_cast<float>(hint.fpsscale));
      }
      else
      {
        m_processInfo.SetVideoFps(1.0);
      }

      return true;
    }

    // Different codec => unload the current stream
    Unload(true);

    m_mediaAPIs = std::make_unique<StarfishMediaAPIs>();
  }


Review comment (bug):
I am failing to understand this condition. Adaptive streaming means that we can change bitrate, resolution and framerate dynamically. So why this check for the same resolution and the uniqueId?
Instead, can we remove flushing here completely then change the condition above like this:

```c++
if (m_videoHint.codec == hint.codec && m_videoHint.hdrType == hint.hdrType)
```

Code after:
    m_mediaAPIs = std::make_unique<StarfishMediaAPIs>();
  }

  if (m_audioHint.codec && m_videoHint.codec)
    return Load(m_videoHint, m_audioHint);
  return true;
}

bool CMediaPipelineWebOS::OpenVideoStream(CDVDStreamInfo hint)
{
  if (!Supports(hint.codec))
  {
    CLog::LogF(LOGERROR, "Unsupported codec: {}", hint.codec);
    return false;
  }

  if (m_loaded)
  {
    if (m_videoHint.codec == hint.codec && m_videoHint.hdrType == hint.hdrType)
    {
      std::scoped_lock lock(m_videoCriticalSection);
      SetupBitstreamConverter(hint);
      m_videoHint = hint;

      m_processInfo.SetVideoInterlaced(hint.interlaced);
      m_processInfo.SetVideoDimensions(hint.width, hint.height);
      m_processInfo.SetVideoDAR(static_cast<float>(hint.aspect));
      if (m_videoHint.fpsrate && m_videoHint.fpsscale)
      {
        m_processInfo.SetVideoFps(static_cast<float>(hint.fpsrate) /
                                  static_cast<float>(hint.fpsscale));
      }
      else
      {
        m_processInfo.SetVideoFps(1.0);
      }

      return true;
    }

    // Different codec => unload the current stream
    Unload(true);

    m_mediaAPIs = std::make_unique<StarfishMediaAPIs>();
  }

  m_videoHint = hint;

  if ((m_audioHint.codec || !m_hasAudio) && m_videoHint.codec)
    return Load(m_videoHint, m_audioHint);
  return true;
Repository: xbmc/xbmc
File: xbmc/filesystem/NFSDirectory.h (C/C++)

Code before:

#include <memory>
#include <vector>

class CFileItem;
struct nfsdirent;

namespace XFILE
{
  class CNFSDirectory : public IDirectory
  {
    public:
      CNFSDirectory(void);
      ~CNFSDirectory(void) override;
      bool GetDirectory(const CURL& url, CFileItemList &items) override;
      CacheType GetCacheType(const CURL& url) const override { return CacheType::ONCE; }
      bool Create(const CURL& url) override;
      bool Exists(const CURL& url) override;
      bool Remove(const CURL& url) override;
    private:
      std::vector<std::shared_ptr<CFileItem>> GetServerList() const;
      std::vector<std::shared_ptr<CFileItem>> GetDirectoryFromExportList(
          const CURL& inputURL) const;
      bool ResolveSymlink(const std::string& dirName,
                          struct nfsdirent* dirent,
                          std::string& resolvedPath) const;
  };
}



Review comment (suggestion):
I think it would be clearer to make this function `static` instead of `const`.

Code after:

#include <memory>
#include <vector>

class CFileItem;
struct nfsdirent;

namespace XFILE
{
  class CNFSDirectory : public IDirectory
  {
    public:
      CNFSDirectory(void);
      ~CNFSDirectory(void) override;
      bool GetDirectory(const CURL& url, CFileItemList &items) override;
      CacheType GetCacheType(const CURL& url) const override { return CacheType::ONCE; }
      bool Create(const CURL& url) override;
      bool Exists(const CURL& url) override;
      bool Remove(const CURL& url) override;
    private:
      std::vector<std::shared_ptr<CFileItem>> GetServerList() const;
      std::vector<std::shared_ptr<CFileItem>> GetDirectoryFromExportList(
          const CURL& inputURL) const;
  };
}
Repository: xbmc/xbmc
File: xbmc/interfaces/legacy/InfoTagVideo.cpp (C++)

Code before:
    {
      infoTag->m_strPictureURL.AddParsedUrl(url, art_type, preview, referrer, cache, post, isgz,
                                            season);
    }

    void InfoTagVideo::setAvailableFanartRaw(CVideoInfoTag* infoTag,
                                             const std::vector<Properties>& images)
    {
      infoTag->m_fanart.Clear();
      for (const auto& dictionary : images)
      {
        auto getValue = [&](std::string_view str) -> const std::string&
        {
          const auto iter = dictionary.find(str);
          if (iter != dictionary.end())
            return iter->second;
          else
            return StringUtils::Empty;
        };

        const std::string& image = getValue("image");
        const std::string& preview = getValue("preview");
        const std::string& colors = getValue("colors");

        if (!image.empty())
          infoTag->m_fanart.AddFanart(image, preview, colors);
      }
      infoTag->m_fanart.Pack();
    }
  }
}


Review comment (suggestion):
We can save some work if `image` is empty:
```suggestion
        if (const std::string& image = getValue("image"); !image.empty())
        {
          const std::string& preview = getValue("preview");
          const std::string& colors = getValue("colors");
          infoTag->m_fanart.AddFanart(image, preview, colors);
        }
```

Code after:
    {
      infoTag->m_strPictureURL.AddParsedUrl(url, art_type, preview, referrer, cache, post, isgz,
                                            season);
    }

    void InfoTagVideo::setAvailableFanartRaw(CVideoInfoTag* infoTag,
                                             const std::vector<Properties>& images)
    {
      infoTag->m_fanart.Clear();
      for (const auto& dictionary : images)
      {
        auto getValue = [&](std::string_view str) -> const std::string&
        {
          const auto iter = dictionary.find(str);
          if (iter != dictionary.end())
            return iter->second;
          else
            return StringUtils::Empty;
        };

        if (const std::string& image = getValue("image"); !image.empty())
        {
          const std::string& preview = getValue("preview");
          const std::string& colors = getValue("colors");
          infoTag->m_fanart.AddFanart(image, preview, colors);
        }
      }
      infoTag->m_fanart.Pack();
    }
  }
}
Repository: xbmc/xbmc
File: xbmc/weather/WeatherManager.cpp (C++)

Code before:
  const std::string prop{StringUtils::ToLower(property)};
  if (prop == "conditions")
  {
    return GetInfo(WEATHER_LABEL_CURRENT_COND);
  }
  else if (prop == "temperature")
  {
    return StringUtils::Format("{}{}", GetInfo(WEATHER_LABEL_CURRENT_TEMP),
                               g_langInfo.GetTemperatureUnitString());
  }
  else if (prop == "location")
  {
    return GetInfo(WEATHER_LABEL_LOCATION);
  }
  else if (prop == "fanartcode")
  {
    std::string value{URIUtils::GetFileName(GetInfo(WEATHER_IMAGE_CURRENT_ICON))};
    URIUtils::RemoveExtension(value);
    return value;
  }
  else if (prop == "conditionsicon")
  {
    return GetInfo(WEATHER_IMAGE_CURRENT_ICON);
  }

  const CGUIWindow* window{CServiceBroker::GetGUI()->GetWindowManager().GetWindow(WINDOW_WEATHER)};
  if (window)
  {
    return window->GetProperty(property).asString();
  }
  return {};
}

std::string CWeatherManager::BusyInfo(int info) const
{
  if (info == WEATHER_IMAGE_CURRENT_ICON)
    return URIUtils::AddFileToFolder(ICON_ADDON_PATH, "na.png");

  return CInfoLoader::BusyInfo(info);
}

std::string CWeatherManager::TranslateInfo(int info) const
{
  std::lock_guard lock(m_critSection);
  switch (info)
  {
    case WEATHER_LABEL_CURRENT_COND:
      return m_info.currentConditions;
    case WEATHER_IMAGE_CURRENT_ICON:
      return m_info.currentIcon;
    case WEATHER_LABEL_CURRENT_TEMP:

Review comment (bug):
CServiceBroker::GetGUI() should have a null pointer check outside of GUI code.

Code after:
  const std::string prop{StringUtils::ToLower(property)};
  if (prop == "conditions")
  {
    return GetInfo(WEATHER_LABEL_CURRENT_COND);
  }
  else if (prop == "temperature")
  {
    return StringUtils::Format("{}{}", GetInfo(WEATHER_LABEL_CURRENT_TEMP),
                               g_langInfo.GetTemperatureUnitString());
  }
  else if (prop == "location")
  {
    return GetInfo(WEATHER_LABEL_LOCATION);
  }
  else if (prop == "fanartcode")
  {
    std::string value{URIUtils::GetFileName(GetInfo(WEATHER_IMAGE_CURRENT_ICON))};
    URIUtils::RemoveExtension(value);
    return value;
  }
  else if (prop == "conditionsicon")
  {
    return GetInfo(WEATHER_IMAGE_CURRENT_ICON);
  }

  CGUIComponent* gui{CServiceBroker::GetGUI()};
  if (gui)
  {
    const CGUIWindow* window{gui->GetWindowManager().GetWindow(WINDOW_WEATHER)};
    if (window)
      return window->GetProperty(property).asString();
  }
  return {};
}

std::string CWeatherManager::BusyInfo(int info) const
{
  if (info == WEATHER_IMAGE_CURRENT_ICON)
    return URIUtils::AddFileToFolder(ICON_ADDON_PATH, "na.png");

  return CInfoLoader::BusyInfo(info);
}

std::string CWeatherManager::TranslateInfo(int info) const
{
  std::lock_guard lock(m_critSection);
  switch (info)
  {
    case WEATHER_LABEL_CURRENT_COND:
      return m_info.currentConditions;
    case WEATHER_IMAGE_CURRENT_ICON:
Repository: xbmc/xbmc
File: xbmc/platform/win32/filesystem/Win32Directory.cpp (C++)

Code before:

  if (hSearch == INVALID_HANDLE_VALUE)
    return GetLastError() == ERROR_FILE_NOT_FOUND ? Exists(url) : false; // return true if directory exist and empty

  std::vector<std::shared_ptr<CFileItem>> fileItems;
  do
  {
    std::wstring itemNameW(findData.cFileName);
    if (itemNameW == L"." || itemNameW == L"..")
      continue;

    std::string itemName;
    if (!g_charsetConverter.wToUTF8(itemNameW, itemName, true) || itemName.empty())
    {
      CLog::Log(LOGERROR, "{}: Can't convert wide string name to UTF-8 encoding", __FUNCTION__);
      continue;
    }

    const bool isDir = (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
    const bool isHidden =
        (findData.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) != 0 ||
        itemName.front() == '.'; // mark files starting from dot as hidden

    std::string itemPath(pathWithSlash + itemName);
    if (isDir)
      itemPath += '\\';

    // calculation of size and date costs a little on win32
    // so DIR_FLAG_NO_FILE_INFO flag is ignored
    auto& item = fileItems.emplace_back(std::make_shared<CFileItem>(itemName));

    item->SetFolder(isDir);
    item->SetPath(itemPath);

    if (auto entryTime = GetEntryTime(findData); entryTime.has_value())
      item->SetDateTime(entryTime.value());
    if (!isDir)
      item->SetSize(GetEntrySize(findData));
    if (isHidden)
      item->SetProperty("file:hidden", true);
  } while (FindNextFileW(hSearch, &findData));

  FindClose(hSearch);

  items.AddItems(std::move(fileItems));

  return true;
}

bool CWin32Directory::Create(const CURL& url)
{

Review comment (suggestion):
```suggestion
      itemPath.push_back('\\');
```

Code after:
        (findData.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) != 0 ||
        itemName.front() == '.'; // mark files starting from dot as hidden

    std::string itemPath(pathWithSlash + itemName);
    if (isDir)
      itemPath.push_back('\\');

    // calculation of size and date costs a little on win32
    // so DIR_FLAG_NO_FILE_INFO flag is ignored
    const auto& item = fileItems.emplace_back(std::make_shared<CFileItem>(itemName));

    item->SetFolder(isDir);
    item->SetPath(itemPath);

    using KODI::TIME::FileTime;
    FileTime localTime{};

    if (FileTimeToLocalFileTime(reinterpret_cast<const FileTime*>(&findData.ftLastWriteTime),
                                &localTime) == TRUE)
      item->SetDateTime(localTime);

    if (!isDir)
      item->SetSize((static_cast<int64_t>(findData.nFileSizeHigh) << 32) + findData.nFileSizeLow);

    if (isHidden)
      item->SetProperty("file:hidden", true);

  } while (FindNextFileW(hSearch, &findData));

  items.AddItems(std::move(fileItems));

  FindClose(hSearch);

  return true;
}

bool CWin32Directory::Create(const CURL& url)
{
  auto nameW(prepareWin32DirectoryName(url.Get()));
  if (nameW.empty())
    return false;

  if (!Create(nameW))
    return Exists(url);

  return true;
}

bool CWin32Directory::Exists(const CURL& url)
{
  std::wstring nameW(prepareWin32DirectoryName(url.Get()));