tesuji 135 Master Poster

Hello,

I am using such a self-written auto-number generator on MS-SQL Server and Sybase databases for generating compound numbers, e.g. suffix.sequence-number.prefix. The numbers are generated from a user definded function for a specified table, say UDF genKey('table_name').

UDF genKey is able to manage various types of compound numbers, for example numbers which are taken from a given interval, numbers incremented by 10, numbers which are reset to start value if max. value exceeded. The data of all number types are stored in an own database table, say genkeys.

-- In principle, using such a number generator proceeds as follows:

create table genkeys ( ... )

insert into genkeys (... data of your specific number generator ...)

create function genKey (in keyTable varchar(25))
returns keyDomain

-- Generate new key for table keyTable depending on generator data stored in genkeys

return (new_key_for_table_keyTable);

end; 

-- Usage of genKey

begin transaction
  ... ;
  Insert into myTable (pk_ofmyTable, ... ) values (genKey('myTable'), ...);
  ... ;
commit;
   
-- Because UDF genKey() modifies table genkeys, this update and the insert/ updates 
-- using genkeys must build a unit of work, therefore begin transaction and commit are
-- absolutely necessary, ok, also sometimes rollback instead of commit.

The outlined generator system works efficiently on the noted databases. The UDF keyGen is written in SQL standard language PSM (Persistent Storage Modul, really weird name for a SQL procedural language derived from Oracles PL/SQL, now has been standardized since 1999) and is portable for most database systems.

tesuji 135 Master Poster

Helo

I think, now I have got a fair impression of what you are intended to do. I would suggest that you test the following query.

select monthname(tarikh_terima) as "Bulan", id_kategori as "Kategori", count(Kategori) as "Bilangan" from S01_ADUAN GROUP BY Bulan, Kategori ORDER BY tarikh_terima;

The idea of this query is that you pre-select your data and in 2nd step this data will be further arranged to meet your spread-sheet-like chart. Tell me its result and whether it meets your concept to some degree, especially whether you are missing some pieces of necessary information.

I would like to know what data is in table Kategoi (there must be such a table because id_kategori seems to be foreign key in S01_ADUAN). Please, state some data examples, say 4 to 5 rows.

Attached is an ERM of your three tables generated by reengineering tool where I decided that all attributes consisting of id + table name are primary keys (red color) and all other attributes having id in their names are foreign keys (green colors), there aren't identifying relationships to the extent I see. In case of foreign keys the unknown reference tables where formally created with names derived from foreign keys. This decision was necessary because, unfortunately, there aren't any primary or foreign key constraints defined in your tables. You may correct this ERM.

Well, is your database schema strictly prespecified or are there any changes possible (e.g. isam -> innodb, adding primary + foreign keys, …

tesuji 135 Master Poster

Hi

Did you #include "CNoFila.cpp" in your main() file ?

Did you add CNoFila.cpp to your project file or make ?

Which system do you use for programming, visual studio 2010?

-- tesu

tesuji 135 Master Poster

hi

The from clause of your first select has 3 joins, no matter whether they are inner or outer joins. Also the dates should be correctly formatted and the order-by predicate could be changed. Therefore the correct wording seems to be:

...
  FROM s01_aduan a 
    OUTER JOIN lkp_bahagian b ON a.id_aduan = b.bahagian_id
    OUTER JOIN s01_aduan_perkara c ON b.bahagian_id = c.id_aduan
  WHERE STR_TO_DATE(a.tarikh_terima, '%d-%m-%Y') BETWEEN STR_TO_DATE('01-01-2010', '%d-%m-%Y') 
    AND STR_TO_DATE('31-12-2010', '%d-%m-%Y') AND b.nama_bahagian='Bahagian Konsular' 
  GROUP BY bln
  ORDER by a.tarikh_terima  -- if tarikh_terima is of date-type, the order will be Jan, Feb, Mar ... Dec

It depends on you which sort of joins to be applied.

I think I can give more help if I know the create-table statements of all related tables, especially of tables s01_aduan, lkp_bahagian, s01_aduan_perkar. Your 2nd select has some more, e.g. table DUAL.

For choosing the right joins it is also important that all primary and forein keys of these tables be identified.

Can you post all these pieces of information?

-- tesu

tesuji 135 Master Poster

Hello,

All these identifiers not found and listed in error listing are class functions, e.g. lugareslavagem in line 21. They are declared in CNoFila.h, however, there exists no implementation as yet.

Corresponding to include file CNoFila.h there usually exists a further implemention file CNoFila.cpp, or some such thing, which must be included too. Furthermore, this implemention file must be part of your project or in the makefile depending on your developing system, e.g. visual studio, kdevelop, wxDec-c++ etc.

-- tesu

tesuji 135 Master Poster

Hello

You could try this:

select * from t3 where c1 || to_char(c3) in (select c1 || to_char(max(c3)) from t3 group by c1) order by c1, c2, c3;

c1, c2, c3 are your three columns. The subselect generates a temporary key from grouped c1 column and the corresponding to_char(maximums of c3). The outer select also generates a temporary key from c1 und c3 without grouping and aggregating. Then all rows with identical keys are seleted. Certainly, there exist more efficient solutions, however above select also finds duplicate rows. If you don't care duplicates, try: select distinct * ...

Hope it will work, nevertheless, this query not tested.

-- tesu

1stDAN commented: I tried but it doesn t work ! +1
tesuji 135 Master Poster

Well, getInFile is a class function of class FileController, where FileController might be inherited from eos because of eof(). If so, getInFile is very specific to class FileController which is not part of c++ iostream library.

Therefore, nobody is able to state anything on the behaviour of getInFile nor the question "Using .eof for looping is bad practice?" can't be seriously answered, except one knows all implementation details of FileController class. Everything else tends to be guesswork of a kind.

-- tesu

tesuji 135 Master Poster

I have to correct a mistake: I wrote that the one's complement would be still commonly used. This is not correct. Today, this complement is never been used. The prime reason is, that it allows two differently encoded zeros (0000, 1111).

To implement the zero test (if (a==0)...) both encodings must be implemented in a processor's hardware. Nowadays, negative whole numbers/integers are only encoded with two's complement because there is a bijective zero. There is a further advantage: If the result of a directly calculated subtraction is negative, this result is in two's complement, e.g. 0011B - 0111B = 1100B, where 1100B is just the two's complement of -4D.

Drawback of two's complement: One cannot calculate the absolute value of the largest negative number. Its result remains negative.

-- tesu

tesuji 135 Master Poster

"weired" should be weird, weird number?

tesuji 135 Master Poster

what is the ones complement representation of 0 ?

Short answer (0D encoded in 1 byte): 00000000 and 11111111. There are really two one's complement representations of decimal 0 (=0D).

Longer answer, well, not sure whether this answer is too long:

There are four commonly used methods for encoding [B]positive and negative[/B] binary number:

[I]One's complement,

Two's complement,

Sign-magnitude method,

Bias method.[/I]

All methods use the high order (hob) oder most significant (msb) bit to encode the sign, except for the bias method. Also in programming language COBOL the sign is encoded on the low-order-bit side (4 bits are used in COBOL, the low order half byte).

To show the various methods let me state this Example:
 
[I]What is the negative encoding of decimal 13D when encoded in [B]one byte/8 bits[/B]?[/I] 

We will also see that the length, the number of bits, used to encode negative numbers, is important too. 
 
Positive value of 13D is binary 1101B or hexadecimal DH what is to extend to 00001101B or 0DH to fill 8 bits (B=Binary, D=Decimal, H=Hexadecimal).

1. Negative 13D using one's complement
--------------------------------------
Rule: 0 becomes 1, 1 becomes 0
Result:  11110010B or hex F2H

2. Negative 13D using two's complement
--------------------------------------
Rule: calculate one's complement, then add 1.
Result: 11110010B + 1 = 11110011B or hex F2H+1 = F3H

In both cases the leading 1 (msb) indicates negative number.

[B]Important:[/B] If we hadn't put the 0000 on the left of 1101B, the negative results would have been wrong. …
tesuji 135 Master Poster

Selamat Siang,

what you are doing is conventional inner join where join conditions ar in where-clause. The result set of inner join only contains rows where these join conditions (a.id_aduan=c.id_aduan AND c.id_bahagian=b.bahagian_id) be completely matched. Only outer joins (left, right, full) guarantee that rows are included in result set where join conditions are not completely matched. This doesn't affect the other predicates, e.g. AND b.nama_bahagian='Bahagian Konsular'.

Btw, instead of

GROUP BY DATE_FORMAT(a.tarikh_terima,'%M')ASC

you can also write

GROUP BY bln

You should omit ASC in GROUP-BY because this clause does not have such thing.

Well, you order the results alphabetically by name of month, so April, August, December ... will be the order, more common seems to be ordering by number of month.

-- tesu

tesuji 135 Master Poster

Hi Iznar

I did some corrections on your program hopefully you will learn something of these. The lines I modified, added or deleted are marked by // and sometimes also explained.

Because of your true problems with pointers you should particularly focus on the usage of & and * in the following code.

#include <fstream>
#include <iostream>
#include <cmath>
using namespace std;

void processBlanks(int*wrd, char cp);  // & dropped and * added

int main()
{
ifstream inFile;
////ofstream outFile; not necessary

////int linecount, numpar;  not necessary
int wrd=0; 
char ch;

inFile.open("C:\\Documents and Settings\\Owner\\Desktop\\test1.txt");

////outFile.open("C:\\Documents and Settings\\Owner\\Desktop\\output.txt");  not necessary

/////if (!inFile) wrong, replaced by:
if (! inFile.is_open())
{
   cout<< "can't open File"<<endl;
   return 1;
}

/////inFile.get(ch); wrongly placed, must be part of while loop

/////while(inFile) wrong, replaced by:
while (inFile.get(ch) && !inFile.eof())
{
   /////while(inFile&&ch !='\n') wrong,  deleted
   /////{ deleted

   processBlanks(&wrd, ch);  ///// actually not necessary, yet consider the added &

    // if you arent't require to use a method/function, you should drop it 
    // and then uncomment the following line:
    // if (ch==' ') wrd++ ;   // that's all

//////} deleted
//////inFile.get(ch); overmuch, deleted

}
cout <<"Number of spaces " << wrd <<endl; 
inFile.close();     //// added 
return 0;       //// added
}

///// void processBlanks(ifstream& infile, int& wrd,char& cp) replaced by:
void processBlanks(int* wrd, char cp) //  <--- consider the * and there is NO &
{

if(cp==' ') (*wrd)++;  // <--- carefully consider the added () and *

//////return ; deleted
}

I only corrected your program in …

tesuji 135 Master Poster

Obviously, size of paintComponent is a global variable (instance or class). Where the scope of Vizatuesi's size is local within this method even it is a formal parameter. Any changes of the local variable does not affect the globally defined size, that is just as living in two different worlds.

Therefore the second code is correct.

You should read something about local, instance and class/ static variables, maybe at sun site.

-- tesu

tesuji 135 Master Poster

Well rayborn66, BOTH of your code snippets are WRONG as Ancient Dragon already pointed out.

You should really go back to your former thread and there you should carefully study my suggested code to understand why I put fin >> next within while loop exactly in the place where it is placed. You can't change the order of the statements as much as you please.

-- tesu

tesuji 135 Master Poster

I am glad that you solved it.

I am also about to learning Hibernate, yet i have been started with JPA 2.0 and Hibernate 3 on oracle database recently. It's really puzzling how Hibernate does all the mystic selects based only on a couple of annotations.

Afterwards, I think that the correlated select of your query might have also been responsible for that slow-down.

-- tesu

tesuji 135 Master Poster

Hello

First, variables must be initialize before using them, e.g. smallest has been defined but never been initialized. So put these two lines just before your while loop:

fin >> next;
smallest = largest = next;

Second, do not use fin.get(next) for this reads one char only, and not an int, result would be DT mismatching. The >> operator is much more powerful for it is overloading with almost all data types of c++, e.g. istream& operator>> (int& val ), just that what you need here.

Third, your while loop starts fine. But inside there is some trouble.

Think of redesign it that way:

while (! fin.eof())  // if you make use of eof(), fin should has been read once at least
{
     // 1. process your just  read-in data here:
     if ( next < smallest ) ...; else; if ( largest < next ) ...;

     // 2. read next data from file 
     fin >> next;  // again, do not use fin.get(.) for data type mismatching
} 

// coming here, smallest and largest shoud contain their appropriate values.
// Sorry, I don't have tested this code, so there might be some minor mistakes.

I hope these hints may help you a little.

-- tesu

tesuji 135 Master Poster

so the 4ah will become 4 and a? but both will be stored in al, so how will i be able to separate that?

Hi

Here is some code for processing the lower nibble (e.g. hex digit A of 4AH)

;....
	mov	dl, [bx]		; 2. processing bits 3 .. 0
	and	dl, 0fh			; clear bits 7 .. 4
	add	dl, 30h			; add '0' to make an ascii for output (!)
	cmp	dl, 3ah			; compare it with  3ah
	jb	lo			; hex digit   '0' .. '9'
	add	dl, 7h			; hex digit 'A' .. 'F' 
lo:     int     21h		        ; doscall, output <cl> on screen
;...

[bx] points to a char array in data segement, for example

chars	db 'abcdefghijklmnopqrstuvwxyz'	; to be output by hex$out
cends	db ?		; create a symbol to calculate number of chars

; then in code segment load byte ptr to chars array:
mov	bx, byte ptr chars	; start offset

Now you should reason how to process higher nibble (e.g. hex digit 4 of 4AH), for that you need a shr instruction (don't use cl reg)

-- tesu

tesuji 135 Master Poster

Standard dev is Sum((datapt - mean)^2)/(counter -1) so you can't add the squared data and then subtract the mean squared unfortunately since there is a cross term of -2*datapt*mean when you square it out. You need to hold all the data then calculate the mean, then do the calculation.

Sorry, even a phrenologist is allowed to make a mistake. Unfortunately, your implication is incorrect.
Proof: ;)

Let standard deviation be defined as:

s^2 = sum (a - xi)^2 /( n - 1)

By multiplying out the sum we get:

(n-1)*s^2 = sum(a^2) - 2*sum (a * xi) + sum(xi^2)
(n-1)*s^2 = sum(a^2) - 2*a*sum(xi) + sum(xi^2)
(n-1)*s^2 = sum(a^2) - 2*a*n*a + sum(xi^2)
(n-1)*s^2 = sum(xi^2) - n*a^2

and finally:

s = sqrt((sum(xi^2) - n*a^2)/(n-1)); 

(where n is number of measured data, xi is a single measured data, a is average sum(xi)/n, s is standard deviation of the measurement series, ^ stands for power of, sqrt() is square root)

You may take a try:

n = 5                              
i      1    2    3    4    5    sum
x      1    2    3    4    5    15
xi^2   1    4    9   16   25    55

a = 15 / 5 = 3
s = sqrt((55 - 5 * 3^2)/(5-1)) = sqrt(( 55 - 45) / 4 ) = sqrt(10/4) = 1.58

Prove it by taking the inconvenient way:

s = sqrt(((3-1)^2 + (3-2)^2 +(3-3)^2 +(3-4)^2 +(3-5)^2)/(5-1))  ?

You can also examine this facts on wikipedia. You may study there the last formula of paragraph "Identities …

jonsca commented: I concede +4
tesuji 135 Master Poster

Sorry, drop the s, so MUL stands for the unsigend multiply instruction.

Number-two homework? But this one is easy by contrast with your first one.

True, there are reasonable doubts in going that way, Jay-Z usually says. Its really easier because of one hexadecimal digit stands for four binary digits. So start by splitting 8 bits into two nibbles (4bits long, do not mistaken that american word :ooh:)

-- tesu

tesuji 135 Master Poster

13 0000000E B8C90B mov ax,3017
14 00000011 BB0300 mov bx,03h
15 00000014 F7F3 div bx

3017 divided by 3 makes 1005 remainder 2
1005 is in ax, remainder in dx
(1005D = 03EDH)

Now it's your turn to carry out these three steps:

16 00000016 0D7777 or ax,7777h
17
18 ; test
19 00000019 A821 test al,21h
20 0000001B B402 mov ah,02h

Hint: for the boolean instruction (test is and AND operation, al AND 21h) you have to write down the binary representation of the operands first. You can shorten the calculations for only 8 bits are significant ;)

-- tesu

tesuji 135 Master Poster

Btw, it is not necessary to read the data file twice for average and standard deviation can be calculated together within the first loop. You may do the following extensions to do this:

// After         double total = 0; // variable to hold total of all numbers

// add:
   double qtotal = 0;   // variable to hold the total squares of all numbers


// After 	total += next; // add numbers from file and store in total

// add:
   qtotal += next*next; // add the squares of the numbers


// After        double avg = (total/counter); // calculate the average

// add:
   double std = sqrt((qtotal - counter * avg)/(counter - 1)); // calculate the standard deviation
   cout << "The standard deviation is " << std; 

/*
The identity 

     sqrt(SUM(avg - next)^2/(counter - 1)) == sqrt((qtotal - counter * avg)/(counter - 1))

can easily be shown by multiplying out the summation of (avg - next)^2. 

If a large quantity of data should be calculated that way and where the standard deviation becomes very small the term (qtotal - counter * avg)/(counter - 1) could slightly fall below nought caused by numerical reasons. If this happens abs(qtotal - counter * avg) should be calculated. And sure, if there is only one number (counter=1), std is not defined.  
*/

You may try this new formula, it will save reading the file twice and the second loop.

-- tesu

tesuji 135 Master Poster

Hello

Could that be that you have mistaken counter and avg in:

stdDev = sqrt((totalDevSqrd / (avg - 1))); /* standard deviation equals the square root of the total square deviations devided by the average minus 1 */

// shouldn't it be?
	stdDev = sqrt((totalDevSqrd / (counter - 1))); //... divided by counter-1

-- tesu

tesuji 135 Master Poster

Yes, by running it manually.

For example what is the result in dx:ax after execution of 00000014 ?

tesuji 135 Master Poster

I was wondering if it is possible to subtract 30 from 4ah? i thought so i can convert the ascii character 'C' to hexadecimal '43', i will just subtract 30h from 43h, then add 30 so it will become 43 again and i will be able to perfrom arithmetic on it, but then i realized, what about when the hexadecimal has letters on it? hmm. help please!

Hi cmsc,

I am glad that we have solved your other task. Fortunately, your new homework is much more easier than the one which required int inputs, just about a full dozen of instructions, all dealing with 8 bit registers, currently no MULs :cool:

-- tesu

tesuji 135 Master Poster

The character in memory position 109h = F

Hello

Well done !

Do you know how to prove it?


-- tesu

tesuji 135 Master Poster

Hi

I didn't found any error function when I was searching the compilers (gcc, visual c, watcom). Therefore, I took an approximation from Abramowitz/Stegun and wrote my own erf(x). It's approximation error is about 10^(-7). which was almost always sufficient for my apps. erf(x) = 1-erfc(x).

double erf(double x)
{  
/* erf(z) = 2/sqrt(pi) * Integral(0..x) exp( -t^2) dt
erf(0.01) = 0.0112834772 erf(3.7) = 0.9999998325
Abramowitz/Stegun: p299, |erf(z)-erf| <= 1.5*10^(-7) 
*/
 double y = 1.0 / ( 1.0 + 0.3275911 * x);   
 return 1 - (((((
        + 1.061405429  * y
        - 1.453152027) * y
        + 1.421413741) * y
        - 0.284496736) * y 
        + 0.254829592) * y) 
        * exp (-x * x);      
}

Maybe this small function is also useful for you.

--tesu

tesuji 135 Master Poster

Hi again,

can you tell me what "product_id" is?

Most likely "product_id" seems to be an unique IDent, possibly generated by autoincrement. If so, there is nothing to group-by. That means count(*) is always 1 because each product_id is unique.

If you want the grand total, that is you want to count all rows of your table, then your select should be:

SELECT COUNT(product_id) AS grandtotal FROM tblproduct;

If you want to count all rows, where product_name is like '%name% your select should be:

SELECT COUNT(product_id) AS tot, product_name FROM tblproduct WHERE product_name LIKE '%name%' GROUP BY product_name ORDER BY tot LIMIT 10;

Here only rows with same '%name%' will be counted together. Every time the value of '%name%' changes, count(*) is reset to 0 and starts again.

If you have LIMIT in your select statement, ORDER BY is mandatory. If you omit ORDER BY, the result is indeterminate too. Almost all database systems will raise an error if FIRST, TOP or LIMIT is used without ORDER BY clause.

-- tesu

tesuji 135 Master Poster

I found it how to show postgresql's execution plan (query plan):

EXPLAIN SELECT your_further_select_statement, and it's like Oracle's EXPLAIN PLAN (what has to be expected). Here is something about joins and cartesian products.

-- tesu

(The operator has decided that I can't update posting older than 29.999 minutes. So I did new posting)

tesuji 135 Master Poster

Hello,

I am glad to meeting here a postgresql fan too! So let's proceed unter mysql's hood.

What do you actually mean by

>> relataions.relation_type_id foreign from relation_type.id
>> relations.from_id foreign from items.id
>> relations.to_id foreign from items.id
?

Sure, because of the one-to-many relationships relataions.relation_type_id is a foreign key which points to master table relation_type. Both columns are used in the where clause to define the inner join.

But this usage DOES NOT mean that the table also has a foreign-key constraint what is usually table-defined in:

create table relataions (... id integer, ... FOREIGN KEY (id) REFERENCES relation_type, ...);

Also usage of relation_type.id does not mean that id is primary key of table relation_type, as usually defined in:

create table relation_type (... id integer, ... PRIMARY KEY (id), ...);

Well, if all these primary and foreign key constraints are well defined the way I just sketched out, there would be automatically put an index on all those primary and foreign key columns.

These indexes are very important to carry out all inner joins with high speed. If these indexes DO NOT exist because of omitting proper definition of primary AND foreign keys the inner joins would degenerate into cartesian products (cross products).

For example if all of your three tables have 1000 rows each, the number of comparisons necessary to compute the degenerated inner …

tesuji 135 Master Poster

Nope didn't work but I actually solved it by trying:
stmt->executeUpdate("UPDATE users SET usersactive = '20' WHERE id='1'");

WOW true! I have to apologize for not seeing the wood for the trees :-O

True, executeQuery is in the wrong place here! Maybe simple execute(.) would have also functioned correctly.

-- tesu

tesuji 135 Master Poster

Well, I am stumped now. I would have bet everything that redefining an already used stmt had caused that error. Now last try: delete stmt just before newstmt = con->createStatement();.

additional question: what is the current value of usersactive2? Is it acceptable?

To be more precise, what actually means: "Doesn't work with this" ? does it mean that the exception still occurs ?

-- tesu

tesuji 135 Master Poster

I am sure the exception around the update statement now disappeared. But there would be some problems within while loop too.

-- tesu

tesuji 135 Master Poster

The executequery where I do the update thing.

Ah sorry, I should have read your code more seriously. So the error happens there:

stmt = con->createStatement();
res = stmt->executeQuery("UPDATE users SET usersactive = '10' WHERE id='1'");

You redefine a prior stmt, what could lead to problems with its dynamically allocated structure.

Simply try the following:

newstmt = con->createStatement();
res = newstmt->executeQuery("UPDATE users SET usersactive = '10' WHERE id='1'");

If I remember correctly, you must use a new stmt if you didn't close the old stmt priorly because of some reentrance problem of mysql c++ connector.

Try it, what is the result?

-- tesu

tesuji 135 Master Poster

Well, some 8k entries and excecuting that select statement would last about 22 sec ? sounds really kind of unreal.

So which database engine? Are there any primary keys and foreign keys, or indexes defined on tables: items it, relations rel, relation_types relType?

If NOT, access time is proportional to the cardinality of numbers of rows (NOR) of table items times NOR of table relationals times NOR of table relation_types, what could be a very large number. You may use count(*) to compute the cardinality of those inner joins.

Therefore, properly defined primary and foreign keys would really speed up access time.

If there aren't any properly defined primary and foreign keys, you can put indexes on the appropriate colums for speeding up access time afterwards, what does not directly affect the existing database schema, in other words, you don't do a redesign when adding indexes.

-- tesu

tesuji 135 Master Poster

sounds really strange.

btw, which line between line# 14 and 59 is actually responsible for this strange exception?

-- tesu

tesuji 135 Master Poster

Hello

Not really sure whether it will work:

1. Sort the array by a method O(n log n), for example by heap or quick sort

2. Then access the array elements by bisection method, O(log n).


-- tesu

tesuji 135 Master Poster

well then,

what actually is wrong with your output? Why not posting this?

Knowing your compiler would be a great help too. Indeed, there are such twerps still not knowing long double. Also there are some convention such as l or L or typecasting when processing long double.

-- tesu

tesuji 135 Master Poster

well, if in

>> while(!IsKeyPressed(VK_ESCAPE) )

IsKeyPressed functions as I am supposing, then your exception is NOT thrown by an sql mistake but thrown by for example most likely heap/stack overflow because

>> stmt = con->createStatement();
>> res = stmt->executeQuery("SELECT isRedeemOn FROM isredeemon");

will be executed as often as not.

Please test it by deleting the while loop.

btw, what do you want to do within the while-loop, accessing the rows and their column values?

-- tesu

tesuji 135 Master Poster

Please, submit the complete method where these both statement

>> stmt = con->createStatement();
>> res = stmt->executeQuery("UPDATE users SET usersactive = usersactive+1");

be executed and the exception be thrown.

-- tesu

tesuji 135 Master Poster

I got only one entry and one column in my table so would I do like this

stmt = con->createStatement();
res = stmt->executeQuery("UPDATE users SET usersactive = usersactive+1");

This isn't working.. What do I do wrong

Maybe this is finally missing:

res = stmt->executeQuery("COMMIT");

It's always necessary after a sequence of INSERT, UPDATE, or DELETE statements if your database is configured with "set autocommit off;".

-- tesu

tesuji 135 Master Poster

unfortunately not, for multiplication or division 16 bits registers dx:ax are required at least.

-- tesu

tesuji 135 Master Poster

@tesu:
The algorithm is correct. Its just that the first tw0 terms of the series must be printed separately. fibo(18) is 2584 iff fibo(0) = 0. So what you are printing as your first term should be the 2nd term (ie fibo(2) if we take the first term as fibo(0)).

generally the series is :

fibo(0)------ 0
fibo(1)------ 1
fibo(2)------ 1
fibo(3)------ 2
fibo(4)------ 3

...............
...............

fibo(18)------ 2584


hope it helps.


P.S: @xaop
once you get the logic correct spend some time on coming up with meaningful variable names. Also use proper indentation. As of now, a small advice, never use void main(). Its plain wrong (and disrespect to the creators of C).

Sorry, I don't agree, NPC.

His algorithm does not produce FIB(18). So it must be considered to be incorrect, even if we don't regard his mistake in if-statement.

Here is a somewhat more compact iterative Fibonacci:

for(int i=0,n=18,x,y=0,z=1;i<=n;i++,x=y,y=z,z=x+z,printf("%3d %5d\n",i-1,x));

-- tesu

tesuji 135 Master Poster

xor ah, ah is equivalent to mov ah, 0 ; yet a bit faster (the fasted 0 one can generate)

AND al, 0FH can be replaced by SUB al, 30H ; 3xH - 30H = 0XH (x from 0..9)

Again, logical instruction AND is faster than numeric SUB.

-- tesu

tesuji 135 Master Poster

hello! i need to make this program that lets the user input like for example 99 then the program will output 'c'.

i don't know how to start. but i thought about getting the first 9 first, then subtract 30h, the multiply it by 10. afterwards, add the other 9, then subtract 26, because c -> 99 -> is 63h in hexadecimal. but... when i try the others i need to subtract different values to convert them to hexadecimal. am i using the wrong approach?
thank you very much for your replies. :D

Your approach starts well but then the idea of subtracting 26 (what base?) leads to wrong solution. Assuming that you want input two-digit integer values, for examples decimal 07, 99, max. 127, by int21h and ah function code 01h, ascii-result (30h..39h) in al twice done, then:

A. Processing first digit

1. AND al, 0FH ; mask 3XH to 0XH, where X is from {0,1..9}

2. XOR ah, ah ; we need AX for multiplying X by 10D

3. MOV bx, 10D ; to compute <ax> * 10 = X0D

4. MUL bx ; computes ax * bx, result in dx:ax, you only need ax

5. MOV bx, ax ; save X0D for further processing

B. Processing second digit and add both decimal digits

Because of 80x86's weak mul capability we need to restore ah first

Now get second digit and mask it, as is first digit, result …

tesuji 135 Master Poster

Hi again,

no, this is not a true brain-teaser, actually it's quite easy to give a correct data model. If you were plain followed my suggestions, you would have already solved it.

-- tesu

tesuji 135 Master Poster

he, there seems to be a mistake in your algorithm, because fib(18) is 2584.

-- tesu

tesuji 135 Master Poster

Still no difference :(

all it prints is " 1 "

that s true, you should also replace if by for loop:

//if(n<=18)

for (int i=1; i <=18; i++)
{
printf("%2d    %5d\n", i ,n);
n=f+s;
f=s;
s=n;
n=f+s;
}
/*
now result is:

 1        1
 2        2
 3        3
 4        5
 5        8
 6       13
 7       21
 8       34
 9       55
10       89
11      144
12      233
13      377
14      610
15      987
16     1597
17     2584
18     4181

>>> Your algorithm isn't completely correct for fibo(18) = 2584. Also f1=f2=1 and f0=0.
Possibly s contains correct series.
*/

-- tesu

tesuji 135 Master Poster

hi,

you should remove the ; in this line: if(n<=18);

-- tesu

tesuji 135 Master Poster

:D thanx a lot! :) at one point i did thought of that, but then i think i forgot..

Ok:) Unfortunately, one can easily be seduced by MySQL when using aggregate functions. Other database systems always adamantly return an error if group-by is missing when using aggregate function together with other columns.

-- tesu

tesuji 135 Master Poster
// Your query

$query="SELECT COUNT(product_id) AS tot,product_id,product_name FROM tblproduct WHERE product_name LIKE '%$pname%'"

// must have group-by clause

$query="SELECT COUNT(product_id) AS tot,product_id,product_name FROM tblproduct WHERE product_name LIKE '%$pname%' [B]GROUP BY[/B] product_id, product_name"

//  in order to work properly.

If you don't like GROUP-BY clause you must omit "product_id,product_name ". If you don't omit these two columns the results are indeterminate.

-- tesu