<commit_before>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Nathan Osman
 *
 * 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 <QApplication>
#include <QMessageBox>

#include "application/application.h"
#include "application/splashdialog.h"
#include "settings/settings.h"
#include "util/platform.h"
#include "config.h"

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    app.setQuitOnLastWindowClosed(false);

    // Set up application properties
    app.setApplicationDisplayName(PROJECT_NAME);
    app.setApplicationName(PROJECT_NAME);
    app.setApplicationVersion(PROJECT_VERSION);
    app.setOrganizationDomain(PROJECT_DOMAIN);
    app.setOrganizationName(PROJECT_AUTHOR);

    // Check to see if the splash screen has been displayed yet
    bool appSplash = Settings::instance()->get(Settings::Key::ApplicationSplash).toBool();

    // If not, display it and remember that the user has seen it
    if(!appSplash) {
        SplashDialog().exec();
        Settings::instance()->set(Settings::Key::ApplicationSplash, true);
    }

#ifdef APPINDICATOR_FOUND
    // If the splash had not been seen and the user is running Gnome,
    // warn them that they need a special extension installed
    if(!appSplash && Platform::currentDesktopEnvironment() ==
            Platform::DesktopEnvironment::Gnome) {
        QMessageBox::about(nullptr, QObject::tr("Warning"), QObject::tr(
                "Some versions of Gnome do not support AppIndicators. This prevents "
                "NitroShare from displaying an indicator in the notification area. "
                "Please ensure you have this extension installed before continuing:"
                "

%1"
        ).arg("https://extensions.gnome.org/extension/615/appindicator-support/"));
    }
#endif

    // Create the tray icon that runs the application
    Application nitroshare;
    Q_UNUSED(nitroshare);

    return app.exec();
}
<commit_msg>Added ability to load translations (#12).<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Nathan Osman
 *
 * 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 <QApplication>
#include <QLibraryInfo>
#include <QLocale>
#include <QMessageBox>
#include <QTranslator>

#include "application/application.h"
#include "application/splashdialog.h"
#include "settings/settings.h"
#include "util/platform.h"
#include "config.h"

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    app.setQuitOnLastWindowClosed(false);

    // Set up application properties
    app.setApplicationDisplayName(PROJECT_NAME);
    app.setApplicationName(PROJECT_NAME);
    app.setApplicationVersion(PROJECT_VERSION);
    app.setOrganizationDomain(PROJECT_DOMAIN);
    app.setOrganizationName(PROJECT_AUTHOR);

    // Set up translations for Qt
    QTranslator qtTranslator;
    qtTranslator.load(QString("qt_%1").arg(QLocale::system().name()),
            QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    app.installTranslator(&qtTranslator);

    // Set up translations for NitroShare
    QTranslator nsTranslator;
    nsTranslator.load(QString("nitroshare_%1").arg(QLocale::system().name()), ":/qm");
    app.installTranslator(&nsTranslator);

    // Check to see if the splash screen has been displayed yet
    bool appSplash = Settings::instance()->get(Settings::Key::ApplicationSplash).toBool();

    // If not, display it and remember that the user has seen it
    if(!appSplash) {
        SplashDialog().exec();
        Settings::instance()->set(Settings::Key::ApplicationSplash, true);
    }

#ifdef APPINDICATOR_FOUND
    // If the splash had not been seen and the user is running Gnome,
    // warn them that they need a special extension installed
    if(!appSplash && Platform::currentDesktopEnvironment() ==
            Platform::DesktopEnvironment::Gnome) {
        QMessageBox::about(nullptr, QObject::tr("Warning"), QObject::tr(
                "Some versions of Gnome do not support AppIndicators. This prevents "
                "NitroShare from displaying an indicator in the notification area. "
                "Please ensure you have this extension installed before continuing:"
                "

%1"
        ).arg("https://extensions.gnome.org/extension/615/appindicator-support/"));
    }
#endif

    // Create the tray icon that runs the application
    Application nitroshare;
    Q_UNUSED(nitroshare);

    return app.exec();
}
<|endoftext|>


<commit_before>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t, time; // t for global, time for local
	init_time(t);
	Feat F;

	// Read parameters file //
	F.readInputFile(argv[1]);
	printFile(argv[1]);

	// Read galaxies
	Gals G;
    if(F.Ascii){
        G=read_galaxies_ascii(F);}
    else{
        G = read_galaxies(F);
    }
	F.Ngal = G.size();
	printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str());

	// Read fiber center positions and compute related things
	PP pp;
	pp.read_fiber_positions(F);
	F.Nfiber = pp.fp.size()/2;
	F.Npetal = max(pp.spectrom)+1; // spectrometer has to be identified from 0 to F.Npetal-1
	F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
	pp.get_neighbors(F); pp.compute_fibsofsp(F);//get neighbors of each fiber;
                                                //for each spectrometer, get list of fibers

	// Read plates in order they are to be observed

	Plates P = read_plate_centers(F);
	F.Nplate = P.size();
	printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

	// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
	F.cb = create_cb(); // cb=central body
	F.fh = create_fh(); // fh=fiber holder

	//// Collect available galaxies <-> tilefibers --------------------
	// HTM Tree of galaxies
	const double MinTreeSize = 0.01;
	init_time_at(time,"# Start building HTM tree",t);
	htmTree<struct galaxy> T(G,MinTreeSize);
	print_time(time,"# ... took :");//T.stats();

	// For plates/fibers, collect available galaxies; done in parallel  P[plate j].av_gal[k]=[g1,g2,..]
	collect_galaxies_for_all(G,T,P,pp,F);

	// For each galaxy, computes available tilefibers  G[i].av_tfs = [(j1,k1),(j2,k2),..]
	collect_available_tilefibers(G,P,F);

	//results_on_inputs("doc/figs/",G,P,F,true);

	//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
	Assignment A(G,F);
	print_time(t,"# Start assignment at : ");

	// Make a plan ----------------------------------------------------
	//new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars
                                   // assumes maximum number of observations needed for QSOs, LRGs
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
    //simple_assign(G,P,pp,F,A);

    /*
	print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
                                    // Want to have even distribution of unused fibers
                                    // so we can put in sky fibers and standard stars

	// Smooth out distribution of free fibers, and increase the number of assignments
	for (int i=0; i<1; i++) redistribute_tf(G,P,pp,F,A);// more iterations will improve performance slightly
	for (int i=0; i<1; i++) {                           // more iterations will improve performance slightly
		improve(G,P,pp,F,A);
		redistribute_tf(G,P,pp,F,A);
		redistribute_tf(G,P,pp,F,A);
	}
	for (int i=0; i<1; i++) redistribute_tf(G,P,pp,F,A);

	print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);

	// Still not updated, so all QSO targets have multiple observations etc
	// Apply and update the plan --------------------------------------
	init_time_at(time,"# Begin real time assignment",t);
	for (int jj=0; jj<F.Nplate; jj++) {
		int j = A.next_plate;
		//printf(" - Plate %d :",j);
		assign_sf_ss(j,G,P,pp,F,A); // Assign SS and SF just before an observation
		assign_unused(j,G,P,pp,F,A);
		//if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies

		//printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl();
		// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
		if (0<=j-F.Analysis) update_plan_from_one_obs(G,P,pp,F,A,F.Nplate-1); else printf("\n");
		A.next_plate++;
		// Redistribute and improve on various occasions  add more times if desired

		if ( j==2000 || j==4000) {
			redistribute_tf(G,P,pp,F,A);
			redistribute_tf(G,P,pp,F,A);
			improve(G,P,pp,F,A);
			redistribute_tf(G,P,pp,F,A);
		}
	}
	print_time(time,"# ... took :");

	// Results -------------------------------------------------------
	if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,G,P,pp,F,A); // Write output
	display_results("doc/figs/",G,P,pp,F,A,true);
	if (F.Verif) A.verif(P,G,pp,F); // Verification that the assignment is sane

	print_time(t,"# Finished !... in");
     */
	return(0);
}
<commit_msg>more debug of main.cpp<commit_after>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t, time; // t for global, time for local
	init_time(t);
	Feat F;

	// Read parameters file //
	F.readInputFile(argv[1]);
	printFile(argv[1]);

	// Read galaxies
	Gals G;
    if(F.Ascii){
        G=read_galaxies_ascii(F);}
    else{
        G = read_galaxies(F);
    }
	F.Ngal = G.size();
	printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str());

	// Read fiber center positions and compute related things
	PP pp;
	pp.read_fiber_positions(F);
	F.Nfiber = pp.fp.size()/2;
	F.Npetal = max(pp.spectrom)+1; // spectrometer has to be identified from 0 to F.Npetal-1
	F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
	pp.get_neighbors(F); pp.compute_fibsofsp(F);//get neighbors of each fiber;
                                                //for each spectrometer, get list of fibers

	// Read plates in order they are to be observed

	Plates P = read_plate_centers(F);
	F.Nplate = P.size();
	printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

	// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
	F.cb = create_cb(); // cb=central body
	F.fh = create_fh(); // fh=fiber holder

	//// Collect available galaxies <-> tilefibers --------------------
	// HTM Tree of galaxies
	const double MinTreeSize = 0.01;
	init_time_at(time,"# Start building HTM tree",t);
	htmTree<struct galaxy> T(G,MinTreeSize);
	print_time(time,"# ... took :");//T.stats();

	// For plates/fibers, collect available galaxies; done in parallel  P[plate j].av_gal[k]=[g1,g2,..]
	collect_galaxies_for_all(G,T,P,pp,F);

	// For each galaxy, computes available tilefibers  G[i].av_tfs = [(j1,k1),(j2,k2),..]
	collect_available_tilefibers(G,P,F);

	//results_on_inputs("doc/figs/",G,P,F,true);

	//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
    printf("before assignment");
	Assignment A(G,F);
	print_time(t,"# Start assignment at : ");

	// Make a plan ----------------------------------------------------
	//new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars
                                   // assumes maximum number of observations needed for QSOs, LRGs
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
    //simple_assign(G,P,pp,F,A);

    /*
	print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
                                    // Want to have even distribution of unused fibers
                                    // so we can put in sky fibers and standard stars

	// Smooth out distribution of free fibers, and increase the number of assignments
	for (int i=0; i<1; i++) redistribute_tf(G,P,pp,F,A);// more iterations will improve performance slightly
	for (int i=0; i<1; i++) {                           // more iterations will improve performance slightly
		improve(G,P,pp,F,A);
		redistribute_tf(G,P,pp,F,A);
		redistribute_tf(G,P,pp,F,A);
	}
	for (int i=0; i<1; i++) redistribute_tf(G,P,pp,F,A);

	print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);

	// Still not updated, so all QSO targets have multiple observations etc
	// Apply and update the plan --------------------------------------
	init_time_at(time,"# Begin real time assignment",t);
	for (int jj=0; jj<F.Nplate; jj++) {
		int j = A.next_plate;
		//printf(" - Plate %d :",j);
		assign_sf_ss(j,G,P,pp,F,A); // Assign SS and SF just before an observation
		assign_unused(j,G,P,pp,F,A);
		//if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies

		//printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl();
		// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
		if (0<=j-F.Analysis) update_plan_from_one_obs(G,P,pp,F,A,F.Nplate-1); else printf("\n");
		A.next_plate++;
		// Redistribute and improve on various occasions  add more times if desired

		if ( j==2000 || j==4000) {
			redistribute_tf(G,P,pp,F,A);
			redistribute_tf(G,P,pp,F,A);
			improve(G,P,pp,F,A);
			redistribute_tf(G,P,pp,F,A);
		}
	}
	print_time(time,"# ... took :");

	// Results -------------------------------------------------------
	if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,G,P,pp,F,A); // Write output
	display_results("doc/figs/",G,P,pp,F,A,true);
	if (F.Verif) A.verif(P,G,pp,F); // Verification that the assignment is sane

	print_time(t,"# Finished !... in");
     */
	return(0);
}
<|endoftext|>


<commit_before>#include "systems/partysystem.h"
#include "cmapclient.h"

using namespace Systems;
using namespace RoseCommon;

PartySystem::PartySystem(SystemManager &m) : System(m) {
    m.registerDispatcher(ePacketType::PAKCS_PARTY_REQ, &PartySystem::processPartyReq);
    m.registerDispatcher(ePacketType::PAKCS_PARTY_REPLY, &PartySystem::processPartyReply);
    m.getEntityManager().on_component_removed<Party>([this](Entity entity, Component<Party> party) {
            (void)entity;
            (void)party;
            // TODO : send a packet to everyone else in the party
            });
    // TODO : use on_component_assign for new members?
}

void PartySystem::update(EntityManager &es, double) {
    Component<Party> party;
    Component<BasicInfo> info;
    for (Entity entity : es.entities_with_components(info, party)) {
        (void)entity;
        if (!party->party_) {
            logger_->trace("Client {} has the Party component but no affiliated party. {}", info->id_, party->isRequested_);
        }
        logger_->trace("Client {} is in a party", info->id_);
        logger_->trace("Party leader is {}, party members are", party->party_->leader_);
        for (auto it : party->party_->members_)
            logger_->trace("client {}", getId(it));
    }
}

void PartySystem::addPartyMember(Entity leader, Entity newMember) {
    auto Cparty = leader.component<Party>();
    if (!Cparty)
        return;
    std::shared_ptr<PartyBase> party = Cparty->party_;
    if (!party)
        party = Cparty->party_ = std::make_shared<PartyBase>(leader, newMember);
    if (newMember.component<Party>())
        return;
    newMember.assign<Party>(party);
    // TODO : send the packets
    party->addMember(newMember);
}

void PartySystem::processPartyReq(CMapClient *client, Entity entity, const CliPartyReq &packet) {
    logger_->trace("PartySystem::processPartyReq");
    Entity other;
    if (!(other = manager_.getEntity(packet.idXorTag())) || !getClient(other)) {
        logger_->debug("Client {} requested a party with the non existing char {}", getId(entity), packet.idXorTag());
        client->Send(*makePacket<ePacketType::PAKWC_PARTY_REPLY>(SrvPartyReply::NOT_FOUND, packet.idXorTag()));
        return;
    }
    Component<Party> party;
    switch (packet.request()) {
        case CliPartyReq::MAKE:
            if (entity.component<Party>()) {
                logger_->warn("Client {} tried to create a party when already in a party", getId(entity));
                return;
            }
            party = entity.assign<Party>();
        case CliPartyReq::JOIN:
            if (!entity.component<Party>()) {
                logger_->warn("Client {} tried to execute an action on its party but doesn't have a party yet", getId(entity));
                return;
            }
            party = entity.component<Party>();
            party->isRequested_ = true;
            getClient(other)->Send(*makePacket<ePacketType::PAKWC_PARTY_REQ>(static_cast<SrvPartyReq::Request>(packet.request()), entity));
            return;
        case CliPartyReq::LEFT:
            if (!entity.component<Party>()) {
                logger_->warn("Client {} tried to leave the party but isn't in one", getId(entity));
                return;
            }
            entity.remove<Party>();
            return;
        case CliPartyReq::CHANGE_OWNER:
            if (!entity.component<Party>()) {
                logger_->warn("Client {} tried to give up ownership but isn't in a party", getId(entity));
                return;
            }
            // TODO : change leader
            return;
        case CliPartyReq::KICK:
            if (!entity.component<Party>())
                return;
            // TODO : kick member
            return;
        default:
            logger_->warn("Client {} sent a non valid request code {}", getId(entity), packet.request());
    }
}

void PartySystem::processPartyReply(CMapClient*, Entity entity, const RoseCommon::CliPartyReply &packet) {
    logger_->trace("PartySystem::processPartyRequest");
    Entity other;
    if (!(other = manager_.getEntity(packet.idXorTag())) || getClient(other)) {
        logger_->warn("Client {} replied to a party request of the non existing char {}", getId(entity), packet.idXorTag());
        return;
    }
    if (!other.component<Party>() || !other.component<Party>()->isRequested_) {
        logger_->warn("Client {} replied to a non existing party request", getId(entity));
        return;
    }
    switch (packet.reply()) {
        // if the guy asked is busy or declined the invitation, we send it to the guy asking
        case CliPartyReply::BUSY:
        case CliPartyReply::REJECT:
            other.component<Party>()->isRequested_ = false;
            if (!other.component<Party>()->party_)
                other.remove<Party>();
            getClient(other)->Send(*makePacket<ePacketType::PAKWC_PARTY_REPLY>(static_cast<SrvPartyReply::Reply>(packet.reply()), entity));
            return;
        // if the guy asked accepts, we send it to the guy asking and we update the party
        case CliPartyReply::ACCEPT_MAKE:
        case CliPartyReply::ACCEPT_JOIN:
            other.component<Party>()->isRequested_ = false;
            // TODO : add party member
            return;
        default:
            logger_->warn("Client {} sent a party reply with reply {}", getId(entity), (int)packet.reply());
    }
}
<commit_msg>Added the network code for adding a new member. Need to do something about that vector creation error<commit_after>#include "systems/partysystem.h"
#include "cmapclient.h"

using namespace Systems;
using namespace RoseCommon;

PartySystem::PartySystem(SystemManager &m) : System(m) {
    m.registerDispatcher(ePacketType::PAKCS_PARTY_REQ, &PartySystem::processPartyReq);
    m.registerDispatcher(ePacketType::PAKCS_PARTY_REPLY, &PartySystem::processPartyReply);
    m.getEntityManager().on_component_removed<Party>([this](Entity entity, Component<Party> Cparty) {
            auto party = Cparty->party_;
            party->removeMember(entity);
            for (auto &it : party->members_)
                getClient(it)->Send(*makePacket<ePacketType::PAKWC_PARTY_MEMBER>(party->options_, true, {entity}));
            });
    // TODO : use on_component_assign for new members?
}

void PartySystem::update(EntityManager &es, double) {
    Component<Party> party;
    Component<BasicInfo> info;
    for (Entity entity : es.entities_with_components(info, party)) {
        (void)entity;
        if (!party->party_) {
            logger_->trace("Client {} has the Party component but no affiliated party. {}", info->id_, party->isRequested_);
        }
        logger_->trace("Client {} is in a party", info->id_);
        logger_->trace("Party leader is {}, party members are", party->party_->leader_);
        for (auto it : party->party_->members_)
            logger_->trace("client {}", getId(it));
    }
}

void PartySystem::addPartyMember(Entity leader, Entity newMember) {
    auto Cparty = leader.component<Party>();
    if (!Cparty)
        return;
    std::shared_ptr<PartyBase> party = Cparty->party_;
    if (!party)
        party = Cparty->party_ = std::make_shared<PartyBase>(leader, newMember);
    if (newMember.component<Party>())
        return;
    newMember.assign<Party>(party);
    for (auto &it : party->members_) {
        getClient(it)->Send(*makePacket<ePacketType::PAKWC_PARTY_MEMBER>(party->options_, false, {newMember}));
    }
    getClient(newMember)->Send(*makePacket<ePacketType::PAKWC_PARTY_MEMBER>(party->options_, false, party->members_));
    party->addMember(newMember);
}

void PartySystem::processPartyReq(CMapClient *client, Entity entity, const CliPartyReq &packet) {
    logger_->trace("PartySystem::processPartyReq");
    Entity other;
    if (!(other = manager_.getEntity(packet.idXorTag())) || !getClient(other)) {
        logger_->debug("Client {} requested a party with the non existing char {}", getId(entity), packet.idXorTag());
        client->Send(*makePacket<ePacketType::PAKWC_PARTY_REPLY>(SrvPartyReply::NOT_FOUND, packet.idXorTag()));
        return;
    }
    Component<Party> party;
    switch (packet.request()) {
        case CliPartyReq::MAKE:
            if (entity.component<Party>()) {
                logger_->warn("Client {} tried to create a party when already in a party", getId(entity));
                return;
            }
            party = entity.assign<Party>();
        case CliPartyReq::JOIN:
            if (!entity.component<Party>()) {
                logger_->warn("Client {} tried to execute an action on its party but doesn't have a party yet", getId(entity));
                return;
            }
            party = entity.component<Party>();
            party->isRequested_ = true;
            getClient(other)->Send(*makePacket<ePacketType::PAKWC_PARTY_REQ>(static_cast<SrvPartyReq::Request>(packet.request()), entity));
            return;
        case CliPartyReq::LEFT:
            if (!entity.component<Party>()) {
                logger_->warn("Client {} tried to leave the party but isn't in one", getId(entity));
                return;
            }
            entity.remove<Party>();
            return;
        case CliPartyReq::CHANGE_OWNER:
            if (!entity.component<Party>()) {
                logger_->warn("Client {} tried to give up ownership but isn't in a party", getId(entity));
                return;
            }
            // TODO : change leader
            return;
        case CliPartyReq::KICK:
            if (!entity.component<Party>())
                return;
            // TODO : kick member
            return;
        default:
            logger_->warn("Client {} sent a non valid request code {}", getId(entity), packet.request());
    }
}

void PartySystem::processPartyReply(CMapClient*, Entity entity, const RoseCommon::CliPartyReply &packet) {
    logger_->trace("PartySystem::processPartyRequest");
    Entity other;
    if (!(other = manager_.getEntity(packet.idXorTag())) || getClient(other)) {
        logger_->warn("Client {} replied to a party request of the non existing char {}", getId(entity), packet.idXorTag());
        return;
    }
    if (!other.component<Party>() || !other.component<Party>()->isRequested_) {
        logger_->warn("Client {} replied to a non existing party request", getId(entity));
        return;
    }
    switch (packet.reply()) {
        // if the guy asked is busy or declined the invitation, we send it to the guy asking
        case CliPartyReply::BUSY:
        case CliPartyReply::REJECT:
            other.component<Party>()->isRequested_ = false;
            if (!other.component<Party>()->party_)
                other.remove<Party>();
            getClient(other)->Send(*makePacket<ePacketType::PAKWC_PARTY_REPLY>(static_cast<SrvPartyReply::Reply>(packet.reply()), entity));
            return;
        // if the guy asked accepts, we send it to the guy asking and we update the party
        case CliPartyReply::ACCEPT_MAKE:
        case CliPartyReply::ACCEPT_JOIN:
            other.component<Party>()->isRequested_ = false;
            // TODO : add party member
            return;
        default:
            logger_->warn("Client {} sent a party reply with reply {}", getId(entity), (int)packet.reply());
    }
}
<|endoftext|>


<commit_before>#include <sstream>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include "errno.h"
#include <string>
#include <list>
#include <string.h>
#include <vector>
#include <cstdlib>
#include <sys/wait.h>
#include <string.h>

using namespace std;
bool global_continue = true;
void fixing_spacing_command(char *org_prompt)
{
    char *finished_prompt = (char*)malloc(50000);
    //x is passed in prompt
    //i is finished prompt after changing spaces
    for(int x = 0,i = 0; org_prompt[x] != '\0'; x++, i++)
    {
        if(org_prompt[x] == '#')
        {
            org_prompt[x] = '\0';
            finished_prompt[i] = '\0';
        }
        else if(org_prompt[x] == ';')
        {
            finished_prompt[i] = ' ';
            finished_prompt[++i] = ';';
            finished_prompt[++i] = ' ';
        }
        else if(org_prompt[x] == '&' && org_prompt[x] == '&')
        {
            finished_prompt[i] = ' ';
            finished_prompt[++i] = '&';
            finished_prompt[++i] = '&';
            finished_prompt[++i] = ' ';
            ++x;
        }
        else if(org_prompt[x] == '|' && org_prompt[x] == '|')
        {
            finished_prompt[i] = ' ';
            finished_prompt[++i] = '|';
            finished_prompt[++i] = '|';
            finished_prompt[++i] = ' ';
            ++x;
        }
        else
        {
            finished_prompt[i] = org_prompt[x];
        }
        if(org_prompt[x + 1] == '\0') finished_prompt[i + 1] = '\0';
    }
    strcpy(org_prompt, finished_prompt);

}

bool execute(char* command, char* command_list[], int conect_type)
{
    int exec_status;
    int status;
    int process_ID = fork();
    if(process_ID <= -1)
    {
        perror("Error occured during forking()");
        exit(1);
    }
    else if(process_ID == 0)            //child process
    {

        exec_status = (execvp(command, command_list));
        if(exec_status == -1)
        {
            perror("error with passed in argument list");
            exit(1);
        }
    }
    else if(process_ID > 0)
    {
        if(waitpid(process_ID, &status,0) == -1)
        {
            perror("error with waitpid()");
        }
    }
    return(!(status == 0 && conect_type == -1) ||( status > 0 && conect_type == 2));
}

int check_connections(char* check)
{
    if(!strcmp(check, ";")) return  0;
    else if(!strcmp(check, "||")) return  1;
    else if(!strcmp(check, "&&")) return  2;
    else return -1;
}

int main(int argc, char **argv)
{
    int sequence = 0;           //sequence of which is executable and flags
    int status;
    char* host = (char*)malloc(500);
    string userinfo;
    bool prompter = true;
    char* token;            //will be bit of code strtok cuts off

    //error checks the user
    if(getlogin() != NULL)
    {
        userinfo = getlogin();
    }
    else
    {
        perror("error getting user info");
    }

    if(gethostname(host, 500) == -1)
    {
        perror("Error getting host name");
    }
    //outputs the userinfo with login and host
    while(prompter)
    {
        cout << userinfo << "@" << host << " $ ";
        //////////////////////////////////////////////login part done, next is all shell commands
        char prompt_holder[50000];//orginal array to hold prompt
        char *comd_arr[50000];
        for(int x = 0; x < 50001; x++)
        {
            prompt_holder[x] = 0;
            comd_arr[x] = 0;
        }
        unsigned int comd_arr_cnt = 0;

        string converter;                           //converts all bits of string into one piece
        string to_be_tokenized;
        getline(cin, to_be_tokenized);
        for(unsigned int x = 0; x < to_be_tokenized.size(); x++)
        {
            prompt_holder[x] =  to_be_tokenized.at(x);
        }
        fixing_spacing_command(prompt_holder);
        int connect_check;                          //indicates which connection is in token
        int exec_result;
        token = strtok(prompt_holder, "\t ");
        while(token != NULL  &&  prompter)
        {
            connect_check = check_connections(token);
            cout << "connect_check: " << connect_check << endl;
            cout << "first token: " << token << endl;
            if(connect_check == -1 && sequence < 1)
            {
                comd_arr[comd_arr_cnt] = token;
                comd_arr_cnt++;
                sequence++;                     //increment only once to see which is executable
            }
            else if(sequence > 0 && connect_check == -1)
            {
                comd_arr[comd_arr_cnt] = token;
                comd_arr_cnt++;

            }
            else if(connect_check != -1 && global_continue == true)
            {
                cout << "outputting token: " << token << endl;
                comd_arr[comd_arr_cnt] = '\0' ;
                sequence = 0;
                comd_arr_cnt = 0;
                exec_result = execute(comd_arr[0], comd_arr, connect_check);
                cout << "exex_result: " << exec_result << endl;
            }
            token = strtok(NULL, " ");
            if(connect_check == -1 && token == NULL && global_continue == true)
            {
                cout << "did this execute" << endl;
                comd_arr[comd_arr_cnt] = '\0';
                execute(comd_arr[0], comd_arr, connect_check);
            }
        }
    }
}

/* || && ;

succeeds ||
notsucceed &&

ls -a

[ls] [-a]

exekcvp([ls],[[ls],[-a]])
char* argumentList[50000];
char executable[50000];
argumentList[0] = executable;
unsigned int size = 0;
ls -a \0
execvp(argumentList[0], argumentList);
*/

<commit_msg>got more going<commit_after>#include <sstream>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include "errno.h"
#include <string>
#include <list>
#include <string.h>
#include <vector>
#include <cstdlib>
#include <sys/wait.h>
#include <string.h>

using namespace std;
bool global_continue = true;
void fixing_spacing_command(char *org_prompt)
{
    char *finished_prompt = (char*)malloc(50000);
    //x is passed in prompt
    //i is finished prompt after changing spaces
    for(int x = 0,i = 0; org_prompt[x] != '\0'; x++, i++)
    {
        if(org_prompt[x] == '#')
        {
            org_prompt[x] = '\0';
            finished_prompt[i] = '\0';
        }
        else if(org_prompt[x] == ';')
        {
            finished_prompt[i] = ' ';
            finished_prompt[++i] = ';';
            finished_prompt[++i] = ' ';
        }
        else if(org_prompt[x] == '&' && org_prompt[x] == '&')
        {
            finished_prompt[i] = ' ';
            finished_prompt[++i] = '&';
            finished_prompt[++i] = '&';
            finished_prompt[++i] = ' ';
            ++x;
        }
        else if(org_prompt[x] == '|' && org_prompt[x] == '|')
        {
            finished_prompt[i] = ' ';
            finished_prompt[++i] = '|';
            finished_prompt[++i] = '|';
            finished_prompt[++i] = ' ';
            ++x;
        }
        else
        {
            finished_prompt[i] = org_prompt[x];
        }
        if(org_prompt[x + 1] == '\0') finished_prompt[i + 1] = '\0';
    }
    strcpy(org_prompt, finished_prompt);

}

bool execute(char* command, char* command_list[], int conect_type)
{
    int exec_status;
    int status;
    int process_ID = fork();
    if(process_ID <= -1)
    {
        perror("Error occured during forking()");
        exit(1);
    }
    else if(process_ID == 0)            //child process
    {

        exec_status = (execvp(command, command_list));
        if(exec_status == -1)
        {
            perror("error with passed in argument list");
            exit(1);
        }
    }
    else if(process_ID > 0)
    {
        if(waitpid(process_ID, &status,0) == -1)
        {
            perror("error with waitpid()");
        }
    }
    return(!(status == 0 && conect_type == -1) ||( status > 0 && conect_type == 2));
}

int check_connections(char* check)
{
    if(!strcmp(check, ";")) return  0;
    else if(!strcmp(check, "||")) return  1;
    else if(!strcmp(check, "&&")) return  2;
    else return -1;
}
void check_exit(char *str)
{
    if(!strcmp(str, "exit"))
    {
        exit(0);
    }
}

int main(int argc, char **argv)
{
    int sequence = 0;           //sequence of which is executable and flags
    int status;
    char* host = (char*)malloc(500);
    string userinfo;
    bool prompter = true;
    char* token;            //will be bit of code strtok cuts off
    bool exec_result = true;
    //error checks the user
    if(getlogin() != NULL)
    {
        userinfo = getlogin();
    }
    else
    {
        perror("error getting user info");
    }

    if(gethostname(host, 500) == -1)
    {
        perror("Error getting host name");
    }

    //outputs the userinfo with login and host
    while(prompter)
    {
        cout << userinfo << "@" << host << " $ ";
        //////////////////////////////////////////////login part done, next is all shell commands
        char prompt_holder[50000];//orginal array to hold prompt
        char *comd_arr[50000];
        for(int x = 0; x < 50001; x++)
        {
            prompt_holder[x] = 0;
            comd_arr[x] = 0;
        }
        unsigned int comd_arr_cnt = 0;

        string converter;                           //converts all bits of string into one piece
        string to_be_tokenized;
        getline(cin, to_be_tokenized);
        for(unsigned int x = 0; x < to_be_tokenized.size(); x++)
        {
            prompt_holder[x] =  to_be_tokenized.at(x);
        }
        fixing_spacing_command(prompt_holder);
        int connect_check;                          //indicates which connection is in token
        token = strtok(prompt_holder, "\t ");
        while(token != NULL  && exec_result)
        {
            connect_check = check_connections(token);
            if(connect_check == -1 && sequence < 1)
            {
                check_exit(token);
                comd_arr[comd_arr_cnt] = token;
                comd_arr_cnt++;
                sequence++;                     //increment only once to see which is executable
            }
            else if(sequence > 0 && connect_check == -1)
            {
                comd_arr[comd_arr_cnt] = token;
                comd_arr_cnt++;

            }
            else if(connect_check != -1)
            {
                comd_arr[comd_arr_cnt] = '\0' ;
                sequence = 0;
                comd_arr_cnt = 0;
                exec_result = execute(comd_arr[0], comd_arr, connect_check);
                if(exec_result == true && connect_check == 1)
                {
                   exec_result = false;
                }

            }
            token = strtok(NULL, " ");
            if(connect_check == -1 && token == NULL && exec_result)
            {
                comd_arr[comd_arr_cnt] = '\0';
                execute(comd_arr[0], comd_arr, connect_check);
            }
        }
    }
}

/* || && ;

succeeds ||
notsucceed &&

ls -a

[ls] [-a]

exekcvp([ls],[[ls],[-a]])
char* argumentList[50000];
char executable[50000];
argumentList[0] = executable;
unsigned int size = 0;
ls -a \0
execvp(argumentList[0], argumentList);
*/

<|endoftext|>


<commit_before>#ifdef __APPLE__

    #include <SDL2/SDL.h>

    extern "C" {
        #include <lua.h>
        #include <lualib.h>
        #include <lauxlib.h>
    }

#elif _WIN32

    #define SDL_MAIN_HANDLED
    #include <SDL.h>
    #include <stdio.h>
    #include <lua.hpp>

#endif

#include <string>

#define SCREEN_WIDTH 400
#define SCREEN_HEIGHT 225

#define GAME_WIDTH 256
#define GAME_HEIGHT 144

//http://www.lua.org/manual/5.3/manual.html#lua_CFunction
static int luaTestFunc(lua_State* state)
{
	/* number of arguments */
	int args = lua_gettop(state);

	for (int n = 1; n <= args; ++n) {
		printf("  arg %d: '%s'\n", n, lua_tostring(state, n));
	}

	lua_pushnumber(state, 123);
	return 1; /* number of results */
}

void renderText(std::string str, SDL_Surface* charSet, SDL_Surface* surf) {

	unsigned int i = 0;
	for (char& c : str) {
		//printf("%c", c);
		unsigned int charIndex = c - 32;
		SDL_Rect src = { 8 * charIndex, 0, 8, 8 };
		SDL_Rect dst = { 8 * i, 16, 8, 8 };

		SDL_BlitSurface(charSet, &src, surf, &dst);
		++i;
	}

}

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

    SDL_version compiled;
    SDL_version linked;

    SDL_VERSION(&compiled);
    SDL_GetVersion(&linked);

    printf("We compiled against SDL version %d.%d.%d ...\n",
           compiled.major, compiled.minor, compiled.patch);
    printf("We are linking against SDL version %d.%d.%d.\n",
           linked.major, linked.minor, linked.patch);

    SDL_Init(SDL_INIT_VIDEO);
    SDL_Window *window = SDL_CreateWindow(
       "unamed-dungeon-crawler",
       SDL_WINDOWPOS_UNDEFINED,
       SDL_WINDOWPOS_UNDEFINED,
       SCREEN_WIDTH*2,
       SCREEN_HEIGHT*2,
	   SDL_WINDOW_RESIZABLE
    );

    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0);

    SDL_Texture *texture = SDL_CreateTexture(renderer,
                                                SDL_PIXELFORMAT_ARGB8888,
                                                SDL_TEXTUREACCESS_STREAMING,
                                                SCREEN_WIDTH, SCREEN_HEIGHT);

//    SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");  // make the scaled rendering look smoother.
//    SDL_RenderSetLogicalSize(renderer, SCREEN_WIDTH*4, SCREEN_HEIGHT*4);

    //SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "ERROR", SDL_GetError(), window);

    SDL_Surface *screen = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 32, 0, 0, 0, 0);
    SDL_Surface *game   = SDL_CreateRGBSurface(0, GAME_WIDTH, GAME_HEIGHT, 32, 0, 0, 0, 0);

    SDL_Surface *testSurface = SDL_LoadBMP("data/base/test.bmp");
    SDL_Surface *borderSurface = SDL_LoadBMP("data/base/borders/border.bmp");
	SDL_Surface *tile00Surface = SDL_LoadBMP("data/base/tiles/tile00.bmp");
	SDL_Surface *tile01Surface = SDL_LoadBMP("data/base/tiles/tile01.bmp");
	SDL_Surface *player = SDL_LoadBMP("data/base/spritesheets/player.bmp");
	SDL_Surface *bmpFont = SDL_LoadBMP("data/base/fonts/standard_font.bmp");

    bool quit = false;

    SDL_Event e;

	//SDL_Rect pos = { 0,40,100,100 };

	//Lua
	lua_State *state = luaL_newstate();
	luaL_openlibs(state);

	lua_register(state, "luaTestFunc", luaTestFunc);

	luaL_dostring(state, "io.write(\"luaTestFunc\")");
	luaL_dostring(state, "luaTestFunc(\"First\", \"Second\", 112233)");

	//Dungeon
	int tilesArray[] = {
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
		1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
		1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1,
		1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1,
		1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1,
		1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1,
		1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
		1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	};

	int arrayWidth  = 16;
	int arrayHeight = 9;

	int playerPos = 0;

    while (!quit)
    {

        while (SDL_PollEvent(&e) != 0)
        {

            const Uint8 *state = SDL_GetKeyboardState(NULL);

            if (e.type == SDL_QUIT)
            {
                quit = true;
            }

            if (state[SDL_SCANCODE_LEFT]) {

				//int oldPos = playerPos;

				int x = playerPos % arrayWidth;
				int y = (playerPos / arrayWidth) % arrayHeight;

				x -= 1;

				playerPos = x + arrayWidth*y;
            } else

            if (state[SDL_SCANCODE_RIGHT]) {

				int x = playerPos % arrayWidth;
				int y = (playerPos / arrayWidth) % arrayHeight;

				x += 1;

				playerPos = x + arrayWidth*y;
            } else

			if (state[SDL_SCANCODE_UP]) {

				int x = playerPos % arrayWidth;
				int y = (playerPos / arrayWidth) % arrayHeight;

				y -= 1;

				playerPos = x + arrayWidth*y;
			} else

			if (state[SDL_SCANCODE_DOWN]) {

				int x = playerPos % arrayWidth;
				int y = (playerPos / arrayWidth) % arrayHeight;

				y += 1;

				playerPos = x + arrayWidth*y;
			}

        }

		//clear screen surface
		SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 255, 0, 0));
		SDL_FillRect(game, NULL, SDL_MapRGB(screen->format, 0, 255, 0));

		//render tiles
		for (size_t i = 0; i < arrayWidth * arrayHeight; i++)
		{
			int x = i % arrayWidth;
			int y = (i / arrayWidth) % arrayHeight;

			SDL_Rect pos = { x * 16, y * 16, 16, 16 };

			//printf("x: %i , y: %i\n", x, y);

			if (tilesArray[i] == 0) {

				SDL_BlitSurface(tile00Surface, NULL, game, &pos);
			} else

			if (tilesArray[i] == 1) {

				SDL_BlitSurface(tile01Surface, NULL, game, &pos);
			}
		}

		//render player

		{

			int x = playerPos % arrayWidth;
			int y = (playerPos / arrayWidth) % arrayHeight;

			SDL_Rect pos = { x * 16, y * 16, 16, 16 };
			SDL_BlitSurface(player, NULL, game, &pos);
		}

		//SDL_BlitSurface(testSurface, 0, game, NULL);

		SDL_BlitSurface(borderSurface, 0, screen, 0);

		SDL_Rect location = { 72,40,100,100 };
		SDL_BlitSurface(game, 0, screen, &location);

		//test
		SDL_BlitSurface(bmpFont, 0, screen, 0);
		renderText(" 0123!", bmpFont, screen);

        SDL_UpdateTexture(texture, NULL, screen->pixels, screen->pitch);
        SDL_RenderClear(renderer);
        SDL_RenderCopy(renderer, texture, 0, 0);
        SDL_RenderPresent(renderer);

        SDL_Delay(16);
    }

	lua_close(state);

    SDL_FreeSurface(testSurface);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;

}
<commit_msg>render text<commit_after>#ifdef __APPLE__

    #include <SDL2/SDL.h>

    extern "C" {
        #include <lua.h>
        #include <lualib.h>
        #include <lauxlib.h>
    }

#elif _WIN32

    #define SDL_MAIN_HANDLED
    #include <SDL.h>
    #include <stdio.h>
    #include <lua.hpp>

#endif

#include <string>

#define SCREEN_WIDTH 400
#define SCREEN_HEIGHT 225

#define GAME_WIDTH 256
#define GAME_HEIGHT 144

//http://www.lua.org/manual/5.3/manual.html#lua_CFunction
static int luaTestFunc(lua_State* state)
{
	/* number of arguments */
	int args = lua_gettop(state);

	for (int n = 1; n <= args; ++n) {
		printf("  arg %d: '%s'\n", n, lua_tostring(state, n));
	}

	lua_pushnumber(state, 123);
	return 1; /* number of results */
}

void renderText(std::string str, SDL_Surface* charSet, SDL_Surface* surf) {

	unsigned int i = 0;
	unsigned int j = 0;
	for (char& c : str) {
		//printf("%c", c);
		if (((int)c) == 10) {
			++j;
			i = 0;
			continue;
		};
		unsigned int charIndex = c - 32;
		SDL_Rect src = { 8 * charIndex, 0, 8, 8 };
		SDL_Rect dst = { 8 * i, (14 + j )*8 , 8, 8 };

		SDL_BlitSurface(charSet, &src, surf, &dst);
		++i;
	}

}

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

    SDL_version compiled;
    SDL_version linked;

    SDL_VERSION(&compiled);
    SDL_GetVersion(&linked);

    printf("We compiled against SDL version %d.%d.%d ...\n",
           compiled.major, compiled.minor, compiled.patch);
    printf("We are linking against SDL version %d.%d.%d.\n",
           linked.major, linked.minor, linked.patch);

    SDL_Init(SDL_INIT_VIDEO);
    SDL_Window *window = SDL_CreateWindow(
       "unamed-dungeon-crawler",
       SDL_WINDOWPOS_UNDEFINED,
       SDL_WINDOWPOS_UNDEFINED,
       SCREEN_WIDTH*2,
       SCREEN_HEIGHT*2,
	   SDL_WINDOW_RESIZABLE
    );

    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0);

    SDL_Texture *texture = SDL_CreateTexture(renderer,
                                                SDL_PIXELFORMAT_ARGB8888,
                                                SDL_TEXTUREACCESS_STREAMING,
                                                SCREEN_WIDTH, SCREEN_HEIGHT);

//    SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");  // make the scaled rendering look smoother.
//    SDL_RenderSetLogicalSize(renderer, SCREEN_WIDTH*4, SCREEN_HEIGHT*4);

    //SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "ERROR", SDL_GetError(), window);

    SDL_Surface *screen = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 32, 0, 0, 0, 0);
    SDL_Surface *game   = SDL_CreateRGBSurface(0, GAME_WIDTH, GAME_HEIGHT, 32, 0, 0, 0, 0);

    SDL_Surface *testSurface = SDL_LoadBMP("data/base/test.bmp");
    SDL_Surface *borderSurface = SDL_LoadBMP("data/base/borders/border.bmp");
	SDL_Surface *tile00Surface = SDL_LoadBMP("data/base/tiles/tile00.bmp");
	SDL_Surface *tile01Surface = SDL_LoadBMP("data/base/tiles/tile01.bmp");
	SDL_Surface *player = SDL_LoadBMP("data/base/spritesheets/player.bmp");
	SDL_Surface *bmpFont = SDL_LoadBMP("data/base/fonts/standard_font.bmp");

    bool quit = false;

    SDL_Event e;

	//SDL_Rect pos = { 0,40,100,100 };

	//Lua
	lua_State *state = luaL_newstate();
	luaL_openlibs(state);

	lua_register(state, "luaTestFunc", luaTestFunc);

	luaL_dostring(state, "io.write(\"luaTestFunc\")");
	luaL_dostring(state, "luaTestFunc(\"First\", \"Second\", 112233)");

	//Dungeon
	int tilesArray[] = {
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
		1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
		1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1,
		1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1,
		1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1,
		1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1,
		1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
		1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	};

	int arrayWidth  = 16;
	int arrayHeight = 9;

	int playerPos = 0;

    while (!quit)
    {

        while (SDL_PollEvent(&e) != 0)
        {

            const Uint8 *state = SDL_GetKeyboardState(NULL);

            if (e.type == SDL_QUIT)
            {
                quit = true;
            }

            if (state[SDL_SCANCODE_LEFT]) {

				//int oldPos = playerPos;

				int x = playerPos % arrayWidth;
				int y = (playerPos / arrayWidth) % arrayHeight;

				x -= 1;

				playerPos = x + arrayWidth*y;
            } else

            if (state[SDL_SCANCODE_RIGHT]) {

				int x = playerPos % arrayWidth;
				int y = (playerPos / arrayWidth) % arrayHeight;

				x += 1;

				playerPos = x + arrayWidth*y;
            } else

			if (state[SDL_SCANCODE_UP]) {

				int x = playerPos % arrayWidth;
				int y = (playerPos / arrayWidth) % arrayHeight;

				y -= 1;

				playerPos = x + arrayWidth*y;
			} else

			if (state[SDL_SCANCODE_DOWN]) {

				int x = playerPos % arrayWidth;
				int y = (playerPos / arrayWidth) % arrayHeight;

				y += 1;

				playerPos = x + arrayWidth*y;
			}

        }

		//clear screen surface
		SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 255, 0, 0));
		SDL_FillRect(game, NULL, SDL_MapRGB(screen->format, 0, 255, 0));

		//render tiles
		for (size_t i = 0; i < arrayWidth * arrayHeight; i++)
		{
			int x = i % arrayWidth;
			int y = (i / arrayWidth) % arrayHeight;

			SDL_Rect pos = { x * 16, y * 16, 16, 16 };

			//printf("x: %i , y: %i\n", x, y);

			if (tilesArray[i] == 0) {

				SDL_BlitSurface(tile00Surface, NULL, game, &pos);
			} else

			if (tilesArray[i] == 1) {

				SDL_BlitSurface(tile01Surface, NULL, game, &pos);
			}
		}

		//render player

		{

			int x = playerPos % arrayWidth;
			int y = (playerPos / arrayWidth) % arrayHeight;

			SDL_Rect pos = { x * 16, y * 16, 16, 16 };
			SDL_BlitSurface(player, NULL, game, &pos);
		}

		//SDL_BlitSurface(testSurface, 0, game, NULL);

		SDL_BlitSurface(borderSurface, 0, screen, 0);

		SDL_Rect location = { 72,40,100,100 };
		SDL_BlitSurface(game, 0, screen, &location);

		//test
		SDL_BlitSurface(bmpFont, 0, screen, 0);
		renderText(" 0123!", bmpFont, screen);

        SDL_UpdateTexture(texture, NULL, screen->pixels, screen->pitch);
        SDL_RenderClear(renderer);
        SDL_RenderCopy(renderer, texture, 0, 0);
        SDL_RenderPresent(renderer);

        SDL_Delay(16);
    }

	lua_close(state);

    SDL_FreeSurface(testSurface);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;

}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Fondazione Istituto Italiano di Tecnologia
 * Authors: Silvio Traversaro
 * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
 *
 */

#include <iDynTree/Model/FreeFloatingState.h>
#include <iDynTree/Model/Model.h>

#include <cassert>

namespace iDynTree
{

FreeFloatingPos::FreeFloatingPos(const Model& model)
{
    resize(model);
}

void FreeFloatingPos::resize(const Model& model)
{
    this->m_jointPos.resize(model.getNrOfPosCoords());
}

Transform& FreeFloatingPos::worldBasePos()
{
    return this->m_worldBasePos;
}

IRawVector & FreeFloatingPos::jointPos()
{
    return this->m_jointPos;
}

const Transform& FreeFloatingPos::worldBasePos() const
{
    return this->m_worldBasePos;
}

const IRawVector & FreeFloatingPos::jointPos() const
{
    return this->m_jointPos;
}

unsigned int FreeFloatingPos::getNrOfPosCoords() const
{
    return this->m_jointPos.size();
}

FreeFloatingPos::~FreeFloatingPos()
{
}

FreeFloatingVel::FreeFloatingVel(const Model& model)
{
    resize(model);
}

Twist& FreeFloatingVel::baseVel()
{
    return this->m_baseVel;
}

const Twist& FreeFloatingVel::baseVel() const
{
    return this->m_baseVel;
}

unsigned int FreeFloatingVel::getNrOfDOFs() const
{
    return this->m_jointVel.size();
}

IRawVector& FreeFloatingVel::jointVel()
{
    return this->m_jointVel;
}

const IRawVector& FreeFloatingVel::jointVel() const
{
    return this->m_jointVel;
}

void FreeFloatingVel::resize(const Model& model)
{
    this->m_jointVel.resize(model.getNrOfDOFs());
}

FreeFloatingVel::~FreeFloatingVel()
{

}

FreeFloatingAcc::FreeFloatingAcc(const Model& model)
{
    resize(model);
}

SpatialAcc& FreeFloatingAcc::baseAcc()
{
    return this->m_baseAcc;
}

const SpatialAcc& FreeFloatingAcc::baseAcc() const
{
    return this->m_baseAcc;
}

unsigned int FreeFloatingAcc::getNrOfDOFs() const
{
    return this->m_jointAcc.size();
}

IRawVector& FreeFloatingAcc::jointAcc()
{
    return this->m_jointAcc;
}

const IRawVector& FreeFloatingAcc::jointAcc() const
{
    return this->m_jointAcc;
}

void FreeFloatingAcc::resize(const Model& model)
{
    this->m_jointAcc.resize(model.getNrOfDOFs());
}

FreeFloatingAcc::~FreeFloatingAcc()
{

}

FreeFloatingGeneralizedTorques::FreeFloatingGeneralizedTorques(const Model& model)
{
    resize(model);
}

void FreeFloatingGeneralizedTorques::resize(const Model& model)
{
    this->m_jointTorques.resize(model.getNrOfDOFs());
}

Wrench& FreeFloatingGeneralizedTorques::baseWrench()
{
    return this->m_baseWrench;
}

IRawVector& FreeFloatingGeneralizedTorques::jointTorques()
{
    return this->m_jointTorques;
}

const Wrench& FreeFloatingGeneralizedTorques::baseWrench() const
{
    return this->m_baseWrench;
}

const IRawVector& FreeFloatingGeneralizedTorques::jointTorques() const
{
    return this->m_jointTorques;
}

unsigned int FreeFloatingGeneralizedTorques::getNrOfDOFs() const
{
    return this->m_jointTorques.size();
}

FreeFloatingGeneralizedTorques::~FreeFloatingGeneralizedTorques()
{

}

}
<commit_msg>Fix missing initialization in FreeFloating** resize<commit_after>/*
 * Copyright (C) 2015 Fondazione Istituto Italiano di Tecnologia
 * Authors: Silvio Traversaro
 * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
 *
 */

#include <iDynTree/Model/FreeFloatingState.h>
#include <iDynTree/Model/Model.h>

#include <cassert>

namespace iDynTree
{

FreeFloatingPos::FreeFloatingPos(const Model& model)
{
    resize(model);
}

void FreeFloatingPos::resize(const Model& model)
{
    this->m_worldBasePos = Transform::Identity();
    this->m_jointPos.resize(model.getNrOfPosCoords());
    this->m_jointPos.zero();
}

Transform& FreeFloatingPos::worldBasePos()
{
    return this->m_worldBasePos;
}

IRawVector & FreeFloatingPos::jointPos()
{
    return this->m_jointPos;
}

const Transform& FreeFloatingPos::worldBasePos() const
{
    return this->m_worldBasePos;
}

const IRawVector & FreeFloatingPos::jointPos() const
{
    return this->m_jointPos;
}

unsigned int FreeFloatingPos::getNrOfPosCoords() const
{
    return this->m_jointPos.size();
}

FreeFloatingPos::~FreeFloatingPos()
{
}

FreeFloatingVel::FreeFloatingVel(const Model& model)
{
    resize(model);
}

Twist& FreeFloatingVel::baseVel()
{
    return this->m_baseVel;
}

const Twist& FreeFloatingVel::baseVel() const
{
    return this->m_baseVel;
}

unsigned int FreeFloatingVel::getNrOfDOFs() const
{
    return this->m_jointVel.size();
}

IRawVector& FreeFloatingVel::jointVel()
{
    return this->m_jointVel;
}

const IRawVector& FreeFloatingVel::jointVel() const
{
    return this->m_jointVel;
}

void FreeFloatingVel::resize(const Model& model)
{
    this->m_baseVel.zero();
    this->m_jointVel.resize(model.getNrOfDOFs());
    this->m_jointVel.zero();
}

FreeFloatingVel::~FreeFloatingVel()
{

}

FreeFloatingAcc::FreeFloatingAcc(const Model& model)
{
    resize(model);
}

SpatialAcc& FreeFloatingAcc::baseAcc()
{
    return this->m_baseAcc;
}

const SpatialAcc& FreeFloatingAcc::baseAcc() const
{
    return this->m_baseAcc;
}

unsigned int FreeFloatingAcc::getNrOfDOFs() const
{
    return this->m_jointAcc.size();
}

IRawVector& FreeFloatingAcc::jointAcc()
{
    return this->m_jointAcc;
}

const IRawVector& FreeFloatingAcc::jointAcc() const
{
    return this->m_jointAcc;
}

void FreeFloatingAcc::resize(const Model& model)
{
    this->m_baseAcc.zero();
    this->m_jointAcc.resize(model.getNrOfDOFs());
    this->m_jointAcc.zero();
}

FreeFloatingAcc::~FreeFloatingAcc()
{

}

FreeFloatingGeneralizedTorques::FreeFloatingGeneralizedTorques(const Model& model)
{
    resize(model);
}

void FreeFloatingGeneralizedTorques::resize(const Model& model)
{
    this->m_jointTorques.resize(model.getNrOfDOFs());
}

Wrench& FreeFloatingGeneralizedTorques::baseWrench()
{
    return this->m_baseWrench;
}

IRawVector& FreeFloatingGeneralizedTorques::jointTorques()
{
    return this->m_jointTorques;
}

const Wrench& FreeFloatingGeneralizedTorques::baseWrench() const
{
    return this->m_baseWrench;
}

const IRawVector& FreeFloatingGeneralizedTorques::jointTorques() const
{
    return this->m_jointTorques;
}

unsigned int FreeFloatingGeneralizedTorques::getNrOfDOFs() const
{
    return this->m_jointTorques.size();
}

FreeFloatingGeneralizedTorques::~FreeFloatingGeneralizedTorques()
{

}

}
<|endoftext|>


<commit_before>#include <msgpack.hpp>
#include <string>
#include <iostream>
#include <sstream>

#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/yield.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/write.hpp>
#include <boost/bind.hpp>

namespace detail {
    using Packer = msgpack::packer<msgpack::sbuffer>;

    template<class X>
        Packer& pack(Packer& pk, const X& x)
        {
              return pk << x;
        }
    template<class X, class Y, class...Z>
        Packer& pack(Packer& pk, const X &x, const Y &y, const Z &...z)
        {
              return pack(pack(pk, x), y, z...);
        }

    static Packer& pack(Packer& pk)
    {
          return pk;
    }
} // namespace detail

class Client {
    boost::asio::io_service &io_service_;
    boost::asio::ip::tcp::socket socket_;

    enum {
        REQUEST  = 0,
        RESPONSE = 1,
        NOTIFY   = 2
    };

public:
    Client(boost::asio::io_service &io_service)
        : io_service_(io_service),
          socket_(io_service)
    {

    }

    void start() {
        connect();
    }

private:

    void connect() {
        socket_.async_connect(
                boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 6666),
                boost::bind(&Client::on_connect, this, boost::asio::placeholders::error));
    }

    void on_connect(const boost::system::error_code &error) {
        if(error) {
            std::cout << "connect failed: " << error.message() << std::endl;
        } else {
            std::cout << "connected" << std::endl;
            send(79); //debug vim_del_current_line
        }
    }

    template<typename...T>
    void send(uint64_t method, const T&...t) {
        //msgpack::type::tuple<int, std::string, std::string> src(2, "vim_command", "vsplit");

        msgpack::sbuffer sbuf;
        detail::Packer pk(&sbuf);
        pk.pack_array(4) << (uint64_t)REQUEST
                         << 0 //id
                         << method;

        pk.pack_array(sizeof...(t));
        detail::pack(pk, t...);

        msgpack::object_handle oh = msgpack::unpack(sbuf.data(), sbuf.size());

        msgpack::object deserialized = oh.get();

        std::cout << "sbuf = " << deserialized << std::endl;

        boost::asio::async_write(
                        socket_,
                        boost::asio::buffer(std::string(sbuf.data())),
                        boost::bind(&Client::on_send, this, boost::asio::placeholders::error,
                                                            boost::asio::placeholders::bytes_transferred));
    }

    void on_send(const boost::system::error_code &error, size_t /*bytes_transferred*/) {
        if(error) {
            std::cout << "send failed: " << error.message() << std::endl;
        } else {
            std::cout << "send correct!" << std::endl;
        }
    }
};

int main() {
    boost::asio::io_service io_service;
    Client client(io_service);

    client.start();
    //client.connect();
    io_service.run();

    //boost::asio::io_service::strand strand = socket.get_io_service();

    //boost::asio::spawn(io_service, [](boost::asio::yield_context yield){
        //async_read(socket, asio::buffer(buffer_), yield);
        //async_write(socket, asio::buffer(buffer_), yield);

        //do something...
    //});

    msgpack::type::tuple<int, bool, std::string> src(1, true, "example");

    std::stringstream buffer;
    msgpack::pack(buffer, src);

    buffer.seekg(0);

    std::string str(buffer.str()); //binary

    msgpack::object_handle oh = msgpack::unpack(str.data(), str.size());

    msgpack::object deserialized = oh.get();

    std::cout << deserialized << std::endl;

    msgpack::type::tuple<int, bool, std::string> dst;
    deserialized.convert(dst);

    return 0;
}
<commit_msg>msg id<commit_after>#include <msgpack.hpp>
#include <string>
#include <iostream>
#include <sstream>

#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/yield.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/write.hpp>
#include <boost/bind.hpp>

namespace detail {
    using Packer = msgpack::packer<msgpack::sbuffer>;

    template<class X>
        Packer& pack(Packer& pk, const X& x)
        {
              return pk << x;
        }
    template<class X, class Y, class...Z>
        Packer& pack(Packer& pk, const X &x, const Y &y, const Z &...z)
        {
              return pack(pack(pk, x), y, z...);
        }

    static Packer& pack(Packer& pk)
    {
          return pk;
    }
} // namespace detail

class Client {
    boost::asio::io_service &io_service_;
    boost::asio::ip::tcp::socket socket_;

    enum {
        REQUEST  = 0,
        RESPONSE = 1,
        NOTIFY   = 2
    };

public:
    Client(boost::asio::io_service &io_service)
        : io_service_(io_service),
          socket_(io_service)
    {

    }

    void start() {
        connect();
    }

private:

    void connect() {
        socket_.async_connect(
                boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 6666),
                boost::bind(&Client::on_connect, this, boost::asio::placeholders::error));
    }

    void on_connect(const boost::system::error_code &error) {
        if(error) {
            std::cout << "connect failed: " << error.message() << std::endl;
        } else {
            std::cout << "connected" << std::endl;
            send(0); //debug vim_del_current_line
        }
    }

    template<typename...T>
    void send(uint64_t method, const T&...t) {
        //msgpack::type::tuple<int, std::string, std::string> src(2, "vim_command", "vsplit");

        msgpack::sbuffer sbuf;
        detail::Packer pk(&sbuf);
        pk.pack_array(4) << (uint64_t)REQUEST
                         << (uint64_t)0 //msgid
                         << std::string("vim_del_current_line");

        pk.pack_array(sizeof...(t));
        detail::pack(pk, t...);

        msgpack::object_handle oh = msgpack::unpack(sbuf.data(), sbuf.size());

        msgpack::object deserialized = oh.get();

        std::cout << "sbuf = " << deserialized << std::endl;

        boost::asio::async_write(
                        socket_,
                        boost::asio::buffer(std::string(sbuf.data())),
                        boost::bind(&Client::on_send, this, boost::asio::placeholders::error,
                                                            boost::asio::placeholders::bytes_transferred));
    }

    void on_send(const boost::system::error_code &error, size_t /*bytes_transferred*/) {
        if(error) {
            std::cout << "send failed: " << error.message() << std::endl;
        } else {
            std::cout << "send correct!" << std::endl;
        }
    }
};

int main() {
    boost::asio::io_service io_service;
    Client client(io_service);

    client.start();
    //client.connect();
    io_service.run();

    //boost::asio::io_service::strand strand = socket.get_io_service();

    //boost::asio::spawn(io_service, [](boost::asio::yield_context yield){
        //async_read(socket, asio::buffer(buffer_), yield);
        //async_write(socket, asio::buffer(buffer_), yield);

        //do something...
    //});

    msgpack::type::tuple<int, bool, std::string> src(1, true, "example");

    std::stringstream buffer;
    msgpack::pack(buffer, src);

    buffer.seekg(0);

    std::string str(buffer.str()); //binary

    msgpack::object_handle oh = msgpack::unpack(str.data(), str.size());

    msgpack::object deserialized = oh.get();

    std::cout << deserialized << std::endl;

    msgpack::type::tuple<int, bool, std::string> dst;
    deserialized.convert(dst);

    return 0;
}
<|endoftext|>


<commit_before>#include<QApplication>
#include<version.hpp>

int main(int argc,char** argv){
	QApplication mcswitch(argc,argv);

	mcswitch.setApplicationName(app_name);
	mcswitch.setApllicationVersion(app_ver);

	return mcswitch.exec();
}
<commit_msg>main.cppにもMITライセンス条文を記述<commit_after>/*
Copyright (c) 2012 opamp

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<QApplication>
#include<version.hpp>

int main(int argc,char** argv){
	QApplication mcswitch(argc,argv);

	mcswitch.setApplicationName(app_name);
	mcswitch.setApllicationVersion(app_ver);

	return mcswitch.exec();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <pwd.h>
using namespace std;

static int *glob_flag;

//output login @ machine $
void prompt(){
struct passwd *log;
	int pid = fork();
		if(pid == -1){
			perror("fork() presented error");
			exit(1);
			}
		else if(pid==0){
			char host[50];
			if ((gethostname(host, sizeof(host)-1))==-1) {
				host[0] = 'h';
				host[1] = 'o';
				host[2] = 's';
				host[3] = 't';
				host[4] = '\0';
				perror("Error trying to get hostname");
			}
			log = getpwuid(getuid());
			if(log == '\0'){
				perror("Error trying to get user login");
			}

			cout << log->pw_name << "@" << host << "$ ";
			exit(1);
			}else if(pid>0){
				if(-1 == wait(0))
			   	perror("wait() presented error");

			}
}

void execute(char *str[],int size){

char * newstr[256];
char * connector;
int i,j,aux;

	//create a shared memory to be accessed from child and process
	glob_flag =(int*) mmap(NULL, sizeof *glob_flag, PROT_READ | PROT_WRITE,
                    MAP_SHARED | MAP_ANONYMOUS, -1, 0);

	for(i=0;i<size;i++){
		*glob_flag = 0;
		//newstr[0] receives commands, first parameter after a connector
		newstr[0] = str[i];
		aux=1;
		//test command without flags carryng a ';'
		connector = strchr(newstr[0],';');
		if(connector!=NULL) newstr[0][connector-newstr[0]] = '\0';
		else
			for(j=i+1;j<size;j++){
				connector = strchr(str[j],';');
				if(connector!=NULL){
				//erase the last character if ';'
					str[j][connector-str[j]] = '\0';
				}
				//check for && setting a flag to 1
				if(memcmp(str[j], "&&",2)==0){
					*glob_flag = 1;
					i = j;
					break;
				}
				//check for || setting a flag to 3
				if(memcmp(str[j], "||",2)==0){
					*glob_flag = 3;
					i = j;
					break;
				}

				//add flags to newstr
				newstr[aux] = str[j];
				aux++;
				i = j;

				if(connector!=NULL) break;
			}

		int pid = fork();
		if(pid == -1){
			perror("fork() presented error");
			exit(1);
		}
		else if(pid == 0){
		  	 if(-1 == execvp(newstr[0], newstr)){
				perror("There was an error");
				//flag 1 means, first command must be successfull to apply the second
				if(*glob_flag == 1) *glob_flag = 2;
				//flag 3 means, first command must be failed to apply the second
				//number 5 won't pass in the breaking loop
				if(*glob_flag == 3) *glob_flag = 5;
			}
    	 		exit(1);
		}
		else if(pid>0){
			if(-1 == wait(0))
		   	perror("wait() presented error");

		}

		// clear the vector newstr in order to execute new commands
		for(int k=0;k<aux;k++)newstr[k]='\0';

		//break loop due to a non valid previous command connected by &&
		if(*glob_flag == 2) break;
		//break loop due to a valid previous command connected by ||
		if(*glob_flag == 3) break;
	}
}

int main(){
   int index;
   string line;
   char * str[256];
   char * pch;

   while(true){
	do{
	    //output login @ machine $
	    prompt();
	    getline(cin,line);
	}while(line[0]=='#');

	//look for '#', if find erase everything until the end of line
	size_t found = line.find('#');
	  if (found!=std::string::npos)
		line.erase (found,line.length()-found);

	//create a dynamic char that is a copy of input
  	char * input = new char [line.length()+1];
  	strcpy (input, line.c_str());

	//built in function to finish program when typed 'EXIT'
	if(memcmp(input, "exit",4)==0) exit(0);

	index=0;
	pch= strtok (input," ");

	while(pch != NULL){
	    str[index]=pch;
	    pch = strtok(NULL, " ");
	    index++;
	}

	str[index] = NULL;

	execute(str,index);

    }
 return 0;
}
<commit_msg>comparisions && and || updated<commit_after>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <pwd.h>
using namespace std;

static int *glob_flag;

//output login @ machine $
void prompt(){
	struct passwd *log;
	int pid = fork();
	if(pid == -1){
	perror("fork() presented error");
	exit(1);
	}
	else if(pid==0){
	char host[50];
	if ((gethostname(host, sizeof(host)-1))==-1) {
	host[0] = 'h';
	host[1] = 'o';
	host[2] = 's';
	host[3] = 't';
	host[4] = '\0';
	perror("Error trying to get hostname");
	}
	log = getpwuid(getuid());
	if(log == '\0'){
		perror("Error trying to get user login");
	}

	cout << log->pw_name << "@" << host << "$ ";
	exit(1);
	}else if(pid>0){
	if(-1 == wait(0))
	perror("wait() presented error");

	}
}

void execute(char *str[], int size){

	char * newstr[512];
	char * connector;
	int i, j, aux;

	//create a shared memory to be accessed from child and process
	glob_flag = (int*)mmap(NULL, sizeof *glob_flag, PROT_READ | PROT_WRITE,
		MAP_SHARED | MAP_ANONYMOUS, -1, 0);

	for (i = 0; i<size; i++){
		*glob_flag = 0;
		//newstr[0] receives commands, first parameter after a connector
		newstr[0] = str[i];
		if(memcmp(newstr[0],"exit",4)==0) exit(0);
		aux = 1;
		//test command without flags carryng a ';'
		connector = strchr(newstr[0], ';');
		if (connector != NULL) newstr[0][connector - newstr[0]] = '\0';
		else
			for (j = i + 1; j<size; j++){
			connector = strchr(str[j], ';');
			if (connector != NULL){
				//erase the last character if ';'
				str[j][connector - str[j]] = '\0';
			}
			//check for && setting a flag to 1
			if (memcmp(str[j], "&&", 2) == 0){
				*glob_flag = 1;
				i = j;
				break;
			}
			//check for || setting a flag to 3
			if (memcmp(str[j], "||", 2) == 0){
				*glob_flag = 3;
				i = j;
				break;
			}

			//add flags to newstr
			newstr[aux] = str[j];
			aux++;
			i = j;

			if (connector != NULL) break;
			}

		int pid = fork();
		if (pid == -1){
			perror("fork() presented error");
			exit(1);
		}
		else if (pid == 0){
			if (-1 == execvp(newstr[0], newstr)){
				perror("There was an error");
				//flag 1 means, first command must be successfull to apply the second
				if (*glob_flag == 1) *glob_flag = 2;
				//flag 3 means, first command must be failed to apply the second
				//number 5 won't pass in the breaking loop
				if (*glob_flag == 3) *glob_flag = 5;
			}
			exit(1);
		}
		else if (pid>0){

			int status;

			wait(&status);
			if (-1 == status)
				perror("wait() presented error");
			else if (status>0){
				//flag 1 means, first command must be successfull to apply the second
				if (*glob_flag == 1){
					int flag2 = 0;
					for (int p = i; p<size; p++){
						//in case command fails look for a semicolon to reestart from there
						connector = strchr(str[p], ';');
						if (connector != NULL){
							i = p;
							//changing this flag will make the parent loop do not break because a semicolon was found
							flag2 = 1;
							break;
						}
					}
					//if there is no more semicolons parent loop will break
					if (flag2 == 0) *glob_flag = 2;
				}
				//flag 3 means, first command must be failed to apply the second
				//number 5 won't pass in the breaking loop
				if (*glob_flag == 3) *glob_flag = 5;
			}

		}

		// clear the vector newstr in order to execute new commands
		for (int k = 0; k<aux; k++)newstr[k] = '\0';

		//break loop due to a non valid previous command connected by &&
		if (*glob_flag == 2) break;
		//break loop due to a valid previous command connected by ||
		if (*glob_flag == 3) break;
	}
}

int main(){
	int index;
	string line;
	char * str[512];
	char * pch;

	while (true){
		do{
			//output login @ machine $
			prompt();
			getline(cin, line);
		} while (line[0] == '#');

		//look for '#', if find erase everything until the end of line
		size_t found = line.find('#');
		if (found != std::string::npos)
			line.erase(found, line.length() - found);

		//create a dynamic char that is a copy of input
		char * input = new char[line.length() + 1];
		strcpy(input, line.c_str());

		//built in function to finish program when typed 'EXIT'
		if (memcmp(input, "exit", 4) == 0) exit(0);

		index = 0;
		pch = strtok(input, " ");

		while (pch != NULL){
			str[index] = pch;
			pch = strtok(NULL, " ");
			index++;
		}

		str[index] = NULL;

		execute(str, index);

	}
	return 0;
}
<|endoftext|>


<commit_before>#include <string>
#include <sstream>
#include <unistd.h> // sysconf()?
#include <sys/sysinfo.h>
#include <linux/kernel.h> // SI_LOAD_SHIFT

#include "load.h"
#include "../luts.h"

std::string load_string( bool use_colors = false ) {
   std::ostringstream oss;

   float f = static_cast<float>(1 << SI_LOAD_SHIFT);

   struct sysinfo sinfo;
   sysinfo(&sinfo);

   if( use_colors ) {
      // Likely does not work on BSD, but not tested
      unsigned number_of_cpus = sysconf( _SC_NPROCESSORS_ONLN );

      float recent_load = sinfo.loads[0] / f;

      // colors range from zero to twice the number of cpu's
      // for the most recent load metric
      unsigned load_percent = static_cast< unsigned int >(
            recent_load / number_of_cpus * 0.5f * 100.0f );

      if( load_percent > 100 )
         load_percent = 100;

      oss << load_lut[load_percent];
   }

   // set precision so we get results like "0.22"
   oss.setf( std::ios::fixed );
   oss.precision(2);

   oss << sinfo.loads[0] / f << " " << sinfo.load[1] / f << " "
	 << sinfo.load[2] / f;

   if( use_colors )
      oss << "#[fg=default,bg=default]";

   return oss.str();
}
<commit_msg>Fixed typos in linux/load.cc<commit_after>#include <string>
#include <sstream>
#include <unistd.h> // sysconf()?
#include <sys/sysinfo.h>
#include <linux/kernel.h> // SI_LOAD_SHIFT

#include "load.h"
#include "../luts.h"

std::string load_string( bool use_colors = false ) {
   std::ostringstream oss;

   float f = static_cast<float>(1 << SI_LOAD_SHIFT);

   struct sysinfo sinfo;
   sysinfo(&sinfo);

   if( use_colors ) {
      // Likely does not work on BSD, but not tested
      unsigned number_of_cpus = sysconf( _SC_NPROCESSORS_ONLN );

      float recent_load = sinfo.loads[0] / f;

      // colors range from zero to twice the number of cpu's
      // for the most recent load metric
      unsigned load_percent = static_cast< unsigned int >(
            recent_load / number_of_cpus * 0.5f * 100.0f );

      if( load_percent > 100 )
         load_percent = 100;

      oss << load_lut[load_percent];
   }

   // set precision so we get results like "0.22"
   oss.setf( std::ios::fixed );
   oss.precision(2);

   oss << sinfo.loads[0] / f << " " << sinfo.loads[1] / f << " "
	 << sinfo.loads[2] / f;

   if( use_colors )
      oss << "#[fg=default,bg=default]";

   return oss.str();
}
<|endoftext|>


<commit_before>#include <cstdlib>
#include <sys/wait.h>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
//#include <stdio.h>
#include <errno.h>
//#include <stdlib.h>

using namespace std;

void connectors(string userinput, vector<int> &x, vector<int> &y, bool &first) {
	for(unsigned int i = 0; i < userinput.size() - 1; i++) {
		if((userinput.at(i) == '|') && (userinput.at(i + 1) == '|')) {
			x.push_back(0);
			y.push_back(i);
		}
		else if((userinput.at(i) == '&') && (userinput.at(i + 1) == '&')) {
			x.push_back(1);
			y.push_back(i);
		}
		else if((userinput.at(i) == ';')) {
			x.push_back(2);
			y.push_back(i);
		}
	}
	y.push_back(0);
}

int main() {
	string userinput = "";
	string login;
	if(!getlogin())
		perror("getlogin");
	else
		login = getlogin();
	char hostname[128];
	if(gethostname(hostname, sizeof hostname))
		perror("gethostname");

	char limits[5] = ";&| ";
	bool ext  = false;
	while(!ext) {
		cout << getlogin() << "@" << hostname << " $ ";
		char *command_a;
		char *command;
		getline(cin, userinput);
		command = new char[userinput.size()];
		vector<int> c_pat;
		vector<int> c_pos;
		bool first = false;
		connectors(userinput, c_pat, c_pos, first);
		int x = 0;
		int b = 0;
		int y = 0;
		char *arg[100000];
		while(c_pos.at(y) != 0)  {
			if(c_pat.size() == 0)
				strcpy(command, userinput.c_str());
			else
				strcpy(command, userinput.substr(x, c_pos.at(y) - x).c_str());
			command_a = strtok(command,limits);
			while(command_a != NULL) {
				arg[b] = command_a;
				command_a = strtok(NULL, limits);
				b++;
			}
			int i = fork();
			if(i ==  -1)
				perror("fork");
			if(i == 0) {
				if(execvp(arg[0], arg) == -1)
					perror("execvp");
				exit(0);
			}
			int status;
			wait(&status);
			for(int i = 0; i < 100; i++)
				cout << arg[i];
			x = c_pos.at(y);
			y++;
			b = 0;
		}
	}
	return 0;
}
<commit_msg>close to figuring the problem out<commit_after>#include <cstdlib>
#include <sys/wait.h>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
//#include <stdio.h>
#include <errno.h>
//#include <stdlib.h>

using namespace std;

void connectors(string userinput, vector<int> &x, vector<int> &y, bool &first) {
	for(unsigned int i = 0; i < userinput.size() - 1; i++) {
		if((userinput.at(i) == '|') && (userinput.at(i + 1) == '|')) {
			x.push_back(0);
			y.push_back(i);
		}
		else if((userinput.at(i) == '&') && (userinput.at(i + 1) == '&')) {
			x.push_back(1);
			y.push_back(i);
		}
		else if((userinput.at(i) == ';')) {
			x.push_back(2);
			y.push_back(i);
		}
	}
	y.push_back(0);
}

int main() {
	string userinput = "";
	string login;
	if(!getlogin())
		perror("getlogin");
	else
		login = getlogin();
	char hostname[128];
	if(gethostname(hostname, sizeof hostname))
		perror("gethostname");

	char limits[5] = ";&| ";
	bool ext  = false;
	while(!ext) {
		cout << getlogin() << "@" << hostname << " $ ";
		char *command_a;
		char *command;
		getline(cin, userinput);
		command = new char[userinput.size()];
		vector<int> c_pat;
		vector<int> c_pos;
		bool first = false;
		connectors(userinput, c_pat, c_pos, first);
		int x = 0;
		int b = 0;
		int y = 0;
		char *arg[100000];
		while(c_pos.at(y) != 0)  {
			if(c_pat.size() == 0)
				strcpy(command, userinput.c_str());
			else
				strcpy(command, userinput.substr(x, c_pos.at(y) - x).c_str());
			command_a = strtok(command,limits);
			cout << command_a[0];
			while(command_a != NULL) {
				arg[b] = command_a;
				command_a = strtok(NULL, limits);
				b++;
			}
			int i = fork();
			if(i ==  -1)
				perror("fork");
			if(i == 0) {
				if(execvp(arg[0], arg) == -1)
					perror("execvp");
				exit(0);
			}
			int status;
			wait(&status);
			x = c_pos.at(y);
			y++;
			b = 0;
		}
	}
	return 0;
}
<|endoftext|>