// Timer callback function
void timerCallback(int temp) {
	if(!turmite->pause) {
		turmite->run();
		glutTimerFunc(turmite->getTime(), timerCallback, 0);
	}
	glutPostRedisplay();
}
Example #2
0
void
context_t::insert(const std::string& name, std::unique_ptr<actor_t> service) {
    scoped_attributes_t guard(*m_log, attribute::set_t({logging::keyword::source() = "core"}));

    const actor_t& actor = *service;

    m_services.apply([&](service_list_t& list) {
        if(std::count_if(list.begin(), list.end(), match{name})) {
            throw cocaine::error_t("service '%s' already exists", name);
        }

        service->run();

        COCAINE_LOG_DEBUG(m_log, "service has been started")(
            "service", name
        );

        list.emplace_back(name, std::move(service));
    });

    // Fire off the signal to alert concerned subscribers about the service removal event.
    m_signals.invoke<context::service::exposed>(actor.prototype().name(), std::forward_as_tuple(
        actor.endpoints(),
        actor.prototype().version(),
        actor.prototype().root()
    ));
}
Example #3
0
 /// Executes a given task.
 void executeTask(std::unique_ptr<Task> task) {
     task->createKernels(_device);
     task->callConfigFunction(_device);
     task->run();
     task->callFinishFunction(_device);
     _device->finish();
 }
Example #4
0
Function *FunctionAST::codegen() {
  // Transfer ownership of the prototype to the FunctionProtos map, but keep a
  // reference to it for use below.
  auto &P = *Proto;
  FunctionProtos[Proto->getName()] = std::move(Proto);
  Function *TheFunction = getFunction(P.getName());
  if (!TheFunction)
    return nullptr;

  // Create a new basic block to start insertion into.
  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
  Builder.SetInsertPoint(BB);

  // Record the function arguments in the NamedValues map.
  NamedValues.clear();
  for (auto &Arg : TheFunction->args())
    NamedValues[Arg.getName()] = &Arg;

  if (Value *RetVal = Body->codegen()) {
    // Finish off the function.
    Builder.CreateRet(RetVal);

    // Validate the generated code, checking for consistency.
    verifyFunction(*TheFunction);

    // Run the optimizer on the function.
    TheFPM->run(*TheFunction);

    return TheFunction;
  }

  // Error reading body, remove function.
  TheFunction->eraseFromParent();
  return nullptr;
}
void keyboard (unsigned char key, int x, int y) 
{
	switch (key) {
		case 27: // Quit
			exit(0);
			break;

		case 's': // Start
		case 'i':
		case 'S':
		case 'I':
			glutPostRedisplay();
			turmite->setDrawFunction(0);
			turmite->pause=false;
			turmite->run();
			glutTimerFunc(turmite->getTime(), timerCallback, 0);
			break;

		case 'm': // ´Draw the 2 state
			glutPostRedisplay();
			turmite->setDrawFunction(1);			
			turmite->pause=false;
			turmite->run();
			glutTimerFunc(turmite->getTime(), timerCallback, 0);
			break;

		case 'p': // Pause/Restart
		case 'P':
			turmite->pause=true;
			break ;

		case 'r': // Re-initialize
			turmite->reinitialize();
			glutPostRedisplay();
			break;
		default:
			break ;
	}
}
Example #6
0
void Command::delegate(std::unique_ptr<Activity> activity) {
    assert(activity);

    connect(activity.get(), SIGNAL(finished()), this, SLOT(activityFinished()), Qt::QueuedConnection);

    ++activityCount_;

#ifdef NC_USE_THREADS
    activity->setAutoDelete(true);
    threadPool()->start(activity.release());
#else
    activity->run();
#endif
}
Example #7
0
Function *FunctionAST::codegen() {
  // Transfer ownership of the prototype to the FunctionProtos map, but keep a
  // reference to it for use below.
  auto &P = *Proto;
  FunctionProtos[Proto->getName()] = std::move(Proto);
  Function *TheFunction = getFunction(P.getName());
  if (!TheFunction)
    return nullptr;

  // If this is an operator, install it.
  if (P.isBinaryOp())
    BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();

  // Create a new basic block to start insertion into.
  BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
  Builder.SetInsertPoint(BB);

  // Record the function arguments in the NamedValues map.
  NamedValues.clear();
  for (auto &Arg : TheFunction->args()) {
    // Create an alloca for this variable.
    AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());

    // Store the initial value into the alloca.
    Builder.CreateStore(&Arg, Alloca);

    // Add arguments to variable symbol table.
    NamedValues[Arg.getName()] = Alloca;
  }

  if (Value *RetVal = Body->codegen()) {
    // Finish off the function.
    Builder.CreateRet(RetVal);

    // Validate the generated code, checking for consistency.
    verifyFunction(*TheFunction);

    // Run the optimizer on the function.
    TheFPM->run(*TheFunction);

    return TheFunction;
  }

  // Error reading body, remove function.
  TheFunction->eraseFromParent();

  if (P.isBinaryOp())
    BinopPrecedence.erase(Proto->getOperatorName());
  return nullptr;
}
Example #8
0
	int run()
	{
		std::clog << "Initializing ..." << std::endl;
		sigterm_.set<MyServer, &MyServer::terminate_handler>(this);
		sigterm_.start(SIGTERM);
		ev_unref(loop_);

		http_.reset(new x0::HttpServer(loop_));
		http_->requestHandler = std::bind(&MyServer::requestHandler, this, std::placeholders::_1);
		http_->setupListener("0.0.0.0", 3000);

		std::clog << "Running ..." << std::endl;
		int rv = http_->run();

		std::clog << "Quitting ..." << std::endl;
		return rv;
	}
Example #9
0
    virtual
    void
    setUp(int64_t) {
        context.reset(new cocaine::context_t(cocaine::config_t("cocaine-benchmark.conf"), "core"));
        reactor.reset(new boost::asio::io_service());

        context->insert("benchmark", std::make_unique<cocaine::actor_t>(
           *context,
            std::make_shared<boost::asio::io_service>(),
            std::make_unique<cocaine::test_service_t>()
        ));

        auto endpoints = context->locate("benchmark").get().endpoints();
        auto socket = std::make_unique<boost::asio::ip::tcp::socket>(*reactor);

        boost::asio::connect(*socket, endpoints.begin(), endpoints.end());

        service.connect(std::move(socket));
        chamber.reset(new boost::thread([this]{ reactor->run(); }));
    }
Example #10
0
bool OptionHandler::generateWaveformData(
    const boost::filesystem::path& input_filename,
    const boost::filesystem::path& output_filename,
    const Options& options)
{
    const std::unique_ptr<ScaleFactor> scale_factor = createScaleFactor(options);

    const boost::filesystem::path output_file_ext = output_filename.extension();

    const std::unique_ptr<AudioFileReader> audio_file_reader =
        createAudioFileReader(input_filename);

    if (audio_file_reader == nullptr) {
        error_stream << "Unknown file type: " << input_filename << '\n';
        return false;
    }

    if (!audio_file_reader->open(input_filename.c_str())) {
        return false;
    }

    WaveformBuffer buffer;
    WaveformGenerator processor(buffer, *scale_factor);

    if (!audio_file_reader->run(processor)) {
        return false;
    }

    assert(output_file_ext == ".dat" || output_file_ext == ".json");

    const int bits = options.getBits();

    if (output_file_ext == ".dat") {
        return buffer.save(output_filename.c_str(), bits);
    }
    else {
        return buffer.saveAsJson(output_filename.c_str(), bits);
    }
}
Example #11
0
int main(int argc, char **argv)
{
#ifndef WIN32
    if (!set_signal_handlers())
    {
        return -1;
    }
#endif

    log::info("Doozy server");
    
    int option;
    bool daemonize = false;
    std::string configFile;
    
    while ((option = getopt (argc, argv, "f:d")) != -1)
    {
        switch (option)
        {
        case 'f':
            configFile = optarg != nullptr ? optarg : "";
            break;
        case 'd':
            daemonize = true;
            break;
        case '?':
        default:
            log::error("invalid arguments");
            //printUsage();
            return -1;
        }
    }

    serverInstance.reset(new doozy::Server());
    serverInstance->run("");
    log::info("Bye");
    return 0;
}
Example #12
0
/// Main function of the cheapl server executable. This will start the cheapl xPL service and execute requests.
/// This program currently takes two optional arguments:
/// # the directory where wav-files can be found that should be played to the RF-connected sound card.
/// # the name of the alsa sound device to which the sequences should be sent.
int main( int argc, char *argv[])
{
    int result = 0;
    try
    {
        atexit(exit_handler);
        config conf = get_config( argc, argv);
        service_ptr.reset( new xpl::cheapl_service{ conf.soundfile_directory, conf.usb_device, conf.application_id, conf.application_version});
        service_ptr->run();
    }
    catch (std::exception &e)
    {
        std::cerr << "something went wrong: " << e.what() << std::endl;
        result = -1;
    }
    catch (boost::system::error_code &e)
    {
        std::cerr << "system error: " << e.message() << std::endl;
        result = -2;
    }

	return result;
}
Example #13
0
int main( int argc, char* args[] ){
	
	app = std::make_unique<Application>( 1024, 600, update );
	app->showFps = true;
	stage = std::make_unique<Stage>();
	stage->setViewport( { 0, 0, 100, 100 } );
	app->addStage( stage.get() );
	
	for ( int i = 0; i < 10000; i++ ) {
		std::unique_ptr<Sprite> s = std::make_unique<Sprite>();
		s->position->x = getRand( 0, 1024 );
		s->position->y = getRand( 0, 600 );
		s->fromImage( "res/piece_vibrance.png" );
		stage->addChild( s.get() );
		vsprites.push_back( std::move( s ) );
	}
	
	app->run();
	vsprites.clear();
	app.reset();
	stage.reset();
    return EXIT_SUCCESS;
}
Example #14
0
    running_t(context_t& context,
              const manifest_t& manifest,
              const profile_t& profile,
              const logging::log_t* log,
              std::shared_ptr<asio::io_service> loop):
        log(log)
    {
        // Create the Overseer - slave spawner/despawner plus the event queue dispatcher.
        overseer.reset(new overseer_t(context, manifest, profile, loop));

        // Create the event balancer.
        // TODO: Rename method.
        overseer->balance(std::make_unique<load_balancer_t>(overseer));

        // Create a TCP server and publish it.
        COCAINE_LOG_TRACE(log, "publishing application service with the context");
        context.insert(manifest.name, std::make_unique<actor_t>(
            context,
            std::make_shared<asio::io_service>(),
            std::make_unique<app_dispatch_t>(context, manifest.name, overseer)
        ));

        // Create an unix actor and bind to {manifest->name}.{pid} unix-socket.
        COCAINE_LOG_TRACE(log, "publishing worker service with the context");
        engine.reset(new unix_actor_t(
            context,
            manifest.endpoint,
            std::bind(&overseer_t::prototype, overseer),
            [](io::dispatch_ptr_t handshaker, std::shared_ptr<session_t> session) {
                std::static_pointer_cast<const handshaker_t>(handshaker)->bind(session);
            },
            std::make_shared<asio::io_service>(),
            std::make_unique<hostess_t>(manifest.name)
        ));
        engine->run();
    }
Example #15
0
        static void cycle(std::unique_ptr<Runnable> runnable)
        {
            try
            {
                ttl::Logger<Log> system_log("system.log", true, std::ios::trunc | std::ios::out);

                do
                {
                    try
                    {
                        if (runnable)
                        {
                            Sti_t cycle_count = 0;
                            std::unique_ptr<Runnable> holder;
                            system_log << Timestamp << "Created temporary\n";

                            do
                            {
                                if (cycle_count == std::numeric_limits<Sti_t>::max())
                                {
                                    cycle_count = 0;
                                    system_log << Timestamp << "Cycle count resetted\n";
                                }
                                system_log << Timestamp << "Entering cycle " << ++cycle_count << "\n";
                                system_log << Timestamp << "Pointer valid, calling run()\n";
                                holder = runnable->run();
                                system_log << Timestamp << "Returned from run()\n";
                                if (holder.get() == runnable.get())
                                {
                                    holder.release();
                                    system_log << Timestamp << "this returned, recalling run()\n";
                                    continue;
                                }
                                runnable = std::move(holder);
                                system_log << Timestamp << "Resetted, checking validity\n";
                            }
                            while (runnable);
                            system_log << Timestamp << "Pointer invalidated, returning\n";
                        }
                        else
                        {
                            system_log << Timestamp << "Pointer invalid, returning\n";
                        }
                    }
                    catch (Runnable *r)
                    {
                        system_log << Timestamp << "An object of ttl::Runnable was caught\n";
                        runnable.reset(r);
                    }
                    catch (std::exception &e)
                    {
                        system_log << Timestamp << "An object of std::exception was caught:\n\twhat(): " << e.what() << "\n";
                        runnable.reset(nullptr);
                    }
                    catch (...)
                    {
                        system_log << Timestamp << "An unknown exception was caught\n";
                        runnable.reset(nullptr);
                    }
                } while (runnable);
            }
            catch (std::exception &e)
            {
                std::cerr << getTimeStamp() << "The logger failed to initialize\n\twhat(): " << e.what() << "\n";
            }
            catch (...)
            {
                std::cerr << getTimeStamp() << "The logger failed to initialize due to an unknown exception\n";
            }
        }
Example #16
0
int main(int argc, char** argv)
{
    std::string configFile = _TRINITY_BNET_CONFIG;
    auto vm = GetConsoleArguments(argc, argv, configFile);
    // exit if help is enabled
    if (vm.count("help"))
        return 0;

    std::string configError;
    if (!sConfigMgr->LoadInitial(configFile, configError))
    {
        printf("Error in config file: %s\n", configError.c_str());
        return 1;
    }

    TC_LOG_INFO("server.bnetserver", "%s (bnetserver)", _FULLVERSION);
    TC_LOG_INFO("server.bnetserver", "<Ctrl-C> to stop.\n");
    TC_LOG_INFO("server.bnetserver", "Using configuration file %s.", configFile.c_str());
    TC_LOG_INFO("server.bnetserver", "Using SSL version: %s (library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION));
    TC_LOG_INFO("server.bnetserver", "Using Boost version: %i.%i.%i", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100);

    // bnetserver PID file creation
    std::string pidFile = sConfigMgr->GetStringDefault("PidFile", "");
    if (!pidFile.empty())
    {
        if (uint32 pid = CreatePIDFile(pidFile))
            TC_LOG_INFO("server.bnetserver", "Daemon PID: %u\n", pid);
        else
        {
            TC_LOG_ERROR("server.bnetserver", "Cannot create PID file %s.\n", pidFile.c_str());
            return 1;
        }
    }

    int32 worldListenPort = sConfigMgr->GetIntDefault("WorldserverListenPort", 1118);
    if (worldListenPort < 0 || worldListenPort > 0xFFFF)
    {
        TC_LOG_ERROR("server.bnetserver", "Specified worldserver listen port (%d) out of allowed range (1-65535)", worldListenPort);
        return 1;
    }

    // Initialize the database connection
    if (!StartDB())
        return 1;

    sIpcContext->Initialize();

    _ioService.reset(new boost::asio::io_service());

    // Get the list of realms for the server
    sRealmList->Initialize(*_ioService, sConfigMgr->GetIntDefault("RealmsStateUpdateDelay", 10), worldListenPort);

    // Start the listening port (acceptor) for auth connections
    int32 bnport = sConfigMgr->GetIntDefault("BattlenetPort", 1119);
    if (bnport < 0 || bnport > 0xFFFF)
    {
        TC_LOG_ERROR("server.bnetserver", "Specified battle.net port (%d) out of allowed range (1-65535)", bnport);
        StopDB();
        return 1;
    }

    std::string bindIp = sConfigMgr->GetStringDefault("BindIP", "0.0.0.0");

    sSessionMgr.StartNetwork(*_ioService, bindIp, bnport);

    // Set signal handlers
    boost::asio::signal_set signals(*_ioService, SIGINT, SIGTERM);
#if PLATFORM == PLATFORM_WINDOWS
    signals.add(SIGBREAK);
#endif
    signals.async_wait(SignalHandler);

    // Set process priority according to configuration settings
    SetProcessPriority("server.bnetserver");

    // Enabled a timed callback for handling the database keep alive ping
    _dbPingInterval = sConfigMgr->GetIntDefault("MaxPingTime", 30);
    _dbPingTimer.reset(new boost::asio::deadline_timer(*_ioService));
    _dbPingTimer->expires_from_now(boost::posix_time::minutes(_dbPingInterval));
    _dbPingTimer->async_wait(KeepDatabaseAliveHandler);

    sComponentMgr->Load();
    sModuleMgr->Load();

    // Start the io service worker loop
    _ioService->run();

    _dbPingTimer->cancel();

    sSessionMgr.StopNetwork();

    sIpcContext->Close();

    sRealmList->Close();

    // Close the Database Pool and library
    StopDB();

    TC_LOG_INFO("server.bnetserver", "Halting process...");

    signals.clear();

    _ioService.reset();
    return 0;
}
Example #17
0
 void prepare(PassRunner* runner, Module *module) override {
   allocator = runner->allocator;
   namer = std::unique_ptr<NameManager>(new NameManager());
   namer->run(runner, module);
 }
Example #18
0
int main(int argc, char *argv[]) {
    int fullscreen_flag = 0;
    std::string style;

    const struct option long_options[] = {
        {"fullscreen", no_argument, &fullscreen_flag, 'f'},
        {"style", required_argument, 0, 's'},
        {0, 0, 0, 0}
    };

    while (true) {
        int option_index = 0;
        int opt = getopt_long(argc, argv, "fs:", long_options, &option_index);
        if (opt == -1) break;
        switch (opt)
        {
        case 0:
            if (long_options[option_index].flag != 0)
                break;
        case 'f':
            // handle fullscreen_flag
            break;
        case 's':
            style = std::string("asset://") + std::string(optarg);
        default:
            break;
        }

    }

    // sigint handling
    struct sigaction sigIntHandler;
    sigIntHandler.sa_handler = quit_handler;
    sigemptyset(&sigIntHandler.sa_mask);
    sigIntHandler.sa_flags = 0;
    sigaction(SIGINT, &sigIntHandler, NULL);

    view = mbgl::util::make_unique<GLFWView>();

    mbgl::SQLiteCache cache("/tmp/mbgl-cache.db");
    mbgl::DefaultFileSource fileSource(&cache);
    mbgl::Map map(*view, fileSource);

    // Load settings
    mbgl::Settings_JSON settings;
    map.setLatLngZoom(mbgl::LatLng(settings.latitude, settings.longitude), settings.zoom);
    map.setBearing(settings.bearing);
    map.setDebug(settings.debug);

    // Set access token if present
    const char *token = getenv("MAPBOX_ACCESS_TOKEN");
    if (token == nullptr) {
        mbgl::Log::Warning(mbgl::Event::Setup, "no access token set. mapbox.com tiles won't work.");
    } else {
        map.setAccessToken(std::string(token));
    }

    // Load style
    if (style.empty()) {
        style = std::string("asset://") + std::string("styles/bright-v7.json");
    }

    map.setStyleURL(style);

    int ret = view->run();

    // Save settings
    mbgl::LatLng latLng = map.getLatLng();
    settings.latitude = latLng.latitude;
    settings.longitude = latLng.longitude;
    settings.zoom = map.getZoom();
    settings.bearing = map.getBearing();
    settings.debug = map.getDebug();
    settings.save();

    return ret;
}
Example #19
0
// ----------------------------------------------------------------------------
void run(const options& options)
{
  dm::init();

  loop_.reset(new dripcore::loop);

  jsonrpc::service service;
  player           player(options.audio_device);

  if ( signal(SIGPIPE, sig_handler) == SIG_ERR ) {
    std::cerr << "Error installing SIGPIPE handler!" << std::endl;
  }

  if ( signal(SIGINT, sig_handler) == SIG_ERR ) {
    std::cerr << "Error installing SIGINT handler!" << std::endl;
  }

  if ( signal(SIGTERM, sig_handler) == SIG_ERR ) {
    std::cerr << "Error installing SIGTERM handler!" << std::endl;
  }

  spotify_source_config sp_cfg{
    options.spotify_username,
    options.spotify_password,
  };

  player.add_source("spotify", std::make_shared<spotify_source>(sp_cfg));
  player.add_source("local", std::make_shared<local_source>());

  using std::placeholders::_1;
  service.add_method("player/play",          std::bind(&json_rpc::play,                std::ref(player), _1));
  service.add_method("player/queue",         std::bind(&json_rpc::queue,               std::ref(player), _1));
  service.add_method("player/skip",          std::bind(&json_rpc::skip,                std::ref(player), _1));
  service.add_method("player/stop",          std::bind(&json_rpc::stop,                std::ref(player), _1));
  service.add_method("player/state",         std::bind(&json_rpc::state,               std::ref(player), _1));
#if 0
  service.add_method("db/tags",          std::bind(&json_rpc::tags,                std::ref(player), _1));
  service.add_method("db/export-tracks", std::bind(&json_rpc::export_tracks,       std::ref(player), _1));
#endif
  service.add_method("db/index",             std::bind(&json_rpc::index,                _1));
  service.add_method("db/save",              std::bind(&json_rpc::save,                 _1));
  service.add_method("db/delete",            std::bind(&json_rpc::erase,                _1));
  service.add_method("db/import-tracks",     std::bind(&json_rpc::import_tracks,        _1));
  service.add_method("db/cover",             std::bind(&json_rpc::cover,                _1));
  service.add_method("db/get/artists",       std::bind(&json_rpc::get_artists,          _1));
  service.add_method("db/get/albums",        std::bind(&json_rpc::get_albums,           _1));
  service.add_method("db/set/album",         std::bind(&json_rpc::set_album,            _1));
  service.add_method("db/get/album/tracks",  std::bind(&json_rpc::get_album_tracks,     _1));
  service.add_method("db/get/tracks",        std::bind(&json_rpc::get_tracks,           _1));
  service.add_method("db/get/source_local",  std::bind(&json_rpc::get_source_local,     _1));
  service.add_method("db/set/source_local",  std::bind(&json_rpc::set_source_local,     _1));
  service.add_method("sources/local/scan",   std::bind(&json_rpc::sources_local_scan,   _1));
  service.add_method("sources/spotify/uris", std::bind(&json_rpc::sources_spotify_uris, _1));

  /////
  // Setup callback to get player state info. Note that the callback is
  // called from player thread context. The service send_notification method
  // will push a send notifition for each connection to be executed in dripcore
  // context.
  //
  player.set_state_info_callback([&](const player_state_info& info)
  {
    json::object params
    {
      { "state",  info.state },
      { "track",  info.track.to_json() },
      { "source", info.source }
    };

    service.send_notification(json_rpc_notification("player/event", params));
  });

  auto acceptor = std::make_shared<dripcore::acceptor>("0.0.0.0", 8212,
    [&](dripcore::socket client) {
      loop_->start(std::make_shared<jsonrpc::server::connection>(service, std::move(client)));
    });

  loop_->start(acceptor);
  loop_->run();

  std::cerr << "shutdown player!" << std::endl;

  player.shutdown();
}