<commit_before>  /*
 * Copyright (C) 2006-2015  Music Technology Group - Universitat Pompeu Fabra
 *
 * This file is part of Essentia
 *
 * Essentia 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 (FSF), 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 General Public License for more
 * details.
 *
 * You should have received a copy of the Affero GNU General Public License
 * version 3 along with this program.  If not, see http://www.gnu.org/licenses/
 */

#include <iostream>
#include <fstream>
#include <essentia/algorithmfactory.h>
#include <essentia/pool.h>
using namespace std;
using namespace essentia;
using namespace standard;

void scaleAudioVector(vector<Real> &buffer, const Real scale)
{
for (int i=0; i < int(buffer.size()); ++i){
    buffer[i] = scale * buffer[i];
}
}

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

  if (argc < 3) {
    cout << "ERROR: incorrect number of arguments." << endl;
    cout << "Usage: " << argv[0] << " audio_input output_file [attenuation_dB]" << endl;
    cout << "attenuation_dB (optional): value in dB's of the attenuation applied to the predominant pitched component. \n \
    A positive value 'mutes' the pitched component. A negative value 'soloes' the pitched component." << endl;
    exit(1);
  }

  string audioFilename = argv[1];
  string outputFilename = argv[2];
  Real attenuation_dB = -200.f;
  if (argc ==4){
   string attstr = argv[3];
   sscanf(attstr.c_str(), "%f",&attenuation_dB);
  }

  // register the algorithms in the factory(ies)
  essentia::init();

  Pool pool;

  /////// PARAMS //////////////

  /////// PARAMS //////////////
  int framesize = 2048;
  int hopsize = 128; // 128 for predominant melody
  Real sr = 44100;
  bool usePredominant = true; // set to true if PredmonantMelody extraction is used. Set to false if monhonic Pitch-YinFFT is used,

  AlgorithmFactory& factory = AlgorithmFactory::instance();

    Algorithm* audioLoader    = factory.create("MonoLoader",
                                           "filename", audioFilename,
                                           "sampleRate", sr,
                                           "downmix", "mix");

  Algorithm* frameCutter  = factory.create("FrameCutter",
                                           "frameSize", framesize,
                                           "hopSize", hopsize,
                                         //  "silentFrames", "noise",
                                           "startFromZero", false );

  Algorithm* window       = factory.create("Windowing", "type", "hann");

  Algorithm* equalLoudness = factory.create("EqualLoudness");

  Algorithm* fft     = factory.create("FFT",
                            "size", framesize);

  Algorithm* predominantMelody = factory.create("PredominantMelody",
                                                "frameSize", framesize,
                                                "hopSize", hopsize,
                                                "sampleRate", sr);
//
  Algorithm* spectrum = factory.create("Spectrum",
                                       "size", framesize);

  Algorithm* pitchDetect = factory.create("PitchYinFFT",
                                          "frameSize", framesize,
                                          "sampleRate", sr);

//  Algorithm* realAccumulator     = factory.create("RealAccumulator");

  Algorithm* harmonicMask     = factory.create("HarmonicMask",
                            "sampleRate", sr,
                            "binWidth", 2,
                            "attenuation", attenuation_dB);

  Algorithm* ifft     = factory.create("IFFT",
                                "size", framesize);

  Algorithm* overlapAdd = factory.create("OverlapAdd",
                                            "frameSize", framesize,
                                           "hopSize", hopsize);

  Algorithm* audioWriter = factory.create("MonoWriter",
                                     "filename", outputFilename);

  vector<Real> pitchIn;
  vector<Real> pitchConf;
  vector<Real> audio;
  vector<Real> eqaudio;
  vector<Real> frame;
  vector<Real> wframe;
  vector<complex<Real> > fftframe;
  vector<complex<Real> > fftmaskframe;
  vector<Real> ifftframe;
  vector<Real> alladuio; // concatenated audio file output
 // Real confidence;

  // analysis
  audioLoader->output("audio").set(audio);

  equalLoudness->input("signal").set(audio);
  equalLoudness->output("signal").set(eqaudio);

  predominantMelody->input("signal").set(eqaudio);
  predominantMelody->output("pitch").set(pitchIn);
  predominantMelody->output("pitchConfidence").set(pitchConf);

  frameCutter->input("signal").set(audio);
  frameCutter->output("frame").set(frame);

  window->input("frame").set(frame);
  window->output("frame").set(wframe);

  // set spectrum:
  vector<Real> spec;
  spectrum->input("frame").set(wframe);
  spectrum->output("spectrum").set(spec);

  // set Yin pitch extraction:
  Real thisPitch = 0., thisConf = 0;
  pitchDetect->input("spectrum").set(spec);
  pitchDetect->output("pitch").set(thisPitch);
  pitchDetect->output("pitchConfidence").set(thisConf);

  fft->input("frame").set(wframe);
  fft->output("fft").set(fftframe);

  // processing harmonic mask (apply mask)
  harmonicMask->input("fft").set(fftframe);
  harmonicMask->input("pitch").set(thisPitch);
  harmonicMask->output("fft").set(fftmaskframe);

  // Synthesis
  ifft->input("fft").set(fftmaskframe);
  ifft->output("frame").set(ifftframe);

  vector<Real> audioOutput;

  overlapAdd->input("signal").set(ifftframe); // or frame ?
  overlapAdd->output("signal").set(audioOutput);

////////
/////////// STARTING THE ALGORITHMS //////////////////
  cout << "-------- start processing " << audioFilename << " --------" << endl;

  audioLoader->compute();
  equalLoudness->compute();
  predominantMelody->compute();

  int counter = 0;

  while (true) {

    // compute a frame
    frameCutter->compute();

    // if it was the last one (ie: it was empty), then we're done.
    if (!frame.size()) {
      break;
    }

    window->compute();

    // pitch extraction
    spectrum->compute();
    pitchDetect->compute();

    // get predominant pitch
    if (usePredominant){
      thisPitch = pitchIn[counter];
    }

    fft->compute();
    harmonicMask-> compute();
    ifft->compute();
    overlapAdd->compute();

    counter++;

    alladuio.insert(alladuio.end(), audioOutput.begin(), audioOutput.end());

  }

  // write results to file
  cout << "-------- writing results to file " << outputFilename << " ---------" << endl;

    // write to output file
    audioWriter->input("audio").set(alladuio);
    audioWriter->compute();

  delete audioLoader;
  delete frameCutter;
  delete fft;
  delete predominantMelody;
  delete pitchDetect;
  //delete realAccumulator;
  delete harmonicMask;
  delete ifft;
  delete overlapAdd;
  delete audioWriter;

  essentia::shutdown();

  return 0;
}

<commit_msg>renaming predominantMelody in harmonicMask exampel<commit_after>  /*
 * Copyright (C) 2006-2015  Music Technology Group - Universitat Pompeu Fabra
 *
 * This file is part of Essentia
 *
 * Essentia 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 (FSF), 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 General Public License for more
 * details.
 *
 * You should have received a copy of the Affero GNU General Public License
 * version 3 along with this program.  If not, see http://www.gnu.org/licenses/
 */

#include <iostream>
#include <fstream>
#include <essentia/algorithmfactory.h>
#include <essentia/pool.h>
using namespace std;
using namespace essentia;
using namespace standard;

void scaleAudioVector(vector<Real> &buffer, const Real scale)
{
for (int i=0; i < int(buffer.size()); ++i){
    buffer[i] = scale * buffer[i];
}
}

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

  if (argc < 3) {
    cout << "ERROR: incorrect number of arguments." << endl;
    cout << "Usage: " << argv[0] << " audio_input output_file [attenuation_dB]" << endl;
    cout << "attenuation_dB (optional): value in dB's of the attenuation applied to the predominant pitched component. \n \
    A positive value 'mutes' the pitched component. A negative value 'soloes' the pitched component." << endl;
    exit(1);
  }

  string audioFilename = argv[1];
  string outputFilename = argv[2];
  Real attenuation_dB = -200.f;
  if (argc ==4){
   string attstr = argv[3];
   sscanf(attstr.c_str(), "%f",&attenuation_dB);
  }

  // register the algorithms in the factory(ies)
  essentia::init();

  Pool pool;

  /////// PARAMS //////////////

  /////// PARAMS //////////////
  int framesize = 2048;
  int hopsize = 128; // 128 for predominant melody
  Real sr = 44100;
  bool usePredominant = true; // set to true if PredmonantMelody extraction is used. Set to false if monhonic Pitch-YinFFT is used,

  AlgorithmFactory& factory = AlgorithmFactory::instance();

    Algorithm* audioLoader    = factory.create("MonoLoader",
                                           "filename", audioFilename,
                                           "sampleRate", sr,
                                           "downmix", "mix");

  Algorithm* frameCutter  = factory.create("FrameCutter",
                                           "frameSize", framesize,
                                           "hopSize", hopsize,
                                         //  "silentFrames", "noise",
                                           "startFromZero", false );

  Algorithm* window       = factory.create("Windowing", "type", "hann");

  Algorithm* equalLoudness = factory.create("EqualLoudness");

  Algorithm* fft     = factory.create("FFT",
                            "size", framesize);

  Algorithm* predominantMelody = factory.create("PredominantPitchMelodia", //PredominantMelody",
                                                "frameSize", framesize,
                                                "hopSize", hopsize,
                                                "sampleRate", sr);
//
  Algorithm* spectrum = factory.create("Spectrum",
                                       "size", framesize);

  Algorithm* pitchDetect = factory.create("PitchYinFFT",
                                          "frameSize", framesize,
                                          "sampleRate", sr);

//  Algorithm* realAccumulator     = factory.create("RealAccumulator");

  Algorithm* harmonicMask     = factory.create("HarmonicMask",
                            "sampleRate", sr,
                            "binWidth", 2,
                            "attenuation", attenuation_dB);

  Algorithm* ifft     = factory.create("IFFT",
                                "size", framesize);

  Algorithm* overlapAdd = factory.create("OverlapAdd",
                                            "frameSize", framesize,
                                           "hopSize", hopsize);

  Algorithm* audioWriter = factory.create("MonoWriter",
                                     "filename", outputFilename);

  vector<Real> pitchIn;
  vector<Real> pitchConf;
  vector<Real> audio;
  vector<Real> eqaudio;
  vector<Real> frame;
  vector<Real> wframe;
  vector<complex<Real> > fftframe;
  vector<complex<Real> > fftmaskframe;
  vector<Real> ifftframe;
  vector<Real> alladuio; // concatenated audio file output
 // Real confidence;

  // analysis
  audioLoader->output("audio").set(audio);

  equalLoudness->input("signal").set(audio);
  equalLoudness->output("signal").set(eqaudio);

  predominantMelody->input("signal").set(eqaudio);
  predominantMelody->output("pitch").set(pitchIn);
  predominantMelody->output("pitchConfidence").set(pitchConf);

  frameCutter->input("signal").set(audio);
  frameCutter->output("frame").set(frame);

  window->input("frame").set(frame);
  window->output("frame").set(wframe);

  // set spectrum:
  vector<Real> spec;
  spectrum->input("frame").set(wframe);
  spectrum->output("spectrum").set(spec);

  // set Yin pitch extraction:
  Real thisPitch = 0., thisConf = 0;
  pitchDetect->input("spectrum").set(spec);
  pitchDetect->output("pitch").set(thisPitch);
  pitchDetect->output("pitchConfidence").set(thisConf);

  fft->input("frame").set(wframe);
  fft->output("fft").set(fftframe);

  // processing harmonic mask (apply mask)
  harmonicMask->input("fft").set(fftframe);
  harmonicMask->input("pitch").set(thisPitch);
  harmonicMask->output("fft").set(fftmaskframe);

  // Synthesis
  ifft->input("fft").set(fftmaskframe);
  ifft->output("frame").set(ifftframe);

  vector<Real> audioOutput;

  overlapAdd->input("signal").set(ifftframe); // or frame ?
  overlapAdd->output("signal").set(audioOutput);

////////
/////////// STARTING THE ALGORITHMS //////////////////
  cout << "-------- start processing " << audioFilename << " --------" << endl;

  audioLoader->compute();
  equalLoudness->compute();
  predominantMelody->compute();

  int counter = 0;

  while (true) {

    // compute a frame
    frameCutter->compute();

    // if it was the last one (ie: it was empty), then we're done.
    if (!frame.size()) {
      break;
    }

    window->compute();

    // pitch extraction
    spectrum->compute();
    pitchDetect->compute();

    // get predominant pitch
    if (usePredominant){
      thisPitch = pitchIn[counter];
    }

    fft->compute();
    harmonicMask-> compute();
    ifft->compute();
    overlapAdd->compute();

    counter++;

    alladuio.insert(alladuio.end(), audioOutput.begin(), audioOutput.end());

  }

  // write results to file
  cout << "-------- writing results to file " << outputFilename << " ---------" << endl;

    // write to output file
    audioWriter->input("audio").set(alladuio);
    audioWriter->compute();

  delete audioLoader;
  delete frameCutter;
  delete fft;
  delete predominantMelody;
  delete pitchDetect;
  //delete realAccumulator;
  delete harmonicMask;
  delete ifft;
  delete overlapAdd;
  delete audioWriter;

  essentia::shutdown();

  return 0;
}

<|endoftext|>


<commit_before>/*
* Copyright (c)2015 Oasis LMF Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   * Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in
*     the documentation and/or other materials provided with the
*     distribution.
*
*   * Neither the original author of this software nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
/*
Convert fmprofile output to csv
Author: Ben Matharu  email: ben.matharu@oasislmf.org
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

#ifdef __unix
    #include <unistd.h>
#endif

#include "../include/oasis.hpp"

using namespace std;

struct fm_programme {
    int prog_id;
    int level_id;
    int agg_id;
    int item_id;
};
void doit()
{

    printf ("\"prog_id\", \"input_id\", \"level_id\",\"agg_id\"\n");

    fm_programme q;
    int i = fread(&q, sizeof(q), 1, stdin);
    while (i != 0) {
        printf("%d, %d, %d, %d\n", q.prog_id, q.item_id, q.level_id, q.agg_id );
        i = fread(&q, sizeof(q), 1, stdin);
    }
}

void help()
{

    cerr << "-I inputfilename\n"
        << "-O outputfielname\n"
        ;
}

int main(int argc, char* argv[])
{
    int opt;
     std::string inFile;
     std::string outFile;

 #ifdef __unix
     while ((opt = getopt(argc, argv, "hI:O:")) != -1) {
         switch (opt) {
         case 'I':
             inFile = optarg;
             break;
          case 'O':
             outFile = optarg;
             break;
         case 'h':
            help();
            exit(EXIT_FAILURE);
         }
     }
 #endif

    initstreams(inFile, outFile);

	doit();
	return 0;
}
<commit_msg>changed header<commit_after>/*
* Copyright (c)2015 Oasis LMF Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   * Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in
*     the documentation and/or other materials provided with the
*     distribution.
*
*   * Neither the original author of this software nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
/*
Convert fmprofile output to csv
Author: Ben Matharu  email: ben.matharu@oasislmf.org
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

#ifdef __unix
    #include <unistd.h>
#endif

#include "../include/oasis.hpp"

using namespace std;

struct fm_programme {
    int prog_id;
    int level_id;
    int to_agg_id;
    int from_agg_id;
};
void doit()
{

    printf ("\"prog_id\", \"from_agg_id\", \"level_id\",\"to_agg_id\"\n");

    fm_programme q;
    int i = fread(&q, sizeof(q), 1, stdin);
    while (i != 0) {
        printf("%d, %d, %d, %d\n", q.prog_id, q.from_agg_id, q.level_id, q.to_agg_id );
        i = fread(&q, sizeof(q), 1, stdin);
    }
}

void help()
{

    cerr << "-I inputfilename\n"
        << "-O outputfielname\n"
        ;
}

int main(int argc, char* argv[])
{
    int opt;
     std::string inFile;
     std::string outFile;

 #ifdef __unix
     while ((opt = getopt(argc, argv, "hI:O:")) != -1) {
         switch (opt) {
         case 'I':
             inFile = optarg;
             break;
          case 'O':
             outFile = optarg;
             break;
         case 'h':
            help();
            exit(EXIT_FAILURE);
         }
     }
 #endif

    initstreams(inFile, outFile);

	doit();
	return 0;
}
<|endoftext|>


<commit_before>/*
Copyright libCellML Contributors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include "libcellml/model.h"

#include <algorithm>
#include <fstream>
#include <map>
#include <sstream>
#include <stack>
#include <utility>
#include <vector>

#include "libcellml/component.h"
#include "libcellml/importsource.h"
#include "libcellml/parser.h"
#include "libcellml/variable.h"
#include "libcellml/units.h"

namespace libcellml {

/**
 * @brief The Model::ModelImpl struct.
 *
 * This struct is the private implementation struct for the Model class.  Separating
 * the implementation from the definition allows for greater flexibility when
 * distributing the code.
 */
struct Model::ModelImpl
{
    std::vector<UnitsPtr>::iterator findUnits(const std::string &name);
    std::vector<UnitsPtr>::iterator findUnits(const UnitsPtr &units);
    std::vector<UnitsPtr> mUnits;
};

std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const std::string &name)
{
    return std::find_if(mUnits.begin(), mUnits.end(),
                        [=](const UnitsPtr& u) -> bool { return u->getName() == name; });
}

std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const UnitsPtr &units)
{
    return std::find_if(mUnits.begin(), mUnits.end(),
                        [=](const UnitsPtr& u) -> bool { return u == units; });
}

Model::Model()
    : mPimpl(new ModelImpl())
{
}

Model::~Model()
{
    delete mPimpl;
}

Model::Model(const Model& rhs)
    : ComponentEntity(rhs)
    , mPimpl(new ModelImpl())
{
    mPimpl->mUnits = rhs.mPimpl->mUnits;
}

Model::Model(Model &&rhs)
    : ComponentEntity(std::move(rhs))
    ,mPimpl(rhs.mPimpl)
{
    rhs.mPimpl = nullptr;
}

Model& Model::operator=(Model m)
{
    ComponentEntity::operator= (m);
    m.swap(*this);
    return *this;
}

void Model::swap(Model &rhs)
{
    std::swap(this->mPimpl, rhs.mPimpl);
}

void Model::doAddComponent(const ComponentPtr &c)
{
    // Check for cycles.
    if (!hasParent(c.get())) {
        c->setParent(this);
        ComponentEntity::doAddComponent(c);
    }
}

void Model::addUnits(const UnitsPtr & units)
{
    mPimpl->mUnits.push_back(units);
}

bool Model::removeUnits(size_t index)
{
    bool status = false;
    if (index < mPimpl->mUnits.size()) {
        mPimpl->mUnits.erase(mPimpl->mUnits.begin() + index);
        status = true;
    }

    return status;
}

bool Model::removeUnits(const std::string &name)
{
    bool status = false;
    auto result = mPimpl->findUnits(name);
    if (result != mPimpl->mUnits.end()) {
        mPimpl->mUnits.erase(result);
        status = true;
    }

    return status;
}

bool Model::removeUnits(const UnitsPtr &units)
{
    bool status = false;
    auto result = mPimpl->findUnits(units);
    if (result != mPimpl->mUnits.end()) {
        mPimpl->mUnits.erase(result);
        status = true;
    }

    return status;
}

void Model::removeAllUnits()
{
    mPimpl->mUnits.clear();
}

bool Model::hasUnits(const std::string &name) const
{
    return mPimpl->findUnits(name) != mPimpl->mUnits.end();
}

UnitsPtr Model::getUnits(size_t index) const
{
    UnitsPtr units = nullptr;
    if (index < mPimpl->mUnits.size()) {
        units = mPimpl->mUnits.at(index);
    }

    return units;
}

UnitsPtr Model::getUnits(const std::string &name) const
{
    UnitsPtr units = nullptr;
    auto result = mPimpl->findUnits(name);
    if (result != mPimpl->mUnits.end()) {
        units = *result;
    }

    return units;
}

UnitsPtr Model::takeUnits(size_t index)
{
    UnitsPtr units = nullptr;
    if (index < mPimpl->mUnits.size()) {
        units = mPimpl->mUnits.at(index);
        removeUnits(index);
        units->clearParent();
    }

    return units;
}

UnitsPtr Model::takeUnits(const std::string &name)
{
    return takeUnits(mPimpl->findUnits(name) - mPimpl->mUnits.begin());
}

bool Model::replaceUnits(size_t index, const UnitsPtr &units)
{
    bool status = false;
    if (removeUnits(index)) {
        mPimpl->mUnits.insert(mPimpl->mUnits.begin() + index, units);
        status = true;
    }

    return status;
}

bool Model::replaceUnits(const std::string &name, const UnitsPtr &units)
{
    return replaceUnits(mPimpl->findUnits(name) - mPimpl->mUnits.begin(), units);
}

bool Model::replaceUnits(const UnitsPtr &oldUnits, const UnitsPtr &newUnits)
{
    return replaceUnits(mPimpl->findUnits(oldUnits) - mPimpl->mUnits.begin(), newUnits);
}

size_t Model::unitsCount() const
{
    return mPimpl->mUnits.size();
}

typedef std::shared_ptr<ImportedEntity> ImportedEntityPtr;

/**
 * @brief Resolve the path of the given filename using the given base.
 *
 * Resolves the full path to the given @p filename using the @p base.
 *
 * This function is only intended to work with local files.  It may not
 * work with bases that use the 'file://' prefix.
 *
 * @param filename The @c std::string relative path from the base path.
 * @param base The @c std::string location on local disk for determining the full path from.
 * @return The full path from the @p base location to the @p filename
 */
std::string resolvePath(const std::string& filename, const std::string& base)
{
    // we can be naive here as we know what we are dealing with
    std::string path = base.substr(0, base.find_last_of('/')+1) + filename;
    return path;
}

void resolveImport(ImportedEntityPtr importedEntity,
                   const std::string& baseFile)
{
    if (importedEntity->isImport()) {
        libcellml::ImportSourcePtr importSource = importedEntity->getImportSource();
        if (!importSource->hasModel()) {
            std::string url = resolvePath(importSource->getUrl(), baseFile);
            std::ifstream t(url);
            std::stringstream buffer;
            buffer << t.rdbuf();
            libcellml::Parser p;
            libcellml::ModelPtr model = p.parseModel(buffer.str());
            if (model) {
                importSource->setModel(model);
                model->resolveImports(url);
            }
        }
    }
}

void recurseResolveComponentImports(ComponentPtr component, const std::string &baseFile);

void resolveComponentImports(ComponentPtr parentComponent, const std::string &baseFile)
{
    for (size_t n = 0; n < parentComponent->componentCount();  ++n)
    {
        libcellml::ComponentPtr component = parentComponent->getComponent(n);
        recurseResolveComponentImports(component, baseFile);
    }
}

void recurseResolveComponentImports(ComponentPtr component, const std::string &baseFile)
{
    if (component->isImport()) {
        resolveImport(component, baseFile);
    } else {
        resolveComponentImports(component, baseFile);
    }
}

void Model::resolveImports(const std::string &baseFile)
{
    for (size_t n = 0; n < unitsCount();  ++n)
    {
        libcellml::UnitsPtr units = getUnits(n);
        resolveImport(units, baseFile);
    }
    for (size_t n = 0; n < componentCount();  ++n)
    {
        libcellml::ComponentPtr component = getComponent(n);
        recurseResolveComponentImports(component, baseFile);
    }
}

bool isUnresolvedImport(ImportedEntityPtr importedEntity)
{
    bool unresolvedImport = false;
    if (importedEntity->isImport()) {
        libcellml::ImportSourcePtr importedSource = importedEntity->getImportSource();
        if (!importedSource->hasModel()) {
            unresolvedImport = true;
        }
    }
    return unresolvedImport;
}

bool hasUnresolvedComponentImports(libcellml::ComponentPtr component);

bool recurseForUnresolvedComponentImports(ComponentPtr parentComponent)
{
    bool unresolvedImports = false;
    for (size_t n = 0; n < parentComponent->componentCount() && !unresolvedImports;  ++n)
    {
        libcellml::ComponentPtr component = parentComponent->getComponent(n);
        unresolvedImports = hasUnresolvedComponentImports(component);
    }

    return unresolvedImports;
}

bool hasUnresolvedComponentImports(libcellml::ComponentPtr component)
{
    bool unresolvedImports = false;
    if (component->isImport()) {
        unresolvedImports = isUnresolvedImport(component);
    } else {
        unresolvedImports = recurseForUnresolvedComponentImports(component);
    }

    return unresolvedImports;
}

bool Model::hasUnresolvedImports() const
{
    bool unresolvedImports = false;
    for (size_t n = 0; n < unitsCount() && !unresolvedImports;  ++n)
    {
        libcellml::UnitsPtr units = getUnits(n);
        unresolvedImports = isUnresolvedImport(units);
    }
    for (size_t n = 0; n < componentCount() && !unresolvedImports;  ++n)
    {
        libcellml::ComponentPtr component = getComponent(n);
        unresolvedImports = hasUnresolvedComponentImports(component);
    }
    return unresolvedImports;
}

}
<commit_msg>Only parse for a model if the file stream is good.<commit_after>/*
Copyright libCellML Contributors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include "libcellml/model.h"

#include <algorithm>
#include <fstream>
#include <map>
#include <sstream>
#include <stack>
#include <utility>
#include <vector>

#include "libcellml/component.h"
#include "libcellml/importsource.h"
#include "libcellml/parser.h"
#include "libcellml/variable.h"
#include "libcellml/units.h"

namespace libcellml {

/**
 * @brief The Model::ModelImpl struct.
 *
 * This struct is the private implementation struct for the Model class.  Separating
 * the implementation from the definition allows for greater flexibility when
 * distributing the code.
 */
struct Model::ModelImpl
{
    std::vector<UnitsPtr>::iterator findUnits(const std::string &name);
    std::vector<UnitsPtr>::iterator findUnits(const UnitsPtr &units);
    std::vector<UnitsPtr> mUnits;
};

std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const std::string &name)
{
    return std::find_if(mUnits.begin(), mUnits.end(),
                        [=](const UnitsPtr& u) -> bool { return u->getName() == name; });
}

std::vector<UnitsPtr>::iterator Model::ModelImpl::findUnits(const UnitsPtr &units)
{
    return std::find_if(mUnits.begin(), mUnits.end(),
                        [=](const UnitsPtr& u) -> bool { return u == units; });
}

Model::Model()
    : mPimpl(new ModelImpl())
{
}

Model::~Model()
{
    delete mPimpl;
}

Model::Model(const Model& rhs)
    : ComponentEntity(rhs)
    , mPimpl(new ModelImpl())
{
    mPimpl->mUnits = rhs.mPimpl->mUnits;
}

Model::Model(Model &&rhs)
    : ComponentEntity(std::move(rhs))
    ,mPimpl(rhs.mPimpl)
{
    rhs.mPimpl = nullptr;
}

Model& Model::operator=(Model m)
{
    ComponentEntity::operator= (m);
    m.swap(*this);
    return *this;
}

void Model::swap(Model &rhs)
{
    std::swap(this->mPimpl, rhs.mPimpl);
}

void Model::doAddComponent(const ComponentPtr &c)
{
    // Check for cycles.
    if (!hasParent(c.get())) {
        c->setParent(this);
        ComponentEntity::doAddComponent(c);
    }
}

void Model::addUnits(const UnitsPtr & units)
{
    mPimpl->mUnits.push_back(units);
}

bool Model::removeUnits(size_t index)
{
    bool status = false;
    if (index < mPimpl->mUnits.size()) {
        mPimpl->mUnits.erase(mPimpl->mUnits.begin() + index);
        status = true;
    }

    return status;
}

bool Model::removeUnits(const std::string &name)
{
    bool status = false;
    auto result = mPimpl->findUnits(name);
    if (result != mPimpl->mUnits.end()) {
        mPimpl->mUnits.erase(result);
        status = true;
    }

    return status;
}

bool Model::removeUnits(const UnitsPtr &units)
{
    bool status = false;
    auto result = mPimpl->findUnits(units);
    if (result != mPimpl->mUnits.end()) {
        mPimpl->mUnits.erase(result);
        status = true;
    }

    return status;
}

void Model::removeAllUnits()
{
    mPimpl->mUnits.clear();
}

bool Model::hasUnits(const std::string &name) const
{
    return mPimpl->findUnits(name) != mPimpl->mUnits.end();
}

UnitsPtr Model::getUnits(size_t index) const
{
    UnitsPtr units = nullptr;
    if (index < mPimpl->mUnits.size()) {
        units = mPimpl->mUnits.at(index);
    }

    return units;
}

UnitsPtr Model::getUnits(const std::string &name) const
{
    UnitsPtr units = nullptr;
    auto result = mPimpl->findUnits(name);
    if (result != mPimpl->mUnits.end()) {
        units = *result;
    }

    return units;
}

UnitsPtr Model::takeUnits(size_t index)
{
    UnitsPtr units = nullptr;
    if (index < mPimpl->mUnits.size()) {
        units = mPimpl->mUnits.at(index);
        removeUnits(index);
        units->clearParent();
    }

    return units;
}

UnitsPtr Model::takeUnits(const std::string &name)
{
    return takeUnits(mPimpl->findUnits(name) - mPimpl->mUnits.begin());
}

bool Model::replaceUnits(size_t index, const UnitsPtr &units)
{
    bool status = false;
    if (removeUnits(index)) {
        mPimpl->mUnits.insert(mPimpl->mUnits.begin() + index, units);
        status = true;
    }

    return status;
}

bool Model::replaceUnits(const std::string &name, const UnitsPtr &units)
{
    return replaceUnits(mPimpl->findUnits(name) - mPimpl->mUnits.begin(), units);
}

bool Model::replaceUnits(const UnitsPtr &oldUnits, const UnitsPtr &newUnits)
{
    return replaceUnits(mPimpl->findUnits(oldUnits) - mPimpl->mUnits.begin(), newUnits);
}

size_t Model::unitsCount() const
{
    return mPimpl->mUnits.size();
}

typedef std::shared_ptr<ImportedEntity> ImportedEntityPtr;

/**
 * @brief Resolve the path of the given filename using the given base.
 *
 * Resolves the full path to the given @p filename using the @p base.
 *
 * This function is only intended to work with local files.  It may not
 * work with bases that use the 'file://' prefix.
 *
 * @param filename The @c std::string relative path from the base path.
 * @param base The @c std::string location on local disk for determining the full path from.
 * @return The full path from the @p base location to the @p filename
 */
std::string resolvePath(const std::string& filename, const std::string& base)
{
    // we can be naive here as we know what we are dealing with
    std::string path = base.substr(0, base.find_last_of('/')+1) + filename;
    return path;
}

void resolveImport(ImportedEntityPtr importedEntity,
                   const std::string& baseFile)
{
    if (importedEntity->isImport()) {
        libcellml::ImportSourcePtr importSource = importedEntity->getImportSource();
        if (!importSource->hasModel()) {
            std::string url = resolvePath(importSource->getUrl(), baseFile);
            std::ifstream t(url);
            if (t.good()) {
                std::stringstream buffer;
                buffer << t.rdbuf();
                libcellml::Parser p;
                libcellml::ModelPtr model = p.parseModel(buffer.str());
                if (model) {
                    importSource->setModel(model);
                    model->resolveImports(url);
                }
            }
        }
    }
}

void recurseResolveComponentImports(ComponentPtr component, const std::string &baseFile);

void resolveComponentImports(ComponentPtr parentComponent, const std::string &baseFile)
{
    for (size_t n = 0; n < parentComponent->componentCount();  ++n)
    {
        libcellml::ComponentPtr component = parentComponent->getComponent(n);
        recurseResolveComponentImports(component, baseFile);
    }
}

void recurseResolveComponentImports(ComponentPtr component, const std::string &baseFile)
{
    if (component->isImport()) {
        resolveImport(component, baseFile);
    } else {
        resolveComponentImports(component, baseFile);
    }
}

void Model::resolveImports(const std::string &baseFile)
{
    for (size_t n = 0; n < unitsCount();  ++n)
    {
        libcellml::UnitsPtr units = getUnits(n);
        resolveImport(units, baseFile);
    }
    for (size_t n = 0; n < componentCount();  ++n)
    {
        libcellml::ComponentPtr component = getComponent(n);
        recurseResolveComponentImports(component, baseFile);
    }
}

bool isUnresolvedImport(ImportedEntityPtr importedEntity)
{
    bool unresolvedImport = false;
    if (importedEntity->isImport()) {
        libcellml::ImportSourcePtr importedSource = importedEntity->getImportSource();
        if (!importedSource->hasModel()) {
            unresolvedImport = true;
        }
    }
    return unresolvedImport;
}

bool hasUnresolvedComponentImports(libcellml::ComponentPtr component);

bool recurseForUnresolvedComponentImports(ComponentPtr parentComponent)
{
    bool unresolvedImports = false;
    for (size_t n = 0; n < parentComponent->componentCount() && !unresolvedImports;  ++n)
    {
        libcellml::ComponentPtr component = parentComponent->getComponent(n);
        unresolvedImports = hasUnresolvedComponentImports(component);
    }

    return unresolvedImports;
}

bool hasUnresolvedComponentImports(libcellml::ComponentPtr component)
{
    bool unresolvedImports = false;
    if (component->isImport()) {
        unresolvedImports = isUnresolvedImport(component);
    } else {
        unresolvedImports = recurseForUnresolvedComponentImports(component);
    }

    return unresolvedImports;
}

bool Model::hasUnresolvedImports() const
{
    bool unresolvedImports = false;
    for (size_t n = 0; n < unitsCount() && !unresolvedImports;  ++n)
    {
        libcellml::UnitsPtr units = getUnits(n);
        unresolvedImports = isUnresolvedImport(units);
    }
    for (size_t n = 0; n < componentCount() && !unresolvedImports;  ++n)
    {
        libcellml::ComponentPtr component = getComponent(n);
        unresolvedImports = hasUnresolvedComponentImports(component);
    }
    return unresolvedImports;
}

}
<|endoftext|>


<commit_before>#ifndef ZXTK_UTILITIES_MODULES_REGISTER_SET_INCLUDE_GUARD
#define ZXTK_UTILITIES_MODULES_REGISTER_SET_INCLUDE_GUARD

#include <zxtk/utilities/exchange.hpp>
#include <zxtk/misc/zxtk_types.hpp>
#include <zxtk/misc/zxtk_config.hpp>
#include <utility>
#include <cstddef>

namespace zxtk {
    namespace register_set {
        namespace impl
        {
#ifdef ZXTK_ENDIANNESS_COMPILE_TIME_CHECK
            constexpr
#endif
            types::byte little_endian()
            {
                return ((std::uint16_t{1}>>8)>0)?0:1;
            }
#ifdef ZXTK_ENDIANNESS_COMPILE_TIME_CHECK
            constexpr
#endif
            types::byte big_endian()
            {
                return ((std::uint16_t{1}>>8)>0)?1:0;
            }
        }
        class Z80_register_set
        {
        public:
            Z80_register_set():st_af{0xffff},st_pc{0x0000} {}

        // Most Z80 registers are not initialised, but they are initialised
        // anyway (af and sp are set to ffff on startup and pc, iffs and iv
        // are 0). We could add in realistic values where compilation flags
        // (to simulate different z80's), time since last use and other things
        // but really, I don't know of any use of this. Submit an issue if you
        // want this feature

            // WARNING: THIS IS NOT THREAD SAFE. WRITING TO THIS FROM SOMETHING OTHER THAN THE CPU OR I/O IS NOT RECOMMENDED
            types::byte& a() {return *(reinterpret_cast<types::byte*>(&st_af)+impl::little_endian());}
            types::byte& f() {return *(reinterpret_cast<types::byte*>(&st_af)+impl::big_endian());}
            types::byte& b() {return *(reinterpret_cast<types::byte*>(&st_bc)+impl::little_endian());}
            types::byte& c() {return *(reinterpret_cast<types::byte*>(&st_bc)+impl::big_endian());}
            types::byte& d() {return *(reinterpret_cast<types::byte*>(&st_de)+impl::little_endian());}
            types::byte& e() {return *(reinterpret_cast<types::byte*>(&st_de)+impl::big_endian());}
            types::byte& h() {return *(reinterpret_cast<types::byte*>(&st_hl)+impl::little_endian());}
            types::byte& l() {return *(reinterpret_cast<types::byte*>(&st_hl)+impl::big_endian());}
            types::byte& ixh() {return *(reinterpret_cast<types::byte*>(&st_ix)+impl::little_endian());}
            types::byte& ixl() {return *(reinterpret_cast<types::byte*>(&st_ix)+impl::big_endian());}
            types::byte& iyh() {return *(reinterpret_cast<types::byte*>(&st_iy)+impl::little_endian());}
            types::byte& iyl() {return *(reinterpret_cast<types::byte*>(&st_iy)+impl::big_endian());}
            types::word& af() {return st_af;}
            types::word& bc() {return st_bc;}
            types::word& de() {return st_de;}
            types::word& hl() {return st_hl;}
            types::word& ix() {return st_ix;}
            types::word& iy() {return st_iy;}
            types::word& sp() {return st_sp;}
            types::word& pc() {return st_pc;}
            types::byte& i() {return st_i;}
            types::byte& r() {return st_r;}
            bool& iff1() {return st_iff1;}
            bool& iff2() {return st_iff2;}
            void exx() {std::swap(st_bc,st_bc_a);std::swap(st_de,st_de_a);std::swap(st_hl,st_hl_a);}
            void ex_af_af() {std::swap(st_af, st_af_a);}
            // const versions
            types::byte a() const {return *(reinterpret_cast<const types::byte*>(&st_af)+impl::little_endian());}
            types::byte f() const {return *(reinterpret_cast<const types::byte*>(&st_af)+impl::big_endian());}
            types::byte b() const {return *(reinterpret_cast<const types::byte*>(&st_bc)+impl::little_endian());}
            types::byte c() const {return *(reinterpret_cast<const types::byte*>(&st_bc)+impl::big_endian());}
            types::byte d() const {return *(reinterpret_cast<const types::byte*>(&st_de)+impl::little_endian());}
            types::byte e() const {return *(reinterpret_cast<const types::byte*>(&st_de)+impl::big_endian());}
            types::byte h() const {return *(reinterpret_cast<const types::byte*>(&st_hl)+impl::little_endian());}
            types::byte l() const {return *(reinterpret_cast<const types::byte*>(&st_hl)+impl::big_endian());}
            types::byte ixh() const {return *(reinterpret_cast<const types::byte*>(&st_ix)+impl::little_endian());}
            types::byte ixl() const {return *(reinterpret_cast<const types::byte*>(&st_ix)+impl::big_endian());}
            types::byte iyh() const {return *(reinterpret_cast<const types::byte*>(&st_iy)+impl::little_endian());}
            types::byte iyl() const {return *(reinterpret_cast<const types::byte*>(&st_iy)+impl::big_endian());}
            types::word af() const {return st_af;}
            types::word bc() const {return st_bc;}
            types::word de() const {return st_de;}
            types::word hl() const {return st_hl;}
            types::word ix() const {return st_ix;}
            types::word iy() const {return st_iy;}
            types::word sp() const {return st_sp;}
            types::word pc() const {return st_pc;}
            types::byte i() const {return st_i;}
            types::byte r() const {return st_r;}
            bool iff1() const {return st_iff1;}
            bool iff2() const {return st_iff2;}
        protected:
            types::word st_af;
            types::word st_bc;
            types::word st_de;
            types::word st_hl;
            types::word st_af_a;
            types::word st_bc_a;
            types::word st_de_a;
            types::word st_hl_a;
            types::word st_pc;
            types::word st_sp;
            types::word st_ix;
            types::word st_iy;
            types::byte st_r;
            types::byte st_i;
            bool st_iff1;
            bool st_iff2;
        };
    }
}

#endif
<commit_msg>Added register set initialisation and corrected interrupts<commit_after>#ifndef ZXTK_UTILITIES_MODULES_REGISTER_SET_INCLUDE_GUARD
#define ZXTK_UTILITIES_MODULES_REGISTER_SET_INCLUDE_GUARD

#include <zxtk/utilities/exchange.hpp>
#include <zxtk/misc/zxtk_types.hpp>
#include <zxtk/misc/zxtk_config.hpp>
#include <utility>
#include <cstddef>

namespace zxtk {
    namespace register_set {
        namespace impl
        {
#ifdef ZXTK_ENDIANNESS_COMPILE_TIME_CHECK
            constexpr
#endif
            types::byte little_endian()
            {
                return ((std::uint16_t{1}>>8)>0)?0:1;
            }
#ifdef ZXTK_ENDIANNESS_COMPILE_TIME_CHECK
            constexpr
#endif
            types::byte big_endian()
            {
                return ((std::uint16_t{1}>>8)>0)?1:0;
            }
        }
        class Z80_register_set
        {
        public:
            Z80_register_set():st_af{0xffff},st_pc{0x0000} {}

        // Most Z80 registers are not initialised, but they are initialised
        // anyway (af and sp are set to ffff on startup and pc, iffs and iv
        // are 0). We could add in realistic values where compilation flags
        // (to simulate different z80's), time since last use and other things
        // but really, I don't know of any use of this. Submit an issue if you
        // want this feature

            // WARNING: THIS IS NOT THREAD SAFE. WRITING TO THIS FROM SOMETHING OTHER THAN THE CPU OR I/O IS NOT RECOMMENDED
            types::byte& a() {return *(reinterpret_cast<types::byte*>(&st_af)+impl::little_endian());}
            types::byte& f() {return *(reinterpret_cast<types::byte*>(&st_af)+impl::big_endian());}
            types::byte& b() {return *(reinterpret_cast<types::byte*>(&st_bc)+impl::little_endian());}
            types::byte& c() {return *(reinterpret_cast<types::byte*>(&st_bc)+impl::big_endian());}
            types::byte& d() {return *(reinterpret_cast<types::byte*>(&st_de)+impl::little_endian());}
            types::byte& e() {return *(reinterpret_cast<types::byte*>(&st_de)+impl::big_endian());}
            types::byte& h() {return *(reinterpret_cast<types::byte*>(&st_hl)+impl::little_endian());}
            types::byte& l() {return *(reinterpret_cast<types::byte*>(&st_hl)+impl::big_endian());}
            types::byte& ixh() {return *(reinterpret_cast<types::byte*>(&st_ix)+impl::little_endian());}
            types::byte& ixl() {return *(reinterpret_cast<types::byte*>(&st_ix)+impl::big_endian());}
            types::byte& iyh() {return *(reinterpret_cast<types::byte*>(&st_iy)+impl::little_endian());}
            types::byte& iyl() {return *(reinterpret_cast<types::byte*>(&st_iy)+impl::big_endian());}
            types::word& af() {return st_af;}
            types::word& bc() {return st_bc;}
            types::word& de() {return st_de;}
            types::word& hl() {return st_hl;}
            types::word& ix() {return st_ix;}
            types::word& iy() {return st_iy;}
            types::word& sp() {return st_sp;}
            types::word& pc() {return st_pc;}
            types::byte& i() {return st_i;}
            types::byte& r() {return st_r;}
            bool& iff1() {return st_iff1;}
            bool& iff2() {return st_iff2;}
            void exx() {std::swap(st_bc,st_bc_a);std::swap(st_de,st_de_a);std::swap(st_hl,st_hl_a);}
            void ex_af_af() {std::swap(st_af, st_af_a);}
            // const versions
            types::byte a() const {return *(reinterpret_cast<const types::byte*>(&st_af)+impl::little_endian());}
            types::byte f() const {return *(reinterpret_cast<const types::byte*>(&st_af)+impl::big_endian());}
            types::byte b() const {return *(reinterpret_cast<const types::byte*>(&st_bc)+impl::little_endian());}
            types::byte c() const {return *(reinterpret_cast<const types::byte*>(&st_bc)+impl::big_endian());}
            types::byte d() const {return *(reinterpret_cast<const types::byte*>(&st_de)+impl::little_endian());}
            types::byte e() const {return *(reinterpret_cast<const types::byte*>(&st_de)+impl::big_endian());}
            types::byte h() const {return *(reinterpret_cast<const types::byte*>(&st_hl)+impl::little_endian());}
            types::byte l() const {return *(reinterpret_cast<const types::byte*>(&st_hl)+impl::big_endian());}
            types::byte ixh() const {return *(reinterpret_cast<const types::byte*>(&st_ix)+impl::little_endian());}
            types::byte ixl() const {return *(reinterpret_cast<const types::byte*>(&st_ix)+impl::big_endian());}
            types::byte iyh() const {return *(reinterpret_cast<const types::byte*>(&st_iy)+impl::little_endian());}
            types::byte iyl() const {return *(reinterpret_cast<const types::byte*>(&st_iy)+impl::big_endian());}
            types::word af() const {return st_af;}
            types::word bc() const {return st_bc;}
            types::word de() const {return st_de;}
            types::word hl() const {return st_hl;}
            types::word ix() const {return st_ix;}
            types::word iy() const {return st_iy;}
            types::word sp() const {return st_sp;}
            types::word pc() const {return st_pc;}
            types::byte i() const {return st_i;}
            types::byte r() const {return st_r;}
            bool iff() const {return st_iff1;}
            types::byte get_im() const {return st_im;}
            void store_im(types::byte b) {switch(b){case 0: case 1: case 2: st_im = b;default:;}}
        protected:
            types::word st_af {0xffff};
            types::word st_bc {0xffff};
            types::word st_de {0xffff};
            types::word st_hl {0xffff};
            types::word st_af_a {0xffff};
            types::word st_bc_a {0xffff};
            types::word st_de_a {0xffff};
            types::word st_hl_a {0xffff};
            types::word st_pc {0x0000};
            types::word st_sp {0xffff};
            types::word st_ix {0xffff};
            types::word st_iy {0xffff};
            types::byte st_r {0xff};
            types::byte st_i {0xff};
            types::byte st_im {0x00};
            bool st_iff1 {0};
            bool st_iff2 {0};
        };
    }
}

#endif
<|endoftext|>


<commit_before>// The MIT License(MIT)
//
// Copyright 2017 bladez-fate
//
// 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 "data.h"
#include "music.h"

#include "engine/easy.h"

namespace pilecode {

	namespace {
		int g_musicIdx = 0;
		bool g_musicDisabled = false;
        bool g_musicRandomize = true;
	}

	void UpdateMusic()
	{
		if (!g_musicDisabled) {
			// switch background music tracks
			if (!music::g_background[g_musicIdx].IsPlaying()) {
				g_musicIdx = (g_musicIdx + 1) % music::g_background.size();
				music::g_background[g_musicIdx].Play(0.2f);
			}
		}
		else {
			if (music::g_background[g_musicIdx].IsPlaying()) {
				music::g_background[g_musicIdx].Stop();
			}

            if (g_musicRandomize) {
                g_musicIdx = rand() % music::g_background.size();
                g_musicRandomize = false;
            } else {
                g_musicIdx = (g_musicIdx + 1) % music::g_background.size();
            }
		}
	}

	void ToggleMusic()
	{
		g_musicDisabled = !g_musicDisabled;
        g_musicRandomize = true;
	}

	bool IsMusicEnabled()
	{
		return !g_musicDisabled;
	}

}
<commit_msg>increase music volume<commit_after>// The MIT License(MIT)
//
// Copyright 2017 bladez-fate
//
// 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 "data.h"
#include "music.h"

#include "engine/easy.h"

namespace pilecode {

	namespace {
		int g_musicIdx = 0;
		bool g_musicDisabled = false;
        bool g_musicRandomize = true;
	}

	void UpdateMusic()
	{
		if (!g_musicDisabled) {
			// switch background music tracks
			if (!music::g_background[g_musicIdx].IsPlaying()) {
				g_musicIdx = (g_musicIdx + 1) % music::g_background.size();
				music::g_background[g_musicIdx].Play(0.4f);
			}
		}
		else {
			if (music::g_background[g_musicIdx].IsPlaying()) {
				music::g_background[g_musicIdx].Stop();
			}

            if (g_musicRandomize) {
                g_musicIdx = rand() % music::g_background.size();
                g_musicRandomize = false;
            } else {
                g_musicIdx = (g_musicIdx + 1) % music::g_background.size();
            }
		}
	}

	void ToggleMusic()
	{
		g_musicDisabled = !g_musicDisabled;
        g_musicRandomize = true;
	}

	bool IsMusicEnabled()
	{
		return !g_musicDisabled;
	}

}
<|endoftext|>


<commit_before>#include <node.h>
#include <v8.h>
#include "LRUCache.h"

using namespace v8;

void init(Handle<Object> exports)
{
	LRUCache::init(exports);
}

NODE_MODULE(native, init)
<commit_msg>test travis<commit_after>#include <node.h>
#include <nan.h>
#include "LRUCache.h"

using namespace v8;

void init(Handle<Object> exports)
{
	LRUCache::init(exports);
}

NODE_MODULE(native, init)
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */

#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

#include <boost/cast.hpp>

#include <pkmnsim/enums.hpp>
#include <pkmnsim/move.hpp>
#include <pkmnsim/team_pokemon.hpp>
#include <pkmnsim/database/queries.hpp>
#include <pkmnsim/types/prng.hpp>

#include "base_pokemon_gen1impl.hpp"
#include "base_pokemon_gen2impl.hpp"
#include "base_pokemon_modernimpl.hpp"

#include "item_impl.hpp"
#include "item_berryimpl.hpp"
#include "item_machineimpl.hpp"

#include "team_pokemon_impl.hpp"
#include "team_pokemon_gen1impl.hpp"
#include "team_pokemon_gen2impl.hpp"
#include "team_pokemon_modernimpl.hpp"

using namespace std;

namespace pkmnsim
{
    team_pokemon::sptr team_pokemon::make(unsigned int id, unsigned int game, unsigned int level,
                                          unsigned int move1, unsigned int move2,
                                          unsigned int move3, unsigned int move4)
    {
        try
        {
            base_pokemon::sptr base = base_pokemon::make(id, game);

            if(base->get_generation() < 1 or base->get_generation() > 5) throw runtime_error("Gen must be 1-5.");

            switch(base->get_generation())
            {
                case 1:
                    return sptr(new team_pokemon_gen1impl(base, game, level,
                                                       move1, move2, move3, move4));

                case 2:
                    return sptr(new team_pokemon_gen2impl(base, game, level,
                                                       move1, move2, move3, move4));

                default:
                    return sptr(new team_pokemon_modernimpl(base, game, level,
                                                       move1, move2, move3, move4));
            }
        }
        catch(exception &e)
        {
            cout << "Caught exception: " << e.what() << endl;
            exit(EXIT_FAILURE);
        }
    }

    team_pokemon_impl::team_pokemon_impl(base_pokemon::sptr base, unsigned int game, unsigned int lvl,
                                         unsigned int move1, unsigned int move2,
                                         unsigned int move3, unsigned int move4): team_pokemon()
    {
        prng rand_gen;
        unsigned int gen = database::get_generation(game);

        personality = rand_gen.lcrng_next(gen);
        trainer_id = rand_gen.lcrng_next(gen);

        base_pkmn = base;
        nickname = base_pkmn->get_species_name();
        trainer_name = "Ash";
        level = lvl;
        from_game = game;
        from_gen = base_pkmn->get_generation();
        held_item = item::make(Items::NONE, from_game);
        ball = PokeBalls::POKE_BALL;

		attributes = dict<string, int>();
        moves = moveset_t(4);
        move_PPs = vla<unsigned int>(4);

        icon_path = base_pkmn->get_icon_path(true);

        moves[0] = move::make(move1, from_game);
        move_PPs[0] = moves[0]->get_base_pp();

        moves[1] = move::make(move2, from_game);
        move_PPs[1] = moves[1]->get_base_pp();

        moves[2] = move::make(move3, from_game);
        move_PPs[2] = moves[2]->get_base_pp();

        moves[3] = move::make(move4, from_game);
        move_PPs[3] = moves[3]->get_base_pp();
    }

    base_pokemon::sptr team_pokemon_impl::get_base_pokemon(bool copy) const
    {
        base_pokemon::sptr to_return = base_pkmn;

        if(copy)
        {
            switch(database::get_generation(from_game))
            {
                case 1:
                {
                    base_pokemon_gen1impl actual1 = *(boost::polymorphic_downcast<base_pokemon_gen1impl*>(to_return.get()));
                    return base_pokemon::sptr(&actual1);
                }

                case 2:
                {
                    base_pokemon_gen2impl actual2 = *(boost::polymorphic_downcast<base_pokemon_gen2impl*>(to_return.get()));
                    return base_pokemon::sptr(&actual2);
                }

                default:
                {
                    base_pokemon_modernimpl actual345 = *(boost::polymorphic_downcast<base_pokemon_modernimpl*>(to_return.get()));
                    return base_pokemon::sptr(&actual345);
                }
            }
        }
        else return to_return;
    }

    pokemon_text team_pokemon_impl::get_nickname() const {return nickname;}

    void team_pokemon_impl::set_nickname(pokemon_text name)
    {
        if(name.std_string().length() == 0) nickname = base_pkmn->get_species_name();
        else if(name.std_string().length() <= 10) nickname = name;
    }

    pokemon_text team_pokemon_impl::get_trainer_name() const {return trainer_name;}

    void team_pokemon_impl::set_trainer_name(pokemon_text name)
    {
        if(name.std_string().length() == 0) trainer_name = "Ash"; //Reset to default
        else if(name.std_string().length() <= 7) trainer_name = name;
    }

    unsigned int team_pokemon_impl::get_level() const {return level;}

    void team_pokemon_impl::set_level(unsigned int lvl)
    {
        if(lvl > 0 and lvl <= 100) level = lvl;
    }

    unsigned int team_pokemon_impl::get_met_level() const {return met_level;}

    void team_pokemon_impl::set_met_level(unsigned int lvl)
    {
        if(lvl > 0 and lvl <= 100) met_level = lvl;
    }

    moveset_t team_pokemon_impl::get_moves() const {return moves;}

    vla<unsigned int> team_pokemon_impl::get_move_PPs() const {return move_PPs;}

    void team_pokemon_impl::set_move(unsigned int move_id, unsigned int pos)
    {
        //Will fail if move is incompatible with this generation
        moves[pos] = move::make(move_id, from_game);
    }

    void team_pokemon_impl::set_move_PP(unsigned int new_PP, unsigned int pos)
    {
        //TODO: implement PP Up stats
        if(new_PP <= moves[pos]->get_base_pp()) move_PPs[pos] = new_PP;
    }

    unsigned int team_pokemon_impl::get_status() const {return nonvolatile_status;}

    void team_pokemon_impl::set_status(unsigned int status)
    {
        if(status >= Statuses::OK and status <= Statuses::SLEEP) nonvolatile_status = status;
        else status = Statuses::OK;
    }

    unsigned int team_pokemon_impl::get_personality() const {return personality;}

    void team_pokemon_impl::set_personality(unsigned int new_personality) {personality = new_personality;}

    unsigned int team_pokemon_impl::get_generation() const {return from_gen;}

    item::sptr team_pokemon_impl::get_held_item(bool copy) const
    {
        item::sptr to_return = held_item;

        unsigned int item_id = to_return->get_item_id();

        if(copy)
        {
            if(item_id >= Items::TM01 and item_id <= Items::HM08)
            {
                item_machineimpl actual_machine = *(boost::polymorphic_downcast<item_machineimpl*>(to_return.get()));
                return item::sptr(&actual_machine);
            }
            else if((item_id >= Items::CHERI_BERRY and item_id <= Items::ROWAP_BERRY)
                    or (item_id >= Items::BERRY and item_id <= Items::MYSTERYBERRY))
            {
                item_berryimpl actual_berry = *(boost::polymorphic_downcast<item_berryimpl*>(to_return.get()));
                return item::sptr(&actual_berry);
            }
            else
            {
                item_impl actual = *(boost::polymorphic_downcast<item_impl*>(to_return.get()));
                return item::sptr(&actual);
            }
        }
        else return to_return;
    }

    void team_pokemon_impl::set_held_item(item::sptr new_item)
    {
        //Don't set item if it doesn't exist in this game
        if(database::get_item_index(new_item->get_item_id(), from_game)) held_item = new_item;
    }

    void team_pokemon_impl::set_held_item(unsigned int item_id)
    {
        set_held_item(item::make(item_id, from_game));
    }

    unsigned int team_pokemon_impl::get_ball() const {return ball;}

    void team_pokemon_impl::set_ball(unsigned int new_ball) {ball = new_ball;}

    string team_pokemon_impl::get_icon_path() const {return icon_path;}

    string team_pokemon_impl::get_sprite_path() const {return sprite_path;}

	int team_pokemon_impl::get_attribute(string attribute) const {return attributes[attribute];}

    dict<string, int> team_pokemon_impl::get_attributes() const {return attributes;}

    bool team_pokemon_impl::has_attribute(string attribute) const {return attributes.has_key(attribute);}

	void team_pokemon_impl::set_attribute(string attribute, int value) {attributes[attribute] = value;}

    void team_pokemon_impl::set_hidden_ability(bool val) {has_hidden_ability = val;}

    unsigned int team_pokemon_impl::get_trainer_gender() const {return otgender;}

    void team_pokemon_impl::set_trainer_gender(unsigned int new_gender) {otgender = new_gender;}

    unsigned int team_pokemon_impl::get_trainer_id() const {return trainer_id;}

    unsigned short team_pokemon_impl::get_public_trainer_id() const {return tid.public_id;}

    unsigned short team_pokemon_impl::get_secret_trainer_id() const {return tid.secret_id;}

    void team_pokemon_impl::set_trainer_id(unsigned int id) {trainer_id = id;}

    void team_pokemon_impl::set_public_trainer_id(unsigned short id) {tid.public_id = id;}

    void team_pokemon_impl::set_secret_trainer_id(unsigned short id) {tid.secret_id = id;}

    vector<string> team_pokemon_impl::get_egg_group_names() const {return base_pkmn->get_egg_group_names();}

    string team_pokemon_impl::get_species_name() const {return base_pkmn->get_species_name();}

    vector<unsigned int> team_pokemon_impl::get_egg_group_ids() const {return base_pkmn->get_egg_group_ids();}

    unsigned int team_pokemon_impl::get_game_id() const {return from_game;}

    unsigned int team_pokemon_impl::get_pokemon_id() const {return base_pkmn->get_pokemon_id();}

    unsigned int team_pokemon_impl::get_species_id() const {return base_pkmn->get_species_id();}

    dict<unsigned int, unsigned int> team_pokemon_impl::get_types() const {return base_pkmn->get_types();}

    dict<unsigned int, unsigned int> team_pokemon_impl::get_base_stats() const {return base_pkmn->get_base_stats();}

    dict<unsigned , unsigned int> team_pokemon_impl::get_ev_yields() const {return base_pkmn->get_ev_yields();}

    bool team_pokemon_impl::is_fully_evolved() const {return base_pkmn->is_fully_evolved();}
}
<commit_msg>team_pokemon: fixed get_item(copy = true)<commit_after>/*
 * Copyright (c) 2013 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */

#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

#include <boost/cast.hpp>

#include <pkmnsim/enums.hpp>
#include <pkmnsim/move.hpp>
#include <pkmnsim/team_pokemon.hpp>
#include <pkmnsim/database/queries.hpp>
#include <pkmnsim/types/prng.hpp>

#include "base_pokemon_gen1impl.hpp"
#include "base_pokemon_gen2impl.hpp"
#include "base_pokemon_modernimpl.hpp"

#include "item_impl.hpp"
#include "item_berryimpl.hpp"
#include "item_machineimpl.hpp"

#include "team_pokemon_impl.hpp"
#include "team_pokemon_gen1impl.hpp"
#include "team_pokemon_gen2impl.hpp"
#include "team_pokemon_modernimpl.hpp"

using namespace std;

namespace pkmnsim
{
    team_pokemon::sptr team_pokemon::make(unsigned int id, unsigned int game, unsigned int level,
                                          unsigned int move1, unsigned int move2,
                                          unsigned int move3, unsigned int move4)
    {
        try
        {
            base_pokemon::sptr base = base_pokemon::make(id, game);

            if(base->get_generation() < 1 or base->get_generation() > 5) throw runtime_error("Gen must be 1-5.");

            switch(base->get_generation())
            {
                case 1:
                    return sptr(new team_pokemon_gen1impl(base, game, level,
                                                       move1, move2, move3, move4));

                case 2:
                    return sptr(new team_pokemon_gen2impl(base, game, level,
                                                       move1, move2, move3, move4));

                default:
                    return sptr(new team_pokemon_modernimpl(base, game, level,
                                                       move1, move2, move3, move4));
            }
        }
        catch(exception &e)
        {
            cout << "Caught exception: " << e.what() << endl;
            exit(EXIT_FAILURE);
        }
    }

    team_pokemon_impl::team_pokemon_impl(base_pokemon::sptr base, unsigned int game, unsigned int lvl,
                                         unsigned int move1, unsigned int move2,
                                         unsigned int move3, unsigned int move4): team_pokemon()
    {
        prng rand_gen;
        unsigned int gen = database::get_generation(game);

        personality = rand_gen.lcrng_next(gen);
        trainer_id = rand_gen.lcrng_next(gen);

        base_pkmn = base;
        nickname = base_pkmn->get_species_name();
        trainer_name = "Ash";
        level = lvl;
        from_game = game;
        from_gen = base_pkmn->get_generation();
        held_item = item::make(Items::NONE, from_game);
        ball = PokeBalls::POKE_BALL;

		attributes = dict<string, int>();
        moves = moveset_t(4);
        move_PPs = vla<unsigned int>(4);

        icon_path = base_pkmn->get_icon_path(true);

        moves[0] = move::make(move1, from_game);
        move_PPs[0] = moves[0]->get_base_pp();

        moves[1] = move::make(move2, from_game);
        move_PPs[1] = moves[1]->get_base_pp();

        moves[2] = move::make(move3, from_game);
        move_PPs[2] = moves[2]->get_base_pp();

        moves[3] = move::make(move4, from_game);
        move_PPs[3] = moves[3]->get_base_pp();
    }

    base_pokemon::sptr team_pokemon_impl::get_base_pokemon(bool copy) const
    {
        base_pokemon::sptr to_return = base_pkmn;

        if(copy)
        {
            switch(database::get_generation(from_game))
            {
                case 1:
                {
                    base_pokemon_gen1impl actual1 = *(boost::polymorphic_downcast<base_pokemon_gen1impl*>(to_return.get()));
                    return base_pokemon::sptr(&actual1);
                }

                case 2:
                {
                    base_pokemon_gen2impl actual2 = *(boost::polymorphic_downcast<base_pokemon_gen2impl*>(to_return.get()));
                    return base_pokemon::sptr(&actual2);
                }

                default:
                {
                    base_pokemon_modernimpl actual345 = *(boost::polymorphic_downcast<base_pokemon_modernimpl*>(to_return.get()));
                    return base_pokemon::sptr(&actual345);
                }
            }
        }
        else return to_return;
    }

    pokemon_text team_pokemon_impl::get_nickname() const {return nickname;}

    void team_pokemon_impl::set_nickname(pokemon_text name)
    {
        if(name.std_string().length() == 0) nickname = base_pkmn->get_species_name();
        else if(name.std_string().length() <= 10) nickname = name;
    }

    pokemon_text team_pokemon_impl::get_trainer_name() const {return trainer_name;}

    void team_pokemon_impl::set_trainer_name(pokemon_text name)
    {
        if(name.std_string().length() == 0) trainer_name = "Ash"; //Reset to default
        else if(name.std_string().length() <= 7) trainer_name = name;
    }

    unsigned int team_pokemon_impl::get_level() const {return level;}

    void team_pokemon_impl::set_level(unsigned int lvl)
    {
        if(lvl > 0 and lvl <= 100) level = lvl;
    }

    unsigned int team_pokemon_impl::get_met_level() const {return met_level;}

    void team_pokemon_impl::set_met_level(unsigned int lvl)
    {
        if(lvl > 0 and lvl <= 100) met_level = lvl;
    }

    moveset_t team_pokemon_impl::get_moves() const {return moves;}

    vla<unsigned int> team_pokemon_impl::get_move_PPs() const {return move_PPs;}

    void team_pokemon_impl::set_move(unsigned int move_id, unsigned int pos)
    {
        //Will fail if move is incompatible with this generation
        moves[pos] = move::make(move_id, from_game);
    }

    void team_pokemon_impl::set_move_PP(unsigned int new_PP, unsigned int pos)
    {
        //TODO: implement PP Up stats
        if(new_PP <= moves[pos]->get_base_pp()) move_PPs[pos] = new_PP;
    }

    unsigned int team_pokemon_impl::get_status() const {return nonvolatile_status;}

    void team_pokemon_impl::set_status(unsigned int status)
    {
        if(status >= Statuses::OK and status <= Statuses::SLEEP) nonvolatile_status = status;
        else status = Statuses::OK;
    }

    unsigned int team_pokemon_impl::get_personality() const {return personality;}

    void team_pokemon_impl::set_personality(unsigned int new_personality) {personality = new_personality;}

    unsigned int team_pokemon_impl::get_generation() const {return from_gen;}

    item::sptr team_pokemon_impl::get_held_item(bool copy) const
    {
        item::sptr to_return = held_item;

        unsigned int item_id = to_return->get_item_id();

        if(copy) return item::make(item_id, from_game);
        else return to_return;
    }

    void team_pokemon_impl::set_held_item(item::sptr new_item)
    {
        //Don't set item if it doesn't exist in this game
        if(database::get_item_index(new_item->get_item_id(), from_game)) held_item = new_item;
    }

    void team_pokemon_impl::set_held_item(unsigned int item_id)
    {
        set_held_item(item::make(item_id, from_game));
    }

    unsigned int team_pokemon_impl::get_ball() const {return ball;}

    void team_pokemon_impl::set_ball(unsigned int new_ball) {ball = new_ball;}

    string team_pokemon_impl::get_icon_path() const {return icon_path;}

    string team_pokemon_impl::get_sprite_path() const {return sprite_path;}

	int team_pokemon_impl::get_attribute(string attribute) const {return attributes[attribute];}

    dict<string, int> team_pokemon_impl::get_attributes() const {return attributes;}

    bool team_pokemon_impl::has_attribute(string attribute) const {return attributes.has_key(attribute);}

	void team_pokemon_impl::set_attribute(string attribute, int value) {attributes[attribute] = value;}

    void team_pokemon_impl::set_hidden_ability(bool val) {has_hidden_ability = val;}

    unsigned int team_pokemon_impl::get_trainer_gender() const {return otgender;}

    void team_pokemon_impl::set_trainer_gender(unsigned int new_gender) {otgender = new_gender;}

    unsigned int team_pokemon_impl::get_trainer_id() const {return trainer_id;}

    unsigned short team_pokemon_impl::get_public_trainer_id() const {return tid.public_id;}

    unsigned short team_pokemon_impl::get_secret_trainer_id() const {return tid.secret_id;}

    void team_pokemon_impl::set_trainer_id(unsigned int id) {trainer_id = id;}

    void team_pokemon_impl::set_public_trainer_id(unsigned short id) {tid.public_id = id;}

    void team_pokemon_impl::set_secret_trainer_id(unsigned short id) {tid.secret_id = id;}

    vector<string> team_pokemon_impl::get_egg_group_names() const {return base_pkmn->get_egg_group_names();}

    string team_pokemon_impl::get_species_name() const {return base_pkmn->get_species_name();}

    vector<unsigned int> team_pokemon_impl::get_egg_group_ids() const {return base_pkmn->get_egg_group_ids();}

    unsigned int team_pokemon_impl::get_game_id() const {return from_game;}

    unsigned int team_pokemon_impl::get_pokemon_id() const {return base_pkmn->get_pokemon_id();}

    unsigned int team_pokemon_impl::get_species_id() const {return base_pkmn->get_species_id();}

    dict<unsigned int, unsigned int> team_pokemon_impl::get_types() const {return base_pkmn->get_types();}

    dict<unsigned int, unsigned int> team_pokemon_impl::get_base_stats() const {return base_pkmn->get_base_stats();}

    dict<unsigned , unsigned int> team_pokemon_impl::get_ev_yields() const {return base_pkmn->get_ev_yields();}

    bool team_pokemon_impl::is_fully_evolved() const {return base_pkmn->is_fully_evolved();}
}
<|endoftext|>


<commit_before>//===-- tsan_mman.cc --------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer (TSan), a race detector.
//
//===----------------------------------------------------------------------===//
#include "tsan_mman.h"
#include "tsan_allocator.h"
#include "tsan_rtl.h"
#include "tsan_report.h"
#include "tsan_flags.h"

namespace __tsan {

static void SignalUnsafeCall(ThreadState *thr, uptr pc) {
  if (!thr->in_signal_handler || !flags()->report_signal_unsafe)
    return;
  StackTrace stack;
  stack.ObtainCurrent(thr, pc);
  ScopedReport rep(ReportTypeSignalUnsafe);
  rep.AddStack(&stack);
  OutputReport(rep, rep.GetReport()->stacks[0]);
}

void *user_alloc(ThreadState *thr, uptr pc, uptr sz) {
  CHECK_GT(thr->in_rtl, 0);
  MBlock *b = (MBlock*)Alloc(sz + sizeof(MBlock));
  b->size = sz;
  void *p = b + 1;
  if (CTX() && CTX()->initialized) {
    MemoryResetRange(thr, pc, (uptr)p, sz);
  }
  DPrintf("#%d: alloc(%lu) = %p\n", thr->tid, sz, p);
  SignalUnsafeCall(thr, pc);
  return p;
}

void user_free(ThreadState *thr, uptr pc, void *p) {
  CHECK_GT(thr->in_rtl, 0);
  CHECK_NE(p, (void*)0);
  DPrintf("#%d: free(%p)\n", thr->tid, p);
  MBlock *b = user_mblock(thr, p);
  p = b + 1;
  if (CTX() && CTX()->initialized && thr->in_rtl == 1) {
    MemoryRangeFreed(thr, pc, (uptr)p, b->size);
  }
  Free(b);
  SignalUnsafeCall(thr, pc);
}

void *user_realloc(ThreadState *thr, uptr pc, void *p, uptr sz) {
  CHECK_GT(thr->in_rtl, 0);
  void *p2 = 0;
  // FIXME: Handle "shrinking" more efficiently,
  // it seems that some software actually does this.
  if (sz) {
    p2 = user_alloc(thr, pc, sz);
    if (p) {
      MBlock *b = user_mblock(thr, p);
      internal_memcpy(p2, p, min(b->size, sz));
    }
  }
  if (p) {
    user_free(thr, pc, p);
  }
  return p2;
}

void *user_alloc_aligned(ThreadState *thr, uptr pc, uptr sz, uptr align) {
  CHECK_GT(thr->in_rtl, 0);
  void *p = user_alloc(thr, pc, sz + align);
  void *pa = RoundUp(p, align);
  DCHECK_LE((uptr)pa + sz, (uptr)p + sz + align);
  return pa;
}

MBlock *user_mblock(ThreadState *thr, void *p) {
  CHECK_GT(thr->in_rtl, 0);
  CHECK_NE(p, (void*)0);
  MBlock *b = (MBlock*)AllocBlock(p);
  // FIXME: Output a warning, it's a user error.
  if (p < (char*)(b + 1) || p > (char*)(b + 1) + b->size) {
    Printf("user_mblock p=%p b=%p size=%lu beg=%p end=%p\n",
        p, b, b->size, (char*)(b + 1), (char*)(b + 1) + b->size);
    CHECK_GE(p, (char*)(b + 1));
    CHECK_LE(p, (char*)(b + 1) + b->size);
  }
  return b;
}

void *internal_alloc(MBlockType typ, uptr sz) {
  ThreadState *thr = cur_thread();
  CHECK_GT(thr->in_rtl, 0);
  return Alloc(sz);
}

void internal_free(void *p) {
  ThreadState *thr = cur_thread();
  CHECK_GT(thr->in_rtl, 0);
  Free(p);
}

}  // namespace __tsan
<commit_msg>tsan: check for overflow in malloc()<commit_after>//===-- tsan_mman.cc --------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer (TSan), a race detector.
//
//===----------------------------------------------------------------------===//
#include "tsan_mman.h"
#include "tsan_allocator.h"
#include "tsan_rtl.h"
#include "tsan_report.h"
#include "tsan_flags.h"

namespace __tsan {

static void SignalUnsafeCall(ThreadState *thr, uptr pc) {
  if (!thr->in_signal_handler || !flags()->report_signal_unsafe)
    return;
  StackTrace stack;
  stack.ObtainCurrent(thr, pc);
  ScopedReport rep(ReportTypeSignalUnsafe);
  rep.AddStack(&stack);
  OutputReport(rep, rep.GetReport()->stacks[0]);
}

void *user_alloc(ThreadState *thr, uptr pc, uptr sz) {
  CHECK_GT(thr->in_rtl, 0);
  if (sz + sizeof(MBlock) < sz)
    return 0;
  MBlock *b = (MBlock*)Alloc(sz + sizeof(MBlock));
  b->size = sz;
  void *p = b + 1;
  if (CTX() && CTX()->initialized) {
    MemoryResetRange(thr, pc, (uptr)p, sz);
  }
  DPrintf("#%d: alloc(%lu) = %p\n", thr->tid, sz, p);
  SignalUnsafeCall(thr, pc);
  return p;
}

void user_free(ThreadState *thr, uptr pc, void *p) {
  CHECK_GT(thr->in_rtl, 0);
  CHECK_NE(p, (void*)0);
  DPrintf("#%d: free(%p)\n", thr->tid, p);
  MBlock *b = user_mblock(thr, p);
  p = b + 1;
  if (CTX() && CTX()->initialized && thr->in_rtl == 1) {
    MemoryRangeFreed(thr, pc, (uptr)p, b->size);
  }
  Free(b);
  SignalUnsafeCall(thr, pc);
}

void *user_realloc(ThreadState *thr, uptr pc, void *p, uptr sz) {
  CHECK_GT(thr->in_rtl, 0);
  void *p2 = 0;
  // FIXME: Handle "shrinking" more efficiently,
  // it seems that some software actually does this.
  if (sz) {
    p2 = user_alloc(thr, pc, sz);
    if (p) {
      MBlock *b = user_mblock(thr, p);
      internal_memcpy(p2, p, min(b->size, sz));
    }
  }
  if (p) {
    user_free(thr, pc, p);
  }
  return p2;
}

void *user_alloc_aligned(ThreadState *thr, uptr pc, uptr sz, uptr align) {
  CHECK_GT(thr->in_rtl, 0);
  void *p = user_alloc(thr, pc, sz + align);
  void *pa = RoundUp(p, align);
  DCHECK_LE((uptr)pa + sz, (uptr)p + sz + align);
  return pa;
}

MBlock *user_mblock(ThreadState *thr, void *p) {
  CHECK_GT(thr->in_rtl, 0);
  CHECK_NE(p, (void*)0);
  MBlock *b = (MBlock*)AllocBlock(p);
  // FIXME: Output a warning, it's a user error.
  if (p < (char*)(b + 1) || p > (char*)(b + 1) + b->size) {
    Printf("user_mblock p=%p b=%p size=%lu beg=%p end=%p\n",
        p, b, b->size, (char*)(b + 1), (char*)(b + 1) + b->size);
    CHECK_GE(p, (char*)(b + 1));
    CHECK_LE(p, (char*)(b + 1) + b->size);
  }
  return b;
}

void *internal_alloc(MBlockType typ, uptr sz) {
  ThreadState *thr = cur_thread();
  CHECK_GT(thr->in_rtl, 0);
  return Alloc(sz);
}

void internal_free(void *p) {
  ThreadState *thr = cur_thread();
  CHECK_GT(thr->in_rtl, 0);
  Free(p);
}

}  // namespace __tsan
<|endoftext|>


<commit_before>#include "logging.h"

#include <boost/log/utility/setup/console.hpp>

namespace logging = boost::log;
using boost::log::trivial::severity_level;

severity_level gLoggingThreshold;

int64_t get_curlopt_verbose() { return gLoggingThreshold <= boost::log::trivial::debug ? 1L : 0L; }

void logger_init() {
  gLoggingThreshold = boost::log::trivial::info;
  logging::add_console_log(std::cout, boost::log::keywords::format = "%Message%",
                           boost::log::keywords::auto_flush = true);
  boost::log::core::get()->set_filter(boost::log::trivial::severity >= gLoggingThreshold);
}

void logger_set_threshold(severity_level threshold) {
  gLoggingThreshold = threshold;
  boost::log::core::get()->set_filter(boost::log::trivial::severity >= gLoggingThreshold);
}

int loggerGetSeverity() { return static_cast<int>(gLoggingThreshold); }

void LoggerConfig::updateFromPropertyTree(const boost::property_tree::ptree& pt) {
  CopyFromConfig(loglevel, "loglevel", boost::log::trivial::trace, pt);
}

void LoggerConfig::writeToStream(std::ostream& out_stream) const { writeOption(out_stream, loglevel, "loglevel"); }

// vim: set tabstop=2 shiftwidth=2 expandtab:
<commit_msg>Only display curl output in -vv (very verbose) mode<commit_after>#include "logging.h"

#include <boost/log/utility/setup/console.hpp>

namespace logging = boost::log;
using boost::log::trivial::severity_level;

severity_level gLoggingThreshold;

int64_t get_curlopt_verbose() { return gLoggingThreshold <= boost::log::trivial::trace ? 1L : 0L; }

void logger_init() {
  gLoggingThreshold = boost::log::trivial::info;
  logging::add_console_log(std::cout, boost::log::keywords::format = "%Message%",
                           boost::log::keywords::auto_flush = true);
  boost::log::core::get()->set_filter(boost::log::trivial::severity >= gLoggingThreshold);
}

void logger_set_threshold(severity_level threshold) {
  gLoggingThreshold = threshold;
  boost::log::core::get()->set_filter(boost::log::trivial::severity >= gLoggingThreshold);
}

int loggerGetSeverity() { return static_cast<int>(gLoggingThreshold); }

void LoggerConfig::updateFromPropertyTree(const boost::property_tree::ptree& pt) {
  CopyFromConfig(loglevel, "loglevel", boost::log::trivial::trace, pt);
}

void LoggerConfig::writeToStream(std::ostream& out_stream) const { writeOption(out_stream, loglevel, "loglevel"); }

// vim: set tabstop=2 shiftwidth=2 expandtab:
<|endoftext|>


<commit_before>#include "ofApp.h"

// ball related properties
int ballPosX;       // x coordinate of the ball's position
int ballPosY;       // y coordinate of the ball's position
int ballRadius;     // radius of the ball
bool ballIsMoving;  // indicates the moving state of the ball

// overall helper values
int movementStep;

//--------------------------------------------------------------
void ofApp::setup(){

    // initialize ball properties
    ballPosX = 300;
    ballPosY = 200;
    ballRadius = 25;
    ballIsMoving = false;

    // initialize helper values
    movementStep = 4;
}

//--------------------------------------------------------------
void ofApp::update(){

    // if ball is supposed to move: update it's position
    if (ballIsMoving) {

        // calculate new x coordinate of the ball
        ballPosX += movementStep;

        // let the ball bounce between the application window's borders
        // if ball's x position (considering its radius) is outside right border OR left border
        if ( (ballPosX > ofGetWindowWidth() - ballRadius) || (ballPosX < 0 + ballRadius) )
        {
            movementStep *= -1;
        }
    }
}

//--------------------------------------------------------------
void ofApp::draw(){

    // set color, apply color "fill" flag for shapes, and draw the ball (circle) at the designated position with the designated radius
    ofSetColor(255, 245, 0);
    ofFill();
    ofCircle(ballPosX, ballPosY, ballRadius);
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

    // DEBUG: print out pressed key (code) to the console
    cout << "Pressed key: " << key << endl;

    // press spacebar (32): toogle between ball's moving state
    if (key == 32) {
        ballIsMoving = !ballIsMoving;   // toogle moving state back and forth between true and false
    }
}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}
<commit_msg>Draw some application feedback, such as FPS, the mouse's position as well as the currently pressed key, directly to the application's window.<commit_after>#include "ofApp.h"

// ball related properties
int ballPosX;       // x coordinate of the ball's position
int ballPosY;       // y coordinate of the ball's position
int ballRadius;     // radius of the ball
bool ballIsMoving;  // indicates the moving state of the ball

// overall helper values
int movementStep;   // indicates the ball's movement step per update cycle
int pressedKey;     // store the key (code) of the most recent pressed key of the keyboard
bool keyIsPressed;  // indicates, if currently a key is pressed

//--------------------------------------------------------------
void ofApp::setup(){

    // initialize ball properties
    ballPosX = 300;
    ballPosY = 200;
    ballRadius = 25;
    ballIsMoving = false;

    // initialize helper values
    movementStep = 4;
}

//--------------------------------------------------------------
void ofApp::update(){

    // if ball is supposed to move: update it's position
    if (ballIsMoving) {

        // calculate new x coordinate of the ball
        ballPosX += movementStep;

        // let the ball bounce between the application window's borders
        // if ball's x position (considering its radius) is outside right border OR left border
        if ( (ballPosX > ofGetWindowWidth() - ballRadius) || (ballPosX < 0 + ballRadius) )
        {
            movementStep *= -1;
        }
    }
}

//--------------------------------------------------------------
void ofApp::draw(){

    // draw some application feedback
    //

    // set color: OF pink
    ofSetColor(236, 50, 135);

    // draw the framerate (FPS, "frames per second")
    ofDrawBitmapString(ofToString(ofGetFrameRate()) + "fps", 10, 15);

    // draw the mouse pointer's position
    ofDrawBitmapString("Mouse x|y: " + ofToString(mouseX) + "|" + ofToString(mouseY), 110, 15);

    // draw the pressed key (code), but only if a key is pressed
    if (keyIsPressed) {
        ofDrawBitmapString("Key: " + ofToString(pressedKey), 280, 15);
    }

    // draw application's (interactive) content
    //

    // set color, apply color "fill" flag for shapes, and draw the ball (circle) at the designated position with the designated radius
    ofSetColor(255, 245, 0);
    ofFill();
    ofCircle(ballPosX, ballPosY, ballRadius);
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

    // DEBUG: print out pressed key (code) to the console
    //cout << "Pressed key: " << key << endl;

    // update key-related helper values
    pressedKey = key;
    keyIsPressed = true;

    // press spacebar (32): toogle between ball's moving state
    if (key == 32) {
        ballIsMoving = !ballIsMoving;   // toogle moving state back and forth between true and false
    }
}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

    // update key-related helper value
    keyIsPressed = false;
}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}
<|endoftext|>


<commit_before>#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){

}

//--------------------------------------------------------------
void ofApp::update(){

}

//--------------------------------------------------------------
void ofApp::draw(){

    ofBackground(0);

    for (int i = 0; i < 100; i++){

        ofLine(0, 500 + ofRandom(-100,100), ofGetWidth(),
               500 + ofRandom(-100,100));

    }

}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}
<commit_msg>added a rectangle<commit_after>#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){

}

//--------------------------------------------------------------
void ofApp::update(){

}

//--------------------------------------------------------------
void ofApp::draw(){

    ofBackground(0);
    ofSetColor(ofRandom(0,255), ofRandom (0,255), ofRandom (0,255));
    for (int i = 0; i < 100; i++){

        ofLine(0, 500 + ofRandom(-100,100), ofGetWidth(),
               500 + ofRandom(-100,100));

    }
    for (int i = 0; i < 100; i++){
    ofRect(mouseX, i, 100,.5*mouseX);
    }
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}
<|endoftext|>