<commit_before>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2018  Clifford Wolf <clifford@symbioticeda.com>
 *  Copyright (C) 2018  Miodrag Milanovic <miodrag@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#ifdef MAIN_EXECUTABLE

#include <fstream>
#include "bitstream.h"
#include "command.h"
#include "design_utils.h"
#include "jsonparse.h"
#include "log.h"
#include "pcf.h"
#include "timing.h"

USING_NEXTPNR_NAMESPACE

class Ice40CommandHandler : public CommandHandler
{
  public:
    Ice40CommandHandler(int argc, char **argv);
    virtual ~Ice40CommandHandler(){};
    std::unique_ptr<Context> createContext(std::unordered_map<std::string, Property> &values) override;
    void setupArchContext(Context *ctx) override;
    void validate() override;
    void customAfterLoad(Context *ctx) override;
    void customBitstream(Context *ctx) override;

  protected:
    po::options_description getArchOptions() override;
};

Ice40CommandHandler::Ice40CommandHandler(int argc, char **argv) : CommandHandler(argc, argv) {}

po::options_description Ice40CommandHandler::getArchOptions()
{
    po::options_description specific("Architecture specific options");
#ifdef ICE40_HX1K_ONLY
    specific.add_options()("hx1k", "set device type to iCE40HX1K");
#else
    specific.add_options()("lp384", "set device type to iCE40LP384");
    specific.add_options()("lp1k", "set device type to iCE40LP1K");
    specific.add_options()("lp8k", "set device type to iCE40LP8K");
    specific.add_options()("hx1k", "set device type to iCE40HX1K");
    specific.add_options()("hx8k", "set device type to iCE40HX8K");
    specific.add_options()("up5k", "set device type to iCE40UP5K");
    specific.add_options()("u4k", "set device type to iCE5LP4K");
#endif
    specific.add_options()("package", po::value<std::string>(), "set device package");
    specific.add_options()("pcf", po::value<std::string>(), "PCF constraints file to ingest");
    specific.add_options()("asc", po::value<std::string>(), "asc bitstream file to write");
    specific.add_options()("read", po::value<std::string>(), "asc bitstream file to read");
    specific.add_options()("promote-logic",
                           "enable promotion of 'logic' globals (in addition to clk/ce/sr by default)");
    specific.add_options()("no-promote-globals", "disable all global promotion");
    specific.add_options()("opt-timing", "run post-placement timing optimisation pass (experimental)");
    specific.add_options()("tmfuzz", "run path delay estimate fuzzer");
    specific.add_options()("pcf-allow-unconstrained", "don't require PCF to constrain all IO");

    return specific;
}
void Ice40CommandHandler::validate()
{
    conflicting_options(vm, "read", "json");
    if ((vm.count("lp384") + vm.count("lp1k") + vm.count("lp8k") + vm.count("hx1k") + vm.count("hx8k") +
         vm.count("up5k") + vm.count("u4k")) > 1)
        log_error("Only one device type can be set\n");
}

void Ice40CommandHandler::customAfterLoad(Context *ctx)
{
    if (vm.count("pcf")) {
        std::string filename = vm["pcf"].as<std::string>();
        std::ifstream pcf(filename);
        if (!apply_pcf(ctx, filename, pcf))
            log_error("Loading PCF failed.\n");
    } else {
        log_warning("No PCF file specified; IO pins will be placed automatically\n");
    }
}
void Ice40CommandHandler::customBitstream(Context *ctx)
{
    if (vm.count("asc")) {
        std::string filename = vm["asc"].as<std::string>();
        std::ofstream f(filename);
        write_asc(ctx, f);
    }
}

void Ice40CommandHandler::setupArchContext(Context *ctx)
{
    if (vm.count("tmfuzz"))
        ice40DelayFuzzerMain(ctx);

    if (vm.count("read")) {
        std::string filename = vm["read"].as<std::string>();
        std::ifstream f(filename);
        if (!read_asc(ctx, f))
            log_error("Loading ASC failed.\n");
    }
}

std::unique_ptr<Context> Ice40CommandHandler::createContext(std::unordered_map<std::string, Property> &values)
{
    ArchArgs chipArgs;
    chipArgs.type = ArchArgs::NONE;
    if (vm.count("lp384")) {
        chipArgs.type = ArchArgs::LP384;
        chipArgs.package = "qn32";
    }

    if (vm.count("lp1k")) {
        chipArgs.type = ArchArgs::LP1K;
        chipArgs.package = "tq144";
    }

    if (vm.count("lp8k")) {
        chipArgs.type = ArchArgs::LP8K;
        chipArgs.package = "ct256";
    }

    if (vm.count("hx1k")) {
        chipArgs.type = ArchArgs::HX1K;
        chipArgs.package = "tq144";
    }

    if (vm.count("hx8k")) {
        chipArgs.type = ArchArgs::HX8K;
        chipArgs.package = "ct256";
    }

    if (vm.count("up5k")) {
        chipArgs.type = ArchArgs::UP5K;
        chipArgs.package = "sg48";
    }

    if (vm.count("u4k")) {
        chipArgs.type = ArchArgs::U4K;
        chipArgs.package = "sg48";
    }

    if (vm.count("package"))
        chipArgs.package = vm["package"].as<std::string>();
    if (values.find("arch.name") != values.end()) {
        std::string arch_name = values["arch.name"].as_string();
        if (arch_name != "ice40")
            log_error("Unsuported architecture '%s'.\n", arch_name.c_str());
    }
    if (values.find("arch.type") != values.end()) {
        std::string arch_type = values["arch.type"].as_string();
        if (chipArgs.type != ArchArgs::NONE)
            log_error("Overriding architecture is unsuported.\n");

        if (arch_type == "lp384") {
            chipArgs.type = ArchArgs::LP384;
        }
        if (arch_type == "lp1k") {
            chipArgs.type = ArchArgs::LP1K;
        }
        if (arch_type == "lp8k") {
            chipArgs.type = ArchArgs::LP8K;
        }
        if (arch_type == "hx1k") {
            chipArgs.type = ArchArgs::HX1K;
        }
        if (arch_type == "hx8k") {
            chipArgs.type = ArchArgs::HX8K;
        }
        if (arch_type == "up5k") {
            chipArgs.type = ArchArgs::UP5K;
        }
        if (arch_type == "u4k") {
            chipArgs.type = ArchArgs::U4K;
        }
        if (chipArgs.type == ArchArgs::NONE)
            log_error("Unsuported FPGA type '%s'.\n", arch_type.c_str());
    }
    if (values.find("arch.package") != values.end()) {
        if (vm.count("package"))
            log_error("Overriding architecture is unsuported.\n");
        chipArgs.package = values["arch.package"].as_string();
    }

    if (chipArgs.type == ArchArgs::NONE) {
        chipArgs.type = ArchArgs::HX1K;
        chipArgs.package = "tq144";
    }
#ifdef ICE40_HX1K_ONLY
    if (chipArgs.type != ArchArgs::HX1K) {
        log_error("This version of nextpnr-ice40 is built with HX1K-support only.\n");
    }
#endif

    log_warning("Use of default value for --package is deprecated. Please add '--package %s' to arguments.\n",
                chipArgs.package.c_str());

    auto ctx = std::unique_ptr<Context>(new Context(chipArgs));
    for (auto &val : values)
        ctx->settings[ctx->id(val.first)] = val.second;

    ctx->settings[ctx->id("arch.package")] = ctx->archArgs().package;
    if (vm.count("promote-logic"))
        ctx->settings[ctx->id("promote_logic")] = Property::State::S1;
    if (vm.count("no-promote-globals"))
        ctx->settings[ctx->id("no_promote_globals")] = Property::State::S1;
    if (vm.count("opt-timing"))
        ctx->settings[ctx->id("opt_timing")] = Property::State::S1;
    if (vm.count("pcf-allow-unconstrained"))
        ctx->settings[ctx->id("pcf_allow_unconstrained")] = Property::State::S1;
    return ctx;
}

int main(int argc, char *argv[])
{
    Ice40CommandHandler handler(argc, argv);
    return handler.exec();
}

#endif
<commit_msg>ice40: Only warn about default package if there is no package argument<commit_after>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2018  Clifford Wolf <clifford@symbioticeda.com>
 *  Copyright (C) 2018  Miodrag Milanovic <miodrag@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#ifdef MAIN_EXECUTABLE

#include <fstream>
#include "bitstream.h"
#include "command.h"
#include "design_utils.h"
#include "jsonparse.h"
#include "log.h"
#include "pcf.h"
#include "timing.h"

USING_NEXTPNR_NAMESPACE

class Ice40CommandHandler : public CommandHandler
{
  public:
    Ice40CommandHandler(int argc, char **argv);
    virtual ~Ice40CommandHandler(){};
    std::unique_ptr<Context> createContext(std::unordered_map<std::string, Property> &values) override;
    void setupArchContext(Context *ctx) override;
    void validate() override;
    void customAfterLoad(Context *ctx) override;
    void customBitstream(Context *ctx) override;

  protected:
    po::options_description getArchOptions() override;
};

Ice40CommandHandler::Ice40CommandHandler(int argc, char **argv) : CommandHandler(argc, argv) {}

po::options_description Ice40CommandHandler::getArchOptions()
{
    po::options_description specific("Architecture specific options");
#ifdef ICE40_HX1K_ONLY
    specific.add_options()("hx1k", "set device type to iCE40HX1K");
#else
    specific.add_options()("lp384", "set device type to iCE40LP384");
    specific.add_options()("lp1k", "set device type to iCE40LP1K");
    specific.add_options()("lp8k", "set device type to iCE40LP8K");
    specific.add_options()("hx1k", "set device type to iCE40HX1K");
    specific.add_options()("hx8k", "set device type to iCE40HX8K");
    specific.add_options()("up5k", "set device type to iCE40UP5K");
    specific.add_options()("u4k", "set device type to iCE5LP4K");
#endif
    specific.add_options()("package", po::value<std::string>(), "set device package");
    specific.add_options()("pcf", po::value<std::string>(), "PCF constraints file to ingest");
    specific.add_options()("asc", po::value<std::string>(), "asc bitstream file to write");
    specific.add_options()("read", po::value<std::string>(), "asc bitstream file to read");
    specific.add_options()("promote-logic",
                           "enable promotion of 'logic' globals (in addition to clk/ce/sr by default)");
    specific.add_options()("no-promote-globals", "disable all global promotion");
    specific.add_options()("opt-timing", "run post-placement timing optimisation pass (experimental)");
    specific.add_options()("tmfuzz", "run path delay estimate fuzzer");
    specific.add_options()("pcf-allow-unconstrained", "don't require PCF to constrain all IO");

    return specific;
}
void Ice40CommandHandler::validate()
{
    conflicting_options(vm, "read", "json");
    if ((vm.count("lp384") + vm.count("lp1k") + vm.count("lp8k") + vm.count("hx1k") + vm.count("hx8k") +
         vm.count("up5k") + vm.count("u4k")) > 1)
        log_error("Only one device type can be set\n");
}

void Ice40CommandHandler::customAfterLoad(Context *ctx)
{
    if (vm.count("pcf")) {
        std::string filename = vm["pcf"].as<std::string>();
        std::ifstream pcf(filename);
        if (!apply_pcf(ctx, filename, pcf))
            log_error("Loading PCF failed.\n");
    } else {
        log_warning("No PCF file specified; IO pins will be placed automatically\n");
    }
}
void Ice40CommandHandler::customBitstream(Context *ctx)
{
    if (vm.count("asc")) {
        std::string filename = vm["asc"].as<std::string>();
        std::ofstream f(filename);
        write_asc(ctx, f);
    }
}

void Ice40CommandHandler::setupArchContext(Context *ctx)
{
    if (vm.count("tmfuzz"))
        ice40DelayFuzzerMain(ctx);

    if (vm.count("read")) {
        std::string filename = vm["read"].as<std::string>();
        std::ifstream f(filename);
        if (!read_asc(ctx, f))
            log_error("Loading ASC failed.\n");
    }
}

std::unique_ptr<Context> Ice40CommandHandler::createContext(std::unordered_map<std::string, Property> &values)
{
    ArchArgs chipArgs;
    chipArgs.type = ArchArgs::NONE;
    if (vm.count("lp384")) {
        chipArgs.type = ArchArgs::LP384;
        chipArgs.package = "qn32";
    }

    if (vm.count("lp1k")) {
        chipArgs.type = ArchArgs::LP1K;
        chipArgs.package = "tq144";
    }

    if (vm.count("lp8k")) {
        chipArgs.type = ArchArgs::LP8K;
        chipArgs.package = "ct256";
    }

    if (vm.count("hx1k")) {
        chipArgs.type = ArchArgs::HX1K;
        chipArgs.package = "tq144";
    }

    if (vm.count("hx8k")) {
        chipArgs.type = ArchArgs::HX8K;
        chipArgs.package = "ct256";
    }

    if (vm.count("up5k")) {
        chipArgs.type = ArchArgs::UP5K;
        chipArgs.package = "sg48";
    }

    if (vm.count("u4k")) {
        chipArgs.type = ArchArgs::U4K;
        chipArgs.package = "sg48";
    }

    if (vm.count("package"))
        chipArgs.package = vm["package"].as<std::string>();
    else
        log_warning("Use of default value for --package is deprecated. Please add '--package %s' to arguments.\n",
                    chipArgs.package.c_str());

    if (values.find("arch.name") != values.end()) {
        std::string arch_name = values["arch.name"].as_string();
        if (arch_name != "ice40")
            log_error("Unsuported architecture '%s'.\n", arch_name.c_str());
    }
    if (values.find("arch.type") != values.end()) {
        std::string arch_type = values["arch.type"].as_string();
        if (chipArgs.type != ArchArgs::NONE)
            log_error("Overriding architecture is unsuported.\n");

        if (arch_type == "lp384") {
            chipArgs.type = ArchArgs::LP384;
        }
        if (arch_type == "lp1k") {
            chipArgs.type = ArchArgs::LP1K;
        }
        if (arch_type == "lp8k") {
            chipArgs.type = ArchArgs::LP8K;
        }
        if (arch_type == "hx1k") {
            chipArgs.type = ArchArgs::HX1K;
        }
        if (arch_type == "hx8k") {
            chipArgs.type = ArchArgs::HX8K;
        }
        if (arch_type == "up5k") {
            chipArgs.type = ArchArgs::UP5K;
        }
        if (arch_type == "u4k") {
            chipArgs.type = ArchArgs::U4K;
        }
        if (chipArgs.type == ArchArgs::NONE)
            log_error("Unsuported FPGA type '%s'.\n", arch_type.c_str());
    }
    if (values.find("arch.package") != values.end()) {
        if (vm.count("package"))
            log_error("Overriding architecture is unsuported.\n");
        chipArgs.package = values["arch.package"].as_string();
    }

    if (chipArgs.type == ArchArgs::NONE) {
        chipArgs.type = ArchArgs::HX1K;
        chipArgs.package = "tq144";
    }
#ifdef ICE40_HX1K_ONLY
    if (chipArgs.type != ArchArgs::HX1K) {
        log_error("This version of nextpnr-ice40 is built with HX1K-support only.\n");
    }
#endif

    auto ctx = std::unique_ptr<Context>(new Context(chipArgs));
    for (auto &val : values)
        ctx->settings[ctx->id(val.first)] = val.second;

    ctx->settings[ctx->id("arch.package")] = ctx->archArgs().package;
    if (vm.count("promote-logic"))
        ctx->settings[ctx->id("promote_logic")] = Property::State::S1;
    if (vm.count("no-promote-globals"))
        ctx->settings[ctx->id("no_promote_globals")] = Property::State::S1;
    if (vm.count("opt-timing"))
        ctx->settings[ctx->id("opt_timing")] = Property::State::S1;
    if (vm.count("pcf-allow-unconstrained"))
        ctx->settings[ctx->id("pcf_allow_unconstrained")] = Property::State::S1;
    return ctx;
}

int main(int argc, char *argv[])
{
    Ice40CommandHandler handler(argc, argv);
    return handler.exec();
}

#endif
<|endoftext|>


<commit_before>/*****************************************************************************
 * Project: BaBar detector at the SLAC PEP-II B-factory
 * Package: RooFitCore
 *    File: $Id: RooGaussModel.cc,v 1.7 2001/08/03 18:13:02 verkerke Exp $
 * Authors:
 *   WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu
 * History:
 *   05-Jun-2001 WV Created initial version
 *
 * Copyright (C) 2001 University of California
 *****************************************************************************/

// -- CLASS DESCRIPTION --
//

#include <iostream.h>
#include "RooFitModels/RooGaussModel.hh"
#include "RooFitCore/RooMath.hh"

ClassImp(RooGaussModel)
;

RooGaussModel::RooGaussModel(const char *name, const char *title, RooRealVar& x,
			     RooAbsReal& _mean, RooAbsReal& _sigma,
			     RooAbsReal& _meanSF, RooAbsReal& _sigmaSF) :
  RooResolutionModel(name,title,x),
  mean("mean","Mean",this,_mean),
  sigma("sigma","Width",this,_sigma),
  msf("msf","Mean Scale Factor",this,_meanSF),
  ssf("ssf","Sigma Scale Factor",this,_sigmaSF)
{
}

RooGaussModel::RooGaussModel(const RooGaussModel& other, const char* name) :
  RooResolutionModel(other,name),
  mean("mean",this,other.mean),
  sigma("sigma",this,other.sigma),
  msf("msf",this,other.msf),
  ssf("ssf",this,other.ssf)
{
}

RooGaussModel::~RooGaussModel()
{
  // Destructor
}

Int_t RooGaussModel::basisCode(const char* name) const
{
  if (!TString("exp(-abs(@0)/@1)").CompareTo(name)) return expBasisPlus ;
  if (!TString("exp(-abs(-@0)/@1)").CompareTo(name)) return expBasisMinus ;
  if (!TString("exp(-abs(@0)/@1)*sin(@0*@2)").CompareTo(name)) return sinBasisPlus ;
  if (!TString("exp(-abs(-@0)/@1)*sin(@0*@2)").CompareTo(name)) return sinBasisMinus ;
  if (!TString("exp(-abs(@0)/@1)*cos(@0*@2)").CompareTo(name)) return cosBasisPlus ;
  if (!TString("exp(-abs(-@0)/@1)*cos(@0*@2)").CompareTo(name)) return cosBasisMinus ;
  return 0 ;
}

Double_t RooGaussModel::evaluate() const
{
  // *** 1st form: Straight Gaussian, used for unconvoluted PDF or expBasis with 0 lifetime ***
  static Double_t root2(sqrt(2)) ;
  static Double_t root2pi(sqrt(2*atan2(0,-1))) ;

  Double_t tau = ((RooAbsReal*)basis().getParameter(1))->getVal() ;

  if (_basisCode==noBasis ||
      ((_basisCode==expBasisPlus||_basisCode==expBasisMinus||
	_basisCode==cosBasisPlus||_basisCode==cosBasisMinus)&&tau==0.)) {
    Double_t xprime = (x-(mean*msf))/(sigma*ssf) ;
    if (_verboseEval>2) cout << "RooGaussModel::evaluate(" << GetName() << ") 1st form" << endl ;
    return exp(-0.5*xprime*xprime)/(sigma*ssf*root2pi) ;
  }

  // *** 2nd form: 0, used for sinBasis and cosBasis with tau=0 ***
  if (tau==0) {
    if (_verboseEval>2) cout << "RooGaussModel::evaluate(" << GetName() << ") 2nd form" << endl ;
    return 0. ;
  }

  // *** 3nd form: Convolution with exp(-t/tau), used for expBasis and cosBasis(omega=0) ***
  Double_t sign = (_basisCode==expBasisPlus||_basisCode==sinBasisPlus||_basisCode==cosBasisPlus)?-1:1 ;
  Double_t omega = ((RooAbsReal*)basis().getParameter(2))->getVal() ;
  Double_t xprime = sign*(x-(mean*msf))/tau ;
  Double_t c = (sigma*ssf)/(root2*tau) ;
  Double_t u = xprime/(2*c) ;

  if ( _basisCode==expBasisPlus || _basisCode==expBasisMinus ||
    ((_basisCode==cosBasisPlus||_basisCode==cosBasisMinus)&&omega==0.)) {
    if (_verboseEval>2) cout << "RooGaussModel::evaluate(" << GetName() << ") 3d form tau=" << tau << endl ;
    return exp(xprime+c*c) * erfc(u+c) ;
  }

  // *** 4th form: Convolution with exp(-t/tau)*sin(omega*t), used for sinBasis(omega<>0,tau<>0) ***
  Double_t swt = sign * omega *tau ;
  if (_basisCode==sinBasisPlus||_basisCode==sinBasisMinus) {
    if (_verboseEval>2) cout << "RooGaussModel::evaluate(" << GetName() << ") 4th form" << endl ;
    return (swt==0.) ? 0. : evalCerfIm(swt,u,c) ;
  }

  // *** 5th form: Convolution with exp(-t/tau)*cos(omega*t), used for cosBasis(omega<>0) ***
  if (_basisCode==cosBasisPlus||_basisCode==cosBasisMinus) {
    if (_verboseEval>2) cout << "RooGaussModel::evaluate(" << GetName()
			     << ") 5th form omega = " << omega << ", tau = " << tau << endl ;
    return evalCerfRe(swt,u,c) ;
  }

  assert(0) ;
  return 0 ;
}

Int_t RooGaussModel::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars) const
{
  switch(_basisCode) {

  // Analytical integration capability of raw PDF
  case noBasis:
    if (matchArgs(allVars,analVars,convVar())) return 1 ;
    break ;

  // Analytical integration capability of convoluted PDF
  case expBasisPlus:
  case expBasisMinus:
  case sinBasisPlus:
  case sinBasisMinus:
  case cosBasisPlus:
  case cosBasisMinus:
    if (matchArgs(allVars,analVars,convVar())) return 1 ;
    break ;
  }

  return 0 ;
}

Double_t RooGaussModel::analyticalIntegral(Int_t code) const
{
  static Double_t root2 = sqrt(2) ;
  static Double_t rootPiBy2 = sqrt(atan2(0.0,-1.0)/2.0);

  // No integration
  if (code==0) return getVal() ;

  // Code must be 0 or 1
  assert(code==1) ;

  // *** 1st form: Straight Gaussian, used for unconvoluted PDF or expBasis with 0 lifetime ***
  Double_t tau = ((RooAbsReal*)basis().getParameter(1))->getVal() ;
  if (_basisCode==noBasis ||
      ((_basisCode==expBasisPlus||_basisCode==expBasisMinus||
	_basisCode==cosBasisPlus||_basisCode==cosBasisMinus)&&tau==0.)) {
    Double_t xscale = root2*(sigma*ssf);
    return 0.5*(erf((x.max()-(mean*msf))/xscale)-erf((x.min()-(mean*msf))/xscale));
  }

  Double_t omega = ((RooAbsReal*)basis().getParameter(2))->getVal() ;

  // *** 2nd form: unity, used for sinBasis and cosBasis with tau=0 (PDF is zero) ***
  if (tau==0&&omega!=0) return 1. ;

  // *** 3rd form: Convolution with exp(-t/tau), used for expBasis and cosBasis(omega=0) ***
  Double_t sign = (_basisCode==expBasisPlus)?-1:1 ;
  Double_t c = (sigma*ssf)/(root2*tau) ;
  Double_t xpmin = sign*(x.min()-(mean*msf))/tau ;
  Double_t xpmax = sign*(x.max()-(mean*msf))/tau ;
  Double_t umin = xpmin/(2*c) ;
  Double_t umax = xpmax/(2*c) ;
  if (_basisCode==expBasisPlus||_basisCode==expBasisMinus ||
    ((_basisCode==cosBasisPlus||_basisCode==cosBasisPlus)&&omega==0.)) {
    Double_t result = sign * tau * ( erf(umax) - erf(umin) +
                                      exp(c*c) * ( exp(xpmax)*erfc(umax+c)
						 - exp(xpmin)*erfc(umin+c) )) ;
    return result ;
  }

  // *** 4th form: Convolution with exp(-t/tau)*sin(omega*t), used for sinBasis(omega<>0,tau<>0) ***
  Double_t swt = omega * tau * sign ;
  RooComplex evalDif(evalCerf(swt,umax,c) - evalCerf(swt,umin,c)) ;
  if (_basisCode==sinBasisPlus||_basisCode==sinBasisMinus) {
    Double_t result = (swt==0)? 1.0
                    : (tau*sign/(1+swt*swt) * ( evalDif.im() - swt*evalDif.re() + erf(umax) - erf(umin) )) ;
    return result ;
  }

  // *** 5th form: Convolution with exp(-t/tau)*cos(omega*t), used for cosBasis(omega<>0) ***
  if (_basisCode==cosBasisPlus||_basisCode==cosBasisMinus) {
    Double_t result = tau*sign/(1+swt*swt) * ( evalDif.re() + swt*evalDif.im() + erf(umax) - erf(umin) ) ;
    return result ;
  }

  assert(0) ;
  return 0 ;
}

RooComplex RooGaussModel::evalCerfApprox(Double_t swt, Double_t u, Double_t c) const
{
  // use the approximation: erf(z) = exp(-z*z)/(sqrt(pi)*z)
  // to explicitly cancel the divergent exp(y*y) behaviour of
  // CWERF for z = x + i y with large negative y

  static Double_t rootpi= sqrt(atan2(0,-1));
  RooComplex z(swt*c,u+c);
  RooComplex zc(u+c,-swt*c);
  RooComplex zsq= z*z;
  RooComplex v= -zsq - u*u;

  return v.exp()*(-zsq.exp()/(zc*rootpi) + 1)*2 ;
}

<commit_msg><commit_after>/*****************************************************************************
 * Project: BaBar detector at the SLAC PEP-II B-factory
 * Package: RooFitCore
 *    File: $Id: RooGaussModel.cc,v 1.8 2001/08/23 01:23:35 verkerke Exp $
 * Authors:
 *   WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu
 * History:
 *   05-Jun-2001 WV Created initial version
 *
 * Copyright (C) 2001 University of California
 *****************************************************************************/

// -- CLASS DESCRIPTION --
//

#include <iostream.h>
#include "RooFitModels/RooGaussModel.hh"
#include "RooFitCore/RooMath.hh"

ClassImp(RooGaussModel)
;

RooGaussModel::RooGaussModel(const char *name, const char *title, RooRealVar& x,
			     RooAbsReal& _mean, RooAbsReal& _sigma,
			     RooAbsReal& _meanSF, RooAbsReal& _sigmaSF) :
  RooResolutionModel(name,title,x),
  mean("mean","Mean",this,_mean),
  sigma("sigma","Width",this,_sigma),
  msf("msf","Mean Scale Factor",this,_meanSF),
  ssf("ssf","Sigma Scale Factor",this,_sigmaSF)
{
}

RooGaussModel::RooGaussModel(const RooGaussModel& other, const char* name) :
  RooResolutionModel(other,name),
  mean("mean",this,other.mean),
  sigma("sigma",this,other.sigma),
  msf("msf",this,other.msf),
  ssf("ssf",this,other.ssf)
{
}

RooGaussModel::~RooGaussModel()
{
  // Destructor
}

Int_t RooGaussModel::basisCode(const char* name) const
{
  if (!TString("exp(-abs(@0)/@1)").CompareTo(name)) return expBasisPlus ;
  if (!TString("exp(-abs(-@0)/@1)").CompareTo(name)) return expBasisMinus ;
  if (!TString("exp(-abs(@0)/@1)*sin(@0*@2)").CompareTo(name)) return sinBasisPlus ;
  if (!TString("exp(-abs(-@0)/@1)*sin(@0*@2)").CompareTo(name)) return sinBasisMinus ;
  if (!TString("exp(-abs(@0)/@1)*cos(@0*@2)").CompareTo(name)) return cosBasisPlus ;
  if (!TString("exp(-abs(-@0)/@1)*cos(@0*@2)").CompareTo(name)) return cosBasisMinus ;
  return 0 ;
}

Double_t RooGaussModel::evaluate() const
{
  // *** 1st form: Straight Gaussian, used for unconvoluted PDF or expBasis with 0 lifetime ***
  static Double_t root2(sqrt(2)) ;
  static Double_t root2pi(sqrt(2*atan2(0,-1))) ;

  Double_t tau = (_basisCode!=noBasis)?((RooAbsReal*)basis().getParameter(1))->getVal():0 ;

  if (_basisCode==noBasis ||
      ((_basisCode==expBasisPlus||_basisCode==expBasisMinus||
	_basisCode==cosBasisPlus||_basisCode==cosBasisMinus)&&tau==0.)) {
    Double_t xprime = (x-(mean*msf))/(sigma*ssf) ;
    if (_verboseEval>2) cout << "RooGaussModel::evaluate(" << GetName() << ") 1st form" << endl ;
    return exp(-0.5*xprime*xprime)/(sigma*ssf*root2pi) ;
  }

  // *** 2nd form: 0, used for sinBasis and cosBasis with tau=0 ***
  if (tau==0) {
    if (_verboseEval>2) cout << "RooGaussModel::evaluate(" << GetName() << ") 2nd form" << endl ;
    return 0. ;
  }

  // *** 3nd form: Convolution with exp(-t/tau), used for expBasis and cosBasis(omega=0) ***
  Double_t sign = (_basisCode==expBasisPlus||_basisCode==sinBasisPlus||_basisCode==cosBasisPlus)?-1:1 ;
  Double_t omega = ((RooAbsReal*)basis().getParameter(2))->getVal() ;
  Double_t xprime = sign*(x-(mean*msf))/tau ;
  Double_t c = (sigma*ssf)/(root2*tau) ;
  Double_t u = xprime/(2*c) ;

  if ( _basisCode==expBasisPlus || _basisCode==expBasisMinus ||
    ((_basisCode==cosBasisPlus||_basisCode==cosBasisMinus)&&omega==0.)) {
    if (_verboseEval>2) cout << "RooGaussModel::evaluate(" << GetName() << ") 3d form tau=" << tau << endl ;
    return exp(xprime+c*c) * erfc(u+c) ;
  }

  // *** 4th form: Convolution with exp(-t/tau)*sin(omega*t), used for sinBasis(omega<>0,tau<>0) ***
  Double_t swt = sign * omega *tau ;
  if (_basisCode==sinBasisPlus||_basisCode==sinBasisMinus) {
    if (_verboseEval>2) cout << "RooGaussModel::evaluate(" << GetName() << ") 4th form" << endl ;
    return (swt==0.) ? 0. : evalCerfIm(swt,u,c) ;
  }

  // *** 5th form: Convolution with exp(-t/tau)*cos(omega*t), used for cosBasis(omega<>0) ***
  if (_basisCode==cosBasisPlus||_basisCode==cosBasisMinus) {
    if (_verboseEval>2) cout << "RooGaussModel::evaluate(" << GetName()
			     << ") 5th form omega = " << omega << ", tau = " << tau << endl ;
    return evalCerfRe(swt,u,c) ;
  }

  assert(0) ;
  return 0 ;
}

Int_t RooGaussModel::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars) const
{
  switch(_basisCode) {

  // Analytical integration capability of raw PDF
  case noBasis:
    if (matchArgs(allVars,analVars,convVar())) return 1 ;
    break ;

  // Analytical integration capability of convoluted PDF
  case expBasisPlus:
  case expBasisMinus:
  case sinBasisPlus:
  case sinBasisMinus:
  case cosBasisPlus:
  case cosBasisMinus:
    if (matchArgs(allVars,analVars,convVar())) return 1 ;
    break ;
  }

  return 0 ;
}

Double_t RooGaussModel::analyticalIntegral(Int_t code) const
{
  static Double_t root2 = sqrt(2) ;
  static Double_t rootPiBy2 = sqrt(atan2(0.0,-1.0)/2.0);

  // No integration
  if (code==0) return getVal() ;

  // Code must be 0 or 1
  assert(code==1) ;

  // *** 1st form: Straight Gaussian, used for unconvoluted PDF or expBasis with 0 lifetime ***
  Double_t tau = (_basisCode!=noBasis)?((RooAbsReal*)basis().getParameter(1))->getVal():0 ;
  if (_basisCode==noBasis ||
      ((_basisCode==expBasisPlus||_basisCode==expBasisMinus||
	_basisCode==cosBasisPlus||_basisCode==cosBasisMinus)&&tau==0.)) {
    Double_t xscale = root2*(sigma*ssf);
    return 0.5*(erf((x.max()-(mean*msf))/xscale)-erf((x.min()-(mean*msf))/xscale));
  }

  Double_t omega = ((RooAbsReal*)basis().getParameter(2))->getVal() ;

  // *** 2nd form: unity, used for sinBasis and cosBasis with tau=0 (PDF is zero) ***
  if (tau==0&&omega!=0) return 1. ;

  // *** 3rd form: Convolution with exp(-t/tau), used for expBasis and cosBasis(omega=0) ***
  Double_t sign = (_basisCode==expBasisPlus)?-1:1 ;
  Double_t c = (sigma*ssf)/(root2*tau) ;
  Double_t xpmin = sign*(x.min()-(mean*msf))/tau ;
  Double_t xpmax = sign*(x.max()-(mean*msf))/tau ;
  Double_t umin = xpmin/(2*c) ;
  Double_t umax = xpmax/(2*c) ;
  if (_basisCode==expBasisPlus||_basisCode==expBasisMinus ||
    ((_basisCode==cosBasisPlus||_basisCode==cosBasisPlus)&&omega==0.)) {
    Double_t result = sign * tau * ( erf(umax) - erf(umin) +
                                      exp(c*c) * ( exp(xpmax)*erfc(umax+c)
						 - exp(xpmin)*erfc(umin+c) )) ;
    return result ;
  }

  // *** 4th form: Convolution with exp(-t/tau)*sin(omega*t), used for sinBasis(omega<>0,tau<>0) ***
  Double_t swt = omega * tau * sign ;
  RooComplex evalDif(evalCerf(swt,umax,c) - evalCerf(swt,umin,c)) ;
  if (_basisCode==sinBasisPlus||_basisCode==sinBasisMinus) {
    Double_t result = (swt==0)? 1.0
                    : (tau*sign/(1+swt*swt) * ( evalDif.im() - swt*evalDif.re() + erf(umax) - erf(umin) )) ;
    return result ;
  }

  // *** 5th form: Convolution with exp(-t/tau)*cos(omega*t), used for cosBasis(omega<>0) ***
  if (_basisCode==cosBasisPlus||_basisCode==cosBasisMinus) {
    Double_t result = tau*sign/(1+swt*swt) * ( evalDif.re() + swt*evalDif.im() + erf(umax) - erf(umin) ) ;
    return result ;
  }

  assert(0) ;
  return 0 ;
}

RooComplex RooGaussModel::evalCerfApprox(Double_t swt, Double_t u, Double_t c) const
{
  // use the approximation: erf(z) = exp(-z*z)/(sqrt(pi)*z)
  // to explicitly cancel the divergent exp(y*y) behaviour of
  // CWERF for z = x + i y with large negative y

  static Double_t rootpi= sqrt(atan2(0,-1));
  RooComplex z(swt*c,u+c);
  RooComplex zc(u+c,-swt*c);
  RooComplex zsq= z*z;
  RooComplex v= -zsq - u*u;

  return v.exp()*(-zsq.exp()/(zc*rootpi) + 1)*2 ;
}

<|endoftext|>


<commit_before>/*****************************************************************************
 * Project: BaBar detector at the SLAC PEP-II B-factory
 * Package: RooFitTools
 *    File: $Id: RooPolynomial.cc,v 1.2 2001/09/26 21:44:06 verkerke Exp $
 * Authors:
 *   DK, David Kirkby, Stanford University, kirkby@hep.stanford.edu
 * History:
 *   05-Jan-2000 DK Created initial version from RooPolynomialProb
 *   02-Jul-2000 DK Add analytic optimizations for generating toy MC
 *                  at low orders
 *
 * Copyright (C) 1999 Stanford University
 *****************************************************************************/

// -- CLASS DESCRIPTION [PDF] --

#include <iostream.h>
#include <math.h>

#include "RooFitModels/RooPolynomial.hh"
#include "RooFitCore/RooAbsReal.hh"
#include "RooFitCore/RooRealVar.hh"
#include "RooFitCore/RooArgList.hh"

ClassImp(RooPolynomial)
;

RooPolynomial::RooPolynomial()
{
  _coefIter = _coefList.createIterator() ;
}

RooPolynomial::RooPolynomial(const char* name, const char* title,
			     RooAbsReal& x, const RooArgList& coefList, Int_t lowestOrder) :
  RooAbsPdf(name, title),
  _x("x", "Dependent", this, x),
  _coefList("coefList","List of coefficients",this),
  _lowestOrder(lowestOrder)
{
  // Constructor
  _coefIter = coefList.createIterator() ;

  // Check lowest order
  if (_lowestOrder<1) {
    cout << "RooPolynomial::ctor(" << GetName()
	 << ") WARNING: lowestOrder must be >=1, setting value to 1" << endl ;
    _lowestOrder=1 ;
  }

  TIterator* coefIter = coefList.createIterator() ;
  RooAbsArg* coef ;
  while(coef = (RooAbsArg*)coefIter->Next()) {
    if (!dynamic_cast<RooAbsReal*>(coef)) {
      cout << "RooPolynomial::ctor(" << GetName() << ") ERROR: coefficient " << coef->GetName()
	   << " is not of type RooAbsReal" << endl ;
      assert(0) ;
    }
    _coefList.add(*coef) ;
  }
  delete coefIter ;
}

RooPolynomial::RooPolynomial(const char* name, const char* title,
                           RooAbsReal& x) :
  RooAbsPdf(name, title),
  _x("x", "Dependent", this, x),
  _coefList("coefList","List of coefficients",this),
  _lowestOrder(1)
{
  _coefIter = _coefList.createIterator() ;
}

RooPolynomial::RooPolynomial(const RooPolynomial& other, const char* name) :
  RooAbsPdf(other, name),
  _x("x", this, other._x),
  _coefList("coefList",this,other._coefList),
  _lowestOrder(other._lowestOrder)
{
  // Copy constructor
  _coefIter = _coefList.createIterator() ;
}

Double_t RooPolynomial::evaluate() const
{
  Double_t sum(1) ;
  Int_t order(_lowestOrder) ;
  _coefIter->Reset() ;

  RooAbsReal* coef ;
  const RooArgSet* nset = _coefList.nset() ;
  while(coef=(RooAbsReal*)_coefIter->Next()) {
    sum += coef->getVal(nset)*pow(_x,order++) ;
  }

  return sum;
}

Int_t RooPolynomial::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars) const
{
  if (matchArgs(allVars, analVars, _x)) return 1;
  return 0;
}

Double_t RooPolynomial::analyticalIntegral(Int_t code) const
{
  assert(code==1) ;

  Double_t sum(_x.max()-_x.min()) ;

  const RooArgSet* nset = _coefList.nset() ;
  Int_t order(_lowestOrder) ;
  _coefIter->Reset() ;
  RooAbsReal* coef ;

  // Primitive = sum(k) coef_k * 1/(k+1) x^(k+1)
  while(coef=(RooAbsReal*)_coefIter->Next()) {
    sum += coef->getVal(nset)*(pow(_x.max(),order+1)-pow(_x.min(),order+1))/(order+1) ;
    order++ ;
  }

  return sum;

}
<commit_msg><commit_after>/*****************************************************************************
 * Project: BaBar detector at the SLAC PEP-II B-factory
 * Package: RooFitTools
 *    File: $Id: RooPolynomial.cc,v 1.3 2001/10/08 05:21:19 verkerke Exp $
 * Authors:
 *   DK, David Kirkby, Stanford University, kirkby@hep.stanford.edu
 * History:
 *   05-Jan-2000 DK Created initial version from RooPolynomialProb
 *   02-Jul-2000 DK Add analytic optimizations for generating toy MC
 *                  at low orders
 *
 * Copyright (C) 1999 Stanford University
 *****************************************************************************/

// -- CLASS DESCRIPTION [PDF] --

#include <iostream.h>
#include <math.h>

#include "RooFitModels/RooPolynomial.hh"
#include "RooFitCore/RooAbsReal.hh"
#include "RooFitCore/RooRealVar.hh"
#include "RooFitCore/RooArgList.hh"

ClassImp(RooPolynomial)
;

RooPolynomial::RooPolynomial()
{
  _coefIter = _coefList.createIterator() ;
}

RooPolynomial::RooPolynomial(const char* name, const char* title,
			     RooAbsReal& x, const RooArgList& coefList, Int_t lowestOrder) :
  RooAbsPdf(name, title),
  _x("x", "Dependent", this, x),
  _coefList("coefList","List of coefficients",this),
  _lowestOrder(lowestOrder)
{
  // Constructor
  _coefIter = _coefList.createIterator() ;

  // Check lowest order
  if (_lowestOrder<1) {
    cout << "RooPolynomial::ctor(" << GetName()
	 << ") WARNING: lowestOrder must be >=1, setting value to 1" << endl ;
    _lowestOrder=1 ;
  }

  TIterator* coefIter = coefList.createIterator() ;
  RooAbsArg* coef ;
  while(coef = (RooAbsArg*)coefIter->Next()) {
    if (!dynamic_cast<RooAbsReal*>(coef)) {
      cout << "RooPolynomial::ctor(" << GetName() << ") ERROR: coefficient " << coef->GetName()
	   << " is not of type RooAbsReal" << endl ;
      assert(0) ;
    }
    _coefList.add(*coef) ;
  }
  delete coefIter ;
}

RooPolynomial::RooPolynomial(const char* name, const char* title,
                           RooAbsReal& x) :
  RooAbsPdf(name, title),
  _x("x", "Dependent", this, x),
  _coefList("coefList","List of coefficients",this),
  _lowestOrder(1)
{
  _coefIter = _coefList.createIterator() ;
}

RooPolynomial::RooPolynomial(const RooPolynomial& other, const char* name) :
  RooAbsPdf(other, name),
  _x("x", this, other._x),
  _coefList("coefList",this,other._coefList),
  _lowestOrder(other._lowestOrder)
{
  // Copy constructor
  _coefIter = _coefList.createIterator() ;
}

Double_t RooPolynomial::evaluate() const
{
  Double_t sum(1) ;
  Int_t order(_lowestOrder) ;
  _coefIter->Reset() ;

  RooAbsReal* coef ;
  const RooArgSet* nset = _coefList.nset() ;
  while(coef=(RooAbsReal*)_coefIter->Next()) {
    sum += coef->getVal(nset)*pow(_x,order++) ;
  }

  return sum;
}

Int_t RooPolynomial::getAnalyticalIntegral(RooArgSet& allVars, RooArgSet& analVars) const
{
  if (matchArgs(allVars, analVars, _x)) return 1;
  return 0;
}

Double_t RooPolynomial::analyticalIntegral(Int_t code) const
{
  assert(code==1) ;

  Double_t sum(_x.max()-_x.min()) ;

  const RooArgSet* nset = _coefList.nset() ;
  Int_t order(_lowestOrder) ;
  _coefIter->Reset() ;
  RooAbsReal* coef ;

  // Primitive = sum(k) coef_k * 1/(k+1) x^(k+1)
  while(coef=(RooAbsReal*)_coefIter->Next()) {
    sum += coef->getVal(nset)*(pow(_x.max(),order+1)-pow(_x.min(),order+1))/(order+1) ;
    order++ ;
  }

  return sum;

}
<|endoftext|>


<commit_before>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "SoundDS.h"
#include "AudioDS.h"
#include "audio/SoundData.h"
#include "core/Engine.h"
#include "utils/Log.h"

namespace ouzel
{
    namespace audio
    {
        SoundDS::SoundDS()
        {
        }

        SoundDS::~SoundDS()
        {
            if (buffer3D) buffer3D->Release();
            if (buffer) buffer->Release();
        }

        bool SoundDS::update()
        {
            std::lock_guard<std::mutex> lock(uploadMutex);

            if (dirty & DIRTY_SOUND_DATA)
            {
                if (soundData)
                {
                    if (buffer3D)
                    {
                        buffer3D->Release();
                        buffer3D = nullptr;
                    }

                    if (buffer)
                    {
                        buffer->Release();
                        buffer = nullptr;
                    }

                    IDirectSoundBuffer* tempBuffer = nullptr;

                    WAVEFORMATEX waveFormat;
                    waveFormat.wFormatTag = soundData->getFormatTag();
                    waveFormat.nChannels = soundData->getChannels();
                    waveFormat.nSamplesPerSec = soundData->getSamplesPerSecond();
                    waveFormat.wBitsPerSample = 16;
                    waveFormat.nBlockAlign = waveFormat.nChannels * (waveFormat.wBitsPerSample / 8);
                    waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
                    waveFormat.cbSize = 0;

                    const std::vector<uint8_t> data = soundData->getData();

                    DSBUFFERDESC bufferDesc;
                    bufferDesc.dwSize = sizeof(bufferDesc);
                    bufferDesc.dwFlags = DSBCAPS_CTRLVOLUME;

                    if (soundData->getChannels() < 2)
                    {
                        bufferDesc.dwFlags |= DSBCAPS_CTRL3D;
                    }

                    bufferDesc.dwBufferBytes = static_cast<DWORD>(data.size());
                    bufferDesc.dwReserved = 0;
                    bufferDesc.lpwfxFormat = &waveFormat;
                    bufferDesc.guid3DAlgorithm = GUID_NULL;

                    AudioDS* audioDS = static_cast<AudioDS*>(sharedEngine->getAudio());
                    HRESULT hr = audioDS->getDirectSound()->CreateSoundBuffer(&bufferDesc, &tempBuffer, nullptr);
                    if (FAILED(hr))
                    {
                        Log(Log::Level::ERR) << "Failed to create DirectSound buffer, error: " << hr;
                        return false;
                    }

                    hr = tempBuffer->QueryInterface(IID_IDirectSoundBuffer8, reinterpret_cast<void**>(&buffer));
                    if (FAILED(hr))
                    {
                        Log(Log::Level::ERR) << "Failed to create DirectSound buffer, error: " << hr;
                        tempBuffer->Release();
                        return false;
                    }

                    tempBuffer->Release();

                    uint8_t* bufferPointer;
                    DWORD bufferSize;
                    hr = buffer->Lock(0, bufferDesc.dwBufferBytes, reinterpret_cast<void**>(&bufferPointer), &bufferSize, nullptr, 0, 0);
                    if (FAILED(hr))
                    {
                        Log(Log::Level::ERR) << "Failed to lock DirectSound buffer, error: " << hr;
                        return false;
                    }

                    std::copy(data.begin(), data.end(), bufferPointer);

                    hr = buffer->Unlock(bufferPointer, bufferSize, nullptr, 0);
                    if (FAILED(hr))
                    {
                        Log(Log::Level::ERR) << "Failed to unlock DirectSound buffer, error: " << hr;
                        return false;
                    }

                    if (bufferDesc.dwFlags & DSBCAPS_CTRL3D)
                    {
                        hr = buffer->QueryInterface(IID_IDirectSound3DBuffer8, reinterpret_cast<void**>(&buffer3D));
                        if (FAILED(hr))
                        {
                            Log(Log::Level::ERR) << "Failed to get DirectSound 3D buffer, error: " << hr;
                            return false;
                        }
                    }
                }
            }

            if (dirty & DIRTY_PITCH)
            {
                if (soundData)
                {
                    DWORD frequency = static_cast<DWORD>(soundData->getSamplesPerSecond() * pitch);
                    buffer->SetFrequency(frequency);
                }
            }

            if (dirty & DIRTY_GAIN)
            {
                LONG volume = DSBVOLUME_MIN + static_cast<LONG>((DSBVOLUME_MAX - DSBVOLUME_MIN) * gain);
                buffer->SetVolume(volume);
            }

            if (dirty & DIRTY_POSITION)
            {
                if (buffer3D)
                {
                    HRESULT hr = buffer3D->SetPosition(position.v[0], position.v[1], position.v[2], DS3D_IMMEDIATE);
                    if (FAILED(hr))
                    {
                        Log(Log::Level::ERR) << "Failed to set DirectSound buffer position, error: " << hr;
                        return false;
                    }
                }
            }

            if (dirty & DIRTY_PLAY_STATE)
            {
                if (buffer)
                {
                    if (shouldPlay)
                    {
                        if (reset)
                        {
                            HRESULT hr = buffer->SetCurrentPosition(0);
                            if (FAILED(hr))
                            {
                                Log(Log::Level::ERR) << "Failed to set DirectSound buffer current position, error: " << hr;
                                return false;
                            }
                        }

                        HRESULT hr = buffer->Play(0, 0, 0);
                        if (FAILED(hr))
                        {
                            Log(Log::Level::ERR) << "Failed to play DirectSound buffer, error: " << hr;
                            return false;
                        }
                    }
                    else
                    {
                        HRESULT hr = buffer->Stop();
                        if (FAILED(hr))
                        {
                            Log(Log::Level::ERR) << "Failed to stop DirectSound buffer, error: " << hr;
                            return false;
                        }

                        hr = buffer->SetCurrentPosition(0);
                        if (FAILED(hr))
                        {
                            Log(Log::Level::ERR) << "Failed to set DirectSound buffer current position, error: " << hr;
                            return false;
                        }
                    }
                }
            }

            dirty = 0;

            return true;
        }
    } // namespace audio
} // namespace ouzel
<commit_msg>Add error checks and fully initialize DirectSound source<commit_after>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "SoundDS.h"
#include "AudioDS.h"
#include "audio/SoundData.h"
#include "core/Engine.h"
#include "utils/Log.h"

namespace ouzel
{
    namespace audio
    {
        SoundDS::SoundDS()
        {
        }

        SoundDS::~SoundDS()
        {
            if (buffer3D) buffer3D->Release();
            if (buffer) buffer->Release();
        }

        bool SoundDS::update()
        {
            std::lock_guard<std::mutex> lock(uploadMutex);

            if (dirty & DIRTY_SOUND_DATA)
            {
                if (soundData)
                {
                    if (buffer3D)
                    {
                        buffer3D->Release();
                        buffer3D = nullptr;
                    }

                    if (buffer)
                    {
                        buffer->Release();
                        buffer = nullptr;
                    }

                    IDirectSoundBuffer* tempBuffer = nullptr;

                    WAVEFORMATEX waveFormat;
                    waveFormat.wFormatTag = soundData->getFormatTag();
                    waveFormat.nChannels = soundData->getChannels();
                    waveFormat.nSamplesPerSec = soundData->getSamplesPerSecond();
                    waveFormat.wBitsPerSample = 16;
                    waveFormat.nBlockAlign = waveFormat.nChannels * (waveFormat.wBitsPerSample / 8);
                    waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
                    waveFormat.cbSize = 0;

                    const std::vector<uint8_t> data = soundData->getData();

                    DSBUFFERDESC bufferDesc;
                    bufferDesc.dwSize = sizeof(bufferDesc);
                    bufferDesc.dwFlags = DSBCAPS_CTRLVOLUME;

                    if (soundData->getChannels() < 2)
                    {
                        bufferDesc.dwFlags |= DSBCAPS_CTRL3D;
                    }

                    bufferDesc.dwBufferBytes = static_cast<DWORD>(data.size());
                    bufferDesc.dwReserved = 0;
                    bufferDesc.lpwfxFormat = &waveFormat;
                    bufferDesc.guid3DAlgorithm = GUID_NULL;

                    AudioDS* audioDS = static_cast<AudioDS*>(sharedEngine->getAudio());
                    HRESULT hr = audioDS->getDirectSound()->CreateSoundBuffer(&bufferDesc, &tempBuffer, nullptr);
                    if (FAILED(hr))
                    {
                        Log(Log::Level::ERR) << "Failed to create DirectSound buffer, error: " << hr;
                        return false;
                    }

                    hr = tempBuffer->QueryInterface(IID_IDirectSoundBuffer8, reinterpret_cast<void**>(&buffer));
                    if (FAILED(hr))
                    {
                        Log(Log::Level::ERR) << "Failed to create DirectSound buffer, error: " << hr;
                        tempBuffer->Release();
                        return false;
                    }

                    tempBuffer->Release();

                    uint8_t* bufferPointer;
                    DWORD bufferSize;
                    hr = buffer->Lock(0, bufferDesc.dwBufferBytes, reinterpret_cast<void**>(&bufferPointer), &bufferSize, nullptr, 0, 0);
                    if (FAILED(hr))
                    {
                        Log(Log::Level::ERR) << "Failed to lock DirectSound buffer, error: " << hr;
                        return false;
                    }

                    std::copy(data.begin(), data.end(), bufferPointer);

                    hr = buffer->Unlock(bufferPointer, bufferSize, nullptr, 0);
                    if (FAILED(hr))
                    {
                        Log(Log::Level::ERR) << "Failed to unlock DirectSound buffer, error: " << hr;
                        return false;
                    }

                    if (pitch != 1.0f)
                    {
                        DWORD frequency = static_cast<DWORD>(soundData->getSamplesPerSecond() * pitch);
                        hr = buffer->SetFrequency(frequency);
                        if (FAILED(hr))
                        {
                            Log(Log::Level::ERR) << "Failed to set DirectSound buffer frequency, error: " << hr;
                            return false;
                        }
                    }

                    if (gain != 1.0f)
                    {
                        LONG volume = DSBVOLUME_MIN + static_cast<LONG>((DSBVOLUME_MAX - DSBVOLUME_MIN) * gain);
                        hr = buffer->SetVolume(volume);
                        if (FAILED(hr))
                        {
                            Log(Log::Level::ERR) << "Failed to set DirectSound buffer volume, error: " << hr;
                            return false;
                        }
                    }

                    if (bufferDesc.dwFlags & DSBCAPS_CTRL3D)
                    {
                        hr = buffer->QueryInterface(IID_IDirectSound3DBuffer8, reinterpret_cast<void**>(&buffer3D));
                        if (FAILED(hr))
                        {
                            Log(Log::Level::ERR) << "Failed to get DirectSound 3D buffer, error: " << hr;
                            return false;
                        }

                        hr = buffer3D->SetPosition(position.v[0], position.v[1], position.v[2], DS3D_IMMEDIATE);
                        if (FAILED(hr))
                        {
                            Log(Log::Level::ERR) << "Failed to set DirectSound buffer position, error: " << hr;
                            return false;
                        }
                    }
                }
            }

            if (dirty & DIRTY_PITCH)
            {
                if (buffer && soundData)
                {
                    DWORD frequency = static_cast<DWORD>(soundData->getSamplesPerSecond() * pitch);
                    HRESULT hr = buffer->SetFrequency(frequency);
                    if (FAILED(hr))
                    {
                        Log(Log::Level::ERR) << "Failed to set DirectSound buffer frequency, error: " << hr;
                        return false;
                    }
                }
            }

            if (dirty & DIRTY_GAIN)
            {
                if (buffer)
                {
                    LONG volume = DSBVOLUME_MIN + static_cast<LONG>((DSBVOLUME_MAX - DSBVOLUME_MIN) * gain);
                    HRESULT hr = buffer->SetVolume(volume);
                    if (FAILED(hr))
                    {
                        Log(Log::Level::ERR) << "Failed to set DirectSound buffer volume, error: " << hr;
                        return false;
                    }
                }
            }

            if (dirty & DIRTY_POSITION)
            {
                if (buffer3D)
                {
                    HRESULT hr = buffer3D->SetPosition(position.v[0], position.v[1], position.v[2], DS3D_IMMEDIATE);
                    if (FAILED(hr))
                    {
                        Log(Log::Level::ERR) << "Failed to set DirectSound buffer position, error: " << hr;
                        return false;
                    }
                }
            }

            if (dirty & DIRTY_PLAY_STATE)
            {
                if (buffer)
                {
                    if (shouldPlay)
                    {
                        if (reset)
                        {
                            HRESULT hr = buffer->SetCurrentPosition(0);
                            if (FAILED(hr))
                            {
                                Log(Log::Level::ERR) << "Failed to set DirectSound buffer current position, error: " << hr;
                                return false;
                            }
                        }

                        HRESULT hr = buffer->Play(0, 0, 0);
                        if (FAILED(hr))
                        {
                            Log(Log::Level::ERR) << "Failed to play DirectSound buffer, error: " << hr;
                            return false;
                        }
                    }
                    else
                    {
                        HRESULT hr = buffer->Stop();
                        if (FAILED(hr))
                        {
                            Log(Log::Level::ERR) << "Failed to stop DirectSound buffer, error: " << hr;
                            return false;
                        }

                        hr = buffer->SetCurrentPosition(0);
                        if (FAILED(hr))
                        {
                            Log(Log::Level::ERR) << "Failed to set DirectSound buffer current position, error: " << hr;
                            return false;
                        }
                    }
                }
            }

            dirty = 0;

            return true;
        }
    } // namespace audio
} // namespace ouzel
<|endoftext|>


<commit_before>/** \brief Tool for title, author and full-text extraction from XMl files corresponding to the Journal Publishing DTD.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2018 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>
#include <stdexcept>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include "FileUtil.h"
#include "util.h"
#include "XMLParser.h"

namespace {

[[noreturn]] void Usage() {
    std::cerr << "Usage: " << ::progname << " xml_input plain_test_output\n";
    std::exit(EXIT_FAILURE);
}

bool ExtractTitle(XMLParser * const xml_parser, std::string * const article_title) {
    article_title->clear();

    if (not xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, "article-title"))
        return false;

    XMLParser::XMLPart xml_part;
    while (xml_parser->getNext(&xml_part)) {
        if (xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG and xml_part.data_ == "article-title")
            return not article_title->empty();
        if (xml_part.type_ == XMLParser::XMLPart::CHARACTERS)
            *article_title += xml_part.data_;
    }

    return false;
}

bool ExtractAuthor(XMLParser * const xml_parser, std::vector<std::string> * const article_authors) {
    if (not xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, "surname"))
        return false;

    XMLParser::XMLPart xml_part;
    if (not xml_parser->getNext(&xml_part) or xml_part.type_ != XMLParser::XMLPart::CHARACTERS)
        return false;
    std::string surname(xml_part.data_);

    while (xml_parser->getNext(&xml_part)) {
        if (xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG and xml_part.data_ == "contrib") {
            article_authors->emplace_back(surname);
            return true;
        } else if (xml_part.type_ == XMLParser::XMLPart::OPENING_TAG and xml_part.data_ == "given-names") {
            if (not xml_parser->getNext(&xml_part) or xml_part.type_ != XMLParser::XMLPart::CHARACTERS)
                return false;
            article_authors->emplace_back(xml_part.data_ + " " + surname);
            return true;
        }
    }

    return false;
}

bool ExtractAuthors(XMLParser * const xml_parser, std::vector<std::string> * const article_authors, std::string * const text_opening_tag) {
    XMLParser::XMLPart xml_part;
    while (xml_parser->getNext(&xml_part)) {
        if (xml_part.type_ == XMLParser::XMLPart::OPENING_TAG) {
            if (xml_part.data_ == "abstract" or xml_part.data_ == "body") {
                *text_opening_tag = xml_part.data_;
                return true;
            }
            else if (xml_part.data_ == "contrib") {
                const auto contrib_type_and_value(xml_part.attributes_.find("contrib-type"));
                if (contrib_type_and_value != xml_part.attributes_.cend() and contrib_type_and_value->second == "author") {
                    if (not ExtractAuthor(xml_parser, article_authors))
                        return false;
                }
            }
        }
    }

    return false;
}

bool ExtractTextHelper(XMLParser * const xml_parser, const std::string &closing_tag, std::string * const text) {
    XMLParser::XMLPart xml_part;
    while (xml_parser->getNext(&xml_part)) {
        if (xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG and xml_part.data_ == closing_tag)
            return true;
        if (xml_part.type_ == XMLParser::XMLPart::CHARACTERS)
            *text += xml_part.data_;
    }

    return false;
}

// Extracts abstracts and bodies.
bool ExtractText(XMLParser * const xml_parser, const std::string &text_opening_tag, std::string * const text) {
    if (not ExtractTextHelper(xml_parser, text_opening_tag, text))
        return false;
    *text += '\n';

    if (text_opening_tag == "body")
        return true;

    if (xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, "body")) {
        if (not ExtractTextHelper(xml_parser, "body", text))
            return false;
        *text += '\n';
    }

    return not text->empty();
}

void ProcessDocument(XMLParser * const xml_parser, File * const plain_text_output) {
    std::string article_title;
    if (not ExtractTitle(xml_parser, &article_title))
        LOG_ERROR("no article title found!");
    std::cout << "Article title is " << article_title << '\n';

    std::vector<std::string> article_authors;
    std::string text_opening_tag;
    if (not ExtractAuthors(xml_parser, &article_authors, &text_opening_tag))
        LOG_ERROR("no article authors found or an error or end-of-document were found while trying to extract an author name!");
    std::cout << "Article authors are:\n";
    for (const auto &author : article_authors)
        std::cout << '\t' << author << '\n';

    std::string text;
    if (not ExtractText(xml_parser, text_opening_tag, &text))
        LOG_ERROR("no text found!");
    plain_text_output->write(text);
}

} // unnamed namespace

int Main(int argc, char *argv[]) {
    if (argc != 3)
        Usage();

    XMLParser xml_parser (argv[1], XMLParser::XML_FILE);
    auto plain_text_output(FileUtil::OpenOutputFileOrDie(argv[2]));
    ProcessDocument(&xml_parser, plain_text_output.get());

    return EXIT_SUCCESS;
}
<commit_msg>Holy shit, it works!!!<commit_after>/** \brief Tool for title, author and full-text extraction from XMl files corresponding to the Journal Publishing DTD.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2018 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>
#include <stdexcept>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include "ControlNumberGuesser.h"
#include "FileUtil.h"
#include "util.h"
#include "XMLParser.h"

namespace {

[[noreturn]] void Usage() {
    std::cerr << "Usage: " << ::progname << " xml_input plain_test_output\n";
    std::exit(EXIT_FAILURE);
}

bool ExtractTitle(XMLParser * const xml_parser, std::string * const article_title) {
    article_title->clear();

    if (not xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, "article-title"))
        return false;

    XMLParser::XMLPart xml_part;
    while (xml_parser->getNext(&xml_part)) {
        if (xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG and xml_part.data_ == "article-title")
            return not article_title->empty();
        if (xml_part.type_ == XMLParser::XMLPart::CHARACTERS)
            *article_title += xml_part.data_;
    }

    return false;
}

bool ExtractAuthor(XMLParser * const xml_parser, std::vector<std::string> * const article_authors) {
    if (not xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, "surname"))
        return false;

    XMLParser::XMLPart xml_part;
    if (not xml_parser->getNext(&xml_part) or xml_part.type_ != XMLParser::XMLPart::CHARACTERS)
        return false;
    std::string surname(xml_part.data_);

    while (xml_parser->getNext(&xml_part)) {
        if (xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG and xml_part.data_ == "contrib") {
            article_authors->emplace_back(surname);
            return true;
        } else if (xml_part.type_ == XMLParser::XMLPart::OPENING_TAG and xml_part.data_ == "given-names") {
            if (not xml_parser->getNext(&xml_part) or xml_part.type_ != XMLParser::XMLPart::CHARACTERS)
                return false;
            article_authors->emplace_back(xml_part.data_ + " " + surname);
            return true;
        }
    }

    return false;
}

bool ExtractAuthors(XMLParser * const xml_parser, std::vector<std::string> * const article_authors, std::string * const text_opening_tag) {
    XMLParser::XMLPart xml_part;
    while (xml_parser->getNext(&xml_part)) {
        if (xml_part.type_ == XMLParser::XMLPart::OPENING_TAG) {
            if (xml_part.data_ == "abstract" or xml_part.data_ == "body") {
                *text_opening_tag = xml_part.data_;
                return true;
            }
            else if (xml_part.data_ == "contrib") {
                const auto contrib_type_and_value(xml_part.attributes_.find("contrib-type"));
                if (contrib_type_and_value != xml_part.attributes_.cend() and contrib_type_and_value->second == "author") {
                    if (not ExtractAuthor(xml_parser, article_authors))
                        return false;
                }
            }
        }
    }

    return false;
}

bool ExtractTextHelper(XMLParser * const xml_parser, const std::string &closing_tag, std::string * const text) {
    XMLParser::XMLPart xml_part;
    while (xml_parser->getNext(&xml_part)) {
        if (xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG and xml_part.data_ == closing_tag)
            return true;
        if (xml_part.type_ == XMLParser::XMLPart::CHARACTERS)
            *text += xml_part.data_;
    }

    return false;
}

// Extracts abstracts and bodies.
bool ExtractText(XMLParser * const xml_parser, const std::string &text_opening_tag, std::string * const text) {
    if (not ExtractTextHelper(xml_parser, text_opening_tag, text))
        return false;
    *text += '\n';

    if (text_opening_tag == "body")
        return true;

    if (xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, "body")) {
        if (not ExtractTextHelper(xml_parser, "body", text))
            return false;
        *text += '\n';
    }

    return not text->empty();
}

void ProcessDocument(XMLParser * const xml_parser, const ControlNumberGuesser &control_number_guesser, File * const plain_text_output) {
    std::string article_title;
    if (not ExtractTitle(xml_parser, &article_title))
        LOG_ERROR("no article title found!");

    std::vector<std::string> article_authors;
    std::string text_opening_tag;
    if (not ExtractAuthors(xml_parser, &article_authors, &text_opening_tag))
        LOG_ERROR("no article authors found or an error or end-of-document were found while trying to extract an author name!");

    const auto matching_control_numbers(control_number_guesser.getGuessedControlNumbers(article_title, article_authors));
    if (matching_control_numbers.empty())
        LOG_ERROR("no matching control numbers found!");

    std::cout << "Matching control numbers:\n";
    for (const auto matching_control_number : matching_control_numbers)
        std::cout << '\t' << matching_control_number << '\n';

    std::string text;
    if (not ExtractText(xml_parser, text_opening_tag, &text))
        LOG_ERROR("no text found!");
    plain_text_output->write(text);
}

} // unnamed namespace

int Main(int argc, char *argv[]) {
    if (argc != 3)
        Usage();

    XMLParser xml_parser (argv[1], XMLParser::XML_FILE);
    auto plain_text_output(FileUtil::OpenOutputFileOrDie(argv[2]));
    ControlNumberGuesser control_number_guesser(ControlNumberGuesser::DO_NOT_CLEAR_DATABASES);
    ProcessDocument(&xml_parser, control_number_guesser, plain_text_output.get());

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <stdlib.h>

using namespace std;

#define FLAG_a 1
#define FLAG_l 2
#define FLAG_R 4

void permission(const struct stat buf, dirent *dirp);
string addC_str(const char *name, char d_name[]);

//function for ls -a
void ls_a(const char* path){
	DIR *dirp;
	if(NULL == (dirp = opendir(path))){
		perror("There was an error with opendir().");
		exit(1);
	}
	struct dirent *filespecs;
	errno = 0;
	while( (filespecs = readdir(dirp) ) != NULL){
		cout << filespecs -> d_name << "  " ;
	}
	if(errno != 0){
		perror("There was an error with readdir().");
		exit(1);
	}
	cout << endl;
	if(-1 == closedir(dirp)){
		perror("There was an error with closedir().");
		exit(1);
	}
	return;
}

//function for ls by itself
void ls(const char* path){
	DIR *dirp;
	if(NULL == (dirp = opendir(path))){
		perror("There was an error with opendir().");
		exit(1);
	}
	struct dirent *filespecs;
	errno = 0;
	while( (filespecs = readdir(dirp) ) != NULL){
		if (strcmp(filespecs->d_name, ".")!=0 && strcmp(filespecs->d_name, "..")!=0
			&& strcmp(filespecs->d_name, ".git") != 0){
			cout << filespecs -> d_name << "  " ;
		}
	}
	if(errno != 0){
		perror("There was an error with readdir().");
		exit(1);
	}
	cout << endl;
	if(-1 == closedir(dirp)){
		perror("There was an error with closedir().");
		exit(1);
	}
	return;
}

//function for ls -l and also when ls -a -l is called
void ls_l(const char* dir, bool isA){
	DIR *dirp;
	if(NULL == (dirp = opendir(dir))){
		perror("There was an error with opendir().");
		exit(1);
	}
	struct dirent *filespecs;
	struct stat s;
	//stat(dir, &s);
	errno = 0;
	while( (filespecs = readdir(dirp) ) != NULL){
		stat(dir, &s);
		if(isA){
			permission(s, filespecs);
		}
		else{
			if (strcmp(filespecs->d_name, ".")!=0
				&& strcmp(filespecs->d_name, "..")!=0
				&& strcmp(filespecs->d_name, ".git") != 0){
				permission(s, filespecs);
			}
		}
	}
	if(errno != 0){
		perror("There was an error with readdir().");
		exit(1);
	}
	cout << endl;
	if(-1 == closedir(dirp)){
		perror("There was an error with closedir().");
		exit(1);
	}

	return;
}

//function for -R
void ls_R(const char* dir){
	DIR *dirp;
	if(NULL == (dirp = opendir(dir))){
		perror("There was an error with opendir().");
		exit(1);
	}
	struct dirent *filespecs;
	errno = 0;

	while( (filespecs=readdir(dirp)) != NULL){
		if(filespecs-> d_name[0] != '.'){
			string path;
			path += addC_str(dir, filespecs->d_name);

			cout << filespecs->d_name << ":" <<  endl;

			if(filespecs-> d_type == DT_DIR)
				ls_R(path.c_str());

		}
		else{
			cout << filespecs->d_name << endl;

		}

	}
	if(errno != 0){
		perror("There was an error with readdir().");
		exit(1);
	}
	cout << endl;
	if(-1 == closedir(dirp)){
		perror("There was an error with closedir().");
		exit(1);
	}

	return;
}

//try to get print info function working so I can delete other functions
void printDir(const char *dir){
	DIR *dirp;
	if(NULL == (dirp = opendir(dir))){
		perror("There was an error with opendir().");
		exit(1);
	}
	struct dirent *filespecs;
	struct stat s;
	//stat(dir, &s);
	errno = 0;
	while( (filespecs = readdir(dirp) ) != NULL){
		if (strcmp(filespecs->d_name, ".")!=0 && strcmp(filespecs->d_name, "..")!=0
			&& strcmp(filespecs->d_name, ".git") != 0){
		stat(dir, &s);
		permission(s, filespecs);
		}
	}
	if(errno != 0){
		perror("There was an error with readdir().");
		exit(1);
	}
	cout << endl;
	if(-1 == closedir(dirp)){
		perror("There was an error with closedir().");
		exit(1);
	}

	return;

}

//permissions to be outputted by -l
void permission(const struct stat buf, dirent *dirp){
	//create a struct with for the time
	struct tm* file_t;
	file_t = localtime( &buf.st_mtime);
	char buffer[100];
	strftime(buffer, 100, "%h %e %R", file_t);

	//output all stat
	(buf.st_mode & S_IFDIR)? cout << "d":
	(buf.st_mode & S_IFCHR) ? cout<< 'c':
	(buf.st_mode & S_IFBLK) ? cout<< 'b':
	(buf.st_mode & S_IFIFO) ? cout<< 'f':
	(buf.st_mode & S_IFSOCK) ? cout<<'s':
	(buf.st_mode & S_IFLNK) ? cout<< 'l':

	(buf.st_mode & S_IRUSR)? cout << "r": cout << "-";
	(buf.st_mode & S_IWUSR)? cout << "w": cout << "-";
	(buf.st_mode & S_IXUSR)? cout << "x": cout << "-";

	(buf.st_mode & S_IRGRP)? cout << "r": cout << "-";
	(buf.st_mode & S_IWGRP)? cout << "w": cout << "-";
	(buf.st_mode & S_IXGRP)? cout << "x": cout << "-";

	(buf.st_mode & S_IROTH)? cout << "r": cout << "-";
	(buf.st_mode & S_IWOTH)? cout << "w": cout << "-";
	(buf.st_mode & S_IXOTH)? cout << "x": cout << "-";
	cout << " ";

	cout << " " << buf.st_nlink << " ";
	cout << getpwuid(buf.st_uid)-> pw_name << " ";
	cout << getgrgid(buf.st_gid) -> gr_name << " ";
	cout << buf.st_size << " " << buffer << " " << dirp->d_name << endl;
}

int main(int argc, char* argv[]){
	//make a vector for the directory names and filenames inputted
	//into command line
	vector<char*> dir_names;
	vector<char*> file_names;
	//char* path;

	//set flags
	int flags=0;
	int numFile=1;
	//booleans to keep track of which flags are called
	bool isA=false;
	bool isL=false;
	bool isR=false;

	//check if the arguments are flags or filenames
	for(int pos=1; pos<argc; pos++){
		if(!strcmp(argv[pos],"-a")){
			isA=true;
			flags= flags | FLAG_a;
			//ls_a(path);
		}
		else if(!strcmp(argv[pos], "-l")){
			isL=true;
			flags = flags | FLAG_l;
		}
		else if(!strcmp(argv[pos], "-R")){
			isR=true;
			flags = flags | FLAG_R;
		}
		else if(!strcmp(argv[pos],"-al") || !strcmp(argv[pos],"-la")){
			isA=true;
			isL=true;
			flags= flags | FLAG_a && FLAG_l;
			//ls_a(path);
		}
		else if(!strcmp(argv[pos],"-aR") || !strcmp(argv[pos],"-Ra")){
			isA=true;
			flags= flags | FLAG_a;
			//ls_a(path);
		}
		//if it is a file or directory
		else{
			if(numFile == 1){
				char *dir_name = argv[pos];
				dir_names[0] = dir_name;
				numFile++;
			}
			else{ dir_names.push_back(argv[pos]); }
		}
	}

	cout << "Outputting argv: ";
	for(unsigned i=0; argv[i] != '\0'; i++)
		cout <<  argv[i] << " ";

	for(unsigned int i=0; i < dir_names.size(); i++)
		cout << "Here is directory names: " <<  dir_names[0] << endl;
	//cout << flag << endl;

	if(argc == 1)
		ls(".");

	if(isA)
		ls_a(".");

	if(isL)
		ls_l(".", isA);
	if(isR)
		ls_R(".");

	return 0;
}

//function to add path names together
string addC_str(const char *name, char d_name[]){
	return string(name) + "/" + string(d_name);
}
<commit_msg>combined ls and ls -a<commit_after>#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <stdlib.h>

using namespace std;

#define FLAG_a 1
#define FLAG_l 2
#define FLAG_R 4

void permission(const struct stat buf, dirent *dirp);
string addC_str(const char *name, char d_name[]);

//function for ls and ls -a
void ls(const char* path, bool isA){
	DIR *dirp;
	if(NULL == (dirp = opendir(path))){
		perror("There was an error with opendir().");
		exit(1);
	}
	struct dirent *filespecs;
	errno = 0;
	while( (filespecs = readdir(dirp) ) != NULL){
		if(isA){
			cout << filespecs->d_name << "  ";
		}
		else{
			 if (strcmp(filespecs->d_name, ".")!=0
			&& strcmp(filespecs->d_name, "..")!=0
			&& strcmp(filespecs->d_name, ".git") != 0){
			cout << filespecs -> d_name << "  " ;
			}
		}
	}
	if(errno != 0){
		perror("There was an error with readdir().");
		exit(1);
	}
	cout << endl;
	if(-1 == closedir(dirp)){
		perror("There was an error with closedir().");
		exit(1);
	}
	return;
}

//function for ls -l and also when ls -a -l is called
void ls_l(const char* dir, bool isA, bool isR){
	DIR *dirp;
	if(NULL == (dirp = opendir(dir))){
		perror("There was an error with opendir().");
		exit(1);
	}
	struct dirent *filespecs;
	struct stat s;
	//stat(dir, &s);
	errno = 0;
	while( (filespecs = readdir(dirp) ) != NULL){
		stat(dir, &s);
		if(isA){
			permission(s, filespecs);
		}
		else if(isR){

		}
		else{
			if (strcmp(filespecs->d_name, ".")!=0
				&& strcmp(filespecs->d_name, "..")!=0
				&& strcmp(filespecs->d_name, ".git") != 0){
				permission(s, filespecs);
			}
		}
	}
	if(errno != 0){
		perror("There was an error with readdir().");
		exit(1);
	}
	cout << endl;
	if(-1 == closedir(dirp)){
		perror("There was an error with closedir().");
		exit(1);
	}

	return;
}

//function for -R
void ls_R(const char* dir){
	DIR *dirp;
	if(NULL == (dirp = opendir(dir))){
		perror("There was an error with opendir().");
		exit(1);
	}
	struct dirent *filespecs;
	errno = 0;

	while( (filespecs=readdir(dirp)) != NULL){
		if(filespecs-> d_name[0] != '.'){
			string path;
			path += addC_str(dir, filespecs->d_name);

			cout << filespecs->d_name << ":" <<  endl;

			if(filespecs-> d_type == DT_DIR)
				ls_R(path.c_str());

		}
		else{
			cout << filespecs->d_name << endl;

		}

	}
	if(errno != 0){
		perror("There was an error with readdir().");
		exit(1);
	}
	cout << endl;
	if(-1 == closedir(dirp)){
		perror("There was an error with closedir().");
		exit(1);
	}

	return;
}

//try to get print info function working so I can delete other functions
void printDir(const char *dir){
	DIR *dirp;
	if(NULL == (dirp = opendir(dir))){
		perror("There was an error with opendir().");
		exit(1);
	}
	struct dirent *filespecs;
	struct stat s;
	//stat(dir, &s);
	errno = 0;
	while( (filespecs = readdir(dirp) ) != NULL){
		if (strcmp(filespecs->d_name, ".")!=0 && strcmp(filespecs->d_name, "..")!=0
			&& strcmp(filespecs->d_name, ".git") != 0){
		stat(dir, &s);
		permission(s, filespecs);
		}
	}
	if(errno != 0){
		perror("There was an error with readdir().");
		exit(1);
	}
	cout << endl;
	if(-1 == closedir(dirp)){
		perror("There was an error with closedir().");
		exit(1);
	}

	return;

}

//permissions to be outputted by -l
void permission(const struct stat buf, dirent *dirp){
	//create a struct with for the time
	struct tm* file_t;
	file_t = localtime( &buf.st_mtime);
	char buffer[100];
	strftime(buffer, 100, "%h %e %R", file_t);

	//output all stat
	(buf.st_mode & S_IFDIR)? cout << "d":
	(buf.st_mode & S_IFCHR) ? cout<< 'c':
	(buf.st_mode & S_IFBLK) ? cout<< 'b':
	(buf.st_mode & S_IFIFO) ? cout<< 'f':
	(buf.st_mode & S_IFSOCK) ? cout<<'s':
	(buf.st_mode & S_IFLNK) ? cout<< 'l':

	(buf.st_mode & S_IRUSR)? cout << "r": cout << "-";
	(buf.st_mode & S_IWUSR)? cout << "w": cout << "-";
	(buf.st_mode & S_IXUSR)? cout << "x": cout << "-";

	(buf.st_mode & S_IRGRP)? cout << "r": cout << "-";
	(buf.st_mode & S_IWGRP)? cout << "w": cout << "-";
	(buf.st_mode & S_IXGRP)? cout << "x": cout << "-";

	(buf.st_mode & S_IROTH)? cout << "r": cout << "-";
	(buf.st_mode & S_IWOTH)? cout << "w": cout << "-";
	(buf.st_mode & S_IXOTH)? cout << "x": cout << "-";
	cout << " ";

	cout << " " << buf.st_nlink << " ";
	cout << getpwuid(buf.st_uid)-> pw_name << " ";
	cout << getgrgid(buf.st_gid) -> gr_name << " ";
	cout << buf.st_size << " " << buffer << " " << dirp->d_name << endl;
}

int main(int argc, char* argv[]){
	//make a vector for the directory names and filenames inputted
	//into command line
	vector<char*> dir_names;
	vector<char*> file_names;
	//char* path;

	//set flags
	int flags=0;
	int numFile=1;
	//booleans to keep track of which flags are called
	bool isA=false;
	bool isL=false;
	bool isR=false;

	//check if the arguments are flags or filenames
	for(int pos=1; pos<argc; pos++){
		if(!strcmp(argv[pos],"-a")){
			isA=true;
			flags= flags | FLAG_a;
			//ls_a(path);
		}
		else if(!strcmp(argv[pos], "-l")){
			isL=true;
			flags = flags | FLAG_l;
		}
		else if(!strcmp(argv[pos], "-R")){
			isR=true;
			flags = flags | FLAG_R;
		}
		else if(!strcmp(argv[pos],"-al") || !strcmp(argv[pos],"-la")){
			isA=true;
			isL=true;
			flags= flags | FLAG_a && FLAG_l;
			//ls_a(path);
		}
		else if(!strcmp(argv[pos],"-aR") || !strcmp(argv[pos],"-Ra")){
			isA=true;
			flags= flags | FLAG_a;
			//ls_a(path);
		}
		//if it is a file or directory
		else{
			if(numFile == 1){
				char *dir_name = argv[pos];
				dir_names[0] = dir_name;
				numFile++;
			}
			else{ dir_names.push_back(argv[pos]); }
		}
	}

	cout << "Outputting argv: ";
	for(unsigned i=0; argv[i] != '\0'; i++)
		cout <<  argv[i] << " ";
	cout << endl;

	for(unsigned int i=0; i < dir_names.size(); i++)
		cout << "Here is directory names: " <<  dir_names[0] << endl;
	//cout << flag << endl;

	if(argc == 1)
		ls(".", isA);

	if(isA) ls(".", isA);

	if(isL)
		ls_l(".", isA, isR);
	if(isR)
		ls_R(".");

	return 0;
}

//function to add path names together
string addC_str(const char *name, char d_name[]){
	return string(name) + "/" + string(d_name);
}
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2013-2014 winlin

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <srs_utest_amf0.hpp>

VOID TEST(AMF0Test, Size)
{
	EXPECT_EQ(2+6, SrsAmf0Size::utf8("winlin"));
	EXPECT_EQ(2+0, SrsAmf0Size::utf8(""));

	EXPECT_EQ(1+2+6, SrsAmf0Size::str("winlin"));
	EXPECT_EQ(1+2+0, SrsAmf0Size::str(""));

	EXPECT_EQ(1+8, SrsAmf0Size::number());

	EXPECT_EQ(1, SrsAmf0Size::null());

	EXPECT_EQ(1, SrsAmf0Size::undefined());

	EXPECT_EQ(1+1, SrsAmf0Size::boolean());

	if (true) {
		int size = 1+3;
		SrsAmf0Object obj;

		EXPECT_EQ(size, SrsAmf0Size::object(&obj));
	}
	if (true) {
		int size = 1+3;
		SrsAmf0Object obj;

		size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
		obj.set("name", new SrsAmf0String("winlin"));

		EXPECT_EQ(size, SrsAmf0Size::object(&obj));
	}

	if (true) {
		int size = 1+4+3;
		SrsAmf0EcmaArray arr;

		EXPECT_EQ(size, SrsAmf0Size::array(&arr));
	}
	if (true) {
		int size = 1+4+3;
		SrsAmf0EcmaArray arr;

		size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
		arr.set("name", new SrsAmf0String("winlin"));

		EXPECT_EQ(size, SrsAmf0Size::array(&arr));
	}
	if (true) {
		int size = 1+4+3;
		SrsAmf0EcmaArray arr;

		size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
		arr.set("name", new SrsAmf0String("winlin"));

		SrsAmf0Object* args = new SrsAmf0Object();
		size += SrsAmf0Size::utf8("args")+SrsAmf0Size::object(args);
		arr.set("args", args);

		EXPECT_EQ(size, SrsAmf0Size::array(&arr));
	}
}
<commit_msg>amf0 utest: refine amf0 size and finish utest.<commit_after>/*
The MIT License (MIT)

Copyright (c) 2013-2014 winlin

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <srs_utest_amf0.hpp>

VOID TEST(AMF0Test, Size)
{
    // size of elem
    EXPECT_EQ(2+6, SrsAmf0Size::utf8("winlin"));
    EXPECT_EQ(2+0, SrsAmf0Size::utf8(""));

    EXPECT_EQ(1+2+6, SrsAmf0Size::str("winlin"));
    EXPECT_EQ(1+2+0, SrsAmf0Size::str(""));

    EXPECT_EQ(1+8, SrsAmf0Size::number());

    EXPECT_EQ(1, SrsAmf0Size::null());

    EXPECT_EQ(1, SrsAmf0Size::undefined());

    EXPECT_EQ(1+1, SrsAmf0Size::boolean());

    // object: empty
    if (true) {
        int size = 1+3;
        SrsAmf0Object o;

        EXPECT_EQ(size, SrsAmf0Size::object(&o));
    }
    // object: elem
    if (true) {
        int size = 1+3;
        SrsAmf0Object o;

        size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
        o.set("name", new SrsAmf0String("winlin"));

        EXPECT_EQ(size, SrsAmf0Size::object(&o));
    }
    if (true) {
        int size = 1+3;
        SrsAmf0Object o;

        size += SrsAmf0Size::utf8("age")+SrsAmf0Size::number();
        o.set("age", new SrsAmf0Number(9));

        EXPECT_EQ(size, SrsAmf0Size::object(&o));
    }
    if (true) {
        int size = 1+3;
        SrsAmf0Object o;

        size += SrsAmf0Size::utf8("email")+SrsAmf0Size::null();
        o.set("email", new SrsAmf0Null());

        EXPECT_EQ(size, SrsAmf0Size::object(&o));
    }
    if (true) {
        int size = 1+3;
        SrsAmf0Object o;

        size += SrsAmf0Size::utf8("email")+SrsAmf0Size::undefined();
        o.set("email", new SrsAmf0Undefined());

        EXPECT_EQ(size, SrsAmf0Size::object(&o));
    }
    if (true) {
        int size = 1+3;
        SrsAmf0Object o;

        size += SrsAmf0Size::utf8("sex")+SrsAmf0Size::boolean();
        o.set("sex", new SrsAmf0Boolean(true));

        EXPECT_EQ(size, SrsAmf0Size::object(&o));
    }

    // array: empty
    if (true) {
        int size = 1+4+3;
        SrsAmf0EcmaArray o;

        EXPECT_EQ(size, SrsAmf0Size::array(&o));
    }
    // array: elem
    if (true) {
        int size = 1+4+3;
        SrsAmf0EcmaArray o;

        size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
        o.set("name", new SrsAmf0String("winlin"));

        EXPECT_EQ(size, SrsAmf0Size::array(&o));
    }
    if (true) {
        int size = 1+4+3;
        SrsAmf0EcmaArray o;

        size += SrsAmf0Size::utf8("age")+SrsAmf0Size::number();
        o.set("age", new SrsAmf0Number(9));

        EXPECT_EQ(size, SrsAmf0Size::array(&o));
    }
    if (true) {
        int size = 1+4+3;
        SrsAmf0EcmaArray o;

        size += SrsAmf0Size::utf8("email")+SrsAmf0Size::null();
        o.set("email", new SrsAmf0Null());

        EXPECT_EQ(size, SrsAmf0Size::array(&o));
    }
    if (true) {
        int size = 1+4+3;
        SrsAmf0EcmaArray o;

        size += SrsAmf0Size::utf8("email")+SrsAmf0Size::undefined();
        o.set("email", new SrsAmf0Undefined());

        EXPECT_EQ(size, SrsAmf0Size::array(&o));
    }
    if (true) {
        int size = 1+4+3;
        SrsAmf0EcmaArray o;

        size += SrsAmf0Size::utf8("sex")+SrsAmf0Size::boolean();
        o.set("sex", new SrsAmf0Boolean(true));

        EXPECT_EQ(size, SrsAmf0Size::array(&o));
    }

    // object: array
    if (true) {
        int size = 1+3;
        SrsAmf0Object o;

        size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
        o.set("name", new SrsAmf0String("winlin"));

        SrsAmf0EcmaArray* args = new SrsAmf0EcmaArray();
        args->set("p0", new SrsAmf0String("function"));
        size += SrsAmf0Size::utf8("args")+SrsAmf0Size::array(args);
        o.set("args", args);

        EXPECT_EQ(size, SrsAmf0Size::object(&o));
    }
    if (true) {
        int size = 1+3;
        SrsAmf0Object o;

        size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
        o.set("name", new SrsAmf0String("winlin"));

        SrsAmf0EcmaArray* args = new SrsAmf0EcmaArray();
        args->set("p0", new SrsAmf0String("function"));
        size += SrsAmf0Size::utf8("args")+SrsAmf0Size::array(args);
        o.set("args", args);

        SrsAmf0EcmaArray* params = new SrsAmf0EcmaArray();
        params->set("p1", new SrsAmf0Number(10));
        size += SrsAmf0Size::utf8("params")+SrsAmf0Size::array(params);
        o.set("params", params);

        EXPECT_EQ(size, SrsAmf0Size::object(&o));
    }

    // array: object
    if (true) {
        int size = 1+4+3;
        SrsAmf0EcmaArray o;

        size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
        o.set("name", new SrsAmf0String("winlin"));

        SrsAmf0Object* args = new SrsAmf0Object();
        args->set("p0", new SrsAmf0String("function"));
        size += SrsAmf0Size::utf8("args")+SrsAmf0Size::object(args);
        o.set("args", args);

        EXPECT_EQ(size, SrsAmf0Size::array(&o));
    }
    if (true) {
        int size = 1+4+3;
        SrsAmf0EcmaArray o;

        size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
        o.set("name", new SrsAmf0String("winlin"));

        SrsAmf0Object* args = new SrsAmf0Object();
        args->set("p0", new SrsAmf0String("function"));
        size += SrsAmf0Size::utf8("args")+SrsAmf0Size::object(args);
        o.set("args", args);

        SrsAmf0Object* params = new SrsAmf0Object();
        params->set("p1", new SrsAmf0Number(10));
        size += SrsAmf0Size::utf8("params")+SrsAmf0Size::object(params);
        o.set("params", params);

        EXPECT_EQ(size, SrsAmf0Size::array(&o));
    }

    // object: object
    if (true) {
        int size = 1+3;
        SrsAmf0Object o;

        size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
        o.set("name", new SrsAmf0String("winlin"));

        SrsAmf0Object* args = new SrsAmf0Object();
        args->set("p0", new SrsAmf0String("function"));
        size += SrsAmf0Size::utf8("args")+SrsAmf0Size::object(args);
        o.set("args", args);

        SrsAmf0Object* params = new SrsAmf0Object();
        params->set("p1", new SrsAmf0Number(10));
        size += SrsAmf0Size::utf8("params")+SrsAmf0Size::object(params);
        o.set("params", params);

        EXPECT_EQ(size, SrsAmf0Size::object(&o));
    }

    // array: array
    if (true) {
        int size = 1+4+3;
        SrsAmf0EcmaArray o;

        size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
        o.set("name", new SrsAmf0String("winlin"));

        SrsAmf0EcmaArray* args = new SrsAmf0EcmaArray();
        args->set("p0", new SrsAmf0String("function"));
        size += SrsAmf0Size::utf8("args")+SrsAmf0Size::array(args);
        o.set("args", args);

        SrsAmf0EcmaArray* params = new SrsAmf0EcmaArray();
        params->set("p1", new SrsAmf0Number(10));
        size += SrsAmf0Size::utf8("params")+SrsAmf0Size::array(params);
        o.set("params", params);

        EXPECT_EQ(size, SrsAmf0Size::array(&o));
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;

bool isDirectory(char* directoryName) {

	struct stat directoryInCurrent;

	if (-1 == (stat(directoryName, &directoryInCurrent))) {

		perror("stat failed");
		return false;
	}

	if (directoryInCurrent.st_mode & S_IFDIR) {
		return true;
	}
	else {
		return false;
	}
}

int ls(char* directoryName) {

		char const *dirName = ".";
		DIR *dirp;
		if (!(dirp = opendir(dirName))) {
			cerr << "Error(" << errno << ") opening " << dirName << endl;
		}

		dirent *direntp;
		while ((direntp = readdir(dirp))) {
			if (direntp->d_name[0] != '.') {

				//cout << direntp->d_name << endl; // use stat here to find attributes of a file
				printf(direntp->d_name, 8);
				cout << " ";
			}
		}
		cout << endl;
		closedir(dirp);
		return 0;
}

int lsWithFlags(char* directoryName, vector<string> flags) {

	bool isA = false;
	bool isL = false;
	bool isR = false;
	for (unsigned i = 0; i < flags.size(); ++i) {
		for (unsigned k = 0; k < flags.at(i).size(); ++k) {
			if (flags.at(i).at(k) == 'a')
				isA = true;
			else if (flags.at(i).at(k) == 'l')
				isL = true;
			else if (flags.at(i).at(k) == 'R')
				isR = true;
		}

	}
	char const *dirName = directoryName;
	DIR *dirp;
	if (!(dirp = opendir(dirName))) {
		cerr << "Error(" << errno << ") opening " << dirName << endl;
		return errno;
	}

	dirent *direntp;
	if (isA) {
		while ((direntp = readdir(dirp))) {

			//cout << direntp->d_name << endl; // use stat here to find attributes of a file
			printf(direntp->d_name, 8);
			cout << " ";

		}
	}
	cout << endl;
	closedir(dirp);
	return 0;
}

int main(int argc, char* argv[]) {

	if (argc == 1) {

		if (errno == ls(".")) {

			return errno;
		}
	}

	else {

		vector<string> directories;
		vector<string> flags;
		vector<int> directoryIndex;
		bool directoryInArgv = false;
		for (int i = 1; i < argc; ++i) {

			if (isDirectory(argv[i])) {
				directoryInArgv = true;
				break;
			}
			else {

				if (argv[i][0] == '-') {

					flags.push_back(argv[i]);
				}
			}
		}
		if (!directoryInArgv) {

			if (errno == lsWithFlags(".", flags)) {

				return errno;
			}
		}
		else {
			for (int i = 0; i < argc; ++i) {

				if (isDirectory(argv[i])) {
					directories.push_back(argv[i]);
					directoryIndex.push_back(i);
				}
			}

			for (unsigned int i = 0; i < directories.size(); ++i) {
				flags.clear();
				for (unsigned int k = static_cast<unsigned>(directoryIndex.at(i));
					 (i + 1) < directoryIndex.size() &&
					 k != (unsigned)directoryIndex.at(i + 1);
					  ++k) {
					if (argv[k][0] == '-') {

						flags.push_back(argv[k]);
					}
				}

				cout << "flags: ";
				for (unsigned i = 0; i < flags.size(); ++i) {

					cout << flags.at(i) << " ";
				}
				cout << endl;

				char* directoryName = new char[directories.at(i).size() + 1];
				strcpy(directoryName, directories.at(i).c_str());

				if (errno == lsWithFlags(directoryName, flags)) {

					return errno;
				}
			}
		}
	}

}

<commit_msg>changed conditions for boolean variables in lswithflags function<commit_after>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;

bool isDirectory(char* directoryName) {

	struct stat directoryInCurrent;

	if (-1 == (stat(directoryName, &directoryInCurrent))) {

		perror("stat failed");
		return false;
	}

	if (directoryInCurrent.st_mode & S_IFDIR) {
		return true;
	}
	else {
		return false;
	}
}

int ls(char* directoryName) {

		char const *dirName = ".";
		DIR *dirp;
		if (!(dirp = opendir(dirName))) {
			cerr << "Error(" << errno << ") opening " << dirName << endl;
		}

		dirent *direntp;
		while ((direntp = readdir(dirp))) {
			if (direntp->d_name[0] != '.') {

				//cout << direntp->d_name << endl; // use stat here to find attributes of a file
				printf(direntp->d_name, 8);
				cout << " ";
			}
		}
		cout << endl;
		closedir(dirp);
		return 0;
}

int lsWithFlags(char* directoryName, vector<string> flags) {

	bool isA = false;
	bool isL = false;
	bool isR = false;
	for (unsigned i = 0; i < flags.size(); ++i) {
		for (unsigned k = 0; k < flags.at(i).size(); ++k) {
			if (flags.at(i).at(k) == 'a')
				isA = true;
			else if (flags.at(i).at(k) == 'l')
				isL = true;
			else if (flags.at(i).at(k) == 'R')
				isR = true;
		}

	}
	char const *dirName = directoryName;
	DIR *dirp;
	if (!(dirp = opendir(dirName))) {
		cerr << "Error(" << errno << ") opening " << dirName << endl;
		return errno;
	}

	dirent *direntp;
	if (isA) {
		while ((direntp = readdir(dirp))) {

			//cout << direntp->d_name << endl; // use stat here to find attributes of a file
			printf(direntp->d_name, 8);
			cout << " ";

		}
	}
	cout << endl;
	closedir(dirp);
	return 0;
}

int main(int argc, char* argv[]) {

	if (argc == 1) {

		if (errno == ls(".")) {

			return errno;
		}
	}

	else {

		vector<string> directories;
		vector<string> flags;
		vector<int> directoryIndex;
		bool directoryInArgv = false;
		for (int i = 1; i < argc; ++i) {

			if (isDirectory(argv[i])) {
				directoryInArgv = true;
				break;
			}
			else {

				if (argv[i][0] == '-') {

					flags.push_back(argv[i]);
				}
			}
		}
		if (!directoryInArgv) {

			if (errno == lsWithFlags(".", flags)) {

				return errno;
			}
		}
		else {
			for (int i = 0; i < argc; ++i) {

				if (isDirectory(argv[i])) {
					directories.push_back(argv[i]);
					directoryIndex.push_back(i);
				}
			}

			for (unsigned int i = 0; i < directories.size(); ++i) {
				flags.clear();
				for (unsigned int k = static_cast<unsigned>(directoryIndex.at(i));
					 (i + 1) < directoryIndex.size() &&
					 k != (unsigned)directoryIndex.at(i + 1);
					  ++k) {
					if (argv[k][0] == '-') {

						flags.push_back(argv[k]);
					}
				}

				cout << "flags: ";
				for (unsigned j = 0; j < flags.size(); ++j) {

					cout << flags.at(j) << " ";
				}
				cout << endl;

				char* directoryName = new char[directories.at(i).size() + 1];
				strcpy(directoryName, directories.at(i).c_str());

				if (errno == lsWithFlags(directoryName, flags)) {

					return errno;
				}
			}
		}
	}

}

<|endoftext|>