JavaCC Ambiguities: How do I tell the parser to chose a certain match from the the list of "longer matches"? - ambiguity

For some input, the parser presents a "Possible kinds of longer matches : { <EXPRESSION>, <TEXT> }", but for some odd reason it chooses the wrong one.
This is the source:
SKIP :
{
" "
| "\r"
| "\t"
| "\n"
}
TOKEN :
{
< DOT : "." >
| < LBRACE : "{" >
| < RBRACE : "}" >
| < LBRACKET: "[" >
| < RBRACKET: "]" >
| < #LETTER : [ "a"-"z" ] >
| < #DIGIT : [ "0"-"9" ] >
| < #IDENTIFIER: < LETTER > (< LETTER >)* >
| < EXPRESSION : (< IDENTIFIER> < DOT > < IDENTIFIER> < DOT > < IDENTIFIER> ((< DOT > < IDENTIFIER> )* | < LBRACKET > (< DIGIT>)* < RBRACKET >)*)*>
| < TEXT : (( < DOT >)* ( < LETTER > )+ (< DOT >)*)* >
}
void q0() :
{Token token = null;}
{
(
< LBRACE > expression() < RBRACE >
| ( token = < TEXT >
{
getTextTokens().add( token.image );
}
)
)* < EOF >
}
void expression() :
{Token token = null;}
{
< EXPRESSION >
}
If we try to parse "a.bc.d" using this grammar it would say " FOUND A <EXPRESSION> MATCH (a.bc.d) "
My question is why did it choose to parse the input as an <EXPRESSION> instead of <TEXT>?
Also, how can I force the parser to choose the right path? I have tried countless LOOKAHEAD scenarios with no success.
The right path is for instance <TEXT> when using "a.bc.d" as input, and <EXPRESSION> for "{a.bc.d}".
Thanks in advance.

From the JavaCC FAQ:
If more than one regular expression describes the longest possible
prefix, then the regular expression that comes first in the .jj file
is used.
So a preference can be established by ordering ambiguous definitions accordingly.

If expressions only appear within { braces }, only expressions (and white space) appear in braces, and braces are only used to delimit expressions, then you can do something like the following. See question 3.11 in the faq, if you are not familiar with lexical states.
// The following abbreviations hold in any state.
TOKEN : {
< #LETTER : [ "a"-"z" ] >
| < #DIGIT : [ "0"-"9" ] >
| < #IDENTIFIER: < LETTER > (< LETTER >)* >
}
// Skip white space in either state
<DEFAULT,INBRACES> SKIP : { " " | "\r" | "\t" | "\n" }
// The following are recognized in the default state.
// A left brace forces a switch to the INBRACES state.
<DEFAULT> TOKEN : {
< DOT : "." >
| < LBRACE : "{" > : INBRACES
| < LBRACKET: "[" >
| < RBRACKET: "]" >
| < TEXT : (( < DOT >)* ( < LETTER > )+ (< DOT >)*)* >
}
// A right brace forces a switch to the DEFAULT state.
<DEFAULT, INBRACES > TOKEN {
< RBRACE : "}" > : DEFAULT
}
// Expressions are only recognized in the INBRACES state.
<INBRACES> TOKEN : {
< EXPRESSION : (< IDENTIFIER> < DOT > < IDENTIFIER> < DOT > < IDENTIFIER> ((< DOT > < IDENTIFIER> )* | < LBRACKET > (< DIGIT>)* < RBRACKET >)*)*>
}
It looks a bit dodgy that DOT is defined in one state and used in another. However, I think that it works fine.

Related

How to generate arbitrary instances of a language given its concrete syntax in Rascal?

Given the concrete syntax of a language, I would like to define a function "instance" with signature str (type[&T]) that could be called with the reified type of the syntax and return a valid instance of the language.
For example, with this syntax:
lexical IntegerLiteral = [0-9]+;
start syntax Exp
= IntegerLiteral
| bracket "(" Exp ")"
> left Exp "*" Exp
> left Exp "+" Exp
;
A valid return of instance(#Exp) could be "1+(2*3)".
The reified type of a concrete syntax definition does contain information about the productions, but I am not sure if this approach is better than a dedicated data structure. Any pointers of how could I implement it?
The most natural thing is to use the Tree data-type from the ParseTree module in the standard library. It is the format that the parser produces, but you can also use it yourself. To get a string from the tree, simply print it in a string like so:
str s = "<myTree>";
A relatively complete random tree generator can be found here: https://github.com/cwi-swat/drambiguity/blob/master/src/GenerateTrees.rsc
The core of the implementation is this:
Tree randomChar(range(int min, int max)) = char(arbInt(max + 1 - min) + min);
Tree randomTree(type[Tree] gr)
= randomTree(gr.symbol, 0, toMap({ <s, p> | s <- gr.definitions, /Production p:prod(_,_,_) <- gr.definitions[s]}));
Tree randomTree(\char-class(list[CharRange] ranges), int rec, map[Symbol, set[Production]] _)
= randomChar(ranges[arbInt(size(ranges))]);
default Tree randomTree(Symbol sort, int rec, map[Symbol, set[Production]] gr) {
p = randomAlt(sort, gr[sort], rec);
return appl(p, [randomTree(delabel(s), rec + 1, gr) | s <- p.symbols]);
}
default Production randomAlt(Symbol sort, set[Production] alts, int rec) {
int w(Production p) = rec > 100 ? p.weight * p.weight : p.weight;
int total(set[Production] ps) = (1 | it + w(p) | Production p <- ps);
r = arbInt(total(alts));
count = 0;
for (Production p <- alts) {
count += w(p);
if (count >= r) {
return p;
}
}
throw "could not select a production for <sort> from <alts>";
}
Tree randomChar(range(int min, int max)) = char(arbInt(max + 1 - min) + min);
It is a simple recursive function which randomly selects productions from a reified grammar.
The trick towards termination lies in the weight of each rule. This is computed a priori, such that every rule has its own weight in the random selection. We take care to give the set of rules that lead to termination at least 50% chance of being selected (as opposed to the recursive rules) (code here: https://github.com/cwi-swat/drambiguity/blob/master/src/Termination.rsc)
Grammar terminationWeights(Grammar g) {
deps = dependencies(g.rules);
weights = ();
recProds = {p | /p:prod(s,[*_,t,*_],_) := g, <delabel(t), delabel(s)> in deps};
for (nt <- g.rules) {
prods = {p | /p:prod(_,_,_) := g.rules[nt]};
count = size(prods);
recCount = size(prods & recProds);
notRecCount = size(prods - recProds);
// at least 50% of the weight should go to non-recursive rules if they exist
notRecWeight = notRecCount != 0 ? (count * 10) / (2 * notRecCount) : 0;
recWeight = recCount != 0 ? (count * 10) / (2 * recCount) : 0;
weights += (p : p in recProds ? recWeight : notRecWeight | p <- prods);
}
return visit (g) {
case p:prod(_, _, _) => p[weight=weights[p]]
}
}
#memo
rel[Symbol,Symbol] dependencies(map[Symbol, Production] gr)
= {<delabel(from),delabel(to)> | /prod(Symbol from,[_*,Symbol to,_*],_) := gr}+;
Note that this randomTree algorithm will not terminate on grammars that are not "productive" (i.e. they have only a rule like syntax E = E;
Also it can generate trees that are filtered by disambiguation rules. So you can check this by running the parser on a generated string and check for parse errors. Also it can generated ambiguous strings.
By the way, this code was inspired by the PhD thesis of Naveneetha Vasudevan of King's College, London.

Drools: how to use abbreviated condition notation together with further conditions?

Using Drools 6.5.0.Final
I want to use abbreviated combined relation condition (e.g. Person( age > 30 && < 40 )) in combination with additional conditions.
I tried it, but the resulting rules are executed more than once.
I have a small example, where temperature deviation from a setpoint is checked and the allowed deviations depend on the setpoint. The allowed deviations are configured with Param facts, see below.
If I execute the example (fire-all-rules):
rule 1 fires two times (bug?)
rule 2 fires once as expected (without abbreviated notation).
Is my usage of the abbreviated notation wrong or is this a bug?
Example rules:
declare Param
from : float
to : float
low : float
high : float
end
declare TemperatureEvent
#role( event )
id : String
setpoint : float
t : float
end
rule "Init abbreviated conditions test"
when
then
insert(new Param(0, 10, 1, 1));
insert(new Param(10,20, 2, 3));
insert(new TemperatureEvent("id1", 13.7f,11.5f));
// rule 1 and rule 2 should fire exactly once
end
rule "rule 1"
when
$p: Param()
$x : TemperatureEvent($p.from <= setpoint && < $p.to, (t < setpoint+$p.low || t > setpoint+$p.high))
then
System.out.println("rule 1: "+$x.getId()+" "+$x.getSetpoint()+" "+$x.getT());
end
rule "rule 2"
when
$p: Param()
$x : TemperatureEvent($p.from <= setpoint, setpoint < $p.to, (t < setpoint+$p.low || t > setpoint+$p.high))
then
System.out.println("rule 2: "+$x.getId()+" "+$x.getSetpoint()+" "+$x.getT());
end
The abbreviated restriction
$p.from <= setpoint && < $p.to
is equivalent to
$p.from <= setpoint && $p.from < $p.to
What you want is
setpoint >= $p.from && < $p.to

How can I remove <math></math> multiline sections with Perl?

How can I remove multiline sections with Perl?
I have such wiki test code:
{|
|-
| colspan="2"|
: <math>
[\underbrace{\color{Red}4,2}_{4 > 2},5,1,7] \rightarrow
[2,\underbrace{\color{OliveGreen}4,5}_{4 < 5},1,7] \rightarrow
[2,4,\underbrace{\color{Red}5,1}_{5 > 1},7] \rightarrow
[2,4,1,\underbrace{\color{OliveGreen}5,7}_{5 < 7}]
</math>
|-
|
: <math>
[\underbrace{\color{OliveGreen}2,4}_{2 < 4},1,5,{\color{Blue}7}] \rightarrow
[2,\underbrace{\color{Red}4,1}_{4 > 1},5,{\color{Blue}7}] \rightarrow
[2,1,\underbrace{\color{OliveGreen}4,5}_{4 < 5},{\color{Blue}7}]
</math>
: <math>
[\underbrace{\color{Red}2,1}_{2 > 1},4,{\color{Blue}5},{\color{Blue}7}] \rightarrow
[1,\underbrace{\color{OliveGreen}2,4}_{2 < 4},{\color{Blue}5},{\color{Blue}7}]
</math>
: <math>
[\underbrace{\color{OliveGreen}1,2}_{1 < 2},{\color{Blue}4},{\color{Blue}5},{\color{Blue}7}]
</math>
|}
And I want to remove from this code all how to do it? I have done such code:
cat math-text.txt | perl -e 'while(<>) { s/<math>.+?<\/math>//gs; print $_; }'
It is not works but should since documentation explains that . will much new lines. How to do it?
The following is a python script which I use to extract all the mathematical formula from wikipedia dumps. Rather than using a multi-line regexp it scans for occurrences of <math> </math> and uses the position on the line to work out where the actual position on the line is and uses a finite state machine to find the actual equations, basically with two states determined by inEqn. It does a few other things like find the title and name space and attributes in the maths tags.
As dumps are in the order of 100MB using a line by line approach may well end up being more efficient than multi-line regexps.
import sys
import re
titleRE = re.compile('<title>(.*)</title>')
nsRE = re.compile('<ns>(.*)</ns>')
mathRE = re.compile('</?math(.*?)>')
pageEndRE = re.compile('</page>')
title =""
attr = ""
ns = -1
inEqn = 0
for line in sys.stdin:
m = titleRE.search(line)
if m :
title = m.group(1)
expression = ""
inEqn = 0
m = nsRE.search(line)
if m :
ns = m.group(1)
start = 0
pos = 0
m = mathRE.search(line,pos)
while m :
if m.group().startswith('<math'):
attr = m.group(1)
start = m.end()
pos = start
expression = ""
inEqn = 1
if m.group() == '</math>' :
end = m.start()
expression = ' '.join([expression,line[start:end]])
print title,'\t',attr,'\t',expression.lstrip().replace('<','<').replace('>','>').replace('&','&')
pos = m.end()
expression = ""
start = 0
inEqn = 0
m = mathRE.search(line,pos)
if start > 0 :
expression = line[start:].rstrip()
elif inEqn :
expression = ' '.join([expression,line.rstrip()])
Another option might be to consider an xml parser. A SAX or DOM based parser would be able to find the equations. This might be worth considering if you want to do more sophisticated analysis of the wiki-text.

Google Translate TTS API blocked

Google implemented a captcha to block people from accessing the TTS translate API https://translate.google.com/translate_tts?ie=UTF-8&q=test&tl=zh-TW. I was using it in my mobile application. Now, it is not returning anything. How do I get around the captcha?
Add the qualifier '&client=tw-ob' to the end of your query.
https://translate.google.com/translate_tts?ie=UTF-8&q=test&tl=zh-TW&client=tw-ob
This answer no longer works consistently. Your ip address will be blocked by google temporarily if you abuse this too much.
there are 3 main issues:
you must include "client" in your query string (client=t seems to work).
(in case you are trying to retrieve it using AJAX) the Referer of the HTTP request must be https://translate.google.com/
"tk" field changes for every query, and it must be populated with a matching hash:
tk = hash(q, TKK), where q is the text to be TTSed, and TKK is a var in the global scope when you load translate.google.com: (type 'window.TKK' in the console). see the hash function at the bottom of this reply (calcHash).
to summarize:
function generateGoogleTTSLink(q, tl, tkk) {
var tk = calcHash(q, tkk);
return `https://translate.google.com/translate_tts?ie=UTF-8&total=1&idx=0&client=t&ttsspeed=1&tl=${tl}&tk=${tk}&q=${q}&textlen=${q.length}`;
}
generateGoogleTTSLink('ciao', 'it', '410353.1336369826');
// see definition of "calcHash" in the bottom of this comment.
=> to get your hands on a TKK, you can open Google Translate website, then type "TKK" in developer tools' console (e.g.: "410353.1336369826").
NOTE that TKK value changes every hour, and so, old TKKs might get blocked at some point, and refreshing it may be necessary (although so far it seems like old keys can work for a LONG time).
if you DO wish to periodically refresh TKK, it can be automated pretty easily, but not if you're running your code from the browser.
you can find a full NodeJS implementation here:
https://github.com/guyrotem/google-translate-server.
it exposes a minimal TTS API (query, language), and is deployed to a free Heroku server, so you can test it online if you like.
function shiftLeftOrRightThenSumOrXor(num, opArray) {
return opArray.reduce((acc, opString) => {
var op1 = opString[1]; // '+' | '-' ~ SUM | XOR
var op2 = opString[0]; // '+' | '^' ~ SLL | SRL
var xd = opString[2]; // [0-9a-f]
var shiftAmount = hexCharAsNumber(xd);
var mask = (op1 == '+') ? acc >>> shiftAmount : acc << shiftAmount;
return (op2 == '+') ? (acc + mask & 0xffffffff) : (acc ^ mask);
}, num);
}
function hexCharAsNumber(xd) {
return (xd >= 'a') ? xd.charCodeAt(0) - 87 : Number(xd);
}
function transformQuery(query) {
for (var e = [], f = 0, g = 0; g < query.length; g++) {
var l = query.charCodeAt(g);
if (l < 128) {
e[f++] = l; // 0{l[6-0]}
} else if (l < 2048) {
e[f++] = l >> 6 | 0xC0; // 110{l[10-6]}
e[f++] = l & 0x3F | 0x80; // 10{l[5-0]}
} else if (0xD800 == (l & 0xFC00) && g + 1 < query.length && 0xDC00 == (query.charCodeAt(g + 1) & 0xFC00)) {
// that's pretty rare... (avoid ovf?)
l = (1 << 16) + ((l & 0x03FF) << 10) + (query.charCodeAt(++g) & 0x03FF);
e[f++] = l >> 18 | 0xF0; // 111100{l[9-8*]}
e[f++] = l >> 12 & 0x3F | 0x80; // 10{l[7*-2]}
e[f++] = l & 0x3F | 0x80; // 10{(l+1)[5-0]}
} else {
e[f++] = l >> 12 | 0xE0; // 1110{l[15-12]}
e[f++] = l >> 6 & 0x3F | 0x80; // 10{l[11-6]}
e[f++] = l & 0x3F | 0x80; // 10{l[5-0]}
}
}
return e;
}
function normalizeHash(encondindRound2) {
if (encondindRound2 < 0) {
encondindRound2 = (encondindRound2 & 0x7fffffff) + 0x80000000;
}
return encondindRound2 % 1E6;
}
function calcHash(query, windowTkk) {
// STEP 1: spread the the query char codes on a byte-array, 1-3 bytes per char
var bytesArray = transformQuery(query);
// STEP 2: starting with TKK index, add the array from last step one-by-one, and do 2 rounds of shift+add/xor
var d = windowTkk.split('.');
var tkkIndex = Number(d[0]) || 0;
var tkkKey = Number(d[1]) || 0;
var encondingRound1 = bytesArray.reduce((acc, current) => {
acc += current;
return shiftLeftOrRightThenSumOrXor(acc, ['+-a', '^+6'])
}, tkkIndex);
// STEP 3: apply 3 rounds of shift+add/xor and XOR with they TKK key
var encondingRound2 = shiftLeftOrRightThenSumOrXor(encondingRound1, ['+-3', '^+b', '+-f']) ^ tkkKey;
// STEP 4: Normalize to 2s complement & format
var normalizedResult = normalizeHash(encondingRound2);
return normalizedResult.toString() + "." + (normalizedResult ^ tkkIndex)
}
// usage example:
var tk = calcHash('hola', '409837.2120040981');
console.log('tk=' + tk);
// OUTPUT: 'tk=70528.480109'
You can also try this format :
pass q= urlencode format of your language
(In JavaScript you can use the encodeURI() function & PHP has the rawurlencode() function)
pass tl = language short name (suppose bangla = bn)
Now try this :
https://translate.google.com.vn/translate_tts?ie=UTF-8&q=%E0%A6%A2%E0%A6%BE%E0%A6%95%E0%A6%BE+&tl=bn&client=tw-ob
First, to avoid captcha, you have to set a proper user-agent like: "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0"
Then to not being blocked you must provide a proper token ("tk" get parameter) for each single request.
On the web you can find many different kind of scripts that try to calculate the token after a lot of reverse engineering...but every time the big G change the algorithm you're stuck again, so it's much easier to retrieve your token just observing in deep similar requests to translate page (with your text in the url).
You can read the token time by time grepping "tk=" from the output of this simple code with phantomjs:
"use strict";
var page = require('webpage').create();
var system = require('system');
var args = system.args;
if (args.length != 2) { console.log("usage: "+args[0]+" text"); phantom.exit(1); }
page.onConsoleMessage = function(msg) { console.log(msg); };
page.onResourceRequested = function(request) { console.log('Request ' + JSON.stringify(request, undefined, 4)); };
page.open("https://translate.google.it/?hl=it&tab=wT#fr/it/"+args[1], function(status) {
if (status === "success") { phantom.exit(0); }
else { phantom.exit(1); }
});
so in the end you can get your speech with something like:
wget -U "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0"
"http://translate.google.com/translate_tts?ie=UTF-8&tl=it&tk=52269.458629&q=ciao&client=t" -O ciao.mp3
(token are probably time based so this link may not work tomorrow)
I rewrote Guy Rotem's answer in Java, so if you prefer Java over Javascript, feel free to use:
public class Hasher {
public long shiftLeftOrRightThenSumOrXor(long num, String[] opArray) {
long result = num;
int current = 0;
while (current < opArray.length) {
char op1 = opArray[current].charAt(1); // '+' | '-' ~ SUM | XOR
char op2 = opArray[current].charAt(0); // '+' | '^' ~ SLL | SRL
char xd = opArray[current].charAt(2); // [0-9a-f]
assertError(op1 == '+'
|| op1 == '-', "Invalid OP: " + op1);
assertError(op2 == '+'
|| op2 == '^', "Invalid OP: " + op2);
assertError(('0' <= xd && xd <= '9')
|| ('a' <= xd && xd <='f'), "Not an 0x? value: " + xd);
int shiftAmount = hexCharAsNumber(xd);
int mask = (op1 == '+') ? ((int) result) >>> shiftAmount : ((int) result) << shiftAmount;
long subresult = (op2 == '+') ? (((int) result) + ((int) mask) & 0xffffffff)
: (((int) result) ^ mask);
result = subresult;
current++;
}
return result;
}
public void assertError(boolean cond, String e) {
if (!cond) {
System.err.println();
}
}
public int hexCharAsNumber(char xd) {
return (xd >= 'a') ? xd - 87 : Character.getNumericValue(xd);
}
public int[] transformQuery(String query) {
int[] e = new int[1000];
int resultSize = 1000;
for (int f = 0, g = 0; g < query.length(); g++) {
int l = query.charAt(g);
if (l < 128) {
e[f++] = l; // 0{l[6-0]}
} else if (l < 2048) {
e[f++] = l >> 6 | 0xC0; // 110{l[10-6]}
e[f++] = l & 0x3F | 0x80; // 10{l[5-0]}
} else if (0xD800 == (l & 0xFC00) &&
g + 1 < query.length() && 0xDC00 == (query.charAt(g + 1) & 0xFC00)) {
// that's pretty rare... (avoid ovf?)
l = (1 << 16) + ((l & 0x03FF) << 10) + (query.charAt(++g) & 0x03FF);
e[f++] = l >> 18 | 0xF0; // 111100{l[9-8*]}
e[f++] = l >> 12 & 0x3F | 0x80; // 10{l[7*-2]}
e[f++] = l & 0x3F | 0x80; // 10{(l+1)[5-0]}
} else {
e[f++] = l >> 12 | 0xE0; // 1110{l[15-12]}
e[f++] = l >> 6 & 0x3F | 0x80; // 10{l[11-6]}
e[f++] = l & 0x3F | 0x80; // 10{l[5-0]}
}
resultSize = f;
}
return Arrays.copyOf(e, resultSize);
}
public long normalizeHash(long encondindRound2) {
if (encondindRound2 < 0) {
encondindRound2 = (encondindRound2 & 0x7fffffff) + 0x80000000L;
}
return (encondindRound2) % 1_000_000;
}
/*
/ EXAMPLE:
/
/ INPUT: query: 'hola', windowTkk: '409837.2120040981'
/ OUTPUT: '70528.480109'
/
*/
public String calcHash(String query, String windowTkk) {
// STEP 1: spread the the query char codes on a byte-array, 1-3 bytes per char
int[] bytesArray = transformQuery(query);
// STEP 2: starting with TKK index,
// add the array from last step one-by-one, and do 2 rounds of shift+add/xor
String[] d = windowTkk.split("\\.");
int tkkIndex = 0;
try {
tkkIndex = Integer.valueOf(d[0]);
}
catch (Exception e) {
e.printStackTrace();
}
long tkkKey = 0;
try {
tkkKey = Long.valueOf(d[1]);
}
catch (Exception e) {
e.printStackTrace();
}
int current = 0;
long result = tkkIndex;
while (current < bytesArray.length) {
result += bytesArray[current];
long subresult = shiftLeftOrRightThenSumOrXor(result,
new String[] {"+-a", "^+6"});
result = subresult;
current++;
}
long encondingRound1 = result;
//System.out.println("encodingRound1: " + encondingRound1);
// STEP 3: apply 3 rounds of shift+add/xor and XOR with they TKK key
long encondingRound2 = ((int) shiftLeftOrRightThenSumOrXor(encondingRound1,
new String[] {"+-3", "^+b", "+-f"})) ^ ((int) tkkKey);
//System.out.println("encodingRound2: " + encondingRound2);
// STEP 4: Normalize to 2s complement & format
long normalizedResult = normalizeHash(encondingRound2);
//System.out.println("normalizedResult: " + normalizedResult);
return String.valueOf(normalizedResult) + "."
+ (((int) normalizedResult) ^ (tkkIndex));
}
}

Button should set the text in the webpage. What to do?

I am having problem in using button with function. I know only about java application and I am trying to learn HTML and JavaScript. I want the button to set the text present in conditional statement on to the webpage and conditions are based on select box.
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>P-Block Chemical Reactions</TITLE>
</HEAD>
<BODY>
<CENTER><FONT FACE="TIMES NEW ROMAN" COLOR="GREEN" size="50"><b><u>P-Block Chemical Reactions</u></b></font>
<br><br><br><h2>Structure of P-Block</h2><br>
<img src="http://2.bp.blogspot.com/-HNGbTyDrWso/UAGMqI2uY6I/AAAAAAAAAC0/mSWX5ZivvDk/s1600/Use%252Bnowwwww-723799.jpg">
<br></center>
<br>
<form>
<select id="Groups" name="Groups" >
<option value="1">Group 13</option>
<option value="2">Group 14</option>
<option value="3">Group 15</option>
<option value="4">Group 16</option>
<option value="5">Group 17</option>
<option value="6">Group 18</option></select>
<button onClick="gr();">See</button></form>
<script type="text/javascript">
function gr()
{
var s = document.getElementById('Groups');
var g = s.options[s.selectedIndex].value;
if (g === 1)
{
document.write("<b><h3>Chemical Reactions for GROUP 13 :</h3></b><br>
< ul type = "disc" >
< li > Reaction with O < sub > 2 < /sub> <br>
Boron is unreactive in crystalline form.Aluminium forms a very thin oxide layer on the surface which protects the metal from further attack. < br > < br >
2E(s) + 3O < sub > 2 < /sub>(g) → 2E<sub>2</sub > O < sub > 3 < /sub>(s)
(E = element) < br > < br >
< li > Reaction with N < sub > 2 < /sub><br>
With dinitrogen at high temperature these elements form nitrides. < br > < br >
2E(s) + N < sub > 2 < /sub>(g) → 2EN(s)
(E = element) < br > < br >
< li > Reaction with acids and alkalies < br >
Boron does not react with acids and alkalies even at moderate temperature, but aluminium dissolves in mineral acids and aqueous alkalies and thus shows amphoteric character. < br > Aluminium dissolves in dilute HCl and liberates dihydrogen. < br > < br >
2Al(s) + 6HCl(aq) → 2Al < sup > 3 + < /sup>(aq) + 6Cl<sup>-</sup > (aq) < br > < br >
However, concentrated nitric acid renders aluminium passive by forming a protective oxide layer on the surface. < br > < br >
Aluminium also reacts with aqueous alkali and liberates dihydrogen. < br > < br >
2Al(s) + 2NaOH(aq) + 6H < sub > 2 < /sub>O(l) → 2Na<sup>+</sup > [Al(OH) < sub > 4 < /sub>]<sup>-</sup > (aq) + 3H < sub > 2 < /sub>(g) <br><br>
< li > Reaction with halogens < br >
These elements react with halogens to form trihalides (except TlI < sub > 3 < /sub>).<br><br>
2E(s) + 3X < sub > 2 < /sub>(g) → 2EX<sub>3</sub > (s) & nbsp; & nbsp; & nbsp; & nbsp; (X = F, Cl, Br, I)
< /ul>");
}
else if (item === 2)
{
document.write("<b><h3>Chemical Reactions for GROUP 14 :</h3></b><br>
< ul type = "disc" >
< li > Reaction with O < sub > 2 < /sub> <br>
All members when heated in oxygen form oxides.There are mainly two types of oxides, i.e., monoxide and dioxide of formula MO and MO < sub > 2 < /sub> respectively. SiO only exists at high temperature. Oxides in higher Oxidation states of elements are generally more acidic than those in lower oxidation states.<br><br> The dioxides : CO<sub>2</sub > , SiO < sub > 2 < /sub> and GeO<sub>2</sub > are acidic, whereas SnO < sub > 2 < /sub> and PbO<sub>2</sub > are amphoteric in nature.Among monoxides, CO is neutral, GeO is distinctly acidic whereas SnO and PbO are amphoteric. < br > < br >
< li > Reaction with water < br >
Carbon, silicon and germanium are not affected by water.Tin decomposes steam to form dioxide and dihydrogen gas. < br > < br >
Sn + 2H < sub > 2 < /sub>O → SnO<sub>2</sub > + 2H < sub > 2 < /sub> <br><br>
Lead is unaffected by water, probably because of a protective oxide film formation. < br > < br >
< li > Reaction with halogen < br >
These elements can form halides of formula MX < sub > 2 < /sub> and MX<sub>4</sub > (where X = F, Cl, Br, I).Except carbon, all other members react directly with halogen under suitable condition to make halides.Most of the MX < sub > 4 < /sub> are covalent in nature. The central metal atom in these halides undergoes sp<sup>3</sup > hybridisation and the molecule is tetrahedral in shape.Exceptions are SnF < sub > 4 < /sub> and PbF<sub>4</sub > , which are ionic in nature. < br > PbI < sub > 4 < /sub> does not exist because Pb-I bond initially formed during the reaction does not release enough energy to unpair 6s<sub>2</sub > electrons and excite one of them to higher orbital to have four unpaired electrons around lead atom.Heavier members Ge to Pb are able to make halides of formula MX < sub > 2 < /sub>. Stability of dihalides increases down the group. Considering the thermal and chemical stability, GeX<sub>4</sub > is more stable than GeX < sub > 2 < /sub>, whereas PbX<sub>2</sub > is more than PbX < sub > 4 < /sub>. Except CCl<sub>4</sub > , other tetrachlorides are easily hydrolysed by water because the central atom can accomodate the lone pair of electrons from oxygen atom of water in d orbital.
< /ul><br><br>");
}
else if (item === 3)
{
document.write("<b><h3>Chemical Reactions for GROUP 15 :</h3></b><br>
< ul type = "disc" >
< li > Reaction with Hydrogen < br >
All the elements of Group 15 form hydrides of the type EH < sub > 3 < /sub> where E = N, P, As, Sb or Bi.<br> The stability of hidrides decreases from NH<sub>3</sub > to BiH < sub > 3 < /sub> which can be observed from their bond dissociation enthalpy. Consequently,the reducing character of the hydrides increases. Ammonia is only a mild reducing agent while BiH<sub>3</sub > is the strongest reducing agent amongst all the hydrides.Basicity also decreases in the order NH < sub > 3 < /sub> > PH<sub>3</sub > & gt; AsH < sub > 3 < /sub> > SbH<sub>3</sub > & ge; BiH < sub > 3 < /sub>.<br><br>
< li > Reaction with Oxygen < br >
All these elements form two types of oxides: E < sub > 2 < /sub>O<sub>3</sub > and E < sub > 2 < /sub>O<sub>5</sub > .The oxide in the higher oxidation state of the element is more acidic than that of lower oxidation state.Their acidic character decreases down the group.The oxides of the type E < sub > 2 < /sub>O<sub>3</sub > of nitrogen and phosphorus are purely acidic, that of arsenic and antimony amphoteric and those of bismuth is predominantaly basic. < br > < br >
< li > Reaction with Halogen < br >
These elements react to form two series of halides: EX < sub > 3 < /sub> and EX<sub>5</sub > .Nitrogen does not form pentahalide due to non - availability of the d - orbitals in its valence shell.Pentahalides are more covalent than trihalides.All the trihalides of these elements except those of nitrogen are stable.In case of nitrogen, only NF < sub > 3 < /sub> is known to be stable. Trihalides except BiF<sub>3</sub > are predominantly covalent in nature. < br > < br >
< li > Reaction with Metal < br >
All these elements react with metals to form their binary compounds exhibiting - 3 oxidation state, such as, Ca < sub > 3 < /sub>N<sub>2</sub > (Calcium nitride), Ca < sub > 3 < /sub>P<sub>2</sub > (Calcium phosphide), Na < sub > 3 < /sub>As<sub>2</sub > (Sodium arsenide), Zn < sub > 3 < /sub>Sb<sub>2</sub > (Zinc antimonide) and Mg < sub > 3 < /sub>Bi<sub>2</sub > (Magnesium bismuthide). < br > < br >
< /ul>");
}
else if (item === 4)
{
document.write("<b><h3>Chemical Reactions for GROUP 16 :</h3></b><br>
< ul type = "disc" >
< li > Reaction with Hydrogen < br >
All the elements of Group 16 form hydrides of the type H < sub > 2 < /sub>E (E = S, Se, Te, Po). Their acidic character increases from H<sub>2</sub > O to H < sub > 2 < /sub>Te. The increse in acidic character can be explained in terms of decrease in bond (H-E) dissociation enthalpy down the group. Owing to the decrease in bond (H-E) dissociation enthalpy down the group, the thermal stability of hydrides also decreases from H<sub>2</sub > O to H < sub > 2 < /sub>Po. All the hydrides except water possess reducing property and this character increases from H<sub>2</sub > S to H < sub > 2 < /sub>Te.<br><br>
< li > Reaction with Oxygen < br >
All these elements form oxides of the EO < sub > 2 < /sub> and EO<sub>3</sub > types where E = S, Se, Te or Po.Ozone (O < sub > 3 < /sub>) and sulphur dioxide (SO<sub>2</sub > ) are gases while selenium dioxide (SeO < sub > 2 < /sub>) is solid. Reducing property of dioxide decreases from SO<sub>2</sub > to TeO < sub > 2 < /sub>. SO<sub>2</sub > is reducing while TeO < sub > 2 < /sub> is an oxidising agent. Besides EO<sub>2</sub > type, sulphur, selenium and tellurium also form EO < sub > 3 < /sub> type oxides (SO<sub>3</sub > , SeO < sub > 3 < /sub>, TeO<sub>3</sub > ).Both types of oxides are acidic in nature. < br > < br >
< li > Reaction with Halogen < br >
Elements of Group 16 form a large number of halides of the type, EX < sub > 6 < /sub>, EX<sub>4</sub > and EX < sub > 2 < /sub> where E is an element of the group and X is a halogen. The stability of the halides decreases in the order F<sup>-</sup > & gt; Cl < sup > - < /sup> > Br<sup>-</sup > & gt; I < sup > - < /sup>. Amongst hexahalides, hexafluorides are the only stable halides. All hexafluorides are in gaseous nature. They have octahedral structure. Sulphur hexafluoride, SF<sub>6</sub > is exceptionally stable for steric reasons. < br >
Amongst tetrafluorides, SF < sub > 4 < /sub> is a gas, SeF<sub>4</sub > a liquid and TeF < sub > 4 < /sub> a solid. These fluorides have sp<sup>3</sup > d hybridisation and thus, have trigonal bipyramidal structures in which one of the equatorial positions is occupied by a lone pair of electrons.This geometry is also regarded as see - saw geometry. < br >
All elements except selenium form dichlorides and dibromides.These dihalides are formed by sp < sup > 3 < /sup> hybridisation and thus, have tetrahedral structure. The well known monohalides are dimeric in nature. Examples are S<sub>2</sub > F < sub > 2 < /sub>, S<sub>2</sub > Cl < sub > 2 < /sub>, S<sub>2</sub > Br < sub > 2 < /sub>, Se<sub>2</sub > Cl < sub > 2 < /sub> and Se<sub>2</sub > Br < sub > 2 < /sub>. These dimeric halides undergo disproportionation as given below: <br><br>
2Se < sub > 2 < /sub>Cl<sub>2</sub > → SeCl < sub > 4 < /sub> + 3Se <br><br>
< /ul>");
}
else if (item === 5)
{
document.write("<li><b><h3>Chemical Reactions for GROUP 17 :</h3></b><br>
< ul type = "disc" >
< li > Reaction with Hydrogen < br >
They all react with hydrogen to give hydrogen halides but affinity for hydrogen decreases from fluorine to iodine.They dissolve in water to form hydrohali acids.The acidic strength of these acids varies in the order: HF & lt; HCl & lt; HBr & lt; HI.The stability of these halides decreases down the group due to decrease in bond (H - X) dissociation enthalpy in the order: H - F & gt; H - Cl & gt; H - Br & gt; H - I. < br > < br >
< li > Reaction with Oxygen < br >
Halogens form many oxides with oxygen but most of them are unstable.Fluorine forms two oxides OF < sub > 2 < /sub>, O<sub>2</sub > F < sub > 2 < /sub>. However, only OF<sub>2</sub > is thermally stable at 298 K.These oxides are essentially oxygen fluorides because of the higher electronegativity of fluorine than oxygen.Both are strong fluorinating agents.O < sub > 2 < /sub>F<sub>2</sub > oxidises plutonium to PuF < sub > 6 < /sub> and the reaction is used in removing plutonium as PuF<sub>6</sub > from spent nuclear fuel. < br >
Chlorine, bromine and iodineChlorine, bromine and iodine form oxides in which the oxidation
states of these halogens range from + 1 to + 7. A combination of kinetic and thermodynamic factors lead to the generally decreasing order of stability of oxides formed by halogens, I & gt; Cl & gt; Br.The higher oxides of halogens tend to be more stable than the lower ones. < br >
Chlorine oxides, Cl < sub > 2 < /sub>O, ClO<sub>2</sub > , Cl < sub > 2 < /sub>O<sub>6</sub > and Cl < sub > 2 < /sub>O<sub>7</sub > are highly reactive oxidising agents and tend to explode.ClO < sub > 2 < /sub> is used as a bleaching agent for paper pulp and textiles and in water treatment.<br>
The bromine oxides, Br < sub > 2 < /sub>O, BrO<sub>2</sub > , BrO < sub > 3 < /sub> are the least stable halogen oxides (middle row anomally) and exist only at low temperatures. They are very powerful oxidising agents. The iodine oxides, I<sub>2</sub > O < sub > 4 < /sub>, I<sub>2</sub > O < sub > 5 < /sub>, I<sub>2</sub > O < sub > 7 < /sub> are insoluble solids and
decompose on heating.I < sub > 2 < /sub>O<sub>5</sub > is a very good oxidising agent and is
used in the estimation of carbon monoxide. < br > < br >
< li > Reaction with Metals < br >
Halogens react with metals to form metal halides.For example, bromine reacts with magnesium to give magnesium bromide. < br > < br >
Mg(s) + Br < sub > 2 < /sub>(l) → MgBr<sub>2</sub > (s) < br > < br >
The ionic character of the halides decreases in the order MF & gt;
MCl & gt; MBr & gt; MI where M is a monovalent metal.If a metal exhibits
more than one oxidation state, the halides in higher oxidation
state will be more covalent than the one in lower oxidation state.
For example, SnCl < sub > 4 < /sub>, PbCl<sub>4</sub >
, SbCl < sub > 5 < /sub> and UF<sub>6</sub >
are more covalent than SnCl < sub > 2 < /sub>
, PbCl < sub > 2 < /sub>, SbCl<sub>3</sub >
and UF < sub > 4 < /sub> respectively.<br><br>
< li > Reaction with Halogens < br >
Halogens combine amongst themselves to form number of compounds known as interhalogens of the types XX < sup > ` < /sup>, XX<sup>`</sup > < sub > 3 < /sub>, XX<sup></sup > < sub > 5 < /sub> and XX<sup>`</sup > < sub > 7 < /sub> where X is a larger size halogen and X<sup>`</sup > is a smaller size halogen. < br > For example: & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; I < sub > 2 < /sub> + Cl<sub>2</sub > & nbsp; → 2ICl < br > & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; (equimolar) < br > < br >
< /ul>");
}
}
</script>
</body>
</html>
Pastebin code
Problems I had to fix;
< br > turns in to plain text: < br > . Use this instead for ALL the HTML tags: <br> without the spaces.
if (item === 2) ???? Item was not defined, had to change it to if (g === "2") ; Please note that "2" is not the same as 2
Applied a classname group to every div; to Hide them whenever the gr() is called.
Goodluck, Jeroen
The problem is in the document.write
You can't do: document.write("")
The javascript thinks website.html is a variable
In your code:
document.write("<b><h3>Chemical Reactions for GROUP 13 :</h3></b><br>
< ul type = "disc" >
It expects "disc" to be a variable
You either can encode all of the " symbols, or put the text in divs and show them when you select an option.
Also; with document.write you can't use [enter] to prettify your code.
Your best bet is placing the text in separate divs and showing/hiding them whenever you hit the see button !
Jeroen