void GL1TextureProvider::set_texture_image3d( GLuint target, PixelBuffer &image, int image_depth, int level) { throw_if_disposed(); GL1TextureStateTracker state_tracker(texture_type, handle); GLint gl_internal_format; GLenum gl_pixel_format; to_opengl_textureformat(image.get_format(), gl_internal_format, gl_pixel_format); // check out if the original texture needs or doesn't need an alpha channel bool needs_alpha = image.has_transparency(); GLenum format; GLenum type; bool conv_needed = !to_opengl_pixelformat(image, format, type); // also check for the pitch (GL1 can only skip pixels, not bytes) if (!conv_needed) { const int bytesPerPixel = image.get_bytes_per_pixel(); if (image.get_pitch() % bytesPerPixel != 0) conv_needed = true; } // no conversion needed if (!conv_needed) { // Upload to GL1: // change alignment glPixelStorei(GL_UNPACK_ALIGNMENT, 1); const int bytesPerPixel = image.get_bytes_per_pixel(); #ifndef __ANDROID__ glPixelStorei(GL_UNPACK_ROW_LENGTH, image.get_pitch() / bytesPerPixel); glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); #endif char *data = (char *) image.get_data(); int image_width = image.get_width(); int image_height = image.get_height() / image_depth; glTexImage3D( target, // target level, // level gl_internal_format, // internalformat image_width, // width image_height, // height image_depth, // depth 0, // border format, // format type, // type data); // texels } // conversion needed else { bool big_endian = Endian::is_system_big(); PixelBuffer buffer( image.get_width(), image.get_height(), needs_alpha ? tf_rgba8 : tf_rgb8); buffer.set_image(image); format = needs_alpha ? GL_RGBA : GL_RGB; // Upload to OpenGL: // change alignment glPixelStorei(GL_UNPACK_ALIGNMENT, 1); const int bytesPerPixel = buffer.get_bytes_per_pixel(); #ifndef __ANDROID__ glPixelStorei(GL_UNPACK_ROW_LENGTH, buffer.get_pitch() / bytesPerPixel); glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); #endif int image_width = image.get_width(); int image_height = image.get_height() / image_depth; // upload glTexImage3D( target, // target level, // level gl_internal_format, // internalformat image_width, // width image_height, // height image_depth, // depth 0, // border format, // format GL_UNSIGNED_BYTE, // type buffer.get_data()); // texels } }
BOOL CSoftInfoQueryTask::QueryByNetwork(const SoftQueryInfoList &queryInfoList, SoftInfo2List &resultList) { static const LPCWSTR pContentType = L"Content-Type: application/x-www-form-urlencoded\r\n"; WinHttpApi2 *pHttpApi = _pSoftQuery->GetWinHttpApi(); if(pHttpApi == NULL) return FALSE; BOOL succeeded = FALSE; HINTERNET hSess = NULL; HINTERNET hConn = NULL; HINTERNET hHttp = NULL; do { // // 加载代理数据 // CString strIniPath; CAppPath::Instance().GetLeidianCfgPath(strIniPath); strIniPath += _T("\\bksafe.ini"); static const int BUF_SIZE = 64; UINT validate = 0; wchar_t szUser[BUF_SIZE] = {0}; wchar_t szPwd[BUF_SIZE] = {0}; wchar_t szProxy[BUF_SIZE * 2] = {0}; UINT type = ::GetPrivateProfileIntW(L"proxy", L"type", 0, strIniPath); if(type == 1) { // 改成无代理 type = 0; do { UINT port = ::GetPrivateProfileIntW(L"proxy", L"port", 65536, strIniPath); if(port == 65536) break; wchar_t szHost[BUF_SIZE] = {0}; ::GetPrivateProfileStringW(L"proxy", L"host", NULL, szHost, BUF_SIZE, strIniPath); if(szHost[0] == L'\0') break; validate = ::GetPrivateProfileIntW(L"proxy", L"validate", -1, strIniPath); if(validate == static_cast<UINT>(-1)) break; INTERNET_PROXY_INFO proxy = {0}; proxy.dwAccessType = INTERNET_OPEN_TYPE_PROXY; swprintf_s(szProxy, BUF_SIZE * 2, L"%s:%d", szHost, port); proxy.lpszProxy = szProxy; if(validate != 0) { ::GetPrivateProfileStringW(L"proxy", L"user", NULL, szUser, BUF_SIZE, strIniPath); if(szUser[0] == L'\0') break; ::GetPrivateProfileStringW(L"proxy", L"password", NULL, szPwd, BUF_SIZE, strIniPath); if(szPwd[0] == L'\0') break; } // 加载数据成功 type = 1; } while(FALSE); } // // 设置代理 // if(type == 1) { hSess = pHttpApi->OpenSession2(L"king_guard_softmgr", szProxy); } else { hSess = pHttpApi->OpenSession(L"king_guard_softmgr"); } if(hSess == NULL) break; pHttpApi->SetTimeouts(hSess, QUERY_TIMEOUT, QUERY_TIMEOUT, QUERY_TIMEOUT, QUERY_TIMEOUT); hConn = pHttpApi->Connect(hSess, QUERY_SERVER_NAME, INTERNET_DEFAULT_PORT); if(hConn == NULL) break; hHttp = pHttpApi->OpenRequest(hConn, L"POST", QUERY_OBJECT_NAME, INTERNET_SCHEME_HTTP); if(hHttp == NULL) break; string bodyContent; BOOL result = CombineBodyContent(queryInfoList, bodyContent); if(!result) break; result = pHttpApi->AddRequestHeaders(hHttp, pContentType); if(!result) break; // // 设置代理用户名与密码 // if(type == 1 && validate == 1) { if(pHttpApi->IsWinHttp()) { pHttpApi->SetOption(hHttp, WINHTTP_OPTION_PROXY_USERNAME, szUser, wcslen(szUser)); pHttpApi->SetOption(hHttp, WINHTTP_OPTION_PROXY_PASSWORD, szPwd, wcslen(szPwd)); } else { pHttpApi->SetOption(hHttp, INTERNET_OPTION_PROXY_USERNAME, szUser, wcslen(szUser)); pHttpApi->SetOption(hHttp, INTERNET_OPTION_PROXY_PASSWORD, szPwd, wcslen(szPwd)); } } result = pHttpApi->SendRequest(hHttp, &bodyContent[0], static_cast<DWORD>(bodyContent.size())); if(!result) break; result = pHttpApi->EndRequest(hHttp); if(!result) break; DWORD cbReturn = 0; DWORD cbSize = sizeof(cbReturn); result = pHttpApi->QueryInfo(hHttp, WINHTTP_QUERY_CONTENT_LENGTH | WINHTTP_QUERY_FLAG_NUMBER, reinterpret_cast<char*>(&cbReturn), &cbSize); if(!result || cbReturn == 0) break; auto_buffer<char> buffer(cbReturn + 2 + 1); if(buffer.empty()) break; DWORD cbRecved = 0; result = pHttpApi->ReadData(hHttp, &buffer[0], cbReturn, &cbRecved); if(!result || cbRecved != cbReturn) break; // 在结尾加\r\n\0空字符 buffer[cbReturn] = '\r'; buffer[cbReturn + 1] = '\n'; buffer[cbReturn + 2] = '\0'; // 开始解析 TiXmlDocument xmlDoc; if(xmlDoc.Parse(&buffer[0]) == NULL) break; TiXmlHandle hRoot(xmlDoc.FirstChildElement("r")); for(TiXmlElement *pElem = hRoot.FirstChildElement("sid").Element(); pElem != NULL; pElem = pElem->NextSiblingElement()) { LPCSTR pId = pElem->Attribute("id"); if(pId == NULL) continue; LONG id = atol(pId); if(id == 0) continue; TiXmlElement *ppElem = pElem->FirstChildElement("grade"); if(ppElem == NULL) continue; LPCSTR pGrade = ppElem->GetText(); if(pGrade == NULL) continue; resultList.push_back(SoftInfo2(id, wstring(CA2W(pGrade)))); } succeeded = TRUE; } while(FALSE); if(hHttp != NULL) pHttpApi->CloseInternetHandle(hHttp); if(hConn != NULL) pHttpApi->CloseInternetHandle(hConn); if(hSess != NULL) pHttpApi->CloseInternetHandle(hSess); return succeeded; }
PassRefPtr<DataView> JSDataView::typedImpl() { return DataView::create(buffer(), byteOffset(), length()); }
ShaderProgram::ShaderProgram(const char *vertex, const char *fragment, const ShaderFlags &flags) { File::uptr vs, fs; v = glCreateShader(GL_VERTEX_SHADER); f = glCreateShader(GL_FRAGMENT_SHADER); uint64 size; vs = File::map(vertex, File::Read, &size); std::unique_ptr<char[]> vs1(new char[size + 1]); memcpy(vs1.get(), vs.get(), size * sizeof(char)); vs1[size] = 0; fs = File::map(fragment, File::Read, &size); std::unique_ptr<char[]> fs1(new char[size + 1]); memcpy(fs1.get(), fs.get(), size * sizeof(char)); fs1[size] = 0; //TODO: Może troszkę to ulepszyć... (Chodzi o to, że header trzeba dokleić po #version) const char * vv = vs1.get(); std::string fscode = fs1.get(); size_t ver = fscode.find("#version"); ver = fscode.find("\n", ver); std::string ffs = fscode.substr(0, ver) + "\n" + flags.getHeader() + fscode.substr(ver + 1); const char * ff = ffs.c_str(); glShaderSource(v, 1, &vv, NULL); glShaderSource(f, 1, &ff, NULL); GLint status; glCompileShader(v); glGetShaderiv(v, GL_INFO_LOG_LENGTH, &status); std::unique_ptr<GLchar[]> buffer(new GLchar[status]); glGetShaderInfoLog(v, status, &status, buffer.get()); glGetShaderiv(v, GL_COMPILE_STATUS, &status); if(status != GL_TRUE) RAISE(ShaderException, "Error while compiling Vertex Shader!", buffer.get()); else LOG(errorLogger, "Vertex Shader Info Log:%s\n", buffer.get()); glCompileShader(f); glGetShaderiv(f, GL_INFO_LOG_LENGTH, &status); buffer = std::unique_ptr<GLchar[]>(new GLchar[status]); glGetShaderInfoLog(f, status, &status, buffer.get()); glGetShaderiv(f, GL_COMPILE_STATUS, &status); if(status != GL_TRUE) RAISE(ShaderException, "Error while compiling Fragment Shader!", buffer.get()); else LOG(errorLogger, "Fragment Shader Info Log:%s\n", buffer.get()); p = glCreateProgram(); glAttachShader(p, v); glAttachShader(p, f); glLinkProgram(p); glValidateProgram(p); glGetProgramiv(p, GL_INFO_LOG_LENGTH, &status); buffer = std::unique_ptr<GLchar[]>(new GLchar[status]); glGetProgramInfoLog(p, status, &status, buffer.get()); glGetProgramiv(p, GL_VALIDATE_STATUS, &status); if(status != GL_TRUE) RAISE(ShaderException, "Error while linking / validating Shader Program!", buffer.get()); else LOG(errorLogger, "Shader Program Info Log:%s\n", buffer.get()); HASSERT(p && v && f); }
friend inline size_t buffer_size(const scoped_buffer_type& _buffer) { return boost::asio::buffer_size(buffer(_buffer)); }
void BufferedSocket::threadRead() throw(SocketException) { if(state != RUNNING) return; DownloadManager *dm = DownloadManager::getInstance(); size_t readsize = inbuf.size(); bool throttling = false; if(mode == MODE_DATA) { uint32_t getMaximum; throttling = dm->throttle(); if (throttling) { getMaximum = dm->throttleGetSlice(); readsize = (uint32_t)min((int64_t)inbuf.size(), (int64_t)getMaximum); if (readsize <= 0 || readsize > inbuf.size()) { // FIX sleep(dm->throttleCycleTime()); return; } } } int left = sock->read(&inbuf[0], (int)readsize); if(left == -1) { // EWOULDBLOCK, no data received... return; } else if(left == 0) { // This socket has been closed... throw SocketException(_("Connection closed")); } string::size_type pos = 0; // always uncompressed data string l; int bufpos = 0, total = left; while (left > 0) { switch (mode) { case MODE_ZPIPE: { const int BUF_SIZE = 1024; // Special to autodetect nmdc connections... string::size_type pos = 0; boost::scoped_array<char> buffer(new char[BUF_SIZE]); l = line; // decompress all input data and store in l. while (left) { size_t in = BUF_SIZE; size_t used = left; bool ret = (*filterIn) (&inbuf[0] + total - left, used, &buffer[0], in); left -= used; l.append (&buffer[0], in); // if the stream ends before the data runs out, keep remainder of data in inbuf if (!ret) { bufpos = total-left; setMode (MODE_LINE, rollback); break; } } // process all lines while ((pos = l.find(separator)) != string::npos) { fire(BufferedSocketListener::Line(), l.substr(0, pos)); l.erase (0, pos + 1 /* separator char */); } // store remainder line = l; break; } case MODE_LINE: // Special to autodetect nmdc connections... if(separator == 0) { if(inbuf[0] == '$') { separator = '|'; } else { separator = '\n'; } } l = line + string ((char*)&inbuf[bufpos], left); while ((pos = l.find(separator)) != string::npos) { fire(BufferedSocketListener::Line(), l.substr(0, pos)); l.erase (0, pos + 1 /* separator char */); if (l.length() < (size_t)left) left = l.length(); if (mode != MODE_LINE) { // we changed mode; remainder of l is invalid. l.clear(); bufpos = total - left; break; } } if (pos == string::npos) left = 0; line = l; break; case MODE_DATA: while(left > 0) { if(dataBytes == -1) { fire(BufferedSocketListener::Data(), &inbuf[bufpos], left); bufpos += (left - rollback); left = rollback; rollback = 0; } else { int high = (int)min(dataBytes, (int64_t)left); fire(BufferedSocketListener::Data(), &inbuf[bufpos], high); bufpos += high; left -= high; dataBytes -= high; if(dataBytes == 0) { mode = MODE_LINE; fire(BufferedSocketListener::ModeChange()); } } if (throttling) { if (left > 0 && left < (int)readsize) { dm->throttleReturnBytes(left - readsize); } uint32_t sleep_interval = dm->throttleCycleTime(); Thread::sleep(sleep_interval); } } break; } } if(mode == MODE_LINE && line.size() > static_cast<size_t>(SETTING(MAX_COMMAND_LENGTH))) { throw SocketException(_("Maximum command length exceeded")); } }
void PostRouteHandler::handleRequest(ServerEventArgs& evt) { try { Poco::Net::HTTPServerResponse& response = evt.getResponse(); // This uuid helps us track form progress updates. std::string postId = Poco::UUIDGenerator::defaultGenerator().createOne().toString(); // Get the content type header (already checked in parent route). Poco::Net::MediaType contentType(evt.getRequest().get("Content-Type", "")); if (contentType.matches(POST_CONTENT_TYPE_URLENCODED) || contentType.matches(POST_CONTENT_TYPE_MULTIPART)) { // Prepare the upload directory if needed. if (contentType.matches(POST_CONTENT_TYPE_MULTIPART)) { ofDirectory _uploadFolder(getRoute().getSettings().getUploadFolder()); if (!_uploadFolder.exists()) { ofLogError("PostRouteHandler::handleRequest") << "Upload folder does not exist and cannot be created."; response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR); getRoute().handleRequest(evt); return; } } PostRouteFileHandler postRoutePartHandler(getRoute(), evt, postId); Poco::Net::HTMLForm form(contentType.toString()); form.setFieldLimit(getRoute().getSettings().getFieldLimit()); form.load(evt.getRequest(), evt.getRequest().stream(), postRoutePartHandler); PostFormEventArgs args(evt, postId, form); ofNotifyEvent(getRoute().events.onHTTPFormEvent, args, &getRoute()); if (form.has("destination") && !form.get("destination").empty()) { response.redirect(form.get("destination")); return; } } else { // Poco::Net::HTMLForm, like php does not handle text/plain because // it cannot be unambiguously encoded. Here we simply return // the raw text with the event. std::string result; Poco::StreamCopier::copyToString(evt.getRequest().stream(), result); ofBuffer buffer(result); PostEventArgs args(evt, postId, buffer); ofNotifyEvent(getRoute().events.onHTTPPostEvent, args, &getRoute()); } if (response.sent()) { return; } else if (!getRoute().getSettings().getUploadRedirect().empty()) { response.redirect(getRoute().getSettings().getUploadRedirect()); return; } else { // done response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_OK); response.setContentLength(0); response.send(); return; } } catch (const Poco::Exception& exc) { evt.getResponse().setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR, exc.displayText()); } catch (const std::exception& exc) { evt.getResponse().setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR, exc.what()); } catch (...) { evt.getResponse().setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR); } }
template <typename Stream> template <typename WriteHandler> BOOST_ASIO_INITFN_RESULT_TYPE(WriteHandler, void (boost::system::error_code, std::size_t)) buffered_write_stream<Stream>::async_flush( BOOST_ASIO_MOVE_ARG(WriteHandler) handler) { // If you get an error on the following line it means that your handler does // not meet the documented type requirements for a WriteHandler. BOOST_ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; async_completion<WriteHandler, void (boost::system::error_code, std::size_t)> init(handler); async_write(next_layer_, buffer(storage_.data(), storage_.size()), detail::buffered_flush_handler<BOOST_ASIO_HANDLER_TYPE( WriteHandler, void (boost::system::error_code, std::size_t))>( storage_, init.completion_handler)); return init.result.get(); } template <typename Stream> template <typename ConstBufferSequence> std::size_t buffered_write_stream<Stream>::write_some( const ConstBufferSequence& buffers) { using boost::asio::buffer_size; if (buffer_size(buffers) == 0) return 0;
// Read a block binary data template< class T > std::vector<T> ReadBinary( u32 count ) { std::vector<T> buffer(count); if( stream.is_open() ) stream.read( (char*)buffer.data(), count * sizeof(T) ); return buffer; }
void ExtendedTableWidget::paste() { // Get list of selected items QItemSelectionModel* selection = selectionModel(); QModelIndexList indices = selection->selectedIndexes(); // Abort if there's nowhere to paste if(indices.isEmpty()) return; SqliteTableModel* m = qobject_cast<SqliteTableModel*>(model()); // We're also checking for system clipboard data first. Only if the data in the system clipboard is not ours, we use the system // clipboard, otherwise we prefer the internal buffer. That's because the data in the internal buffer is easier to parse and more // accurate, too. However, if we always preferred the internal copy-paste buffer there would be no way to copy data from other // applications in here once the internal buffer has been filled. // If clipboard contains an image and no text, just insert the image const QMimeData* mimeClipboard = qApp->clipboard()->mimeData(); if (mimeClipboard->hasImage() && !mimeClipboard->hasText()) { QImage img = qApp->clipboard()->image(); QByteArray ba; QBuffer buffer(&ba); buffer.open(QIODevice::WriteOnly); img.save(&buffer, "PNG"); // We're always converting the image format to PNG here. TODO: Is that correct? buffer.close(); m->setData(indices.first(), ba); return; } // Get the clipboard text QString clipboard = qApp->clipboard()->text(); // If data in system clipboard is ours and the internal copy-paste buffer is filled, use the internal buffer; otherwise parse the // system clipboard contents (case for data copied by other application). QList<QByteArrayList> clipboardTable; QList<QByteArrayList>* source; if(mimeClipboard->hasHtml() && mimeClipboard->html().contains(m_generatorStamp) && !m_buffer.isEmpty()) { source = &m_buffer; } else { clipboardTable = parseClipboard(clipboard); source = &clipboardTable; } // Stop here if there's nothing to paste if(!source->size()) return; // Starting from assumption that selection is rectangular, and then first index is upper-left corner and last is lower-right. int rows = source->size(); int columns = source->first().size(); int firstRow = indices.front().row(); int firstColumn = indices.front().column(); int selectedRows = indices.back().row() - firstRow + 1; int selectedColumns = indices.back().column() - firstColumn + 1; // If last row and column are after table size, clamp it int lastRow = qMin(firstRow + rows - 1, m->rowCount() - 1); int lastColumn = qMin(firstColumn + columns - 1, m->columnCount() - 1); // Special case: if there is only one cell of data to be pasted, paste it into all selected fields if(rows == 1 && columns == 1) { QByteArray data = source->first().first(); for(int row=firstRow;row<firstRow+selectedRows;row++) { for(int column=firstColumn;column<firstColumn+selectedColumns;column++) m->setData(m->index(row, column), data); } return; } // If more than one cell was selected, check if the selection matches the cliboard dimensions if(selectedRows != rows || selectedColumns != columns) { // Ask user if they are sure about this if(QMessageBox::question(this, QApplication::applicationName(), tr("The content of the clipboard is bigger than the range selected.\nDo you want to insert it anyway?"), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) { // If the user doesn't want to paste the clipboard data anymore, stop now return; } } // If we get here, we can definitely start pasting: either the ranges match in their size or the user agreed to paste anyway // Copy the data cell by cell and as-is from the source buffer to the table int row = firstRow; for(const QByteArrayList& source_row : *source) { int column = firstColumn; for(const QByteArray& source_cell : source_row) { m->setData(m->index(row, column), source_cell); column++; if (column > lastColumn) break; } row++; if (row > lastRow) break; } }
int main(int argc, char** argv) { std::cout << "Image from string..." << std::endl; if (argc!=3) { std::cout << "Usage:" << argv[0] << " <path-to-image-file> <num_runs>" << std::endl; return 1; } unsigned NUM_RUNS = std::atoi(argv[2]); std::string filename(argv[1]); // node-blend { std::cerr << "========== Node-blend ImageReader FROM FILE" << std::endl; std::cout << "NUM_RUNS="<<NUM_RUNS << std::endl; boost::timer::auto_cpu_timer t; for (unsigned count=0; count < NUM_RUNS; ++count) { std::ifstream is(filename.c_str() , std::ios::binary); std::string buffer((std::istreambuf_iterator<char>(is)), std::istreambuf_iterator<char>()); const std::unique_ptr<ImageReader> layer(ImageReader::create((uint8_t*)buffer.data(),buffer.size())); layer->decode(); } } { // mapnik std::cerr << "========== Mapnik image_reader FROM FILE" << std::endl; std::cout << "NUM_RUNS="<<NUM_RUNS << std::endl; boost::timer::auto_cpu_timer t; for (unsigned count=0; count < NUM_RUNS; ++count) { try { const std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(filename)); unsigned width = reader->width(); unsigned height = reader->height(); mapnik::image_data_32 buffer(width,height); reader->read(0,0,buffer); } catch (mapnik::image_reader_exception const& ex) { std::cerr << ex.what() << std::endl; } catch( std::exception const& ex) { std::cerr << ex.what() << std::endl; } } } std::ifstream is(filename.c_str() , std::ios::binary); std::string buffer((std::istreambuf_iterator<char>(is)), std::istreambuf_iterator<char>()); // node-blend { std::cerr << "========== Node-blend ImageReader FROM MEM BUFFER" << std::endl; std::cout << "NUM_RUNS="<<NUM_RUNS << std::endl; boost::timer::auto_cpu_timer t; for (unsigned count=0; count < NUM_RUNS; ++count) { const std::unique_ptr<ImageReader> layer(ImageReader::create((uint8_t*)buffer.data(),buffer.size())); layer->decode(); } } { // mapnik std::cerr << "========== Mapnik image_reader FROM MEM BUFFER" << std::endl; std::cout << "NUM_RUNS="<<NUM_RUNS << std::endl; boost::timer::auto_cpu_timer t; for (unsigned count=0; count < NUM_RUNS; ++count) { try { const std::unique_ptr<mapnik::image_reader> reader(mapnik::get_image_reader(buffer.data(), buffer.size())); unsigned width = reader->width(); unsigned height = reader->height(); mapnik::image_data_32 buffer(width,height); reader->read(0,0,buffer); } catch (mapnik::image_reader_exception const& ex) { std::cerr << ex.what() << std::endl; } catch( std::exception const& ex) { std::cerr << ex.what() << std::endl; } } } return 0; }
void ExtendedTableWidget::copy(const bool withHeaders) { QModelIndexList indices = selectionModel()->selectedIndexes(); // Remove all indices from hidden columns, because if we don't we might copy data from hidden columns as well which is very // unintuitive; especially copying the rowid column when selecting all columns of a table is a problem because pasting the data // won't work as expected. QMutableListIterator<QModelIndex> i(indices); while (i.hasNext()) { if (isColumnHidden(i.next().column())) i.remove(); } // Abort if there's nothing to copy if (indices.isEmpty()) return; SqliteTableModel* m = qobject_cast<SqliteTableModel*>(model()); // Clear internal copy-paste buffer m_buffer.clear(); // If a single cell is selected, copy it to clipboard if (!withHeaders && indices.size() == 1) { QImage img; QVariant data = m->data(indices.first(), Qt::EditRole); if (img.loadFromData(data.toByteArray())) { // If it's an image, copy the image data to the clipboard qApp->clipboard()->setImage(img); return; } else { // It it's not an image, check if it's an empty field if (data.toByteArray().isEmpty()) { // The field is either NULL or empty. Those are are handled via the internal copy-paste buffer qApp->clipboard()->setText(QString()); // Calling clear() alone doesn't seem to work on all systems qApp->clipboard()->clear(); m_buffer.push_back(QByteArrayList{data.toByteArray()}); return; } // The field isn't empty. Copy the text to the clipboard without quoting (for general plain text clipboard) qApp->clipboard()->setText(data.toByteArray()); return; } } // If we got here, there are multiple selected cells, or copy with headers was requested. // In this case, we copy selected data into internal copy-paste buffer and then // we write a table both in HTML and text formats to the system clipboard. // Copy selected data into internal copy-paste buffer int last_row = indices.first().row(); QByteArrayList lst; for(int i=0;i<indices.size();i++) { if(indices.at(i).row() != last_row) { m_buffer.push_back(lst); lst.clear(); } lst << indices.at(i).data(Qt::EditRole).toByteArray(); last_row = indices.at(i).row(); } m_buffer.push_back(lst); QString result; QString htmlResult = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"; htmlResult.append("<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">"); htmlResult.append("<title></title>"); // The generator-stamp is later used to know whether the data in the system clipboard is still ours. // In that case we will give precedence to our internal copy buffer. QString now = QDateTime::currentDateTime().toString("YYYY-MM-DDTHH:mm:ss.zzz"); m_generatorStamp = QString("<meta name=\"generator\" content=\"%1\"><meta name=\"date\" content=\"%2\">").arg(QApplication::applicationName().toHtmlEscaped(), now); htmlResult.append(m_generatorStamp); // TODO: is this really needed by Excel, since we use <pre> for multi-line cells? htmlResult.append("<style type=\"text/css\">br{mso-data-placement:same-cell;}</style></head><body><table>"); int currentRow = indices.first().row(); const QString fieldSepHtml = "</td><td>"; const QString rowSepHtml = "</td></tr><tr><td>"; const QString fieldSepText = "\t"; const QString rowSepText = "\r\n"; // Table headers if (withHeaders) { htmlResult.append("<tr><th>"); int firstColumn = indices.front().column(); for(int i = firstColumn; i <= indices.back().column(); i++) { QByteArray headerText = model()->headerData(i, Qt::Horizontal, Qt::DisplayRole).toByteArray(); if (i != firstColumn) { result.append(fieldSepText); htmlResult.append("</th><th>"); } result.append(escapeCopiedData(headerText)); htmlResult.append(headerText); } result.append(rowSepText); htmlResult.append("</th></tr>"); } // Table data rows for(const QModelIndex& index : indices) { // Separators. For first cell, only opening table row tags must be added for the HTML and nothing for the text version. if (indices.first() == index) htmlResult.append("<tr><td>"); else if (index.row() != currentRow) { result.append(rowSepText); htmlResult.append(rowSepHtml); } else { result.append(fieldSepText); htmlResult.append(fieldSepHtml); } currentRow = index.row(); QImage img; QVariant data = index.data(Qt::EditRole); // Table cell data: image? Store it as an embedded image in HTML and as base 64 in text version if (img.loadFromData(data.toByteArray())) { QByteArray ba; QBuffer buffer(&ba); buffer.open(QIODevice::WriteOnly); img.save(&buffer, "PNG"); buffer.close(); QString imageBase64 = ba.toBase64(); htmlResult.append("<img src=\"data:image/png;base64,"); htmlResult.append(imageBase64); result.append(QString()); htmlResult.append("\" alt=\"Image\">"); } else { QByteArray text; if (!m->isBinary(index)) text = data.toByteArray(); // Table cell data: text if (text.contains('\n') || text.contains('\t')) htmlResult.append("<pre>" + QString(text).toHtmlEscaped() + "</pre>"); else htmlResult.append(QString(text).toHtmlEscaped()); result.append(escapeCopiedData(text)); } } QMimeData *mimeData = new QMimeData; mimeData->setHtml(htmlResult + "</td></tr></table></body></html>"); mimeData->setText(result); qApp->clipboard()->setMimeData(mimeData); }
void SkFlatPaint::dump() const { SkPaint defaultPaint; SkFlattenableReadBuffer buffer(fPaintData); SkTypeface* typeface = (SkTypeface*) buffer.readPtr(); char pBuffer[DUMP_BUFFER_SIZE]; char* bufferPtr = pBuffer; bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "paint: "); if (typeface != defaultPaint.getTypeface()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "typeface:%p ", typeface); SkScalar textSize = buffer.readScalar(); if (textSize != defaultPaint.getTextSize()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "textSize:%g ", SkScalarToFloat(textSize)); SkScalar textScaleX = buffer.readScalar(); if (textScaleX != defaultPaint.getTextScaleX()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "textScaleX:%g ", SkScalarToFloat(textScaleX)); SkScalar textSkewX = buffer.readScalar(); if (textSkewX != defaultPaint.getTextSkewX()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "textSkewX:%g ", SkScalarToFloat(textSkewX)); const SkPathEffect* pathEffect = (const SkPathEffect*) buffer.readFlattenable(); if (pathEffect != defaultPaint.getPathEffect()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "pathEffect:%p ", pathEffect); SkDELETE(pathEffect); const SkShader* shader = (const SkShader*) buffer.readFlattenable(); if (shader != defaultPaint.getShader()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "shader:%p ", shader); SkDELETE(shader); const SkXfermode* xfermode = (const SkXfermode*) buffer.readFlattenable(); if (xfermode != defaultPaint.getXfermode()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "xfermode:%p ", xfermode); SkDELETE(xfermode); const SkMaskFilter* maskFilter = (const SkMaskFilter*) buffer.readFlattenable(); if (maskFilter != defaultPaint.getMaskFilter()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "maskFilter:%p ", maskFilter); SkDELETE(maskFilter); const SkColorFilter* colorFilter = (const SkColorFilter*) buffer.readFlattenable(); if (colorFilter != defaultPaint.getColorFilter()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "colorFilter:%p ", colorFilter); SkDELETE(colorFilter); const SkRasterizer* rasterizer = (const SkRasterizer*) buffer.readFlattenable(); if (rasterizer != defaultPaint.getRasterizer()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "rasterizer:%p ", rasterizer); SkDELETE(rasterizer); const SkDrawLooper* drawLooper = (const SkDrawLooper*) buffer.readFlattenable(); if (drawLooper != defaultPaint.getLooper()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "drawLooper:%p ", drawLooper); SkDELETE(drawLooper); unsigned color = buffer.readU32(); if (color != defaultPaint.getColor()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "color:0x%x ", color); SkScalar strokeWidth = buffer.readScalar(); if (strokeWidth != defaultPaint.getStrokeWidth()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "strokeWidth:%g ", SkScalarToFloat(strokeWidth)); SkScalar strokeMiter = buffer.readScalar(); if (strokeMiter != defaultPaint.getStrokeMiter()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "strokeMiter:%g ", SkScalarToFloat(strokeMiter)); unsigned flags = buffer.readU16(); if (flags != defaultPaint.getFlags()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "flags:0x%x ", flags); int align = buffer.readU8(); if (align != defaultPaint.getTextAlign()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "align:0x%x ", align); int strokeCap = buffer.readU8(); if (strokeCap != defaultPaint.getStrokeCap()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "strokeCap:0x%x ", strokeCap); int strokeJoin = buffer.readU8(); if (strokeJoin != defaultPaint.getStrokeJoin()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "align:0x%x ", strokeJoin); int style = buffer.readU8(); if (style != defaultPaint.getStyle()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "style:0x%x ", style); int textEncoding = buffer.readU8(); if (textEncoding != defaultPaint.getTextEncoding()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "textEncoding:0x%x ", textEncoding); SkDebugf("%s\n", pBuffer); }
std::u32string read_with_bom(std::istream & src) { enum encoding { encoding_utf32be = 0, encoding_utf32le, encoding_utf16be, encoding_utf16le, encoding_utf8, encoding_ascii, }; std::vector<std::string> boms = { std::string("\x00\x00\xFE\xFF", 4), std::string("\xFF\xFE\x00\x00", 4), std::string("\xFE\xFF", 2), std::string("\xFF\xFE", 2), std::string("\xEF\xBB\xBF", 3) }; std::string buffer((std::istreambuf_iterator<char>(src)), std::istreambuf_iterator<char>()); encoding enc = encoding_ascii; for (unsigned int i = 0; i < boms.size(); ++i) { std::string testBom = boms[i]; if (buffer.compare(0, testBom.length(), testBom) == 0) { enc = encoding(i); buffer = buffer.substr(testBom.length()); break; } } switch (enc) { case encoding_utf32be: { if (buffer.length() % 4 != 0) { throw std::logic_error("size in bytes must be a multiple of 4"); } int count = buffer.length() / 4; std::u32string temp = std::u32string(count, 0); for (int i = 0; i < count; ++i) { temp[i] = static_cast<char32_t>(buffer[i * 4 + 3] << 0 | buffer[i * 4 + 2] << 8 | buffer[i * 4 + 1] << 16 | buffer[i * 4 + 0] << 24); } return temp; } case encoding_utf32le: { if (buffer.length() % 4 != 0) { throw std::logic_error("size in bytes must be a multiple of 4"); } int count = buffer.length() / 4; std::u32string temp = std::u32string(count, 0); for (int i = 0; i < count; ++i) { temp[i] = static_cast<char32_t>(buffer[i * 4 + 0] << 0 | buffer[i * 4 + 1] << 8 | buffer[i * 4 + 2] << 16 | buffer[i * 4 + 3] << 24); } return temp; } case encoding_utf16be: { if (buffer.length() % 2 != 0) { throw std::logic_error("size in bytes must be a multiple of 2"); } int count = buffer.length() / 2; std::u16string temp = std::u16string(count, 0); for (int i = 0; i < count; ++i) { temp[i] = static_cast<char16_t>(buffer[i * 2 + 1] << 0 | buffer[i * 2 + 0] << 8); } return to_utf32(temp); } case encoding_utf16le: { if (buffer.length() % 2 != 0) { throw std::logic_error("size in bytes must be a multiple of 2"); } int count = buffer.length() / 2; std::u16string temp = std::u16string(count, 0); for (int i = 0; i < count; ++i) { temp[i] = static_cast<char16_t>(buffer[i * 2 + 0] << 0 | buffer[i * 2 + 1] << 8); } return to_utf32(temp); } default: return to_utf32(buffer); } }
void NoGhostGameofLife::update_neighbor_values_with_remote_elements() { stk::CommSparse buffer(m_bulkData->parallel()); send_num_active_neighbors_of_remote_elem_keys(buffer); recieve_num_active_neighbors_of_local_elements(buffer);; }
bool AudioBufferSourceNode::renderFromBuffer(ContextRenderLock& r, AudioBus* bus, unsigned destinationFrameOffset, size_t numberOfFrames) { if (!r.context()) return false; // Basic sanity checking ASSERT(bus); ASSERT(buffer()); if (!bus || !buffer()) return false; unsigned numChannels = numberOfChannels(r); unsigned busNumberOfChannels = bus->numberOfChannels(); bool channelCountGood = numChannels && numChannels == busNumberOfChannels; ASSERT(channelCountGood); if (!channelCountGood) return false; // Sanity check destinationFrameOffset, numberOfFrames. size_t destinationLength = bus->length(); bool isLengthGood = destinationLength <= 4096 && numberOfFrames <= 4096; ASSERT(isLengthGood); if (!isLengthGood) return false; bool isOffsetGood = destinationFrameOffset <= destinationLength && destinationFrameOffset + numberOfFrames <= destinationLength; ASSERT(isOffsetGood); if (!isOffsetGood) return false; // Potentially zero out initial frames leading up to the offset. if (destinationFrameOffset) { for (unsigned i = 0; i < numChannels; ++i) memset(m_destinationChannels[i], 0, sizeof(float) * destinationFrameOffset); } // Offset the pointers to the correct offset frame. unsigned writeIndex = destinationFrameOffset; size_t bufferLength = buffer()->length(); double bufferSampleRate = buffer()->sampleRate(); // Avoid converting from time to sample-frames twice by computing // the grain end time first before computing the sample frame. unsigned endFrame = m_isGrain ? AudioUtilities::timeToSampleFrame(m_grainOffset + m_grainDuration, bufferSampleRate) : bufferLength; // This is a HACK to allow for HRTF tail-time - avoids glitch at end. // FIXME: implement tailTime for each AudioNode for a more general solution to this problem. // https://bugs.webkit.org/show_bug.cgi?id=77224 if (m_isGrain) endFrame += 512; // Do some sanity checking. if (endFrame > bufferLength) endFrame = bufferLength; if (m_virtualReadIndex >= endFrame) m_virtualReadIndex = 0; // reset to start // If the .loop attribute is true, then values of m_loopStart == 0 && m_loopEnd == 0 implies // that we should use the entire buffer as the loop, otherwise use the loop values in m_loopStart and m_loopEnd. double virtualEndFrame = endFrame; double virtualDeltaFrames = endFrame; if (loop() && (m_loopStart || m_loopEnd) && m_loopStart >= 0 && m_loopEnd > 0 && m_loopStart < m_loopEnd) { // Convert from seconds to sample-frames. double loopStartFrame = m_loopStart * buffer()->sampleRate(); double loopEndFrame = m_loopEnd * buffer()->sampleRate(); virtualEndFrame = std::min(loopEndFrame, virtualEndFrame); virtualDeltaFrames = virtualEndFrame - loopStartFrame; } double pitchRate = totalPitchRate(r); // Sanity check that our playback rate isn't larger than the loop size. if (fabs(pitchRate) >= virtualDeltaFrames) return false; // Get local copy. double virtualReadIndex = m_virtualReadIndex; // Render loop - reading from the source buffer to the destination using linear interpolation. int framesToProcess = numberOfFrames; const float** sourceChannels = m_sourceChannels.get(); float** destinationChannels = m_destinationChannels.get(); // Optimize for the very common case of playing back with pitchRate == 1. // We can avoid the linear interpolation. if (pitchRate == 1 && virtualReadIndex == floor(virtualReadIndex) && virtualDeltaFrames == floor(virtualDeltaFrames) && virtualEndFrame == floor(virtualEndFrame)) { unsigned readIndex = static_cast<unsigned>(virtualReadIndex); unsigned deltaFrames = static_cast<unsigned>(virtualDeltaFrames); endFrame = static_cast<unsigned>(virtualEndFrame); while (framesToProcess > 0) { int framesToEnd = endFrame - readIndex; int framesThisTime = std::min(framesToProcess, framesToEnd); framesThisTime = std::max(0, framesThisTime); for (unsigned i = 0; i < numChannels; ++i) memcpy(destinationChannels[i] + writeIndex, sourceChannels[i] + readIndex, sizeof(float) * framesThisTime); writeIndex += framesThisTime; readIndex += framesThisTime; framesToProcess -= framesThisTime; // Wrap-around. if (readIndex >= endFrame) { readIndex -= deltaFrames; if (renderSilenceAndFinishIfNotLooping(r, bus, writeIndex, framesToProcess)) break; } } virtualReadIndex = readIndex; } else { while (framesToProcess--) { unsigned readIndex = static_cast<unsigned>(virtualReadIndex); double interpolationFactor = virtualReadIndex - readIndex; // For linear interpolation we need the next sample-frame too. unsigned readIndex2 = readIndex + 1; if (readIndex2 >= bufferLength) { if (loop()) { // Make sure to wrap around at the end of the buffer. readIndex2 = static_cast<unsigned>(virtualReadIndex + 1 - virtualDeltaFrames); } else readIndex2 = readIndex; } // Final sanity check on buffer access. // FIXME: as an optimization, try to get rid of this inner-loop check and put assertions and guards before the loop. if (readIndex >= bufferLength || readIndex2 >= bufferLength) break; // Linear interpolation. for (unsigned i = 0; i < numChannels; ++i) { float* destination = destinationChannels[i]; const float* source = sourceChannels[i]; double sample1 = source[readIndex]; double sample2 = source[readIndex2]; double sample = (1.0 - interpolationFactor) * sample1 + interpolationFactor * sample2; destination[writeIndex] = narrowPrecisionToFloat(sample); } writeIndex++; virtualReadIndex += pitchRate; // Wrap-around, retaining sub-sample position since virtualReadIndex is floating-point. if (virtualReadIndex >= virtualEndFrame) { virtualReadIndex -= virtualDeltaFrames; if (renderSilenceAndFinishIfNotLooping(r, bus, writeIndex, framesToProcess)) break; } } } bus->clearSilentFlag(); m_virtualReadIndex = virtualReadIndex; return true; }
ZTuple ZClipboard::Get() { #if ZCONFIG(OS, MacOS7) SInt16 currentScrapCount = ::InfoScrap()->scrapCount; if (fLastKnownScrapCount != currentScrapCount) { fLastKnownScrapCount = currentScrapCount; fTuple = ZTuple(); // Walk through all the registered types and suck any data that might be on the clipboard into our tuple size_t theCount = ZDragClipManager::sGet()->Count(); for (size_t x = 0; x < theCount; ++x) { string currentMIME = ZDragClipManager::sGet()->At(x); bool isString; ScrapFlavorType theScrapFlavorType; if (ZDragClipManager::sGet()->LookupMIME(currentMIME, theScrapFlavorType, isString)) { SInt32 theOffset = 0; SInt32 theLength = ::GetScrap(nil, theScrapFlavorType, &theOffset); if (theLength >= 0) { // Creates a zero-length handle, rather than a NULL handle ZHandle theHandle(0); theLength = ::GetScrap(theHandle.GetMacHandle(), theScrapFlavorType, &theOffset); // AG 99-01-07. For the moment we're ignoring the value of theOffset, which indicates the order in which // different data items were written to the desk scrap, and hence their preference level. if (theHandle.GetSize() == theLength) { ZHandle::Ref theRef(theHandle); if (isString) fTuple.SetString(currentMIME, string(reinterpret_cast<char*>(theRef.GetData()), theRef.GetSize())); else fTuple.SetRaw(currentMIME, theRef.GetData(), theRef.GetSize()); } } } } } return fTuple; #elif ZCONFIG(OS, Carbon) || ZCONFIG(OS, MacOSX) ScrapRef currentScrapRef; ::GetCurrentScrap(¤tScrapRef); if (fLastKnownScrapRef != currentScrapRef) { fLastKnownScrapRef = currentScrapRef; fTuple = ZTuple(); // Walk through all the registered types and suck any data that might be on the clipboard into our tuple size_t theCount = ZDragClipManager::sGet()->Count(); for (size_t x = 0; x < theCount; ++x) { string currentMIME = ZDragClipManager::sGet()->At(x); bool isString; ScrapFlavorType flavorType; if (ZDragClipManager::sGet()->LookupMIME(currentMIME, flavorType, isString)) { ScrapFlavorFlags flavorFlags; if (noErr == ::GetScrapFlavorFlags(currentScrapRef, flavorType, &flavorFlags)) { Size availByteCount = 0; OSStatus status = ::GetScrapFlavorSize(currentScrapRef, flavorType, &availByteCount); if ((status == noErr) && (availByteCount >= 0)) { vector<uint8> buffer(availByteCount); Size actualByteCount = availByteCount; status = ::GetScrapFlavorData(currentScrapRef, flavorType, &actualByteCount, &buffer[0]); if (actualByteCount == availByteCount) { if (isString) fTuple.SetString(currentMIME, string(reinterpret_cast<char*>(&buffer[0]), availByteCount)); else fTuple.SetRaw(currentMIME, &buffer[0], availByteCount); } } } } } } return fTuple; #elif ZCONFIG(OS, Win32) return sWin32_Get(); #else ZDebugLogf(0, ("ZClipboard::Get(), Unsupported platform")); return ZTuple(); #endif }
void AudioBufferSourceNode::process(ContextRenderLock& r, size_t framesToProcess) { AudioBus* outputBus = output(0)->bus(r); if (!buffer() || !isInitialized() || ! r.context()) { outputBus->zero(); return; } // After calling setBuffer() with a buffer having a different number of channels, there can in rare cases be a slight delay // before the output bus is updated to the new number of channels because of use of tryLocks() in the context's updating system. // In this case, if the the buffer has just been changed and we're not quite ready yet, then just output silence. if (numberOfChannels(r) != buffer()->numberOfChannels()) { outputBus->zero(); return; } if (m_startRequested) { // Do sanity checking of grain parameters versus buffer size. double bufferDuration = buffer()->duration(); double grainOffset = std::max(0.0, m_requestGrainOffset); m_grainOffset = std::min(bufferDuration, grainOffset); m_grainOffset = grainOffset; // Handle default/unspecified duration. double maxDuration = bufferDuration - grainOffset; double grainDuration = m_requestGrainDuration; if (!grainDuration) grainDuration = maxDuration; grainDuration = std::max(0.0, grainDuration); grainDuration = std::min(maxDuration, grainDuration); m_grainDuration = grainDuration; m_isGrain = true; m_startTime = m_requestWhen; // We call timeToSampleFrame here since at playbackRate == 1 we don't want to go through linear interpolation // at a sub-sample position since it will degrade the quality. // When aligned to the sample-frame the playback will be identical to the PCM data stored in the buffer. // Since playbackRate == 1 is very common, it's worth considering quality. m_virtualReadIndex = AudioUtilities::timeToSampleFrame(m_grainOffset, buffer()->sampleRate()); m_startRequested = false; } size_t quantumFrameOffset; size_t bufferFramesToProcess; updateSchedulingInfo(r, framesToProcess, outputBus, quantumFrameOffset, bufferFramesToProcess); if (!bufferFramesToProcess) { outputBus->zero(); return; } for (unsigned i = 0; i < outputBus->numberOfChannels(); ++i) { m_destinationChannels[i] = outputBus->channel(i)->mutableData(); } // Render by reading directly from the buffer. if (!renderFromBuffer(r, outputBus, quantumFrameOffset, bufferFramesToProcess)) { outputBus->zero(); return; } // Apply the gain (in-place) to the output bus. float totalGain = gain()->value(r) * m_buffer->gain(); outputBus->copyWithGainFrom(*outputBus, &m_lastGain, totalGain); outputBus->clearSilentFlag(); }
bool Favoris::add(TFavoris * fav) { QSqlQuery requete(db_fav); QDialog fenetre(this); QComboBox liste_dossiers; QLineEdit champ_nom(fav->nom); QDialogButtonBox btn(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal); QFormLayout layout; QStringList dossiers; liste_dossiers.setEditable(true); layout.addRow("nom du favoris :",&champ_nom); layout.addRow("Dossier :",&liste_dossiers); layout.addRow(&btn); fenetre.setLayout(&layout); connect(&btn,SIGNAL(accepted()),&fenetre,SLOT(accept())); connect(&btn,SIGNAL(rejected()),&fenetre,SLOT(close())); //on remplit la liste des dossiers if(requete.exec("Select nom_dossier from dossiers")) { while(requete.next()) dossiers << requete.value(0).toString(); } else QMessageBox::critical(this,"Erreur","Problème survenu lors de la lecture des dossiers : " + requete.lastError().text()); liste_dossiers.addItems(dossiers); if(fenetre.exec()) //si on click sur Save { QByteArray bytes; QBuffer buffer(&bytes); buffer.open(QIODevice::WriteOnly); QPixmap pix = fav->favicon.pixmap(16,16); pix.save(&buffer,"png"); requete.prepare("INSERT INTO adresses (url,nom_favoris,dossier,favicon) VALUES (:url,:nom,:dossier,:favicon);"); requete.bindValue(":url",fav->url,QSql::In); requete.bindValue(":nom",champ_nom.text(),QSql::In); requete.bindValue(":dossier",liste_dossiers.currentText(),QSql::In); requete.bindValue(":favicon",buffer.data(),QSql::In | QSql::Binary); buffer.close(); if(dossiers.contains(liste_dossiers.currentText())) //si le dossier existe déjà { if(!requete.exec()) { QMessageBox::critical(this,"Erreur","Problème survenu lors de l'enregistrement' : " + requete.lastError().text()); return false; } } else //sinon on doit l'ajouter dans la base de données... { //if(!requete.exec("INSERT INTO adresses (url,nom_favoris,dossier,favicon) VALUES ('"+fav->url+"','"+champ_nom.text()+"','"+liste_dossiers.currentText()+"','"+QVariant(fav->favicon).toByteArray()+"');")) if(!requete.exec()) { QMessageBox::critical(this,"Erreur","Problème survenu lors de l'enregistrement (adresse) : " + requete.lastError().text()); return false; } if(!requete.exec("INSERT INTO dossiers (nom_dossier,parent) VALUES ('"+liste_dossiers.currentText()+"','favoris');")) { QMessageBox::critical(this,"Erreur","Problème survenu lors de l'enregistrement (dossier) : " + requete.lastError().text()); return false; } } } else return false; //si l'enregistrement à merdé... fav->nom = champ_nom.text(); //nom sous lequel le lien à été enregitsré fav->path = liste_dossiers.currentText(); //nom du dossier dans lequel l'ajout à été fait... return true; //si l'enregistrement s'est bien passé }
int main(int argc, char** argv) { std::string fileName = "link_chunk.dat"; if (argc>1 && argv != nullptr) { if (argv[1] != nullptr) { fileName = std::string(argv[1]); } } //if std::cout << "Trying to read link chunk from \"" << fileName << "\"..." << std::endl; std::ifstream inFileStream; inFileStream.open(fileName, std::ios_base::in | std::ios_base::binary); if (!inFileStream.is_open() || !inFileStream.good()) { std::cout << "Error: Could not open file " << fileName << "!" << std::endl; return 1; } const unsigned int bufferSize = 1024; std::unique_ptr<char[]> buffer(new char[bufferSize]); std::memset(buffer.get(), 0, bufferSize); inFileStream.getline(buffer.get(), bufferSize-1, '\n'); if (!inFileStream.good()) { std::cout << "Unable to read chunk header from stream!" << std::endl; return false; } std::string line = std::string(buffer.get()); libuhs::removeTrailingCarriageReturn(line); const auto pieces = libuhs::splitAtSeparator(line, ' '); if (pieces.size() != 2) { std::cout << "Error: line contains " << pieces.size() << " pieces instead of two!" << std::endl; return 1; } //check if it is a link chunk if (pieces[1] != "link") { std::cout << "Error: expected link chunk, but found \"" << pieces[1] << "\" instead!" << std::endl; return 1; } unsigned int linesTotal = 0; if (!libuhs::stringToUnsignedInt<unsigned int>(pieces[0], linesTotal)) { std::cout << "Error: \"" << pieces[0] << "\" is not an unsigned integer!" << std::endl; return 1; } if (linesTotal!=3) { std::cout << "Error: expected line count to be three (3), but found \"" << linesTotal << "\" instead!" << std::endl; return 1; } libuhs::LinkChunk lc(1, "", 0); try { bool success = lc.readFromStream(inFileStream, linesTotal); inFileStream.close(); if (!success) { std::cout << "Error: Reading link chunk failed!" << std::endl; return 1; } std::cout << "Info: Successfully read link chunk from file!" << std::endl; std::cout << " Label: " << lc.getLabel() << std::endl << " Destination: " << lc.destinationLine << std::endl; if (lc == cExpected) { std::cout << "Link chunk data matches the expected result." << std::endl; } else { std::cout << "Error: Link chunk data does NOT match the expected result." << std::endl; return 1; } } catch(std::exception& except) { std::cout << "Caught exception: " << except.what() << std::endl; if (inFileStream.is_open()) inFileStream.close(); return 1; } //try-catch if (inFileStream.is_open()) inFileStream.close(); return 0; }
void PostRouteFileHandler::handlePart(const Poco::Net::MessageHeader& header, std::istream& stream) { if (header.has("Content-Type")) { std::string contentType = header["Content-Type"]; if (!_route.getSettings().getValidContentTypes().empty() && !isContentTypeValid(contentType)) { ofLogError("PostRouteFileHandler::handlePart") << "Invalid content type: " << contentType; return; // reject } } else { ofLogError("PostRouteFileHandler::handlePart") << "No Content-Type header."; return; } // Is this an uploaded file and are we allowing files to be uploaded? if (header.has("Content-Disposition") && _route.getSettings().getMaximumFileUploadSize() > 0) { std::string contentDisposition = header["Content-Disposition"]; Poco::Net::NameValueCollection parameters; Poco::Net::MessageHeader::splitParameters(contentDisposition.begin(), contentDisposition.end(), parameters); std::string formFileName = parameters.get("filename", ""); std::string formFieldName = parameters.get("name", ""); if(!formFileName.empty()) { try { std::stringstream ss; ss << _route.getSettings().getUploadFolder(); ss << "/"; ss << Poco::UUIDGenerator::defaultGenerator().createOne().toString(); ss << "."; ss << Poco::Path(formFileName).getExtension(); std::string newFilename = ofToDataPath(ss.str(), true); ofFile file(newFilename, ofFile::WriteOnly,true); Poco::Net::MediaType contentType(header["Content-Type"]); PostUploadEventArgs args(_evt, _postId, formFieldName, formFileName, newFilename, contentType, 0, PostUploadEventArgs::UPLOAD_STARTING); ofNotifyEvent(_route.events.onHTTPUploadEvent, args, &_route); ofLogVerbose("PostRouteFileHandler::handlePart") << "Writing file to absolute path : " << file.getAbsolutePath(); // The section below is from StreamCopier::copyStream, // and might be used for upload progress feedback Poco::Buffer<char> buffer(_route.getSettings().getWriteBufferSize()); stream.read(buffer.begin(), _route.getSettings().getWriteBufferSize()); unsigned long long sz = 0; unsigned long long n = stream.gcount(); while (n > 0) { if (sz > _route.getSettings().getMaximumFileUploadSize()) { ofLogError("PostRouteFileHandler::handlePart") << "File upload size exceeded. Removing file."; file.close(); ofFile::removeFile(newFilename, false); return; } sz += n; file.write(buffer.begin(), n); if (stream && file) { stream.read(buffer.begin(), _route.getSettings().getWriteBufferSize()); n = stream.gcount(); } else { n = 0; } PostUploadEventArgs uploadArgs(_evt, _postId, formFieldName, formFileName, newFilename, contentType, sz, PostUploadEventArgs::UPLOAD_PROGRESS); ofNotifyEvent(_route.events.onHTTPUploadEvent, uploadArgs, &_route); } file.close(); PostUploadEventArgs finishedArgs(_evt, _postId, formFieldName, formFileName, newFilename, contentType, sz, PostUploadEventArgs::UPLOAD_FINISHED); ofNotifyEvent(_route.events.onHTTPUploadEvent, finishedArgs, &_route); } catch (const Poco::Exception& exc) { ofLogError("PostRouteFileHandler::handlePart") << exc.displayText(); } catch (const std::exception& exc) { ofLogError("PostRouteFileHandler::handlePart") << exc.what(); } catch ( ... ) { ofLogError("PostRouteFileHandler::handlePart") << "Uncaught thread exception: Unknown exception."; } } else { ofLogError("PostRouteFileHandler::handlePart") << "No filename in header."; } } }
void Dialog::GetDlgItemText(int id_item, std::wstring& output) { int len = ::GetWindowTextLength(GetDlgItem(id_item)) + 1; std::vector<wchar_t> buffer(len); ::GetDlgItemText(window_, id_item, &buffer[0], len); output.assign(&buffer[0]); }
friend inline Type buffer_cast(const scoped_buffer_type& _buffer) { return boost::asio::buffer_cast<Type>(buffer(_buffer)); }
std::wstring Dialog::GetDlgItemText(int id_item) { int len = ::GetWindowTextLength(GetDlgItem(id_item)) + 1; std::vector<wchar_t> buffer(len); ::GetDlgItemText(window_, id_item, &buffer[0], len); return std::wstring(&buffer[0]); }
friend inline typename memory_pool::buffer_type buffer(typename memory_pool::shared_buffer_type _buffer, size_t size) { return buffer(*_buffer, size); }
TEST(CircularBuffer, Capacity) { CircularBuffer buffer(2); LONGS_EQUAL(2, buffer.Capacity()); }
void StepWorldV1Lambda(world_t &world, float dt, unsigned n) { unsigned w = world.w, h = world.h; float outer = world.alpha * dt; // We spread alpha to other cells per time float inner = 1 - outer / 4; // Anything that doesn't spread stays // This is our temporary working space std::vector<float> buffer(w * h); auto kernel_xy = [&](unsigned x, unsigned y) { unsigned index = y * w + x; if ((world.properties[index] & Cell_Fixed) || (world.properties[index] & Cell_Insulator)) { // Do nothing, this cell never changes (e.g. a boundary, or an interior // fixed-value heat-source) buffer[index] = world.state[index]; } else { float contrib = inner; float acc = inner * world.state[index]; // Cell above if (!(world.properties[index - w] & Cell_Insulator)) { contrib += outer; acc += outer * world.state[index - w]; } // Cell below if (!(world.properties[index + w] & Cell_Insulator)) { contrib += outer; acc += outer * world.state[index + w]; } // Cell left if (!(world.properties[index - 1] & Cell_Insulator)) { contrib += outer; acc += outer * world.state[index - 1]; } // Cell right if (!(world.properties[index + 1] & Cell_Insulator)) { contrib += outer; acc += outer * world.state[index + 1]; } // Scale the accumulate value by the number of places contributing to it float res = acc / contrib; // Then clamp to the range [0,1] res = std::min(1.0f, std::max(0.0f, res)); buffer[index] = res; } }; for (unsigned t = 0; t < n; t++) { for (unsigned y = 0; y < h; y++) { for (unsigned x = 0; x < w; x++) { kernel_xy(x, y); } // end of for(x... } // end of for(y... // All cells have now been calculated and placed in buffer, so we replace // the old state with the new state std::swap(world.state, buffer); // Swapping rather than assigning is cheaper: just a pointer swap // rather than a memcpy, so O(1) rather than O(w*h) world.t += dt; // We have moved the world forwards in time } // end of for(t... }
void NoGhostGameofLife::create_local_element_to_remote_element_key_map() { stk::CommSparse buffer(m_bulkData->parallel()); fill_buffer_with_local_neighbors_of_remote_keys(buffer); unpack_local_and_remote_key_info_from_each_processor(buffer); }
//---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( HistoryBuffer, buffering, Ordinal ) { typedef MCLS::AdjointHistory<Ordinal> HT; HT::setByteSize(); int num_history = 4; MCLS::HistoryBuffer<HT> buffer( HT::getPackedBytes(), num_history ); TEST_EQUALITY( MCLS::HistoryBuffer<HT>::maxNum(), 4 ); TEST_EQUALITY( MCLS::HistoryBuffer<HT>::sizePackedHistory(), sizeof(double)+sizeof(Ordinal)+3*sizeof(int) ); TEST_EQUALITY( buffer.allocatedSize(), num_history*MCLS::HistoryBuffer<HT>::sizePackedHistory() + sizeof(int) ); TEST_ASSERT( buffer.isEmpty() ); TEST_EQUALITY( buffer.numHistories(), 0 ); std::stack<HT> bank; TEST_ASSERT( bank.empty() ); HT h1( 1, 1, 1 ); HT h2( 2, 2, 2 ); HT h3( 3, 4, 3 ); HT h4( 4, 4, 4 ); buffer.bufferHistory( h1 ); TEST_ASSERT( !buffer.isFull() ); TEST_ASSERT( !buffer.isEmpty() ); TEST_EQUALITY( buffer.numHistories(), 1 ); buffer.bufferHistory( h2 ); TEST_ASSERT( !buffer.isFull() ); TEST_ASSERT( !buffer.isEmpty() ); TEST_EQUALITY( buffer.numHistories(), 2 ); buffer.bufferHistory( h3 ); TEST_ASSERT( !buffer.isFull() ); TEST_ASSERT( !buffer.isEmpty() ); TEST_EQUALITY( buffer.numHistories(), 3 ); buffer.bufferHistory( h4 ); TEST_ASSERT( buffer.isFull() ); TEST_ASSERT( !buffer.isEmpty() ); TEST_EQUALITY( buffer.numHistories(), 4 ); buffer.addToBank( bank ); HT ph1, ph2, ph3, ph4; TEST_EQUALITY( bank.size(), 4 ); ph4 = bank.top(); bank.pop(); TEST_EQUALITY( ph4.globalState(), 4 ); TEST_EQUALITY( ph4.weight(), 4 ); TEST_EQUALITY( bank.size(), 3 ); ph3 = bank.top(); bank.pop(); TEST_EQUALITY( ph3.globalState(), 3 ); TEST_EQUALITY( ph3.weight(), 3 ); TEST_EQUALITY( bank.size(), 2 ); ph2 = bank.top(); bank.pop(); TEST_EQUALITY( ph2.globalState(), 2 ); TEST_EQUALITY( ph2.weight(), 2 ); TEST_EQUALITY( bank.size(), 1 ); ph1 = bank.top(); bank.pop(); TEST_EQUALITY( ph1.globalState(), 1 ); TEST_EQUALITY( ph1.weight(), 1 ); TEST_ASSERT( bank.empty() ); }
void GL1TextureProvider::set_texture_image2d( GLuint target, PixelBuffer &image, int level) { throw_if_disposed(); GL1TextureStateTracker state_tracker(texture_type, handle); GLint gl_internal_format; GLenum gl_pixel_format; to_opengl_textureformat(image.get_format(), gl_internal_format, gl_pixel_format); /* GL_UNPACK_SWAP_BYTES GL_UNPACK_LSB_FIRST GL_UNPACK_SKIP_ROWS GL_UNPACK_SKIP_PIXELS GL_UNPACK_ROW_LENGTH GL_UNPACK_ALIGNMENT GL_UNPACK_IMAGE_HEIGHT GL_UNPACK_SKIP_IMAGES */ // check out if the original texture needs or doesn't need an alpha channel bool needs_alpha = image.has_transparency(); GLenum format; GLenum type; bool conv_needed = !to_opengl_pixelformat(image, format, type); // also check for the pitch (GL1 can only skip pixels, not bytes) if (!conv_needed) { const int bytesPerPixel = image.get_bytes_per_pixel(); if (image.get_pitch() % bytesPerPixel != 0) conv_needed = true; } // no conversion needed if (!conv_needed) { // Upload to GL1: // change alignment glPixelStorei(GL_UNPACK_ALIGNMENT, 1); const int bytesPerPixel = image.get_bytes_per_pixel(); #ifndef __ANDROID__ glPixelStorei(GL_UNPACK_ROW_LENGTH, image.get_pitch() / bytesPerPixel); glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); #endif char *data = (char *) image.get_data(); int image_width = image.get_width(); int image_height = image.get_height(); /* int image_width = 1; int image_height = 1; while (image_width < image.get_width()) image_width *= 2; while (image_height < image.get_height()) image_height *= 2; */ glTexImage2D( target, // target level, // level gl_internal_format, // internalformat image_width, // width image_height, // height 0, // border format, // format type, // type data); // texels } // conversion needed else { bool big_endian = Endian::is_system_big(); PixelBuffer buffer( image.get_width(), image.get_height(), needs_alpha ? tf_rgba8 : tf_rgb8); buffer.set_image(image); format = needs_alpha ? GL_RGBA : GL_RGB; // Upload to OpenGL: // change alignment glPixelStorei(GL_UNPACK_ALIGNMENT, 1); const int bytesPerPixel = buffer.get_bytes_per_pixel(); #ifndef __ANDROID__ glPixelStorei(GL_UNPACK_ROW_LENGTH, buffer.get_pitch() / bytesPerPixel); glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); #endif // upload glTexImage2D( target, // target level, // level gl_internal_format, // internalformat image.get_width(), // width image.get_height(), // height 0, // border format, // format GL_UNSIGNED_BYTE, // type buffer.get_data()); // texels /* glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); */ } }