• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C++ query函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中query函数的典型用法代码示例。如果您正苦于以下问题:C++ query函数的具体用法?C++ query怎么用?C++ query使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了query函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: DocumentListLoadedEvent

 void MongoShell::handle(ExecuteQueryResponse *event)
 {
     AppRegistry::instance().bus()->publish(new DocumentListLoadedEvent(this, event->resultIndex, event->queryInfo, query(), event->documents));
 }
开发者ID:Bych,项目名称:robomongo,代码行数:4,代码来源:MongoShell.cpp


示例2: notifyChange

 void notifyChange(const VarT & v) {
     for (auto & l : query(varsListeners, &v)) l->updateValue();
 }
开发者ID:edvorg,项目名称:cpp-react,代码行数:3,代码来源:vardispatcher.hpp


示例3: CLASS_D

		CLASS_D("tianlongsi") + "/benxiang" : 1,
		CLASS_D("tianlongsi") + "/bencan"   : 1,
		CLASS_D("tianlongsi") + "/benyin"   : 1,
        ]));
        setup();
}

void init()
{
        add_action("do_quit", "quit");
        add_action("do_quit", "exit");
}

string long()
{
        if (mapp(query("exits")))
                return query("long");

        return query("long") + "    现在室内剑气纵横,你来"
               "我往,杀个不停。\n";
}

int do_quit()
{
        object me;

        me = this_player();
        if (! mapp(query("exits")))
        {
                write("现在没有出路,你无法离开。\n");
                return 1;
开发者ID:mudchina,项目名称:nitan3,代码行数:31,代码来源:munitang.c


示例4: query

/*!
 * \brief Insert file details into database.
 *        If it is an audio file, read the metadata and insert
 *        that information at the same time.
 *
 *        If it is an image file, just insert the filename and
 *        type.
 *
 * \param filename Full path to file.
 *
 * \returns Nothing.
 */
void FileScanner::AddFileToDB(const QString &filename)
{
    QString extension = filename.section( '.', -1 ) ;
    QString directory = filename;
    directory.remove(0, m_startdir.length());
    directory = directory.section( '/', 0, -2);

    QString nameFilter = gCoreContext->GetSetting("AlbumArtFilter",
                                              "*.png;*.jpg;*.jpeg;*.gif;*.bmp");

    // If this file is an image, insert the details into the music_albumart table
    if (nameFilter.indexOf(extension.toLower()) > -1)
    {
        QString name = filename.section( '/', -1);

        MSqlQuery query(MSqlQuery::InitCon());
        query.prepare("INSERT INTO music_albumart SET filename = :FILE, "
                      "directory_id = :DIRID, imagetype = :TYPE;");
        query.bindValue(":FILE", name);
        query.bindValue(":DIRID", m_directoryid[
                            QString(directory.toUtf8()).toLower()]);
        query.bindValue(":TYPE", AlbumArtImages::guessImageType(name));

        if (!query.exec() || query.numRowsAffected() <= 0)
        {
            MythDB::DBError("music insert artwork", query);
        }
        return;
    }

    Decoder *decoder = Decoder::create(filename, NULL, NULL, true);

    if (decoder)
    {
        VERBOSE(VB_FILE, QString("Reading metadata from %1").arg(filename));
        Metadata *data = decoder->readMetadata();
        if (data) {

            QString album_cache_string;

            // Set values from cache
            int did = m_directoryid[QString(directory.toUtf8()).toLower()];
            if (did > 0)
                data->setDirectoryId(did);

            int aid = m_artistid[QString(data->Artist().toUtf8()).toLower()];
            if (aid > 0)
            {
                data->setArtistId(aid);

                // The album cache depends on the artist id
                album_cache_string = data->getArtistId() + "#"
                    + QString(data->Album().toUtf8()).toLower();

                if (m_albumid[album_cache_string] > 0)
                    data->setAlbumId(m_albumid[album_cache_string]);
            }

            int gid = m_genreid[QString(data->Genre().toUtf8()).toLower()];
            if (gid > 0)
                data->setGenreId(gid);

            // Commit track info to database
            data->dumpToDatabase();

            // Update the cache
            m_artistid[QString(data->Artist().toUtf8()).toLower()] =
                data->getArtistId();

            m_genreid[QString(data->Genre().toUtf8()).toLower()] =
                data->getGenreId();

            album_cache_string = data->getArtistId() + "#"
                + QString(data->Album().toUtf8()).toLower();
            m_albumid[album_cache_string] = data->getAlbumId();
            delete data;
        }

        delete decoder;
    }
}
开发者ID:Cougar,项目名称:mythtv,代码行数:93,代码来源:filescanner.cpp


示例5: EasyRecordList

QTSS_Error EasyRecordList(Easy_RecordList_Params* inParams)
{
	EasyRecordQuery query(EasyRecordSession::sLocalRecordPath, inParams->inStreamName);
	query.List(inParams->inBeginTime, inParams->inEndTime, inParams->outRecords);
	return QTSS_NoErr;
}
开发者ID:EricChen2013,项目名称:EasyRMS,代码行数:6,代码来源:EasyRecordModule.cpp


示例6: file

bool ChatLogger::init(QString jid)
{
    Utilities::logData("Initializing logger for " + jid);
    this->jid = jid;

    QDir home = QDir::home();
    QFile file(home.path() + LOGS_DIR + jid.left(jid.indexOf("@")) + LOG_EXTENSION);

    bool logAvailable = file.exists();

    // Initialization of databases
    db = QSqlDatabase::addDatabase("QSQLITE",jid);

    db.setDatabaseName(file.fileName());

    if (!db.open())
     return false;

    if (!logAvailable)
    {
        QSqlQuery query(db);

        query.exec("create table log ("
                   "localid integer primary key autoincrement,"
                   "name varchar(256),"
                   "from_me boolean,"
                   "timestamp integer not null,"
                   "id varchar(20) not null,"
                   "type integer not null,"
                   "data varchar(65535),"
                   "thumb_image varchar(256),"
                   "status integer not null,"
                   "media_url varchar(256),"
                   "media_mime_type varchar(20),"
                   "media_wa_type integer,"
                   "media_size integer,"
                   "media_name varchar(256),"
                   "media_duration_seconds integer,"
                   "local_file_uri varchar(512),"
                   "live boolean,"
                   "latitude real,"
                   "longitude real,"
                   "media_caption varchar(160),"
                   "msg_count integer,"
                   "msg_delivered varchar(8192),"
                   "msg_read varchar(8192)"
                   ")");

        query.exec("create table settings ("
                   "version integer"
                   ")");

        query.exec("insert into settings (version) values (" +
                   QString::number(LOG_VERSION) + ")");

        lastId = -1;
    }
    else
    {
        QSqlQuery query(db);

        // Check the DB is the current version

        query.prepare("select version from settings");
        query.exec();

        if (query.next())
        {
            int version = query.value(0).toInt();

            if (version == 1)
            {
                // Upgrade it to version 2

                Utilities::logData("Upgrading log " + jid + " to version 2");

                query.prepare("alter table log add column local_file_uri varchar(512)");
                query.exec();
                query.prepare("update settings set version=2");
                query.exec();

                version = 2;
                query.prepare("update settings set version="+
                              QString::number(version));
                query.exec();
            }

            if (version == 2)
            {
                // Upgrade it to version 3

                Utilities::logData("Upgrading log " + jid + " to version " +
                                   QString::number(LOG_VERSION));

                query.prepare("alter table log add column live boolean");
                query.exec();
                query.prepare("alter table log add column latitude real");
                query.exec();
                query.prepare("alter table log add column longitude real");
                query.exec();
//.........这里部分代码省略.........
开发者ID:aeickho,项目名称:yappari,代码行数:101,代码来源:chatlogger.cpp


示例7: io_service_pool_

  //--------------------------------------------------------------------------------
  Server::Server(std::size_t        io_service_pool_size,
                 const std::string& application_id,
                 const std::string& application_instance,
                 bool               runAsDaemon          /*= true*/,
                 const std::string& config_root_path     /*= ""*/,
                 const std::string& address              /*= "get_from_config"*/,
                 const std::string& port                 /*= "get_from_config"*/)
    : io_service_pool_   (io_service_pool_size),
      stop_signals_      (io_service_pool_.get_io_service()),
      log_reopen_signals_(io_service_pool_.get_io_service()),
      acceptor_          (io_service_pool_.get_io_service()),
      new_connection_    (),
      request_router_    ()
  {
    if (createLockFile(application_id, application_instance)) {

      std::cerr << "Lock file created for: [" << application_id << "] [" << application_instance << "]" << std::endl;

      if(runAsDaemon) {
        std::cerr << "Running as Daemon." << std::endl;
        becomeDaemonProcess();
      }

      signalRegistrations();
      std::cerr << "Signal registration completed." << std::endl;

      Config::instance(application_id, application_instance, config_root_path);
      std::cerr << "Configuration instance created." << std::endl;

      initializeLogging((!runAsDaemon));
      std::cerr << "Initialized Logging." << std::endl;

      // create the stats keeper instance here. So that it's available as soon as the server is constructed.
      StatsKeeper::instance(Config::instance()->get<unsigned long int>("kcc-stats.gather-period" ,300),
                            Config::instance()->get<unsigned long int>("kcc-stats.history-length",12));
      std::cerr << "Initialized StatsKeeper." << std::endl;

      ErrorStateList::instance();   // same goes for the error state list.
      std::cerr << "Initialized ErrorStateList." << std::endl;

      initialize_standard_handlers();
      std::cerr << "Initialized Standard Handlers." << std::endl;

      boost::asio::ip::tcp::resolver        resolver(acceptor_.get_io_service()); // Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR).
      std::cerr << "Initialized resolver." << std::endl;

      boost::asio::ip::tcp::resolver::query query(Config::instance()->get<std::string>("kcc-server.address"),
                                                  Config::instance()->get<std::string>("kcc-server.port"));
      std::cerr << "Initialized query object." << std::endl;

      boost::asio::ip::tcp::endpoint        endpoint = *resolver.resolve(query);
      std::cerr << "Initialized endpoint." << std::endl;

      acceptor_.open(endpoint.protocol());
      std::cerr << "Acceptor opened." << std::endl;

      acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
      std::cerr << "Acceptor options set." << std::endl;

      acceptor_.bind(endpoint);
      std::cerr << "Acceptor bound." << std::endl;

      acceptor_.listen();

      std::cerr << "Server started, now accepting connections." << std::endl;
      start_accept();
      std::cerr << "Server Ready." << std::endl;
    } else {
      std::cerr << "Could not create Lockfile for this appid and instance: ["
                << lockFilePath.native()
                << "]"
                << std::endl
                << "If this message is not preceded by a message indicating that a lock file already exists, "
                << "you most likely have a permissions problem, or the directory in which you wish to create lock files, "
                << "does not exist."
                << std::endl;

      throw std::runtime_error("Could not create lock file: Terminating.");
    }
  }
开发者ID:TheLastCylon,项目名称:kisscpp,代码行数:81,代码来源:server.cpp


示例8: test_query

void test_query(){



 cs_init();



 char * dummy1 = "one_is_1";

 char * dummy2 = "two_is_2";

 char * dummy3 = "three_is_3";

 char * dummy4 = "four_is_4";

 char * dummy5 = "five_is_5";



 add_message(dummy1);

 add_message(dummy2);

 add_message(dummy3);

 add_message(dummy4);

 add_message(dummy5);



 printf("Query (7,8):\n");

 UnityAssertEqualNumber((_U_SINT)((0)), (_U_SINT)((query(7,8))), (((void *)0)), (_U_UINT)88, UNITY_DISPLAY_STYLE_INT);



 printf("\nQuery (1,3):\n");

 UnityAssertEqualNumber((_U_SINT)((1)), (_U_SINT)((query(1,3))), (((void *)0)), (_U_UINT)91, UNITY_DISPLAY_STYLE_INT);



 printf("\nQuery (4,5):\n");

 UnityAssertEqualNumber((_U_SINT)((1)), (_U_SINT)((query(4,5))), (((void *)0)), (_U_UINT)94, UNITY_DISPLAY_STYLE_INT);



 printf("\nQuery (2,6):\n");

 UnityAssertEqualNumber((_U_SINT)((1)), (_U_SINT)((query(2,6))), (((void *)0)), (_U_UINT)97, UNITY_DISPLAY_STYLE_INT);



 printf("\nQuery (1,1000):");

 UnityAssertEqualNumber((_U_SINT)((1)), (_U_SINT)((query(1,1000))), (((void *)0)), (_U_UINT)100, UNITY_DISPLAY_STYLE_INT);



}
开发者ID:ricardoferro390,项目名称:PSis,代码行数:63,代码来源:test_chat_storage.c


示例9: getFileContents

bool InitDriveThread::method_resizePartitions()
{
    int newStartOfRescuePartition = getFileContents("/sys/class/block/mmcblk0p1/start").trimmed().toInt();
    int newSizeOfRescuePartition  = sizeofBootFilesInKB()/1000 + 100;

    if (!umountSystemPartition())
    {
        emit error(tr("Error unmounting system partition."));
        return false;
    }

    if (!QFile::exists("/dev/mmcblk0p1"))
    {
        // SD card does not have a MBR.

        // Warn user that their SD card does not have an MBR and ask
        // if they would like us to create one for them
        QMessageBox::StandardButton answer;
        emit query(tr("Would you like NOOBS to create one for you?\nWARNING: This will erase all data on your SD card"),
                   tr("Error: No MBR present on SD Card"),
                   &answer);

        if(answer == QMessageBox::Yes)
        {
            emit statusUpdate(tr("Zeroing partition table"));
            if (!zeroMbr())
            {
                emit error(tr("Error zero'ing MBR/GPT. SD card may be broken or advertising wrong capacity."));
                return false;
            }

            // Create MBR containing single FAT partition
            emit statusUpdate(tr("Writing new MBR"));
            QProcess proc;
            proc.setProcessChannelMode(proc.MergedChannels);
            proc.start("/usr/sbin/parted /dev/mmcblk0 --script -- mktable msdos mkpartfs primary fat32 8192s -1");
            proc.waitForFinished(-1);
            if (proc.exitCode() != 0)
            {
                // Warn user if we failed to create an MBR on their card
                emit error(tr("Error creating MBR")+"\n"+proc.readAll());
                return false;
            }
            qDebug() << "Created missing MBR on SD card. parted output:" << proc.readAll();

            // Advise user that their SD card has now been formatted
            // suitably for installing NOOBS and that they will have to
            // re-copy the files before rebooting
            emit error(tr("SD card has now been formatted ready for NOOBS installation. Please re-copy the NOOBS files onto the card and reboot"));
            return false;
        }
        else
        {
            emit error(tr("SD card has not been formatted correctly. Please reformat using the SD Association Formatting Tool and try again."));
            return false;
        }

    }

    emit statusUpdate(tr("Removing partitions 2,3,4"));

    QFile f("/dev/mmcblk0");
    f.open(f.ReadWrite);
    // Seek to partition entry 2
    f.seek(462);
    // Zero out partition 2,3,4 to prevent parted complaining about invalid constraints
    f.write(QByteArray(16*3, '\0'));
    f.flush();
    // Tell Linux to re-read the partition table
    ioctl(f.handle(), BLKRRPART);
    f.close();
    QThread::msleep(500);

    emit statusUpdate(tr("Resizing FAT partition"));

    /* Relocating the start of the FAT partition is a write intensive operation
     * only move it when it is not aligned on a MiB boundary already */
    if (newStartOfRescuePartition < 2048 || newStartOfRescuePartition % 2048 != 0)
    {
        newStartOfRescuePartition = 8192; /* 4 MiB */
    }

    QString cmd = "/usr/sbin/parted --script /dev/mmcblk0 resize 1 "+QString::number(newStartOfRescuePartition)+"s "+QString::number(newSizeOfRescuePartition)+"M";
    qDebug() << "Executing" << cmd;
    QProcess p;
    p.setProcessChannelMode(p.MergedChannels);
    p.start(cmd);
    p.closeWriteChannel();
    p.waitForFinished(-1);

    if (p.exitCode() != 0)
    {
        emit error(tr("Error resizing existing FAT partition")+"\n"+p.readAll());
        return false;
    }
    qDebug() << "parted done, output:" << p.readAll();
    QThread::msleep(500);

    emit statusUpdate(tr("Creating extended partition"));

//.........这里部分代码省略.........
开发者ID:Akkiesoft,项目名称:noobs,代码行数:101,代码来源:initdrivethread.cpp


示例10: locker

bool PersistentStore::init()
{
    QMutexLocker locker(&_mutex);

    // Get application data directory and database filename.
    QSettings settings;
    QString   appdata = settings.value("app/app_data").toString();
    if(appdata.isEmpty())
    {
        DEBUG << "Error creating the PersistentStore: app.appdata not set.";
        return false;
    }
    bool      create = false;
    QString   dbUrl(appdata + QDir::separator() + DEFAULT_DBNAME);
    QFileInfo dbFileInfo(dbUrl);

    // Initialize database object.
    _db = _db.addDatabase("QSQLITE", "tarsnap");
    _db.setConnectOptions("QSQLITE_OPEN_URI");
    _db.setDatabaseName(dbUrl);

    // Determine whether to try to open the database.
    if(!dbFileInfo.exists())
    {
        create = true;
    }
    else if(!dbFileInfo.isFile() || !dbFileInfo.isReadable())
    {
        DEBUG
            << "Error creating the PersistentStore: DB file is not accessible "
            << dbUrl;
        return false;
    } // Database file exists and is readable; attempt to open.
    else if(!_db.open())
    {
        DEBUG << "Error opening the PersistentStore DB: "
              << _db.lastError().text();
        return false;
    }
    else
    {
        // Successfully opened database.
        QStringList tables = _db.tables();
        // Is the database valid?
        if(!tables.contains("archives", Qt::CaseInsensitive))
        {
            _db.close();
            DEBUG << "Invalid PersistentStore DB found. Attempting to recover.";
            QString newName(dbUrl + "." +
                            QString::number(QDateTime::currentMSecsSinceEpoch()));
            if(!QFile::rename(dbUrl, newName))
            {
                DEBUG << "Failed to rename current invalid PersistentStore DB. "
                         "Please manually clean up the DB directory "
                      << appdata;
                return false;
            }
            create = true;
        }
        else
        {
            // Check the database version, and upgrade if necessary.
            if(!tables.contains("version", Qt::CaseInsensitive))
            {
                if(!upgradeVersion0())
                {
                    DEBUG << "Failed to upgrade PersistentStore DB. It's best "
                             "to start from scratch by purging the existing DB "
                             "in "
                          << appdata;
                    return false;
                }
            }
            int       version = -1;
            QSqlQuery query(_db);
            if(query.exec("SELECT version FROM version"))
            {
                query.next();
                version = query.value(0).toInt();
            }
            else
            {
                DEBUG << "Failed to get current DB version: "
                      << query.lastError().text();
                return false;
            }
            if((version == 0) && upgradeVersion1())
            {
                DEBUG << "DB upgraded to version 1.";
                version = 1;
            }
            if((version == 1) && upgradeVersion2())
            {
                DEBUG << "DB upgraded to version 2.";
                version = 2;
            }
            if((version == 2) && upgradeVersion3())
            {
                DEBUG << "DB upgraded to version 3.";
                version = 3;
//.........这里部分代码省略.........
开发者ID:shinnok,项目名称:tarsnap-gui,代码行数:101,代码来源:persistentstore.cpp


示例11: main

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

	// variables
	SDL_Surface *screen; // pantalla
	SDL_Event event; // para los eventos de SDL (teclado y/o mouse)
	Uint8 *keystates = SDL_GetKeyState(NULL); // para detectar teclas mantenidas presionadas
	Uint8 salir = 0; // para determinar cuando se cierra la ventana
	int mouse_x=0, mouse_y=0; // coordenadas del mouse
	char info1[100]; // texto para mostrar informacion variada linea 1
	char info2[100]; // texto para mostrar informacion variada linea 2
	short int time; // variable para la hora
	short int ticks; // variable para mover elementos independiente de los FPS

	// cargar configuracion
	struct conf *conf = conf_load();
	if (!conf)
		return EXIT_FAILURE;

	// verificar a donde nos queremos conectar
	// se indicó el servidor como 1er parametro
	if(argc>=2) {
		free(conf->SERVER);
		conf->SERVER = malloc(strlen(argv[1]));
		strcpy(conf->SERVER, argv[1]);
	}
	// se indicó el puerto como 2do parametro
	if(argc>=3) {
		conf->PORT = atoi(argv[2]);
	}

	// conectar al servidor
	int connection = client_init(conf);
	if (!connection)
		return EXIT_FAILURE;
	// buffer para transferencia entre servidor y cliente
	char buffer[BUFFER_SIZE];

	// obtener id del jugador
	int playerID = atoi(query("get;id", connection));

	// recibir y actualizar configuraciones desde el servidor
	conf_update(conf, query("get;conf", connection));

	// inicializar sistema
	sdl_init(&screen);
	// cargar fuente
	TTF_Font *fuente = ttf_load(FONT_NAME, FONT_SIZE, FONT_STYLE);
	// cargar todos los posibles objetos de un mapa
	MapObject *mapobjects = mapobjects_load(screen);
	if (!mapobjects)
		return EXIT_FAILURE;
	// cargar mapa
	char **map = map_open(conf->MAP);
	if (!map)
		return EXIT_FAILURE;
	// cargar armas
	Weapon *weapons = weapons_load();
	if (!weapons)
		return EXIT_FAILURE;
	// crear personaje jugador
	Player *pj = player_create(playerID, conf->PLAYER_NAME, conf->PLAYER_CHARACTER, screen, weapons, conf);
	// asignar armas al personaje
	player_change_weapon(&pj, conf->WEAPON_PRIMARY, 1);
	player_change_weapon(&pj, conf->WEAPON_SECONDARY, 2);
	// ubicar personaje en el mapa
	player_set_position(&pj, map, -1, -1, mapobjects);

	// informar estado del usuario
	bzero(buffer, sizeof(buffer));
	sprintf(buffer, "info;%s;%s", conf->PLAYER_CHARACTER, conf->PLAYER_NAME);
	write(connection, buffer, strlen(buffer));

	// crear bots y ubicar en el mapa
	Player *bots = bots_create(screen, weapons, conf);
	int i;
	for(i=0; i<conf->BOTS; ++i) {
		Player *aux = &bots[i];
		player_set_position(&aux, map, -1, -1, mapobjects);
	}

	// guardar ticks
	ticks = SDL_GetTicks();
	// ciclo infinito para refrescar la imagen de la pantalla
	while (!salir) {

		// solicitar informacion de todos los jugadores (menos el mio)
		char *enemies = query("get;players", connection);

		// enviar posicion del jugador al servidor
		sprintf(buffer, "position;%d;%d", (int)(pj->y), (int)(pj->x));
		write(connection, buffer, strlen(buffer));
		
		// time
		time = SDL_GetTicks()/1000;
		// dibujar mapa
		map_draw(screen, map, mapobjects, conf->BACKGROUND);
		// revisar si existen eventos de SDL
		while (SDL_PollEvent(&event)) {
			// salir del programa
			if(event.type==SDL_QUIT) salir = 1;
//.........这里部分代码省略.........
开发者ID:estebandelaf,项目名称:ShootMe,代码行数:101,代码来源:shootme.c


示例12: turret_query

int vehicle::automatic_fire_turret( vehicle_part &pt )
{
    auto gun = turret_query( pt );
    if( gun.query() != turret_data::status::ready ) {
        return 0;
    }

    tripoint pos = global_part_pos3( pt );

    npc tmp;
    tmp.set_fake( true );
    tmp.name = rmp_format( _( "<veh_player>The %s" ), pt.name().c_str() );
    tmp.set_skill_level( gun.base()->gun_skill(), 8 );
    tmp.set_skill_level( skill_id( "gun" ), 4 );
    tmp.recoil = abs( velocity ) / 100 / 4;
    tmp.setpos( pos );
    tmp.str_cur = 16;
    tmp.dex_cur = 8;
    tmp.per_cur = 12;
    // Assume vehicle turrets are friendly to the player.
    tmp.attitude = NPCATT_FOLLOW;

    int area = aoe_size( gun.ammo_effects() );
    if( area > 0 ) {
        area += area == 1 ? 1 : 2; // Pad a bit for less friendly fire
    }

    tripoint targ = pos;
    auto &target = pt.target;
    if( target.first == target.second ) {
        // Manual target not set, find one automatically
        const bool u_see = g->u.sees( pos );
        int boo_hoo;

        // @todo calculate chance to hit and cap range based upon this
        int range = std::min( gun.range(), 12 );
        Creature *auto_target = tmp.auto_find_hostile_target( range, boo_hoo, area );
        if( auto_target == nullptr ) {
            if( u_see && boo_hoo ) {
                add_msg( m_warning, ngettext( "%s points in your direction and emits an IFF warning beep.",
                                              "%s points in your direction and emits %d annoyed sounding beeps.",
                                              boo_hoo ),
                         tmp.name.c_str(), boo_hoo );
            }
            return 0;
        }

        targ = auto_target->pos();
    } else if( target.first != target.second ) {
        // Target set manually
        // Make sure we didn't move between aiming and firing (it's a bug if we did)
        if( targ != target.first ) {
            target.second = target.first;
            return 0;
        }

        targ = target.second;
        // Remove the target
        target.second = target.first;
    } else {
        // Shouldn't happen
        target.first = target.second;
        return 0;
    }

    auto shots = gun.fire( tmp, targ );

    if( g->u.sees( pos ) && shots ) {
        add_msg( _( "The %1$s fires its %2$s!" ), name.c_str(), pt.name().c_str() );
    }

    return shots;
}
开发者ID:Reikim,项目名称:Cataclysm-DDA,代码行数:73,代码来源:turret.cpp


示例13: ok

bool ok (int *c, int *s, int p1, int p2){
    while (last < p2-p1) modify (c, s[last++], -1);
    return p1 != m && query (c, s[p2]-1) == low[p1] && query (c, s[p2]) == eq[p1];
}
开发者ID:Merlinhool,项目名称:ACM-Source-Code,代码行数:4,代码来源:SPOJ7022.cpp


示例14: query

void CepController::add(Cep cep)
{
    QSqlDatabase db = DBUtil::getDatabase();
    QSqlQuery query(db);

    QString cidade = cep.getCidade().getNome();
    QString bairro = cep.getBairro().getNome();
    QString endereco = cep.getEndereco().getNome();
    QString estado = cep.getEstado().getUF();
    int cepint = cep.getCep();

    query.prepare("insert into cidade (nome) VALUES (:nome)");
    query.bindValue(":nome", cidade);
    int cidade_id = 0;
    if(!query.exec()){
        query.prepare("select id from cidade where nome = :nome");
        query.bindValue(":nome", cidade);
        query.exec();
        query.next();
        cidade_id = query.value(0).toInt();
    }else{
        cidade_id = query.lastInsertId().toInt();
    }

    int bairro_id = 0;
    query.prepare("insert into bairro (nome) VALUES (:nome)");
    query.bindValue(":nome", bairro);
    if(!query.exec()){
        query.prepare("select id from bairro where nome = :nome");
        query.bindValue(":nome", bairro);
        query.exec();
        query.next();
        bairro_id = query.value(0).toInt();
    }else{
        bairro_id = query.lastInsertId().toInt();
    }

    int endereco_id = 0;
    query.prepare("insert into endereco (nome) VALUES (:nome)");
    query.bindValue(":nome", endereco);
    if(!query.exec()){
        query.prepare("select id from endereco where nome = :nome");
        query.bindValue(":nome", endereco);
        query.exec();
        query.next();
        endereco_id = query.value(0).toInt();
    }else{
        endereco_id = query.lastInsertId().toInt();
    }

    query.prepare("insert into cep (endereco_id,bairro_id,cidade_id,estado_uf,cep) VALUES (:endereco_id,:bairro_id,:cidade_id,:estado_uf,:cep)");
    query.bindValue(":endereco_id", endereco_id);
    query.bindValue(":bairro_id", bairro_id);
    query.bindValue(":cidade_id", cidade_id);
    query.bindValue(":estado_uf", estado);
    query.bindValue(":cep", cepint);

    if( !query.exec() )
    {
        qDebug() << query.lastError().text();
    }

}
开发者ID:coxande,项目名称:qsc,代码行数:63,代码来源:cepcontroller.cpp


示例15: location

void MusicSearchEngine::watchForChanges()
{
	// Gather all folders registered on music locations
	QFileInfoList dirs;
	for (QString musicPath : SettingsPrivate::instance()->musicLocations()) {
		QFileInfo location(musicPath);
		QDirIterator it(location.absoluteFilePath(), QDir::Dirs | QDir::Hidden | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
		while (it.hasNext()) {
			QString entry = it.next();
			QFileInfo qFileInfo(entry);
			dirs << qFileInfo;
		}
	}

	SqlDatabase *db = SqlDatabase::instance();
	db->open();
	db->exec("PRAGMA journal_mode = MEMORY");
	db->exec("PRAGMA synchronous = OFF");
	db->exec("PRAGMA temp_store = 2");
	db->exec("PRAGMA foreign_keys = 1");

	QStringList newFoldersToAddInLibrary;
	// Add folders that were not found first
	for (QFileInfo f : dirs) {
		QSqlQuery query(*db);
		query.setForwardOnly(true);
		query.prepare("SELECT * FROM filesystem WHERE path = ?");
		query.addBindValue(f.absoluteFilePath());
		if (query.exec() && !query.next()) {
			newFoldersToAddInLibrary << f.absoluteFilePath();
			QSqlQuery prepared(*db);
			prepared.setForwardOnly(true);
			prepared.prepare("INSERT INTO filesystem (path, lastModified) VALUES (?, ?)");
			prepared.addBindValue(f.absoluteFilePath());
			prepared.addBindValue(f.lastModified().toTime_t());
			prepared.exec();
		}
	}

	if (!newFoldersToAddInLibrary.isEmpty()) {
		this->doSearch(newFoldersToAddInLibrary);
	}

	// Process in reverse mode to clean cache: from database file and check if entry exists in database
	QSqlQuery cache("SELECT * FROM filesystem", *db);
	qDebug() << Q_FUNC_INFO << "SELECT * FROM filesystem";
	cache.setForwardOnly(true);
	if (cache.exec()) {
		QStringList oldLocations;
		while (cache.next()) {
			QDir d(cache.record().value(0).toString());
			d.exists();
			QFileInfo fileInfo(cache.record().value(0).toString());
			// Remove folder in database because it couldn't be find in the filesystem
			if (!fileInfo.exists()) {
				QSqlQuery deleteFromFilesystem(*db);
				deleteFromFilesystem.prepare("DELETE FROM filesystem WHERE path = ?");
				deleteFromFilesystem.addBindValue(fileInfo.absoluteFilePath());
				qDebug() << Q_FUNC_INFO << "DELETE FROM filesystem WHERE path = ?";

				if (deleteFromFilesystem.exec()) {
					oldLocations << fileInfo.absoluteFilePath();
				}
			}
		}
		qDebug() << Q_FUNC_INFO << oldLocations;
		if (!oldLocations.isEmpty()) {
			db->rebuild(oldLocations, QStringList());
		}
	}
}
开发者ID:sun-friderick,项目名称:Miam-Player,代码行数:71,代码来源:musicsearchengine.cpp


示例16: query

void CustomPriority::testSchedule(void)
{
    MythUIButtonListItem *item = m_prioritySpin->GetItemCurrent();
    if (!item)
        return;

    QString ttable = "powerpriority_tmp";

    MSqlQueryInfo dbcon = MSqlQuery::SchedCon();
    MSqlQuery query(dbcon);
    QString thequery;

    thequery = "SELECT GET_LOCK(:LOCK, 2);";
    query.prepare(thequery);
    query.bindValue(":LOCK", "DiffSchedule");
    if (!query.exec())
    {
        QString msg =
            QString("DB Error (Obtaining lock in testRecording): \n"
                    "Query was: %1 \nError was: %2 \n")
            .arg(thequery)
            .arg(MythDB::DBErrorMessage(query.lastError()));
        LOG(VB_GENERAL, LOG_ERR, msg);
        return;
    }

    thequery = QString("DROP TABLE IF EXISTS %1;").arg(ttable);
    query.prepare(thequery);
    if (!query.exec())
    {
        QString msg =
            QString("DB Error (deleting old table in testRecording): \n"
                    "Query was: %1 \nError was: %2 \n")
            .arg(thequery)
            .arg(MythDB::DBErrorMessage(query.lastError()));
        LOG(VB_GENERAL, LOG_ERR, msg);
        return;
    }

    thequery = QString("CREATE TABLE %1 SELECT * FROM powerpriority;")
                       .arg(ttable);
    query.prepare(thequery);
    if (!query.exec())
    {
        QString msg =
            QString("DB Error (create new table): \n"
                    "Query was: %1 \nError was: %2 \n")
            .arg(thequery)
            .arg(MythDB::DBErrorMessage(query.lastError()));
        LOG(VB_GENERAL, LOG_ERR, msg);
        return;
    }

    query.prepare(QString("DELETE FROM %1 WHERE priorityname = :NAME;")
                          .arg(ttable));
    query.bindValue(":NAME", m_titleEdit->GetText());

    if (!query.exec())
        MythDB::DBError("Test power search delete", query);

    thequery = QString("INSERT INTO %1 "
                       "(priorityname, recpriority, selectclause) "
                       "VALUES(:NAME,:VALUE,:CLAUSE);").arg(ttable);
    query.prepare(thequery);
    query.bindValue(":NAME", m_titleEdit->GetText());
    query.bindValue(":VALUE", item->GetText());
    query.bindValue(":CLAUSE", m_descriptionEdit->GetText());

    if (!query.exec())
        MythDB::DBError("Test power search insert", query);

    QString ltitle = tr("Power Priority");
    if (!m_titleEdit->GetText().isEmpty())
        ltitle = m_titleEdit->GetText();

    MythScreenStack *mainStack = GetMythMainWindow()->GetMainStack();
    ViewScheduleDiff *vsd = new ViewScheduleDiff(mainStack, ttable, 0, ltitle);

    if (vsd->Create())
        mainStack->AddScreen(vsd);
    else
        delete vsd;

    thequery = "SELECT RELEASE_LOCK(:LOCK);";
    query.prepare(thequery);
    query.bindValue(":LOCK", "DiffSchedule");
    if (!query.exec())
    {
        QString msg =
            QString("DB Error (free lock): \n"
                    "Query was: %1 \nError was: %2 \n")
            .arg(thequery)
            .arg(MythDB::DBErrorMessage(query.lastError()));
        LOG(VB_GENERAL, LOG_ERR, msg);
    }
}
开发者ID:garybuhrmaster,项目名称:mythtv,代码行数:96,代码来源:custompriority.cpp


示例17: main

int main(int argc, char* argv[])
{
	if (argc < 2)
	{
		std::cerr << "Insufficient number of arguments." << std::endl;
		usage(argv[0]);
		return 1;
	}

	try
	{
		namespace asio = boost::asio;

		std::string server_addr = argv[1];
		std::string server_port = argv[2];

		std::cout << "Connecting to " << server_addr << " on port " << server_port << std::endl;

		asio::io_service io_service;

		asio::ip::tcp::resolver resolver(io_service);
		asio::ip::tcp::resolver::query query(server_addr, server_port);
		asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

		asio::ip::tcp::socket socket(io_service);
		boost::asio::connect(socket, endpoint_iterator);

		std::ostringstream oss;
		for (;;)
		{
			boost::array<char, 1024> buf;
			boost::system::error_code error;

			const std::size_t len = socket.read_some(boost::asio::buffer(buf), error);
			if (error == boost::asio::error::eof)
			{
				break; // Connection closed cleanly by peer.
			}
			else if (error)
			{
				throw boost::system::system_error(error); // Some other error.
			}

			oss << std::string(buf.data(), len);
			//std::cout.write(buf.data(), len);
		}
		socket.close();

		if (oss.str().empty())
		{
			std::cout << "Nothing received" << std::endl;
		}
		else
		{
			boost::uint32_t sz;
			std::string meminfo;

			boost::tie(sz, meminfo) = unpack(oss.str().c_str());

			std::cerr << "MEMINFO: " << meminfo << std::endl;

			Json::Value root;   // will contains the root value after parsing
			Json::Reader reader;
			bool parse_ok = reader.parse(meminfo, root);
			if (!parse_ok)
			{
				std::cerr  << "Failed to parse configuration: " << reader.getFormattedErrorMessages() << std::endl;
				return 1;
			}

			long double mem_tot = 0;
			long double mem_avail = 0;
			std::istringstream iss;
			iss.str(root.get("MemTotal", "").asString());
			iss >> mem_tot;
			iss.str(root.get("MemAvailable", "").asString());
			iss >> mem_avail;
			std::cout << "MEMINFO => Tot: " << mem_tot << " kB, Avail: " << mem_avail << " kB" << std::endl;
		}
	}
	catch (std::exception const& e)
	{
		std::cerr << e.what() << std::endl;
		return 1;
	}
}
开发者ID:sguazt,项目名称:dcsxx-testbed,代码行数:86,代码来源:meminfo-cli.cpp


示例18: transaction

QSet<int> DirectoryDAO::relocateDirectory(const QString& oldFolder,
                                          const QString& newFolder) {
    // TODO(rryan): This method could use error reporting. It can fail in
    // mysterious ways for example if a track in the oldFolder also has a zombie
    // track location in newFolder then the replace query will fail because the
    // location column becomes non-unique.
    ScopedTransaction transaction(m_database);
    QSqlQuery query(m_database);
    query.prepare("UPDATE " % DIRECTORYDAO_TABLE % " SET " % DIRECTORYDAO_DIR %
                  "=:newFolder WHERE " % DIRECTORYDAO_DIR % " = :oldFolder");
    query.bindValue(":newFolder", newFolder);
    query.bindValue(":oldFolder", oldFo 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ queryHelper函数代码示例发布时间:2022-05-30
下一篇:
C++ quatRotate函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap