void SqliteTableModel::setQuery(const QString& sQuery, bool dontClearHeaders)
{
    // clear
    if(!dontClearHeaders)
        reset();

    if(!m_db->isOpen())
        return;

    m_sQuery = removeComments(sQuery).trimmed();

    // do a count query to get the full row count in a fast manner
    m_rowCount = getQueryRowCount();
    if(m_rowCount == -1)
    {
        m_valid = false;
        return;
    }

    // headers
    if(!dontClearHeaders)
    {
        m_headers.append(getColumns(sQuery));
    }

    // now fetch the first entries
    clearCache();
    fetchData(0, m_chunkSize);
    m_valid = true;

    emit layoutChanged();
}
Exemple #2
0
TiffEntry::TiffEntry(FileMap* f, uint32 offset, uint32 up_offset) {
  parent_offset = up_offset;
  own_data = NULL;
  empty_data = 0;
  file = f;
  unsigned short* p = (unsigned short*)f->getData(offset, 2);
  tag = (TiffTag)p[0];
  type = (TiffDataType)p[1];
  count = *(align1_int*)f->getData(offset + 4, 4);

  if (type > 13)
    ThrowTPE("Error reading TIFF structure. Unknown Type 0x%x encountered.", type);

  uint64 bytesize = (uint64)count << datashifts[type];
  if (bytesize > UINT32_MAX)
    ThrowTPE("TIFF entry is supposedly %llu bytes", bytesize);

  if (bytesize == 0) // Better return empty than NULL-dereference later
    data = (uchar8 *) &empty_data;
  else if (bytesize <= 4)
    data = f->getDataWrt(offset + 8, bytesize);
  else { // offset
    data_offset = *(align1_uint*)f->getData(offset + 8, 4);
    fetchData();
  }
#ifdef _DEBUG
  debug_intVal = 0xC0CAC01A;
  debug_floatVal = sqrtf(-1);

  if (type == TIFF_LONG || type == TIFF_SHORT)
    debug_intVal = getInt();
  if (type == TIFF_FLOAT || type == TIFF_DOUBLE)
    debug_floatVal = getFloat();
#endif
}
Exemple #3
0
TiffEntry::TiffEntry(FileMap* f, uint32 offset, uint32 up_offset) {
  parent_offset = up_offset;
  own_data = NULL;
  file = f;
  unsigned short* p = (unsigned short*)f->getData(offset);
  tag = (TiffTag)p[0];
  type = (TiffDataType)p[1];
  count = *(int*)f->getData(offset + 4);
  if (type > 13)
    ThrowTPE("Error reading TIFF structure. Unknown Type 0x%x encountered.", type);
  uint32 bytesize = count << datashifts[type];
  if (bytesize <= 4) {
    data = f->getDataWrt(offset + 8);
  } else { // offset
    data_offset = *(uint32*)f->getData(offset + 8);
    fetchData();
  }
#ifdef _DEBUG
  debug_intVal = 0xC0CAC01A;
  debug_floatVal = sqrtf(-1);

  if (type == TIFF_LONG || type == TIFF_SHORT)
    debug_intVal = getInt();
  if (type == TIFF_FLOAT || type == TIFF_DOUBLE)
    debug_floatVal = getFloat();
#endif
}
bool Bitmaszyna::getAccountInfo()
{
    struct json_object *json,*jtmp,*jtmp2,*jtmp3;
    struct array_list *arr,*arr2;
    int i,j;

    curl_mutex.lock();
    if (makeApiCall("accountInfo",&json,string("nonce=")+to_stringl(getctime()).toStdString()))
    {
        if (!fetchData(&json,&jtmp)) return(false);
        log(string(chunk.memory)+"\n");
        json_object_object_get_ex(json,"deposits",&jtmp);
        arr=json_object_get_array(jtmp);
        deposits.clear();
        for(i=0;i<arr->length;i++)
        {
            Deposit d;

            jtmp2=(struct json_object *)array_list_get_idx(arr,i);
            json_object_object_get_ex(jtmp2,"currency",&jtmp3);
            d.currency=json_object_get_string(jtmp3);
            json_object_object_get_ex(jtmp2,"bank_name",&jtmp3);
            d.bank_name=json_object_get_string(jtmp3);
            json_object_object_get_ex(jtmp2,"pay_to",&jtmp3);
            d.pay_to=json_object_get_string(jtmp3);
            json_object_object_get_ex(jtmp2,"acc_num",&jtmp3);
            d.acc_num=json_object_get_string(jtmp3);
            json_object_object_get_ex(jtmp2,"swift_code",&jtmp3);
            d.swift_code=json_object_get_string(jtmp3);
            json_object_object_get_ex(jtmp2,"transfer_title",&jtmp3);
            d.transfer_title=json_object_get_string(jtmp3);
            deposits.push_back(d);
        }
        json_object_object_get_ex(json,"withdrawalAccounts",&jtmp);
        arr=json_object_get_array(jtmp);
        for(j=0;j<arr->length;j++)
        {
            withdrawalaccounts[j].clear();
            arr2=json_object_get_array((struct json_object *)array_list_get_idx(arr,j));
            for(i=0;i<arr2->length;)
            {
                WithdrawalAccount w;
                jtmp2=(struct json_object *)array_list_get_idx(arr2,i);
                w.account=json_object_get_string(jtmp2);
                i++;
                jtmp2=(struct json_object *)array_list_get_idx(arr2,i);
                w.name=json_object_get_string(jtmp2);
                i++;
                if (w.account.size()>0) withdrawalaccounts[adjustCurrency(j)].push_back(w);
            }
        }
        json_object_put(json);
        logged=true;
        curl_mutex.unlock();
        return(true);
    }
    curl_mutex.unlock();
    return(false);
}
void QXmlInputSource_QtDShell::__override_fetchData(bool static_call)
{
    if (static_call) {
        QXmlInputSource::fetchData();
    } else {
        fetchData();
    }
}
Exemple #6
0
    int GoogleMapView::getMapTile(uint64 p_zoom, uint64 p_row, uint64 p_column, void** p_data, size_t* p_size) {
     
        void *data = NULL;
        size_t datasize = 0;

        String url = "";//cmd->baseUrl;
        
        int zoom = (int)p_zoom;
        
        
        uint64 pow2 = rho_math_pow2(zoom);
        
        double current_width_in_pixels = (double)(pow2 * (TILE_SIZE));
        double current_height_in_pixels = (double)(pow2 * (TILE_SIZE));
        
        double tile_center_x_in_pixels = (double)(p_column*(TILE_SIZE)+((TILE_SIZE)/2));
        double tile_center_y_in_pixels = (double)(p_row*(TILE_SIZE)+((TILE_SIZE)/2));
        
        double center_latitude = pixelsToDegreesY((uint64)tile_center_y_in_pixels, zoom);//((double)-90.0) + ((current_height_in_pixels - tile_center_y_in_pixels)/(current_height_in_pixels))*((double)180.0);
        double center_longitude = pixelsToDegreesX((uint64)tile_center_x_in_pixels, zoom);//((double)-180.0) + ((tile_center_x_in_pixels)/(current_width_in_pixels))*((double)360.0);
        
        
        // Make url
        char buf[1024];
        
        // Open Street Map
        //snprintf(buf, sizeof(buf), "http://a.tah.openstreetmap.org/Tiles/tile/%d/%d/%d.png", zoom, (int)p_column, (int)p_row);
        
        // Google Map
        snprintf(buf, sizeof(buf), "http://maps.googleapis.com/maps/api/staticmap?center=%f,%f&zoom=%d&size=256x280&scale=1&maptype=%s&format=png&sensor=false&mobile=true", center_latitude, center_longitude, zoom, mapType().c_str());
        
        // Google Map on Blackberry
        
        // StringBuffer url = new StringBuffer();
        // url.append("http://maps.google.com/maps/api/staticmap?");
        // url.append("center=" + Double.toString(latitude) + "," + Double.toString(longitude));
        // url.append("&zoom=" + cmd.zoom);
        // url.append("&size=" + cmd.width + "x" + cmd.height);
        // url.append("&maptype=" + cmd.maptype);
        // url.append("&format=png&sensor=false");
        // url.append("&mobile=" + (cmd.maptype.equals("roadmap") ? "true" : "false"));
        // url.append("&key=" + mapkey);
        // String finalUrl = url.toString();
        
        // byte[] data = fetchData(finalUrl);
        
        
        url += buf;
        
        if (!fetchData(url, &data, &datasize))
            return 0;

        *p_data = data;
        *p_size = datasize;
        
        return 1;
        
    }
Exemple #7
0
float SHT3x::readHumidity(const uint16_t& command) const {
//    uint32_t raw_data = getMeasurement(command);
    uint32_t raw_data = fetchData();
    if (!raw_data) {
        throw std::runtime_error("Bad Reading.");
    }
    uint16_t raw_humidity = raw_data & 0xFFFF;
    float humidity = 100.0 * ((float) raw_humidity / (float) 0xFFFF);
    return humidity;
}
Exemple #8
0
void pollServer()
{
	fd_set rfs;
	int maxd = srv.ld;
	mGame * gm;
	mPlayer * pm;
	int sel;

	FD_ZERO(&rfs);
	FD_SET(srv.ld, &rfs);

	for (pm = srv.players; pm; pm = pm->next)
	{
		FD_SET(pm->player->fd, &rfs);
		maxd = max(maxd, pm->player->fd);
	}

	for (gm = srv.games; gm; gm = gm->next)
		for (pm = gm->game->players; pm; pm = pm->next)
		{
			FD_SET(pm->player->fd, &rfs);
			maxd = max(maxd, pm->player->fd);
		}

	sel = select(maxd+1, &rfs, NULL, NULL, NULL);
	if (sel < 1)
		merror("select");

	if (FD_ISSET(srv.ld, &rfs))
		acceptPlayer();

	for (pm = srv.players; pm; pm = pm->next)
		if (FD_ISSET(pm->player->fd, &rfs))
			fetchData(pm->player);

	for (gm = srv.games; gm; gm = gm->next)
		for (pm = gm->game->players; pm; pm = pm->next)
			if (FD_ISSET(pm->player->fd, &rfs))
				fetchData(pm->player);
}
Exemple #9
0
/* 如果显示调用
typedef int (*lpFetchData)();
typedef int (*lpSaveVar)();
typedef LPCSTR (*lpGetVar)(const LPCSTR group, const LPCSTR key);
typedef int(*lpShowVar)();
typedef int(*lpTest_save)();
......
HINSTANCE hDll = LoadLibrary("fKeyValue.dll");//导入.dll动态连接库
lpFetchData fetchData=(lpFetchData)GetProcAddress(hDll,"fetchData");
lpShowVar showVar=(lpShowVar)GetProcAddress(hDll,"showVar");
lpGetVar getVar=(lpGetVar)GetProcAddress(hDll,"getVar");
......
dosomething....
FreeLibrary(hDll);
*/
int main(void)
{
    setFile("D:\\users\\goosy\\codes\\GoosyFBase\\data.ini");
    //test_save();
    fetchData();
    showVar();
    setVar("Date","safeDays","7845");
    saveVar();
    printf("安全天数为%s", getVar("Date","safeDays"));
    //MessageBoxA(0, getVar("Date","safeDays"), "安全天数为", MB_OK | MB_ICONINFORMATION);
    getch();
    return 0;
}
// Dtype  //jin
void MyImageDataLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
		vector<Blob<Dtype>*>* top) {

	//更新input
	fetchData();

	// Copy the data
	caffe_copy(prefetch_data_.count(), prefetch_data_.cpu_data(),
			   (*top)[0]->mutable_cpu_data());
	caffe_copy(prefetch_label_.count(), prefetch_label_.cpu_data(),
			   (*top)[1]->mutable_cpu_data());

//	return Dtype(0.); //jin
}
/* Load data to cache from corresponding external object(s),
 * this task COULD be performed in other than GUI thread: */
void UIGlobalSettingsExtension::loadToCacheFrom(QVariant &data)
{
    /* Fetch data to properties & settings: */
    UISettingsPageGlobal::fetchData(data);

    /* Load to cache: */
    const CExtPackManager &manager = vboxGlobal().virtualBox().GetExtensionPackManager();
    const CExtPackVector &packages = manager.GetInstalledExtPacks();
    for (int i = 0; i < packages.size(); ++i)
        m_cache.m_items << fetchData(packages[i]);

    /* Upload properties & settings to data: */
    UISettingsPageGlobal::uploadData(data);
}
bool Bitmaszyna::makeSimpleApiCall(string method,string post)
{
    struct json_object *json,*jtmp;

    curl_mutex.lock();
    if (makeApiCall(method,&json,post))
    {
        if(!fetchData(&json,&jtmp)) return(false);
        log(string(chunk.memory)+"\n");
        json_object_put(json);
        curl_mutex.unlock();
        return(true);
    }
    curl_mutex.unlock();
    return(false);
}
void SqliteTableModel::setQuery(const QString& sQuery, bool dontClearHeaders)
{
    // clear
    if(!dontClearHeaders)
    {
        m_mWhere.clear();
        m_headers.clear();
    }

    if(!m_db->isOpen())
        return;

    m_sQuery = removeComments(sQuery).trimmed();

    // do a count query to get the full row count in a fast manner
    m_rowCount = getQueryRowCount();
    if(m_rowCount == -1)
    {
        m_valid = false;
        return;
    }

    // headers
    if(!dontClearHeaders)
    {
        sqlite3_stmt* stmt;
        QByteArray utf8Query = sQuery.toUtf8();
        int status = sqlite3_prepare_v2(m_db->_db, utf8Query, utf8Query.size(), &stmt, NULL);
        if(SQLITE_OK == status)
        {
            status = sqlite3_step(stmt);
            int columns = sqlite3_data_count(stmt);
            for(int i = 0; i < columns; ++i)
                m_headers.append(QString::fromUtf8((const char*)sqlite3_column_name(stmt, i)));
        }
        sqlite3_finalize(stmt);
    }

    // now fetch the first entries
    clearCache();
    fetchData(0, m_chunkSize);
    m_valid = true;

    emit layoutChanged();
}
Exemple #14
0
void CDataView::ReadData(
	const std::shared_ptr<SourceSetting>& pSrcSetting,
	std::shared_ptr<IDataSetting>& pDataSetting)
{
	m_pSrcSetting = pSrcSetting;
	m_pDataSetting = pDataSetting;
	if (
		fetchData(
			pSrcSetting,
			pDataSetting->GetTotalBytes(),
			m_data
		)
	) {
		ProcessData();
		Invalidate();
		UpdateWindow();
	}
}
bool Bitmaszyna::getfunds()
{    
    struct json_object *json,*jtmp,*jtmp2;

    curl_mutex.lock();
    if (makeApiCall("funds",&json,string("nonce=")+to_stringl(getctime()).toStdString()))
    {
        if (!fetchData(&json,&jtmp)) return(false);
        log(string(chunk.memory)+"\n");
        json_object_object_get_ex(json,"funds",&jtmp);
        json_object_object_get_ex(jtmp,"available_btc",&jtmp2);
        balance.balance[BTC]=json_object_get_double(jtmp2);
        json_object_object_get_ex(jtmp,"blocked_btc",&jtmp2);
        balance.blocked[BTC]=json_object_get_double(jtmp2);
        json_object_object_get_ex(jtmp,"available_ltc",&jtmp2);
        balance.balance[LTC]=json_object_get_double(jtmp2);
        json_object_object_get_ex(jtmp,"blocked_ltc",&jtmp2);
        balance.blocked[LTC]=json_object_get_double(jtmp2);
        json_object_object_get_ex(jtmp,"available_kbm",&jtmp2);
        balance.balance[KBM]=json_object_get_double(jtmp2);
        json_object_object_get_ex(jtmp,"blocked_kbm",&jtmp2);
        balance.blocked[KBM]=json_object_get_double(jtmp2);
        json_object_object_get_ex(jtmp,"available_pln",&jtmp2);
        balance.balance[PLN]=json_object_get_double(jtmp2);
        json_object_object_get_ex(jtmp,"blocked_pln",&jtmp2);
        balance.blocked[PLN]=json_object_get_double(jtmp2);
        json_object_object_get_ex(jtmp,"takerfee",&jtmp2);
        fees.taker=json_object_get_double(jtmp2);
        json_object_object_get_ex(jtmp,"makerfee",&jtmp2);
        fees.maker=json_object_get_double(jtmp2);
        json_object_put(json);
        logged=true;
        curl_mutex.unlock();
        return(getAccountInfo());
    }
    curl_mutex.unlock();
    return(false);
}
bool Bitmaszyna::getopenorders(string)
{
    struct json_object *json,*jtmp;
    struct array_list *arr;
    int i;
    Offer o;

    curl_mutex.lock();
    orders.clear();
    if (makeApiCall("offers",&json,string("nonce=")+to_stringl(getctime()).toStdString()))
    {
        if (!fetchData(&json,&jtmp)) return(false);
        json_object_object_get_ex(json,"orders",&jtmp);
        arr=json_object_get_array(jtmp);
        for(i=0;i<arr->length;i++)
        {
            struct json_object *jtmp3,*jtmp4;

            jtmp3=(struct json_object *)array_list_get_idx(arr,i);
            json_object_object_get_ex(jtmp3,"id",&jtmp4);
            o.id=to_stringl(json_object_get_int(jtmp4)).toStdString();
            json_object_object_get_ex(jtmp3,"price",&jtmp4);
            o.price=json_object_get_double(jtmp4);
            json_object_object_get_ex(jtmp3,"amount",&jtmp4);
            o.amount=json_object_get_double(jtmp4);
            json_object_object_get_ex(jtmp3,"type",&jtmp4);
            o.type=json_object_get_double(jtmp4);
            orders.push_back(o);
        }
        json_object_put(json);
        curl_mutex.unlock();
        return(true);
    }
    curl_mutex.unlock();
    return(false);
}
/* Package add procedure: */
void UIGlobalSettingsExtension::sltInstallPackage()
{
    /*
     * Open file-open window to let user to choose package file.
     *
     * The default location is the user's Download or Downloads directory with
     * the user's home directory as a fallback.  ExtPacks are downloaded.
     */
    QString strBaseFolder = QDir::homePath() + "/Downloads";
    if (!QDir(strBaseFolder).exists())
    {
        strBaseFolder = QDir::homePath() + "/Download";
        if (!QDir(strBaseFolder).exists())
            strBaseFolder = QDir::homePath();
    }
    QString strTitle = tr("Select an extension package file");
    QStringList extensions;
    for (int i = 0; i < VBoxExtPackFileExts.size(); ++i)
        extensions << QString("*.%1").arg(VBoxExtPackFileExts[i]);
    QString strFilter = tr("Extension package files (%1)").arg(extensions.join(" "));

    QStringList fileNames = QIFileDialog::getOpenFileNames(strBaseFolder, strFilter, this, strTitle, 0, true, true);

    QString strFilePath;
    if (!fileNames.isEmpty())
        strFilePath = fileNames.at(0);

    /*
     * Install the chosen package.
     */
    if (!strFilePath.isEmpty())
    {
        QString strExtPackName;
        doInstallation(strFilePath, QString(), this, &strExtPackName);

        /*
         * Since we might be reinstalling an existing package, we have to
         * do a little refreshing regardless of what the user chose.
         */
        if (!strExtPackName.isNull())
        {
            /* Remove it from the cache. */
            for (int i = 0; i < m_cache.m_items.size(); i++)
                if (!strExtPackName.compare(m_cache.m_items[i].m_strName, Qt::CaseInsensitive))
                {
                    m_cache.m_items.removeAt(i);
                    break;
                }

            /* Remove it from the tree. */
            const int cItems = m_pPackagesTree->topLevelItemCount();
            for (int i = 0; i < cItems; i++)
            {
                UIExtensionPackageItem *pItem = static_cast<UIExtensionPackageItem*>(m_pPackagesTree->topLevelItem(i));
                if (!strExtPackName.compare(pItem->name(), Qt::CaseInsensitive))
                {
                    delete pItem;
                    break;
                }
            }

            /* Reinsert it into the cache and tree. */
            CExtPackManager manager = vboxGlobal().virtualBox().GetExtensionPackManager();
            const CExtPack &package = manager.Find(strExtPackName);
            if (package.isOk())
            {
                m_cache.m_items << fetchData(package);

                UIExtensionPackageItem *pItem = new UIExtensionPackageItem(m_pPackagesTree, m_cache.m_items.last());
                m_pPackagesTree->setCurrentItem(pItem);
                m_pPackagesTree->sortByColumn(1, Qt::AscendingOrder);
            }
        }
    }
}
Exemple #18
0
void aprilTagHandler(void *vargp)
{
	SOCKET fd;
	char *port, hostname[MAX_TEXTBOX_LENGTH];
	int i, id, rid, n, oldhead;
	int tid;						// Thread ID
	struct socketIO socketio;		// Robust IO buffer for socket
	char buffer[APRILTAG_BUFFERSIZE], *bufp;
	char lbuffer[BUFFERSIZE + APRILTAG_BUFFERSIZE + 16];
	fd_set read_set, ready_set;		// Read set for select
	struct timeval tv = { 0, 1 };	// Timeout for select
	GLfloat x, y, t;				// Data from server
	int ts;							// Timestamp from server

	if (aprilTagConnected) {
		return;
	}

	mutexLock(&aprilTagURL.mutex);
	strcpy(hostname, aprilTagURL.message);

	/* Parse out port from hostname */
	if ((port = strpbrk(hostname, ":")) != NULL) {
		*(port++) = '\0';
	} else {
		port = "2001";
	}

	if ((fd = openClientFD(hostname, port)) == INVALID_SOCKET) {
		mutexUnlock(&aprilTagURL.mutex);
		return;
	}

	tid = 0;

	aprilTagConnected = 1;
	robots[0].type = UNKNOWN;
	robots[0].up = 1;
	aprilTagURL.isActive = 0;
	mutexUnlock(&aprilTagURL.mutex);

	if (verbose) {
		printf("A%02d: Handler thread initialized\n", tid);
	}

	/* Initialize robust IO on the socket */
	socketInitIO(&socketio, fd);

	if (verbose) {
		printf("A%02d: Processing April Tag Data\n", tid);
	}

	/* Initialize stuff for select */
	FD_ZERO(&read_set);
	FD_SET(fd, &read_set);

	for (;;) {
		memset(buffer, 0, APRILTAG_BUFFERSIZE);
		ready_set = read_set;

		/* Check if there is data available from the client. */
		if (select(fd + 1, &ready_set, NULL, NULL, &tv) < 0) {
			break;
		}

		/* Is there is data to be read? */
		if (FD_ISSET(fd, &ready_set)) {
			if ((n = socketReadline(&socketio, buffer, APRILTAG_BUFFERSIZE - 1))
				!= 0) {
				/* Get the beginning of the remote message */
				if ((bufp = strpbrk(buffer, " ")) == NULL) {
					bufp = buffer;
					continue;
				}
				/* Format end to be CRLF */
				while (buffer[n - 1] == '\r' || buffer[n - 1] == '\n') {
					buffer[n--] = '\0';
				}

				buffer[n] = '\r';
				buffer[n + 1] = '\n';
				insertBuffer(0, buffer, 0);

				/* Parse AprilTag ID */
				*(bufp++) = '\0';
				if (sscanf(buffer, "%d,", &id) < 1) {
					continue;
				}

				if (id < 0 || id >= MAX_APRILTAG) {
					continue;
				}

				if (id > maxAprilTag) {
					maxAprilTag = id;
				}

				mutexLock(&aprilTagData[id].mutex);
				aprilTagData[id].active = 1;
				strcpy(aprilTagData[id].buffer[aprilTagData[id].head], bufp);

				aprilTagData[id].up = clock();

				if (sscanf(bufp, "%f, %f, %f, %d", &x, &y, &t, &ts) == 4) {
					aprilTagData[id].x = x;
					aprilTagData[id].y = y;
					aprilTagData[id].t = t;

					if (ATsatID != 0) {
						if ((aprilTagData[id].up - aprilTagData[id].bcastTime > SAT_BCAST_TIME)
							&& aprilTagData[id].rid != -1) {
							sprintf(lbuffer, "EP %d,%d,%d,%d\n", aprilTagData[id].rid,
																 (int) round(x),
																 (int) round(y),
																 (int) round(t));
							hprintf(robots[ATsatID].hSerial, lbuffer);
							aprilTagData[id].bcastTime = aprilTagData[id].up;
						}
					}

					if (x > 2 * aprilTagX) {
						aprilTagX = ((int) (aprilTagData[id].x / 2) + 50) / 100
							* 100;
						aprilTagX += (aprilTagX < aprilTagData[id].x) ? 50 : 0;
					}

					if (y > 2 * aprilTagY) {
						aprilTagY = ((int) (aprilTagData[id].y / 2) + 50) / 100
							* 100;
						aprilTagY += (aprilTagY < aprilTagData[id].y) ? 50 : 0;
					}
				}

				oldhead = aprilTagData[id].head;
				aprilTagData[id].head = (aprilTagData[id].head + 1)
					% NUMBUFFER_APRILTAG;

				if (aprilTagData[id].log && logging) {
					if ((rid = aprilTagData[id].rid) != -1) {
						mutexUnlock(&aprilTagData[id].mutex);
						fetchData(lbuffer, rid, -1, id, -1);
						mutexLock(&aprilTagData[id].mutex);
						hprintf(&aprilTagData[id].logH, lbuffer);
					} else {
						hprintf(&aprilTagData[id].logH, "%11d, %s", clock(),
							aprilTagData[id].buffer[oldhead]);
					}
				}
				mutexUnlock(&aprilTagData[id].mutex);
			} else {
				break;
			}
		}
	}

	if (verbose) {
		printf("A%02d: AprilTag connection closed!\n", tid);
	}

	for (i = 0; i < MAX_APRILTAG; i++) {
		mutexLock(&aprilTagData[i].mutex);
		aprilTagData[i].active = 0;
		aprilTagData[i].up = 0;
		aprilTagData[i].display = 0;
		if (aprilTagData[i].log) {
			aprilTagData[i].log = 0;
			CloseHandle(aprilTagData[i].logH);
		}
		mutexUnlock(&aprilTagData[i].mutex);
	}

	/* Clean up */
	aprilTagConnected = 0;
	Close(fd);

	return;
}
Exemple #19
0
bool MRWContainer::locateDirsPreHook()
{
    char version[9];
    off_t position;

    Trace(DEBUG1) << "> MRWContainer::locateDirsPreHook()\n";
    m_endian = ENDIAN_BIG;

    /* MRW file always starts with an MRM datablock. */
    mrm = std::make_shared<MRW::DataBlock>(m_offset, this);
    if (mrm->name() != "MRM") {
        Trace(WARNING) << "MRW file begins not with MRM block, "
                          "but with unrecognized DataBlock :: name == "
                       << mrm->name() << "\n";
        return false;
    }

    /* Subblocks are contained within the MRM block. Scan them and create
     * appropriate block descriptors.
     */
    position = mrm->offset() + MRW::DataBlockHeaderLength;
    while (position < pixelDataOffset()) {
        MRW::DataBlock::Ref ref(
            std::make_shared<MRW::DataBlock>(position, this));
        Trace(DEBUG1) << "Loaded DataBlock :: name == " << ref->name() << "\n";
        if (!ref || !ref->loaded()) {
            break;
        }
        if (ref->name() == "PRD") {
            if (prd) {
                Trace(WARNING)
                    << "File contains duplicate DataBlock :: name == "
                    << ref->name() << "\n";
            }
            prd = ref;
        } else if (ref->name() == "TTW") {
            if (ttw) {
                Trace(WARNING)
                    << "File contains duplicate DataBlock :: name == "
                    << ref->name() << "\n";
            }
            ttw = ref;
        } else if (ref->name() == "WBG") {
            if (wbg) {
                Trace(WARNING)
                    << "File contains duplicate DataBlock :: name == "
                    << ref->name() << "\n";
            }
            wbg = ref;
        } else if (ref->name() == "RIF") {
            if (rif) {
                Trace(WARNING)
                    << "File contains duplicate DataBlock :: name == "
                    << ref->name() << "\n";
            }
            rif = ref;
        } else if (ref->name() != "PAD") {
            Trace(WARNING) << "File contains unrecognized DataBlock :: name == "
                           << ref->name() << "\n";
        }
        position = ref->offset() + MRW::DataBlockHeaderLength + ref->length();
    }

    /* Check that we found all the expected data blocks. */
    if (!prd) {
        Trace(WARNING)
            << "File does NOT contain expected DataBlock :: name == PRD\n";
        return false;
    }
    if (!ttw) {
        Trace(WARNING)
            << "File does NOT contain expected DataBlock :: name == TTW\n";
        return false;
    }
    if (!wbg) {
        Trace(WARNING)
            << "File does NOT contain expected DataBlock :: name == WBG\n";
        return false;
    }
    if (!rif) {
        Trace(WARNING)
            << "File does NOT contain expected DataBlock :: name == RIF\n";
        return false;
    }

    /* Extract the file version string. */
    if (fetchData(version,
                  prd->offset() + MRW::DataBlockHeaderLength + MRW::PRD_VERSION,
                  8) != 8) {
        // FIXME: Handle error
        Debug::Trace(DEBUG1) << "  Error reading version string\n";
    }
    version[8] = '\0';
    m_version = std::string(version);
    Trace(DEBUG1) << "  MRW file version == " << m_version << "\n";

    /* For the benefit of our parent class, set the container offset to the
     * beginning of
     * the TIFF data (the contents of the TTW data block), and seek there.
     */
    m_offset = ttw->offset() + MRW::DataBlockHeaderLength;

    // TODO: Not sure exactly here the origin of this.
    // But it doesn't work.
    //  if((version[2] != '7') || (version[3] != '3')) {
    setExifOffsetCorrection(m_offset);
    Trace(DEBUG1) << "setting correction to " << m_offset << "\n";
    //  }

    m_file->seek(m_offset, SEEK_SET);
    Trace(DEBUG1) << "< MRWContainer\n";

    return true;
}
Exemple #20
0
bool WaveTrack::getData(unsigned framePos, int channels, unsigned nframe, float** bp)
      {
      bool have_data = false;
      if ((MusEGlobal::song->bounceTrack != this) && !noInRoute()) {
            RouteList* irl = inRoutes();
            for(ciRoute i = irl->begin(); i != irl->end(); ++i)
            {
              if(i->track->isMidiTrack())
                continue;

              ((AudioTrack*)i->track)->copyData(framePos, channels,
                                               i->channel,
                                               i->channels,
                                               nframe, bp, have_data);
              have_data = true;
            }
            
            if (recordFlag()) {
            //if (have_data && recordFlag()) {
                  //if (MusEGlobal::audio->isRecording() && recFile()) {
                  if (have_data && MusEGlobal::audio->isRecording() && recFile()) {
                        if (MusEGlobal::audio->freewheel()) {
                              }
                        else {
#ifdef _AUDIO_USE_TRUE_FRAME_
                              // TODO: Tested: This is the line that would be needed for Audio Inputs, 
                              //  because the data arrived in the previous period! Test OK, the waves are in sync.
                              // So we need to do Audio Inputs separately above, AND find a way to mix two overlapping
                              //  periods into the file! Nothing wrong with the FIFO per se, we could stamp overlapping
                              //  times. But the soundfile just writes, does not mix.
                              //if (fifo.put(channels, nframe, bp, MusEGlobal::audio->previousPos().frame()))
                              //
                              // Tested: This line is OK for track-to-track recording, the waves are in sync:
#endif                              
                              if (fifo.put(channels, nframe, bp, MusEGlobal::audio->pos().frame()))  
                                    printf("WaveTrack::getData(%d, %d, %d): fifo overrun\n",
                                       framePos, channels, nframe);
                              }
                        }
                  //return true;  // REMOVE Tim. Can't hear existing parts while recording, even while simply armed.
                  // FIXME TODO Remove this. But first code below needs to become ADDITIVE/REPLACING (don't just take over buffers).
                  return have_data;  
                  }
            }
      if (!MusEGlobal::audio->isPlaying())
            return false;
            //return have_data;
      
      if (MusEGlobal::audio->freewheel()) {

            // when freewheeling, read data direct from file:
            // Indicate do not seek file before each read.
            fetchData(framePos, nframe, bp, false);

            }
      else {
            unsigned pos;
            if (_prefetchFifo.get(channels, nframe, bp, &pos)) {
                  printf("WaveTrack::getData(%s) fifo underrun\n",
                      name().toLocal8Bit().constData());
                  return false;
                  }
            if (pos != framePos) {
                  if (MusEGlobal::debugMsg)
                        printf("fifo get error expected %d, got %d\n",
                            framePos, pos);
                  while (pos < framePos) {
                        if (_prefetchFifo.get(channels, nframe, bp, &pos)) {
                              printf("WaveTrack::getData(%s) fifo underrun\n",
                                  name().toLocal8Bit().constData());
                              return false;
                              }
                        }
                  }
            }
      return true;
      }
int main () {
  int *data = fetchData();
  processData(data);
  showData(data);
  return 0;
}
Exemple #22
0
/**
 * Thread to handle a connection, feeds data to the port
 */
void connectionHandler(void *vargp)
{
	int tid;						// Thread ID
	int id;							// Requested robot ID
	int n;
	int aid;						// AprilTag ID
	int head;						// Last location of robot buffer viewed
	int up, bl;						// Flag
	struct Connection *conn;		// Connection information
	char buffer[BUFFERSIZE];		// General use buffer
	char inBuffer[BUFFERSIZE];		// Input buffer from client
	struct socketIO socketio;		// Robust IO buffer for socket
	fd_set read_set, ready_set;		// Read set for select
	struct timeval tv = { 0, 1 };	// Timeout for select

	conn = (struct Connection *) vargp;
	tid = conn->n;

	if (verbose) {
		printf("T%02d: Handler thread initialized\n", tid);
	}

	/* Initialize robust IO on the socket */
	socketInitIO(&socketio, conn->fd);

	if (verbose) {
		printf("T%02d: [%d] Processing new client connection\n", tid, conn->n);
	}

	/* Initialize stuff for select */
	FD_ZERO(&read_set);
	FD_SET(conn->fd, &read_set);

	/* Query user for robot ID */
	id = -1;
	while (id == -1) {
		if (aprilTagConnected) {
			if (socketWrite(conn->fd,
				"Enter the robot ID you wish to view (0 for AprilTag only): ",
				59) < 0) {
				break;
			}
		} else {
			if (socketWrite(conn->fd, "Enter the robot ID you wish to view: ",
				37) < 0) {
				break;
			}
		}

		if (socketReadline(&socketio, buffer, BUFFERSIZE) == 0) {
			break;
		}

		if (sscanf(buffer, "%d\n", &id) != 1) {
			if (socketWrite(conn->fd, "Invalid ID! Try Again.\r\n", 24) < 0) {
				break;
			}
			continue;
		}

		/* Handle bad numbers */
		if (id >= MAXROBOTID || id < 0) {
			id = -1;
			if (socketWrite(conn->fd, "Invalid ID! Try Again.\r\n", 24) < 0) {
				break;
			}
			continue;
		}

		if (id == 0 && !aprilTagConnected) {
			id = -1;
			if (socketWrite(conn->fd, "Invalid ID! Try Again.\r\n", 24) < 0) {
				break;
			}
			continue;
		}

		mutexLock(&robots[id].mutex);
		up = robots[id].up;
		bl = robots[id].blacklisted && !(robots[id].type == REMOTE);
		mutexUnlock(&robots[id].mutex);

		if (up && !bl) {
			if (socketWrite(conn->fd, "Connected!\r\n", 12) < 0) {
				break;
			}
		} else {
			id = -1;
			if (socketWrite(conn->fd, "Robot ID not connected!\r\n", 25) < 0) {
				break;
			}
		}
	}

	/* Close if the connection broke */
	if (id == -1) {
		if (verbose) {
			printf("T%02d: [%d] Done!\n", tid, conn->n);
		}

		Close(conn->fd);
		Free(conn);
		return;
	}

	if (verbose) {
		printf("T%02d: [%d] Connected to robot %02d\n", tid, conn->n, id);
	}

	aid = robots[id].aid;
	if (aprilTagConnected) {
		while (aid == -1) {
			if (socketWrite(conn->fd, "Robot AprilTag (Enter for none): ", 33)
				< 0) {
				break;
			}

			if (socketReadline(&socketio, buffer, BUFFERSIZE) == 0) {
				break;
			}

			if (sscanf(buffer, "%d\n", &aid) != 1) {
				aid = -1;
				break;
			}

			/* Handle bad numbers */
			if (aid >= MAX_APRILTAG || aid < 0) {
				aid = -1;
				if (socketWrite(conn->fd, "Invalid AprilTag! Try Again.\r\n",
					30) < 0) {
					break;
				}
				continue;
			}

			if (aprilTagData[aid].active) {
				if (socketWrite(conn->fd, "AprilTag linked!\r\n", 18) < 0) {
					break;
				}

				if (verbose) {
					printf("T%02d: [%d] Connected to AprilTag %d\n", tid,
						conn->n, aid);
				}
			} else {
				if (socketWrite(conn->fd, "AprilTag not seen!\r\n", 20) < 0) {
					break;
				}
				aid = -1;
			}
		}
	}

	/* Connected to a robot / AprilTag feed */
	if (id != 0 || (id == 0 && aid == -1)) {
		mutexLock(&robots[id].mutex);
		head = robots[id].head;
		mutexUnlock(&robots[id].mutex);

		for (;;) {
			ready_set = read_set;

			/* Check if there is data available from the client. */
			if (select(conn->fd + 1, &ready_set, NULL, NULL, &tv) < 0) {
				break;
			}

			/* Is there is data to be read? */
			if (FD_ISSET(conn->fd, &ready_set)) {
				if (socketRead(&socketio, inBuffer, BUFFERSIZE) != 0) {
					/* Write data out to serial port if the robot is local */
					mutexLock(&robots[id].mutex);
					if (robots[id].type == LOCAL || robots[id].type == HOST) {
						hprintf(robots[id].hSerial, inBuffer);
					}
					mutexUnlock(&robots[id].mutex);
				} else {
					break;
				}
			}
			/* Extensively use the mutex to prevent all data-races */
			mutexLock(&robots[id].mutex);
			/* If there is new data in the robot buffer */
			while (head != robots[id].head) {
				mutexUnlock(&robots[id].mutex);

				fetchData(buffer, id, head, aid, -1);

				if ((n = socketWrite(conn->fd, buffer, strlen(buffer))) < 0) {
					break;
				}

				head = (head + 1) % NUMBUFFER;
				mutexLock(&robots[id].mutex);
			}

			/* If true, connection is broken so exit out. */
			if (n < 0)
				break;

			/* Check if the robot is disconnected. */
			if ((robots[id].blacklisted
				&& !(robots[id].type == REMOTE))
				|| !robots[id].up) {
				socketWrite(conn->fd, "Robot ID disconnected!\r\n", 24);
				mutexUnlock(&robots[id].mutex);
				break;
			}
			mutexUnlock(&robots[id].mutex);
		}
	/* Connected to an AprilTag */
	} else {
		int rid;

		sprintf(tbuffer, "New Connection to AprilTag ID %2d!", aid);
		setToaster(tbuffer);

		mutexLock(&aprilTagData[aid].mutex);
		head = aprilTagData[aid].head;
		mutexUnlock(&aprilTagData[aid].mutex);

		for (;;) {
			mutexLock(&aprilTagData[aid].mutex);
			/* If there is new data in the robot buffer */
			while (head != aprilTagData[aid].head) {
				rid = aprilTagData[aid].rid;
				mutexUnlock(&aprilTagData[aid].mutex);
				fetchData(buffer, rid, -1, aid, -1);

				if ((n = socketWrite(conn->fd, buffer, strlen(buffer))) < 0) {
					break;
				}

				head = (head + 1) % NUMBUFFER_APRILTAG;
				mutexLock(&aprilTagData[aid].mutex);
			}
			mutexUnlock(&aprilTagData[aid].mutex);

			/* If true, connection is broken so exit out. */
			if (n < 0)
				break;
		}
	}

	if (verbose) {
		printf("T%02d: [%d] Done!\n", tid, conn->n);
	}

	/* Clean up. */
	Close(conn->fd);
	Free(conn);

	return;
}
void SqliteTableModel::fetchMore(const QModelIndex&)
{
    int row = m_data.size();
    fetchData(row, row + m_chunkSize);
}
Exemple #24
0
void GoogleGeoCoding::processCommand(IQueueCommand *pCmd)
{
    Command *cmd = (Command*)pCmd;
    GeoCodingCallback &cb = *(cmd->callback);

    String url = "http://maps.googleapis.com/maps/api/geocode/json?address=";
    url += net::URI::urlEncode(cmd->address);
    url += "&sensor=false";

    RHO_MAP_TRACE1("GoogleGeoCoding: processCommand: url=%s", url.c_str());

    void *data;
    size_t datasize;
    if (!fetchData(url, &data, &datasize))
    {
        RAWLOG_ERROR1("Can not fetch data by url=%s", url.c_str());
        return;
    }

    RHO_MAP_TRACE("GoogleGeoCoding: processCommand: Parse received json...");

    double latitude, longitude;
    if (parse_json((const char *)data, &latitude, &longitude))
    {
        RHO_MAP_TRACE("GoogleGeoCoding: processCommand: json parsed successfully");
        cb.onSuccess(latitude, longitude);
    }
    else
    {
        RHO_MAP_TRACE("GoogleGeoCoding: processCommand: can't parse json");
        cb.onError("Can not parse JSON response");
    }
    /*
    char *error = 0;
    unsigned long json = rjson_tokener_parse((char const *)data, &error);
    if (!rho_ruby_is_NIL(json))
    {
        RHO_MAP_TRACE("GoogleGeoCoding: processCommand: extract coordinates from json...");
        unsigned long coords = rho_ruby_google_geocoding_get_coordinates(json);
        if (rho_ruby_is_NIL(coords))
        {
            RHO_MAP_TRACE("GoogleGeoCoding: processCommand: rho_ruby_google_geocoding_get_coordinates return nil");
            cb.onError("Cannot parse received JSON object");
        }
        else
        {
            RHO_MAP_TRACE("GoogleGeoCoding: processCommand: rho_ruby_google_geocoding_get_coordinates return coordinates");
            double latitude = rho_ruby_google_geocoding_get_latitude(coords);
            double longitude = rho_ruby_google_geocoding_get_longitude(coords);
            RHO_MAP_TRACE2("GoogleGeoCoding: processCommand: latitude=%lf, longitude=%lf", latitude, longitude);
            cb.onSuccess(latitude, longitude);
        }
    }
    else
    {
        RHO_MAP_TRACE("GoogleGeoCoding: processCommand: rjson_tokener_parse return nil");
        cb.onError(error);
    }

    if (error)
        free (error);
    */

    free(data);
}
Exemple #25
0
void VisualNavbar::fetchAndPaintData()
{
    fetchData();
    fillData();
}
Exemple #26
0
bot::Chat::Chat(const Json::Value& chat)
    : User(chat)
{
    fetchData(chat);
}