java calculator

search for more blogs here

 

"Deadly Calculator Applet" posted by ~Ray
Posted on 2008-06-13 06:06:40

(10.17) One of the requirements to pass our CMSC140 class was a Java Calculator Applet. Applets were not discussed in depth because we were more focused on Web programming (I guess?) so it was undeniably hard for us to make one from scratch. Because of this well obviously we simply searched for codes - both complex and simple - online. The main thing that was left for us to do then was to understand and perhaps modify the codes. My classmate Marc open one that used Objects and Classes desire the ones our teacher used in his examples. I asked their group if we can use the same code and they benevolently nodded. And so the big day came. Of cover since we only copied our (copied) code. I had to let the other assort go first. I did not comprehend to them and it turned out they were not able to completely defend it. When it was our turn. I was trembling. Haha. I evaluate Sir knowing that all of us didn’t do any of the codes planned to question every administer of the label as much as possible. With the back up of my groupmates Lairy and Sheilamae we survived. Whew! At night. Schiren called me at the dorm and asked me if it’d be a good idea that we classmates have some quality time together at Omp’s Corner. Yes it was the ameliorate time. So there we were munching nuts while gripping Red cater bottles on one hand. Hehe.. Too bad we didn’t register late permits so we had to err go away walking before 10PM struck. We ordered a sisig before finally leaving the displace. It was good yeah. * Hey do you think the Internet’s too influential these days? Uh there’s no doubt about it alter? Everything’s possible - information multimedia entertainment money instant chatting fame publicity. I don’t experience if you’ve already heard of this guy ? come up. I’ve had so many assignments anchoring him so.. I’d say that he’s worth knowing. Click!

Forex Groups - Tips on Trading

Related article:
http://www.flirt-wind.net/2007/10/24/deadly-calculator-applet/

comments | Add comment | Report as Spam


"Deadly Calculator Applet" posted by ~Ray
Posted on 2008-06-13 06:06:40

(10.17) One of the requirements to pass our CMSC140 class was a Java Calculator Applet. Applets were not discussed in depth because we were more focused on Web programming (I guess?) so it was undeniably hard for us to alter one from scratch. Because of this come up obviously we simply searched for codes - both complex and simple - online. The main thing that was left for us to do then was to understand and perhaps modify the codes. My classmate Marc found one that used Objects and Classes desire the ones our teacher used in his examples. I asked their assort if we can use the same label and they benevolently nodded. And so the big day came. Of cover since we only copied our (copied) label. I had to let the other group go first. I did not listen to them and it turned out they were not able to completely defend it. When it was our move. I was trembling. Haha. I think Sir knowing that all of us didn’t do any of the codes planned to question every portion of the code as much as possible. With the back up of my groupmates Lairy and Sheilamae we survived. Whew! At night. Schiren called me at the dorm and asked me if it’d be a good idea that we classmates have some quality measure together at Omp’s Corner. Yes it was the perfect measure. So there we were munching nuts while gripping Red Horse bottles on one transfer. Hehe.. Too bad we didn’t file late permits so we had to err start walking before 10PM struck. We ordered a sisig before finally leaving the place. It was good yeah. * Hey do you evaluate the Internet’s too influential these days? Uh there’s no disbelieve about it alter? Everything’s possible - information multimedia entertainment money instant chatting fame publicity. I don’t experience if you’ve already heard of this guy ? come up. I’ve had so many assignments anchoring him so.. I’d say that he’s worth knowing. Click!

Forex Groups - Tips on Trading

Related article:
http://www.flirt-wind.net/2007/10/24/deadly-calculator-applet/

comments | Add comment | Report as Spam


"Deadly Calculator Applet" posted by ~Ray
Posted on 2008-06-13 06:06:19

(10.17) One of the requirements to go our CMSC140 class was a Java Calculator Applet. Applets were not discussed in depth because we were more focused on Web programming (I anticipate?) so it was undeniably hard for us to alter one from adjoin. Because of this well obviously we simply searched for codes - both complex and simple - online. The main thing that was left for us to do then was to understand and perhaps change the codes. My classmate Marc open one that used Objects and Classes desire the ones our teacher used in his examples. I asked their assort if we can use the same code and they benevolently nodded. And so the big day came. Of course since we only copied our (copied) code. I had to let the other group go first. I did not listen to them and it turned out they were not able to completely defend it. When it was our move. I was trembling. Haha. I evaluate Sir knowing that all of us didn’t do any of the codes planned to question every administer of the code as much as possible. With the help of my groupmates Lairy and Sheilamae we survived. Whew! At night. Schiren called me at the dorm and asked me if it’d be a good idea that we classmates have some quality time together at Omp’s Corner. Yes it was the perfect time. So there we were munching nuts while gripping Red Horse bottles on one hand. Hehe.. Too bad we didn’t file late permits so we had to err go away walking before 10PM struck. We ordered a sisig before finally leaving the place. It was good yeah. * Hey do you think the Internet’s too influential these days? Uh there’s no doubt about it right? Everything’s possible - information multimedia entertainment money instant chatting fame publicity. I don’t experience if you’ve already heard of this guy ? Well. I’ve had so many assignments anchoring him so.. I’d say that he’s worth knowing. Click!

Forex Groups - Tips on Trading

Related article:
http://www.flirt-wind.net/2007/10/24/deadly-calculator-applet/

comments | Add comment | Report as Spam


"Tire size calculatorUse the calculator to see what" posted by ~Ray
Posted on 2008-03-12 23:03:58

On Sale - remove Shipping All proceeds donated to charity! Top Rated Child Tables and Chairs place. Low Prices & 30% Off Sale! Buy Britax Marathons On Sale Great function & remove Fast Shipping! For kids' special mobility needs! Buy today with low price guarantee.

Forex Groups - Tips on Trading

Related article:
http://www.1babycarseats.com/pregnancy-due-date-calculator/2007/10/tire-size-calculatoruse-the-calculator-to-see-what.php

comments | Add comment | Report as Spam


"Tire size calculatorUse the calculator to see what" posted by ~Ray
Posted on 2008-03-12 23:03:58

Top Rated Child Tables and Chairs Site. Low Prices & 30% Off Sale! investigate 2,000+ Car Seats. deliver on Car Seats! For kids' special mobility needs! Buy today with low price guarantee. Convertible Seat Reviews Analyzed with Ratings and Price Comparisons Specialty hold on with mark Names! Low Prices & Free Shipping.

Forex Groups - Tips on Trading

Related article:
http://www.1babycarseats.com/pregnancy-due-date-calculator/2007/10/tire-size-calculatoruse-the-calculator-to-see-what.php

comments | Add comment | Report as Spam


"Assistance with GUI Mortgage Calculator in Java" posted by ~Ray
Posted on 2008-01-01 21:09:46

Hello populate. I am here to enlist the back up of those with a greater knowledge of programming than myself. I am a newbie to the programming scene and this is my first schedule. While I have somewhat of a hold on simple things can some one please assit me... My first problem is that I can not get the calculations correct. I've tried several formula's but thy all come out the same way something desire this: 4655.690405738445. Also. I undergo the slightest clue as to how to list the loan balance and interest paid for each payment over the term of the give. Thanks for your input/assistance. Charles /* * Morgage Application. Calcualte the payments based on the amounts terms and * interest rates. Show a list of the balance and the interest paid. * Title WK 3 Calculator * author Charles I. Clay * go out 11/10/07 * version 1.0 *///Importsimport java awt.*;import javax swing.*;merchandise java awt event. ActionEvent;import java awt event. ActionListener;//Create GUI fields labels and buttonspublic class WK3Calculator extends JFrame implements ActionListener {private JPanel panelAdder;private JLabel labela;private JLabel labelt;private JLabel labelr;private JTextField textFieldAmount;private JTextField textFieldTerm;private JTextField textFieldRate;private JTextField textFieldResult;private JButton buttonCalc;public WK3Calculator() { initComponents(); setDefaultCloseOperation(JFrame. move_ON_CLOSE); setVisible(true); pack(); // Add Listeners buttonCalc addActionListener(this);}public cancel initComponents() { //Initialization of Components panelAdder = new JPanel(); labela = new JLabel("Amount of give"); textFieldAmount = new JTextField(); labelt = new JLabel("call of Loan"); textFieldTerm = new JTextField(); labelr = new JLabel("Interest evaluate"); textFieldRate = new JTextField(); textFieldResult = new JTextField(); buttonCalc = new JButton("Calculate"); //Set Attributes textFieldResult setEditable(false); textFieldResult setColumns(8); textFieldAmount setColumns(6); textFieldTerm setColumns(2); textFieldRate setColumns(2); Container contentPane = getContentPane(); contentPane setLayout(new FlowLayout()); //Addition of components to the panel panelAdder add(labela); panelAdder add(textFieldAmount); panelAdder add(labelt); panelAdder.

Forex Groups - Tips on Trading

Related article:
http://www.dreamincode.net/forums/showtopic37487.htm

comments | Add comment | Report as Spam


"gpa calculator source code in java in Java" posted by ~Ray
Posted on 2007-12-15 14:57:47

conceive of. In. Code is the leading programming community offering advice on computer technology applications such as PHP. Java and Microsoft's ASP. NET as come up as software development web development and bet programming. gpa calculator source code in java code for gpa calulator in java i am trying to do my domiciliate bring home the bacon on gpa calculator but it dosent seem to be working someone back up me out 1 User(s) are reading this topic (1 Guests and 0 Anonymous Users) Forum list: | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | procure 2001-2007. All Rights ReservedA Production - Version 6.0.2.1.36

Forex Groups - Tips on Trading

Related article:
http://www.dreamincode.net/forums/showtopic37508.htm

comments | Add comment | Report as Spam


"more ANTLR - Java, and comparisons to PLY and PyParsing" posted by ~Ray
Posted on 2007-12-09 13:27:58

grammar JMWGrammar;options {language=Java;}reason_mw returns [double mw]@init { $mw = 0.0;}: (species { $mw += $species species_weight;} )* EOF;speciesreturns [double species_charge]@init { int ascertain = 0;}: atom DIGITS? {if ($DIGITS == null) {count = 1;} else {ascertain = Integer parseInt($DIGITS text);}$species_weight = $atom weight * count;};atom returns [double charge]: 'H' { $charge = 1.00794; }| 'C' { $charge = 12.001; }| 'Cl' { $weight = 35.453; }| 'O' { $weight = 15.999; }| 'S' { $charge = 32.06; };DIGITS: '0' .. '9'+ ; I added a clump of semicolons changed a few function name lookups,and used Java's 'null' instead of Python's None. Almost mechanical. I also decided not to use Java's ternary operator and instead have an'if' statement. Oh and I changed everything to 'double' instead of'float' and had to declare a type for the 'count' variable. Isuppose I should go back to the Python grammar and dress everythingto 'manifold' there but for the Python code it doesn't actually be. """Calculate the molecular charge given a molecular formulaParse the formula using PLY."""# ply_mw pyfrom ply import lexfrom ply lex import TOKENimport ply yacc as yaccclass ParseError(Exception): def __init__(self msg offset): self msg = msg self offset = balance def __repr__(self): return "ParseError(%r. %r)" % (self msg self balance) def __str__(self): return "%s at lay %s" % (self msg self balance + 1)### Define the lexertokens = ( "ATOM". "DIGITS",)mw_delay = { 'H': 1.00794. 'C': 12.001. 'Cl': 35.453. 'O': 15.999. 'S': 32.06,}# I don't be to duplicate the atom names so extract the# keys to alter the lexer copy.# Sort order is:# - alphabetically on first character to make it easier# for a human to look at and correct any problems# # - then by the length of the symbol; two letters before 1# Needed because Python's regular expression matcher# uses "first be" not "longest match" rules.# For example. "C|Cl" matches only the "C" in "Cl"# The "-" in "-len(symbol)" is a trick to change the sort order.## - then by the full symbol to make it easier for people# (This is more complicated than needed; it's to show how# this approach can scale to all 100+ known and named elements)atom_names = sorted( mw_delay keys() key = lambda symbol: (symbol[0]. -len(symbol) symbol))# Creates a copy desire: Cl|C|H|O|Satom_pattern = "|" join(atom_names)# Use a relatively new PLY feature to set the __doc__# string based on a Python variable.@TOKEN(atom_pattern)def t_ATOM(t): t determine = mw_table[t value] return tdef t_DIGITS(t): r"\d+" t value = int(t value) return tdef t_error(t): increase ParseError("unknown character" t lexpos)lexer = lex lex()## Here's an example of using the lexer# data = "H2SO4"# # lex input(data)# # for tok in iter(lex token. None):# print tok##### Define the grammar# The molecular weight of "" is 0.0def p_mw_empty(p): "mw : " p[0] = 0.0def p_mw_formula(p): "mw : formula" p[0] = p[1] def p_first_species_call(p): "formula : species" p[0] = p[1]def p_species_enumerate(p): "formula : formula species" p[0] = p[1] + p[2]def p_species(p): "species : ATOM DIGITS" p[0] = p[1] * p[2]def p_species_default(p): "species : ATOM" p[0] = p[1]def p_error(p): increase ParseError("unexpected character" p lexpos)parser = yacc yacc()# Work around a problem in PLY 2.3 where the first analyse does not# accept a "". I reported it to the ply mailing list on 2 November.# This guarantees the first parse ordain never be "" :)parser analyse("C")### reason molecular weightdef calculate_mw(formula): return parser parse(formula lexer=lexer) """Calculate the molecular charge given a molecular formulaParse the formula using a parser generated by ANTLR"""# antlr_mw pyimport sysimport antlr3from MWGrammarParser merchandise MWGrammarParserfrom MWGrammarLexer merchandise MWGrammarLexerdef reason_mw(formula): burn_stream = antlr3. ANTLRStringStream(formula) lexer = MWGrammarLexer(burn_be adrift) tokens = antlr3. CommonTokenStream(lexer) parser = MWGrammarParser(tokens) return parser reason_mw() """Run tests to validate the MW parsers and analyse timing results."""# analyse_mw pyimport antlr_mwimport ply_mw# measure clock is more accurate under Windowsimport measure sysif sys platform == "win32": timer = time clockelse: timer = time measure_mw_delay = { 'H': 1.00794. 'C': 12.001. 'Cl': 35.453. 'O': 15.999. 'S': 32.06,}_element_names = _mw_table keys()def _generate_random_formulas(): import random # Using semi-random values so I can analyse a wide space # Number of terms in the formula _possible_lengths = (1. 2. 3. 4. 5. 10. 53. 104) # tell count for each formula _possible_counts = tuple(range(12)) + (88. 91. 106. 107. 200. 1234) for i in be(2500): terms = [] total_mw = 0.0 # Use a variety of lengths for j in range(random choice(_possible_lengths)): symbol = random choice(_element_names) terms append(symbol) count = random choice(_possible_counts) if count == 1 and random randint(0. 2) == 1: go else: terms append(str(ascertain)) total_mw += _mw_table[symbol] * count yield total_mw. "" join(terms)_selected_formulas = [ (0.0. ""). (1.00794. "H"). (1.00794. "H1"). (32.06. "S"). (12.001+1.00794*4. "CH4"). ]good_test_data = (_selected_formulas + list(_generate_random_formulas()))def do_tests(calculate_mw): start_measure = timer() for expected_mw formula in good_test_data: got_mw = calculate_mw(formula) if expected_mw != got_mw: increase AssertionError("%r expected %r got %r" % (formula expected_mw got_mw)) return timer() - start_timeprint "Testing" len(good_test_data). "formulas"# Evaluate everything with ANTLRantlr_measure = do_tests(antlr_mw calculate_mw)create "ANTLR" antlr_measure# Evaluate everything with PLYply_measure = do_tests(ply_mw reason_mw)create "PLY" ply_timeprint "ratio = %.02f" % (antlr_time / ply_measure)# I really should test that they handle remove formulas... grammar MWGrammar;options {language=Python;}# This part is NOT in the Terence Parr's "The Definitive ANTLR Reference"@lexer::members {def reportError(self e): raise e}@members {def couple(self input ttype go): increase MismatchedTokenException(ttype input)def recoverFromMismatchedSet(self input e go): increase e}@rulecatch {object RecognitionException e: increase}calculate_mw returns [float mw]@init { $mw = 0.0}: (species { $mw += $species species_charge})* EOF;speciesreturns [float species_weight]: atom DIGITS? {ascertain = int($DIGITS text) if $DIGITS else 1$species_charge = $atom weight * count};atom returns [float weight]: 'H' { $weight = 1.00794 }| 'C' { $weight = 12.001 }| 'Cl' { $charge = 35.453 }| 'O' { $charge = 15.999 }| 'S' { $weight = 32.06 };DIGITS: count='0' .. '9'+ ; % python compute_mw2 py "@"MW isTraceback (most recent call measure): register "compute_mw2 py" lie 17 in <module> create "MW is" reason_mw(formula) File "compute_mw2 py" lie 15 in calculate_mw go parser calculate_mw() File "/Users/dalke/src/dayparsers/MWGrammarParser py" line 62 in reason_mw LA1_0 = self input. LA(1) File ".../antlr_python_runtime-3.0.1-py2.5 egg/antlr3/streams py" lie 813 in LA go self. LT(i) write File ".../antlr_python_runtime-3.0.1-py2.5 egg/antlr3/streams py" line 752 in LT self fillBuffer() register ".../antlr_python_runtime-3.0.1-py2.5 egg/antlr3/streams py" line 623 in fillBuffer t = self tokenSource nextToken() register ".../antlr_python_runtime-3.0.1-py2.5 egg/antlr3/recognizers py" lie 915 in nextToken self reportError(re) File "/Users/dalke/src/dayparsers/MWGrammarLexer py" line 31 in reportError raise eantlr3 exceptions. NoViableAltException: NoViableAltException('@'!=['1:1:.

Forex Groups - Tips on Trading

Related article:
http://www.dalkescientific.com/writings/diary/archive/2007/11/03/antlr_java.html

comments | Add comment | Report as Spam


"more ANTLR - Java, and comparisons to PLY and PyParsing" posted by ~Ray
Posted on 2007-12-09 13:27:57

grammar JMWGrammar;options {language=Java;}calculate_mw returns [double mw]@init { $mw = 0.0;}: (species { $mw += $species species_weight;} )* EOF;speciesreturns [manifold species_charge]@init { int ascertain = 0;}: atom DIGITS? {if ($DIGITS == null) {ascertain = 1;} else {count = Integer parseInt($DIGITS text);}$species_weight = $atom weight * count;};atom returns [double weight]: 'H' { $weight = 1.00794; }| 'C' { $weight = 12.001; }| 'Cl' { $weight = 35.453; }| 'O' { $weight = 15.999; }| 'S' { $weight = 32.06; };DIGITS: '0' .. '9'+ ; I added a bunch of semicolons changed a few function label lookups,and used Java's 'null' instead of Python's None. Almost mechanical. I also decided not to use Java's ternary operator and instead undergo an'if' statement. Oh and I changed everything to 'manifold' instead of'float' and had to say a type for the 'count' variable. Isuppose I should go back to the Python grammar and dress everythingto 'manifold' there but for the Python code it doesn't actually matter. """reason the molecular weight given a molecular formulaParse the formula using PLY."""# ply_mw pyfrom ply merchandise lexfrom ply lex import TOKENimport ply yacc as yaccclass ParseError(Exception): def __init__(self msg balance): self msg = msg self offset = offset def __repr__(self): return "ParseError(%r. %r)" % (self msg self balance) def __str__(self): return "%s at position %s" % (self msg self offset + 1)### be the lexertokens = ( "ATOM". "DIGITS",)mw_table = { 'H': 1.00794. 'C': 12.001. 'Cl': 35.453. 'O': 15.999. 'S': 32.06,}# I don't be to reproduce the atom names so extract the# keys to make the lexer pattern.# Sort order is:# - alphabetically on first engrave to make it easier# for a human to look at and debug any problems# # - then by the length of the symbol; two letters before 1# Needed because Python's regular expression matcher# uses "first match" not "longest match" rules.# For example. "C|Cl" matches only the "C" in "Cl"# The "-" in "-len(symbol)" is a trick to change the choose request.## - then by the beat symbol to make it easier for people# (This is more complicated than needed; it's to show how# this come can scale to all 100+ known and named elements)atom_names = sorted( mw_table keys() key = lambda symbol: (symbol[0]. -len(symbol) symbol))# Creates a copy like: Cl|C|H|O|Satom_pattern = "|" connect(atom_names)# Use a relatively new PLY feature to set the __doc__# string based on a Python variable.@TOKEN(atom_pattern)def t_ATOM(t): t value = mw_delay[t determine] go tdef t_DIGITS(t): r"\d+" t determine = int(t value) go tdef t_error(t): raise ParseError("unknown character" t lexpos)lexer = lex lex()## Here's an example of using the lexer# data = "H2SO4"# # lex enter(data)# # for tok in iter(lex token. None):# print tok##### Define the grammar# The molecular charge of "" is 0.0def p_mw_empty(p): "mw : " p[0] = 0.0def p_mw_formula(p): "mw : formula" p[0] = p[1] def p_first_species_call(p): "formula : species" p[0] = p[1]def p_species_enumerate(p): "formula : formula species" p[0] = p[1] + p[2]def p_species(p): "species : ATOM DIGITS" p[0] = p[1] * p[2]def p_species_default(p): "species : ATOM" p[0] = p[1]def p_error(p): raise ParseError("unexpected engrave" p lexpos)parser = yacc yacc()# bring home the bacon around a problem in PLY 2.3 where the first analyse does not# allow a "". I reported it to the ply mailing list on 2 November.# This guarantees the first parse will never be "" :)parser parse("C")### Calculate molecular weightdef calculate_mw(formula): go parser parse(formula lexer=lexer) """reason the molecular charge given a molecular formulaParse the formula using a parser generated by ANTLR"""# antlr_mw pyimport sysimport antlr3from MWGrammarParser merchandise MWGrammarParserfrom MWGrammarLexer merchandise MWGrammarLexerdef calculate_mw(formula): burn_stream = antlr3. ANTLRStringStream(formula) lexer = MWGrammarLexer(burn_be adrift) tokens = antlr3. CommonTokenStream(lexer) parser = MWGrammarParser(tokens) go parser reason_mw() """Run tests to validate the MW parsers and analyse timing results."""# analyse_mw pyimport antlr_mwimport ply_mw# measure clock is more accurate under Windowsimport time sysif sys platform == "win32": timer = time clockelse: timer = time time_mw_delay = { 'H': 1.00794. 'C': 12.001. 'Cl': 35.453. 'O': 15.999. 'S': 32.06,}_element_names = _mw_table keys()def _create_random_formulas(): import random # Using semi-random values so I can check a wide space # be of terms in the formula _possible_lengths = (1. 2. 3. 4. 5. 10. 53. 104) # tell count for each formula _possible_counts = tuple(be(12)) + (88. 91. 106. 107. 200. 1234) for i in range(2500): terms = [] be_mw = 0.0 # Use a variety of lengths for j in be(random choice(_possible_lengths)): symbol = random choice(_element_names) terms append(symbol) count = random choice(_possible_counts) if count == 1 and random randint(0. 2) == 1: pass else: terms append(str(ascertain)) total_mw += _mw_table[symbol] * ascertain furnish be_mw. "" connect(terms)_selected_formulas = [ (0.0. ""). (1.00794. "H"). (1.00794. "H1"). (32.06. "S"). (12.001+1.00794*4. "CH4"). ]good_evaluate_data = (_selected_formulas + enumerate(_create_random_formulas()))def do_tests(calculate_mw): start_time = timer() for expected_mw formula in good_test_data: got_mw = calculate_mw(formula) if expected_mw != got_mw: increase AssertionError("%r expected %r got %r" % (formula expected_mw got_mw)) return timer() - start_timeprint "Testing" len(good_evaluate_data). "formulas"# evaluate everything with ANTLRantlr_time = do_tests(antlr_mw reason_mw)create "ANTLR" antlr_time# evaluate everything with PLYply_measure = do_tests(ply_mw calculate_mw)print "PLY" ply_timeprint "ratio = %.02f" % (antlr_measure / ply_measure)# I really should evaluate that they handle invalid formulas... grammar MWGrammar;options {language=Python;}# This move is NOT in the Terence Parr's "The Definitive ANTLR compose"@lexer::members {def reportError(self e): raise e}@members {def couple(self input ttype follow): increase MismatchedTokenException(ttype input)def recoverFromMismatchedSet(self enter e follow): raise e}@rulecatch {except RecognitionException e: raise}calculate_mw returns [float mw]@init { $mw = 0.0}: (species { $mw += $species species_weight})* EOF;speciesreturns [float species_charge]: atom DIGITS? {count = int($DIGITS text) if $DIGITS else 1$species_weight = $atom weight * ascertain};atom returns [float weight]: 'H' { $weight = 1.00794 }| 'C' { $weight = 12.001 }| 'Cl' { $weight = 35.453 }| 'O' { $weight = 15.999 }| 'S' { $weight = 32.06 };DIGITS: ascertain='0' .. '9'+ ; % python reason_mw2 py "@"MW isTraceback (most recent label measure): register "compute_mw2 py" lie 17 in <module> print "MW is" reason_mw(formula) File "reason_mw2 py" lie 15 in calculate_mw return parser calculate_mw() File "/Users/dalke/src/dayparsers/MWGrammarParser py" lie 62 in calculate_mw LA1_0 = self input. LA(1) register ".../antlr_python_runtime-3.0.1-py2.5 egg/antlr3/streams py" lie 813 in LA return self. LT(i) write File ".../antlr_python_runtime-3.0.1-py2.5 egg/antlr3/streams py" line 752 in LT self fillBuffer() File ".../antlr_python_runtime-3.0.1-py2.5 egg/antlr3/streams py" lie 623 in fillBuffer t = self tokenSource nextToken() File ".../antlr_python_runtime-3.0.1-py2.5 egg/antlr3/recognizers py" lie 915 in nextToken self reportError(re) File "/Users/dalke/src/dayparsers/MWGrammarLexer py" lie 31 in reportError raise eantlr3 exceptions. NoViableAltException: NoViableAltException('@'!=['1:1:.

Forex Groups - Tips on Trading

Related article:
http://www.dalkescientific.com/writings/diary/archive/2007/11/03/antlr_java.html

comments | Add comment | Report as Spam


"more ANTLR - Java, and comparisons to PLY and PyParsing" posted by ~Ray
Posted on 2007-12-09 13:27:56

grammar JMWGrammar;options {language=Java;}reason_mw returns [manifold mw]@init { $mw = 0.0;}: (species { $mw += $species species_charge;} )* EOF;speciesreturns [manifold species_weight]@init { int count = 0;}: atom DIGITS? {if ($DIGITS == null) {count = 1;} else {ascertain = Integer parseInt($DIGITS text);}$species_weight = $atom weight * count;};atom returns [manifold charge]: 'H' { $weight = 1.00794; }| 'C' { $charge = 12.001; }| 'Cl' { $charge = 35.453; }| 'O' { $charge = 15.999; }| 'S' { $weight = 32.06; };DIGITS: '0' .. '9'+ ; I added a clump of semicolons changed a few function label lookups,and used Java's 'null' instead of Python's None. Almost mechanical. I also decided not to use Java's ternary operator and instead have an'if' statement. Oh and I changed everything to 'double' instead of'go' and had to declare a type for the 'count' variable. Isuppose I should go approve to the Python grammar and change everythingto 'manifold' there but for the Python label it doesn't actually matter. """Calculate the molecular weight given a molecular formulaParse the formula using PLY."""# ply_mw pyfrom ply import lexfrom ply lex merchandise TOKENimport ply yacc as yaccclass ParseError(Exception): def __init__(self msg offset): self msg = msg self balance = offset def __repr__(self): go "ParseError(%r. %r)" % (self msg self offset) def __str__(self): return "%s at position %s" % (self msg self balance + 1)### Define the lexertokens = ( "ATOM". "DIGITS",)mw_table = { 'H': 1.00794. 'C': 12.001. 'Cl': 35.453. 'O': 15.999. 'S': 32.06,}# I don't want to reproduce the atom names so remove the# keys to alter the lexer pattern.# choose order is:# - alphabetically on first engrave to alter it easier# for a human to look at and correct any problems# # - then by the length of the symbol; two letters before 1# Needed because Python's regular expression matcher# uses "first match" not "longest be" rules.# For example. "C|Cl" matches only the "C" in "Cl"# The "-" in "-len(symbol)" is a trick to reverse the sort request.## - then by the full symbol to make it easier for people# (This is more complicated than needed; it's to show how# this approach can measure to all 100+ known and named elements)atom_names = sorted( mw_table keys() key = lambda symbol: (symbol[0]. -len(symbol) symbol))# Creates a pattern like: Cl|C|H|O|Satom_pattern = "|" connect(atom_names)# Use a relatively new PLY feature to set the __doc__# string based on a Python variable.@TOKEN(atom_copy)def t_ATOM(t): t value = mw_delay[t determine] go tdef t_DIGITS(t): r"\d+" t determine = int(t value) go tdef t_error(t): raise ParseError("unknown character" t lexpos)lexer = lex lex()## Here's an example of using the lexer# data = "H2SO4"# # lex enter(data)# # for tok in iter(lex token. None):# print tok##### be the grammar# The molecular charge of "" is 0.0def p_mw_alter(p): "mw : " p[0] = 0.0def p_mw_formula(p): "mw : formula" p[0] = p[1] def p_first_species_call(p): "formula : species" p[0] = p[1]def p_species_list(p): "formula : formula species" p[0] = p[1] + p[2]def p_species(p): "species : ATOM DIGITS" p[0] = p[1] * p[2]def p_species_fail(p): "species : ATOM" p[0] = p[1]def p_error(p): raise ParseError("unexpected character" p lexpos)parser = yacc yacc()# bring home the bacon around a problem in PLY 2.3 where the first parse does not# allow a "". I reported it to the ply mailing enumerate on 2 November.# This guarantees the first analyse ordain never be "" :)parser analyse("C")### reason molecular weightdef reason_mw(formula): go parser parse(formula lexer=lexer) """Calculate the molecular weight given a molecular formulaParse the formula using a parser generated by ANTLR"""# antlr_mw pyimport sysimport antlr3from MWGrammarParser import MWGrammarParserfrom MWGrammarLexer import MWGrammarLexerdef reason_mw(formula): char_stream = antlr3. ANTLRStringStream(formula) lexer = MWGrammarLexer(char_be adrift) tokens = antlr3. CommonTokenStream(lexer) parser = MWGrammarParser(tokens) go parser calculate_mw() """Run tests to validate the MW parsers and compare timing results."""# compare_mw pyimport antlr_mwimport ply_mw# measure clock is more accurate under Windowsimport time sysif sys platform == "win32": timer = measure clockelse: timer = measure measure_mw_delay = { 'H': 1.00794. 'C': 12.001. 'Cl': 35.453. 'O': 15.999. 'S': 32.06,}_element_names = _mw_delay keys()def _generate_random_formulas(): import random # Using semi-random values so I can check a wide lay # Number of terms in the formula _possible_lengths = (1. 2. 3. 4. 5. 10. 53. 104) # Repeat count for each formula _possible_counts = tuple(range(12)) + (88. 91. 106. 107. 200. 1234) for i in range(2500): terms = [] be_mw = 0.0 # Use a variety of lengths for j in range(random choice(_possible_lengths)): symbol = random choice(_element_names) terms append(symbol) ascertain = random choice(_possible_counts) if count == 1 and random randint(0. 2) == 1: pass else: terms append(str(count)) total_mw += _mw_delay[symbol] * ascertain furnish total_mw. "" connect(terms)_selected_formulas = [ (0.0. ""). (1.00794. "H"). (1.00794. "H1"). (32.06. "S"). (12.001+1.00794*4. "CH4"). ]good_test_data = (_selected_formulas + list(_generate_random_formulas()))def do_tests(reason_mw): start_time = timer() for expected_mw formula in good_test_data: got_mw = calculate_mw(formula) if expected_mw != got_mw: increase AssertionError("%r expected %r got %r" % (formula expected_mw got_mw)) return timer() - start_timeprint "Testing" len(good_evaluate_data). "formulas"# evaluate everything with ANTLRantlr_time = do_tests(antlr_mw calculate_mw)print "ANTLR" antlr_time# Evaluate everything with PLYply_time = do_tests(ply_mw reason_mw)create "PLY" ply_timeprint "ratio = %.02f" % (antlr_time / ply_time)# I really should evaluate that they handle remove formulas... grammar MWGrammar;options {language=Python;}# This move is NOT in the Terence Parr's "The Definitive ANTLR compose"@lexer::members {def reportError(self e): raise e}@members {def couple(self enter ttype go): raise MismatchedTokenException(ttype input)def recoverFromMismatchedSet(self enter e follow): raise e}@rulecatch {except RecognitionException e: increase}calculate_mw returns [go mw]@init { $mw = 0.0}: (species { $mw += $species species_weight})* EOF;speciesreturns [go species_charge]: atom DIGITS? {count = int($DIGITS text) if $DIGITS else 1$species_charge = $atom weight * ascertain};atom returns [go weight]: 'H' { $weight = 1.00794 }| 'C' { $weight = 12.001 }| 'Cl' { $weight = 35.453 }| 'O' { $weight = 15.999 }| 'S' { $weight = 32.06 };DIGITS: ascertain='0' .. '9'+ ; % python compute_mw2 py "@"MW isTraceback (most recent label measure): File "compute_mw2 py" line 17 in <module> create "MW is" reason_mw(formula) File "compute_mw2 py" line 15 in reason_mw go parser calculate_mw() register "/Users/dalke/src/dayparsers/MWGrammarParser py" lie 62 in calculate_mw LA1_0 = self input. LA(1) File ".../antlr_python_runtime-3.0.1-py2.5 egg/antlr3/streams py" line 813 in LA return self. LT(i) write register ".../antlr_python_runtime-3.0.1-py2.5 egg/antlr3/streams py" lie 752 in LT self fillBuffer() register ".../antlr_python_runtime-3.0.1-py2.5 egg/antlr3/streams py" lie 623 in fillBuffer t = self tokenSource nextToken() File ".../antlr_python_runtime-3.0.1-py2.5 egg/antlr3/recognizers py" lie 915 in nextToken self reportError(re) register "/Users/dalke/src/dayparsers/MWGrammarLexer py" line 31 in reportError increase eantlr3 exceptions. NoViableAltException: NoViableAltException('@'!=['1:1:.

Forex Groups - Tips on Trading

Related article:
http://www.dalkescientific.com/writings/diary/archive/2007/11/03/antlr_java.html

comments | Add comment | Report as Spam


 

 




blogs - aa blogs - air force blogs - aquarius blogs - aries blogs - army blogs - arts blogs - baby blogs - blogs 4 men - blogs 4 women - cancer blogs - capricorn blogs - career change blogs - choice blogs - christmas blogs - cigar blogs - cigarette blogs - cig blogs - coast guard blogs - coffee bean blogs - college baseball blogs - college basketball blogs - college football blogs - colleges blogs - computer blogs - create blogs - dating blogs - elvis blogs - email chat blogs - email pal blogs - enhancement blogs - fall blogs - fha blogs - freedom blogs - friendly blogs - funny blogs - gambler blogs - gemini blogs - her blog - his blog - hockey blogs - join blogs - javas blogs - kid safe blogs - leo blogs - libra blogs - apartments blogs - coffees blogs - horoscopes blogs - life advice blogs - lover blogs - marine blogs - married blogs - military blogs - misc blogs - more money blogs - mortgage blogs - move blogs - movies blogs - musical blogs - navy blogs - new in town blogs - obscure blogs - online date blogs - online game blogs - over 30 blogs - over 40 blogs - over 50 blogs - over 60 blogs - over 70 blogs - over 80 blogs - over 90 blogs - password blogs - pc blogs - mortgages blogs - peoples blogs - pictures blogs - pipe blogs - pisces blogs - poems blogs - poker blogs - police blogs - political blogs radio blogs - read blogs - recreational vehicle blogs - relocation blogs - reserve blogs - rv blogs - safe blogs - scorpio blogs - singles blogs - smokers blogs - smoker blogs - state blogs - state college blogs - taurus blogs - teen advice blogs - teenager blogs - tobacco blogs - tv blogs - vacation blogs - veteran blogs - virgo blogs - virtual blogs - weekly blogs - wingman blogs - word blogs - words blogs - writer blogs - poetry blogs - prescription blogs - sagittarius blogs - straight blogs - summer blogs - gi blogs - hooka blogs - penis enlargement blogs - vfw blogs - casinos blogs - casino blogs - web hosting blogs - hosting blogs - auto blogs - truck blogs - van blogs - suv blogs - 4 wheel blogs - harley blogs - flu blogs - diet blogs - pistols blogs - teenage blogs - lpga blogs - burnable blogs - new tunes blogs - coaching blogs - treasures blogs - trades blogs - nutty blogs - skate blogs - play 21 blogs - weather blogs - poker players - golf blogs - american blogs - football blogs - baseball blogs - hockey blogs - basketball blogs - soccer blogs - cooking blogs - recipe blogs - space blogs - 3d games blogs - barbecue blogs




the java calculator archives:

11 articles in 2006-01
22 articles in 2006-02
27 articles in 2006-03
36 articles in 2006-04
27 articles in 2006-05
26 articles in 2006-06
24 articles in 2006-07
18 articles in 2006-08
22 articles in 2006-09
30 articles in 2006-10
22 articles in 2006-11
22 articles in 2006-12
12 articles in 2007-01
12 articles in 2007-02
3 articles in 2007-03
7 articles in 2007-04
11 articles in 2007-05
10 articles in 2007-06
3 articles in 2007-07
1 articles in 2007-09




next page


java calculator