<commit_before>/*
    Copyright (c) 2007 Tobias Koenig <tokoe@kde.org>

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

    This library 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 Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "nepomukcontactfeeder.h"

#include <kabc/addressee.h>

#include <libakonadi/changerecorder.h>

#include <nepomuk/resource.h>
#include <nepomuk/variant.h>
#include <kurl.h>

// ontology includes
#include "personcontact.h"
#include "bbsnumber.h"
#include "carphonenumber.h"
#include "cellphonenumber.h"
#include "faxnumber.h"
#include "isdnnumber.h"
#include "messagingnumber.h"
#include "modemnumber.h"
#include "pagernumber.h"
#include "pcsnumber.h"
#include "videotelephonenumber.h"
#include "voicephonenumber.h"

using namespace Akonadi;

NepomukContactFeeder::NepomukContactFeeder( const QString &id )
  : AgentBase( id )
{
  monitor()->fetchAllParts();
  monitor()->monitorMimeType( "text/directory" );
  monitor()->setChangeRecordingEnabled( false );
}

void NepomukContactFeeder::itemAdded( const Akonadi::Item &item, const Akonadi::Collection& )
{
  itemChanged( item, QStringList() );
}

void NepomukContactFeeder::itemChanged( const Akonadi::Item &item, const QStringList& )
{
  if ( !item.hasPayload<KABC::Addressee>() )
    return;

  const KABC::Addressee addressee = item.payload<KABC::Addressee>();

  Nepomuk::PersonContact contact( item.url() );

  contact.setNameGivens( QStringList( addressee.givenName() ) );
  contact.setNameAdditionals( QStringList( addressee.additionalName() ) );
  contact.setNameFamilys( QStringList( addressee.familyName() ) );
  contact.setNameHonorificPrefixs( QStringList( addressee.prefix() ) );
  contact.setNameHonorificSuffixs( QStringList( addressee.suffix() ) );
  contact.setLocations( QStringList( addressee.geo().toString() ) ); // make it better
  // keys
  // sounds
  // logos
  // photos
  contact.setNotes( QStringList( addressee.note() ) );
  contact.setNicknames( QStringList( addressee.nickName() ) );
  contact.setContactUIDs( QStringList( addressee.uid() ) );
  contact.setFullnames( QStringList( addressee.name() ) );
  contact.setBirthDate( addressee.birthday().date() );

  // phone numbers

  // first clean all
  contact.setPhoneNumbers( QList<Nepomuk::PhoneNumber>() );

  // add all existing
  const KABC::PhoneNumber::List phoneNumbers = addressee.phoneNumbers();
  for ( int i = 0; i < phoneNumbers.count(); ++i ) {
    if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Bbs ) {
      Nepomuk::BbsNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Car ) {
      Nepomuk::CarPhoneNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Cell ) {
      Nepomuk::CellPhoneNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Fax ) {
      Nepomuk::FaxNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Isdn ) {
      Nepomuk::IsdnNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Msg ) {
      Nepomuk::MessagingNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Modem ) {
      Nepomuk::ModemNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Pager ) {
      Nepomuk::PagerNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Pcs ) {
      Nepomuk::PcsNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Video ) {
      Nepomuk::VideoTelephoneNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Voice ) {
      Nepomuk::VoicePhoneNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else { // matches Home and Work
      Nepomuk::PhoneNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    }
  }
}

void NepomukContactFeeder::itemRemoved( const Akonadi::DataReference &ref )
{
  Item item( ref );

  Nepomuk::PersonContact contact( item.url() );

  QList<Nepomuk::PhoneNumber> numbers = contact.phoneNumbers();
  Q_FOREACH( Nepomuk::PhoneNumber number, numbers ) {
    number.remove();
  }

  contact.remove();
}

int main( int argc, char **argv )
{
  return AgentBase::init<NepomukContactFeeder>( argc, argv );
}

#include "nepomukcontactfeeder.moc"
<commit_msg>extended nepomuk feeder to feed email and postal addresses into nepomuk<commit_after>/*
    Copyright (c) 2007 Tobias Koenig <tokoe@kde.org>

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

    This library 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 Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "nepomukcontactfeeder.h"

#include <kabc/addressee.h>

#include <libakonadi/changerecorder.h>

#include <nepomuk/resource.h>
#include <nepomuk/variant.h>
#include <kurl.h>

// ontology includes
#include "bbsnumber.h"
#include "carphonenumber.h"
#include "cellphonenumber.h"
#include "emailaddress.h"
#include "faxnumber.h"
#include "isdnnumber.h"
#include "messagingnumber.h"
#include "modemnumber.h"
#include "pagernumber.h"
#include "personcontact.h"
#include "pcsnumber.h"
#include "postaladdress.h"
#include "videotelephonenumber.h"
#include "voicephonenumber.h"

using namespace Akonadi;

NepomukContactFeeder::NepomukContactFeeder( const QString &id )
  : AgentBase( id )
{
  monitor()->fetchAllParts();
  monitor()->monitorMimeType( "text/directory" );
  monitor()->setChangeRecordingEnabled( false );
}

void NepomukContactFeeder::itemAdded( const Akonadi::Item &item, const Akonadi::Collection& )
{
  itemChanged( item, QStringList() );
}

void NepomukContactFeeder::itemChanged( const Akonadi::Item &item, const QStringList& )
{
  if ( !item.hasPayload<KABC::Addressee>() )
    return;

  const KABC::Addressee addressee = item.payload<KABC::Addressee>();

  Nepomuk::PersonContact contact( item.url() );

  contact.setNameGivens( QStringList( addressee.givenName() ) );
  contact.setNameAdditionals( QStringList( addressee.additionalName() ) );
  contact.setNameFamilys( QStringList( addressee.familyName() ) );
  contact.setNameHonorificPrefixs( QStringList( addressee.prefix() ) );
  contact.setNameHonorificSuffixs( QStringList( addressee.suffix() ) );
  contact.setLocations( QStringList( addressee.geo().toString() ) ); // make it better
  // keys
  // sounds
  // logos
  // photos
  contact.setNotes( QStringList( addressee.note() ) );
  contact.setNicknames( QStringList( addressee.nickName() ) );
  contact.setContactUIDs( QStringList( addressee.uid() ) );
  contact.setFullnames( QStringList( addressee.name() ) );
  contact.setBirthDate( addressee.birthday().date() );

  // phone numbers

  // first clean all
  contact.setPhoneNumbers( QList<Nepomuk::PhoneNumber>() );

  // add all existing
  const KABC::PhoneNumber::List phoneNumbers = addressee.phoneNumbers();
  for ( int i = 0; i < phoneNumbers.count(); ++i ) {
    if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Bbs ) {
      Nepomuk::BbsNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Car ) {
      Nepomuk::CarPhoneNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Cell ) {
      Nepomuk::CellPhoneNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Fax ) {
      Nepomuk::FaxNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Isdn ) {
      Nepomuk::IsdnNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Msg ) {
      Nepomuk::MessagingNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Modem ) {
      Nepomuk::ModemNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Pager ) {
      Nepomuk::PagerNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Pcs ) {
      Nepomuk::PcsNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Video ) {
      Nepomuk::VideoTelephoneNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else if ( phoneNumbers[ i ].type() & KABC::PhoneNumber::Voice ) {
      Nepomuk::VoicePhoneNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    } else { // matches Home and Work
      Nepomuk::PhoneNumber number;
      number.setPhoneNumbers( QStringList( phoneNumbers[ i ].number() ) );
      contact.addPhoneNumber( number );
    }
  }

  // im accounts

  // email addresses
  contact.setEmailAddresss( QList<Nepomuk::EmailAddress>() );

  const QStringList emails = addressee.emails();
  for ( int i = 0; i < emails.count(); ++i ) {
    Nepomuk::EmailAddress email;
    email.setEmailAddress( emails[ i ] );
    contact.addEmailAddress( email );
  }

  // addresses
  contact.setPostalAddresss( QList<Nepomuk::PostalAddress>() );

  const KABC::Address::List addresses = addressee.addresses();
  for ( int i = 0; i < addresses.count(); ++i ) {
    Nepomuk::PostalAddress address;
    address.addStreetAddress( addresses[ i ].street() );
    address.setPostalcode( addresses[ i ].postalCode() );
    address.setLocality( addresses[ i ].locality() );
    address.setRegion( addresses[ i ].region() );
    address.addPobox( addresses[ i ].postOfficeBox() );
    address.setCountry( addresses[ i ].country() );
    address.addExtendedAddress(  addresses[ i ].extended() );

    contact.addPostalAddress( address );
  }
}

void NepomukContactFeeder::itemRemoved( const Akonadi::DataReference &ref )
{
  Item item( ref );

  Nepomuk::PersonContact contact( item.url() );

  QList<Nepomuk::PhoneNumber> numbers = contact.phoneNumbers();
  Q_FOREACH( Nepomuk::PhoneNumber number, numbers ) {
    number.remove();
  }

  QList<Nepomuk::EmailAddress> emails = contact.emailAddresss();
  Q_FOREACH( Nepomuk::EmailAddress email, emails ) {
    email.remove();
  }

  QList<Nepomuk::PostalAddress> addresses = contact.postalAddresss();
  Q_FOREACH( Nepomuk::PostalAddress address, addresses ) {
    address.remove();
  }

  contact.remove();
}

int main( int argc, char **argv )
{
  return AgentBase::init<NepomukContactFeeder>( argc, argv );
}

#include "nepomukcontactfeeder.moc"
<|endoftext|>


<commit_before>/*
 * rpi_spi.cpp
 *
 *  Created on: 2016. 2. 26.
 *      Author: hwang
 */

#include "rpi_spi.hpp"
#include <cossb.hpp>
#include <string>
#include <3rdparty/bcm2835.h>
#include <tuple>

using namespace std;

#define PIN RPI_BPLUS_GPIO_J8_05

using namespace std;

USE_COMPONENT_INTERFACE(rpi_spi)

rpi_spi::rpi_spi()
:cossb::interface::icomponent(COMPONENT(rpi_spi)){
	// TODO Auto-generated constructor stub

}

rpi_spi::~rpi_spi() {

}

bool rpi_spi::setup()
{
	if(!bcm2835_init())
		return false;

	if(!bcm2835_spi_begin())
		return false;

	//set gpio as input
	//bcm2835_gpio_fsel(PIN, BCM2835_GPIO_FSEL_INPT);
	bcm2835_gpio_fsel(PIN, BCM2835_GPIO_FSEL_OUTP);
	//bcm2835_gpio_set_pud(PIN, BCM2835_GPIO_PUD_UP);

	//set default spi
	bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);      // The default
	bcm2835_spi_setDataMode(BCM2835_SPI_MODE0);                   // The default
	bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_65536); // The default
	bcm2835_spi_chipSelect(BCM2835_SPI_CS0);                      // The default
	bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW);      // the default

	return true;
}

bool rpi_spi::run()
{

	//1. check gpio
	//unsigned char value = bcm2835_gpio_lev(PIN);
	bcm2835_gpio_write(PIN, HIGH);

	//cossb_log->log(log::loglevel::INFO, fmt::format("GPIO : {}", value));

	/*if(value!=0x00){
		//cossb_log->log(log::loglevel::INFO, "GPIO : HIGH");
		unsigned char readata = bcm2835_spi_transfer(_write_byte);
		cossb_log->log(log::loglevel::INFO, fmt::format("Read SPI : {}", readata));
	}
	else {
		//cossb_log->log(log::loglevel::INFO, "GPIO : LOW");
	}*/

	return true;
}

bool rpi_spi::stop()
{
	//1. close spi
	bcm2835_spi_end();

	if(!bcm2835_close())
		return false;

	return true;
}

void rpi_spi::request(cossb::message* const msg)
{
	switch(msg->get_frame()->type) {
		case cossb::base::msg_type::REQUEST: break;
		case cossb::base::msg_type::DATA: {

			//subscribe emotion data
			try {
			unsigned char emotion_data = boost::any_cast<unsigned char>(*msg);
			_write_byte = emotion_data;	//copy

			cossb_log->log(log::loglevel::INFO, fmt::format("SPI write : {}", emotion_data));
			}
			catch(const boost::bad_any_cast&){
				cossb_log->log(log::loglevel::ERROR, "Invalid type casting..");
			}
		} break;
		case cossb::base::msg_type::RESPONSE: break;
		case cossb::base::msg_type::EVENT:  break;
		}
}

void rpi_spi::read()
{

}

<commit_msg>- update<commit_after>/*
 * rpi_spi.cpp
 *
 *  Created on: 2016. 2. 26.
 *      Author: hwang
 */

#include "rpi_spi.hpp"
#include <cossb.hpp>
#include <string>
#include <3rdparty/bcm2835.h>
#include <tuple>

using namespace std;

#define PIN RPI_BPLUS_GPIO_J8_05

using namespace std;

USE_COMPONENT_INTERFACE(rpi_spi)

rpi_spi::rpi_spi()
:cossb::interface::icomponent(COMPONENT(rpi_spi)){
	// TODO Auto-generated constructor stub

}

rpi_spi::~rpi_spi() {

}

bool rpi_spi::setup()
{
	if(!bcm2835_init())
		return false;

	if(!bcm2835_spi_begin())
		return false;

	//set gpio as input
	bcm2835_gpio_fsel(PIN, BCM2835_GPIO_FSEL_INPT);
	//bcm2835_gpio_set_pud(PIN, BCM2835_GPIO_PUD_UP);

	//set default spi
	bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);      // The default
	bcm2835_spi_setDataMode(BCM2835_SPI_MODE0);                   // The default
	bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_65536); // The default
	bcm2835_spi_chipSelect(BCM2835_SPI_CS0);                      // The default
	bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW);      // the default

	return true;
}

bool rpi_spi::run()
{

	//1. check gpio
	unsigned char value = bcm2835_gpio_lev(PIN);

	cossb_log->log(log::loglevel::INFO, fmt::format("GPIO : {}", value));

	if(value!=0x00){
		//cossb_log->log(log::loglevel::INFO, "GPIO : HIGH");
		unsigned char readata = bcm2835_spi_transfer(_write_byte);
		cossb_log->log(log::loglevel::INFO, fmt::format("Read SPI : {}", readata));
	}
	else {
		//cossb_log->log(log::loglevel::INFO, "GPIO : LOW");
	}

	return true;
}

bool rpi_spi::stop()
{
	//1. close spi
	bcm2835_spi_end();

	if(!bcm2835_close())
		return false;

	return true;
}

void rpi_spi::request(cossb::message* const msg)
{
	switch(msg->get_frame()->type) {
		case cossb::base::msg_type::REQUEST: break;
		case cossb::base::msg_type::DATA: {

			//subscribe emotion data
			try {
			unsigned char emotion_data = boost::any_cast<unsigned char>(*msg);
			_write_byte = emotion_data;	//copy

			cossb_log->log(log::loglevel::INFO, fmt::format("SPI write : {}", emotion_data));
			}
			catch(const boost::bad_any_cast&){
				cossb_log->log(log::loglevel::ERROR, "Invalid type casting..");
			}
		} break;
		case cossb::base::msg_type::RESPONSE: break;
		case cossb::base::msg_type::EVENT:  break;
		}
}

void rpi_spi::read()
{

}

<|endoftext|>


<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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 <Trigger.hpp>

void trigger(const Options &options, const unsigned int padding, const unsigned int integration, const AstroData::Observation &observation, const HostMemory &hostMemory, TriggeredEvents &triggeredEvents)
{
    unsigned int nrDMs = 0;

    if (options.subbandDedispersion)
    {
        nrDMs = observation.getNrDMs(true) * observation.getNrDMs();
    }
    else
    {
        nrDMs = observation.getNrDMs();
    }
#pragma omp parallel for
    for (unsigned int beam = 0; beam < observation.getNrSynthesizedBeams(); beam++)
    {
        for (unsigned int dm = 0; dm < nrDMs; dm++)
        {
            unsigned int maxIndex = 0;
            outputDataType maxSNR = 0;
            outputDataType maxSNR_mad = 0;

            if (options.snrMode == SNRMode::Standard)
            {
                maxSNR = hostMemory.snrData.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
                maxIndex = hostMemory.snrSamples.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
            }
            else if (options.snrMode == SNRMode::Momad)
            {
                maxSNR_mad = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / (hostMemory.medianOfMediansAbsoluteDeviation.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) * 1.48);
                maxSNR = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / hostMemory.stdevs.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
                maxIndex = hostMemory.maxIndices.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
            }

            if ( (std::isnormal(maxSNR)) && (maxSNR >= options.threshold) )
            {
                // std::cout<<"\n\n=TRIGGER=" << "\tSNR_mad: "<< maxSNR_mad << "\tSNR_stdev: " << maxSNR << "\tDM: " << dm << "\tthreshold: " << options.threshold <<  std::endl;
                // std::cout<<"integration: " << integration << "\tstdev: "<<hostMemory.stdevs.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)<<"\tmad*1.48: "<<(hostMemory.medianOfMediansAbsoluteDeviation.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) * 1.48)<<std::endl;
                // std::cout << std::endl;

                TriggeredEvent event;
                event.beam = beam;
                event.sample = maxIndex;
                event.integration = integration;
                event.DM = dm;
                event.SNR = maxSNR;
                try
                {
                    // Add event to its existing list
                    triggeredEvents.at(beam).at(dm).push_back(event);
                }
                catch (std::out_of_range &err)
                {
                    // Add event to new list
                    std::vector<TriggeredEvent> events;

                    events.push_back(event);
                    triggeredEvents.at(beam).insert(std::pair<unsigned int, std::vector<TriggeredEvent>>(dm, events));
                }
            }
        }
    }
}

void compact(const AstroData::Observation &observation, const TriggeredEvents &triggeredEvents, CompactedEvents &compactedEvents)
{
    CompactedEvents temporaryEvents(observation.getNrSynthesizedBeams());

    // Compact integration
    for (auto beamEvents = triggeredEvents.begin(); beamEvents != triggeredEvents.end(); ++beamEvents)
    {
        for (auto dmEvents = beamEvents->begin(); dmEvents != beamEvents->end(); ++dmEvents)
        {
            CompactedEvent event;

            for (auto dmEvent = dmEvents->second.begin(); dmEvent != dmEvents->second.end(); ++dmEvent)
            {
                if (dmEvent->SNR > event.SNR)
                {
                    event.beam = dmEvent->beam;
                    event.sample = dmEvent->sample;
                    event.integration = dmEvent->integration;
                    event.DM = dmEvent->DM;
                    event.SNR = dmEvent->SNR;
                }
            }
            event.compactedIntegration = dmEvents->second.size();
            temporaryEvents.at(event.beam).push_back(event);
        }
    }
    // Compact DM
    for (auto beamEvents = temporaryEvents.begin(); beamEvents != temporaryEvents.end(); ++beamEvents)
    {
        for (auto event = beamEvents->begin(); event != beamEvents->end(); ++event)
        {
            CompactedEvent finalEvent;
            unsigned int window = 0;

            while ( (event->DM + window) == (event + window)->DM && ((event + window) != beamEvents->end()) )
            {
                if ((event + window)->SNR > finalEvent.SNR)
                {
                    finalEvent.beam = (event + window)->beam;
                    finalEvent.sample = (event + window)->sample;
                    finalEvent.integration = (event + window)->integration;
                    finalEvent.compactedIntegration = (event + window)->compactedIntegration;
                    finalEvent.DM = (event + window)->DM;
                    finalEvent.SNR = (event + window)->SNR;
                }
                window++;
            }
            finalEvent.compactedDMs = window;
            compactedEvents.at(finalEvent.beam).push_back(finalEvent);
            // Move the iterator forward
            event += (window - 1);
        }
    }
}
<commit_msg>Add 3sig factor<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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 <Trigger.hpp>

void trigger(const Options &options, const unsigned int padding, const unsigned int integration, const AstroData::Observation &observation, const HostMemory &hostMemory, TriggeredEvents &triggeredEvents)
{
    unsigned int nrDMs = 0;

    if (options.subbandDedispersion)
    {
        nrDMs = observation.getNrDMs(true) * observation.getNrDMs();
    }
    else
    {
        nrDMs = observation.getNrDMs();
    }
#pragma omp parallel for
    for (unsigned int beam = 0; beam < observation.getNrSynthesizedBeams(); beam++)
    {
        for (unsigned int dm = 0; dm < nrDMs; dm++)
        {
            unsigned int maxIndex = 0;
            outputDataType maxSNR = 0;
            outputDataType maxSNR_mad = 0;

            if (options.snrMode == SNRMode::Standard)
            {
                maxSNR = hostMemory.snrData.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
                maxIndex = hostMemory.snrSamples.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
            }
            else if (options.snrMode == SNRMode::Momad)
            {
                //maxSNR_mad = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / (hostMemory.medianOfMediansAbsoluteDeviation.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) * 1.48);
                //maxSNR = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / (1.014*hostMemory.stdevs.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm));
                maxIndex = hostMemory.maxIndices.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);

                maxSNR = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / (1.014f*hostMemory.stdevs.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm));
                maxIndex = hostMemory.maxIndices.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);

                std::cout << hostMemory.stdevs.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) << std::endl;
            }

            if ( (std::isnormal(maxSNR)) && (maxSNR >= options.threshold) )
            {
                // std::cout<<"\n\n=TRIGGER=" << "\tSNR_mad: "<< maxSNR_mad << "\tSNR_stdev: " << maxSNR << "\tDM: " << dm << "\tthreshold: " << options.threshold <<  std::endl;
                // std::cout<<"integration: " << integration << "\tstdev: "<<hostMemory.stdevs.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)<<"\tmad*1.48: "<<(hostMemory.medianOfMediansAbsoluteDeviation.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) * 1.48)<<std::endl;
                // std::cout << std::endl;

                TriggeredEvent event;
                event.beam = beam;
                event.sample = maxIndex;
                event.integration = integration;
                event.DM = dm;
                event.SNR = maxSNR;
                try
                {
                    // Add event to its existing list
                    triggeredEvents.at(beam).at(dm).push_back(event);
                }
                catch (std::out_of_range &err)
                {
                    // Add event to new list
                    std::vector<TriggeredEvent> events;

                    events.push_back(event);
                    triggeredEvents.at(beam).insert(std::pair<unsigned int, std::vector<TriggeredEvent>>(dm, events));
                }
            }
        }
    }
}

void compact(const AstroData::Observation &observation, const TriggeredEvents &triggeredEvents, CompactedEvents &compactedEvents)
{
    CompactedEvents temporaryEvents(observation.getNrSynthesizedBeams());

    // Compact integration
    for (auto beamEvents = triggeredEvents.begin(); beamEvents != triggeredEvents.end(); ++beamEvents)
    {
        for (auto dmEvents = beamEvents->begin(); dmEvents != beamEvents->end(); ++dmEvents)
        {
            CompactedEvent event;

            for (auto dmEvent = dmEvents->second.begin(); dmEvent != dmEvents->second.end(); ++dmEvent)
            {
                if (dmEvent->SNR > event.SNR)
                {
                    event.beam = dmEvent->beam;
                    event.sample = dmEvent->sample;
                    event.integration = dmEvent->integration;
                    event.DM = dmEvent->DM;
                    event.SNR = dmEvent->SNR;
                }
            }
            event.compactedIntegration = dmEvents->second.size();
            temporaryEvents.at(event.beam).push_back(event);
        }
    }
    // Compact DM
    for (auto beamEvents = temporaryEvents.begin(); beamEvents != temporaryEvents.end(); ++beamEvents)
    {
        for (auto event = beamEvents->begin(); event != beamEvents->end(); ++event)
        {
            CompactedEvent finalEvent;
            unsigned int window = 0;

            while ( (event->DM + window) == (event + window)->DM && ((event + window) != beamEvents->end()) )
            {
                if ((event + window)->SNR > finalEvent.SNR)
                {
                    finalEvent.beam = (event + window)->beam;
                    finalEvent.sample = (event + window)->sample;
                    finalEvent.integration = (event + window)->integration;
                    finalEvent.compactedIntegration = (event + window)->compactedIntegration;
                    finalEvent.DM = (event + window)->DM;
                    finalEvent.SNR = (event + window)->SNR;
                }
                window++;
            }
            finalEvent.compactedDMs = window;
            compactedEvents.at(finalEvent.beam).push_back(finalEvent);
            // Move the iterator forward
            event += (window - 1);
        }
    }
}
<|endoftext|>


<commit_before>#ifndef INCLUDE_ACKWARD_CORE_PROPERTY_HPP
#define INCLUDE_ACKWARD_CORE_PROPERTY_HPP

#include <iostream>
#include <string>

#include <boost/call_traits.hpp>

#include <ackward/core/ExceptionTranslator.hpp>
#include <ackward/core/Object.hpp>

namespace ackward {
namespace core {

/** Property<T> is a value-like C++ interface to an underlying Python
    property. It provides a C++ API for properties which is similar to
    what you get in Python.

    \rst
    General use is like this::

      class MyClass {
      public:
        Property<int> myProperty;
      };
      ...
      MyClass c;
      c.myProperty = 3;
      int x = c.myProperty;

    \endrst
 */
template <typename T>
class Property : private Object
{
public:
    typedef T value_type;

    /** Construct a new property.

        @param obj The underlying Python object.
        @param pythonName The name of the property on `obj`.
     */
    Property(boost::python::object obj,
             const std::string& pythonName) :
        Object (obj),
        pythonName_ (pythonName)
        {}

    /** Get the underlying property value.
     */
    operator value_type () const
        {
            try {
                return boost::python::extract<value_type>(
                    obj().attr(pythonName_.c_str()));
            } TRANSLATE_PYTHON_EXCEPTION();
        }

    /** Assign to the underlying property.

        @param v The value to assign.
        @returns This object.
     */
    Property<value_type>& operator=(typename boost::call_traits<value_type>::const_reference v)
        {
            try {
                obj().attr(pythonName_.c_str()) = v;
            } TRANSLATE_PYTHON_EXCEPTION();

            return *this;
        }

    using Object::obj;

private:
    std::string pythonName_;

};

template <typename T>
std::ostream& operator<<(std::ostream& os, const Property<T>& p)
{
    os << static_cast<T>(p);
    return os;
}

}
}

#endif
<commit_msg>split core::Property up into ROProperty and Property<commit_after>#ifndef INCLUDE_ACKWARD_CORE_PROPERTY_HPP
#define INCLUDE_ACKWARD_CORE_PROPERTY_HPP

#include <iostream>
#include <string>

#include <boost/call_traits.hpp>

#include <ackward/core/ExceptionTranslator.hpp>
#include <ackward/core/Object.hpp>

namespace ackward {
namespace core {

/** Property<T> is a value-like C++ interface to an underlying Python
    property. It provides a C++ API for properties which is similar to
    what you get in Python.

    \rst
    General use is like this::

      class MyClass {
      public:
        Property<int> myProperty;
      };
      ...
      MyClass c;
      c.myProperty = 3;
      int x = c.myProperty;

    \endrst
 */
template <typename T>
class ROProperty : private Object
{
public:
    typedef T value_type;

    /** Construct a new read-only property.

        @param obj The underlying Python object.
        @param pythonName The name of the property on `obj`.
     */
    ROProperty(boost::python::object obj,
             const std::string& pythonName) :
        Object (obj),
        pythonName_ (pythonName)
        {}

    /** Get the underlying property value.
     */
    operator value_type () const
        {
            try {
                return boost::python::extract<value_type>(
                    obj().attr(pythonName_.c_str()));
            } TRANSLATE_PYTHON_EXCEPTION();
        }

    using Object::obj;

    const std::string& pythonName() const
        {
            return pythonName_;
        }

private:
    std::string pythonName_;

};

template <typename T>
class Property : public ROProperty<T>
{
public:
    typedef typename ROProperty<T>::value_type value_type;

    /** Construct a new property.

        @param obj The underlying Python object.
        @param pythonName The name of the property on `obj`.
     */
    Property(boost::python::object obj,
             const std::string& pythonName) :
        ROProperty<T>(obj, pythonName)
        {}

    /** Assign to the underlying property.

        @param v The value to assign.
        @returns This object.
     */
    Property<value_type>& operator=(typename boost::call_traits<value_type>::const_reference v)
        {
            try {
                obj().attr(this->pythonName().c_str()) = v;
            } TRANSLATE_PYTHON_EXCEPTION();

            return *this;
        }

    using ROProperty<T>::obj;
};

template <typename T>
std::ostream& operator<<(std::ostream& os, const ROProperty<T>& p)
{
    os << static_cast<T>(p);
    return os;
}

}
}

#endif
<|endoftext|>


<commit_before>/*
 * AscEmu Framework based on ArcEmu MMORPG Server
 * Copyright (C) 2014-2015 AscEmu Team <http://www.ascemu.org/>
 * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/>
 * Copyright (C) 2005-2007 Ascent Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "StdAfx.h"

const char* GetDifficultyString(uint8 difficulty)
{
    switch (difficulty)
    {
        case MODE_NORMAL:
            return "normal";
        case MODE_HEROIC:
            return "heroic";
        default:
            return "unknown";
    }
}

const char* GetRaidDifficultyString(uint8 diff)
{
    switch (diff)
    {
        case MODE_NORMAL_10MEN:
            return "normal 10men";
        case MODE_NORMAL_25MEN:
            return "normal 25men";
        case MODE_HEROIC_10MEN:
            return "heroic 10men";
        case MODE_HEROIC_25MEN:
            return "heroic 25men";
        default:
            return "unknown";
    }
}

const char* GetMapTypeString(uint8 type)
{
    switch (type)
    {
        case INSTANCE_NULL:
            return "Continent";
        case INSTANCE_RAID:
            return "Raid";
        case INSTANCE_NONRAID:
            return "Non-Raid";
        case INSTANCE_BATTLEGROUND:
            return "PvP";
        case INSTANCE_MULTIMODE:
            return "MultiMode";
        default:
            return "Unknown";
    }
}

bool ChatHandler::HandleResetAllInstancesCommand(const char* args, WorldSession* m_session)
{

    Player* plr;
    if (strlen(args) == 0)
        plr = getSelectedChar(m_session, true);
    else
        plr = objmgr.GetPlayer(args, false);;

    if (!plr)
    {
        RedSystemMessage(m_session, "Player not found");
        return true;
    }

    SystemMessage(m_session, "Trying to reset all instances of player %s...", plr->GetName());
    sInstanceMgr.ResetSavedInstances(plr);
    SystemMessage(m_session, "...done");

    sGMLog.writefromsession(m_session, "used reset all instances command on %s,", plr->GetName());
    return true;
}

bool ChatHandler::HandleResetInstanceCommand(const char* args, WorldSession* m_session)
{

    uint32 instanceId;
    int argc = 1;
    char* playername = NULL;
    char* guidString = (char*)args;

    // Parse arguments
    char* space = (char*)strchr(args, ' ');
    if (space)
    {
        *space = '\0';
        playername = space + 1;
        argc = 2;
    }

    instanceId = atoi(guidString);
    if (!instanceId)
    {
        RedSystemMessage(m_session, "You must specify an instance id.");
        return true;
    }

    Player* plr;

    if (argc == 1)
        plr = getSelectedChar(m_session, true);
    else
        plr = objmgr.GetPlayer((const char*)playername, false);;

    if (!plr)
    {
        RedSystemMessage(m_session, "Player not found");
        return true;
    }

    Instance* instance = sInstanceMgr.GetInstanceByIds(NUM_MAPS, instanceId);
    if (instance == NULL)
    {
        RedSystemMessage(m_session, "There's no instance with id %u.", instanceId);
        return true;
    }

    if (IS_PERSISTENT_INSTANCE(instance))
    {
        if (m_session->CanUseCommand('z'))
        {
            bool foundSomething = false;
            plr->getPlayerInfo()->savedInstanceIdsLock.Acquire();
            for (uint32 difficulty = 0; difficulty < NUM_INSTANCE_MODES; difficulty++)
            {
                PlayerInstanceMap::iterator itr = plr->getPlayerInfo()->savedInstanceIds[difficulty].find(instance->m_mapId);
                if (itr == plr->getPlayerInfo()->savedInstanceIds[difficulty].end() || (*itr).second != instance->m_instanceId)
                    continue;
                plr->SetPersistentInstanceId(instance->m_mapId, difficulty, 0);
                SystemMessage(m_session, "Instance with id %u (%s) is persistent and will only be revoked from player.", instanceId, GetDifficultyString(static_cast<uint8>(difficulty)));
                foundSomething = true;
            }
            plr->getPlayerInfo()->savedInstanceIdsLock.Release();
            if (!foundSomething)
                RedSystemMessage(m_session, "Player is not assigned to persistent instance with id %u.", instanceId);
            return true;
        }
        else
        {
            RedSystemMessage(m_session, "Instance with id %u is persistent and can only be removed from player by admins.", instanceId);
            return true;
        }
    }

    if (instance->m_mapMgr && instance->m_mapMgr->HasPlayers())
    {
        RedSystemMessage(m_session, "Failed to reset non-persistent instance with id %u, due to player still inside.", instanceId);
        return true;
    }

    if (instance->m_creatorGroup)
    {
        Group* group = plr->GetGroup();
        if (group == NULL || instance->m_creatorGroup != group->GetID())
        {
            RedSystemMessage(m_session, "Player %s is not a member of the group assigned to the non-persistent instance with id %u.", plr->GetName(), instanceId);
            return true;
        }
    }
    else if (instance->m_creatorGuid == 0 || instance->m_creatorGuid != plr->GetLowGUID())
    {
        RedSystemMessage(m_session, "Player %s is not assigned to instance with id %u.", plr->GetName(), instanceId);
        return true;
    }

    // tell player the instance was reset
    WorldPacket data(SMSG_INSTANCE_RESET, 4);
    data << instance->m_mapId;
    plr->GetSession()->SendPacket(&data);

    // shut down instance
    sInstanceMgr.DeleteBattlegroundInstance(instance->m_mapId, instance->m_instanceId);
    instance->m_mapMgr->InstanceShutdown();
    //    RedSystemMessage(m_session, "Resetting single non-persistent instances is not available yet.");
    sGMLog.writefromsession(m_session, "used reset instance command on %s, instance %u,", plr->GetName(), instanceId);
    return true;
}

bool ChatHandler::HandleShutdownInstanceCommand(const char* args, WorldSession* m_session)
{
    uint32 instanceId = (args ? atoi(args) : 0);
    if (instanceId == 0)
        return false;

    Instance* instance = sInstanceMgr.GetInstanceByIds(NUM_MAPS, instanceId);
    if (instance == NULL)
    {
        RedSystemMessage(m_session, "There's no instance with id %u.", instanceId);
        return true;
    }

    if (instance->m_mapMgr == NULL)
    {
        RedSystemMessage(m_session, "Instance with id %u already shut down.", instanceId);
        return true;
    }

    SystemMessage(m_session, "Attempting to shutdown instance with id %u...", instanceId);

    sInstanceMgr.SafeDeleteInstance(instance->m_mapMgr);

    instance = NULL;

    SystemMessage(m_session, "...done");

    sGMLog.writefromsession(m_session, "used shutdown instance command on instance %u,", instanceId);

    return true;
}

//bool ChatHandler::HandleDeleteInstanceCommand(const char* args, WorldSession* m_session)
//{
//    RedSystemMessage(m_session, "Command not implemented yet.");
//    return true;
//    //sGMLog.writefromsession(m_session, "used delete instance command on instance %u,", 0);
//}

bool ChatHandler::HandleGetInstanceInfoCommand(const char* args, WorldSession* m_session)
{
    Player* plr = m_session->GetPlayer();
    if (plr == NULL)
        return false;

    bool userInput = true;
    uint32 instanceId = (args ? atoi(args) : 0);
    if (instanceId == 0)
    {
        userInput = false;
        instanceId = plr->GetInstanceID();
        if (instanceId == 0)
            return false;
    }

    Instance* instance = sInstanceMgr.GetInstanceByIds(NUM_MAPS, instanceId);
    if (instance == NULL)
    {
        if (userInput)
        {
            RedSystemMessage(m_session, "Instance with id %u not found.", instanceId);
            return true;
        }
        return false;
    }

    std::stringstream ss;
    ss << "Instance ID: " << MSG_COLOR_CYAN << instance->m_instanceId << "|r (" << MSG_COLOR_CYAN;
    if (instance->m_mapInfo == NULL)
        ss << instance->m_mapId;
    else
        ss << instance->m_mapInfo->name;
    ss << "|r)\n";
    ss << "Persistent: " << MSG_COLOR_CYAN << (instance->m_persistent ? "Yes" : "No") << "|r\n";
    if (instance->m_mapInfo != NULL)
    {
        ss << "Type: " << MSG_COLOR_CYAN << GetMapTypeString(static_cast<uint8>(instance->m_mapInfo->type)) << "|r";

        if (instance->m_mapInfo->type == INSTANCE_MULTIMODE)
        {
            ss << " (" << MSG_COLOR_CYAN << GetDifficultyString(static_cast<uint8>(instance->m_difficulty)) << "|r)";
        }

        if (instance->m_mapInfo->type == INSTANCE_RAID)
        {
            ss << " (" << MSG_COLOR_CYAN << GetRaidDifficultyString(static_cast<uint8>(instance->m_difficulty)) << "|r)";
        }

        ss << "\n";
    }
    ss << "Created: " << MSG_COLOR_CYAN << ConvertTimeStampToDataTime((uint32)instance->m_creation) << "|r\n";
    if (instance->m_expiration != 0)
        ss << "Expires: " << MSG_COLOR_CYAN << ConvertTimeStampToDataTime((uint32)instance->m_expiration) << "|r\n";

    if (instance->m_mapMgr == NULL)
    {
        ss << "Status: " << MSG_COLOR_LIGHTRED << "Shut Down|r\n";
    }
    else if (!instance->m_mapMgr->HasPlayers())
    {
        ss << "Status: " << MSG_COLOR_LIGHTRED << "Idle|r";
        if (instance->m_mapMgr->InactiveMoveTime && instance->m_mapMgr->GetMapInfo()->type != INSTANCE_NULL)
            ss << " (" << MSG_COLOR_CYAN << "Shutdown in " << MSG_COLOR_LIGHTRED << (((long)instance->m_mapMgr->InactiveMoveTime - UNIXTIME) / 60) << MSG_COLOR_CYAN << " minutes|r)";
        ss << "\n";
    }
    else
    {
        ss << "Status: " << MSG_COLOR_GREEN << "In use|r (" << MSG_COLOR_GREEN << (uint32)instance->m_mapMgr->GetPlayerCount() << MSG_COLOR_CYAN << " players inside|r)\n";

    }
    SendMultilineMessage(m_session, ss.str().c_str());

    return true;
}

bool ChatHandler::HandleCreateInstanceCommand(const char* args, WorldSession* m_session)
{
    Player* plr = getSelectedChar(m_session, true);
    float x, y, z;
    uint32 mapid;
    if (sscanf(args, "%u %f %f %f", (unsigned int*)&mapid, &x, &y, &z) != 4)
        return false;

    if (!plr)
    {
        plr = m_session->GetPlayer();
        SystemMessage(m_session, "Auto-targeting self.");
    }
    if (!plr) return false;

    /* Create Map Manager */
    MapMgr* mgr = sInstanceMgr.CreateInstance(INSTANCE_NONRAID, mapid);
    if (mgr == NULL)
    {
        sLog.Error("CreateInstanceGMCommand", "CreateInstance() call failed for map %u", mapid);
        return false;      // Shouldn't happen
    }
    Log.Notice("CreateInstanceGMCommand", "GM created instance for map %u", mapid);

    LocationVector vec(x, y, z);
    m_session->GetPlayer()->SafeTeleport(mgr, vec);
    return true;

}

bool ChatHandler::HandleExitInstanceCommand(const char* args, WorldSession* m_session)
{
    BlueSystemMessage(m_session, "Attempting to exit from instance...");
    bool result = m_session->GetPlayer()->ExitInstance();
    if (!result)
    {
        RedSystemMessage(m_session, "Entry points not found.");
        return true;
    }
    else
    {
        GreenSystemMessage(m_session, "Removal successful.");
        return true;
    }
}

bool ChatHandler::HandleShowInstancesCommand(const char* args, WorldSession* m_session)
{
    Player* plr = getSelectedChar(m_session, true);
    if (!plr)
        return true;

    uint32 count = 0;
    std::stringstream ss;
    ss << "Show persistent instances of " << MSG_COLOR_CYAN << plr->GetName() << "|r\n";
    plr->getPlayerInfo()->savedInstanceIdsLock.Acquire();
    for (uint32 difficulty = 0; difficulty < NUM_INSTANCE_MODES; difficulty++)
    {
        for (PlayerInstanceMap::iterator itr = plr->getPlayerInfo()->savedInstanceIds[difficulty].begin(); itr != plr->getPlayerInfo()->savedInstanceIds[difficulty].end(); ++itr)
        {
            count++;
            ss << " - " << MSG_COLOR_CYAN << (*itr).second << "|r";
            MapInfo* mapInfo = WorldMapInfoStorage.LookupEntry((*itr).first);
            if (mapInfo != NULL)
                ss << " (" << MSG_COLOR_CYAN << mapInfo->name << "|r)";
            Instance* pInstance = sInstanceMgr.GetInstanceByIds((*itr).first, (*itr).second);
            if (pInstance == NULL)
                ss << " - " << MSG_COLOR_RED << "Expired!|r";
            else
            {
                ss << " [" << GetMapTypeString(static_cast<uint8>(pInstance->m_mapInfo->type)) << "]";
                if (pInstance->m_mapInfo->type == INSTANCE_MULTIMODE)
                {
                    ss << " [" << GetDifficultyString(static_cast<uint8>(pInstance->m_difficulty)) << "]";
                }
                ss << " - ";
                if (pInstance->m_mapMgr == NULL)
                    ss << MSG_COLOR_LIGHTRED << "Shut Down|r";
                else
                {
                    if (!pInstance->m_mapMgr->HasPlayers())
                        ss << MSG_COLOR_LIGHTRED << "Idle|r";
                    else
                        ss << MSG_COLOR_GREEN << "In use|r";
                }
            }
            ss << "\n";
        }
    }
    plr->getPlayerInfo()->savedInstanceIdsLock.Release();

    if (count == 0)
        ss << "Player is not assigned to any persistent instances.\n";
    else
        ss << "Player is assigned to " << MSG_COLOR_CYAN << count << "|r persistent instances.\n";

    SendMultilineMessage(m_session, ss.str().c_str());
    sGMLog.writefromsession(m_session, "used show instances command on %s,", plr->GetName());
    return true;
}
<commit_msg>Dereference after null check CID 52655 (InstanceCommands.cpp): sInstanceMgr.DeleteBattlegroundInstance calls InstanceShutdown. No need to call it twice.<commit_after>/*
 * AscEmu Framework based on ArcEmu MMORPG Server
 * Copyright (C) 2014-2015 AscEmu Team <http://www.ascemu.org/>
 * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/>
 * Copyright (C) 2005-2007 Ascent Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "StdAfx.h"

const char* GetDifficultyString(uint8 difficulty)
{
    switch (difficulty)
    {
        case MODE_NORMAL:
            return "normal";
        case MODE_HEROIC:
            return "heroic";
        default:
            return "unknown";
    }
}

const char* GetRaidDifficultyString(uint8 diff)
{
    switch (diff)
    {
        case MODE_NORMAL_10MEN:
            return "normal 10men";
        case MODE_NORMAL_25MEN:
            return "normal 25men";
        case MODE_HEROIC_10MEN:
            return "heroic 10men";
        case MODE_HEROIC_25MEN:
            return "heroic 25men";
        default:
            return "unknown";
    }
}

const char* GetMapTypeString(uint8 type)
{
    switch (type)
    {
        case INSTANCE_NULL:
            return "Continent";
        case INSTANCE_RAID:
            return "Raid";
        case INSTANCE_NONRAID:
            return "Non-Raid";
        case INSTANCE_BATTLEGROUND:
            return "PvP";
        case INSTANCE_MULTIMODE:
            return "MultiMode";
        default:
            return "Unknown";
    }
}

bool ChatHandler::HandleResetAllInstancesCommand(const char* args, WorldSession* m_session)
{

    Player* plr;
    if (strlen(args) == 0)
        plr = getSelectedChar(m_session, true);
    else
        plr = objmgr.GetPlayer(args, false);;

    if (!plr)
    {
        RedSystemMessage(m_session, "Player not found");
        return true;
    }

    SystemMessage(m_session, "Trying to reset all instances of player %s...", plr->GetName());
    sInstanceMgr.ResetSavedInstances(plr);
    SystemMessage(m_session, "...done");

    sGMLog.writefromsession(m_session, "used reset all instances command on %s,", plr->GetName());
    return true;
}

bool ChatHandler::HandleResetInstanceCommand(const char* args, WorldSession* m_session)
{

    uint32 instanceId;
    int argc = 1;
    char* playername = NULL;
    char* guidString = (char*)args;

    // Parse arguments
    char* space = (char*)strchr(args, ' ');
    if (space)
    {
        *space = '\0';
        playername = space + 1;
        argc = 2;
    }

    instanceId = atoi(guidString);
    if (!instanceId)
    {
        RedSystemMessage(m_session, "You must specify an instance id.");
        return true;
    }

    Player* plr;

    if (argc == 1)
        plr = getSelectedChar(m_session, true);
    else
        plr = objmgr.GetPlayer((const char*)playername, false);;

    if (!plr)
    {
        RedSystemMessage(m_session, "Player not found");
        return true;
    }

    Instance* instance = sInstanceMgr.GetInstanceByIds(NUM_MAPS, instanceId);
    if (instance == NULL)
    {
        RedSystemMessage(m_session, "There's no instance with id %u.", instanceId);
        return true;
    }

    if (IS_PERSISTENT_INSTANCE(instance))
    {
        if (m_session->CanUseCommand('z'))
        {
            bool foundSomething = false;
            plr->getPlayerInfo()->savedInstanceIdsLock.Acquire();
            for (uint32 difficulty = 0; difficulty < NUM_INSTANCE_MODES; difficulty++)
            {
                PlayerInstanceMap::iterator itr = plr->getPlayerInfo()->savedInstanceIds[difficulty].find(instance->m_mapId);
                if (itr == plr->getPlayerInfo()->savedInstanceIds[difficulty].end() || (*itr).second != instance->m_instanceId)
                    continue;
                plr->SetPersistentInstanceId(instance->m_mapId, difficulty, 0);
                SystemMessage(m_session, "Instance with id %u (%s) is persistent and will only be revoked from player.", instanceId, GetDifficultyString(static_cast<uint8>(difficulty)));
                foundSomething = true;
            }
            plr->getPlayerInfo()->savedInstanceIdsLock.Release();
            if (!foundSomething)
                RedSystemMessage(m_session, "Player is not assigned to persistent instance with id %u.", instanceId);
            return true;
        }
        else
        {
            RedSystemMessage(m_session, "Instance with id %u is persistent and can only be removed from player by admins.", instanceId);
            return true;
        }
    }

    if (instance->m_mapMgr && instance->m_mapMgr->HasPlayers())
    {
        RedSystemMessage(m_session, "Failed to reset non-persistent instance with id %u, due to player still inside.", instanceId);
        return true;
    }

    if (instance->m_creatorGroup)
    {
        Group* group = plr->GetGroup();
        if (group == NULL || instance->m_creatorGroup != group->GetID())
        {
            RedSystemMessage(m_session, "Player %s is not a member of the group assigned to the non-persistent instance with id %u.", plr->GetName(), instanceId);
            return true;
        }
    }
    else if (instance->m_creatorGuid == 0 || instance->m_creatorGuid != plr->GetLowGUID())
    {
        RedSystemMessage(m_session, "Player %s is not assigned to instance with id %u.", plr->GetName(), instanceId);
        return true;
    }

    // tell player the instance was reset
    WorldPacket data(SMSG_INSTANCE_RESET, 4);
    data << instance->m_mapId;
    plr->GetSession()->SendPacket(&data);

    // shut down instance
    sInstanceMgr.DeleteBattlegroundInstance(instance->m_mapId, instance->m_instanceId);
    //    RedSystemMessage(m_session, "Resetting single non-persistent instances is not available yet.");
    sGMLog.writefromsession(m_session, "used reset instance command on %s, instance %u,", plr->GetName(), instanceId);
    return true;
}

bool ChatHandler::HandleShutdownInstanceCommand(const char* args, WorldSession* m_session)
{
    uint32 instanceId = (args ? atoi(args) : 0);
    if (instanceId == 0)
        return false;

    Instance* instance = sInstanceMgr.GetInstanceByIds(NUM_MAPS, instanceId);
    if (instance == NULL)
    {
        RedSystemMessage(m_session, "There's no instance with id %u.", instanceId);
        return true;
    }

    if (instance->m_mapMgr == NULL)
    {
        RedSystemMessage(m_session, "Instance with id %u already shut down.", instanceId);
        return true;
    }

    SystemMessage(m_session, "Attempting to shutdown instance with id %u...", instanceId);

    sInstanceMgr.SafeDeleteInstance(instance->m_mapMgr);

    instance = NULL;

    SystemMessage(m_session, "...done");

    sGMLog.writefromsession(m_session, "used shutdown instance command on instance %u,", instanceId);

    return true;
}

//bool ChatHandler::HandleDeleteInstanceCommand(const char* args, WorldSession* m_session)
//{
//    RedSystemMessage(m_session, "Command not implemented yet.");
//    return true;
//    //sGMLog.writefromsession(m_session, "used delete instance command on instance %u,", 0);
//}

bool ChatHandler::HandleGetInstanceInfoCommand(const char* args, WorldSession* m_session)
{
    Player* plr = m_session->GetPlayer();
    if (plr == NULL)
        return false;

    bool userInput = true;
    uint32 instanceId = (args ? atoi(args) : 0);
    if (instanceId == 0)
    {
        userInput = false;
        instanceId = plr->GetInstanceID();
        if (instanceId == 0)
            return false;
    }

    Instance* instance = sInstanceMgr.GetInstanceByIds(NUM_MAPS, instanceId);
    if (instance == NULL)
    {
        if (userInput)
        {
            RedSystemMessage(m_session, "Instance with id %u not found.", instanceId);
            return true;
        }
        return false;
    }

    std::stringstream ss;
    ss << "Instance ID: " << MSG_COLOR_CYAN << instance->m_instanceId << "|r (" << MSG_COLOR_CYAN;
    if (instance->m_mapInfo == NULL)
        ss << instance->m_mapId;
    else
        ss << instance->m_mapInfo->name;
    ss << "|r)\n";
    ss << "Persistent: " << MSG_COLOR_CYAN << (instance->m_persistent ? "Yes" : "No") << "|r\n";
    if (instance->m_mapInfo != NULL)
    {
        ss << "Type: " << MSG_COLOR_CYAN << GetMapTypeString(static_cast<uint8>(instance->m_mapInfo->type)) << "|r";

        if (instance->m_mapInfo->type == INSTANCE_MULTIMODE)
        {
            ss << " (" << MSG_COLOR_CYAN << GetDifficultyString(static_cast<uint8>(instance->m_difficulty)) << "|r)";
        }

        if (instance->m_mapInfo->type == INSTANCE_RAID)
        {
            ss << " (" << MSG_COLOR_CYAN << GetRaidDifficultyString(static_cast<uint8>(instance->m_difficulty)) << "|r)";
        }

        ss << "\n";
    }
    ss << "Created: " << MSG_COLOR_CYAN << ConvertTimeStampToDataTime((uint32)instance->m_creation) << "|r\n";
    if (instance->m_expiration != 0)
        ss << "Expires: " << MSG_COLOR_CYAN << ConvertTimeStampToDataTime((uint32)instance->m_expiration) << "|r\n";

    if (instance->m_mapMgr == NULL)
    {
        ss << "Status: " << MSG_COLOR_LIGHTRED << "Shut Down|r\n";
    }
    else if (!instance->m_mapMgr->HasPlayers())
    {
        ss << "Status: " << MSG_COLOR_LIGHTRED << "Idle|r";
        if (instance->m_mapMgr->InactiveMoveTime && instance->m_mapMgr->GetMapInfo()->type != INSTANCE_NULL)
            ss << " (" << MSG_COLOR_CYAN << "Shutdown in " << MSG_COLOR_LIGHTRED << (((long)instance->m_mapMgr->InactiveMoveTime - UNIXTIME) / 60) << MSG_COLOR_CYAN << " minutes|r)";
        ss << "\n";
    }
    else
    {
        ss << "Status: " << MSG_COLOR_GREEN << "In use|r (" << MSG_COLOR_GREEN << (uint32)instance->m_mapMgr->GetPlayerCount() << MSG_COLOR_CYAN << " players inside|r)\n";

    }
    SendMultilineMessage(m_session, ss.str().c_str());

    return true;
}

bool ChatHandler::HandleCreateInstanceCommand(const char* args, WorldSession* m_session)
{
    Player* plr = getSelectedChar(m_session, true);
    float x, y, z;
    uint32 mapid;
    if (sscanf(args, "%u %f %f %f", (unsigned int*)&mapid, &x, &y, &z) != 4)
        return false;

    if (!plr)
    {
        plr = m_session->GetPlayer();
        SystemMessage(m_session, "Auto-targeting self.");
    }
    if (!plr) return false;

    /* Create Map Manager */
    MapMgr* mgr = sInstanceMgr.CreateInstance(INSTANCE_NONRAID, mapid);
    if (mgr == NULL)
    {
        sLog.Error("CreateInstanceGMCommand", "CreateInstance() call failed for map %u", mapid);
        return false;      // Shouldn't happen
    }
    Log.Notice("CreateInstanceGMCommand", "GM created instance for map %u", mapid);

    LocationVector vec(x, y, z);
    m_session->GetPlayer()->SafeTeleport(mgr, vec);
    return true;

}

bool ChatHandler::HandleExitInstanceCommand(const char* args, WorldSession* m_session)
{
    BlueSystemMessage(m_session, "Attempting to exit from instance...");
    bool result = m_session->GetPlayer()->ExitInstance();
    if (!result)
    {
        RedSystemMessage(m_session, "Entry points not found.");
        return true;
    }
    else
    {
        GreenSystemMessage(m_session, "Removal successful.");
        return true;
    }
}

bool ChatHandler::HandleShowInstancesCommand(const char* args, WorldSession* m_session)
{
    Player* plr = getSelectedChar(m_session, true);
    if (!plr)
        return true;

    uint32 count = 0;
    std::stringstream ss;
    ss << "Show persistent instances of " << MSG_COLOR_CYAN << plr->GetName() << "|r\n";
    plr->getPlayerInfo()->savedInstanceIdsLock.Acquire();
    for (uint32 difficulty = 0; difficulty < NUM_INSTANCE_MODES; difficulty++)
    {
        for (PlayerInstanceMap::iterator itr = plr->getPlayerInfo()->savedInstanceIds[difficulty].begin(); itr != plr->getPlayerInfo()->savedInstanceIds[difficulty].end(); ++itr)
        {
            count++;
            ss << " - " << MSG_COLOR_CYAN << (*itr).second << "|r";
            MapInfo* mapInfo = WorldMapInfoStorage.LookupEntry((*itr).first);
            if (mapInfo != NULL)
                ss << " (" << MSG_COLOR_CYAN << mapInfo->name << "|r)";
            Instance* pInstance = sInstanceMgr.GetInstanceByIds((*itr).first, (*itr).second);
            if (pInstance == NULL)
                ss << " - " << MSG_COLOR_RED << "Expired!|r";
            else
            {
                ss << " [" << GetMapTypeString(static_cast<uint8>(pInstance->m_mapInfo->type)) << "]";
                if (pInstance->m_mapInfo->type == INSTANCE_MULTIMODE)
                {
                    ss << " [" << GetDifficultyString(static_cast<uint8>(pInstance->m_difficulty)) << "]";
                }
                ss << " - ";
                if (pInstance->m_mapMgr == NULL)
                    ss << MSG_COLOR_LIGHTRED << "Shut Down|r";
                else
                {
                    if (!pInstance->m_mapMgr->HasPlayers())
                        ss << MSG_COLOR_LIGHTRED << "Idle|r";
                    else
                        ss << MSG_COLOR_GREEN << "In use|r";
                }
            }
            ss << "\n";
        }
    }
    plr->getPlayerInfo()->savedInstanceIdsLock.Release();

    if (count == 0)
        ss << "Player is not assigned to any persistent instances.\n";
    else
        ss << "Player is assigned to " << MSG_COLOR_CYAN << count << "|r persistent instances.\n";

    SendMultilineMessage(m_session, ss.str().c_str());
    sGMLog.writefromsession(m_session, "used show instances command on %s,", plr->GetName());
    return true;
}
<|endoftext|>


<commit_before>#include <world/world.hpp>
#include <limits>
#include <cstring>

namespace MCPP {

	Vector<Byte> ColumnContainer::ToChunkData (const ColumnID & id) const {

		//	First we need to convert the sane
		//	in memory format to the insane
		//	Mojang format

		Word size=(
			//	One byte per block
			//	for block type
			(16*16*16*16)+
			//	Half a byte per block
			//	for metadata
			((16*16*16*16)/2)+
			//	Half a byte per block
			//	for light
			((16*16*16*16)/2)+
			//	One byte per column for
			//	biome information
			(16*16)
		);

		//	Do we have to send "add"?
		bool add=false;
		for (Word i=0;i<(16*16*16*16);++i) {

			if (Blocks[i].GetType()>std::numeric_limits<Byte>::max()) {

				add=true;

				break;

			}

		}

		//	If we have to send add it's
		//	one half byte per block
		if (add) size+=(16*16*16*16)/2;

		//	If we have to send skylight it's
		//	one half byte per block
		bool skylight=HasSkylight(id.Dimension);
		if (skylight) size+=(16*16*16*16)/2;

		//	Allocate enough space to hold
		//	the column in Mojang format
		Vector<Byte> column(size);
		column.SetCount(size);

		Word offset=0;

		//	Loop for block types
		for (const auto & b : Blocks) column[offset++]=static_cast<Byte>(b.GetType());

		//	Loop for block metadata
		bool even=true;
		for (const auto & b : Blocks) {

			if (even) {

				column[offset]=b.GetMetadata()<<4;
				even=false;

			} else {

				column[offset++]|=b.GetMetadata();
				even=true;

			}

		}

		//	Loop for light
		even=true;
		for (const auto & b : Blocks) {

			if (even) {

				column[offset]=b.GetLight()<<4;
				even=false;

			} else {

				column[offset++]|=b.GetLight();
				even=true;

			}

		}

		//	Loop for skylight if applicable
		if (skylight) {

			even=true;

			for (const auto & b : Blocks) {

				if (even) {

					column[offset]=b.GetSkylight()<<4;
					even=false;

				} else {

					column[offset++]|=b.GetSkylight();
					even=true;

				}

			}

		}

		//	Loop for "add" if applicable
		if (add) {

			even=true;

			for (const auto & b : Blocks) {

				auto type=b.GetType();
				Byte val=(type>std::numeric_limits<Byte>::max()) ? static_cast<Byte>(type>>8) : 0;

				if (even) {

					column[offset]=val<<4;
					even=false;

				} else {

					column[offset++]|=val;
					even=true;

				}

			}

		}

		//	Copy biomes
		memcpy(
			&column[offset],
			Biomes,
			sizeof(Biomes)
		);

		//	Prepare the final buffer
		size=(
			//	X-coordinate of this chunk
			sizeof(Int32)+
			//	Z-coordinate of this chunk
			sizeof(Int32)+
			//	Group-up continuous
			sizeof(bool)+
			//	Primary bit mask
			sizeof(UInt16)+
			//	"Add" bit mask
			sizeof(UInt16)+
			//	Size of compressed data
			sizeof(Int32)+
			//	Largest possible size for
			//	compressed column data
			DeflateBound(
				column.Count()
			)
		);

		//	Allocate sufficient memory
		Vector<Byte> buffer(size);

		PacketHelper<Int32>::ToBytes(
			id.X,
			buffer
		);
		PacketHelper<Int32>::ToBytes(
			id.Z,
			buffer
		);
		PacketHelper<bool>::ToBytes(
			true,
			buffer
		);
		PacketHelper<UInt16>::ToBytes(
			std::numeric_limits<UInt16>::max(),
			buffer
		);
		PacketHelper<UInt16>::ToBytes(
			std::numeric_limits<UInt16>::max(),
			buffer
		);

		//	Push end point of buffer past
		//	where the size will go
		//	(as we do not yet know the size)
		Word size_loc=buffer.Count();
		buffer.SetCount(size_loc+sizeof(Int32));

		//	Compress
		Deflate(
			column.begin(),
			column.end(),
			&buffer
		);

		//	Get compressed size
		SafeWord compressed_size(buffer.Count()-size_loc-sizeof(Int32));

		Word final_size=buffer.Count();

		//	Insert compressed size
		buffer.SetCount(size_loc);
		PacketHelper<Int32>::ToBytes(
			Int32(compressed_size),
			buffer
		);

		buffer.SetCount(final_size);

		return buffer;

	}

}
<commit_msg>ColumnContainer Bugfix<commit_after>#include <world/world.hpp>
#include <limits>
#include <cstring>

namespace MCPP {

	Vector<Byte> ColumnContainer::ToChunkData (const ColumnID & id) const {

		//	First we need to convert the sane
		//	in memory format to the insane
		//	Mojang format

		Word size=(
			//	One byte per block
			//	for block type
			(16*16*16*16)+
			//	Half a byte per block
			//	for metadata
			((16*16*16*16)/2)+
			//	Half a byte per block
			//	for light
			((16*16*16*16)/2)+
			//	One byte per column for
			//	biome information
			(16*16)
		);

		//	Do we have to send "add"?
		bool add=false;
		for (Word i=0;i<(16*16*16*16);++i) {

			if (Blocks[i].GetType()>std::numeric_limits<Byte>::max()) {

				add=true;

				break;

			}

		}

		//	If we have to send add it's
		//	one half byte per block
		if (add) size+=(16*16*16*16)/2;

		//	If we have to send skylight it's
		//	one half byte per block
		bool skylight=HasSkylight(id.Dimension);
		if (skylight) size+=(16*16*16*16)/2;

		//	Allocate enough space to hold
		//	the column in Mojang format
		Vector<Byte> column(size);
		column.SetCount(size);

		Word offset=0;

		//	Loop for block types
		for (const auto & b : Blocks) column[offset++]=static_cast<Byte>(b.GetType());

		//	Loop for block metadata
		bool even=true;
		for (const auto & b : Blocks) {

			if (even) {

				column[offset]=b.GetMetadata()<<4;
				even=false;

			} else {

				column[offset++]|=b.GetMetadata();
				even=true;

			}

		}

		//	Loop for light
		even=true;
		for (const auto & b : Blocks) {

			if (even) {

				column[offset]=b.GetLight()<<4;
				even=false;

			} else {

				column[offset++]|=b.GetLight();
				even=true;

			}

		}

		//	Loop for skylight if applicable
		if (skylight) {

			even=true;

			for (const auto & b : Blocks) {

				if (even) {

					column[offset]=b.GetSkylight()<<4;
					even=false;

				} else {

					column[offset++]|=b.GetSkylight();
					even=true;

				}

			}

		}

		//	Loop for "add" if applicable
		if (add) {

			even=true;

			for (const auto & b : Blocks) {

				auto type=b.GetType();
				Byte val=(type>std::numeric_limits<Byte>::max()) ? static_cast<Byte>(type>>8) : 0;

				if (even) {

					column[offset]=val<<4;
					even=false;

				} else {

					column[offset++]|=val;
					even=true;

				}

			}

		}

		//	Copy biomes
		memcpy(
			&column[offset],
			Biomes,
			sizeof(Biomes)
		);

		//	Prepare the final buffer
		size=(
			//	Packet type
			sizeof(Byte)+
			//	X-coordinate of this chunk
			sizeof(Int32)+
			//	Z-coordinate of this chunk
			sizeof(Int32)+
			//	Group-up continuous
			sizeof(bool)+
			//	Primary bit mask
			sizeof(UInt16)+
			//	"Add" bit mask
			sizeof(UInt16)+
			//	Size of compressed data
			sizeof(Int32)+
			//	Largest possible size for
			//	compressed column data
			DeflateBound(
				column.Count()
			)
		);

		//	Allocate sufficient memory
		Vector<Byte> buffer(size);

		buffer.Add(0x33);

		PacketHelper<Int32>::ToBytes(
			id.X,
			buffer
		);
		PacketHelper<Int32>::ToBytes(
			id.Z,
			buffer
		);
		PacketHelper<bool>::ToBytes(
			true,
			buffer
		);
		PacketHelper<UInt16>::ToBytes(
			std::numeric_limits<UInt16>::max(),
			buffer
		);
		PacketHelper<UInt16>::ToBytes(
			std::numeric_limits<UInt16>::max(),
			buffer
		);

		//	Push end point of buffer past
		//	where the size will go
		//	(as we do not yet know the size)
		Word size_loc=buffer.Count();
		buffer.SetCount(size_loc+sizeof(Int32));

		//	Compress
		Deflate(
			column.begin(),
			column.end(),
			&buffer
		);

		//	Get compressed size
		SafeWord compressed_size(buffer.Count()-size_loc-sizeof(Int32));

		Word final_size=buffer.Count();

		//	Insert compressed size
		buffer.SetCount(size_loc);
		PacketHelper<Int32>::ToBytes(
			Int32(compressed_size),
			buffer
		);

		buffer.SetCount(final_size);

		return buffer;

	}

}
<|endoftext|>


<commit_before>#include <x0/io/fileinfo_service.hpp>
#include <x0/strutils.hpp>

#include <boost/tokenizer.hpp>

namespace x0 {

fileinfo_service::fileinfo_service(struct ::ev_loop *loop) :
	loop_(loop),
#if defined(HAVE_SYS_INOTIFY_H)
	handle_(),
	inotify_(loop_),
	wd_(),
#endif
	cache_(),
	etag_consider_mtime_(true),
	etag_consider_size_(true),
	etag_consider_inode_(false),
	mimetypes_(),
	default_mimetype_("text/plain")
{
#if defined(HAVE_SYS_INOTIFY_H)
	handle_ = inotify_init();
	if (handle_ != -1)
	{
		fcntl(handle_, F_SETFL, O_NONBLOCK | FD_CLOEXEC);

		inotify_.set<fileinfo_service, &fileinfo_service::on_inotify>(this);
		inotify_.start(handle_, ev::READ);
	}
#endif
}

fileinfo_service::~fileinfo_service()
{
#if defined(HAVE_SYS_INOTIFY_H)
	if (handle_ != -1)
	{
		::close(handle_);
	}
#endif
}

void fileinfo_service::on_inotify(ev::io& w, int revents)
{
	DEBUG("fileinfo_service::on_inotify()");

	char buf[4096];
	ssize_t rv = ::read(handle_, &buf, sizeof(buf));
	if (rv > 0)
	{
		inotify_event *i = (inotify_event *)buf;
		inotify_event *e = i + rv;

		while (i < e && i->wd != 0)
		{
			auto wi = wd_.find(i->wd);
			if (wi != wd_.end())
			{
				auto k = cache_.find(wi->second);
				// on_invalidate(k->first, k->second);
				cache_.erase(k);
				wd_.erase(wi);
			}
			i += sizeof(*i) + i->len;
		}
	}
}

void fileinfo_service::load_mimetypes(const std::string& filename)
{
	typedef boost::tokenizer<boost::char_separator<char> > tokenizer;

	std::string input(x0::read_file(filename));
	tokenizer lines(input, boost::char_separator<char>("\n"));

	mimetypes_.clear();

	for (tokenizer::iterator i = lines.begin(), e = lines.end(); i != e; ++i)
	{
		std::string line(x0::trim(*i));
		tokenizer columns(line, boost::char_separator<char>(" \t"));

		tokenizer::iterator ci = columns.begin(), ce = columns.end();
		std::string mime = ci != ce ? *ci++ : std::string();

		if (!mime.empty() && mime[0] != '#')
		{
			for (; ci != ce; ++ci)
			{
				mimetypes_[*ci] = mime;
			}
		}
	}
}

} // namespace x0
<commit_msg>core: code cleanup<commit_after>#include <x0/io/fileinfo_service.hpp>
#include <x0/strutils.hpp>

#include <boost/tokenizer.hpp>

namespace x0 {

fileinfo_service::fileinfo_service(struct ::ev_loop *loop) :
	loop_(loop),
#if defined(HAVE_SYS_INOTIFY_H)
	handle_(),
	inotify_(loop_),
	wd_(),
#endif
	cache_(),
	etag_consider_mtime_(true),
	etag_consider_size_(true),
	etag_consider_inode_(false),
	mimetypes_(),
	default_mimetype_("text/plain")
{
#if defined(HAVE_SYS_INOTIFY_H)
	handle_ = inotify_init();
	if (handle_ != -1)
	{
		fcntl(handle_, F_SETFL, O_NONBLOCK | FD_CLOEXEC);

		inotify_.set<fileinfo_service, &fileinfo_service::on_inotify>(this);
		inotify_.start(handle_, ev::READ);
	}
#endif
}

fileinfo_service::~fileinfo_service()
{
#if defined(HAVE_SYS_INOTIFY_H)
	if (handle_ != -1)
	{
		::close(handle_);
	}
#endif
}

void fileinfo_service::on_inotify(ev::io& w, int revents)
{
	//DEBUG("fileinfo_service::on_inotify()");

	char buf[4096];
	ssize_t rv = ::read(handle_, &buf, sizeof(buf));
	if (rv > 0)
	{
		inotify_event *i = (inotify_event *)buf;
		inotify_event *e = i + rv;

		while (i < e && i->wd != 0)
		{
			auto wi = wd_.find(i->wd);
			if (wi != wd_.end())
			{
				auto k = cache_.find(wi->second);
				// on_invalidate(k->first, k->second);
				cache_.erase(k);
				wd_.erase(wi);
			}
			i += sizeof(*i) + i->len;
		}
	}
}

void fileinfo_service::load_mimetypes(const std::string& filename)
{
	typedef boost::tokenizer<boost::char_separator<char> > tokenizer;

	std::string input(x0::read_file(filename));
	tokenizer lines(input, boost::char_separator<char>("\n"));

	mimetypes_.clear();

	for (tokenizer::iterator i = lines.begin(), e = lines.end(); i != e; ++i)
	{
		std::string line(x0::trim(*i));
		tokenizer columns(line, boost::char_separator<char>(" \t"));

		tokenizer::iterator ci = columns.begin(), ce = columns.end();
		std::string mime = ci != ce ? *ci++ : std::string();

		if (!mime.empty() && mime[0] != '#')
		{
			for (; ci != ce; ++ci)
			{
				mimetypes_[*ci] = mime;
			}
		}
	}
}

} // namespace x0
<|endoftext|>


<commit_before>#include <vector>
#include <fstream>
#include <string>
#include <sys/stat.h>
#include <Windows.h>

char appplication_folder[1024];
void set_application_folder( char const* application_path )
{
    int length = strrchr( application_path, '\\' ) - application_path + 1;
    memcpy( appplication_folder, application_path, length );
    appplication_folder[length] = 0;
}

char const* get_application_folder()
{
    return appplication_folder;
}

BOOL run( char* command_line )
{
    STARTUPINFO si = {0};
    PROCESS_INFORMATION pi = {0};
    BOOL result = CreateProcess( 0, command_line, 0, 0, FALSE, 0, NULL, NULL, &si, &pi );

    if( !result )
    {
        printf( "ERROR: Could not run '%s'!\n", command_line );
        return -1;
    }
    else
    {
        WaitForSingleObject( pi.hProcess, INFINITE );
        CloseHandle(pi.hThread);
        CloseHandle(pi.hProcess);
        return 0;
    }
}

struct compiler
{
    compiler( char const* compiler_path )
    :   path( compiler_path )
    {
        int ext_begin = strrchr(compiler_path, '\\') - compiler_path + 1;
        int ext_end = strrchr(compiler_path, '.') - compiler_path - ext_begin;
        extension = path.substr(ext_begin, ext_end);
    }

    void compile( char const* asset_path, char const* output_folder )
    {
        char command_line[1024];
        sprintf( command_line, "%s \"%s\" \"%s\"", path.c_str(), asset_path, output_folder );
        run( command_line );
    }

    std::string extension;
    std::string path;
};

typedef std::vector< std::string > file_list;
typedef std::vector< compiler* > compiler_list;

void list_files( char const* folder, char const* extension, file_list& files )
{
    char search_key[1024];
    sprintf( search_key, "%s\\*", folder, extension );

    WIN32_FIND_DATA find_data;
    HANDLE find_handle = FindFirstFile( search_key, &find_data );

    if( find_handle != INVALID_HANDLE_VALUE )
    {
        do
        {
            if( strstr( find_data.cFileName, extension ) && strlen( strstr( find_data.cFileName, extension ) ) == strlen( extension ) )
            {
                char file_path[1024];
                sprintf( file_path, "%s\\%s", folder, find_data.cFileName );
                files.push_back( file_path );
            }
            else if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
            {
                if( find_data.cFileName[0] != '.' )
                {
                    char subfolder[2048];
                    sprintf( subfolder, "%s\\%s", folder, find_data.cFileName );

                    list_files( subfolder, extension, files );
                }
            }
        }while( FindNextFile( find_handle, &find_data ) );
    }
}

void list_folders( char const* path, file_list& folders )
{
    char search_key[1024];
    sprintf( search_key, "%s\\*", path );

    WIN32_FIND_DATA find_data;
    HANDLE find_handle = FindFirstFile( search_key, &find_data );

    if( find_handle != INVALID_HANDLE_VALUE )
    {
        do
        {
            if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
            {
                if( find_data.cFileName[0] != '.' )
                {
                    char subfolder[2048];
                    sprintf( subfolder, "%s\\%s", path, find_data.cFileName );

                    folders.push_back( subfolder );
                }
            }
        }while( FindNextFile( find_handle, &find_data ) );
    }
}

compiler_list get_compilers( char const* folder )
{
    file_list paths;
    list_files( folder, "exe", paths );
    compiler_list compilers;
    for( file_list::iterator iter = paths.begin(); iter != paths.end(); ++iter )
    {
        char const* path = (*iter).c_str();
        compilers.push_back( new compiler( path ) );
    }
    return compilers;
}

void compile_folder( compiler* c, char const* asset_folder, char const* mod_folder )
{
    file_list files;
    list_files( asset_folder, c->extension.c_str(), files );
    for( file_list::iterator file_iter = files.begin(); file_iter != files.end(); ++file_iter )
    {
        c->compile( file_iter->c_str(), mod_folder );
    }
}

void get_asset_folders( compiler& c, file_list& asset_folders )
{
    std::string asset_list_path = c.path + std::string( ".txt" );
    std::ifstream in = std::ifstream( asset_list_path.c_str() );

    char path[1024];
    while( !in.eof() )
    {
        in.getline( path, sizeof( path ) );
        asset_folders.push_back( path );
    }
}

int main( int argument_count, char** arguments )
{
    char module_name[1024];
    GetModuleFileName( 0, module_name, 1024 );
    set_application_folder( module_name );

    file_list mod_folders;
    char mods_folder[1024];

    sprintf( mods_folder, "%s..\\..\\mods", get_application_folder() );
    list_folders( mods_folder, mod_folders );

    sprintf( mods_folder, "%s..\\..\\dont_starve\\mods", get_application_folder() );
    list_folders( mods_folder, mod_folders );

    char compilers_folder[1024] ;
    sprintf( compilers_folder, "%scompilers", get_application_folder() );

    compiler_list compilers = get_compilers( compilers_folder );
    for( compiler_list::iterator iter = compilers.begin(); iter != compilers.end(); ++iter )
    {
        compiler* c = *iter;
        file_list asset_folders;
        get_asset_folders( *c, asset_folders );

        for( file_list::iterator mod_folder_iter = mod_folders.begin(); mod_folder_iter != mod_folders.end(); ++mod_folder_iter )
        {
            for( file_list::iterator asset_folder_iter = asset_folders.begin(); asset_folder_iter != asset_folders.end(); ++asset_folder_iter )
            {
                char asset_folder[1024];
                sprintf( asset_folder, "%s/%s", mod_folder_iter->c_str(), asset_folder_iter->c_str() );
                compile_folder( c, asset_folder, mod_folder_iter->c_str() );
            }
        }
   }

    return 0;
}<commit_msg>Removed some dependencies on 'Windows.h'.<commit_after>#include <vector>
#include <fstream>
#include <string>
#include <sys/stat.h>
#include <Windows.h>

char appplication_folder[1024];
void set_application_folder( char const* application_path )
{
    int length = strrchr( application_path, '\\' ) - application_path + 1;
    memcpy( appplication_folder, application_path, length );
    appplication_folder[length] = 0;
}

char const* get_application_folder()
{
    return appplication_folder;
}

bool run( char* command_line )
{
	return system( command_line ) == 0;
}

struct compiler
{
    compiler( char const* compiler_path )
    :   path( compiler_path )
    {
        int ext_begin = strrchr(compiler_path, '\\') - compiler_path + 1;
        int ext_end = strrchr(compiler_path, '.') - compiler_path - ext_begin;
        extension = path.substr(ext_begin, ext_end);
    }

    void compile( char const* asset_path, char const* output_folder )
    {
        char command_line[1024];
        sprintf( command_line, "%s \"%s\" \"%s\"", path.c_str(), asset_path, output_folder );
        run( command_line );
    }

    std::string extension;
    std::string path;
};

typedef std::vector< std::string > file_list;
typedef std::vector< compiler* > compiler_list;

void list_files( char const* folder, char const* extension, file_list& files )
{
    char search_key[1024];
    sprintf( search_key, "%s\\*", folder, extension );

    WIN32_FIND_DATA find_data;
    HANDLE find_handle = FindFirstFile( search_key, &find_data );

    if( find_handle != INVALID_HANDLE_VALUE )
    {
        do
        {
            if( strstr( find_data.cFileName, extension ) && strlen( strstr( find_data.cFileName, extension ) ) == strlen( extension ) )
            {
                char file_path[1024];
                sprintf( file_path, "%s\\%s", folder, find_data.cFileName );
                files.push_back( file_path );
            }
            else if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
            {
                if( find_data.cFileName[0] != '.' )
                {
                    char subfolder[2048];
                    sprintf( subfolder, "%s\\%s", folder, find_data.cFileName );

                    list_files( subfolder, extension, files );
                }
            }
        }while( FindNextFile( find_handle, &find_data ) );
    }
}

void list_folders( char const* path, file_list& folders )
{
    char search_key[1024];
    sprintf( search_key, "%s\\*", path );

    WIN32_FIND_DATA find_data;
    HANDLE find_handle = FindFirstFile( search_key, &find_data );

    if( find_handle != INVALID_HANDLE_VALUE )
    {
        do
        {
            if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
            {
                if( find_data.cFileName[0] != '.' )
                {
                    char subfolder[2048];
                    sprintf( subfolder, "%s\\%s", path, find_data.cFileName );

                    folders.push_back( subfolder );
                }
            }
        }while( FindNextFile( find_handle, &find_data ) );
    }
}

compiler_list get_compilers( char const* folder )
{
    file_list paths;
    list_files( folder, "exe", paths );
    compiler_list compilers;
    for( file_list::iterator iter = paths.begin(); iter != paths.end(); ++iter )
    {
        char const* path = (*iter).c_str();
        compilers.push_back( new compiler( path ) );
    }
    return compilers;
}

void compile_folder( compiler* c, char const* asset_folder, char const* mod_folder )
{
    file_list files;
    list_files( asset_folder, c->extension.c_str(), files );
    for( file_list::iterator file_iter = files.begin(); file_iter != files.end(); ++file_iter )
    {
        c->compile( file_iter->c_str(), mod_folder );
    }
}

void get_asset_folders( compiler& c, file_list& asset_folders )
{
    std::string asset_list_path = c.path + std::string( ".txt" );
    std::ifstream in = std::ifstream( asset_list_path.c_str() );

    char path[1024];
    while( !in.eof() )
    {
        in.getline( path, sizeof( path ) );
        asset_folders.push_back( path );
    }
}

int main( int argument_count, char** arguments )
{
    char module_name[1024];
    GetModuleFileName( 0, module_name, 1024 );
    set_application_folder( module_name );

    file_list mod_folders;
    char mods_folder[1024];

    sprintf( mods_folder, "%s..\\..\\mods", get_application_folder() );
    list_folders( mods_folder, mod_folders );

    sprintf( mods_folder, "%s..\\..\\dont_starve\\mods", get_application_folder() );
    list_folders( mods_folder, mod_folders );

    char compilers_folder[1024] ;
    sprintf( compilers_folder, "%scompilers", get_application_folder() );

    compiler_list compilers = get_compilers( compilers_folder );
    for( compiler_list::iterator iter = compilers.begin(); iter != compilers.end(); ++iter )
    {
        compiler* c = *iter;
        file_list asset_folders;
        get_asset_folders( *c, asset_folders );

        for( file_list::iterator mod_folder_iter = mod_folders.begin(); mod_folder_iter != mod_folders.end(); ++mod_folder_iter )
        {
            for( file_list::iterator asset_folder_iter = asset_folders.begin(); asset_folder_iter != asset_folders.end(); ++asset_folder_iter )
            {
                char asset_folder[1024];
                sprintf( asset_folder, "%s/%s", mod_folder_iter->c_str(), asset_folder_iter->c_str() );
                compile_folder( c, asset_folder, mod_folder_iter->c_str() );
            }
        }
   }

    return 0;
}<|endoftext|>