<commit_before>/*=========================================================================

  Program: DICOM for VTK

  Copyright (c) 2012-2014 David Gobbi
  All rights reserved.
  See Copyright.txt or http://dgobbi.github.io/bsd3.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkDICOMDirectory.h"
#include "vtkDICOMMetaData.h"
#include "vtkDICOMItem.h"
#include "vtkDICOMDataElement.h"
#include "vtkDICOMParser.h"
#include "vtkDICOMMetaData.h"
#include "vtkDICOMMetaDataAdapter.h"

// from dicomcli
#include "readquery.h"

#include <vtkStringArray.h>
#include <vtkSmartPointer.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <iostream>

// print the version
void dicomfind_version(FILE *file, const char *cp)
{
  fprintf(file, "%s %s\n", cp, DICOM_VERSION);
  fprintf(file, "\n"
    "Copyright (c) 2012-2014, David Gobbi.\n\n"
    "This software is distributed under an open-source license.  See the\n"
    "Copyright.txt file that comes with the vtk-dicom source distribution.\n");
}

// print the usage
void dicomfind_usage(FILE *file, const char *cp)
{
  fprintf(file, "usage:\n"
    "  %s -q <query.txt> -o <data.csv> <directory>\n\n", cp);
  fprintf(file, "options:\n"
    "  -q <query.txt>  Provide a file to describe the find query.\n"
    "  -o <data.csv>   Provide a file for the query results.\n"
    "  --help          Print a brief help message.\n"
    "  --version       Print the software version.\n");
}

// print the help
void dicomfind_help(FILE *file, const char *cp)
{
  dicomfind_usage(file, cp);
  fprintf(file, "\n"
    "Dump the metadata from a DICOM series as text.\n");
}

// remove path portion of filename
const char *dicomfind_basename(const char *filename)
{
  const char *cp = filename + strlen(filename);
  while (cp != filename && cp[-1] != '\\' && cp[-1] != '/') { --cp; }
  return cp;
}

typedef vtkDICOMVR VR;

// Write the header
void dicomfind_writeheader(
  const vtkDICOMItem& query, const QueryTagList *ql, std::ostream& os)
{
  // print human-readable names for each tag
  for (size_t i = 0; i < ql->size(); i++)
    {
    if (i != 0)
      {
      os << ",";
      }
    const vtkDICOMItem *pitem = &query;
    vtkDICOMTagPath tagPath = ql->at(i);
    for (;;)
      {
      vtkDICOMTag tag = tagPath.GetHead();
      vtkDICOMDictEntry e = pitem->FindDictEntry(tag);
      if (e.IsValid())
        {
        os << e.GetName();
        }
      if (!tagPath.HasTail())
        {
        break;
        }
      pitem = pitem->GetAttributeValue(tag).GetSequenceData();
      tagPath = tagPath.GetTail();
      os << "\\";
      }
    }
  os << "\r\n";

  // print the private creator
  for (size_t i = 0; i < ql->size(); i++)
    {
    if (i != 0)
      {
      os << ",";
      }
    const vtkDICOMItem *pitem = &query;
    vtkDICOMTagPath tagPath = ql->at(i);
    for (;;)
      {
      vtkDICOMTag tag = tagPath.GetHead();
      std::string creator = "DICOM";
      if ((tag.GetGroup() & 0x0001) == 1)
        {
        vtkDICOMTag ctag(tag.GetGroup(), tag.GetElement() >> 8);
        creator = pitem->GetAttributeValue(ctag).AsString();
        }
      os << creator.c_str();
      if (!tagPath.HasTail())
        {
        break;
        }
      pitem = pitem->GetAttributeValue(tag).GetSequenceData();
      tagPath = tagPath.GetTail();
      os << "\\";
      }
    }
  os << "\r\n";

  // print the tag as a hexadecimal number
  for (size_t i = 0; i < ql->size(); i++)
    {
    if (i != 0)
      {
      os << ",";
      }
    const vtkDICOMItem *pitem = &query;
    vtkDICOMTagPath tagPath = ql->at(i);
    for (;;)
      {
      vtkDICOMTag tag = tagPath.GetHead();
      unsigned short g = tag.GetGroup();
      unsigned short e = tag.GetElement();
      std::string creator;
      if ((tag.GetGroup() & 0x0001) == 1)
        {
        vtkDICOMTag ctag(tag.GetGroup(), tag.GetElement() >> 8);
        creator = pitem->GetAttributeValue(ctag).AsString();
        if (creator.length() > 0)
          {
          // remove the creator portion of the element number
          e &= 0x00FF;
          }
        }
      char tagtext[16];
      sprintf(tagtext, "%04X%04X", g, e);
      os << tagtext;
      if (!tagPath.HasTail())
        {
        break;
        }
      pitem = pitem->GetAttributeValue(tag).GetSequenceData();
      tagPath = tagPath.GetTail();
      os << "\\";
      }
    }
  os << "\r\n";

  // print the VR
  for (size_t i = 0; i < ql->size(); i++)
    {
    if (i != 0)
      {
      os << ",";
      }
    const vtkDICOMItem *pitem = &query;
    vtkDICOMTagPath tagPath = ql->at(i);
    vtkDICOMValue v = query.GetAttributeValue(tagPath);
    if (v.IsValid())
      {
      os << v.GetVR().GetText();
      }
    else
      {
      for (;;)
        {
        vtkDICOMTag tag = tagPath.GetHead();
        if (!tagPath.HasTail())
          {
          vtkDICOMDictEntry e = pitem->FindDictEntry(tag);
          if (e.IsValid())
            {
            os << e.GetVR().GetText();
            }
          break;
          }
        pitem = pitem->GetAttributeValue(tag).GetSequenceData();
        tagPath = tagPath.GetTail();
        }
      }
    }
  os << "\r\n";
}

// Convert date to format YYYY-MM-DD HH:MM:SS
std::string dicomfind_date(const std::string& dt, vtkDICOMVR vr)
{
  if (vr == VR::TM && dt.length() >= 6)
    {
    return dt.substr(0,2) + ":" + dt.substr(2,2) + ":" + dt.substr(4,2);
    }
  else if (vr == VR::DA && dt.length() >= 8)
    {
    return dt.substr(0,4) + "-" + dt.substr(4,2) + "-" + dt.substr(6,2);
    }
  else if (vr == VR::DT && dt.length() >= 14)
    {
    return dt.substr(0,4) + "-" + dt.substr(4,2) + "-" + dt.substr(6,2) + " " +
           dt.substr(8,2) + ":" + dt.substr(10,2) + ":" + dt.substr(12,2);
    }

  return "";
}

// Quote a string by doubling any double-quotes that are found
// (this follows RFC 4180)
std::string dicomfind_quote(const std::string& s)
{
  size_t i = 0;
  std::string r;

  for (;;)
    {
    size_t j = s.find('\"', i);
    if (j < s.length())
      {
      r += s.substr(i, j-i+1);
      r += "\"";
      i = j+1;
      }
    else
      {
      r += s.substr(i);
      break;
      }
    }

  return r;
}

// Write out the results
void dicomfind_write(vtkDICOMDirectory *finder,
  const vtkDICOMItem& query, const QueryTagList *ql, std::ostream& os)
{
  for (int j = 0; j < finder->GetNumberOfStudies(); j++)
    {
    int k0 = finder->GetFirstSeriesForStudy(j);
    int k1 = finder->GetLastSeriesForStudy(j);
    for (int k = k0; k <= k1; k++)
      {
      vtkStringArray *a = finder->GetFileNamesForSeries(k);
      if (a->GetNumberOfValues() == 0)
        {
        continue;
        }

      vtkSmartPointer<vtkDICOMMetaData> meta =
        vtkSmartPointer<vtkDICOMMetaData>::New();
      vtkSmartPointer<vtkDICOMParser> parser =
        vtkSmartPointer<vtkDICOMParser>::New();

      parser->SetFileName(a->GetValue(0));
      parser->SetMetaData(meta);
      parser->SetQueryItem(query);
      parser->Update();

      // create an adapter, in case of enhanced IOD
      vtkDICOMMetaDataAdapter adapter(meta);

      // print the value of each tag
      for (size_t i = 0; i < ql->size(); i++)
        {
        if (i != 0)
          {
          os << ",";
          }

        const vtkDICOMItem *qitem = &query;
        const vtkDICOMItem *mitem = 0;
        const vtkDICOMValue *vp = 0;
        vtkDICOMTagPath tagPath = ql->at(i);
        for (;;)
          {
          vtkDICOMTag tag = tagPath.GetHead();
          std::string creator;
          if ((tag.GetGroup() & 0x0001) == 1)
            {
            vtkDICOMTag ctag(tag.GetGroup(), tag.GetElement() >> 8);
            creator = qitem->GetAttributeValue(ctag).AsString();
            if (mitem)
              {
              tag = mitem->ResolvePrivateTag(tag, creator);
              }
            else
              {
              tag = adapter->ResolvePrivateTag(tag, creator);
              }
            }
          if (mitem)
            {
            vp = &mitem->GetAttributeValue(tag);
            }
          else
            {
            vp = &adapter->GetAttributeValue(tag);
            }
          if (vp && !vp->IsValid())
            {
            vp = 0;
            }
          if (vp == 0 || !tagPath.HasTail())
            {
            break;
            }
          qitem = qitem->GetAttributeValue(
            tagPath.GetHead()).GetSequenceData();
          tagPath = tagPath.GetTail();
          mitem = vp->GetSequenceData();
          if (mitem == 0 || vp->GetNumberOfValues() == 0)
            {
            break;
            }
          }

        if (vp != 0)
          {
          const vtkDICOMValue& v = *vp;
          if (v.GetNumberOfValues() == 1 &&
              (v.GetVR() == VR::SS ||
               v.GetVR() == VR::US ||
               v.GetVR() == VR::SL ||
               v.GetVR() == VR::UL ||
               v.GetVR() == VR::FL ||
               v.GetVR() == VR::FD))
            {
            os << v;
            }
          else if (v.GetVR() == VR::DA ||
                   v.GetVR() == VR::TM ||
                   v.GetVR() == VR::DT)
            {
            os << "\"" << dicomfind_date(v.AsString(), v.GetVR()) << "\"";
            }
          else if (v.GetVR() == VR::SQ)
            {
            // how should a sequence be printed out to the csv file?
            }
          else if (v.GetVL() != 0 && v.GetVL() != 0xFFFFFFFF)
            {
            os << "\"" << dicomfind_quote(v.AsUTF8String()) << "\"";
            }
          }
        else if (tagPath.GetHead() == DC::ReferencedFileID &&
                 !tagPath.HasTail())
          {
          // ReferencedFileID (0004,1500) is meant to be used in DICOMDIR files,
          // but we hijack it to report the first file in the series.
          os << "\"" << dicomfind_quote(a->GetValue(0)) << "\"";
          }
        else if (tagPath.GetHead() == DC::NumberOfReferences &&
                 !tagPath.HasTail())
          {
          // NumberOfReferences (0004,1600) is a retired attribute meant count the
          // number of references to a file, but we hijack it and use it to report
          // the number of files found for the series.
          os << "\"" << a->GetNumberOfValues() << "\"";
          }
        }

      os << "\r\n";
      }
    }
}

// This program will dump all the metadata in the given file
int main(int argc, char *argv[])
{
  int rval = 0;

  vtkSmartPointer<vtkStringArray> a = vtkSmartPointer<vtkStringArray>::New();
  const char *ofile = 0;
  const char *qfile = 0;

  if (argc < 2)
    {
    dicomfind_usage(stdout, dicomfind_basename(argv[0]));
    return rval;
    }
  else if (argc == 2 && strcmp(argv[1], "--help") == 0)
    {
    dicomfind_help(stdout, dicomfind_basename(argv[0]));
    return rval;
    }
  else if (argc == 2 && strcmp(argv[1], "--version") == 0)
    {
    dicomfind_version(stdout, dicomfind_basename(argv[0]));
    return rval;
    }

  for (int argi = 1; argi < argc; argi++)
    {
    const char *arg = argv[argi];
    if (strcmp(arg, "-q") == 0 || strcmp(arg, "-o") == 0)
      {
      if (argi + 1 == argc || argv[argi+1][0] == '-')
        {
        fprintf(stderr, "%s must be followed by a file.\n\n", arg);
        dicomfind_usage(stderr, dicomfind_basename(argv[0]));
        return 1;
        }

      if (arg[1] == 'q')
        {
        qfile = argv[++argi];
        }
      else if (arg[1] == 'o')
        {
        ofile = argv[++argi];
        }
      }
    else if (arg[0] == '-')
      {
      fprintf(stderr, "unrecognized option %s.\n\n", arg);
      dicomfind_usage(stderr, dicomfind_basename(argv[0]));
      return 1;
      }
    else
      {
      a->InsertNextValue(arg);
      }
    }

  if (qfile == 0)
    {
    fprintf(stderr, "No query file.\n\n");
    dicomfind_usage(stderr, dicomfind_basename(argv[0]));
    return 1;
    }

  std::ostream *osp = &std::cout;
  std::ofstream ofs;

  if (ofile)
    {
    ofs.open(ofile,
             std::ofstream::out |
             std::ofstream::binary |
             std::ofstream::trunc);

    if (ofs.bad())
      {
      fprintf(stderr, "Unable to open output file %s.\n", ofile);
      return 1;
      }
    osp = &ofs;
    }

  // read the query file, create a query
  QueryTagList qtlist;
  vtkDICOMItem query = dicomcli_readquery(qfile, &qtlist);

  // always add the functional sequences for advanced files
  query.SetAttributeValue(
    DC::SharedFunctionalGroupsSequence, vtkDICOMValue(VR::SQ));
  query.SetAttributeValue(
    DC::PerFrameFunctionalGroupsSequence, vtkDICOMValue(VR::SQ));

  // Write the header
  dicomfind_writeheader(query, &qtlist, *osp);
  osp->flush();

  // Write data for every input directory
  for (vtkIdType i = 0; i < a->GetNumberOfTuples(); i++)
    {
    vtkSmartPointer<vtkDICOMDirectory> finder =
      vtkSmartPointer<vtkDICOMDirectory>::New();
    finder->SetDirectoryName(a->GetValue(i));
    finder->SetScanDepth(8);
    finder->SetFindQuery(query);
    finder->Update();

    dicomfind_write(finder, query, &qtlist, *osp);
    osp->flush();
    }

  return rval;
}
<commit_msg>Fix grammar in code comment.<commit_after>/*=========================================================================

  Program: DICOM for VTK

  Copyright (c) 2012-2014 David Gobbi
  All rights reserved.
  See Copyright.txt or http://dgobbi.github.io/bsd3.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkDICOMDirectory.h"
#include "vtkDICOMMetaData.h"
#include "vtkDICOMItem.h"
#include "vtkDICOMDataElement.h"
#include "vtkDICOMParser.h"
#include "vtkDICOMMetaData.h"
#include "vtkDICOMMetaDataAdapter.h"

// from dicomcli
#include "readquery.h"

#include <vtkStringArray.h>
#include <vtkSmartPointer.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <iostream>

// print the version
void dicomfind_version(FILE *file, const char *cp)
{
  fprintf(file, "%s %s\n", cp, DICOM_VERSION);
  fprintf(file, "\n"
    "Copyright (c) 2012-2014, David Gobbi.\n\n"
    "This software is distributed under an open-source license.  See the\n"
    "Copyright.txt file that comes with the vtk-dicom source distribution.\n");
}

// print the usage
void dicomfind_usage(FILE *file, const char *cp)
{
  fprintf(file, "usage:\n"
    "  %s -q <query.txt> -o <data.csv> <directory>\n\n", cp);
  fprintf(file, "options:\n"
    "  -q <query.txt>  Provide a file to describe the find query.\n"
    "  -o <data.csv>   Provide a file for the query results.\n"
    "  --help          Print a brief help message.\n"
    "  --version       Print the software version.\n");
}

// print the help
void dicomfind_help(FILE *file, const char *cp)
{
  dicomfind_usage(file, cp);
  fprintf(file, "\n"
    "Dump the metadata from a DICOM series as text.\n");
}

// remove path portion of filename
const char *dicomfind_basename(const char *filename)
{
  const char *cp = filename + strlen(filename);
  while (cp != filename && cp[-1] != '\\' && cp[-1] != '/') { --cp; }
  return cp;
}

typedef vtkDICOMVR VR;

// Write the header
void dicomfind_writeheader(
  const vtkDICOMItem& query, const QueryTagList *ql, std::ostream& os)
{
  // print human-readable names for each tag
  for (size_t i = 0; i < ql->size(); i++)
    {
    if (i != 0)
      {
      os << ",";
      }
    const vtkDICOMItem *pitem = &query;
    vtkDICOMTagPath tagPath = ql->at(i);
    for (;;)
      {
      vtkDICOMTag tag = tagPath.GetHead();
      vtkDICOMDictEntry e = pitem->FindDictEntry(tag);
      if (e.IsValid())
        {
        os << e.GetName();
        }
      if (!tagPath.HasTail())
        {
        break;
        }
      pitem = pitem->GetAttributeValue(tag).GetSequenceData();
      tagPath = tagPath.GetTail();
      os << "\\";
      }
    }
  os << "\r\n";

  // print the private creator
  for (size_t i = 0; i < ql->size(); i++)
    {
    if (i != 0)
      {
      os << ",";
      }
    const vtkDICOMItem *pitem = &query;
    vtkDICOMTagPath tagPath = ql->at(i);
    for (;;)
      {
      vtkDICOMTag tag = tagPath.GetHead();
      std::string creator = "DICOM";
      if ((tag.GetGroup() & 0x0001) == 1)
        {
        vtkDICOMTag ctag(tag.GetGroup(), tag.GetElement() >> 8);
        creator = pitem->GetAttributeValue(ctag).AsString();
        }
      os << creator.c_str();
      if (!tagPath.HasTail())
        {
        break;
        }
      pitem = pitem->GetAttributeValue(tag).GetSequenceData();
      tagPath = tagPath.GetTail();
      os << "\\";
      }
    }
  os << "\r\n";

  // print the tag as a hexadecimal number
  for (size_t i = 0; i < ql->size(); i++)
    {
    if (i != 0)
      {
      os << ",";
      }
    const vtkDICOMItem *pitem = &query;
    vtkDICOMTagPath tagPath = ql->at(i);
    for (;;)
      {
      vtkDICOMTag tag = tagPath.GetHead();
      unsigned short g = tag.GetGroup();
      unsigned short e = tag.GetElement();
      std::string creator;
      if ((tag.GetGroup() & 0x0001) == 1)
        {
        vtkDICOMTag ctag(tag.GetGroup(), tag.GetElement() >> 8);
        creator = pitem->GetAttributeValue(ctag).AsString();
        if (creator.length() > 0)
          {
          // remove the creator portion of the element number
          e &= 0x00FF;
          }
        }
      char tagtext[16];
      sprintf(tagtext, "%04X%04X", g, e);
      os << tagtext;
      if (!tagPath.HasTail())
        {
        break;
        }
      pitem = pitem->GetAttributeValue(tag).GetSequenceData();
      tagPath = tagPath.GetTail();
      os << "\\";
      }
    }
  os << "\r\n";

  // print the VR
  for (size_t i = 0; i < ql->size(); i++)
    {
    if (i != 0)
      {
      os << ",";
      }
    const vtkDICOMItem *pitem = &query;
    vtkDICOMTagPath tagPath = ql->at(i);
    vtkDICOMValue v = query.GetAttributeValue(tagPath);
    if (v.IsValid())
      {
      os << v.GetVR().GetText();
      }
    else
      {
      for (;;)
        {
        vtkDICOMTag tag = tagPath.GetHead();
        if (!tagPath.HasTail())
          {
          vtkDICOMDictEntry e = pitem->FindDictEntry(tag);
          if (e.IsValid())
            {
            os << e.GetVR().GetText();
            }
          break;
          }
        pitem = pitem->GetAttributeValue(tag).GetSequenceData();
        tagPath = tagPath.GetTail();
        }
      }
    }
  os << "\r\n";
}

// Convert date to format YYYY-MM-DD HH:MM:SS
std::string dicomfind_date(const std::string& dt, vtkDICOMVR vr)
{
  if (vr == VR::TM && dt.length() >= 6)
    {
    return dt.substr(0,2) + ":" + dt.substr(2,2) + ":" + dt.substr(4,2);
    }
  else if (vr == VR::DA && dt.length() >= 8)
    {
    return dt.substr(0,4) + "-" + dt.substr(4,2) + "-" + dt.substr(6,2);
    }
  else if (vr == VR::DT && dt.length() >= 14)
    {
    return dt.substr(0,4) + "-" + dt.substr(4,2) + "-" + dt.substr(6,2) + " " +
           dt.substr(8,2) + ":" + dt.substr(10,2) + ":" + dt.substr(12,2);
    }

  return "";
}

// Quote a string by doubling any double-quotes that are found
// (this follows RFC 4180)
std::string dicomfind_quote(const std::string& s)
{
  size_t i = 0;
  std::string r;

  for (;;)
    {
    size_t j = s.find('\"', i);
    if (j < s.length())
      {
      r += s.substr(i, j-i+1);
      r += "\"";
      i = j+1;
      }
    else
      {
      r += s.substr(i);
      break;
      }
    }

  return r;
}

// Write out the results
void dicomfind_write(vtkDICOMDirectory *finder,
  const vtkDICOMItem& query, const QueryTagList *ql, std::ostream& os)
{
  for (int j = 0; j < finder->GetNumberOfStudies(); j++)
    {
    int k0 = finder->GetFirstSeriesForStudy(j);
    int k1 = finder->GetLastSeriesForStudy(j);
    for (int k = k0; k <= k1; k++)
      {
      vtkStringArray *a = finder->GetFileNamesForSeries(k);
      if (a->GetNumberOfValues() == 0)
        {
        continue;
        }

      vtkSmartPointer<vtkDICOMMetaData> meta =
        vtkSmartPointer<vtkDICOMMetaData>::New();
      vtkSmartPointer<vtkDICOMParser> parser =
        vtkSmartPointer<vtkDICOMParser>::New();

      parser->SetFileName(a->GetValue(0));
      parser->SetMetaData(meta);
      parser->SetQueryItem(query);
      parser->Update();

      // create an adapter, in case of enhanced IOD
      vtkDICOMMetaDataAdapter adapter(meta);

      // print the value of each tag
      for (size_t i = 0; i < ql->size(); i++)
        {
        if (i != 0)
          {
          os << ",";
          }

        const vtkDICOMItem *qitem = &query;
        const vtkDICOMItem *mitem = 0;
        const vtkDICOMValue *vp = 0;
        vtkDICOMTagPath tagPath = ql->at(i);
        for (;;)
          {
          vtkDICOMTag tag = tagPath.GetHead();
          std::string creator;
          if ((tag.GetGroup() & 0x0001) == 1)
            {
            vtkDICOMTag ctag(tag.GetGroup(), tag.GetElement() >> 8);
            creator = qitem->GetAttributeValue(ctag).AsString();
            if (mitem)
              {
              tag = mitem->ResolvePrivateTag(tag, creator);
              }
            else
              {
              tag = adapter->ResolvePrivateTag(tag, creator);
              }
            }
          if (mitem)
            {
            vp = &mitem->GetAttributeValue(tag);
            }
          else
            {
            vp = &adapter->GetAttributeValue(tag);
            }
          if (vp && !vp->IsValid())
            {
            vp = 0;
            }
          if (vp == 0 || !tagPath.HasTail())
            {
            break;
            }
          qitem = qitem->GetAttributeValue(
            tagPath.GetHead()).GetSequenceData();
          tagPath = tagPath.GetTail();
          mitem = vp->GetSequenceData();
          if (mitem == 0 || vp->GetNumberOfValues() == 0)
            {
            break;
            }
          }

        if (vp != 0)
          {
          const vtkDICOMValue& v = *vp;
          if (v.GetNumberOfValues() == 1 &&
              (v.GetVR() == VR::SS ||
               v.GetVR() == VR::US ||
               v.GetVR() == VR::SL ||
               v.GetVR() == VR::UL ||
               v.GetVR() == VR::FL ||
               v.GetVR() == VR::FD))
            {
            os << v;
            }
          else if (v.GetVR() == VR::DA ||
                   v.GetVR() == VR::TM ||
                   v.GetVR() == VR::DT)
            {
            os << "\"" << dicomfind_date(v.AsString(), v.GetVR()) << "\"";
            }
          else if (v.GetVR() == VR::SQ)
            {
            // how should a sequence be printed out to the csv file?
            }
          else if (v.GetVL() != 0 && v.GetVL() != 0xFFFFFFFF)
            {
            os << "\"" << dicomfind_quote(v.AsUTF8String()) << "\"";
            }
          }
        else if (tagPath.GetHead() == DC::ReferencedFileID &&
                 !tagPath.HasTail())
          {
          // ReferencedFileID (0004,1500) is meant to be used in DICOMDIR files,
          // but we hijack it to report the first file in the series.
          os << "\"" << dicomfind_quote(a->GetValue(0)) << "\"";
          }
        else if (tagPath.GetHead() == DC::NumberOfReferences &&
                 !tagPath.HasTail())
          {
          // NumberOfReferences (0004,1600) is a retired attribute meant to count
          // the number of references to a file, but we hijack it and use it to
          // report the number of files found for the series.
          os << "\"" << a->GetNumberOfValues() << "\"";
          }
        }

      os << "\r\n";
      }
    }
}

// This program will dump all the metadata in the given file
int main(int argc, char *argv[])
{
  int rval = 0;

  vtkSmartPointer<vtkStringArray> a = vtkSmartPointer<vtkStringArray>::New();
  const char *ofile = 0;
  const char *qfile = 0;

  if (argc < 2)
    {
    dicomfind_usage(stdout, dicomfind_basename(argv[0]));
    return rval;
    }
  else if (argc == 2 && strcmp(argv[1], "--help") == 0)
    {
    dicomfind_help(stdout, dicomfind_basename(argv[0]));
    return rval;
    }
  else if (argc == 2 && strcmp(argv[1], "--version") == 0)
    {
    dicomfind_version(stdout, dicomfind_basename(argv[0]));
    return rval;
    }

  for (int argi = 1; argi < argc; argi++)
    {
    const char *arg = argv[argi];
    if (strcmp(arg, "-q") == 0 || strcmp(arg, "-o") == 0)
      {
      if (argi + 1 == argc || argv[argi+1][0] == '-')
        {
        fprintf(stderr, "%s must be followed by a file.\n\n", arg);
        dicomfind_usage(stderr, dicomfind_basename(argv[0]));
        return 1;
        }

      if (arg[1] == 'q')
        {
        qfile = argv[++argi];
        }
      else if (arg[1] == 'o')
        {
        ofile = argv[++argi];
        }
      }
    else if (arg[0] == '-')
      {
      fprintf(stderr, "unrecognized option %s.\n\n", arg);
      dicomfind_usage(stderr, dicomfind_basename(argv[0]));
      return 1;
      }
    else
      {
      a->InsertNextValue(arg);
      }
    }

  if (qfile == 0)
    {
    fprintf(stderr, "No query file.\n\n");
    dicomfind_usage(stderr, dicomfind_basename(argv[0]));
    return 1;
    }

  std::ostream *osp = &std::cout;
  std::ofstream ofs;

  if (ofile)
    {
    ofs.open(ofile,
             std::ofstream::out |
             std::ofstream::binary |
             std::ofstream::trunc);

    if (ofs.bad())
      {
      fprintf(stderr, "Unable to open output file %s.\n", ofile);
      return 1;
      }
    osp = &ofs;
    }

  // read the query file, create a query
  QueryTagList qtlist;
  vtkDICOMItem query = dicomcli_readquery(qfile, &qtlist);

  // always add the functional sequences for advanced files
  query.SetAttributeValue(
    DC::SharedFunctionalGroupsSequence, vtkDICOMValue(VR::SQ));
  query.SetAttributeValue(
    DC::PerFrameFunctionalGroupsSequence, vtkDICOMValue(VR::SQ));

  // Write the header
  dicomfind_writeheader(query, &qtlist, *osp);
  osp->flush();

  // Write data for every input directory
  for (vtkIdType i = 0; i < a->GetNumberOfTuples(); i++)
    {
    vtkSmartPointer<vtkDICOMDirectory> finder =
      vtkSmartPointer<vtkDICOMDirectory>::New();
    finder->SetDirectoryName(a->GetValue(i));
    finder->SetScanDepth(8);
    finder->SetFindQuery(query);
    finder->Update();

    dicomfind_write(finder, query, &qtlist, *osp);
    osp->flush();
    }

  return rval;
}
<|endoftext|>


<commit_before>#include "Enemy.h"

/*
Enemy::Enemy(vector3 ipos)
{
	BOMngr = MyBoundingObjectManager::GetInstance();
	spawn(ipos);
	name += std::to_string(rand());
	meshManager->LoadModel("Thwomp.obj", name);
	vertexList = meshManager->GetVertexList(name);
	BOMngr->SetBO(vertexList, name, "enem", nullptr);
}
*/
Enemy::~Enemy()
{

}

void Enemy::move(double fTimeSpan)
{
	//cout << "calling update of" << name << endl;

	fRunTime += fTimeSpan;
	float flerp = MapValue(fRunTime, 0.0f, 10.0f, 0.0f, 1.0f);
	vector3 v3lerp = glm::lerp(pos, vector3(0,1,0), flerp);
	GameObject::SetModelMatrix(glm::translate(v3lerp));

	std::cout << "MOVE" << std::endl;

	/*
	meshManager->SetModelMatrix(glm::translate(v3lerp), name);
	BOMngr->SetModelMatrix(name, meshManager->GetModelMatrix(name));*/
	GameObject::Render();

}

void Enemy::Update(double fTimeSpan)
{

	if (isAlive)
	{
		move(fTimeSpan);
		//if its has no health make it dead and remove it from the bounding object vector

	}
}

void Enemy::Die() {
	isAlive = false;
	BOMngr->RemoveBO(BO);
}

void Enemy::spawn(vector3 ipos)
{
	fRunTime = 0;
	pos = ipos;
	pos.y = 1;
	isAlive = true;
}
/*
void Enemy::Render()
{
	//meshManager->AddCubeToRenderList(glm::translate(pos), REBLUE, SOLID);
	//meshManager->AddInstanceToRenderList(name);
	GameObject::Render();
}*/
<commit_msg>Removed MOVE debug print for enemies.<commit_after>#include "Enemy.h"

/*
Enemy::Enemy(vector3 ipos)
{
	BOMngr = MyBoundingObjectManager::GetInstance();
	spawn(ipos);
	name += std::to_string(rand());
	meshManager->LoadModel("Thwomp.obj", name);
	vertexList = meshManager->GetVertexList(name);
	BOMngr->SetBO(vertexList, name, "enem", nullptr);
}
*/
Enemy::~Enemy()
{

}

void Enemy::move(double fTimeSpan)
{
	//cout << "calling update of" << name << endl;

	fRunTime += fTimeSpan;
	float flerp = MapValue(fRunTime, 0.0f, 10.0f, 0.0f, 1.0f);
	vector3 v3lerp = glm::lerp(pos, vector3(0,1,0), flerp);
	GameObject::SetModelMatrix(glm::translate(v3lerp));

	/*
	meshManager->SetModelMatrix(glm::translate(v3lerp), name);
	BOMngr->SetModelMatrix(name, meshManager->GetModelMatrix(name));*/
	GameObject::Render();

}

void Enemy::Update(double fTimeSpan)
{

	if (isAlive)
	{
		move(fTimeSpan);
		//if its has no health make it dead and remove it from the bounding object vector

	}
}

void Enemy::Die() {
	isAlive = false;
	BOMngr->RemoveBO(BO);
}

void Enemy::spawn(vector3 ipos)
{
	fRunTime = 0;
	pos = ipos;
	pos.y = 1;
	isAlive = true;
}
/*
void Enemy::Render()
{
	//meshManager->AddCubeToRenderList(glm::translate(pos), REBLUE, SOLID);
	//meshManager->AddInstanceToRenderList(name);
	GameObject::Render();
}*/
<|endoftext|>


<commit_before>/*
 * QuadraticFunctions.cpp
 *
 *  Created on: Sep. 2017
 *      Author: NizyBoxer03
 */

#include <iostream>
#include <cmath>

class ConvFunc
{
	public:
		float a = 0, b = 0, c = 0, x1 = 0, x2 = 0, xv = 0, yv = 0;
		void stoi(float a, float b, float c)
		{
			n = true;
			x1 = bhsk(a, b, c, n);
			n = false;
			x2 = bhsk(a, b, c, n);
			std::cout << "The Intercept Form is:\n";
			std::cout << a << "(x+" << x1 << ")" << "(x+" << x2 << ")" <<"\n";
		}

		void stov(float a, float b, float c)
		{
			xv = xvp(a, b);
			yv = yvp(a, b, c, xv);
			std::cout << "The Vertex Form is:\n";
			std::cout << a << "(x-" << xv << ")^2+" << yv <<"\n";
		}

		float itos(/*float a, float x1, float x2*/)
		{
			std::cout << "TEST\n";
			return 0;
		}

		float itov(/*float a, float x1, float x2*/)
		{
			std::cout << "TEST\n";
			return 0;
		}

		float vtos(/*float a, float x1, float x2*/)
				{
					std::cout << "TEST\n";
					return 0;
				}

		float vtoi(/*float a, float x1, float x2*/)
				{
					std::cout << "TEST\n";
					return 0;
				}

		void sel()
			{
				std::cout << "Select an option:\n1.Standard to Intercept.\n2.Standard to Vertex.\n3.Intercept to Standard.\n4.Intercept to Vertex.\n5.Vertex to Standard.\n6.Vertex to Intercept.\n";
				std::cin >> opt;
				switch(opt)
				{
					case 1:
						std::cout << "Enter the value of \"a\":\n";
						std::cin >> a;
						std::cout << "Enter the value of \"b\":\n";
						std::cin >> b;
						std::cout << "Enter the value of \"c\":\n";
						std::cin >> c;
						stoi(a, b, c);
						break;

					case 2:
						std::cout << "Enter the value of \"a\":\n";
						std::cin >> a;
						std::cout << "Enter the value of \"b\":\n";
						std::cin >> b;
						std::cout << "Enter the value of \"c\":\n";
						std::cin >> c;
						stov(a, b, c);
						break;

					case 3:
						itos();
						break;

					case 4:
						itov();
						break;

					case 5:
						vtos();
						break;

					case 6:
						vtoi();
						break;
				}
			}

	private:
		int opt;
		bool n;
		float bhsk(float a, float b, float c, bool n)
		{
			float x = 0;
			float a2 = (2*a) ;
			if(n == true)
			{
				x = (-b+sqrt(pow(b, 2)-4*a*c))/a2 ;
			}
			else
			{
				x = (-b-sqrt(pow(b, 2)-4*a*c))/a2;
			}
			return x;
		}

		float xvp(float a, float b)
		{
			float x = 0;
			x = (-b/(2*a));
			return x;
		}

		float xvf(/*float x1, float x2*/)
		{
			std::cout << "TEST\n";
			return 0;
		}

		float yvp(float a, float b, float c, float xv)
		{
			float x = 0, pxv = pow(xv, 2), apxv = (a*pxv), bxv = (b*xv);
			x = (apxv+bxv+c);
			return x;
		}

		float yvf(/*float a, float x1, float x2, float xv*/)
		{
			std::cout << "TEST\n";
			return 0;
		}
};

int main(int argc, char **argv)
{
	ConvFunc cf;
	cf.sel();
	return 0;
}

<commit_msg>Delete QuadraticFunctions.cpp<commit_after><|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

// Interface to the Altro format
// to read and write digits
// To be used in Alice Data Challenges
// and in the compression of the RAW data

#include "AliAltroBuffer.h"
#include "AliAltroMapping.h"
#include "AliRawDataHeaderSim.h"
#include "AliLog.h"
#include "AliFstream.h"
//#include <stdlib.h>

ClassImp(AliAltroBuffer)

//_____________________________________________________________________________
AliAltroBuffer::AliAltroBuffer(const char* fileName, AliAltroMapping *mapping):
  fShift(0),
  fCurrentCell(0),
  fFreeCellBuffer(16),
  fVerbose(0),
  fFile(NULL),
  fDataHeaderPos(0),
  fMapping(mapping)
{
  //the buffer is cleaned
  for (Int_t i = 0; i < 5; i++) fBuffer[i] = 0;

  //open the output file
  fFile = new AliFstream(fileName);

}

//_____________________________________________________________________________
AliAltroBuffer::~AliAltroBuffer()
{
// destructor

  //Flush out the Buffer content at the end only if Buffer wasn't completely filled
  Flush();
  if (fVerbose) Info("~AliAltroBuffer", "File Created");

  delete fFile;

}

//_____________________________________________________________________________
AliAltroBuffer::AliAltroBuffer(const AliAltroBuffer& source):
  TObject(source),
  fShift(source.fShift),
  fCurrentCell(source.fCurrentCell),
  fFreeCellBuffer(source.fFreeCellBuffer),
  fVerbose(source.fVerbose),
  fFile(NULL),
  fDataHeaderPos(source.fDataHeaderPos),
  fMapping(source.fMapping)
{
// Copy Constructor

  Fatal("AliAltroBuffer", "copy constructor not implemented");
}

//_____________________________________________________________________________
AliAltroBuffer& AliAltroBuffer::operator = (const AliAltroBuffer& /*source*/)
{
//Assigment operator

  Fatal("operator =", "assignment operator not implemented");
  return *this;
}

//_____________________________________________________________________________
void AliAltroBuffer::Flush()
{
// Flushes the Buffer content
  if (fFreeCellBuffer != 16) {
    Int_t temp = fFreeCellBuffer;
    for (Int_t i = 0; i < temp; i++){
      FillBuffer(0x2AA);
    }//end for
  }//end if
}

//_____________________________________________________________________________
void AliAltroBuffer::FillBuffer(Int_t val)
{
//Fills the Buffer with 16 ten bits words and write into a file

  if ((val > 0x3FF) || (val < 0)) {
    Error("FillBuffer", "Value out of range (10 bits): %d", val);
    val = 0x3FF;
  }
  fFreeCellBuffer--;

  fBuffer[fCurrentCell] |= (val << fShift);
  fShift += 10;

  if (fShift > 32) {
    fCurrentCell++;
    fShift -= 32;
    fBuffer[fCurrentCell] |= (val >> (10 - fShift));
  }

  if (fShift == 32) {
    //Buffer is written into a file
    fFile->WriteBuffer((char*)fBuffer, sizeof(UInt_t)*5);
    //Buffer is empty
    for (Int_t j = 0; j < 5; j++) fBuffer[j] = 0;
    fShift = 0;
    fCurrentCell = 0;
    fFreeCellBuffer = 16;
  }
}

//_____________________________________________________________________________
void AliAltroBuffer::WriteDummyTrailer(Int_t wordsNumber, Int_t padNumber,
				       Int_t rowNumber, Int_t secNumber)
{
//Writes a trailer of 40 bits

   Int_t num = fFreeCellBuffer % 4;
   for(Int_t i = 0; i < num; i++) {
     FillBuffer(0x2AA);
   }//end for
   FillBuffer(wordsNumber);
   FillBuffer(padNumber);
   FillBuffer(rowNumber);
   FillBuffer(secNumber);
}

//_____________________________________________________________________________
void AliAltroBuffer::WriteTrailer(Int_t wordsNumber, Int_t padNumber,
				  Int_t rowNumber, Int_t secNumber)
{
//Writes a trailer of 40 bits

  if (!fMapping) {
    AliError("No ALTRO mapping information is loaded! Filling a dummy trailer!");
    return WriteDummyTrailer(wordsNumber,padNumber,
			     rowNumber,secNumber);
  }

  Short_t hwAddress = fMapping->GetHWAddress(rowNumber,padNumber,secNumber);
  if (hwAddress == -1)
    AliFatal(Form("No hardware (ALTRO) adress found for these pad-row (%d) and pad (%d) indeces !",rowNumber,padNumber));
  WriteTrailer(wordsNumber,hwAddress);
}

//_____________________________________________________________________________
void AliAltroBuffer::WriteTrailer(Int_t wordsNumber, Short_t hwAddress)
{
//Writes a trailer of 40 bits using
//a given hardware adress
  Int_t num = fFreeCellBuffer % 4;
  for(Int_t i = 0; i < num; i++) {
    FillBuffer(0x2AA);
  }//end for
  Int_t temp;
  temp = hwAddress & 0x3FF;
  FillBuffer(temp);

  temp = (wordsNumber << 6) & 0x3FF;
  temp |= (0xA << 2);
  temp |= ((hwAddress >> 10) & 0x3);
  FillBuffer(temp);

  temp = 0xA << 6;
  temp |= ((wordsNumber & 0x3FF) >> 4);
  FillBuffer(temp);

  temp = 0x2AA;
  FillBuffer(temp);
}

//_____________________________________________________________________________
void AliAltroBuffer::WriteChannel(Int_t padNumber, Int_t rowNumber,
				  Int_t secNumber,
				  Int_t nTimeBins, const Int_t* adcValues,
				  Int_t threshold)
{
  //Write all ADC values and the trailer of a channel
  Int_t nWords = WriteBunch(nTimeBins,adcValues,threshold);
  // write the trailer
  if (nWords) WriteTrailer(nWords, padNumber, rowNumber, secNumber);
}

//_____________________________________________________________________________
void AliAltroBuffer::WriteChannel(Short_t hwAddress,
				  Int_t nTimeBins, const Int_t* adcValues,
				  Int_t threshold)
{
  //Write all ADC values and the trailer of a channel
  Int_t nWords = WriteBunch(nTimeBins,adcValues,threshold);
  // write the trailer
  if (nWords) WriteTrailer(nWords, hwAddress);
}

//_____________________________________________________________________________
Int_t AliAltroBuffer::WriteBunch(Int_t nTimeBins, const Int_t* adcValues,
				 Int_t threshold)
{
  //Write all ADC values
  //Return number of words written

  Int_t nWords = 0;
  Int_t timeBin = -1;
  Int_t bunchLength = 0;

  // loop over time bins
  for (Int_t iTime = 0; iTime < nTimeBins; iTime++) {
    if (adcValues[iTime] >= threshold) { // ADC value above threshold
      FillBuffer(adcValues[iTime]);
      nWords++;
      timeBin = iTime;
      bunchLength++;

    } else if (timeBin >= 0) {  // end of bunch
      FillBuffer(timeBin);
      FillBuffer(bunchLength + 2);
      nWords += 2;
      timeBin = -1;
      bunchLength = 0;
    }
  }

  if (timeBin >= 0) {  // end of bunch
    FillBuffer(timeBin);
    FillBuffer(bunchLength + 2);
    nWords += 2;
  }

  return nWords;
}

//_____________________________________________________________________________
void AliAltroBuffer::WriteDataHeader(Bool_t dummy, Bool_t compressed)
{
//Write a (dummy or real) DDL data header,
//set the compression bit if compressed

  AliRawDataHeaderSim header;
  if (dummy) {
    //if size=0 it means that this data header is a dummy data header
    fDataHeaderPos = fFile->Tellp();
    fFile->WriteBuffer((char*)(&header), sizeof(header));
  } else {
    WriteRCUTrailer(0);
    UInt_t currentFilePos = fFile->Tellp();
    fFile->Seekp(fDataHeaderPos);
    header.fSize = currentFilePos-fDataHeaderPos;
    header.SetAttribute(0);  // valid data
    if (compressed) header.SetAttribute(1);
    fFile->WriteBuffer((char*)(&header), sizeof(header));
    fFile->Seekp(currentFilePos);
  }
}

//_____________________________________________________________________________
void AliAltroBuffer::WriteRCUTrailer(Int_t rcuId)
{
  // Writes the RCU trailer
  // rcuId the is serial number of the corresponding
  // RCU. The basic format of the trailer can be
  // found in the RCU manual.
  // This method should be called at the end of
  // raw data writing.

  UInt_t currentFilePos = fFile->Tellp();
  UInt_t size = currentFilePos-fDataHeaderPos;
  size -= sizeof(AliRawDataHeader);

  if ((size % 5) != 0) {
    AliFatal(Form("The current raw data payload is not a mutiple of 5 (%d) ! Can not write the RCU trailer !",size));
    return;
  }

  // Now put the size in unit of number of 40bit words
  size /= 5;
  fFile->WriteBuffer((char *)(&size),sizeof(UInt_t));

  // Now several not yet full defined fields
  // In principle they are supposed to contain
  // information about the sampling frequency,
  // L1 phase, list of 'dead' FECs, etc.
  //  UInt_t buffer[n];
  //  fFile->WriteBuffer((char *)(buffer),sizeof(UInt_t)*n);

  //  Now the RCU identifier and size of the trailer
  //  FOr the moment the triler size is 2 32-bit words
  UInt_t buffer = (2 & 0x7F);
  buffer |= ((rcuId & 0x1FF) << 7);
  buffer |= 0xAAAA << 16;
  fFile->WriteBuffer((char *)(&buffer),sizeof(UInt_t));

}
<commit_msg>RCU can't write raw-data size so one gets always 0xffffffff in the CDH event-size field<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

// Interface to the Altro format
// to read and write digits
// To be used in Alice Data Challenges
// and in the compression of the RAW data

#include "AliAltroBuffer.h"
#include "AliAltroMapping.h"
#include "AliRawDataHeaderSim.h"
#include "AliLog.h"
#include "AliFstream.h"
//#include <stdlib.h>

ClassImp(AliAltroBuffer)

//_____________________________________________________________________________
AliAltroBuffer::AliAltroBuffer(const char* fileName, AliAltroMapping *mapping):
  fShift(0),
  fCurrentCell(0),
  fFreeCellBuffer(16),
  fVerbose(0),
  fFile(NULL),
  fDataHeaderPos(0),
  fMapping(mapping)
{
  //the buffer is cleaned
  for (Int_t i = 0; i < 5; i++) fBuffer[i] = 0;

  //open the output file
  fFile = new AliFstream(fileName);

}

//_____________________________________________________________________________
AliAltroBuffer::~AliAltroBuffer()
{
// destructor

  //Flush out the Buffer content at the end only if Buffer wasn't completely filled
  Flush();
  if (fVerbose) Info("~AliAltroBuffer", "File Created");

  delete fFile;

}

//_____________________________________________________________________________
AliAltroBuffer::AliAltroBuffer(const AliAltroBuffer& source):
  TObject(source),
  fShift(source.fShift),
  fCurrentCell(source.fCurrentCell),
  fFreeCellBuffer(source.fFreeCellBuffer),
  fVerbose(source.fVerbose),
  fFile(NULL),
  fDataHeaderPos(source.fDataHeaderPos),
  fMapping(source.fMapping)
{
// Copy Constructor

  Fatal("AliAltroBuffer", "copy constructor not implemented");
}

//_____________________________________________________________________________
AliAltroBuffer& AliAltroBuffer::operator = (const AliAltroBuffer& /*source*/)
{
//Assigment operator

  Fatal("operator =", "assignment operator not implemented");
  return *this;
}

//_____________________________________________________________________________
void AliAltroBuffer::Flush()
{
// Flushes the Buffer content
  if (fFreeCellBuffer != 16) {
    Int_t temp = fFreeCellBuffer;
    for (Int_t i = 0; i < temp; i++){
      FillBuffer(0x2AA);
    }//end for
  }//end if
}

//_____________________________________________________________________________
void AliAltroBuffer::FillBuffer(Int_t val)
{
//Fills the Buffer with 16 ten bits words and write into a file

  if ((val > 0x3FF) || (val < 0)) {
    Error("FillBuffer", "Value out of range (10 bits): %d", val);
    val = 0x3FF;
  }
  fFreeCellBuffer--;

  fBuffer[fCurrentCell] |= (val << fShift);
  fShift += 10;

  if (fShift > 32) {
    fCurrentCell++;
    fShift -= 32;
    fBuffer[fCurrentCell] |= (val >> (10 - fShift));
  }

  if (fShift == 32) {
    //Buffer is written into a file
    fFile->WriteBuffer((char*)fBuffer, sizeof(UInt_t)*5);
    //Buffer is empty
    for (Int_t j = 0; j < 5; j++) fBuffer[j] = 0;
    fShift = 0;
    fCurrentCell = 0;
    fFreeCellBuffer = 16;
  }
}

//_____________________________________________________________________________
void AliAltroBuffer::WriteDummyTrailer(Int_t wordsNumber, Int_t padNumber,
				       Int_t rowNumber, Int_t secNumber)
{
//Writes a trailer of 40 bits

   Int_t num = fFreeCellBuffer % 4;
   for(Int_t i = 0; i < num; i++) {
     FillBuffer(0x2AA);
   }//end for
   FillBuffer(wordsNumber);
   FillBuffer(padNumber);
   FillBuffer(rowNumber);
   FillBuffer(secNumber);
}

//_____________________________________________________________________________
void AliAltroBuffer::WriteTrailer(Int_t wordsNumber, Int_t padNumber,
				  Int_t rowNumber, Int_t secNumber)
{
//Writes a trailer of 40 bits

  if (!fMapping) {
    AliError("No ALTRO mapping information is loaded! Filling a dummy trailer!");
    return WriteDummyTrailer(wordsNumber,padNumber,
			     rowNumber,secNumber);
  }

  Short_t hwAddress = fMapping->GetHWAddress(rowNumber,padNumber,secNumber);
  if (hwAddress == -1)
    AliFatal(Form("No hardware (ALTRO) adress found for these pad-row (%d) and pad (%d) indeces !",rowNumber,padNumber));
  WriteTrailer(wordsNumber,hwAddress);
}

//_____________________________________________________________________________
void AliAltroBuffer::WriteTrailer(Int_t wordsNumber, Short_t hwAddress)
{
//Writes a trailer of 40 bits using
//a given hardware adress
  Int_t num = fFreeCellBuffer % 4;
  for(Int_t i = 0; i < num; i++) {
    FillBuffer(0x2AA);
  }//end for
  Int_t temp;
  temp = hwAddress & 0x3FF;
  FillBuffer(temp);

  temp = (wordsNumber << 6) & 0x3FF;
  temp |= (0xA << 2);
  temp |= ((hwAddress >> 10) & 0x3);
  FillBuffer(temp);

  temp = 0xA << 6;
  temp |= ((wordsNumber & 0x3FF) >> 4);
  FillBuffer(temp);

  temp = 0x2AA;
  FillBuffer(temp);
}

//_____________________________________________________________________________
void AliAltroBuffer::WriteChannel(Int_t padNumber, Int_t rowNumber,
				  Int_t secNumber,
				  Int_t nTimeBins, const Int_t* adcValues,
				  Int_t threshold)
{
  //Write all ADC values and the trailer of a channel
  Int_t nWords = WriteBunch(nTimeBins,adcValues,threshold);
  // write the trailer
  if (nWords) WriteTrailer(nWords, padNumber, rowNumber, secNumber);
}

//_____________________________________________________________________________
void AliAltroBuffer::WriteChannel(Short_t hwAddress,
				  Int_t nTimeBins, const Int_t* adcValues,
				  Int_t threshold)
{
  //Write all ADC values and the trailer of a channel
  Int_t nWords = WriteBunch(nTimeBins,adcValues,threshold);
  // write the trailer
  if (nWords) WriteTrailer(nWords, hwAddress);
}

//_____________________________________________________________________________
Int_t AliAltroBuffer::WriteBunch(Int_t nTimeBins, const Int_t* adcValues,
				 Int_t threshold)
{
  //Write all ADC values
  //Return number of words written

  Int_t nWords = 0;
  Int_t timeBin = -1;
  Int_t bunchLength = 0;

  // loop over time bins
  for (Int_t iTime = 0; iTime < nTimeBins; iTime++) {
    if (adcValues[iTime] >= threshold) { // ADC value above threshold
      FillBuffer(adcValues[iTime]);
      nWords++;
      timeBin = iTime;
      bunchLength++;

    } else if (timeBin >= 0) {  // end of bunch
      FillBuffer(timeBin);
      FillBuffer(bunchLength + 2);
      nWords += 2;
      timeBin = -1;
      bunchLength = 0;
    }
  }

  if (timeBin >= 0) {  // end of bunch
    FillBuffer(timeBin);
    FillBuffer(bunchLength + 2);
    nWords += 2;
  }

  return nWords;
}

//_____________________________________________________________________________
void AliAltroBuffer::WriteDataHeader(Bool_t dummy, Bool_t compressed)
{
//Write a (dummy or real) DDL data header,
//set the compression bit if compressed

  AliRawDataHeaderSim header;
  if (dummy) {
    //if size=0 it means that this data header is a dummy data header
    fDataHeaderPos = fFile->Tellp();
    fFile->WriteBuffer((char*)(&header), sizeof(header));
  } else {
    WriteRCUTrailer(0);
    UInt_t currentFilePos = fFile->Tellp();
    fFile->Seekp(fDataHeaderPos);
    header.fSize = 0xFFFFFFFF; // RCU can't write raw-data size so we always get an 'invalid' size field
    //    header.fSize = currentFilePos-fDataHeaderPos;
    header.SetAttribute(0);  // valid data
    if (compressed) header.SetAttribute(1);
    fFile->WriteBuffer((char*)(&header), sizeof(header));
    fFile->Seekp(currentFilePos);
  }
}

//_____________________________________________________________________________
void AliAltroBuffer::WriteRCUTrailer(Int_t rcuId)
{
  // Writes the RCU trailer
  // rcuId the is serial number of the corresponding
  // RCU. The basic format of the trailer can be
  // found in the RCU manual.
  // This method should be called at the end of
  // raw data writing.

  UInt_t currentFilePos = fFile->Tellp();
  UInt_t size = currentFilePos-fDataHeaderPos;
  size -= sizeof(AliRawDataHeader);

  if ((size % 5) != 0) {
    AliFatal(Form("The current raw data payload is not a mutiple of 5 (%d) ! Can not write the RCU trailer !",size));
    return;
  }

  // Now put the size in unit of number of 40bit words
  size /= 5;
  fFile->WriteBuffer((char *)(&size),sizeof(UInt_t));

  // Now several not yet full defined fields
  // In principle they are supposed to contain
  // information about the sampling frequency,
  // L1 phase, list of 'dead' FECs, etc.
  //  UInt_t buffer[n];
  //  fFile->WriteBuffer((char *)(buffer),sizeof(UInt_t)*n);

  //  Now the RCU identifier and size of the trailer
  //  FOr the moment the triler size is 2 32-bit words
  UInt_t buffer = (2 & 0x7F);
  buffer |= ((rcuId & 0x1FF) << 7);
  buffer |= 0xAAAA << 16;
  fFile->WriteBuffer((char *)(&buffer),sizeof(UInt_t));

}
<|endoftext|>


<commit_before>#include "ScaledImageFactory.h"

#include <memory>

#include "LinearImage.h"

using namespace std;

SrgbImagePtr GetScaledSubrect( const LinearImage& src, auto_ptr< Resampler > resamplers[ 4 ], const wxRect& rect )
{
    LinearImage dst
        (
        rect.GetWidth(),
        rect.GetHeight(),
        NULL,
        ( src.GetNumChannels() == 4 ? (unsigned char*)1 : NULL )
        );

    for( size_t c = 0; c < src.GetNumChannels(); ++c )
    {
        resamplers[ c ]->StartResample
            (
            rect.x, rect.y,
            rect.GetWidth(), rect.GetHeight()
            );
    }

    size_t dstY = 0;
    for( size_t y = 0; y < src.GetHeight(); ++y )
    {
        for( size_t c = 0; c < src.GetNumChannels(); ++c )
        {
            resamplers[ c ]->PutLine( src.GetRow( c, y ) );
        }

        while( true )
        {
            bool missedLine = false;
            for( size_t c = 0; c < src.GetNumChannels(); ++c )
            {
                const float* line = resamplers[ c ]->GetLine();
                if( NULL == line )
                {
                    missedLine = true;
                    break;
                }

                copy( line, line + dst.GetWidth(), dst.GetRow( c, dstY ) );
            }

            if( missedLine )
            {
                break;
            }

            dstY++;
        }
    }

    SrgbImagePtr ret( new SrgbImage );
    dst.GetSrgb( ret->mColor, ret->mAlpha );
    return ret;
}

class WorkerThread : public wxThread
{
public:
    WorkerThread
        (
        wxEvtHandler* eventSink,
        int id,
        ScaledImageFactory::JobQueueType& mJobQueue,
        ScaledImageFactory::ResultQueueType& mResultQueue
        )
        : wxThread( wxTHREAD_JOINABLE )
        , mEventSink( eventSink ), mEventId( id ), mJobQueue( mJobQueue ), mResultQueue( mResultQueue )
    { }

    virtual ExitCode Entry()
    {
        wxSharedPtr< Resampler::ContribLists > curContribLists;
        auto_ptr< Resampler > resamplers[ 4 ];

        ScaledImageFactory::JobItem job;
        while( wxMSGQUEUE_NO_ERROR == mJobQueue.Receive( job ) )
        {
            if( NULL == job.second.mImage || TestDestroy() )
                break;

            const wxRect& rect = job.first;
            ScaledImageFactory::Context& ctx = job.second;

            if( curContribLists != ctx.mContribLists )
            {
                curContribLists = ctx.mContribLists;
                for( size_t i = 0; i < 4; ++i )
                {
                    resamplers[ i ].reset( new Resampler( *curContribLists ) );
                }
            }

            ScaledImageFactory::ResultItem result;
            result.mGeneration = ctx.mGeneration;
            result.mRect = rect;
            result.mImage = GetScaledSubrect
                (
                *ctx.mImage,
                resamplers,
                rect
                );
            mResultQueue.Post( result );

            wxQueueEvent( mEventSink, new wxThreadEvent( wxEVT_THREAD, mEventId ) );
        }

        return static_cast< wxThread::ExitCode >( 0 );
    }

private:
    wxEvtHandler* mEventSink;
    int mEventId;
    ScaledImageFactory::JobQueueType& mJobQueue;
    ScaledImageFactory::ResultQueueType& mResultQueue;
};

ScaledImageFactory::ScaledImageFactory( wxEvtHandler* eventSink, int id )
    : mEventSink( eventSink )
    , mEventId( id )
{
    size_t numThreads = wxThread::GetCPUCount();
    if( numThreads <= 0 )   numThreads = 1;
    if( numThreads > 1 )    numThreads--;

    for( size_t i = 0; i < numThreads; ++i )
    {
        mThreads.push_back( new WorkerThread( eventSink, id, mJobQueue, mResultQueue ) );
    }

    for( wxThread*& thread : mThreads )
    {
        if( NULL == thread )
            continue;

        if( thread->Run() != wxTHREAD_NO_ERROR )
        {
            delete thread;
            thread = NULL;
        }
    }

    mCurrentCtx.mGeneration = 0;
}

ScaledImageFactory::~ScaledImageFactory()
{
    // clear job queue and send down "kill" jobs
    mJobQueue.Clear();
    for( size_t i = 0; i < mThreads.size(); ++i )
    {
        mJobQueue.Post( JobItem( wxRect(), Context() ) );
    }

    for( wxThread* thread : mThreads )
    {
        if( NULL == thread )
            continue;

        thread->Wait();
        delete thread;
    }
}

void ScaledImageFactory::SetImage( LinearImagePtr& newImage, double scale )
{
    mCurrentCtx.mGeneration++;
    mJobQueue.Clear();
    mCurrentCtx.mImage = newImage;
    SetScale( scale );
}

void ScaledImageFactory::SetScale( double newScale )
{
    if( NULL == mCurrentCtx.mImage )
        throw std::runtime_error( "Image not set!" );

    mCurrentCtx.mGeneration++;
    mJobQueue.Clear();

    // regenerate contrib lists
    mCurrentCtx.mContribLists = new Resampler::ContribLists
        (
        mCurrentCtx.mImage->GetWidth(),
        mCurrentCtx.mImage->GetHeight(),
        mCurrentCtx.mImage->GetWidth() * newScale,
        mCurrentCtx.mImage->GetHeight() * newScale
        );
}

bool ScaledImageFactory::AddRect( const wxRect& rect )
{
    if( NULL == mCurrentCtx.mImage )
        throw std::runtime_error( "Image not set!" );

    wxMessageQueueError err;
    err = mJobQueue.Post( JobItem( rect, mCurrentCtx ) );
    return( wxMSGQUEUE_NO_ERROR == err );
}

bool ScaledImageFactory::GetImage( wxRect& rect, SrgbImagePtr& image )
{
    ResultItem item;
    wxMessageQueueError err;
    while( true )
    {
        err = mResultQueue.ReceiveTimeout( 0, item );
        if( wxMSGQUEUE_TIMEOUT == err )
            return false;
        if( wxMSGQUEUE_MISC_ERROR == err )
            throw std::runtime_error( "ResultQueue misc error!" );
        if( item.mGeneration != mCurrentCtx.mGeneration )
            continue;
        break;
    }

    rect = item.mRect;
    image = item.mImage;
    return true;
}<commit_msg>Simplify ScaledImageFactory::AddRect()<commit_after>#include "ScaledImageFactory.h"

#include <memory>

#include "LinearImage.h"

using namespace std;

SrgbImagePtr GetScaledSubrect( const LinearImage& src, auto_ptr< Resampler > resamplers[ 4 ], const wxRect& rect )
{
    LinearImage dst
        (
        rect.GetWidth(),
        rect.GetHeight(),
        NULL,
        ( src.GetNumChannels() == 4 ? (unsigned char*)1 : NULL )
        );

    for( size_t c = 0; c < src.GetNumChannels(); ++c )
    {
        resamplers[ c ]->StartResample
            (
            rect.x, rect.y,
            rect.GetWidth(), rect.GetHeight()
            );
    }

    size_t dstY = 0;
    for( size_t y = 0; y < src.GetHeight(); ++y )
    {
        for( size_t c = 0; c < src.GetNumChannels(); ++c )
        {
            resamplers[ c ]->PutLine( src.GetRow( c, y ) );
        }

        while( true )
        {
            bool missedLine = false;
            for( size_t c = 0; c < src.GetNumChannels(); ++c )
            {
                const float* line = resamplers[ c ]->GetLine();
                if( NULL == line )
                {
                    missedLine = true;
                    break;
                }

                copy( line, line + dst.GetWidth(), dst.GetRow( c, dstY ) );
            }

            if( missedLine )
            {
                break;
            }

            dstY++;
        }
    }

    SrgbImagePtr ret( new SrgbImage );
    dst.GetSrgb( ret->mColor, ret->mAlpha );
    return ret;
}

class WorkerThread : public wxThread
{
public:
    WorkerThread
        (
        wxEvtHandler* eventSink,
        int id,
        ScaledImageFactory::JobQueueType& mJobQueue,
        ScaledImageFactory::ResultQueueType& mResultQueue
        )
        : wxThread( wxTHREAD_JOINABLE )
        , mEventSink( eventSink ), mEventId( id ), mJobQueue( mJobQueue ), mResultQueue( mResultQueue )
    { }

    virtual ExitCode Entry()
    {
        wxSharedPtr< Resampler::ContribLists > curContribLists;
        auto_ptr< Resampler > resamplers[ 4 ];

        ScaledImageFactory::JobItem job;
        while( wxMSGQUEUE_NO_ERROR == mJobQueue.Receive( job ) )
        {
            if( NULL == job.second.mImage || TestDestroy() )
                break;

            const wxRect& rect = job.first;
            ScaledImageFactory::Context& ctx = job.second;

            if( curContribLists != ctx.mContribLists )
            {
                curContribLists = ctx.mContribLists;
                for( size_t i = 0; i < 4; ++i )
                {
                    resamplers[ i ].reset( new Resampler( *curContribLists ) );
                }
            }

            ScaledImageFactory::ResultItem result;
            result.mGeneration = ctx.mGeneration;
            result.mRect = rect;
            result.mImage = GetScaledSubrect
                (
                *ctx.mImage,
                resamplers,
                rect
                );
            mResultQueue.Post( result );

            wxQueueEvent( mEventSink, new wxThreadEvent( wxEVT_THREAD, mEventId ) );
        }

        return static_cast< wxThread::ExitCode >( 0 );
    }

private:
    wxEvtHandler* mEventSink;
    int mEventId;
    ScaledImageFactory::JobQueueType& mJobQueue;
    ScaledImageFactory::ResultQueueType& mResultQueue;
};

ScaledImageFactory::ScaledImageFactory( wxEvtHandler* eventSink, int id )
    : mEventSink( eventSink )
    , mEventId( id )
{
    size_t numThreads = wxThread::GetCPUCount();
    if( numThreads <= 0 )   numThreads = 1;
    if( numThreads > 1 )    numThreads--;

    for( size_t i = 0; i < numThreads; ++i )
    {
        mThreads.push_back( new WorkerThread( eventSink, id, mJobQueue, mResultQueue ) );
    }

    for( wxThread*& thread : mThreads )
    {
        if( NULL == thread )
            continue;

        if( thread->Run() != wxTHREAD_NO_ERROR )
        {
            delete thread;
            thread = NULL;
        }
    }

    mCurrentCtx.mGeneration = 0;
}

ScaledImageFactory::~ScaledImageFactory()
{
    // clear job queue and send down "kill" jobs
    mJobQueue.Clear();
    for( size_t i = 0; i < mThreads.size(); ++i )
    {
        mJobQueue.Post( JobItem( wxRect(), Context() ) );
    }

    for( wxThread* thread : mThreads )
    {
        if( NULL == thread )
            continue;

        thread->Wait();
        delete thread;
    }
}

void ScaledImageFactory::SetImage( LinearImagePtr& newImage, double scale )
{
    mCurrentCtx.mGeneration++;
    mJobQueue.Clear();
    mCurrentCtx.mImage = newImage;
    SetScale( scale );
}

void ScaledImageFactory::SetScale( double newScale )
{
    if( NULL == mCurrentCtx.mImage )
        throw std::runtime_error( "Image not set!" );

    mCurrentCtx.mGeneration++;
    mJobQueue.Clear();

    // regenerate contrib lists
    mCurrentCtx.mContribLists = new Resampler::ContribLists
        (
        mCurrentCtx.mImage->GetWidth(),
        mCurrentCtx.mImage->GetHeight(),
        mCurrentCtx.mImage->GetWidth() * newScale,
        mCurrentCtx.mImage->GetHeight() * newScale
        );
}

bool ScaledImageFactory::AddRect( const wxRect& rect )
{
    if( NULL == mCurrentCtx.mImage )
        throw std::runtime_error( "Image not set!" );

    return( wxMSGQUEUE_NO_ERROR == mJobQueue.Post( JobItem( rect, mCurrentCtx ) ) );
}

bool ScaledImageFactory::GetImage( wxRect& rect, SrgbImagePtr& image )
{
    ResultItem item;
    wxMessageQueueError err;
    while( true )
    {
        err = mResultQueue.ReceiveTimeout( 0, item );
        if( wxMSGQUEUE_TIMEOUT == err )
            return false;
        if( wxMSGQUEUE_MISC_ERROR == err )
            throw std::runtime_error( "ResultQueue misc error!" );
        if( item.mGeneration != mCurrentCtx.mGeneration )
            continue;
        break;
    }

    rect = item.mRect;
    image = item.mImage;
    return true;
}
<|endoftext|>


<commit_before>/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can
 *  be found in the License.html file in the root of the source tree.
 */

#include <QApplication>
#include <QtGlobal>
#include <QtPlugin>
#include <iostream>
#include "mainwindow.h"

#include <ZenLib/Ztring.h>
#include <ZenLib/ZtringListList.h>

using namespace ZenLib;
#define wstring2QString(_DATA) \
    QString::fromUtf8(Ztring(_DATA).To_UTF8().c_str())
#define QString2wstring(_DATA) \
    Ztring().From_UTF8(_DATA.toUtf8())

using namespace std;

int main(int argc, char *argv[])
{
    QStringList filesnames;
    int output = -1;
#if defined(_WIN32) && defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_APP) //UWP Application
    QApplication::setAttribute(Qt::AA_ImmediateWidgetCreation, true);
    QApplication a(argc, argv);
#else
    QApplication a(argc, argv);
    QStringList args = QCoreApplication::arguments();

    // Strip program path from arguments
    if (args.size() && args.at(0)==QCoreApplication::applicationFilePath())
        args.removeFirst();

    foreach(QString arg,args) {
        if(!arg.compare("--help",Qt::CaseInsensitive)||!arg.compare("-h",Qt::CaseInsensitive)) {
            cout << "Usage : mediainfo-gui [OPTIONS] [files]" << endl;
            cout << "Options : " << endl;
            cout << "-h,--help : show this help" << endl;
            cout << "--output=OUTPUT : select the view OUTPUT at launch" << endl;
            cout << "--version : show the version" << endl;
            return 0;
        } else if(!arg.compare("--version",Qt::CaseInsensitive)) {
            Core C;
            C.Menu_Help_Version();
            cout << wstring2QString(C.Text_Get()).toStdString() << endl;
            return 0;
        } else if(arg.startsWith("--output=",Qt::CaseInsensitive)) {
            arg.remove(0,9);
            int i=0;
            while(i<NB_VIEW) {
                if(arg.compare(nameView(ViewMode(i)),Qt::CaseInsensitive)==0) {
                    cout << arg.toStdString() << "view selected" << endl;
                    output=i;
                    break;
                }
                i++;
            }
            if(i<0) {
                cout << arg.toStdString() << " : unkown view" << endl;
            }
        } else {
            filesnames.append(arg);
        }
    }
#endif
    MainWindow w(filesnames,output);

    w.show();
    return a.exec();
}
<commit_msg>Use QCommandLineParser in Qt GUI<commit_after>/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can
 *  be found in the License.html file in the root of the source tree.
 */

#include <QApplication>
#include <QCommandLineParser>
#include <QtGlobal>
#include <QtPlugin>
#include <iostream>
#include "mainwindow.h"

#include <ZenLib/Ztring.h>
#include <ZenLib/ZtringListList.h>

#include "Common/Preferences.h"

using namespace ZenLib;
using namespace std;

int main(int argc, char *argv[])
{
    QStringList filesnames;
    int output = -1;

    QCoreApplication::setApplicationName("mediainfo-gui");
    QCoreApplication::setApplicationVersion(QString().fromStdString(Ztring(MediaInfo_Version_GUI).To_UTF8()));

#if defined(_WIN32) && defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_APP) //UWP Application
    QApplication::setAttribute(Qt::AA_ImmediateWidgetCreation, true);
    QApplication a(argc, argv);
#else
    QApplication a(argc, argv);
    QCommandLineParser parser;

    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("files", "Files to analyze.");

    QCommandLineOption outputOption(QStringList() << "o" << "output", "select the view OUTPUT at launch.", "OUTPUT");
    parser.addOption(outputOption);

    parser.process(a);

    if(!parser.value(outputOption).isEmpty())
    {
        int i=0;
        while(i<NB_VIEW)
        {
            if(parser.value(outputOption).compare(nameView(ViewMode(i)), Qt::CaseInsensitive)==0)
            {
                cout << parser.value(outputOption).toStdString() << " view selected" << endl;
                output=i;
                break;
            }
            i++;
        }
        if(i>=NB_VIEW) {
            cout << "Unknown view: " << parser.value(outputOption).toStdString() << endl;
        }
    }

    filesnames = parser.positionalArguments();
#endif
    MainWindow w(filesnames,output);

    w.show();
    return a.exec();
}
<|endoftext|>


<commit_before>
// ---------------------------------------------------
// The FDiffDelete Project
// Github: https://github.com/shishir993/fdiffdelete
// Author: Shishir Bhat
// The MIT License (MIT)
// Copyright (c) 2014
//

#include "HashFactory.h"
#include <WinCrypt.h>

HRESULT HashFactoryInit(_Out_ HCRYPTPROV *phCrypt)
{
    HRESULT hr = S_OK;

    *phCrypt = NULL;

    HCRYPTPROV hCrypt = NULL;
    if (CryptAcquireContext(
        &hCrypt,// handle out
        NULL,   // container
        NULL,   // provider
        PROV_DSS,           // provider type
        CRYPT_VERIFYCONTEXT))   // flags
    {
        *phCrypt = hCrypt;
    }
    else
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        logerr(L"CryptAcquireContext() failed.");
    }
    return hr;
}

void HashFactoryDestroy(_In_ HCRYPTPROV hCrypt)
{
    SB_ASSERT(hCrypt != NULL);
    CryptReleaseContext(hCrypt, 0);
}

HRESULT CalculateSHA1(_In_ HCRYPTPROV hCrypt, _In_ HANDLE hFile, _Out_bytecap_c_(HASHLEN_SHA1) PBYTE pbHash)
{
    SB_ASSERT(hCrypt != NULL);

    HRESULT hr = S_OK;
    HCRYPTHASH hHash = NULL;
    HANDLE hMapObj = NULL;
    HANDLE hMapView = NULL;
    DWORD dwHashSize = HASHLEN_SHA1;
    LARGE_INTEGER fileSize = {};

    if (!CryptCreateHash(hCrypt, CALG_SHA1, NULL, 0, &hHash))
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        logerr(L"CryptCreateHash() failed");
        goto fend;
    }

    hr = CHL_GnCreateMemMapOfFile(hFile, PAGE_READONLY, &hMapObj, &hMapView);
    if (FAILED(hr))
    {
        logerr(L"Failed to mem-map file, hr: %x", hr);
        goto fend;
    }

    if (!GetFileSizeEx(hFile, &fileSize))
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        logerr(L"GetFileSizeEx failed, hr: %x", hr);
        goto fend;
    }
    if (MAXDWORD < fileSize.QuadPart)
    {
        hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
        logerr(L"File too big");
        goto fend;
    }

    if (!CryptHashData(hHash, (PBYTE)hMapView, fileSize.LowPart, 0))
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        logerr(L"CryptHashData failed, hr: %x", hr);
        goto fend;
    }

    if (!CryptGetHashParam(hHash, HP_HASHVAL, pbHash, &dwHashSize, 0))
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        logerr(L"CryptGetHashParam failed, hr: %x", hr);
        goto fend;
    }

#ifdef _DEBUG
    CHAR szHash[STRLEN_SHA1];
    HashValueToString(pbHash, szHash);
    logdbg(L"Hash string = [%S]", szHash);
#endif

fend:
    if (hHash != NULL)
    {
        CryptDestroyHash(hHash);
        hHash = NULL;
    }

    if (hMapView != NULL)
    {
        UnmapViewOfFile(hMapView);
        hMapView = NULL;
    }

    if (hMapObj != NULL)
    {
        CloseHandle(hMapObj);
        hMapObj = NULL;
    }

    return hr;
}

void HashValueToString(_In_bytecount_c_(HASHLEN_SHA1) PBYTE pbHash, _Inout_z_ PSTR pszHashValue)
{
    for (int i = 0; i < HASHLEN_SHA1; ++i)
    {
        sprintf_s(pszHashValue + (i << 1), STRLEN_SHA1 - (i << 1), "%02x", pbHash[i]);
    }
    pszHashValue[STRLEN_SHA1 - 1] = 0;
}
<commit_msg>Move full file hash code into separate function<commit_after>
// ---------------------------------------------------
// The FDiffDelete Project
// Github: https://github.com/shishir993/fdiffdelete
// Author: Shishir Bhat
// The MIT License (MIT)
// Copyright (c) 2014
//

#include "HashFactory.h"
#include <WinCrypt.h>

#define MBYTES  (1024 * 1024)

static HRESULT _HashFileOneShot(_In_ HCRYPTPROV hCrypt, _In_ HANDLE hFile, _In_ DWORD cbFile, _Out_bytecap_c_(HASHLEN_SHA1) PBYTE pbHash);
static HRESULT _HashFilePieceMeal(_In_ HCRYPTPROV hCrypt, _In_ HANDLE hFile, _In_ INT64 cbFile, _Out_bytecap_c_(HASHLEN_SHA1) PBYTE pbHash);

HRESULT HashFactoryInit(_Out_ HCRYPTPROV *phCrypt)
{
    HRESULT hr = S_OK;

    *phCrypt = NULL;

    HCRYPTPROV hCrypt = NULL;
    if (CryptAcquireContext(
        &hCrypt,// handle out
        NULL,   // container
        NULL,   // provider
        PROV_DSS,           // provider type
        CRYPT_VERIFYCONTEXT))   // flags
    {
        *phCrypt = hCrypt;
    }
    else
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        logerr(L"CryptAcquireContext() failed.");
    }
    return hr;
}

void HashFactoryDestroy(_In_ HCRYPTPROV hCrypt)
{
    SB_ASSERT(hCrypt != NULL);
    CryptReleaseContext(hCrypt, 0);
}

HRESULT CalculateSHA1(_In_ HCRYPTPROV hCrypt, _In_ HANDLE hFile, _Out_bytecap_c_(HASHLEN_SHA1) PBYTE pbHash)
{
    SB_ASSERT(hCrypt != NULL);

    HRESULT hr = S_OK;
    LARGE_INTEGER fileSize = {};

    if (!GetFileSizeEx(hFile, &fileSize))
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        logerr(L"GetFileSizeEx failed, hr: %x", hr);
        goto fend;
    }

    if ((200 * MBYTES) <= fileSize.QuadPart)
    {
        hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
        logerr(L"File too big");
        goto fend;
    }

    hr = _HashFileOneShot(hCrypt, hFile, fileSize.LowPart, pbHash);

#ifdef _DEBUG
    CHAR szHash[STRLEN_SHA1];
    HashValueToString(pbHash, szHash);
    logdbg(L"Hash string = [%S]", szHash);
#endif

fend:
    return hr;
}

void HashValueToString(_In_bytecount_c_(HASHLEN_SHA1) PBYTE pbHash, _Inout_z_ PSTR pszHashValue)
{
    for (int i = 0; i < HASHLEN_SHA1; ++i)
    {
        sprintf_s(pszHashValue + (i << 1), STRLEN_SHA1 - (i << 1), "%02x", pbHash[i]);
    }
    pszHashValue[STRLEN_SHA1 - 1] = 0;
}

HRESULT _HashFileOneShot(_In_ HCRYPTPROV hCrypt, _In_ HANDLE hFile, _In_ DWORD cbFile, _Out_bytecap_c_(HASHLEN_SHA1) PBYTE pbHash)
{
    HRESULT hr = S_OK;
    HCRYPTHASH hHash = NULL;
    HANDLE hMapObj = NULL;
    HANDLE hMapView = NULL;
    DWORD dwHashSize = HASHLEN_SHA1;

    hr = CHL_GnCreateMemMapOfFile(hFile, PAGE_READONLY, &hMapObj, &hMapView);
    if (FAILED(hr))
    {
        logerr(L"Failed to mem-map file, hr: %x", hr);
        goto fend;
    }

    if (!CryptCreateHash(hCrypt, CALG_SHA1, NULL, 0, &hHash))
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        logerr(L"CryptCreateHash() failed");
        goto fend;
    }

    if (!CryptHashData(hHash, (PBYTE)hMapView, cbFile, 0))
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        logerr(L"CryptHashData failed, hr: %x", hr);
        goto fend;
    }

    if (!CryptGetHashParam(hHash, HP_HASHVAL, pbHash, &dwHashSize, 0))
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        logerr(L"CryptGetHashParam failed, hr: %x", hr);
        goto fend;
    }

fend:
    if (hHash != NULL)
    {
        CryptDestroyHash(hHash);
        hHash = NULL;
    }

    if (hMapView != NULL)
    {
        UnmapViewOfFile(hMapView);
        hMapView = NULL;
    }

    if (hMapObj != NULL)
    {
        CloseHandle(hMapObj);
        hMapObj = NULL;
    }

    return hr;
}

HRESULT _HashFilePieceMeal(_In_ HCRYPTPROV hCrypt, _In_ HANDLE hFile, _In_ INT64 cbFile, _Out_bytecap_c_(HASHLEN_SHA1) PBYTE pbHash)
{
    return E_NOTIMPL;
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <stan/agrad/fwd.hpp>
#include <boost/math/special_functions/digamma.hpp>
#include <stan/math/functions/binomial_coefficient_log.hpp>
#include <stan/agrad/rev.hpp>
#include <test/unit/agrad/util.hpp>

TEST(AgradFwdBinomialCoefficientLog,Fvar) {
  using stan::agrad::fvar;
  using stan::math::binomial_coefficient_log;
  using boost::math::digamma;

  fvar<double> x(2004.0,1.0);
  fvar<double> y(1002.0,2.0);

  fvar<double> a = stan::agrad::binomial_coefficient_log(x, y);
  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_);
  EXPECT_FLOAT_EQ(0.69289774, a.d_);
}

// TEST(AgradFwdBinomialCoefficientLog,FvarVar_1stDeriv) {
//   using stan::agrad::fvar;
//   using stan::agrad::var;
//   using stan::math::binomial_coefficient_log;
//   using boost::math::digamma;

//   fvar<var> x(2004.0,1.0);
//   fvar<var> z(1002.0,2.0);
//   fvar<var> a = binomial_coefficient_log(x,z);

//   EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val());
//   EXPECT_FLOAT_EQ(0.69289774, a.d_.val());

//   AVEC y = createAVEC(x.val_,z.val_);
//   VEC g;
//   a.val_.grad(y,g);
//   EXPECT_FLOAT_EQ(0.69289774, g[0]);
//   EXPECT_FLOAT_EQ(-7.9936058e-15, g[1]);
// }

// TEST(AgradFwdBinomialCoefficientLog,FvarFvarDouble) {
//   using stan::agrad::fvar;
//   using stan::math::binomial_coefficient_log;
//   using stan::agrad::binomial_coefficient_log;

//   fvar<fvar<double> > x;
//   x.val_.val_ = 2004.0;
//   x.val_.d_ = 1.0;

//   fvar<fvar<double> > y;
//   y.val_.val_ = 1002.0;
//   y.d_.val_ = 1.0;

//   fvar<fvar<double> > a = binomial_coefficient_log(x,y);

//   EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_);
//   EXPECT_FLOAT_EQ(0.69289774, a.val_.d_);
//   EXPECT_FLOAT_EQ(-8.8817842e-15, a.d_.val_);
//   EXPECT_FLOAT_EQ(0.0009975062, a.d_.d_);
// }
<commit_msg>added higher order autodiff tests to binomial_coefficient_log<commit_after>#include <gtest/gtest.h>
#include <stan/agrad/fwd.hpp>
#include <boost/math/special_functions/digamma.hpp>
#include <stan/math/functions/binomial_coefficient_log.hpp>
#include <stan/agrad/rev.hpp>
#include <test/unit/agrad/util.hpp>

TEST(AgradFwdBinomialCoefficientLog,Fvar) {
  using stan::agrad::fvar;
  using stan::math::binomial_coefficient_log;
  using boost::math::digamma;

  fvar<double> x(2004.0,1.0);
  fvar<double> y(1002.0,2.0);

  fvar<double> a = stan::agrad::binomial_coefficient_log(x, y);
  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0, 1002.0), a.val_);
  EXPECT_FLOAT_EQ(0.69289774, a.d_);
}

TEST(AgradFwdBinomialCoefficientLog,FvarVar_Double_1stDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using stan::math::binomial_coefficient_log;
  using boost::math::digamma;

  fvar<var> x(2004.0,1.0);
  double z(1002);
  fvar<var> a = binomial_coefficient_log(x,z);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val());
  EXPECT_FLOAT_EQ(0.69289774, a.d_.val());

  AVEC y = createAVEC(x.val_);
  VEC g;
  a.val_.grad(y,g);
  EXPECT_FLOAT_EQ(0.69289774, g[0]);
}
TEST(AgradFwdBinomialCoefficientLog,Double_FvarVar_1stDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using stan::math::binomial_coefficient_log;
  using boost::math::digamma;

  double x(2004.0);
  fvar<var> z(1002.0,2.0);
  fvar<var> a = binomial_coefficient_log(x,z);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val());
  EXPECT_NEAR(0, a.d_.val(),1e-8);

  AVEC y = createAVEC(z.val_);
  VEC g;
  a.val_.grad(y,g);
  EXPECT_NEAR(0, g[0],1e-8);
}
TEST(AgradFwdBinomialCoefficientLog,FvarVar_Double_2ndDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using stan::math::binomial_coefficient_log;
  using boost::math::digamma;

  fvar<var> x(2004.0,1.0);
  double z(1002);
  fvar<var> a = binomial_coefficient_log(x,z);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val());
  EXPECT_FLOAT_EQ(0.69289774, a.d_.val());

  AVEC y = createAVEC(x.val_);
  VEC g;
  a.d_.grad(y,g);
  EXPECT_FLOAT_EQ(-0.00049862865, g[0]);
}
TEST(AgradFwdBinomialCoefficientLog,Double_FvarVar_2ndDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using stan::math::binomial_coefficient_log;
  using boost::math::digamma;

  double x(2004.0);
  fvar<var> z(1002.0,2.0);
  fvar<var> a = binomial_coefficient_log(x,z);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val());
  EXPECT_NEAR(0, a.d_.val(),1e-8);

  AVEC y = createAVEC(z.val_);
  VEC g;
  a.d_.grad(y,g);
  EXPECT_FLOAT_EQ(-0.00399002460681026, g[0]);
}

TEST(AgradFwdBinomialCoefficientLog,FvarVar_FvarVar_1stDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using stan::math::binomial_coefficient_log;
  using boost::math::digamma;

  fvar<var> x(2004.0,1.0);
  fvar<var> z(1002.0,2.0);
  fvar<var> a = binomial_coefficient_log(x,z);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val());
  EXPECT_FLOAT_EQ(0.69289774, a.d_.val());

  AVEC y = createAVEC(x.val_,z.val_);
  VEC g;
  a.val_.grad(y,g);
  EXPECT_FLOAT_EQ(0.69289774, g[0]);
  EXPECT_NEAR(0, g[1],1e-8);
}
TEST(AgradFwdBinomialCoefficientLog,FvarVar_FvarVar_2ndDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using stan::math::binomial_coefficient_log;
  using boost::math::digamma;

  fvar<var> x(2004.0,1.0);
  fvar<var> z(1002.0,2.0);
  fvar<var> a = binomial_coefficient_log(x,z);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val());
  EXPECT_FLOAT_EQ(0.69289774, a.d_.val());

  AVEC y = createAVEC(x.val_,z.val_);
  VEC g;
  a.d_.grad(y,g);
  EXPECT_FLOAT_EQ(0.0014963837, g[0]);
  EXPECT_FLOAT_EQ(-0.0029925184551076781, g[1]);
}

TEST(AgradFwdBinomialCoefficientLog,FvarFvarDouble) {
  using stan::agrad::fvar;
  using stan::math::binomial_coefficient_log;
  using stan::agrad::binomial_coefficient_log;

  fvar<fvar<double> > x;
  x.val_.val_ = 2004.0;
  x.val_.d_ = 1.0;

  fvar<fvar<double> > y;
  y.val_.val_ = 1002.0;
  y.d_.val_ = 1.0;

  fvar<fvar<double> > a = binomial_coefficient_log(x,y);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_);
  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_);
  EXPECT_NEAR(0, a.d_.val_,1e-8);
  EXPECT_FLOAT_EQ(0.0009975062, a.d_.d_);
}

TEST(AgradFwdBinomialCoefficientLog,FvarFvarVar_FvarFvarVar_1stDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using stan::math::binomial_coefficient_log;
  using stan::agrad::binomial_coefficient_log;

  fvar<fvar<var> > x;
  x.val_.val_ = 2004.0;
  x.val_.d_ = 1.0;

  fvar<fvar<var> > y;
  y.val_.val_ = 1002.0;
  y.d_.val_ = 1.0;

  fvar<fvar<var> > a = binomial_coefficient_log(x,y);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());
  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());
  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);
  EXPECT_FLOAT_EQ(0.0009975062, a.d_.d_.val());

  AVEC p = createAVEC(x.val_.val_,y.val_.val_);
  VEC g;
  a.val_.val_.grad(p,g);
  EXPECT_FLOAT_EQ(0.69289774, g[0]);
  EXPECT_NEAR(0, g[1],1e-8);
}
TEST(AgradFwdBinomialCoefficientLog,FvarFvarVar_Double_1stDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using stan::math::binomial_coefficient_log;
  using stan::agrad::binomial_coefficient_log;

  fvar<fvar<var> > x;
  x.val_.val_ = 2004.0;
  x.val_.d_ = 1.0;

  double y(1002.0);

  fvar<fvar<var> > a = binomial_coefficient_log(x,y);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());
  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());
  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);
  EXPECT_FLOAT_EQ(0, a.d_.d_.val());

  AVEC p = createAVEC(x.val_.val_);
  VEC g;
  a.val_.val_.grad(p,g);
  EXPECT_FLOAT_EQ(0.69289774, g[0]);
}
TEST(AgradFwdBinomialCoefficientLog,Double_FvarFvarVar_1stDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using stan::math::binomial_coefficient_log;
  using stan::agrad::binomial_coefficient_log;

  double x(2004.0);

  fvar<fvar<var> > y;
  y.val_.val_ = 1002.0;
  y.d_.val_ = 1.0;

  fvar<fvar<var> > a = binomial_coefficient_log(x,y);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());
  EXPECT_FLOAT_EQ(0, a.val_.d_.val());
  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);
  EXPECT_FLOAT_EQ(0, a.d_.d_.val());

  AVEC p = createAVEC(y.val_.val_);
  VEC g;
  a.val_.val_.grad(p,g);
  EXPECT_NEAR(0, g[0],1e-8);
}

TEST(AgradFwdBinomialCoefficientLog,FvarFvarVar_FvarFvarVar_2ndDeriv_x) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using stan::math::binomial_coefficient_log;
  using stan::agrad::binomial_coefficient_log;

  fvar<fvar<var> > x;
  x.val_.val_ = 2004.0;
  x.val_.d_ = 1.0;

  fvar<fvar<var> > y;
  y.val_.val_ = 1002.0;
  y.d_.val_ = 1.0;

  fvar<fvar<var> > a = binomial_coefficient_log(x,y);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());
  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());
  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);
  EXPECT_FLOAT_EQ(0.0009975062, a.d_.d_.val());

  AVEC p = createAVEC(x.val_.val_,y.val_.val_);
  VEC g;
  a.val_.d_.grad(p,g);
  EXPECT_FLOAT_EQ(-0.00049862865, g[0]);
  EXPECT_FLOAT_EQ(0.00099750615170258105, g[1]);
}
TEST(AgradFwdBinomialCoefficientLog,FvarFvarVar_FvarFvarVar_2ndDeriv_y) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using stan::math::binomial_coefficient_log;
  using stan::agrad::binomial_coefficient_log;

  fvar<fvar<var> > x;
  x.val_.val_ = 2004.0;
  x.val_.d_ = 1.0;

  fvar<fvar<var> > y;
  y.val_.val_ = 1002.0;
  y.d_.val_ = 1.0;

  fvar<fvar<var> > a = binomial_coefficient_log(x,y);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());
  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());
  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);
  EXPECT_FLOAT_EQ(0.0009975062, a.d_.d_.val());

  AVEC p = createAVEC(x.val_.val_,y.val_.val_);
  VEC g;
  a.d_.val_.grad(p,g);
  EXPECT_FLOAT_EQ(0.0009975062, g[0]);
  EXPECT_FLOAT_EQ(-0.0019950123034051291, g[1]);
}
TEST(AgradFwdBinomialCoefficientLog,Double_FvarFvarVar_2ndDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using stan::math::binomial_coefficient_log;
  using stan::agrad::binomial_coefficient_log;

  double x(2004.0);

  fvar<fvar<var> > y;
  y.val_.val_ = 1002.0;
  y.d_.val_ = 1.0;

  fvar<fvar<var> > a = binomial_coefficient_log(x,y);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());
  EXPECT_FLOAT_EQ(0, a.val_.d_.val());
  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);
  EXPECT_FLOAT_EQ(0, a.d_.d_.val());

  AVEC p = createAVEC(y.val_.val_);
  VEC g;
  a.d_.val_.grad(p,g);
  EXPECT_NEAR(-0.00199501230340513, g[0],1e-8);
}
TEST(AgradFwdBinomialCoefficientLog,FvarFvarVar_Double_2ndDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using stan::math::binomial_coefficient_log;
  using stan::agrad::binomial_coefficient_log;

  fvar<fvar<var> > x;
  x.val_.val_ = 2004.0;
  x.val_.d_ = 1.0;

  double y(1002.0);

  fvar<fvar<var> > a = binomial_coefficient_log(x,y);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());
  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());
  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);
  EXPECT_FLOAT_EQ(0, a.d_.d_.val());

  AVEC p = createAVEC(x.val_.val_);
  VEC g;
  a.val_.d_.grad(p,g);
  EXPECT_FLOAT_EQ(-0.00049862863648177515, g[0]);
}
TEST(AgradFwdBinomialCoefficientLog,FvarFvarVar_FvarFvarVar_3rdDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using stan::math::binomial_coefficient_log;
  using stan::agrad::binomial_coefficient_log;

  fvar<fvar<var> > x;
  x.val_.val_ = 2004.0;
  x.val_.d_ = 1.0;

  fvar<fvar<var> > y;
  y.val_.val_ = 1002.0;
  y.d_.val_ = 1.0;

  fvar<fvar<var> > a = binomial_coefficient_log(x,y);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());
  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());
  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);
  EXPECT_FLOAT_EQ(0.0009975062, a.d_.d_.val());

  AVEC p = createAVEC(x.val_.val_,y.val_.val_);
  VEC g;
  a.d_.d_.grad(p,g);
  EXPECT_FLOAT_EQ(-9.9501847e-07, g[0]);
  EXPECT_FLOAT_EQ(9.9501847e-07, g[1]);
}
TEST(AgradFwdBinomialCoefficientLog,Double_FvarFvarVar_3rdDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using stan::math::binomial_coefficient_log;
  using stan::agrad::binomial_coefficient_log;

  double x(2004.0);

  fvar<fvar<var> > y;
  y.val_.val_ = 1002.0;
  y.d_.val_ = 1.0;
  y.val_.d_ = 1.0;

  fvar<fvar<var> > a = binomial_coefficient_log(x,y);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());
  EXPECT_NEAR(0, a.val_.d_.val(),1e-8);
  EXPECT_NEAR(0, a.d_.val_.val(),1e-8);
  EXPECT_FLOAT_EQ(-0.0019950124, a.d_.d_.val());

  AVEC p = createAVEC(y.val_.val_);
  VEC g;
  a.d_.d_.grad(p,g);
  EXPECT_NEAR(0, g[0],1e-8);
}
TEST(AgradFwdBinomialCoefficientLog,FvarFvarVar_Double_3rdDeriv) {
  using stan::agrad::fvar;
  using stan::agrad::var;
  using stan::math::binomial_coefficient_log;
  using stan::agrad::binomial_coefficient_log;

  fvar<fvar<var> > x;
  x.val_.val_ = 2004.0;
  x.val_.d_ = 1.0;
  x.d_.val_ = 1.0;

  double y(1002.0);

  fvar<fvar<var> > a = binomial_coefficient_log(x,y);

  EXPECT_FLOAT_EQ(binomial_coefficient_log(2004.0,1002.0), a.val_.val_.val());
  EXPECT_FLOAT_EQ(0.69289774, a.val_.d_.val());
  EXPECT_FLOAT_EQ(0.69289774181268948, a.d_.val_.val());
  EXPECT_FLOAT_EQ(-0.00049862865, a.d_.d_.val());

  AVEC p = createAVEC(x.val_.val_);
  VEC g;
  a.d_.d_.grad(p,g);
  EXPECT_FLOAT_EQ(7.4613968e-07, g[0]);
}
<|endoftext|>


<commit_before>#include "sudokuJudger.h"
#include "sudokuGenerator.h"
#include "sudokuPrinter.h"
#include "sudokuIO.h"
#include "sudokuExceptionInspector.h"
#include <stdlib.h>
#include <fstream>
// #include <unistd.h>
#include <iostream>
using namespace std;

int main(int argc, char *argv[]) {
    if (argc < 3) {
        cout << "Error occurs when parsing arguments." << endl;
        cout << "Usage: sudoku.exe -c [N: a number]" << endl;
        return 1;
    }

    int solutionNumber;
    SudokuExceptionInspector sudokuExceptionInspector;
    try {
        solutionNumber = sudokuExceptionInspector.parser(argv[2]);
    } catch(ParserException) {
        cout << "Error occurs when parsing arguments." << endl;
        cout << "Usage: sudoku.exe -c [N: a number]" << endl;
        cout << "Please check your input number." << endl;
        return 1;
    }

    SudokuGenerator sudokuGenerator;
    SudokuIOer sudokuIOer;
    // SudokuPrinter sudokuPrinter;

    fstream sudokuFile;
    // open sudoku.txt
    sudokuFile.open(filename, ios::app);

    bool signal = false;

    for (int i = 0; i < solutionNumber; i++) {
        signal = sudokuGenerator.Generator();
        if (signal) {
            sudokuGenerator.increaseRandomSeed();
            sudokuIOer.outputFile(sudokuGenerator.solution, sudokuFile);
        } else {
            cout << "Error occurs when applying sudokuGenerator." << endl;
            return 1;
        }
    }

    // close sudoku.txt
    sudokuFile.close();

    return 0;
}
<commit_msg>update main.cpp: enable file IO using std::ofstream<commit_after>#include "sudokuJudger.h"
#include "sudokuGenerator.h"
#include "sudokuPrinter.h"
#include "sudokuIO.h"
#include "sudokuExceptionInspector.h"
#include <stdlib.h>
#include <fstream>
// #include <unistd.h>
#include <iostream>
using namespace std;

int main(int argc, char *argv[]) {
    if (argc < 3) {
        cout << "Error occurs when parsing arguments." << endl;
        cout << "Usage: sudoku.exe -c [N: a number]" << endl;
        return 1;
    }

    int solutionNumber;
    SudokuExceptionInspector sudokuExceptionInspector;
    try {
        solutionNumber = sudokuExceptionInspector.parser(argv[2]);
    } catch(ParserException) {
        cout << "Error occurs when parsing arguments." << endl;
        cout << "Usage: sudoku.exe -c [N: a number]" << endl;
        cout << "Please check your input number." << endl;
        return 1;
    }

    SudokuGenerator sudokuGenerator;
    SudokuIOer sudokuIOer;
    // SudokuPrinter sudokuPrinter;

    ofstream sudokuFile("sudoku.txt", ios::out | ios::ate);
    // open sudoku.txt
    // sudokuFile.open("sudoku.txt", ios::app);

    bool signal = false;

    for (int i = 0; i < solutionNumber; i++) {
        signal = sudokuGenerator.Generator();
        if (signal) {
            sudokuGenerator.increaseRandomSeed();
            sudokuIOer.outputFile(sudokuGenerator.solution, sudokuFile);
        } else {
            cout << "Error occurs when applying sudokuGenerator." << endl;
            return 1;
        }
    }

    // close sudoku.txt
    sudokuFile.close();

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Main.cpp
 *
 * Created on: Dec 31, 2014
 * Author: jrparks
 */
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2/opencv.hpp>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include "zedin.cpp"

using namespace std;
using namespace cv;

int main(int argc, char *argv[])
{
    ZedIn *camera = NULL;

    if (argc == 2)
    {
        camera = new ZedIn(argv[1]);
    }
    else
    {
        camera = new ZedIn;
    }
    char name[PATH_MAX];
    int  index = 0;
    int  rc;
    struct stat statbuf;
    do
    {
        sprintf(name, "cap%d.avi", index++);
        rc = stat(name, &statbuf);
    } while (rc == 0);
    VideoWriter outputVideo(name, CV_FOURCC('M', 'J', 'P', 'G'), 30, Size(camera->width(), camera->height()), true);
    Mat         frame;

    while (true)
    {
        camera->update();
        camera->getFrame().copyTo(frame);
        if (!frame.empty())
        {
            outputVideo << frame;
        }
        else
        {
            fprintf(stderr, "Unable to grab frame.\n");
            break;
        }
        int wait_key = cv::waitKey(5);
        if ((wait_key == 27) || (wait_key == 32))
        {
            break;
        }
    }
    fprintf(stdout, "Closing camera.\n");
}
<commit_msg>Fixed waitkey<commit_after>/*
 * Main.cpp
 *
 * Created on: Dec 31, 2014
 * Author: jrparks
 */
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2/opencv.hpp>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include "zedin.cpp"

using namespace std;
using namespace cv;

int main(int argc, char *argv[])
{
    ZedIn *camera = NULL;

    if (argc == 2)
    {
        camera = new ZedIn(argv[1]);
    }
    else
    {
        camera = new ZedIn;
    }
    char name[PATH_MAX];
    int  index = 0;
    int  rc;
    struct stat statbuf;
    do
    {
        sprintf(name, "cap%d.avi", index++);
        rc = stat(name, &statbuf);
    } while (rc == 0);
    VideoWriter outputVideo(name, CV_FOURCC('M', 'J', 'P', 'G'), 30, Size(camera->width(), camera->height()), true);
    Mat frame(200,200,CV_8UC3);

    imshow("Frame", frame);

    while (true)
    {
        camera->update();
        camera->getFrame().copyTo(frame);
        if (!frame.empty())
        {
            outputVideo << frame;
        }
        else
        {
            fprintf(stderr, "Unable to grab frame.\n");
            break;
        }
        uchar wait_key = cv::waitKey(5);
	cout << wait_key << endl;
        if ((wait_key == 27) || (wait_key == 32))
        {
            break;
        }
    }
    fprintf(stdout, "Closing camera.\n");
}
<|endoftext|>