<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2017.  All rights reserved
 */
//  TEST    Foundation::Execution::Signals
#include "Stroika/Foundation/StroikaPreComp.h"

#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/SignalHandlers.h"
#include "Stroika/Foundation/Execution/Sleep.h"

#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"

using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;

using Containers::Set;

namespace {
    void Test1_Basic_ ()
    {
        Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);
        {
            bool called = false;
            Stroika_Foundation_Debug_ValgrindDisableHelgrind (called); // helgrind doesnt know signal handler must have returend by end of sleep.
            SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }));
            ::raise (SIGINT);
            Execution::Sleep (0.5); // delivery could be delayed because signal is pushed to another thread
            VerifyTestResult (called);
        }
        SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);
    }
}

namespace {
    Stroika_Foundation_Debug_ATTRIBUTE_NO_SANITIZE ("thread") void Test2_Direct_ ()
    {
        Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);
        {
            bool called = false;
            SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }, SignalHandler::Type::eDirect));
            Stroika_Foundation_Debug_ValgrindDisableHelgrind (called); // helgrind doesnt know signal handler must have returend by end of sleep.
            ::raise (SIGINT);
            VerifyTestResult (called);
        }
        SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);
    }
}

namespace {
    void Test3_Safe_ ()
    {
        Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);
        {
            bool called = false;
            SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }));
            Stroika_Foundation_Debug_ValgrindDisableHelgrind (called); // helgrind doesnt know signal handler must have returend by end of sleep.
            ::raise (SIGINT);
            Execution::Sleep (0.5); // delivery could be delayed because signal is pushed to another thread
            VerifyTestResult (called);
        }
        SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);
    }
}

namespace {

    void DoRegressionTests_ ()
    {
        Test1_Basic_ ();
        Test2_Direct_ ();
        Test3_Safe_ ();
    }
}

int main (int argc, const char* argv[])
{
    SignalHandlerRegistry::SafeSignalsManager safeSignals;
    Stroika::TestHarness::Setup ();
    return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<commit_msg>fixed missing include<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2017.  All rights reserved
 */
//  TEST    Foundation::Execution::Signals
#include "Stroika/Foundation/StroikaPreComp.h"

#include "Stroika/Foundation/Debug/Assertions.h"
#include "Stroika/Foundation/Debug/Sanitizer.h"
#include "Stroika/Foundation/Debug/Trace.h"
#include "Stroika/Foundation/Execution/SignalHandlers.h"
#include "Stroika/Foundation/Execution/Sleep.h"

#include "../TestHarness/SimpleClass.h"
#include "../TestHarness/TestHarness.h"

using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;

using Containers::Set;

namespace {
    void Test1_Basic_ ()
    {
        Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);
        {
            bool called = false;
            Stroika_Foundation_Debug_ValgrindDisableHelgrind (called); // helgrind doesnt know signal handler must have returend by end of sleep.
            SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }));
            ::raise (SIGINT);
            Execution::Sleep (0.5); // delivery could be delayed because signal is pushed to another thread
            VerifyTestResult (called);
        }
        SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);
    }
}

namespace {
    Stroika_Foundation_Debug_ATTRIBUTE_NO_SANITIZE ("thread") void Test2_Direct_ ()
    {
        Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);
        {
            bool called = false;
            SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }, SignalHandler::Type::eDirect));
            Stroika_Foundation_Debug_ValgrindDisableHelgrind (called); // helgrind doesnt know signal handler must have returend by end of sleep.
            ::raise (SIGINT);
            VerifyTestResult (called);
        }
        SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);
    }
}

namespace {
    void Test3_Safe_ ()
    {
        Set<SignalHandler> saved = SignalHandlerRegistry::Get ().GetSignalHandlers (SIGINT);
        {
            bool called = false;
            SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, SignalHandler ([&called](SignalID signal) -> void { called = true; }));
            Stroika_Foundation_Debug_ValgrindDisableHelgrind (called); // helgrind doesnt know signal handler must have returend by end of sleep.
            ::raise (SIGINT);
            Execution::Sleep (0.5); // delivery could be delayed because signal is pushed to another thread
            VerifyTestResult (called);
        }
        SignalHandlerRegistry::Get ().SetSignalHandlers (SIGINT, saved);
    }
}

namespace {

    void DoRegressionTests_ ()
    {
        Test1_Basic_ ();
        Test2_Direct_ ();
        Test3_Safe_ ();
    }
}

int main (int argc, const char* argv[])
{
    SignalHandlerRegistry::SafeSignalsManager safeSignals;
    Stroika::TestHarness::Setup ();
    return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
}
<|endoftext|>


<commit_before>/*
 * Radiation Watch Pocket Geiger Type 5 library for Arduino.
 *
 * Documentation and usage at:
 * https://github.com/MonsieurV/RadiationWatch
 *
 * Released under MIT License. See LICENSE file.
 *
 * Contributed by:
 * Radiation Watch <http://www.radiation-watch.org/>
 * thomasaw <https://github.com/thomasaw>
 * Tourmal <https://github.com/Toumal>
 * Yoan Tournade <yoan@ytotech.com>
 */
#include "RadiationWatch.h"
#ifndef ARDUINO_ARCH_AVR
#include <avr/dtostrf.h>
#endif

int volatile radiationCount = 0;
int volatile noiseCount = 0;
bool volatile radiationFlag = false;
bool volatile noiseFlag = false;
// Message buffer for output.
char _msg[60];

void _onRadiationHandler()
{
  radiationCount++;
  radiationFlag = true;
}

void _onNoiseHandler()
{
  noiseCount++;
  noiseFlag = true;
}

RadiationWatch::RadiationWatch(byte signPin, byte noisePin):
    _signPin(signPin), _noisePin(noisePin)
{
  previousTime = 0;
  _cpm = 0;
  cpmIndex = 0;
  cpmIndexPrev = 0;
  totalTime = 0;
  _radiationCallback = NULL;
  _noiseCallback = NULL;
}

void RadiationWatch::setup()
{
  pinMode(_signPin, INPUT_PULLUP);
  pinMode(_noisePin, INPUT_PULLUP);
  // Initialize cpmHistory[].
  for(int i = 0; i < HISTORY_LENGTH; i++)
    _cpmHistory[i] = 0;
  // Init measurement time.
  previousTime = millis();
  // Attach interrupt handlers.
  attachInterrupt(digitalPinToInterrupt(_signPin), _onRadiationHandler, FALLING);
  attachInterrupt(digitalPinToInterrupt(_noisePin), _onNoiseHandler, RISING);
}

unsigned long loopTime = 0;
unsigned int loopElasped = 0;

void RadiationWatch::loop()
{
  // Process radiation dose if the process period has elapsed.
  loopElasped = loopElasped + abs(millis() - loopTime);
  loopTime = millis();
  if(loopElasped > PROCESS_PERIOD) {
    unsigned long currentTime = millis();
    if(noiseCount == 0) {
      // Shift an array for counting log for each 6 seconds.
      unsigned long totalTimeSec = totalTime / 1000;
      if(totalTimeSec % HISTORY_UNIT == 0 && cpmIndexPrev != totalTimeSec) {
        cpmIndexPrev = totalTimeSec;
        cpmIndex++;
        if(cpmIndex >= HISTORY_LENGTH)
          cpmIndex = 0;
        if(_cpm > 0 && _cpmHistory[cpmIndex] > 0)
          _cpm -= _cpmHistory[cpmIndex];
        _cpmHistory[cpmIndex] = 0;
      }
      noInterrupts();
      // Store count log.
      _cpmHistory[cpmIndex] += radiationCount;
      // Add number of counts.
      _cpm += radiationCount;
      // Get the elapsed time.
      totalTime += abs(currentTime - previousTime);
      loopElasped = 0;
    }
    // Initialization for next N loops.
    previousTime = currentTime;
    radiationCount = 0;
    noiseCount = 0;
    interrupts();
    // Enable the callbacks.
    if(_radiationCallback && radiationFlag) {
      radiationFlag = false;
      _radiationCallback();
    }
    if(_noiseCallback && noiseFlag) {
      noiseFlag = false;
      _noiseCallback();
    }
  }
}

void RadiationWatch::registerRadiationCallback(void (*callback)(void))
{
  _radiationCallback = callback;
}

void RadiationWatch::registerNoiseCallback(void (*callback)(void))
{
  _noiseCallback = callback;
}

char* RadiationWatch::csvKeys()
{
  // CSV-formatting for output.
  return "time(ms),count,cpm,uSv/h,uSv/hError";
}

char* RadiationWatch::csvStatus()
{
  // Format message. We use dtostrf() to format float to string.
  char cpmBuff[8];
  char uSvBuff[8];
  char uSvdBuff[8];
  dtostrf(cpm(), -1, 3, cpmBuff);
  dtostrf(uSvh(), -1, 3, uSvBuff);
  dtostrf(uSvhError(), -1, 3, uSvdBuff);
  sprintf(_msg, "%lu,%d,%s,%s,%s",
    totalTime, radiationCount, cpmBuff, uSvBuff, uSvdBuff);
  return _msg;
}

unsigned long RadiationWatch::duration()
{
  return totalTime;
}

int RadiationWatch::currentRadiationCount() {
  return radiationCount;
}

float RadiationWatch::cpm()
{
  // cpm = uSv x alpha
  float min = cpmTime();
  return (min > 0) ? _cpm / min : 0;
}

static const float kAlpha = 53.032;

float RadiationWatch::uSvh()
{
  return cpm() / kAlpha;
}

float RadiationWatch::uSvhError()
{
  float min = cpmTime();
  return (min > 0) ? sqrt(_cpm) / min / kAlpha : 0;
}
<commit_msg>ESP8266 compatibility<commit_after>/*
 * Radiation Watch Pocket Geiger Type 5 library for Arduino.
 *
 * Documentation and usage at:
 * https://github.com/MonsieurV/RadiationWatch
 *
 * Released under MIT License. See LICENSE file.
 *
 * Contributed by:
 * Radiation Watch <http://www.radiation-watch.org/>
 * thomasaw <https://github.com/thomasaw>
 * Tourmal <https://github.com/Toumal>
 * Yoan Tournade <yoan@ytotech.com>
 */
#include "RadiationWatch.h"
#if !defined(ARDUINO_ARCH_AVR) && !defined(ESP8266)
#include <avr/dtostrf.h>
#endif

int volatile radiationCount = 0;
int volatile noiseCount = 0;
bool volatile radiationFlag = false;
bool volatile noiseFlag = false;
// Message buffer for output.
char _msg[60];

void _onRadiationHandler()
{
  radiationCount++;
  radiationFlag = true;
}

void _onNoiseHandler()
{
  noiseCount++;
  noiseFlag = true;
}

RadiationWatch::RadiationWatch(byte signPin, byte noisePin):
    _signPin(signPin), _noisePin(noisePin)
{
  previousTime = 0;
  _cpm = 0;
  cpmIndex = 0;
  cpmIndexPrev = 0;
  totalTime = 0;
  _radiationCallback = NULL;
  _noiseCallback = NULL;
}

void RadiationWatch::setup()
{
  pinMode(_signPin, INPUT_PULLUP);
  pinMode(_noisePin, INPUT_PULLUP);
  // Initialize cpmHistory[].
  for(int i = 0; i < HISTORY_LENGTH; i++)
    _cpmHistory[i] = 0;
  // Init measurement time.
  previousTime = millis();
  // Attach interrupt handlers.
  attachInterrupt(digitalPinToInterrupt(_signPin), _onRadiationHandler, FALLING);
  attachInterrupt(digitalPinToInterrupt(_noisePin), _onNoiseHandler, RISING);
}

unsigned long loopTime = 0;
unsigned int loopElasped = 0;

void RadiationWatch::loop()
{
  // Process radiation dose if the process period has elapsed.
  loopElasped = loopElasped + abs(millis() - loopTime);
  loopTime = millis();
  if(loopElasped > PROCESS_PERIOD) {
    unsigned long currentTime = millis();
    if(noiseCount == 0) {
      // Shift an array for counting log for each 6 seconds.
      unsigned long totalTimeSec = totalTime / 1000;
      if(totalTimeSec % HISTORY_UNIT == 0 && cpmIndexPrev != totalTimeSec) {
        cpmIndexPrev = totalTimeSec;
        cpmIndex++;
        if(cpmIndex >= HISTORY_LENGTH)
          cpmIndex = 0;
        if(_cpm > 0 && _cpmHistory[cpmIndex] > 0)
          _cpm -= _cpmHistory[cpmIndex];
        _cpmHistory[cpmIndex] = 0;
      }
      noInterrupts();
      // Store count log.
      _cpmHistory[cpmIndex] += radiationCount;
      // Add number of counts.
      _cpm += radiationCount;
      // Get the elapsed time.
      totalTime += abs(currentTime - previousTime);
      loopElasped = 0;
    }
    // Initialization for next N loops.
    previousTime = currentTime;
    radiationCount = 0;
    noiseCount = 0;
    interrupts();
    // Enable the callbacks.
    if(_radiationCallback && radiationFlag) {
      radiationFlag = false;
      _radiationCallback();
    }
    if(_noiseCallback && noiseFlag) {
      noiseFlag = false;
      _noiseCallback();
    }
  }
}

void RadiationWatch::registerRadiationCallback(void (*callback)(void))
{
  _radiationCallback = callback;
}

void RadiationWatch::registerNoiseCallback(void (*callback)(void))
{
  _noiseCallback = callback;
}

char* RadiationWatch::csvKeys()
{
  // CSV-formatting for output.
  return "time(ms),count,cpm,uSv/h,uSv/hError";
}

char* RadiationWatch::csvStatus()
{
  // Format message. We use dtostrf() to format float to string.
  char cpmBuff[8];
  char uSvBuff[8];
  char uSvdBuff[8];
  dtostrf(cpm(), -1, 3, cpmBuff);
  dtostrf(uSvh(), -1, 3, uSvBuff);
  dtostrf(uSvhError(), -1, 3, uSvdBuff);
  sprintf(_msg, "%lu,%d,%s,%s,%s",
    totalTime, radiationCount, cpmBuff, uSvBuff, uSvdBuff);
  return _msg;
}

unsigned long RadiationWatch::duration()
{
  return totalTime;
}

int RadiationWatch::currentRadiationCount() {
  return radiationCount;
}

float RadiationWatch::cpm()
{
  // cpm = uSv x alpha
  float min = cpmTime();
  return (min > 0) ? _cpm / min : 0;
}

static const float kAlpha = 53.032;

float RadiationWatch::uSvh()
{
  return cpm() / kAlpha;
}

float RadiationWatch::uSvhError()
{
  float min = cpmTime();
  return (min > 0) ? sqrt(_cpm) / min / kAlpha : 0;
}
<|endoftext|>


<commit_before>
#include <iostream>

#include "queryset/models/model.h"

int main(int argc, char** argv){
    std::cout << "== QuerysetCPP Test Package ==\n";

    typedef qs::Model<int, float> MyModel;
    std::cout << "Count is: " << MyModel::objects().all().count() << std::endl;
}<commit_msg>fix test_package<commit_after>
#include <iostream>

#include "queryset/models/model.h"

int main(int argc, char** argv){
    std::cout << "== QuerysetCPP Test Package ==\n";

    typedef qs::Model<qs::memory::Manager, int, float> MyModel;
    std::cout << "Count is: " << MyModel::objects().all().count() << std::endl;
}<|endoftext|>


<commit_before>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.75
Copyright (C) 2022 GOMC Group
A copy of the MIT License can be found in License.txt
along with this program, also can be found at <https://opensource.org/licenses/MIT>.
********************************************************************************/
#include "OutConst.h" //For namespace spec;

namespace out
{
const std::string ENERGY_TOTAL = "TOT_EN";
const std::string ENERGY_INTER = "EN_INTER";
const std::string ENERGY_TC = "EN_TC";
const std::string ENERGY_INTRA_B  = "EN_INTRA(B)";
const std::string ENERGY_INTRA_NB = "EN_INTRA(NB)";
const std::string ENERGY_ELECT = "EN_ELECT";
const std::string ENERGY_REAL = "EN_REAL";
const std::string ENERGY_RECIP = "EN_RECIP";
const std::string VIRIAL_TOTAL = "TOTAL_VIR";
const std::string PRESSURE = "PRESSURE";
const std::string COMPRESSIBILITY = "COMPRESSIBILITY";
const std::string ENTHALPY = "ENTHALPY";
#if ENSEMBLE == GEMC
const std::string HEAT_OF_VAP = "HEAT_VAP";
const std::string VOLUME = "VOLUME";
#endif
#if ENSEMBLE == NPT
const std::string VOLUME = "VOLUME";
#endif
const std::string DENSITY = "TOT_DENS";
const std::string MOL_NUM = "TOT_MOL";
const std::string MOL_FRACTION = "MOLFRACT";
const std::string MOL_DENSITY = "MOLDENS";
const std::string SURF_TENSION = "SURF_TENSION";
}
<commit_msg>Fix Another Output Message from EN_TC to EN_LRC<commit_after>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.75
Copyright (C) 2022 GOMC Group
A copy of the MIT License can be found in License.txt
along with this program, also can be found at <https://opensource.org/licenses/MIT>.
********************************************************************************/
#include "OutConst.h" //For namespace spec;

namespace out
{
const std::string ENERGY_TOTAL = "TOT_EN";
const std::string ENERGY_INTER = "EN_INTER";
const std::string ENERGY_TC = "EN_LRC";
const std::string ENERGY_INTRA_B  = "EN_INTRA(B)";
const std::string ENERGY_INTRA_NB = "EN_INTRA(NB)";
const std::string ENERGY_ELECT = "EN_ELECT";
const std::string ENERGY_REAL = "EN_REAL";
const std::string ENERGY_RECIP = "EN_RECIP";
const std::string VIRIAL_TOTAL = "TOTAL_VIR";
const std::string PRESSURE = "PRESSURE";
const std::string COMPRESSIBILITY = "COMPRESSIBILITY";
const std::string ENTHALPY = "ENTHALPY";
#if ENSEMBLE == GEMC
const std::string HEAT_OF_VAP = "HEAT_VAP";
const std::string VOLUME = "VOLUME";
#endif
#if ENSEMBLE == NPT
const std::string VOLUME = "VOLUME";
#endif
const std::string DENSITY = "TOT_DENS";
const std::string MOL_NUM = "TOT_MOL";
const std::string MOL_FRACTION = "MOLFRACT";
const std::string MOL_DENSITY = "MOLDENS";
const std::string SURF_TENSION = "SURF_TENSION";
}
<|endoftext|>


<commit_before>/*
  pvsops.c: pvs opcodes

  Copyright (C) 2017 Victor Lazzarini
  This file is part of Csound.

  The Csound Library is free software; you can redistribute it
  and/or modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  Csound is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with Csound; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  02111-1307 USA
*/
#include <plugin.h>
#include <algorithm>

struct PVTrace : csnd::FPlugin<1, 2> {
  csnd::AuxMem<float> amps;
  static constexpr char const *otypes = "f";
  static constexpr char const *itypes = "fk";

  int init() {
    if (inargs.fsig_data(0).isSliding())
      return csound->init_error(Str("sliding not supported"));

    if (inargs.fsig_data(0).fsig_format() != csnd::fsig_format::pvs &&
        inargs.fsig_data(0).fsig_format() != csnd::fsig_format::polar)
      return csound->init_error(Str("fsig format not supported"));

    amps.allocate(csound, inargs.fsig_data(0).nbins());
    csnd::Fsig &fout = outargs.fsig_data(0);
    fout.init(csound, inargs.fsig_data(0));
    framecount = 0;
    return OK;
  }

  int kperf() {
    csnd::pv_frame &fin = inargs.fsig_data(0);
    csnd::pv_frame &fout = outargs.fsig_data(0);

    if (framecount < fin.count()) {
      int n =  fin.len() - (int) inargs[1];
      float thrsh;
      std::transform(fin.begin(), fin.end(), amps.begin(),
                     [](csnd::pv_bin f){ return f.amp(); });
      std::nth_element(amps.begin(), amps.begin()+n, amps.end());
      thrsh = amps[n];
      std::transform(fin.begin(), fin.end(), fout.begin(),
                     [thrsh](csnd::pv_bin f){
                       return f.amp() >= thrsh ? f : csnd::pv_bin(); });
      framecount = fout.count(fin.count());
    }
    return OK;
  }
};

struct TVConv : csnd::Plugin<1,4> {
  static constexpr char const *otypes = "a";
  static constexpr char const *itypes = "aaii";
  csnd::AuxMem<MYFLT> ir;
  csnd::AuxMem<MYFLT> in;
  csnd::AuxMem<MYFLT> out;
  csnd::AuxMem<MYFLT> saved;
  uint32_t n;
  uint32_t fils;
  uint32_t pars;
  uint32_t ffts;
  uint32_t nparts;
  uint32_t pp;
  csnd::fftp fwd,inv;
  typedef std::complex<MYFLT> cmplx;

  uint32_t rpow2(uint32_t n) {
  uint32_t v = 2;
  while (v <= n)
    v <<= 1;
  if((n - (v >> 1)) < (v - n))
   return v >> 1;
  else return v;
  }

  cmplx *to_cmplx(MYFLT *f) {
    return reinterpret_cast<cmplx*>(f);
  }

  cmplx real_prod(cmplx &a, cmplx &b) {
    return cmplx(a.real()*b.real(),
		 a.imag()*b.imag());
  }

  int init() {
    fils = rpow2(inargs[2]);
    pars = rpow2(inargs[3]);
    if(pars > fils) std::swap(pars,fils);
    ffts = pars*2;
    fwd = csound->fft_setup(ffts,FFT_FWD);
    inv = csound->fft_setup(ffts,FFT_INV);
    ir.allocate(csound, 2*fils);
    in.allocate(csound, 2*fils);
    out.allocate(csound, 2*pars);
    saved.allocate(csound, pars);
    n = 0;
    pp = 0;
    nparts = fils/pars;
    fils *= 2;
    return OK;
  }

  int aperf() {
    csnd::AudioSig insig(this, inargs(0));
    csnd::AudioSig irsig(this, inargs(1));
    csnd::AudioSig outsig(this, outargs(0));

    auto irp = irsig.begin();
    auto inp = insig.begin();

    for(auto &s: outsig) {
      ir[n+pp] = *irp++;
      in[n+pp] = *inp++;
      in[n+pp+pars] = ir[n+pp+pars] = 0.;
      s  = out[n] + saved[n];
      saved[n] = out[n + pars];
       if(++n == pars) {
	 cmplx *ins,*irs, *ous = to_cmplx(out.data());
	 std::fill(out.begin(), out.end(), 0.);
	 // FFT
         csound->rfft(fwd, ir.data() + pp);
	 csound->rfft(fwd, in.data() + pp);
	 pp += ffts;
	 if(pp == fils) pp = 0;
	 // spectral delay line
         for(uint32_t k = 0, kp = pp; k < nparts; k++, kp+=ffts) {
	   if(kp == fils) kp = 0;
	   ins = to_cmplx(in.data() + kp);
	   irs = to_cmplx(ir.data() + (nparts - k - 1)*ffts);
	   // spectral product
           for(uint i=1; i < pars; i++)
	     ous[i] +=  ins[i] * irs[i];
	   ous[0] += real_prod(ins[0],irs[0]);
	 }
	 // IFFT
	 csound->rfft(inv, out.data());
         n = 0;
       }
    }
    return OK;
  }
};

#include <modload.h>
void csnd::on_load(Csound *csound) {
  csnd::plugin<PVTrace>(csound, "pvstrace", csnd::thread::ik);
  csnd::plugin<TVConv>(csound, "tvconv", csnd::thread::ia);
}
<commit_msg>tvconv dconv option<commit_after>/*
  pvsops.c: pvs and other spectral-based opcodes

  Copyright (C) 2017 Victor Lazzarini
  This file is part of Csound.

  The Csound Library is free software; you can redistribute it
  and/or modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  Csound is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with Csound; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  02111-1307 USA
*/
#include <plugin.h>
#include <algorithm>

struct PVTrace : csnd::FPlugin<1, 2> {
  csnd::AuxMem<float> amps;
  static constexpr char const *otypes = "f";
  static constexpr char const *itypes = "fk";

  int init() {
    if (inargs.fsig_data(0).isSliding())
      return csound->init_error(Str("sliding not supported"));

    if (inargs.fsig_data(0).fsig_format() != csnd::fsig_format::pvs &&
        inargs.fsig_data(0).fsig_format() != csnd::fsig_format::polar)
      return csound->init_error(Str("fsig format not supported"));

    amps.allocate(csound, inargs.fsig_data(0).nbins());
    csnd::Fsig &fout = outargs.fsig_data(0);
    fout.init(csound, inargs.fsig_data(0));
    framecount = 0;
    return OK;
  }

  int kperf() {
    csnd::pv_frame &fin = inargs.fsig_data(0);
    csnd::pv_frame &fout = outargs.fsig_data(0);

    if (framecount < fin.count()) {
      int n =  fin.len() - (int) inargs[1];
      float thrsh;
      std::transform(fin.begin(), fin.end(), amps.begin(),
                     [](csnd::pv_bin f){ return f.amp(); });
      std::nth_element(amps.begin(), amps.begin()+n, amps.end());
      thrsh = amps[n];
      std::transform(fin.begin(), fin.end(), fout.begin(),
                     [thrsh](csnd::pv_bin f){
                       return f.amp() >= thrsh ? f : csnd::pv_bin(); });
      framecount = fout.count(fin.count());
    }
    return OK;
  }
};

struct TVConv : csnd::Plugin<1,4> {
  static constexpr char const *otypes = "a";
  static constexpr char const *itypes = "aaii";
  csnd::AuxMem<MYFLT> ir;
  csnd::AuxMem<MYFLT> in;
  csnd::AuxMem<MYFLT> out;
  csnd::AuxMem<MYFLT> saved;
  uint32_t n;
  uint32_t fils;
  uint32_t pars;
  uint32_t ffts;
  uint32_t nparts;
  uint32_t pp;
  csnd::fftp fwd,inv;
  typedef std::complex<MYFLT> cmplx;

  uint32_t rpow2(uint32_t n) {
  uint32_t v = 2;
  while (v <= n)
    v <<= 1;
  if((n - (v >> 1)) < (v - n))
   return v >> 1;
  else return v;
  }

  cmplx *to_cmplx(MYFLT *f) {
    return reinterpret_cast<cmplx*>(f);
  }

  cmplx real_prod(cmplx &a, cmplx &b) {
    return cmplx(a.real()*b.real(),
		 a.imag()*b.imag());
  }

  int init() {
    pars = inargs[2];
    fils = inargs[3];
    if(pars > fils) std::swap(pars,fils);
    if(pars > 1) {
      pars = rpow2(pars);
      fils = rpow2(fils);
      ffts = pars*2;
      fwd = csound->fft_setup(ffts,FFT_FWD);
      inv = csound->fft_setup(ffts,FFT_INV);
      out.allocate(csound, 2*pars);
      saved.allocate(csound, pars);
      ir.allocate(csound, 2*fils);
      in.allocate(csound, 2*fils);
      nparts = fils/pars;
      fils *= 2;
    } else {
      ir.allocate(csound, fils);
      in.allocate(csound, fils);
    }
    n = 0;
    pp = 0;
    return OK;
  }

  int pconv(csnd::AudioSig &outsig,
	    csnd::AudioSig &insig,
	    csnd::AudioSig &irsig){
    auto irp = irsig.begin();
    auto inp = insig.begin();
    for(auto &s: outsig) {
      ir[n+pp] = *irp++;
      in[n+pp] = *inp++;
      in[n+pp+pars] = ir[n+pp+pars] = 0.;
      s  = out[n] + saved[n];
      saved[n] = out[n + pars];
       if(++n == pars) {
	 cmplx *ins,*irs, *ous = to_cmplx(out.data());
	 std::fill(out.begin(), out.end(), 0.);
	 // FFT
         csound->rfft(fwd, ir.data() + pp);
	 csound->rfft(fwd, in.data() + pp);
	 pp += ffts;
	 if(pp == fils) pp = 0;
	 // spectral delay line
         for(uint32_t k = 0, kp = pp; k < nparts; k++, kp+=ffts) {
	   if(kp == fils) kp = 0;
	   ins = to_cmplx(in.data() + kp);
	   irs = to_cmplx(ir.data() + (nparts - k - 1)*ffts);
	   // spectral product
           for(uint i=1; i < pars; i++)
	     ous[i] +=  ins[i] * irs[i];
	   ous[0] += real_prod(ins[0],irs[0]);
	 }
	 // IFFT
	 csound->rfft(inv, out.data());
         n = 0;
       }
    }
    return OK;
  }

  int dconv(csnd::AudioSig &outsig,
	    csnd::AudioSig &insig,
	    csnd::AudioSig &irsig) {
    auto irp = irsig.begin();
    auto inp = insig.begin();
    MYFLT sum = 0.0;
    for(auto &s: outsig) {
     ir[pp] = *irp++;
     in[pp] = *inp++;
     pp = pp != fils - 1 ? pp + 1 : 0;
     for(uint32_t k = 0, kp = pp; k < fils; k++, kp++) {
       if(kp == fils) kp = 0;
       sum += in[kp] * ir[fils - k - 1];
     }
     s = sum;
     sum = 0;
    }
    return OK;
  }

  int aperf() {
    csnd::AudioSig ins(this, inargs(0));
    csnd::AudioSig irs(this, inargs(1));
    csnd::AudioSig outs(this, outargs(0));
    if(pars > 1) return pconv(outs, ins, irs);
    else return dconv(outs, ins, irs);
  }
};

#include <modload.h>
void csnd::on_load(Csound *csound) {
  csnd::plugin<PVTrace>(csound, "pvstrace", csnd::thread::ik);
  csnd::plugin<TVConv>(csound, "tvconv", csnd::thread::ia);
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------
//
// CASROS: Component-based Architecture for Safe Robotic Systems
//
// Copyright (C) 2012-2014 Min Yang Jung and Peter Kazanzides
//
//------------------------------------------------------------------------
//
// Created on   : Jul 10, 2014
// Last revision: Jul 28, 2014
// Author       : Min Yang Jung (myj@jhu.edu)
// Github       : https://github.com/minyang/casros
//
#include "accessor.h"
#include "QtJsBridge/jsApiHandler.h"
#include <cisstMultiTask/mtsManagerLocal.h>

#include <iomanip>

#define VERBOSE 0

using namespace SF;

// JSON object that has complete information of all states of the entire system (including
// multiple processes)
// TODO: issue of shared resource with this
SF::JSON CasrosSystemStates;
SF::JSON::JSONVALUE & CasrosSystemStatesRoot = CasrosSystemStates.GetRoot();

// for safety coordinator color selection
static int SCColorCode = 0;

#define COLOR_RED1    "#ff0000"
#define COLOR_RED2    "#c91a26"
#define COLOR_YELLOW1 "#fffa00"
#define COLOR_YELLOW2 "#ffda00"
#define COLOR_WHITE   "#ffffff"
#define COLOR_GREY    "#e3e7ee"

const std::string GetColorCodeForState(unsigned int state, bool projectedState = false)
{
    if (projectedState) {
        switch (static_cast<State::StateType>(state)) {
        case State::NORMAL:  return COLOR_GREY;
        case State::WARNING: return COLOR_YELLOW2;
        case State::ERROR:   return COLOR_RED2;
        case State::FAILURE:
        case State::INVALID: return "black";
        }
    } else {
        switch (static_cast<State::StateType>(state)) {
        case State::NORMAL:  return COLOR_WHITE;
        case State::WARNING: return COLOR_YELLOW1;
        case State::ERROR:   return COLOR_RED1;
        case State::FAILURE:
        case State::INVALID: return "green";
        }
    }
}

const std::string GetColorCodeForSafetyCoordinator(void)
{
    // ref: http://www.dtelepathy.com/blog/inspiration/beautiful-color-palettes-for-your-next-web-project
    const int N = 5;

    switch (SCColorCode++ % N) {
    case 0: return "#2e6093";
    case 1: return "#3a5988";
    case 2: return "#9d4e87";
    case 3: return "#92538c";
    case 4: return "#72659d";
    case 5: return "#293E6A";
    case 6: return "#3B5A99";
    case 7: return "#74ABF8";
    case 8: return "#6992AC";
    default:
            return "#ffffff";
    }
}

//
// Subscriber callback
//
void ViewerSubscriberCallback::CallbackControl(SF::Topic::Control::CategoryType category, const std::string & json)
{
    SFASSERT(false);
}

void ViewerSubscriberCallback::CallbackData(SF::Topic::Data::CategoryType category, const std::string & json)
{
    std::string categoryName;
    switch (category) {
    case SF::Topic::Data::MONITOR:
        categoryName = "MONITOR";
        break;
    case SF::Topic::Data::EVENT:
        categoryName = "EVENT";
        break;
    case SF::Topic::Data::READ_RES:
        categoryName = "READ_RES";
        break;
    default:
        categoryName = "INVALID";
        break;
    }

#if VERBOSE
    SFLOG_INFO << "message received - topic: " << TopicName << ", category: " << categoryName << " ]" << std::endl;
    if (category == SF::Topic::Data::READ_RES) {
        std::cout << "ViewerSubscriberCallback:" << __LINE__ << " Received json => " << json << std::endl;
    }
#endif

    // input JSON: state information from CASROS
    SF::JSON in;
    if (!in.Read(json.c_str())) {
        SFLOG_ERROR << "Failed to parse json: " << json << std::endl;
        return;
    }

    const SF::JSON::JSONVALUE & inroot = in.GetRoot();

    // Get target safety coordinator (assigned as process name in cisst)
    //const std::string targetProcessName =
        //JSON::GetSafeValueString(inroot["target"], "safety_coordinator");
    //const std::string thisProcessName = mtsManagerLocal::GetInstance()->GetProcessName();
    //if (targetProcessName.compare("*") != 0 && (targetProcessName != thisProcessName))
        //return;

    // Check command type
    const std::string cmd = SF::JSON::GetSafeValueString(inroot, "cmd");
    if (cmd.compare("message") == 0) {
        std::cout << SF::JSON::GetSafeValueString(inroot, "msg") << std::endl;
        return;
    } else {
        if (cmd.compare("state_list") != 0) {
            SFLOG_INFO << "not state information: " << cmd << std::endl;
            return;
        }
    }

    // extract name of safety coordinator
    const std::string nameOfThisSC = SF::JSON::GetSafeValueString(inroot, "safety_coordinator");
    // update state cache (overwrite)
    CasrosSystemStatesRoot[nameOfThisSC] = inroot;

    // placeholder for D3
    SF::JSON D3States;
    SF::JSON::JSONVALUE D3StatesRoot = D3States.GetRoot();

    // iterate each state cache instance, convert it to D3 format, and stack it up.
    size_t cntSC = 0;
    JSON::JSONVALUE::iterator it = CasrosSystemStatesRoot.begin();
    const JSON::JSONVALUE::iterator itEnd = CasrosSystemStatesRoot.end();
    for (; it != itEnd; ++it) {
        SF::JSON outSC;
        SF::JSON::JSONVALUE & outSCroot = outSC.GetRoot();
        GenerateD3JSON(*it, outSCroot);
        D3StatesRoot[cntSC++] = outSCroot;
    }

    // get json-encoded string for state viewer
    const std::string outJson = SF::JSON::GetJSONString(D3StatesRoot);

    // Reset color code
    SCColorCode = 0;

    // refresh state chart
    QJsApiHandler::UpdateJSONState(outJson);
}

void ViewerSubscriberCallback::GenerateD3JSON(const JSON::JSONVALUE & inroot, JSON::JSONVALUE & outSCroot)
{
    // safety coordinator name
    outSCroot["name"] = SF::JSON::GetSafeValueString(inroot, "safety_coordinator");
    outSCroot["color"] = GetColorCodeForSafetyCoordinator();

    // for each component
    const JSON::JSONVALUE inComponents = inroot["components"];
    for (size_t i = 0; i < inComponents.size(); ++i) {
        // inputs for component
        const JSON::JSONVALUE inComponent = inComponents[i];
        // outputs for component
        SF::JSON outComponent;
        SF::JSON::JSONVALUE & outComponentRoot = outComponent.GetRoot();
        {
            // component name
            outComponentRoot["name"] = inComponent["name"];
            outComponentRoot["color"] = GetColorCodeForState(JSON::GetSafeValueUInt(inComponent, "s"), true);

            // outputs for component state (three views: system, framework, application)
            SF::JSON outStateComponent;
            SF::JSON::JSONVALUE & outStateComponentRoot = outStateComponent.GetRoot();
            // Get system view of component state
            SF::State stateComponentSystemView, stateComponentFrameworkView, stateComponentAppView;
            stateComponentFrameworkView = static_cast<State::StateType>(JSON::GetSafeValueUInt(inComponent["s_F"], "state"));
            stateComponentAppView       = static_cast<State::StateType>(JSON::GetSafeValueUInt(inComponent["s_A"], "state"));
            stateComponentSystemView = stateComponentFrameworkView * stateComponentAppView;

            outStateComponentRoot["name"] = "Component";
            outStateComponentRoot["color"] = GetColorCodeForState(stateComponentSystemView.GetState(), true);
            {
                size_t cntComponentState = 0;
                SF::JSON outStateFramework;
                SF::JSON::JSONVALUE & outStateFrameworkRoot = outStateFramework.GetRoot();
                {
                    outStateFrameworkRoot["name"] = "Framework";
                    outStateFrameworkRoot["color"] = GetColorCodeForState(stateComponentFrameworkView.GetState());
                    if (inComponent["s_F"]["event"] != JSON::JSONVALUE::null)
                        outStateFrameworkRoot["pendingevent"] = JSON::GetJSONString(inComponent["s_F"]["event"]);
                }
                outStateComponentRoot["children"][cntComponentState++] = outStateFrameworkRoot;

                SF::JSON outStateApp;
                SF::JSON::JSONVALUE & outStateAppRoot = outStateApp.GetRoot();
                {
                    outStateAppRoot["name"] = "Application";
                    outStateAppRoot["color"] = GetColorCodeForState(stateComponentAppView.GetState());
                    if (inComponent["s_A"]["event"] != JSON::JSONVALUE::null)
                        outStateAppRoot["pendingevent"] = JSON::GetJSONString(inComponent["s_A"]["event"]);
                }
                outStateComponentRoot["children"][cntComponentState++] = outStateAppRoot;
            }
            size_t j = 0;
            outComponentRoot["children"][j++] = outStateComponentRoot;

            // outputs for provided interface
            // for each interface
            const JSON::JSONVALUE inPrvInterfaces = inComponent["interfaces_provided"];
            const size_t cntProvided = inPrvInterfaces.size();
            for (size_t k = 0; k < cntProvided; ++k) {
                // input for provided interface
                const JSON::JSONVALUE inPrvInterface = inPrvInterfaces[k];
                // output for provided interface
                SF::JSON outInterfaceProvidedEach;
                SF::JSON::JSONVALUE & outInterfaceProvidedEachRoot = outInterfaceProvidedEach.GetRoot();
                {
                    outInterfaceProvidedEachRoot["name"] = "Service";
                    outInterfaceProvidedEachRoot["color"] =
                        GetColorCodeForState(JSON::GetSafeValueUInt(inPrvInterface, "service_state"), true);

                    size_t cnt = 0;
                    outInterfaceProvidedEachRoot["children"][cnt]["name"] = inPrvInterface["name"];
                    outInterfaceProvidedEachRoot["children"][cnt]["color"] =
                        GetColorCodeForState(JSON::GetSafeValueUInt(inPrvInterface, "state"));
                    if (inPrvInterface["event"] != JSON::JSONVALUE::null)
                        outInterfaceProvidedEachRoot["pendingevent"] = JSON::GetJSONString(inPrvInterface["event"]);
                }
                //outInterfaceProvidedRoot["children"][k] = outInterfaceProvidedEachRoot;

                outComponentRoot["children"][j++] = outInterfaceProvidedEachRoot;
            }

            // outputs for required interface
            SF::JSON outInterfaceRequired;
            SF::JSON::JSONVALUE & outInterfaceRequiredRoot = outInterfaceRequired.GetRoot();
            size_t cntRequired = 0;
            {
                outInterfaceRequiredRoot["name"] = "Required";
                outInterfaceRequiredRoot["color"] = GetColorCodeForState(JSON::GetSafeValueUInt(inComponent, "s_R"), true);

                // for each interface
                const JSON::JSONVALUE inReqInterfaces = inComponent["interfaces_required"];
                cntRequired = inReqInterfaces.size();
                for (size_t k = 0; k < cntRequired; ++k) {
                    // input for provided interface
                    const JSON::JSONVALUE inReqInterface = inReqInterfaces[k];
                    // output for provided interface
                    SF::JSON outInterfaceRequiredEach;
                    SF::JSON::JSONVALUE & outInterfaceRequiredEachRoot = outInterfaceRequiredEach.GetRoot();
                    {
                        outInterfaceRequiredEachRoot["name"] = inReqInterface["name"];
                        outInterfaceRequiredEachRoot["color"] =
                            GetColorCodeForState(JSON::GetSafeValueUInt(inReqInterface, "state"));
                        // TODO: add pending event semantics to required interfaces later.
                        //if (JSON::GetJSONString(inReqInterface["event"]) != JSON::JSONVALUE::null)
                        //    outInterfaceRequiredEachRoot["pendingevent"] = JSON::GetJSONString(inReqInterface["event"]);
                    }
                    outInterfaceRequiredRoot["children"][k] = outInterfaceRequiredEachRoot;
                }
            }
            if (cntRequired)
                outComponentRoot["children"][j++] = outInterfaceRequiredRoot;
        }
        outSCroot["children"][i] = outComponentRoot;
    }
    //std::cout << "###### " << JSON::GetJSONString(outSCroot) << std::endl;
}

//
// CASROS accessor for console
//
AccessorViewer::AccessorViewer(void)
    : SF::cisstAccessor(true,  // enablePublisherControl
                        false, // enablePublisherData
                        false,  // enableSubscriberControl
                        true,  // enableSubscriberData
                        0,//new ViewerSubscriberCallback(SF::Dict::TopicNames::CONTROL),
                        new ViewerSubscriberCallback(SF::Dict::TopicNames::DATA))
{
}

bool AccessorViewer::RequestStateList(const std::string & safetyCoordinatorName,
                                      const std::string & componentName) const
{
    std::stringstream ss;
    ss << "{ \"target\": { \"safety_coordinator\": \"" << safetyCoordinatorName << "\", "
          "\"component\": \"" << componentName << "\" }, "
          "\"request\": \"state_list\" }";
    if (!Publishers.Control->PublishControl(SF::Topic::Control::READ_REQ, ss.str())) {
        std::cerr << "RequestStateList: Failed to publish message (Control, READ_REQ): " << ss.str() << std::endl;
        return false;
    }

    std::cout << "requested list of states" << std::endl;

    return true;
}
<commit_msg>state viewer: now outstanding event of required interface shows up<commit_after>//------------------------------------------------------------------------
//
// CASROS: Component-based Architecture for Safe Robotic Systems
//
// Copyright (C) 2012-2014 Min Yang Jung and Peter Kazanzides
//
//------------------------------------------------------------------------
//
// Created on   : Jul 10, 2014
// Last revision: Jul 28, 2014
// Author       : Min Yang Jung (myj@jhu.edu)
// Github       : https://github.com/minyang/casros
//
#include "accessor.h"
#include "QtJsBridge/jsApiHandler.h"
#include <cisstMultiTask/mtsManagerLocal.h>

#include <iomanip>

#define VERBOSE 0

using namespace SF;

// JSON object that has complete information of all states of the entire system (including
// multiple processes)
// TODO: issue of shared resource with this
SF::JSON CasrosSystemStates;
SF::JSON::JSONVALUE & CasrosSystemStatesRoot = CasrosSystemStates.GetRoot();

// for safety coordinator color selection
static int SCColorCode = 0;

#define COLOR_RED1    "#ff0000"
#define COLOR_RED2    "#c91a26"
#define COLOR_YELLOW1 "#fffa00"
#define COLOR_YELLOW2 "#ffda00"
#define COLOR_WHITE   "#ffffff"
#define COLOR_GREY    "#e3e7ee"

const std::string GetColorCodeForState(unsigned int state, bool projectedState = false)
{
    if (projectedState) {
        switch (static_cast<State::StateType>(state)) {
        case State::NORMAL:  return COLOR_GREY;
        case State::WARNING: return COLOR_YELLOW2;
        case State::ERROR:   return COLOR_RED2;
        case State::FAILURE:
        case State::INVALID: return "black";
        }
    } else {
        switch (static_cast<State::StateType>(state)) {
        case State::NORMAL:  return COLOR_WHITE;
        case State::WARNING: return COLOR_YELLOW1;
        case State::ERROR:   return COLOR_RED1;
        case State::FAILURE:
        case State::INVALID: return "green";
        }
    }
}

const std::string GetColorCodeForSafetyCoordinator(void)
{
    // ref: http://www.dtelepathy.com/blog/inspiration/beautiful-color-palettes-for-your-next-web-project
    const int N = 5;

    switch (SCColorCode++ % N) {
    case 0: return "#2e6093";
    case 1: return "#3a5988";
    case 2: return "#9d4e87";
    case 3: return "#92538c";
    case 4: return "#72659d";
    case 5: return "#293E6A";
    case 6: return "#3B5A99";
    case 7: return "#74ABF8";
    case 8: return "#6992AC";
    default:
            return "#ffffff";
    }
}

//
// Subscriber callback
//
void ViewerSubscriberCallback::CallbackControl(SF::Topic::Control::CategoryType category, const std::string & json)
{
    SFASSERT(false);
}

void ViewerSubscriberCallback::CallbackData(SF::Topic::Data::CategoryType category, const std::string & json)
{
    std::string categoryName;
    switch (category) {
    case SF::Topic::Data::MONITOR:
        categoryName = "MONITOR";
        break;
    case SF::Topic::Data::EVENT:
        categoryName = "EVENT";
        break;
    case SF::Topic::Data::READ_RES:
        categoryName = "READ_RES";
        break;
    default:
        categoryName = "INVALID";
        break;
    }

#if VERBOSE
    SFLOG_INFO << "message received - topic: " << TopicName << ", category: " << categoryName << " ]" << std::endl;
    if (category == SF::Topic::Data::READ_RES) {
        std::cout << "ViewerSubscriberCallback:" << __LINE__ << " Received json => " << json << std::endl;
    }
#endif

    // input JSON: state information from CASROS
    SF::JSON in;
    if (!in.Read(json.c_str())) {
        SFLOG_ERROR << "Failed to parse json: " << json << std::endl;
        return;
    }

    const SF::JSON::JSONVALUE & inroot = in.GetRoot();

    // Get target safety coordinator (assigned as process name in cisst)
    //const std::string targetProcessName =
        //JSON::GetSafeValueString(inroot["target"], "safety_coordinator");
    //const std::string thisProcessName = mtsManagerLocal::GetInstance()->GetProcessName();
    //if (targetProcessName.compare("*") != 0 && (targetProcessName != thisProcessName))
        //return;

    // Check command type
    const std::string cmd = SF::JSON::GetSafeValueString(inroot, "cmd");
    if (cmd.compare("message") == 0) {
        std::cout << SF::JSON::GetSafeValueString(inroot, "msg") << std::endl;
        return;
    } else {
        if (cmd.compare("state_list") != 0) {
            SFLOG_INFO << "not state information: " << cmd << std::endl;
            return;
        }
    }

    // extract name of safety coordinator
    const std::string nameOfThisSC = SF::JSON::GetSafeValueString(inroot, "safety_coordinator");
    // update state cache (overwrite)
    CasrosSystemStatesRoot[nameOfThisSC] = inroot;

    // placeholder for D3
    SF::JSON D3States;
    SF::JSON::JSONVALUE D3StatesRoot = D3States.GetRoot();

    // iterate each state cache instance, convert it to D3 format, and stack it up.
    size_t cntSC = 0;
    JSON::JSONVALUE::iterator it = CasrosSystemStatesRoot.begin();
    const JSON::JSONVALUE::iterator itEnd = CasrosSystemStatesRoot.end();
    for (; it != itEnd; ++it) {
        SF::JSON outSC;
        SF::JSON::JSONVALUE & outSCroot = outSC.GetRoot();
        GenerateD3JSON(*it, outSCroot);
        D3StatesRoot[cntSC++] = outSCroot;
    }

    // get json-encoded string for state viewer
    const std::string outJson = SF::JSON::GetJSONString(D3StatesRoot);

    // Reset color code
    SCColorCode = 0;

    // refresh state chart
    QJsApiHandler::UpdateJSONState(outJson);
}

void ViewerSubscriberCallback::GenerateD3JSON(const JSON::JSONVALUE & inroot, JSON::JSONVALUE & outSCroot)
{
    // safety coordinator name
    outSCroot["name"] = SF::JSON::GetSafeValueString(inroot, "safety_coordinator");
    outSCroot["color"] = GetColorCodeForSafetyCoordinator();

    // for each component
    const JSON::JSONVALUE inComponents = inroot["components"];
    for (size_t i = 0; i < inComponents.size(); ++i) {
        // inputs for component
        const JSON::JSONVALUE inComponent = inComponents[i];
        // outputs for component
        SF::JSON outComponent;
        SF::JSON::JSONVALUE & outComponentRoot = outComponent.GetRoot();
        {
            // component name
            outComponentRoot["name"] = inComponent["name"];
            outComponentRoot["color"] = GetColorCodeForState(JSON::GetSafeValueUInt(inComponent, "s"), true);

            // outputs for component state (three views: system, framework, application)
            SF::JSON outStateComponent;
            SF::JSON::JSONVALUE & outStateComponentRoot = outStateComponent.GetRoot();
            // Get system view of component state
            SF::State stateComponentSystemView, stateComponentFrameworkView, stateComponentAppView;
            stateComponentFrameworkView = static_cast<State::StateType>(JSON::GetSafeValueUInt(inComponent["s_F"], "state"));
            stateComponentAppView       = static_cast<State::StateType>(JSON::GetSafeValueUInt(inComponent["s_A"], "state"));
            stateComponentSystemView = stateComponentFrameworkView * stateComponentAppView;

            outStateComponentRoot["name"] = "Component";
            outStateComponentRoot["color"] = GetColorCodeForState(stateComponentSystemView.GetState(), true);
            {
                size_t cntComponentState = 0;
                SF::JSON outStateFramework;
                SF::JSON::JSONVALUE & outStateFrameworkRoot = outStateFramework.GetRoot();
                {
                    outStateFrameworkRoot["name"] = "Framework";
                    outStateFrameworkRoot["color"] = GetColorCodeForState(stateComponentFrameworkView.GetState());
                    if (inComponent["s_F"]["event"] != JSON::JSONVALUE::null)
                        outStateFrameworkRoot["pendingevent"] = JSON::GetJSONString(inComponent["s_F"]["event"]);
                }
                outStateComponentRoot["children"][cntComponentState++] = outStateFrameworkRoot;

                SF::JSON outStateApp;
                SF::JSON::JSONVALUE & outStateAppRoot = outStateApp.GetRoot();
                {
                    outStateAppRoot["name"] = "Application";
                    outStateAppRoot["color"] = GetColorCodeForState(stateComponentAppView.GetState());
                    if (inComponent["s_A"]["event"] != JSON::JSONVALUE::null)
                        outStateAppRoot["pendingevent"] = JSON::GetJSONString(inComponent["s_A"]["event"]);
                }
                outStateComponentRoot["children"][cntComponentState++] = outStateAppRoot;
            }
            size_t j = 0;
            outComponentRoot["children"][j++] = outStateComponentRoot;

            // outputs for provided interface
            // for each interface
            const JSON::JSONVALUE inPrvInterfaces = inComponent["interfaces_provided"];
            const size_t cntProvided = inPrvInterfaces.size();
            for (size_t k = 0; k < cntProvided; ++k) {
                // input for provided interface
                const JSON::JSONVALUE inPrvInterface = inPrvInterfaces[k];
                // output for provided interface
                SF::JSON outInterfaceProvidedEach;
                SF::JSON::JSONVALUE & outInterfaceProvidedEachRoot = outInterfaceProvidedEach.GetRoot();
                {
                    outInterfaceProvidedEachRoot["name"] = "Service";
                    outInterfaceProvidedEachRoot["color"] =
                        GetColorCodeForState(JSON::GetSafeValueUInt(inPrvInterface, "service_state"), true);

                    size_t cnt = 0;
                    outInterfaceProvidedEachRoot["children"][cnt]["name"] = inPrvInterface["name"];
                    outInterfaceProvidedEachRoot["children"][cnt]["color"] =
                        GetColorCodeForState(JSON::GetSafeValueUInt(inPrvInterface, "state"));
                    if (inPrvInterface["event"] != JSON::JSONVALUE::null)
                        outInterfaceProvidedEachRoot["pendingevent"] = JSON::GetJSONString(inPrvInterface["event"]);
                }
                //outInterfaceProvidedRoot["children"][k] = outInterfaceProvidedEachRoot;

                outComponentRoot["children"][j++] = outInterfaceProvidedEachRoot;
            }

            // outputs for required interface
            SF::JSON outInterfaceRequired;
            SF::JSON::JSONVALUE & outInterfaceRequiredRoot = outInterfaceRequired.GetRoot();
            size_t cntRequired = 0;
            {
                outInterfaceRequiredRoot["name"] = "Required";
                outInterfaceRequiredRoot["color"] = GetColorCodeForState(JSON::GetSafeValueUInt(inComponent["s_R"], "state"), true);
                if (inComponent["s_R"]["event"] != JSON::JSONVALUE::null)
                    outInterfaceRequiredRoot["pendingevent"] = JSON::GetJSONString(inComponent["s_R"]["event"]);

                // for each interface
                const JSON::JSONVALUE inReqInterfaces = inComponent["interfaces_required"];
                cntRequired = inReqInterfaces.size();
                for (size_t k = 0; k < cntRequired; ++k) {
                    // input for provided interface
                    const JSON::JSONVALUE inReqInterface = inReqInterfaces[k];
                    // output for provided interface
                    SF::JSON outInterfaceRequiredEach;
                    SF::JSON::JSONVALUE & outInterfaceRequiredEachRoot = outInterfaceRequiredEach.GetRoot();
                    {
                        outInterfaceRequiredEachRoot["name"] = inReqInterface["name"];
                        outInterfaceRequiredEachRoot["color"] =
                            GetColorCodeForState(JSON::GetSafeValueUInt(inReqInterface, "state"));
                        if (inReqInterface["event"] != JSON::JSONVALUE::null)
                            outInterfaceRequiredEachRoot["pendingevent"] = JSON::GetJSONString(inReqInterface["event"]);
                    }
                    outInterfaceRequiredRoot["children"][k] = outInterfaceRequiredEachRoot;
                }
            }
            if (cntRequired)
                outComponentRoot["children"][j++] = outInterfaceRequiredRoot;
        }
        outSCroot["children"][i] = outComponentRoot;
    }
    //std::cout << "###### " << JSON::GetJSONString(outSCroot) << std::endl;
}

//
// CASROS accessor for console
//
AccessorViewer::AccessorViewer(void)
    : SF::cisstAccessor(true,  // enablePublisherControl
                        false, // enablePublisherData
                        false,  // enableSubscriberControl
                        true,  // enableSubscriberData
                        0,//new ViewerSubscriberCallback(SF::Dict::TopicNames::CONTROL),
                        new ViewerSubscriberCallback(SF::Dict::TopicNames::DATA))
{
}

bool AccessorViewer::RequestStateList(const std::string & safetyCoordinatorName,
                                      const std::string & componentName) const
{
    std::stringstream ss;
    ss << "{ \"target\": { \"safety_coordinator\": \"" << safetyCoordinatorName << "\", "
          "\"component\": \"" << componentName << "\" }, "
          "\"request\": \"state_list\" }";
    if (!Publishers.Control->PublishControl(SF::Topic::Control::READ_REQ, ss.str())) {
        std::cerr << "RequestStateList: Failed to publish message (Control, READ_REQ): " << ss.str() << std::endl;
        return false;
    }

    std::cout << "requested list of states" << std::endl;

    return true;
}
<|endoftext|>


<commit_before>/*
 * Priority.cpp
 *
 * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
 * Copyright 2000, Bastiaan Bakker. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#include "PortabilityImpl.hh"
#include <log4cpp/Priority.hh>
#include <cstdlib>

namespace log4cpp {

    namespace {
        const std::string names[10] = {
            "FATAL", "ALERT", "CRIT", "ERROR", "WARN",
            "NOTICE", "INFO", "DEBUG", "NOTSET", "UNKNOWN"
        };
    }

    const std::string& Priority::getPriorityName(int priority) throw() {

        priority++;
        priority /= 100;
        return names[((priority < 0) || (priority > 8)) ? 8 : priority];
    }

    Priority::Value Priority::getPriorityValue(const std::string& priorityName)
    throw(std::invalid_argument) {
	Priority::Value value = -1;

	for (unsigned int i = 0; i < 10; i++) {
	    if (priorityName == names[i]) {
		value = i * 100;
		break;
	    }
	}

	if (value == -1) {
	    if (priorityName == "EMERG") {
		value = 0;
	    } else {
		char* endPointer;
		value = std::strtoul(priorityName.c_str(), &endPointer, 10);
		if (*endPointer != 0) {
		    throw std::invalid_argument(std::string("unknown priority name: '") + priorityName + "'");
		}
	    }
	}

	return value;
    }
}
<commit_msg>Align literals for a better visibility<commit_after>/*
 * Priority.cpp
 *
 * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
 * Copyright 2000, Bastiaan Bakker. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#include "PortabilityImpl.hh"
#include <log4cpp/Priority.hh>
#include <cstdlib>

namespace log4cpp {

    namespace {
        const std::string names[10] = {
            "FATAL",
			"ALERT",
			"CRIT",
			"ERROR",
			"WARN",
            "NOTICE",
			"INFO",
			"DEBUG",
			"NOTSET",
			"UNKNOWN"
        };
    }

    const std::string& Priority::getPriorityName(int priority) throw() {

        priority++;
        priority /= 100;
        return names[((priority < 0) || (priority > 8)) ? 8 : priority];
    }

    Priority::Value Priority::getPriorityValue(const std::string& priorityName)
    throw(std::invalid_argument) {
	Priority::Value value = -1;

	for (unsigned int i = 0; i < 10; i++) {
	    if (priorityName == names[i]) {
		value = i * 100;
		break;
	    }
	}

	if (value == -1) {
	    if (priorityName == "EMERG") {
		value = 0;
	    } else {
		char* endPointer;
		value = std::strtoul(priorityName.c_str(), &endPointer, 10);
		if (*endPointer != 0) {
		    throw std::invalid_argument(std::string("unknown priority name: '") + priorityName + "'");
		}
	    }
	}

	return value;
    }
}
<|endoftext|>


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

#include "zip.h"

#include <cstdio>
#include <vector>

#include "zlib/contrib/minizip/zip.h"
#include "zip_internal.h"
#include "zip_reader.h"
#include "zip_utils.h"

#if defined(OS_WIN)
#include <windows.h>
#elif defined(OS_POSIX)
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <utime.h>
#endif

namespace {

// Get all relative file paths from root_path.
std::vector<std::string> GetAllFilesFromDirectory(
    const std::string& root_path, const std::string& relative_path) {
  std::string absolute_path = root_path + "/" + relative_path;
  DIR* dir = opendir(absolute_path.c_str());
  std::vector<std::string> files;
  if (dir != NULL) {
    struct dirent* entry;
    while((entry = readdir(dir))) {
      if (strcmp(entry->d_name, "..") == 0 ||
          strcmp(entry->d_name, ".") == 0) {
        continue;
      }
      std::string entry_relative_file_path;
      if (relative_path.empty())
        entry_relative_file_path = std::string(entry->d_name);
      else
        entry_relative_file_path = relative_path + "/" +
            std::string(entry->d_name);
      if (entry->d_type & DT_DIR) {
        std::vector<std::string> sub_files = GetAllFilesFromDirectory(
            absolute_path, entry_relative_file_path);
        files.insert(files.end(), sub_files.begin(), sub_files.end());
      } else {
        files.push_back(entry_relative_file_path);
      }
    }
  }
  return files;
}

//Returns a zip_fileinfo with the last modification date of |path| set.
bool GetFileInfoForZipping(const std::string& path, zip_fileinfo* zip_info) {
#ifdef OS_POSIX
  struct stat s;
  if (stat(path.c_str(), &s) == 0) {
    struct tm* file_date = localtime(&s.st_mtime);
    zip_info->tmz_date.tm_sec  = file_date->tm_sec;
    zip_info->tmz_date.tm_min  = file_date->tm_min;
    zip_info->tmz_date.tm_hour = file_date->tm_hour;
    zip_info->tmz_date.tm_mday = file_date->tm_mday;
    zip_info->tmz_date.tm_mon  = file_date->tm_mon ;
    zip_info->tmz_date.tm_year = file_date->tm_year;
    return true;
  }
#endif
  return false;
}

bool AddFileToZip(zipFile zip_file, const std::string& absolute_path) {
  FILE* file = fopen(absolute_path.c_str(), "rb");
  if (!file)
    return false;
  int num_bytes;
  char buf[zip::internal::kZipBufSize];

  do {
    num_bytes = fread(buf, sizeof(char), zip::internal::kZipBufSize, file);
    if (num_bytes > 0) {
      if (ZIP_OK != zipWriteInFileInZip(zip_file, buf, num_bytes))
        return false;
    }
  } while (num_bytes > 0);

  std::fclose(file);
  return true;
}

bool AddEntryToZip(zipFile zip_file, const std::string& root_path,
                   const std::string& relative_path) {
  std::string parent_path = root_path;
#if defined(OS_WIN)
  std::replace(parent_path.begin(), parent_path.end(), '\\', '/');
#endif
  zip_fileinfo file_info = {};
  std::string absolute_path = zip::utils::RemoveExtraFileSeparator(
      parent_path + "/" + relative_path);
  GetFileInfoForZipping(absolute_path, &file_info);

  // Section 4.4.4 http://www.pkware.com/documents/casestudies/APPNOTE.TXT
  // Setting the Language encoding flag so the file is told to be in utf-8.
  const uLong LANGUAGE_ENCODING_FLAG = 0x1 << 11;

  if (ZIP_OK != zipOpenNewFileInZip4(
                    zip_file,  // file
                    relative_path.c_str(),  // relative filename
                    &file_info,  // zipfi
                    NULL,  // extrafield_local,
                    0u,  // size_extrafield_local
                    NULL,  // extrafield_global
                    0u,  // size_extrafield_global
                    NULL,  // comment
                    Z_DEFLATED,  // method
                    Z_DEFAULT_COMPRESSION,  // level
                    0,  // raw
                    -MAX_WBITS,  // windowBits
                    DEF_MEM_LEVEL,  // memLevel
                    Z_DEFAULT_STRATEGY,  // strategy
                    NULL,  // password
                    0,  // crcForCrypting
                    0,  // versionMadeBy
                    LANGUAGE_ENCODING_FLAG)) {  // flagBase
    return false;
  }

  bool success = true;
  success = AddFileToZip(zip_file, absolute_path);

  if (ZIP_OK != zipCloseFileInZip(zip_file))
    return false;

  return success;
}

}  // namespace

namespace zip {

bool Zip(const std::string& src_dir, const std::string& dest_file,
         std::string* error) {
  zipFile zip_file = internal::OpenForZipping(dest_file.c_str(),
                                              APPEND_STATUS_CREATE);
  if (!zip_file) {
    if (error)
      *error = "Couldn't create file " + dest_file + ".";
    return false;
  }

  std::vector<std::string> files = GetAllFilesFromDirectory(src_dir, "");
  for (size_t i = 0; i < files.size(); ++i) {
    if (!AddEntryToZip(zip_file, src_dir, files[i])) {
      if (error)
        *error = "Fail to add " + files[i] + " to zip.";
      return false;
    }
  }
  if (ZIP_OK != zipClose(zip_file, NULL)) {
    if (error)
      *error = "Error closing zip file " + dest_file + ".";
    return false;
  }
  return true;
}

bool Unzip(const std::string& zip_file, const std::string& dest_dir,
           std::string* error) {
  if (dest_dir.empty()) {
    if (error)
      *error = "dest_dir shouldn't be empty.";
    return false;
  }

  ZipReader reader;
  if (!reader.Open(zip_file)) {
    if (error)
      *error = "Failed to open " + zip_file + ".";
    return false;
  }
  while (reader.HasMore()) {
    if (!reader.OpenCurrentEntryInZip()) {
      if (error)
        *error = "Failed to open the current file in zip.";
      return false;
    }
    if (!reader.ExtractCurrentEntryIntoDirectory(dest_dir)) {
      if (error)
        *error = "Failed to extract " +
            reader.current_entry_info()->file_path;
      return false;
    }
    if (!reader.AdvanceToNextEntry()) {
      if (error)
        *error = "Failed to advance to the next file";
      return false;
    }
  }
  return true;
}

}  // namespace zip
<commit_msg>Check whether src_dir is existent before zipping.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "zip.h"

#include <cstdio>
#include <vector>

#include "zlib/contrib/minizip/zip.h"
#include "zip_internal.h"
#include "zip_reader.h"
#include "zip_utils.h"

#if defined(OS_WIN)
#include <windows.h>
#elif defined(OS_POSIX)
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <utime.h>
#endif

namespace {

// Get all relative file paths from root_path.
std::vector<std::string> GetAllFilesFromDirectory(
    const std::string& root_path, const std::string& relative_path) {
  std::string absolute_path = root_path + "/" + relative_path;
  DIR* dir = opendir(absolute_path.c_str());
  std::vector<std::string> files;
  if (dir != NULL) {
    struct dirent* entry;
    while((entry = readdir(dir))) {
      if (strcmp(entry->d_name, "..") == 0 ||
          strcmp(entry->d_name, ".") == 0) {
        continue;
      }
      std::string entry_relative_file_path;
      if (relative_path.empty())
        entry_relative_file_path = std::string(entry->d_name);
      else
        entry_relative_file_path = relative_path + "/" +
            std::string(entry->d_name);
      if (entry->d_type & DT_DIR) {
        std::vector<std::string> sub_files = GetAllFilesFromDirectory(
            absolute_path, entry_relative_file_path);
        files.insert(files.end(), sub_files.begin(), sub_files.end());
      } else {
        files.push_back(entry_relative_file_path);
      }
    }
  }
  return files;
}

//Returns a zip_fileinfo with the last modification date of |path| set.
bool GetFileInfoForZipping(const std::string& path, zip_fileinfo* zip_info) {
#ifdef OS_POSIX
  struct stat s;
  if (stat(path.c_str(), &s) == 0) {
    struct tm* file_date = localtime(&s.st_mtime);
    zip_info->tmz_date.tm_sec  = file_date->tm_sec;
    zip_info->tmz_date.tm_min  = file_date->tm_min;
    zip_info->tmz_date.tm_hour = file_date->tm_hour;
    zip_info->tmz_date.tm_mday = file_date->tm_mday;
    zip_info->tmz_date.tm_mon  = file_date->tm_mon ;
    zip_info->tmz_date.tm_year = file_date->tm_year;
    return true;
  }
#endif
  return false;
}

bool AddFileToZip(zipFile zip_file, const std::string& absolute_path) {
  FILE* file = fopen(absolute_path.c_str(), "rb");
  if (!file)
    return false;
  int num_bytes;
  char buf[zip::internal::kZipBufSize];

  do {
    num_bytes = fread(buf, sizeof(char), zip::internal::kZipBufSize, file);
    if (num_bytes > 0) {
      if (ZIP_OK != zipWriteInFileInZip(zip_file, buf, num_bytes))
        return false;
    }
  } while (num_bytes > 0);

  std::fclose(file);
  return true;
}

bool AddEntryToZip(zipFile zip_file, const std::string& root_path,
                   const std::string& relative_path) {
  std::string parent_path = root_path;
#if defined(OS_WIN)
  std::replace(parent_path.begin(), parent_path.end(), '\\', '/');
#endif
  zip_fileinfo file_info = {};
  std::string absolute_path = zip::utils::RemoveExtraFileSeparator(
      parent_path + "/" + relative_path);
  GetFileInfoForZipping(absolute_path, &file_info);

  // Section 4.4.4 http://www.pkware.com/documents/casestudies/APPNOTE.TXT
  // Setting the Language encoding flag so the file is told to be in utf-8.
  const uLong LANGUAGE_ENCODING_FLAG = 0x1 << 11;

  if (ZIP_OK != zipOpenNewFileInZip4(
                    zip_file,  // file
                    relative_path.c_str(),  // relative filename
                    &file_info,  // zipfi
                    NULL,  // extrafield_local,
                    0u,  // size_extrafield_local
                    NULL,  // extrafield_global
                    0u,  // size_extrafield_global
                    NULL,  // comment
                    Z_DEFLATED,  // method
                    Z_DEFAULT_COMPRESSION,  // level
                    0,  // raw
                    -MAX_WBITS,  // windowBits
                    DEF_MEM_LEVEL,  // memLevel
                    Z_DEFAULT_STRATEGY,  // strategy
                    NULL,  // password
                    0,  // crcForCrypting
                    0,  // versionMadeBy
                    LANGUAGE_ENCODING_FLAG)) {  // flagBase
    return false;
  }

  bool success = true;
  success = AddFileToZip(zip_file, absolute_path);

  if (ZIP_OK != zipCloseFileInZip(zip_file))
    return false;

  return success;
}

}  // namespace

namespace zip {

bool Zip(const std::string& src_dir, const std::string& dest_file,
         std::string* error) {
  if (!utils::DirectoryExists(src_dir)) {
    if (error)
      *error = "Dir " + src_dir + " is not existent.";
    return false;
  }

  zipFile zip_file = internal::OpenForZipping(dest_file.c_str(),
                                              APPEND_STATUS_CREATE);
  if (!zip_file) {
    if (error)
      *error = "Couldn't create file " + dest_file + ".";
    return false;
  }

  std::vector<std::string> files = GetAllFilesFromDirectory(src_dir, "");
  for (size_t i = 0; i < files.size(); ++i) {
    if (!AddEntryToZip(zip_file, src_dir, files[i])) {
      if (error)
        *error = "Fail to add " + files[i] + " to zip.";
      return false;
    }
  }
  if (ZIP_OK != zipClose(zip_file, NULL)) {
    if (error)
      *error = "Error closing zip file " + dest_file + ".";
    return false;
  }
  return true;
}

bool Unzip(const std::string& zip_file, const std::string& dest_dir,
           std::string* error) {
  if (dest_dir.empty()) {
    if (error)
      *error = "dest_dir shouldn't be empty.";
    return false;
  }

  ZipReader reader;
  if (!reader.Open(zip_file)) {
    if (error)
      *error = "Failed to open " + zip_file + ".";
    return false;
  }
  while (reader.HasMore()) {
    if (!reader.OpenCurrentEntryInZip()) {
      if (error)
        *error = "Failed to open the current file in zip.";
      return false;
    }
    if (!reader.ExtractCurrentEntryIntoDirectory(dest_dir)) {
      if (error)
        *error = "Failed to extract " +
            reader.current_entry_info()->file_path;
      return false;
    }
    if (!reader.AdvanceToNextEntry()) {
      if (error)
        *error = "Failed to advance to the next file";
      return false;
    }
  }
  return true;
}

}  // namespace zip
<|endoftext|>


<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "AutowiringDebug.h"
#include "Autowired.h"
#include <iomanip>
#include <iostream>
#include <sstream>

using namespace autowiring;
using namespace autowiring::dbg;

#ifdef _MSC_VER
// On Windows, lambda functions start with the key string "class <"
bool autowiring::dbg::IsLambda(const std::type_info& ti) {
  return demangle(ti).compare(0, 7, "class <") == 0;
}
#else
// On other platforms, try to find lambda functions by the presence of forbidden characters
bool autowiring::dbg::IsLambda(const std::type_info& ti) {
  auto name = demangle(ti);
  for (auto cur : name)
    if (
      !('a' <= cur && cur <= 'z') &&
      !('A' <= cur && cur <= 'Z') &&
      !('0' <= cur && cur <= '9')
    )
      return true;
  return false;
}
#endif

static std::string TrimPrefix(std::string name) {
  // "class" or "struct" prefixes should be eliminated
  if (name.compare(0, 6, "class "))
    name = name.substr(5);
  if (name.compare(0, 7, "struct "))
    name = name.substr(6);
  return name;
}

static std::string DemangleWithAutoID(const std::type_info& ti) {
  auto retVal = demangle(ti);

  // prefix is at the beginning of the string, skip over it
  static const char prefix [] = "struct auto_id<";
  if (retVal.compare(0, sizeof(prefix) - 1, prefix) == 0) {
    size_t off = sizeof(prefix) - 1;
    retVal = retVal.substr(off, retVal.length() - off - 2);
  }
  return TrimPrefix(retVal);
}

std::string autowiring::dbg::ContextName(void) {
  AutoCurrentContext ctxt;
  return autowiring::demangle(ctxt->GetSigilType());
}

AutoPacket* autowiring::dbg::CurrentPacket(void) {
  Autowired<AutoPacketFactory> factory;
  if (!factory)
    return nullptr;
  return factory->CurrentPacket().get();
}

static const AutoFilterDescriptor* DescriptorByName(const char* name, const std::vector<AutoFilterDescriptor>& filters) {
  for (const auto& filter : filters) {
    auto type = filter.GetType();
    if (!type)
      continue;

    auto curName = TrimPrefix(demangle(type));
    if (!curName.compare(name))
      return &filter;
  }
  return nullptr;
}

const AutoFilterDescriptor* autowiring::dbg::DescriptorByName(const char* name) {
  Autowired<AutoPacketFactory> factory;
  if (!factory)
    return nullptr;

  return DescriptorByName(name, factory->GetAutoFilters());
}

std::string autowiring::dbg::AutoFilterInfo(const char* name) {
  Autowired<AutoPacketFactory> factory;
  if (!factory)
    return "No factory detected in this context";

  // Obtain all descriptors:
  const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters();

  // Need the root descriptor first
  const AutoFilterDescriptor* desc = DescriptorByName(name, descs);
  if (!desc)
    return "Filter not found";

  std::ostringstream os;
  std::function<void(const AutoFilterDescriptor&, int)> fnCall = [&](const AutoFilterDescriptor& desc, size_t nLevels) {
    auto args = desc.GetAutoFilterArguments();

    for (size_t i = 0; i < desc.GetArity(); i++) {
      // Argument must be an input to the filter we want to know more about
      if (!args[i].is_input)
        continue;

      // Who provides this input?
      for (const auto& providerDesc : descs) {
        auto providerArg = providerDesc.GetArgumentType(args[i].ti);
        if (providerArg && providerArg->is_output) {
          // Need to print information about this provider:
          os << demangle(*args[i].ti) << ' ' << std::string(' ', nLevels) << demangle(*providerDesc.GetType()) << std::endl;

          // The current descriptor provides an input to the parent, recurse
          fnCall(providerDesc, nLevels + 1);
        }
      }
    }
  };

  // Root typename print first:
  os << demangle(desc->GetType()) << std::endl;
  fnCall(*desc, 1);

  auto retVal = os.str();
  return retVal;
}

std::vector<std::string> autowiring::dbg::ListRootDecorations(void) {
  Autowired<AutoPacketFactory> factory;
  if (!factory)
    return std::vector<std::string>{};

  // Obtain all descriptors:
  const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters();

  // Get all baseline descriptor types, figure out what isn't satisfied:
  std::unordered_map<std::type_index, const std::type_info*> outputs;
  std::unordered_map<std::type_index, const std::type_info*> inputs;

  for (const auto& desc : descs) {
    auto args = desc.GetAutoFilterArguments();
    for (size_t i = 0; i < desc.GetArity(); i++)
      (args[i].is_output ? outputs : inputs)[*args[i].ti] = args[i].ti;
  }

  // Remove all inputs that exist in the outputs set:
  for (auto& output : outputs)
    inputs.erase(*output.second);

  // Any remaining inputs are unsatisfied
  std::vector<std::string> retVal;
  for (auto& input : inputs)
    if (input.second)
      retVal.push_back(DemangleWithAutoID(*input.second));
  return retVal;
}

void autowiring::dbg::DebugInit(void) {

}<commit_msg>Fix lambda check on mac and linux<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "AutowiringDebug.h"
#include "Autowired.h"
#include <iomanip>
#include <iostream>
#include <sstream>

using namespace autowiring;
using namespace autowiring::dbg;

#ifdef _MSC_VER
// On Windows, lambda functions start with the key string "class <"
bool autowiring::dbg::IsLambda(const std::type_info& ti) {
  return demangle(ti).compare(0, 7, "class <") == 0;
}
#else
// On other platforms, try to find lambda functions by the presence of forbidden characters
bool autowiring::dbg::IsLambda(const std::type_info& ti) {
  auto name = demangle(ti);
  for (auto cur : name)
    if (
      !('a' <= cur && cur <= 'z') &&
      !('A' <= cur && cur <= 'Z') &&
      !('0' <= cur && cur <= '9') &&
      cur != '_' &&
      cur != ':' &&
      cur != '<' &&
      cur != '>' &&
      cur != ',' &&
      cur != ' '
    )
      return true;
  return false;
}
#endif

static std::string TrimPrefix(std::string name) {
  // "class" or "struct" prefixes should be eliminated
  if (name.compare(0, 6, "class "))
    name = name.substr(5);
  if (name.compare(0, 7, "struct "))
    name = name.substr(6);
  return name;
}

static std::string DemangleWithAutoID(const std::type_info& ti) {
  auto retVal = demangle(ti);

  // prefix is at the beginning of the string, skip over it
  static const char prefix [] = "struct auto_id<";
  if (retVal.compare(0, sizeof(prefix) - 1, prefix) == 0) {
    size_t off = sizeof(prefix) - 1;
    retVal = retVal.substr(off, retVal.length() - off - 2);
  }
  return TrimPrefix(retVal);
}

std::string autowiring::dbg::ContextName(void) {
  AutoCurrentContext ctxt;
  return autowiring::demangle(ctxt->GetSigilType());
}

AutoPacket* autowiring::dbg::CurrentPacket(void) {
  Autowired<AutoPacketFactory> factory;
  if (!factory)
    return nullptr;
  return factory->CurrentPacket().get();
}

static const AutoFilterDescriptor* DescriptorByName(const char* name, const std::vector<AutoFilterDescriptor>& filters) {
  for (const auto& filter : filters) {
    auto type = filter.GetType();
    if (!type)
      continue;

    auto curName = TrimPrefix(demangle(type));
    if (!curName.compare(name))
      return &filter;
  }
  return nullptr;
}

const AutoFilterDescriptor* autowiring::dbg::DescriptorByName(const char* name) {
  Autowired<AutoPacketFactory> factory;
  if (!factory)
    return nullptr;

  return DescriptorByName(name, factory->GetAutoFilters());
}

std::string autowiring::dbg::AutoFilterInfo(const char* name) {
  Autowired<AutoPacketFactory> factory;
  if (!factory)
    return "No factory detected in this context";

  // Obtain all descriptors:
  const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters();

  // Need the root descriptor first
  const AutoFilterDescriptor* desc = DescriptorByName(name, descs);
  if (!desc)
    return "Filter not found";

  std::ostringstream os;
  std::function<void(const AutoFilterDescriptor&, int)> fnCall = [&](const AutoFilterDescriptor& desc, size_t nLevels) {
    auto args = desc.GetAutoFilterArguments();

    for (size_t i = 0; i < desc.GetArity(); i++) {
      // Argument must be an input to the filter we want to know more about
      if (!args[i].is_input)
        continue;

      // Who provides this input?
      for (const auto& providerDesc : descs) {
        auto providerArg = providerDesc.GetArgumentType(args[i].ti);
        if (providerArg && providerArg->is_output) {
          // Need to print information about this provider:
          os << demangle(*args[i].ti) << ' ' << std::string(' ', nLevels) << demangle(*providerDesc.GetType()) << std::endl;

          // The current descriptor provides an input to the parent, recurse
          fnCall(providerDesc, nLevels + 1);
        }
      }
    }
  };

  // Root typename print first:
  os << demangle(desc->GetType()) << std::endl;
  fnCall(*desc, 1);

  auto retVal = os.str();
  return retVal;
}

std::vector<std::string> autowiring::dbg::ListRootDecorations(void) {
  Autowired<AutoPacketFactory> factory;
  if (!factory)
    return std::vector<std::string>{};

  // Obtain all descriptors:
  const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters();

  // Get all baseline descriptor types, figure out what isn't satisfied:
  std::unordered_map<std::type_index, const std::type_info*> outputs;
  std::unordered_map<std::type_index, const std::type_info*> inputs;

  for (const auto& desc : descs) {
    auto args = desc.GetAutoFilterArguments();
    for (size_t i = 0; i < desc.GetArity(); i++)
      (args[i].is_output ? outputs : inputs)[*args[i].ti] = args[i].ti;
  }

  // Remove all inputs that exist in the outputs set:
  for (auto& output : outputs)
    inputs.erase(*output.second);

  // Any remaining inputs are unsatisfied
  std::vector<std::string> retVal;
  for (auto& input : inputs)
    if (input.second)
      retVal.push_back(DemangleWithAutoID(*input.second));
  return retVal;
}

void autowiring::dbg::DebugInit(void) {

}<|endoftext|>


<commit_before>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>

#include "server.h"
#include "duckchat.h"

// TODO Server can accept connections.
// TODO Server handles Login and Logout from users, and keeps records of which users are logged in.
// TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.

//std::string user;

class Channel {
public:
  std::string name;
  std::list<User *> users;

  Channel(std::string name): name(name) {};
};

class User {
public:
  std::string name;
  struct sockaddr_in *address;
  std::list<Channel *> channels;

  User(std::string name, struct sockaddr_in *address): name(name), address(address) {};
};

std::map<std::string, User *> users;
std::map<std::string, Channel *> channels;

void Error(const char *msg) {
  perror(msg);
  exit(1);
}

void ProcessRequest(void *buffer, struct sockaddr_in *address) {
  struct request current_request;
  User *new_user;
  std::map<std::string, User *>::iterator it;

  memcpy(&current_request, buffer, sizeof(struct request));
  std::cout << "request type: " << current_request.req_type << std::endl;
  request_t request_type = current_request.req_type;

  switch(request_type) {
    case REQ_LOGIN:
      struct request_login login_request;
      memcpy(&login_request, buffer, sizeof(struct request_login));

      new_user = new User(login_request.req_username, address);
      users.insert({std::string(login_request.req_username), new_user});

      for (auto user : users) {
        unsigned short user_port = user.second->address->sin_port;
        in_addr_t user_address = user.second->address->sin_addr.s_addr;

        std::cout << user.first << " " << user_address << ":" << user_port << std::endl;
        std::cout << std::endl;
      }

      std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
      break;
    case REQ_LOGOUT:
      struct request_logout logout_request;
      memcpy(&logout_request, buffer, sizeof(struct request_logout));

      for (auto user : users) {
        unsigned short user_port = user.second->address->sin_port;
        in_addr_t user_address = user.second->address->sin_addr.s_addr;

        unsigned short request_port = address->sin_port;
        in_addr_t request_address = address->sin_addr.s_addr;

        std::cout << user_port << " == " << request_port << " && " << user_address << " == " << request_address << std::endl;

        if (user_port == request_port && user_address == request_address) {
          std::cout << "server: " << user.first << " logs out" << std::endl;
          users.erase(user.first);
          break;
        }
      }
      break;
    case REQ_JOIN:
      struct request_join join_request;
      memcpy(&join_request, buffer, sizeof(struct request_join));
//      std::cout << "server: " << username << " joins channel " << join_request.req_channel << std::endl;
      break;
    default:
      break;
  }
}

int main(int argc, char *argv[]) {
  struct sockaddr_in server_addr;

  int server_socket;
  int receive_len;
  void* buffer[kBufferSize];
  int port;

//  user = "";

  if (argc < 2) {
    std::cerr << "server: no port provided" << std::endl;
    exit(1);
  }

  port = atoi(argv[1]);

  memset((char *) &server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  server_addr.sin_port = htons(port);

  if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    Error("server: can't open socket\n");
  }

  if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
    Error("server: bind failed\n");
  }

  printf("server: waiting on port %d\n", port);
  while (1) {
    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
//    std::cout << "before recvfrom" << std::endl;
    receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
    if (receive_len > 0) {
      buffer[receive_len] = 0;
      ProcessRequest(buffer, &client_addr);
    }
  }
}
<commit_msg>pass new User into map insert<commit_after>#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <cstring>
#include <stdio.h>
#include <string>
#include <iostream>
#include <list>
#include <map>

#include "server.h"
#include "duckchat.h"

// TODO Server can accept connections.
// TODO Server handles Login and Logout from users, and keeps records of which users are logged in.
// TODO Server handles Join and Leave from users, keeps records of which channels a user belongs to,
// and keeps records of which users are in a channel.
// TODO Server handles the Say message.
// TODO Server correctly handles List and Who.
// TODO Create copies of your client and server source. Modify them to send invalid packets to your good client
// and server, to see if you can make your client or server crash. Fix any bugs you find.

//std::string user;

class Channel {
public:
  std::string name;
  std::list<User *> users;

  Channel(std::string name): name(name) {};
};

class User {
public:
  std::string name;
  struct sockaddr_in *address;
  std::list<Channel *> channels;

  User(std::string name, struct sockaddr_in *address): name(name), address(address) {};
};

std::map<std::string, User *> users;
std::map<std::string, Channel *> channels;

void Error(const char *msg) {
  perror(msg);
  exit(1);
}

void ProcessRequest(void *buffer, struct sockaddr_in *address) {
  struct request current_request;
//  User *new_user;
  std::map<std::string, User *>::iterator it;

  memcpy(&current_request, buffer, sizeof(struct request));
  std::cout << "request type: " << current_request.req_type << std::endl;
  request_t request_type = current_request.req_type;

  switch(request_type) {
    case REQ_LOGIN:
      struct request_login login_request;
      memcpy(&login_request, buffer, sizeof(struct request_login));

//      new_user = new User(login_request.req_username, address);
      users.insert({std::string(login_request.req_username), new User(login_request.req_username, address)});

      for (auto user : users) {
        unsigned short user_port = user.second->address->sin_port;
        in_addr_t user_address = user.second->address->sin_addr.s_addr;

        std::cout << user.first << " " << user_address << ":" << user_port << std::endl;
        std::cout << std::endl;
      }

      std::cout << "server: " << login_request.req_username << " logs in" << std::endl;
      break;
    case REQ_LOGOUT:
      struct request_logout logout_request;
      memcpy(&logout_request, buffer, sizeof(struct request_logout));

      for (auto user : users) {
        unsigned short user_port = user.second->address->sin_port;
        in_addr_t user_address = user.second->address->sin_addr.s_addr;

        unsigned short request_port = address->sin_port;
        in_addr_t request_address = address->sin_addr.s_addr;

        std::cout << user_port << " == " << request_port << " && " << user_address << " == " << request_address << std::endl;

        if (user_port == request_port && user_address == request_address) {
          std::cout << "server: " << user.first << " logs out" << std::endl;
          users.erase(user.first);
          break;
        }
      }
      break;
    case REQ_JOIN:
      struct request_join join_request;
      memcpy(&join_request, buffer, sizeof(struct request_join));
//      std::cout << "server: " << username << " joins channel " << join_request.req_channel << std::endl;
      break;
    default:
      break;
  }
}

int main(int argc, char *argv[]) {
  struct sockaddr_in server_addr;

  int server_socket;
  int receive_len;
  void* buffer[kBufferSize];
  int port;

//  user = "";

  if (argc < 2) {
    std::cerr << "server: no port provided" << std::endl;
    exit(1);
  }

  port = atoi(argv[1]);

  memset((char *) &server_addr, 0, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  server_addr.sin_port = htons(port);

  if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    Error("server: can't open socket\n");
  }

  if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
    Error("server: bind failed\n");
  }

  printf("server: waiting on port %d\n", port);
  while (1) {
    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
//    std::cout << "before recvfrom" << std::endl;
    receive_len = recvfrom(server_socket, buffer, kBufferSize, 0, (struct sockaddr *) &client_addr, &client_addr_len);
    if (receive_len > 0) {
      buffer[receive_len] = 0;
      ProcessRequest(buffer, &client_addr);
    }
  }
}
<|endoftext|>