Why is qStringList.indexof() is not functioning as expected? - indexof

I have read the following into a qStringList variable from a .csv file
This printout is from the debugger screen in QTcreator. The [17] is the qstringlist index according to the debugger. See the code snippet following. When I request the indexof("Calcium") the function never finds Calcium. It never finds any of the "keys".
[17] "Calcium, Ca,269,mg,\r\n" QString
case CALCIUM: // = 21,
{
if(strlist.indexOf("Calcium") == -1)
{
reply = -999;
}else{
reply = strlist.indexOf("Calcium");
}
break;
}

Related

Brother Printer SDK cannot print label ERROR_WRONG_LABEL_ IOS

I am trying to print a label from my Nativescript+Vue application for IOS. I can successfully connect to printer, however when I try to print an image, it will give me an Error. The printer I am using is the "QL-810W". The label that I have loaded is the 62mm roll (no set length) and can support both red and black.
Here is the surrounding code:
exports.BrotherPrinterClass = BrotherPrinterClass;
var BrotherPrinter = (function () {
function BrotherPrinter() {
}
BrotherPrinter.prototype.print_image = function (PrinterName, ipAddress, image) {
try {
let printer = new BRPtouchPrinter()
printer.printerName = PrinterName
printer.interface = CONNECTION_TYPE_WLAN
printer.setIPAddress(ipAddress)
let settings = new BRPtouchPrintInfo()
settings.strPaperName = "62mmRB"
settings.nPrintMode = 0x03 //PRINT_FIT_TO_PAGE
settings.nAutoCutFlag = 0x00000001 //OPTION_AUTOCUT
settings.nOrientation = 0x00 //ORI_LANDSCAPE
settings.nHorizontalAlign = 0x01 //ALIGN_CENTER
settings.nVerticalAlign = 0x01 //ALIGN_MIDDLE
printer.setPrintInfo(settings)
if (printer.startCommunication()) {
//Print to the printer
let errorCode = printer.printImageCopy(image.ios.CGImage, 1);
if (errorCode != 0)
console.log("ERROR - ", errorCode)
}
printer.endCommunication()
}
else{
console.log("Failed to connect")
}
}
catch(e) {
console.log("Error - ", e);
}
};
This then returns the error "-41" which correlates to ERROR_WRONG_LABEL_. I've tried adjusting all properties, I've also tried settings.strPaperName = "62mm" and that didn't return anything different.
The image that is been passed in is of an ImageSource type, and I've also tried the following line, let errorCode = printer.printImageCopy(image.ios, 1);. This returns an error code of 0 which correlates to ERROR_NONE_ But nothing gets printed out. And as far as I know, this isn't a CGImage like the SDK wants.
I can print from an iPad using the "iPrint&Label" app. Just not from the SDK
EDIT:
I have tried to print from a file using printFilesCopy(). This returns no error when I go to print, but nothing gets printed. Additionally, I can set the settings incorrectly (eg, change '62mmRB' for '102mm') or I can outright not set the settings by commenting out the printer.setPrintInfo(settings) line. These changes do not impact the result.
Furthermore, I have purchased a 62mm black only roll, and tried that, only to find that I have the exact same issue.

Visual Studio 2010 error: identifier out of scope when trying to debug

I am stepping through c++ code and I am seeing a bunch of stuff where it says the symbol is undefined.
The strangest one was a method that I put a break point in. I was a couple lines under the method signature and I added a watch to a String^ variable type in the method. The first one I could see the value. The second one in the method signature it said that it was undefined. What could cause this?
If I put the breakpoint on the first line I can see a value in string1, but string2 is undefined. The error message in the watch window is:
error: identifier 'string2' out of scope
Project is in debug mode.
Configuration Properties->C/C++->Optimization->Optimization = Disabled (/Od)
System::String^ MyNameSpace::CodeXML(String^ string1, String^ string2)
{
System::Diagnostics::Stopwatch ^ performance_timer = System::Diagnostics::Stopwatch::StartNew();
if(System::String::IsNullOrEmpty(string1))
return System::String::Empty;
int iTimeLimit=500,flags=0;
bool bDBGFilter=false;
System::String^ abc = System::String::Empty;
if (!System::String::IsNullOrEmpty(string2)) {
System::IO::StringReader^ sr = gcnew System::IO::StringReader(string2);
XPathDocument^ doc;
try {
doc = gcnew XPathDocument(sr);
} catch (System::Xml::XmlException^) {
throw_managed_exception("Bad parameters XML");
}
XPathNavigator^ root = doc->CreateNavigator();
if (XPathNavigator^ nav = root->SelectSingleNode("XXX/A"))
if(!System::String::IsNullOrEmpty(nav->Value))
iTimeLimit = nav->ValueAsInt;
if (XPathNavigator^ nav = root->SelectSingleNode("XXX/B"))
if(!System::String::IsNullOrEmpty(nav->Value))
flags = nav->ValueAsInt;
if (XPathNavigator^ nav = root->SelectSingleNode("XXX/C"))
if(!System::String::IsNullOrEmpty(nav->Value))
abc = nav->Value->Trim();
}
MyReport Report(EMPTY_STRING, iTimeLimit);
ExtractedData^ ed = gcnew ExtractedData();
if(System::String::IsNullOrEmpty(abc))
Report.SetHasSuperfilter(false);
else
Report.SetHasSuperfilter(true);
Report.init();
bool bRet = ExtractCodes(string1, abc, ed, Report);
if (!bRet)
throw_managed_exception("ExtractCodes returned false");
ostringstream dgn_strm;
Report.summarize(dgn_strm);
performance_timer->Stop();
Report.add_performance_output("CodeXML", (long)performance_timer->ElapsedMilliseconds);
String^ rv = OutputWriter::serialize(ed, Report);
if (DBO d = "old") d << dgn_strm.str();
MappingDiagnosticsSummaryLogger::IncDocCount();
MappingDiagnosticsSummaryLogger::Log();
return rv;
}
I stepped up a level in the call stack and I can see the value of the variable by holding my mouse over it. I just cannot see it in the function with the break point is.
virtual System::String^ ParentFunction(System::String^ string1, System::String^ string2) {
return myObject->CodeXML(string1, string2);
}

alBufferData() sets AL_INVALID_OPERATION when using buffer ID obtained from alSourceUnqueueBuffers()

I am trying to stream audio data from disk using OpenAL's buffer queueing mechanism. I load and enqueue 4 buffers, start the source playing, and check in a regular intervals to refresh the queue. Everything looks like it's going splendidly, up until the first time I try to load data into a recycled buffer I got from alSourceUnqueueBuffers(). In this situation, alBufferData() always sets AL_INVALID_OPERATION, which according to the official v1.1 spec, it doesn't seem like it should be able to do.
I have searched extensively on Google and StackOverflow, and can't seem to find any reason why this would happen. The closest thing I found was someone with a possibly-related issue in an archived forum post, but details are few and responses are null. There was also this SO question with slightly different circumstances, but the only answer's suggestion does not help.
Possibly helpful: I know my context and device are configured correctly, because loading small wav files completely into a single buffer and playing them works fine. Through experimentation, I've also found that queueing 2 buffers, starting the source playing, and immediately loading and enqueueing the other two buffers throws no errors; it's only when I've unqueued a processed buffer that I run into trouble.
The relevant code:
static constexpr int MAX_BUFFER_COUNT = 4;
#define alCall(funcCall) {funcCall; SoundyOutport::CheckError(__FILE__, __LINE__, #funcCall) ? abort() : ((void)0); }
bool SoundyOutport::CheckError(const string &pFile, int pLine, const string &pfunc)
{
ALenum tErrCode = alGetError();
if(tErrCode != 0)
{
auto tMsg = alGetString(tErrCode);
Log::e(ro::TAG) << tMsg << " at " << pFile << "(" << pLine << "):\n"
<< "\tAL call " << pfunc << " failed." << end;
return true;
}
return false;
}
void SoundyOutport::EnqueueBuffer(const float* pData, int pFrames)
{
static int called = 0;
++called;
ALint tState;
alCall(alGetSourcei(mSourceId, AL_SOURCE_TYPE, &tState));
if(tState == AL_STATIC)
{
Stop();
// alCall(alSourcei(mSourceId, AL_BUFFER, NULL));
}
ALuint tBufId = AL_NONE;
int tQueuedBuffers = QueuedUpBuffers();
int tReady = ProcessedBuffers();
if(tQueuedBuffers < MAX_BUFFER_COUNT)
{
tBufId = mBufferIds[tQueuedBuffers];
}
else if(tReady > 0)
{
// the fifth time through, this code gets hit
alCall(alSourceUnqueueBuffers(mSourceId, 1, &tBufId));
// debug code: make sure these values go down by one
tQueuedBuffers = QueuedUpBuffers();
tReady = ProcessedBuffers();
}
else
{
return; // no update needed yet.
}
void* tConverted = convert(pData, pFrames);
// the fifth time through, we get AL_INVALID_OPERATION, and call abort()
alCall(alBufferData(tBufId, mFormat, tConverted, pFrames * mBitdepth/8, mSampleRate));
alCall(alSourceQueueBuffers(mSourceId, 1, &mBufferId));
if(mBitdepth == BITDEPTH_8)
{
delete (uint8_t*)tConverted;
}
else // if(mBitdepth == BITDEPTH_16)
{
delete (uint16_t*)tConverted;
}
}
void SoundyOutport::PlayBufferedStream()
{
if(!StreamingMode() || !QueuedUpBuffers())
{
Log::w(ro::TAG) << "Attempted to play an unbuffered stream" << end;
return;
}
alCall(alSourcei(mSourceId, AL_LOOPING, AL_FALSE)); // never loop streams
alCall(alSourcePlay(mSourceId));
}
int SoundyOutport::QueuedUpBuffers()
{
int tCount = 0;
alCall(alGetSourcei(mSourceId, AL_BUFFERS_QUEUED, &tCount));
return tCount;
}
int SoundyOutport::ProcessedBuffers()
{
int tCount = 0;
alCall(alGetSourcei(mSourceId, AL_BUFFERS_PROCESSED, &tCount));
return tCount;
}
void SoundyOutport::Stop()
{
if(Playing())
{
alCall(alSourceStop(mSourceId));
}
int tBuffers;
alCall(alGetSourcei(mSourceId, AL_BUFFERS_QUEUED, &tBuffers));
if(tBuffers)
{
ALuint tDummy[tBuffers];
alCall(alSourceUnqueueBuffers(mSourceId, tBuffers, tDummy));
}
alCall(alSourcei(mSourceId, AL_BUFFER, AL_NONE));
}
bool SoundyOutport::Playing()
{
ALint tPlaying;
alCall(alGetSourcei(mSourceId, AL_SOURCE_STATE, &tPlaying));
return tPlaying == AL_PLAYING;
}
bool SoundyOutport::StreamingMode()
{
ALint tState;
alCall(alGetSourcei(mSourceId, AL_SOURCE_TYPE, &tState));
return tState == AL_STREAMING;
}
bool SoundyOutport::StaticMode()
{
ALint tState;
alCall(alGetSourcei(mSourceId, AL_SOURCE_TYPE, &tState));
return tState == AL_STATIC;
}
And here's an annotated screen cap of what I see in my debugger when I hit the error:
I've tried a bunch of little tweaks and variations, and the result is always the same. I've wasted too many days trying to fix this. Please help :)
This error occurs when you trying to fill buffer with data, when the buffer is still queued to the source.
Also this code is wrong.
if(tQueuedBuffers < MAX_BUFFER_COUNT)
{
tBufId = mBufferIds[tQueuedBuffers];
}
else if(tReady > 0)
{
// the fifth time through, this code gets hit
alCall(alSourceUnqueueBuffers(mSourceId, 1, &tBufId));
// debug code: make sure these values go down by one
tQueuedBuffers = QueuedUpBuffers();
tReady = ProcessedBuffers();
}
else
{
return; // no update needed yet.
}
You can fill buffer with data only if it unqueued from source. But your first if block gets tBufId that queued to the source. Rewrite code like so
if(tReady > 0)
{
// the fifth time through, this code gets hit
alCall(alSourceUnqueueBuffers(mSourceId, 1, &tBufId));
// debug code: make sure these values go down by one
tQueuedBuffers = QueuedUpBuffers();
tReady = ProcessedBuffers();
}
else
{
return; // no update needed yet.
}

Core Audio : Recording in .wav format doesn't work properly

I use AudioFileWritePackets() to write data, and it returns no error during
recording. The data format flag I am using is:
if(appDelegate.screenRecording){
cPacket = 0;inNumPackets = inCompleteAQBuffer->mPacketDescriptionCount;
if (AudioFileWritePackets(nAudioFile, false, numBytes, mPacketDescs, mPacketIndex, &nPackets, inCompleteAQBuffer->mAudioData) == noErr)
{
mPacketIndex += nPackets;
NSLog(#"sample result");
}
else {
NSLog(#"ext err");
}
}
Every time it's calling Nslog(ext err);
Please help me solve this.

Using sockets (nsIServerSocket) in XPCOM component (Firefox Extension) (sockets + new window = seg faults)

PLEASE READ THE UPDATE #2 BELOW IF YOU ARE INTERESTED IN THIS PROBLEM ;)
Say I put this code into the JS of my extension.
var reader = {
onInputStreamReady : function(input) {
var sin = Cc["#mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream);
sin.init(input);
sin.available();
var request = '';
while (sin.available()) {
request = request + sin.read(512);
}
console.log('Received: ' + request);
input.asyncWait(reader,0,0,null);
}
}
var listener = {
onSocketAccepted: function(serverSocket, clientSocket) {
console.log("Accepted connection on "+clientSocket.host+":"+clientSocket.port);
input = clientSocket.openInputStream(0, 0, 0).QueryInterface(Ci.nsIAsyncInputStream);
output = clientSocket.openOutputStream(Ci.nsITransport.OPEN_BLOCKING, 0, 0);
input.asyncWait(reader,0,0,null);
}
}
var serverSocket = Cc["#mozilla.org/network/server-socket;1"].
createInstance(Ci.nsIServerSocket);
serverSocket.init(-1, true, 5);
console.log("Opened socket on " + serverSocket.port);
serverSocket.asyncListen(listener);
Then I run Firefox and connect to the socket via telnet
telnet localhost PORT
I send 5 messages and they get printed out, but when I try to send 6th message I get
firefox-bin: Fatal IO error 11 (Resource temporarily unavailable) on X server :0.0.
Even worse, when I try to put this same code into an XPCOM component (because that's where I actually need it), after I try sending a message via telnet I get
Segmentation fault
or sometimes
GLib-ERROR **: /build/buildd/glib2.0-2.24.1/glib/gmem.c:137: failed to allocate 32 bytes
aborting...
Aborted
printed to the terminal from which I launched firefox.
This is really weird stuff.. Can you spot something wrong with the code I've pasted or is smth wrong with my firefox/system or is the nsIServerSocket interface deprecated?
I'm testing with Firefox 3.6.6.
I would really appreciate some answer. Perhaps you could point me to a good example of using Sockets within an XPCOM component. I haven't seen many of those around.
UPDATE
I just realised that it used to work so now I think that my Console
component breaks it. I have no idea how this is related. But if I
don't use this component the sockets are working fine.
Here is the code of my Console component. I will try to figure out
what's wrong and why it interferes and I'll post my findings later.
Likely I'm doing something terribly wrong here to cause Segmentation
faults with my javascript =)
Voodoo..
components/Console.js:
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
Console.prototype = (function() {
var win;
var initialized = false;
var ready = false;
var _log = function(m, level, location) {
if (initialized&&ready) {
var prefix = "INFO: ";
switch (level) {
case "empty":
prefix = ""
break;
case "error":
prefix = "ERORR: "
break;
case "warning":
prefix = "WARNING: "
break;
}
win.document.getElementById(location).value =
win.document.getElementById(location).value + prefix + m + "\n";
win.focus();
} else if (initialized&&!ready) {
// Now it is time to create the timer...
var timer = Components.classes["#mozilla.org/timer;1"]
.createInstance(Components.interfaces.nsITimer);
// ... and to initialize it, we want to call
event.notify() ...
// ... one time after exactly ten second.
timer.initWithCallback(
{ notify: function() { log(m); } },
10,
Components.interfaces.nsITimer.TYPE_ONE_SHOT
);
} else {
init();
log(m);
}
}
var log = function(m, level) {
_log(m, level, 'debug');
}
var poly = function(m, level) {
_log(m, "empty", 'polyml');
}
var close = function() {
win.close();
}
var setReady = function() {
ready = true;
}
var init = function() {
initialized = true;
var ww = Components.classes["#mozilla.org/embedcomp/window-
watcher;1"]
.getService(Components.interfaces.nsIWindowWatcher);
win = ww.openWindow(null, "chrome://polymlext/content/
console.xul",
"console", "chrome,centerscreen,
resizable=no", null);
win.onload = setReady;
return win;
}
return {
init: init,
log : log,
poly : poly,
}
}());
// turning Console Class into an XPCOM component
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
function Console() {
this.wrappedJSObject = this;
}
prototype2 = {
classDescription: "A special Console for PolyML extension",
classID: Components.ID("{483aecbc-42e7-456e-b5b3-2197ea7e1fb4}"),
contractID: "#ed.ac.uk/poly/console;1",
QueryInterface: XPCOMUtils.generateQI(),
}
//add the required XPCOM glue into the Poly class
for (attr in prototype2) {
Console.prototype[attr] = prototype2[attr];
}
var components = [Console];
function NSGetModule(compMgr, fileSpec) {
return XPCOMUtils.generateModule(components);
}
I'm using this component like this:
console = Cc["#ed.ac.uk/poly/console;1"].getService().wrappedJSObject;
console.log("something");
And this breaks the sockets :-S =)
UPDATE #2
Ok, if anyone is interested in checking this thing out I would really
appreciate it + I think this is likely some kind of bug (Seg fault
from javascript shouldn't happen)
I've made a minimal version of the extension that causes the problem,
you can install it from here:
http://dl.dropbox.com/u/645579/segfault.xpi
The important part is chrome/content/main.js:
http://pastebin.com/zV0e73Na
The way my friend and me can reproduce the error is by launching the
firefox, then a new window should appear saying "Opened socket on
9999". Connect using "telnet localhost 9999" and send a few messages.
After 2-6 messages you get one of the following printed out in the
terminal where firefox was launched:
1 (most common)
Segmentation fault
2 (saw multiple times)
firefox-bin: Fatal IO error 11 (Resource temporarily unavailable) on
X
server :0.0.
3 (saw a couple of times)
GLib-ERROR **: /build/buildd/glib2.0-2.24.1/glib/gmem.c:137: failed
to
allocate 32 bytes
aborting...
Aborted
4 (saw once)
firefox-bin: ../../src/xcb_io.c:249: process_responses: Assertion
`(((long) (dpy->last_request_read) - (long) (dpy->request)) <= 0)'
failed.
Aborted
If you need any more info or could point me to where to post a bug
report :-/ I'll be glad to do that.
I know this is just one of the many bugs... but perhaps you have an
idea of what should I do differently to avoid this? I would like to
use that "console" of mine in such way.
I'll try doing it with buffer/flushing/try/catch as people are suggesting, but I wonder whether try/catch will catch the Seg fault...
This is a thread problem. The callback onInputStreamReady happened to be executed in a different thread and accessing UI / DOM is only allowed from the main thread.
Solution is really simple:
change
input.asyncWait(reader,0,0,null);
to
var tm = Cc["#mozilla.org/thread-manager;1"].getService();
input.asyncWait(reader,0,0,tm.mainThread);

Resources