parseInt error in my code - parseint

I get error messages in my code. Code and errors is below.
public class Main {
public static void main(String[] args){
String sayi[] = {"37107287533902102798797998220837590246510135740250",
"46376937677490009712648124896970078050417018260538",
"74324986199524741059474233309513058123726617309629",
"91942213363574161572522430563301811072406154908250",
"23067588207539346171171980310421047513778063246676",
"89261670696623633820136378418383684178734361726757",
"28112879812849979408065481931592621691275889832738",
"44274228917432520321923589422876796487670272189318",
"47451445736001306439091167216856844588711603153276",
"70386486105843025439939619828917593665686757934951",
"62176457141856560629502157223196586755079324193331",
"64906352462741904929101432445813822663347944758178",
"92575867718337217661963751590579239728245598838407",
"58203565325359399008402633568948830189458628227828",
"80181199384826282014278194139940567587151170094390",
"35398664372827112653829987240784473053190104293586",
"86515506006295864861532075273371959191420517255829",
"71693888707715466499115593487603532921714970056938",
"54370070576826684624621495650076471787294438377604",
"53282654108756828443191190634694037855217779295145",
"36123272525000296071075082563815656710885258350721",
"45876576172410976447339110607218265236877223636045",
"17423706905851860660448207621209813287860733969412",
"81142660418086830619328460811191061556940512689692",
"51934325451728388641918047049293215058642563049483",
"62467221648435076201727918039944693004732956340691",
"15732444386908125794514089057706229429197107928209",
"55037687525678773091862540744969844508330393682126",
"18336384825330154686196124348767681297534375946515",
"80386287592878490201521685554828717201219257766954",
"78182833757993103614740356856449095527097864797581",
"16726320100436897842553539920931837441497806860984",
"48403098129077791799088218795327364475675590848030",
"87086987551392711854517078544161852424320693150332",
"59959406895756536782107074926966537676326235447210",
"69793950679652694742597709739166693763042633987085",
"41052684708299085211399427365734116182760315001271",
"65378607361501080857009149939512557028198746004375",
"35829035317434717326932123578154982629742552737307",
"94953759765105305946966067683156574377167401875275",
"88902802571733229619176668713819931811048770190271",
"25267680276078003013678680992525463401061632866526",
"36270218540497705585629946580636237993140746255962",
"24074486908231174977792365466257246923322810917141",
"91430288197103288597806669760892938638285025333403",
"34413065578016127815921815005561868836468420090470",
"23053081172816430487623791969842487255036638784583",
"11487696932154902810424020138335124462181441773470",
"63783299490636259666498587618221225225512486764533",
"67720186971698544312419572409913959008952310058822",
"95548255300263520781532296796249481641953868218774",
"76085327132285723110424803456124867697064507995236",
"37774242535411291684276865538926205024910326572967",
"23701913275725675285653248258265463092207058596522",
"29798860272258331913126375147341994889534765745501",
"18495701454879288984856827726077713721403798879715",
"38298203783031473527721580348144513491373226651381",
"34829543829199918180278916522431027392251122869539",
"40957953066405232632538044100059654939159879593635",
"29746152185502371307642255121183693803580388584903",
"41698116222072977186158236678424689157993532961922",
"62467957194401269043877107275048102390895523597457",
"23189706772547915061505504953922979530901129967519",
"86188088225875314529584099251203829009407770775672",
"11306739708304724483816533873502340845647058077308",
"82959174767140363198008187129011875491310547126581",
"97623331044818386269515456334926366572897563400500",
"42846280183517070527831839425882145521227251250327",
"55121603546981200581762165212827652751691296897789",
"32238195734329339946437501907836945765883352399886",
"75506164965184775180738168837861091527357929701337",
"62177842752192623401942399639168044983993173312731",
"32924185707147349566916674687634660915035914677504",
"99518671430235219628894890102423325116913619626622",
"73267460800591547471830798392868535206946944540724",
"76841822524674417161514036427982273348055556214818",
"97142617910342598647204516893989422179826088076852",
"87783646182799346313767754307809363333018982642090",
"10848802521674670883215120185883543223812876952786",
"71329612474782464538636993009049310363619763878039",
"62184073572399794223406235393808339651327408011116",
"66627891981488087797941876876144230030984490851411",
"60661826293682836764744779239180335110989069790714",
"85786944089552990653640447425576083659976645795096",
"66024396409905389607120198219976047599490197230297",
"64913982680032973156037120041377903785566085089252",
"16730939319872750275468906903707539413042652315011",
"94809377245048795150954100921645863754710598436791",
"78639167021187492431995700641917969777599028300699",
"15368713711936614952811305876380278410754449733078",
"40789923115535562561142322423255033685442488917353",
"44889911501440648020369068063960672322193204149535",
"41503128880339536053299340368006977710650566631954",
"81234880673210146739058568557934581403627822703280",
"82616570773948327592232845941706525094512325230608",
"22918802058777319719839450180888072429661980811197",
"77158542502016545090413245809786882778948721859617",
"72107838435069186155435662884062257473692284509516",
"20849603980134001723930671666823555245252804609722",
"53503534226472524250874054075591789781264330331690"};
int no[] = new int[100];
int sum = 0;
for(int i = 0; i < 100; i++)
{
no[i] = Integer.parseInt(sayi[i].substring(0, 10));
}
for(int k = 0; k < 10; k++)
{
sum += no[k];
}
System.out.println(sum);
}
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "3710728753"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
at Main.main(Main.java:111)
This error is about this line:
no[i] = Integer.parseInt(sayi[i].substring(0, 10));

Range of an int is about -2 to 2 milliards. 10-digit numbers don't fit in that range.
Try to parse a long or a float there.

Related

How To Use CompUtil To Parse With Plugin

When using the Alloy API to perform parsing on the following string:
Module mod = CompUtil.parseEverything_fromString("run {} for 5")
I receive the following error:
Fatal error:
Parser Exception
at edu.mit.csail.sdg.alloy4compiler.parser.CompParser.alloy_parseStream(CompParser.java:2260)
at edu.mit.csail.sdg.alloy4compiler.parser.CompUtil.parseRecursively(CompUtil.java:178)
at edu.mit.csail.sdg.alloy4compiler.parser.CompUtil.parseEverything_fromFile(CompUtil.java:280)
at edu.mit.csail.sdg.alloy4compiler.parser.CompUtil.parseEverything_fromString(CompUtil.java:333)
at edu.mit.csail.sdg.alloy4compiler.parser.CompUtil$parseEverything_fromString.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:136)
at MyOM.MyOMPlugin.Modularize(MyOMPlugin.groovy:107)
...
--------------------------------------------------------------------------
class file:
package MyOM
class MyOMPlugin extends Plugin{
void Modularize() throws Err{
//line 107 is the only line in the method and is below
Module mod = CompUtil.parseEverything_fromString("run {} for 5")
}
}
I am performing this task in a groovy class file within a groovy project. The code works fine until I run it in conjunction with the plugin I am using.
EDIT:
The parse function is what causes the parse exception and the code for that method is included below for reference:
#Override public Symbol parse() throws java.lang.Exception {
int act; // current action code
Symbol lhs_sym = null; // the Symbol/stack element returned by a reduce
short handle_size, lhs_sym_num; // information about production being reduced with
boolean logging = "yes".equals(System.getProperty("debug"));
production_tab = production_table();
action_tab = action_table();
reduce_tab = reduce_table();
init_actions();
user_init();
// start
cur_token = scan();
stack.removeAllElements();
stack.push(getSymbolFactory().startSymbol("START", 0, start_state()));
tos = 0;
for (_done_parsing = false; !_done_parsing; ) {
act = get_action(((Symbol)stack.peek()).parse_state, cur_token.sym);
if (act > 0) { // "shift"; thus, we shift to the encoded state by pushing it on the stack
if (logging) System.out.println("shift " + cur_token.sym);
cur_token.parse_state = act-1;
stack.push(cur_token);
tos++;
cur_token = scan();
} else if (act<0) { // "reduce"
if (logging) System.out.println("reduce " + ((-act)-1));
lhs_sym = do_action((-act)-1, this, stack, tos);
lhs_sym_num = production_tab[(-act)-1][0];
handle_size = production_tab[(-act)-1][1];
for (int i = 0; i < handle_size; i++) { stack.pop(); tos--; }
act = get_reduce(((Symbol)stack.peek()).parse_state, lhs_sym_num);
lhs_sym.parse_state = act;
stack.push(lhs_sym);
tos++;
} else { // "error"
if (logging) System.out.println("error");
syntax_error(cur_token);
done_parsing();
}
}
return lhs_sym;
}

unordered_map insertion is creating bottleneck

So here I am trying to create a Graph data structure in which i have to keep track of edges according to their ids. So I am creating edge ids in string data structure as eid: sourceid_destinationid
using namespace std;
class Edge{
public:
bool operator==(const Edge* &obj) const
{
return eid==obj->eid;
}
std::string eid;
set<int> rrids;
int sourceid;
int destid;
int strength;
public:
Edge(std::string eid,int from,int to);
std::string getId();
void addRRid(int rrid);
void removeRRid(int rrid);
void setRRid(set<int> rrids);
void setId(std::string eid);
};
This is another class which I am using for adding and removing the edges.
hpp-file
using namespace std;
class RRassociatedGraph{
public:
unordered_map<int,vertex*> vertexMap;
std::unordered_map<std::string,Edge*> EdgeMap;
int noOfEdges;
public:
RRassociatedGraph();
unordered_set<vertex> getVertices();
int getNumberOfVertices();
void addVertex(vertex v);
vertex* find(int id);
Edge* findedge(std::string id);
void addEdge(int from, int to, int label);
void removeEdge(int from, int to,int rrSetID);
};
When I debugged the code I found out that in the function add edge here the place where I am doing EdgeMap.insert the execution doesn't go to next line. It remains in hashtable for loop of some bucket entry. I can't debug this code frequently because I have to wait for 3 hours to get this issue. The code is working perfectly with small graphs. But for larger graphs where edgeMap has to store 800k edges. It goes in this hashtable infinite loop. I don't get this hashtable code. But is there something wrong with my data structure of creating Edgemap?
#include "RRassociatedGraph.hpp"
RRassociatedGraph::RRassociatedGraph() {
noOfEdges=0;
}
void RRassociatedGraph::addVertex(vertex v) {
vertexMap.insert(pair<int,vertex*>(v.getId(), &v));
}
vertex* RRassociatedGraph::find(int id) {
unordered_map<int,vertex*>::const_iterator got=vertexMap.find(id);
if(got != vertexMap.end() )
return got->second;
return nullptr;
}
Edge* RRassociatedGraph::findedge(std::string id){
unordered_map<std::string,Edge*>::const_iterator got=EdgeMap.find(id);
if(got != EdgeMap.end() )
return got->second;
return nullptr;
}
void RRassociatedGraph::addEdge(int from, int to, int label) {
vertex* fromVertex = find(from);
if (fromVertex == nullptr) {
fromVertex = new vertex(from);
vertexMap.insert(pair<int,vertex*>(fromVertex->getId(), fromVertex));
}
vertex* toVertex = find(to);
if (toVertex == nullptr) {
toVertex = new vertex(to);
vertexMap.insert(pair<int,vertex*>(toVertex->getId(), toVertex));
}
if(fromVertex==toVertex){
// fromVertex->outDegree++;
//cout<<fromVertex->getId()<<" "<<toVertex->getId()<<"\n";
return;
}
std::string eid=std::to_string(from);
eid+="_"+std::to_string(to);
Edge* edge=findedge(eid);
if(edge==nullptr){
edge=new Edge(eid,from,to);
edge->addRRid(label);
fromVertex->addOutGoingEdges(edge);
EdgeMap.insert(pair<std::string,Edge*>(edge->getId(), edge));
noOfEdges++;
}
else{
edge->addRRid(label);
fromVertex->outDegree++;
}
}
void RRassociatedGraph::removeEdge(int from, int to,int rrSetID) {
vertex* fromVertex = find(from);
std::string eid=std::to_string(from);
eid+="_"+std::to_string(to);
if(EdgeMap.count(eid)==1){
Edge* e=EdgeMap.find(eid)->second;
if(fromVertex->removeOutgoingEdge(e,rrSetID)){
EdgeMap.erase(eid);
delete e;
}
}
}
this is the place where it keeps going into this for loop. The insertion time of map should be very less but this is creating bottleneck in my code.
template <class _Tp, class _Hash, class _Equal, class _Alloc>
void
__hash_table<_Tp, _Hash, _Equal, _Alloc>::__rehash(size_type __nbc)
{
#if _LIBCPP_DEBUG_LEVEL >= 2
__get_db()->__invalidate_all(this);
#endif // _LIBCPP_DEBUG_LEVEL >= 2
__pointer_allocator& __npa = __bucket_list_.get_deleter().__alloc();
__bucket_list_.reset(__nbc > 0 ?
__pointer_alloc_traits::allocate(__npa, __nbc) : nullptr);
__bucket_list_.get_deleter().size() = __nbc;
if (__nbc > 0)
{
for (size_type __i = 0; __i < __nbc; ++__i)
__bucket_list_[__i] = nullptr;
__next_pointer __pp = __p1_.first().__ptr();
__next_pointer __cp = __pp->__next_;
if (__cp != nullptr)
{
size_type __chash = __constrain_hash(__cp->__hash(), __nbc);
__bucket_list_[__chash] = __pp;
size_type __phash = __chash;
for (__pp = __cp, __cp = __cp->__next_; __cp != nullptr;
__cp = __pp->__next_)
{
__chash = __constrain_hash(__cp->__hash(), __nbc);
if (__chash == __phash)
__pp = __cp;
else
{
if (__bucket_list_[__chash] == nullptr)
{
__bucket_list_[__chash] = __pp;
__pp = __cp;
__phash = __chash;
}
else
{
__next_pointer __np = __cp;
for (; __np->__next_ != nullptr &&
key_eq()(__cp->__upcast()->__value_,
__np->__next_->__upcast()->__value_);
__np = __np->__next_)
;
__pp->__next_ = __np->__next_;
__np->__next_ = __bucket_list_[__chash]->__next_;
__bucket_list_[__chash]->__next_ = __cp;
}
}
}
}
}
}
I have many files so I can't put the whole code. I am not that good in c++. Please let me know if I have to implement it some other way. I have to use hashMap because I also need faster search.
You are probably experiencing re-hash at insert. Unordered_map has number of buckets. When they are filled worst case insert time is O(size()).
http://en.cppreference.com/w/cpp/container/unordered_map/insert
Rehashing occurs only if the new number of elements is greater than max_load_factor()*bucket_count().
What you may do with your current setup is:
1. Growth map at the init of the program, as usually number of buckets doesn't shrink.
2. Change from std::unordered_map to Boost::intrusive_map, where you can manager number of buckets manually.

XAdES-BES countersignature cannot resolve reference error

I implemented verification for XAdES-BES and after testing everything works now besides counter-signatures. The same error occurs not only for files signed with xades4j but also using other software so it is not related to any mistakes in my countersignature implementation. I wonder if I should implement additional ResourceResolver? I added a countersigned file as the attachment with 'REMOVED' for some private entries here.
Below is the code for verification. certDataList is a list with all certificates from the document in String and getCert will return List. DummyCertificateValidationProvider returns ValidationData with a list of previously constructed x509certs.
public boolean verify(final File file) {
if (!Dictionaries.valid()) {
return true;
}
certList = null;
try {
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
final DocumentBuilder db = dbf.newDocumentBuilder();
final Document doc = db.parse(file);
doc.getDocumentElement().normalize();
final NodeList nList = doc.getElementsByTagName("ds:Signature");
Element elem = null;
for (int temp = 0; temp < nList.getLength(); temp++) {
final Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
elem = (Element) nNode;
}
}
final NodeList nList2 = doc.getElementsByTagName("ds:X509Certificate");
final List<String> certDataList = new ArrayList<String>();
for (int temp = 0; temp < nList2.getLength(); temp++) {
final Node nNode = nList2.item(temp);
certDataList.add(nNode.getTextContent());
}
certList = getCert(certDataList);
final CertificateValidationProvider certValidator = new DummyCertificateValidationProvider(certList);
final XadesVerificationProfile p = new XadesVerificationProfile(certValidator);
final XadesVerifier v = p.newVerifier();
final SignatureSpecificVerificationOptions opts = new SignatureSpecificVerificationOptions();
// for relative document paths
final String baseUri = "file:///" + file.getParentFile().getAbsolutePath().replace("\\", "/") + "/";
LOGGER.debug("baseUri:" + baseUri);
opts.useBaseUri(baseUri);
v.verify(elem, opts);
return true;
} catch (final IllegalArgumentException | XAdES4jException | CertificateException | IOException | ParserConfigurationException | SAXException e) {
LOGGER.error("XML not validated!", e);
}
return false;
}
Here is the stacktrace:
21:31:48,203 DEBUG ResourceResolver:158 - I was asked to create a ResourceResolver and got 0
21:31:48,203 DEBUG ResourceResolver:101 - check resolvability by class org.apache.xml.security.utils.resolver.ResourceResolver
21:31:48,204 DEBUG ResolverFragment:137 - State I can resolve reference: "#xmldsig-5de7b1d0-be70-4dde-b746-3f4d4d6de39f-sigvalue"
21:31:48,204 ERROR SignComponent:658 - XML not validated!
xades4j.XAdES4jXMLSigException: Error verifying the signature
at xades4j.verification.XadesVerifierImpl.doCoreVerification(XadesVerifierImpl.java:284)
at xades4j.verification.XadesVerifierImpl.verify(XadesVerifierImpl.java:188)
at com.signapplet.sign.SignComponent.verify(SignComponent.java:655)
...
Caused by: org.apache.xml.security.signature.MissingResourceFailureException: The Reference for URI #xmldsig-5de7b1d0-be70-4dde-b746-3f4d4d6de39f-sigvalue has no XMLSignatureInput
Original Exception was org.apache.xml.security.signature.ReferenceNotInitializedException: Cannot resolve element with ID xmldsig-5de7b1d0-be70-4dde-b746-3f4d4d6de39f-sigvalue
Original Exception was org.apache.xml.security.utils.resolver.ResourceResolverException: Cannot resolve element with ID xmldsig-5de7b1d0-be70-4dde-b746-3f4d4d6de39f-sigvalue
at org.apache.xml.security.signature.Manifest.verifyReferences(Manifest.java:414)
at org.apache.xml.security.signature.SignedInfo.verify(SignedInfo.java:259)
at org.apache.xml.security.signature.XMLSignature.checkSignatureValue(XMLSignature.java:724)
at org.apache.xml.security.signature.XMLSignature.checkSignatureValue(XMLSignature.java:656)
at xades4j.verification.XadesVerifierImpl.doCoreVerification(XadesVerifierImpl.java:277)
... 39 more
Caused by: org.apache.xml.security.signature.ReferenceNotInitializedException: Cannot resolve element with ID xmldsig-5de7b1d0-be70-4dde-b746-3f4d4d6de39f-sigvalue
Edit:
The same error occurs when I try to validate file provided with xades4j unit tests document.signed.bes.cs.xml.
Caused by: org.apache.xml.security.signature.MissingResourceFailureException: The Reference for URI #xmldsig-281967d1-74f8-482c-8222-ed58dbd1909b-sigvalue has no XMLSignatureInput
Original Exception was org.apache.xml.security.signature.ReferenceNotInitializedException: Cannot resolve element with ID xmldsig-281967d1-74f8-482c-8222-ed58dbd1909b-sigvalue
Caused by: org.apache.xml.security.signature.ReferenceNotInitializedException: Cannot resolve element with ID xmldsig-281967d1-74f8-482c-8222-ed58dbd1909b-sigvalue
The problem was with ds:Signature. In counter signatures you will have more than one ds:Signature entry. In my verification method I used the for loop:
for (int temp = 0; temp < nList.getLength(); temp++) {
final Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
elem = (Element) nNode;
}
}
As you can see, there was no break when element was found so I ended up with the last ds:Signature, not the first one so all previous signatures could not be found.

ObservableList producing errors

I made this program that produces 6 random numbers between 1 and 41. In the UI i have 6 textfields and a button. If i press the button the 6 numbers are being displayed in the textfields. I have 1 function(theNumbers()) fired when the button is pressed, the first function makes an ObservableList with the numbers 1-41 and the second function picks 6 numbers randomly.
The problem that happens is that after pressing the button a few times there is an ArrayIndexOutofBound Exception: -1 thrown, usually after (or a few times after) the number 0 is produced (which isnt even in the list) also sometimes a IndexOutOfBoundsException: Index: 4, Size: 4 exception is thrown(the number is random btw). Also it seems to be able to produce the same number twice or numbers bigger then 41.(seen 151)
This is my code:
First function:
ObservableList<Integer> list1 = FXCollections.observableArrayList();
private void createList(ObservableList<Integer> list1) {
this.list1 = list1;
int numbers = 41;
for (int i = 1; i <= numbers; i++) {
list1.add(i);
}
}
Second function:
private void theNumbers() {
createList(list1);
ObservableList<Integer> finalNums = FXCollections.observableArrayList();
try {
for (int i = 0; i < 6; i++) {
FXCollections.shuffle(list1);
int lucky = new Random().nextInt(list1.size());
finalNums.add(lucky);
list1.remove(list1.indexOf(lucky));
}
} catch (Exception ex) {
throw ex;
}
FXCollections.sort(finalNums);
textField1.setText(finalNums.get(0).toString());
textField2.setText(finalNums.get(1).toString());
textField3.setText(finalNums.get(2).toString());
textField4.setText(finalNums.get(3).toString());
textField5.setText(finalNums.get(4).toString());
textField6.setText(finalNums.get(5).toString());
list1.clear();
finalNums.clear();
}
Any clues to why it does this? Could it be my Acer Aspire One Netbook messing up? To my knowledge these errors shouldn't be happening.
Your code tries to remove the exact same number twice ore more in one pass of the for construct. For example you cannot remove the number "2" more than once from the list. The indexOf(2) method will return with -1 because it cannot find the value 2 in the list anymore.
So you might check if a number still exists in list1 before you try to remove from there.
private void theNumbers() {
createList(list1);
ObservableList<Integer> finalNums = FXCollections.observableArrayList();
try {
for (int i = 0; i < 6; i++) {
FXCollections.shuffle(list1);
int lucky;
do
{
lucky= new Random().nextInt(list1.size());
}while(list1.indexOf(lucky) == -1);
finalNums.add(lucky);
list1.remove(list1.indexOf(lucky));
}
} catch (Exception ex) {
throw ex;
}
That should solve your problem.
try using
int lucky = new Random().nextInt(list1.size()-1);

Should I use CRITICAL_SECTION or not?

I have a program which has a Ui with which users choose the way to display and do small configurations. It also has a background procedure, which continuously reads data from the network and update the data to display.
Now I put them in one process:
background procedure:
STATE MainWindow::Rcv()
{
DeviceMAP::iterator dev;
for(dev= dev_map.begin(); dev!= dev_map.end(); dev++)
{
dev->second.rcvData();//receive data from the network, the time can be ignored.
BitLog* log = new BitLog();
dev->second.parseData(log);
LogItem* logItem = new LogItem();
logItem->time = QString::fromLocal8Bit(log->rcvTime.c_str());
logItem->name = QString::fromLocal8Bit(log->basicInfo.getName().c_str());
logItem->PIN = QString::fromLocal8Bit(log->basicInfo.getPIN().c_str()).toShort();
delete log;
add_logItem(logItem);
}
return SUCCESS;
}
add_logItem:
void MainWindow::add_logItem(LogItem* logItem)
{
writeToFile(logItem);
Device* r = getDevbyPIN(QString::number(logItem->PIN));
if(r == NULL)return;
devInfo_inside_widget::States state = logItem->state;
bool bool_list[portsNum_X];
for(int i =0; i < portsNum_X; i++)
{
bool_list[i] = 0;
}
for(int i = 0; i < portsNum; i++)
{
bool_list[i] = (logItem->BITS[i/8] >> (7 - i%8)) & 0x1;
}
r->refresh(state, logItem->time, bool_list);//update data inside...state, time , BITS...
IconLabel* icl = getIConLabelByDev(r);//update data
icl->refresh(state);
logDisplayQueue.enqueue(logItem);//write queue here
int size = logDisplayQueue.size();
if(size > 100)
{
logDisplayQueue.dequeue();//write queue here
}
}
The section above has not dealt with any ui operations yet, but when user push a radio button in the ui, the program has to filter the data in the queue and display it in the table widget:
ui operations:
void MainWindow::filter_log_display(bool bol)
{
row_selectable = false;
ui->tableWidget->setRowCount(0);//delete table items all
row_selectable = true;
int size_1 = logDisplayQueue.size() - 1;
ui->tableWidget->verticalScrollBar()->setSliderPosition(0);
if(size_1+1 < 100)
{
ui->tableWidget->setRowCount(size_1 + 1);
}
else
{
ui->tableWidget->setRowCount(100);//display 100 rows at most
}
if(bol)//filter from logDisplayQueue and display unworking-state-log rows
{
int index = 0;
for(int queue_i = size_1; queue_i >= 0; queue_i--)
{
LogItem* logItem = (LogItem*)logDisplayQueue.at(queue_i); // read queue here
if(logItem->state == STATE_WORK || logItem->state == STATE_UN)continue;
QString BITS_str = bits2Hexs(logItem->BITS);
ui->tableWidget->setItem(index, 0, new QTableWidgetItem(logItem->time));//time
ui->tableWidget->setItem(index, 1, new QTableWidgetItem(logItem->name));//name
ui->tableWidget->setItem(index, 2, new QTableWidgetItem(BITS_str));//BITS
if(queue_i == oldRowItemNo)ui->tableWidget->selectRow(index);
index++;
}
ui->tableWidget->setRowCount(index);
}
else//display all rows
{
for(int queue_i = size_1, index = 0; queue_i >= 0; queue_i--, index++)
{
LogItem* logItem = (LogItem*)logDisplayQueue.at(queue_i); //read queue here
QString BITS_str = bits2Hexs(logItem->BITS);//
finish = clock();
ui->tableWidget->setItem(index, 0, new QTableWidgetItem(logItem->time));//time
ui->tableWidget->setItem(index, 1, new QTableWidgetItem(logItem->name));//name
ui->tableWidget->setItem(index, 2, new QTableWidgetItem(BITS_str));//BITS
if(queue_i == oldRowItemNo)ui->tableWidget->selectRow(index);
}
}
}
So the queue is quite samll and the background procedure is quite frequent(nearly 500 times per sec). That is, the queue will be written 500 times in 1 sec, but displayed time from time by the user.
I want to split the functions into two threads and run them together, one rev and update data, one display.
If i do not use any lock or mutex, the user may get the wrong data, but if i force the write-data procedure enter critical section and leave critical section everytime, it will be a heavy overload. :)
Should I use CRITICAL_SECTION or something else, any suggestions related?(my words could be verbose for you :) , i only hope for some hints :)
I'd put "Recv" function in another QObject derived class, put it under other QThread not main gui thread and connect "logItemAdded(LogItem* item)" signal to main window's "addLogItem(LogItem* item)" slot.
for just quick and dirty hint my conceptual code follows.
#include <QObject>
class Logger : public QObject
{
Q_OBJECT
public:
Logger(QObject* parent=0);
virtual ~Logger();
signals:
void logItemAdded(LogItem* logItem);
public slots:
protected:
void Rcv()
{
// ...
// was "add_logItem(logItem)"
emit logItemAdded(logItem);
}
};
MainWindow::MainWindow(...)
{
Logger logger = new Logger;
// setup your logger
QThread* thread = new QThread;
logger->moveToThread(thread);
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
Hope this helps.
Good luck.

Resources