ActiveX C++ control WriteFile fails after 4 attempts - javascript

I have an ActiveX HTML object written in C++. The code is used to print to a bluetooth printer. I am able to make 4 successful calls to the code (shown below) and then the "WriteFile" function starts returning "0". When I shut down the browser and open it up again, it works for another 4 trys... so this sure seems like a memory leak or something, but i'm not very good with C++ unfortunately... so here i am for some help :)
BOOL RegGetValue(HKEY hRootKey, LPCTSTR lpSubKey, LPCTSTR lpValueName, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbDataLen)
{
LRESULT lResult = -1;
HKEY hKey = NULL;
lResult =RegOpenKeyEx(hRootKey, lpSubKey, 0, 0, &hKey);
int e = GetLastError();
if (lResult == ERROR_SUCCESS)
{
lResult = RegQueryValueEx(hKey, lpValueName, NULL, lpType, lpData, lpcbDataLen);
e = GetLastError();
RegCloseKey(hKey);
}
return (lResult == ERROR_SUCCESS);
}
#define MSS_PORTS_BASE _T("Software\\Microsoft\\Bluetooth\\Serial\\Ports")
bool FindBluetoothPort(TCHAR name[16])
{
HKEY hKey, hRoot;
TCHAR szPort[20] = _T(""), szPortString[20];
DWORD len, dwIndex=0;
bool bFound=false;
INT i = 0, rc;
DWORD dwNSize;
DWORD dwCSize;
TCHAR szClass[256];
TCHAR szName[MAX_PATH];
FILETIME ft;
hRoot = HKEY_LOCAL_MACHINE;
if (RegOpenKeyEx (hRoot, MSS_PORTS_BASE, 0, 0, &hKey) != ERROR_SUCCESS)
{ rc = GetLastError();
return 0;
}
dwNSize = dim(szName);
dwCSize = dim(szClass);
rc = RegEnumKeyEx (hKey, i, szName, &dwNSize, NULL, szClass, &dwCSize, &ft);
while (rc == ERROR_SUCCESS)
{
// how many children
TCHAR szCurrentKey[MAX_PATH];
wcscpy(szCurrentKey, MSS_PORTS_BASE);
wcscat(szCurrentKey, TEXT("\\"));
wcscat(szCurrentKey, szName);
wcscat(szCurrentKey, TEXT("\\"));
len = sizeof(szPort);
if(RegGetValue(hRoot, szCurrentKey, _T("Port"), NULL, (LPBYTE)szPort, &len))
{
wsprintf(szPortString, _T("%s:"), szPort);
bFound = true;
break;
}
dwNSize = dim(szName);
rc = RegEnumKeyEx(hKey, ++i, szName, &dwNSize, NULL, NULL, 0, &ft);
}
if(bFound)
_tcscpy(name, szPortString);
return bFound;
}
WriteFile(
HANDLE hFile,
__in_bcount(nNumberOfBytesToWrite) LPCVOID lpBuffer,
DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten,
LPOVERLAPPED lpOverlapped
);
void CHSMBTPrintXCtrl::PrintLabel(void)
{
//MessageBox(TEXT("Started"), TEXT("HSMBTPrintX"), MB_OK);
TCHAR g_szComPort[16];
char szout[900];
TCHAR comPort[16];
HANDLE hCom;
unsigned long bytesWritten;
int counter;
for (counter = 0; counter < 900; counter++)
szout[counter] = NULL;
AFX_MANAGE_STATE(AfxGetStaticModuleState());
if (!FindBluetoothPort(g_szComPort))
{
MessageBox(TEXT("No Port Found"), TEXT("HSMBTPrintX"), MB_OK);
return;
}
//Try at least 3 times to get a valid handle
for(counter = 0; counter < 2; ++counter)
{
hCom = CreateFile(g_szComPort,GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0);
if (hCom)
break;
}
if (hCom == NULL)
{
MessageBox(TEXT("Could not open file to print"), TEXT("HSMBTPrintX"), MB_OK);
return;
}
CT2CA date(COleDateTime::GetCurrentTime().Format(L"%m/%d/%y"));
CT2CA time(COleDateTime::GetCurrentTime().Format(L"%H:%M"));
if (m_actionParameter == "SKUTagPrint") {
CT2CA department (m_departmentParameter);
CT2CA sku (m_skuParameter);
for (counter = 0; counter < 900; counter++)
szout[counter] = NULL;
strcpy(szout, "^XA\n");
strcat(szout, "SomeTextHere");
//more strcat lines here
if(WriteFile(hCom,szout,900,&bytesWritten,NULL)==0) {
MessageBox(TEXT("Unable to write file"), TEXT("HSMBTPrintX"), MB_OK);
return;
}
}
// MessageBox(m_barcodeParameter, TEXT("HSMBTPrintX"), MB_OK);
// Create text to send to printer
FireLabelPrinted();
return;
}
// HTML
<object id="HSMBTPrintX1" width="350" height="350"
classid="CLSID:68D05400-18A6-4B39-B3FF-A17D77C1EDDF"
codebase=".\..\HSMBTPrintX.ocx#1,0,0,1" style="display:none;">
</object>
<script type="text/javascript" for="HSMBTPrintX1" event="LabelPrinted()">
alert('Label(s) successfully printed.');
</script>
// Javascript
HSMBTPrintX1.sizeParameter = document.getElementById("tdSize").innerText;
HSMBTPrintX1.actionParameter = "SKUTagPrint";
HSMBTPrintX1.PrintLabel();

You need to match a CreateFile() with a CloseHandle() or odd things can happen, see: http://msdn.microsoft.com/en-us/library/aa363858(v=vs.85).aspx

Related

How to underline charachters in InDesign with JavaScript?

I started writing this piece of code for InDesign to underline all letters except from the one with descendants, and added a dialog window to chose stroke and offset of the line.
Now I have two problems:
the program underlines all letters
the stroke and offset won't change
I'm a beginner in Javascript and it's the first time coding for InDesign. Does someone have a clue? Thank you!
// UNDERLINE ALL BUT NO DESCENDANTS
//Make certain that user interaction (display of dialogs, etc.) is turned on.
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll;
if (app.documents.length != 0){
try {
// Run script with single undo if supported
if (parseFloat(app.version) < 6) {
main();
} else {
app.doScript(main, ScriptLanguage.JAVASCRIPT, undefined, UndoModes.ENTIRE_SCRIPT, "Expand State Abbreviations");
}
// Global error reporting
} catch ( error ) {
alert( error + " (Line " + error.line + " in file " + error.fileName + ")");
}
}else{
alert("Open a document first before running this script.");
}
///MAIN FUNCTION
function main(){
if(app.selection.length != 0){
myDisplayDialog();
}
}
//INTERFACE
function myDisplayDialog(){
//declare variables
//general
var myDoc = app.activeDocument;
var mS = myDoc.selection;
// dialog
var myDialog = app.dialogs.add({name:"Underliner"});
var myLabelWidth = 70;
with(myDialog.dialogColumns.add()){
with(borderPanels.add()){
with(dialogColumns.add()){
with(dialogRows.add()){
staticTexts.add({staticLabel:"Stroke:", minWidth:myLabelWidth});
staticTexts.add({staticLabel:"Offset:", minWidth:myLabelWidth});
}
}
with(dialogRows.add()){
staticTexts.add({staticLabel:""});
var myStroke = measurementEditboxes.add({editValue:1, editUnits:MeasurementUnits.points});
var myOffset = measurementEditboxes.add({editValue: 15, editUnits:MeasurementUnits.points});
}
}
}
var myResult = myDialog.show();
if(myResult == true){
var myStroke = myStroke.editValue;
var myOffset = myOffset.editValue;
myDialog.destroy();
underline(mS,myStroke,myOffset);
}
else{
myDialog.destroy();
alert("Invalid page range.");
}
}
//REAL FUNCTION
function underline(charList,stroke, offset){
var len = charList.length;
const doNotUnderline = ['g','j','p','q','y'];
for (var i=0; i < len; i++){
try{
var myChar = charList[i];
//console.log(typeof myText);
if (includes(myChar, doNotUnderline) == false)
{
myChar.underline = true;
myChar.underlineWeight == stroke;
myChar.underlineOffset == offset;
} else {
myChar.underline = false;
}
}catch(r){
alert(r.description);
break;
}
}
}
//function to know if char is in array
function includes(elemento,array)
{
var len = array.length;
for(var i=0; i<len ;i++)
{
if(array[i]==elemento){return true;}
}
return false;
}
Try these changes in the function underline():
//REAL FUNCTION
function underline(words,stroke, offset) { // <------ here 'words' instead of 'charList'
var charList = words[0].characters; // <------ here get 'characters' of the 'words'
var len = charList.length;
const doNotUnderline = ['g','j','p','q','y'].join(); // <------- here '.join()'
for (var i=0; i < len; i++){
try{
var myChar = charList[i];
// if (includes(myChar, doNotUnderline) == false) // <----- no need
if (doNotUnderline.indexOf(myChar.contents) < 0) // <------ 'indexOf()' instead of 'includes()'
{
myChar.underline = true;
myChar.underlineWeight = stroke; // <------- here '=' instead of '=='
myChar.underlineOffset = offset; // <------- here '=' instead of '=='
} else {
myChar.underline = false;
}
}catch(r){
alert(r.description);
break;
}
}
}
Probably there can be another improvements as well. It's need additional researches. But if you change these lines it should work to a degree.
And there is one little thing that improves user experience greatly: to keep last used values in the input fields. It can be done pretty easy, let me know it you need it.
Update
Here is the way I'm using to store and restore any preferences of my scripts.
Add somewhere at the start of your script these lines:
// get preferences
var PREFS = { stroke: 1, offset: 15 }; // set default prefs
var PREFS_FILE = File(Folder.temp + '/underline_prefs.json'); // the file with preferences
if (PREFS_FILE.exists) PREFS = $.evalFile(PREFS_FILE); // get the prefs from the file
Now you can use the global values PREFS.stroke and PREFS.offset anywhere you want. In your case they go here:
with(dialogRows.add()){
staticTexts.add({staticLabel:""});
var myStroke = measurementEditboxes.add({editValue:PREFS.stroke, editUnits:MeasurementUnits.points});
var myOffset = measurementEditboxes.add({editValue:PREFS.offset, editUnits:MeasurementUnits.points});
}
This way script will get the stroke and weight from the file underline_prefs.json that will be stored in the standard temporary folder of current user.
Final step is to save the values back into the file after the script got them from the dialog window.
I'd put this piece of code here:
if (myResult == true) {
var myStroke = myStroke.editValue;
var myOffset = myOffset.editValue;
myDialog.destroy();
underline(mS, myStroke, myOffset);
// save preferences here
PREFS.stroke = myStroke;
PREFS.offset = myOffset;
PREFS_FILE.open('w');
PREFS_FILE.write(PREFS.toSource());
PREFS_FILE.close();
} else {
myDialog.destroy();
alert("Invalid page range.");
}
Voilá. Now don't need to type the values every time they differ from default ones.

How to save last searched when using search on input?

I am trying to write an algorithm that saves the recently searched keywords. The issue is that the user is not triggering the search but instead the search is being triggered every time something is typed. Currently, I am trying to save the last searched keyword and checking if the next one starts with the last one in order to discard the last one.
async _persistSearch(term) {
const serachLog = await this._getLastSearchedFile()
console.log("[SEARCH]", serachLog);
if (Object.keys(serachLog) == 0) {
serachLog.searches = [term];
serachLog.lastUpdated = Date.now()
} else if (term.startsWith(this.lastSearhed)) {
const toPersist = serachLog.searches.filter((value) => value != this.lastSearhed).push(term);
serachLog.searches = toPersist;
} else {
serachLog.searches.push(term);
}
this.lastSearhed = term;
await writeJSONFile(this.searchesFile, serachLog);
}
For example for an input [so, som, some, somet, someth,somethi, somethin, something, somethin] to be [something]
You should use Trie(Prefix Tree) to save searched keywords. Say you are only dealing with lower-case English letters, then each node can have up to 26 children nodes. For each new search keyword, call the startsWith method to check if this new keyword is any prefix of the previous keywords.
Read about this https://en.wikipedia.org/wiki/Trie if you need more explanations about why a Trie should be used in your case.
A java implementation of this data structure is as following.
class Trie {
class TrieNode{
private char c;
private Map<Character, TrieNode> map;
private boolean isLeaf;
TrieNode() {
this.map = new HashMap<>();
}
TrieNode(char c) {
this.c = c;
this.map = new HashMap<>();
}
}
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode currNode = root;
for(int i = 0; i < word.length(); i++) {
char currChar = word.charAt(i);
if(!currNode.map.containsKey(currChar)) {
TrieNode newNode = new TrieNode(currChar);
currNode.map.put(currChar, newNode);
currNode = newNode;
}
else {
currNode = currNode.map.get(currChar);
}
if(i == word.length() - 1) {
currNode.isLeaf = true;
}
}
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode currNode = root;
for(int i = 0; i < word.length(); i++) {
if(!currNode.map.containsKey(word.charAt(i))) {
return false;
}
currNode = currNode.map.get(word.charAt(i));
if( i == word.length() - 1 && !currNode.isLeaf) {
return false;
}
}
return true;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode currNode = root;
for(int i = 0; i < prefix.length(); i++) {
if(!currNode.map.containsKey(prefix.charAt(i))) {
return false;
}
currNode = currNode.map.get(prefix.charAt(i));
}
return true;
}
}

sortable.js don't work with other script condition.js and <body onload="contition()">

hi i run 2 scripts the first is
sorttable.js
/*
SortTable
version 2
7th April 2007
Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
Instructions:
Download this file
Add <script src="sorttable.js"></script> to your HTML
Add class="sortable" to any table you'd like to make sortable
Click on the headers to sort
Thanks to many, many people for contributions and suggestions.
Licenced as X11: http://www.kryogenix.org/code/browser/licence.html
This basically means: do what you want with it.
*/
var stIsIE = /*#cc_on!#*/false;
sorttable = {
init: function() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
if (!document.createElement || !document.getElementsByTagName) return;
sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
forEach(document.getElementsByTagName('table'), function(table) {
if (table.className.search(/\bsortable\b/) != -1) {
sorttable.makeSortable(table);
}
});
},
makeSortable: function(table) {
if (table.getElementsByTagName('thead').length == 0) {
// table doesn't have a tHead. Since it should have, create one and
// put the first table row in it.
the = document.createElement('thead');
the.appendChild(table.rows[0]);
table.insertBefore(the,table.firstChild);
}
// Safari doesn't support table.tHead, sigh
if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];
if (table.tHead.rows.length != 1) return; // can't cope with two header rows
// Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
// "total" rows, for example). This is B&R, since what you're supposed
// to do is put them in a tfoot. So, if there are sortbottom rows,
// for backwards compatibility, move them to tfoot (creating it if needed).
sortbottomrows = [];
for (var i=0; i<table.rows.length; i++) {
if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
sortbottomrows[sortbottomrows.length] = table.rows[i];
}
}
if (sortbottomrows) {
if (table.tFoot == null) {
// table doesn't have a tfoot. Create one.
tfo = document.createElement('tfoot');
table.appendChild(tfo);
}
for (var i=0; i<sortbottomrows.length; i++) {
tfo.appendChild(sortbottomrows[i]);
}
delete sortbottomrows;
}
// work through each column and calculate its type
headrow = table.tHead.rows[0].cells;
for (var i=0; i<headrow.length; i++) {
// manually override the type with a sorttable_type attribute
if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
if (mtch) { override = mtch[1]; }
if (mtch && typeof sorttable["sort_"+override] == 'function') {
headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
} else {
headrow[i].sorttable_sortfunction = sorttable.guessType(table,i);
}
// make it clickable to sort
headrow[i].sorttable_columnindex = i;
headrow[i].sorttable_tbody = table.tBodies[0];
dean_addEvent(headrow[i],"click", function(e) {
if (this.className.search(/\bsorttable_sorted\b/) != -1) {
// if we're already sorted by this column, just
// reverse the table, which is quicker
sorttable.reverse(this.sorttable_tbody);
this.className = this.className.replace('sorttable_sorted',
'sorttable_sorted_reverse');
this.removeChild(document.getElementById('sorttable_sortfwdind'));
sortrevind = document.createElement('span');
sortrevind.id = "sorttable_sortrevind";
sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : ' ▴';
this.appendChild(sortrevind);
return;
}
if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
// if we're already sorted by this column in reverse, just
// re-reverse the table, which is quicker
sorttable.reverse(this.sorttable_tbody);
this.className = this.className.replace('sorttable_sorted_reverse',
'sorttable_sorted');
this.removeChild(document.getElementById('sorttable_sortrevind'));
sortfwdind = document.createElement('span');
sortfwdind.id = "sorttable_sortfwdind";
sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : ' ▾';
this.appendChild(sortfwdind);
return;
}
// remove sorttable_sorted classes
theadrow = this.parentNode;
forEach(theadrow.childNodes, function(cell) {
if (cell.nodeType == 1) { // an element
cell.className = cell.className.replace('sorttable_sorted_reverse','');
cell.className = cell.className.replace('sorttable_sorted','');
}
});
sortfwdind = document.getElementById('sorttable_sortfwdind');
if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
sortrevind = document.getElementById('sorttable_sortrevind');
if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
this.className += ' sorttable_sorted';
sortfwdind = document.createElement('span');
sortfwdind.id = "sorttable_sortfwdind";
sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : ' ▾';
this.appendChild(sortfwdind);
// build an array to sort. This is a Schwartzian transform thing,
// i.e., we "decorate" each row with the actual sort key,
// sort based on the sort keys, and then put the rows back in order
// which is a lot faster because you only do getInnerText once per row
row_array = [];
col = this.sorttable_columnindex;
rows = this.sorttable_tbody.rows;
for (var j=0; j<rows.length; j++) {
row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
}
/* If you want a stable sort, uncomment the following line */
sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
//row_array.sort(this.sorttable_sortfunction);
tb = this.sorttable_tbody;
for (var j=0; j<row_array.length; j++) {
tb.appendChild(row_array[j][1]);
}
delete row_array;
});
}
}
},
guessType: function(table, column) {
// guess the type of a column based on its first non-blank row
sortfn = sorttable.sort_alpha;
for (var i=0; i<table.tBodies[0].rows.length; i++) {
text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
if (text != '') {
if (text.match(/^-?[£$€]?[\d,.]+%?$/)) {
return sorttable.sort_numeric;
}
// check for a date: dd/mm/yyyy or dd/mm/yy
// can have / or . or - as separator
// can be mm/dd as well
possdate = text.match(sorttable.DATE_RE)
if (possdate) {
// looks like a date
first = parseInt(possdate[1]);
second = parseInt(possdate[2]);
if (first > 12) {
// definitely dd/mm
return sorttable.sort_ddmm;
} else if (second > 12) {
return sorttable.sort_mmdd;
} else {
// looks like a date, but we can't tell which, so assume
// that it's dd/mm (English imperialism!) and keep looking
sortfn = sorttable.sort_ddmm;
}
}
}
}
return sortfn;
},
getInnerText: function(node) {
// gets the text we want to use for sorting for a cell.
// strips leading and trailing whitespace.
// this is *not* a generic getInnerText function; it's special to sorttable.
// for example, you can override the cell text with a customkey attribute.
// it also gets .value for <input> fields.
hasInputs = (typeof node.getElementsByTagName == 'function') &&
node.getElementsByTagName('input').length;
if (node.getAttribute("sorttable_customkey") != null) {
return node.getAttribute("sorttable_customkey");
}
else if (typeof node.textContent != 'undefined' && !hasInputs) {
return node.textContent.replace(/^\s+|\s+$/g, '');
}
else if (typeof node.innerText != 'undefined' && !hasInputs) {
return node.innerText.replace(/^\s+|\s+$/g, '');
}
else if (typeof node.text != 'undefined' && !hasInputs) {
return node.text.replace(/^\s+|\s+$/g, '');
}
else {
switch (node.nodeType) {
case 3:
if (node.nodeName.toLowerCase() == 'input') {
return node.value.replace(/^\s+|\s+$/g, '');
}
case 4:
return node.nodeValue.replace(/^\s+|\s+$/g, '');
break;
case 1:
case 11:
var innerText = '';
for (var i = 0; i < node.childNodes.length; i++) {
innerText += sorttable.getInnerText(node.childNodes[i]);
}
return innerText.replace(/^\s+|\s+$/g, '');
break;
default:
return '';
}
}
},
reverse: function(tbody) {
// reverse the rows in a tbody
newrows = [];
for (var i=0; i<tbody.rows.length; i++) {
newrows[newrows.length] = tbody.rows[i];
}
for (var i=newrows.length-1; i>=0; i--) {
tbody.appendChild(newrows[i]);
}
delete newrows;
},
/* sort functions
each sort function takes two parameters, a and b
you are comparing a[0] and b[0] */
sort_numeric: function(a,b) {
aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
if (isNaN(aa)) aa = 0;
bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
if (isNaN(bb)) bb = 0;
return aa-bb;
},
sort_alpha: function(a,b) {
if (a[0]==b[0]) return 0;
if (a[0]<b[0]) return -1;
return 1;
},
sort_ddmm: function(a,b) {
mtch = a[0].match(sorttable.DATE_RE);
y = mtch[3]; m = mtch[2]; d = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt1 = y+m+d;
mtch = b[0].match(sorttable.DATE_RE);
y = mtch[3]; m = mtch[2]; d = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt2 = y+m+d;
if (dt1==dt2) return 0;
if (dt1<dt2) return -1;
return 1;
},
sort_mmdd: function(a,b) {
mtch = a[0].match(sorttable.DATE_RE);
y = mtch[3]; d = mtch[2]; m = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt1 = y+m+d;
mtch = b[0].match(sorttable.DATE_RE);
y = mtch[3]; d = mtch[2]; m = mtch[1];
if (m.length == 1) m = '0'+m;
if (d.length == 1) d = '0'+d;
dt2 = y+m+d;
if (dt1==dt2) return 0;
if (dt1<dt2) return -1;
return 1;
},
shaker_sort: function(list, comp_func) {
// A stable sort function to allow multi-level sorting of data
// see: http://en.wikipedia.org/wiki/Cocktail_sort
// thanks to Joseph Nahmias
var b = 0;
var t = list.length - 1;
var swap = true;
while(swap) {
swap = false;
for(var i = b; i < t; ++i) {
if ( comp_func(list[i], list[i+1]) > 0 ) {
var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
swap = true;
}
} // for
t--;
if (!swap) break;
for(var i = t; i > b; --i) {
if ( comp_func(list[i], list[i-1]) < 0 ) {
var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
swap = true;
}
} // for
b++;
} // while(swap)
}
}
/* ******************************************************************
Supporting functions: bundled here to avoid depending on a library
****************************************************************** */
// Dean Edwards/Matthias Miller/John Resig
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", sorttable.init, false);
}
/* for Internet Explorer */
/*#cc_on #*/
/*#if (#_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
sorttable.init(); // call the onload handler
}
};
/*#end #*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
sorttable.init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = sorttable.init;
// written by Dean Edwards, 2005
// with input from Tino Zijdel, Matthias Miller, Diego Perini
// http://dean.edwards.name/weblog/2005/10/add-event/
function dean_addEvent(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
// assign each event handler a unique ID
if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
// create a hash table of event types for the element
if (!element.events) element.events = {};
// create a hash table of event handlers for each element/event pair
var handlers = element.events[type];
if (!handlers) {
handlers = element.events[type] = {};
// store the existing event handler (if there is one)
if (element["on" + type]) {
handlers[0] = element["on" + type];
}
}
// store the event handler in the hash table
handlers[handler.$$guid] = handler;
// assign a global event handler to do all the work
element["on" + type] = handleEvent;
}
};
// a counter used to create unique IDs
dean_addEvent.guid = 1;
function removeEvent(element, type, handler) {
if (element.removeEventListener) {
element.removeEventListener(type, handler, false);
} else {
// delete the event handler from the hash table
if (element.events && element.events[type]) {
delete element.events[type][handler.$$guid];
}
}
};
function handleEvent(event) {
var returnValue = true;
// grab the event object (IE uses a global event object)
event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
// get a reference to the hash table of event handlers
var handlers = this.events[event.type];
// execute each event handler
for (var i in handlers) {
this.$$handleEvent = handlers[i];
if (this.$$handleEvent(event) === false) {
returnValue = false;
}
}
return returnValue;
};
function fixEvent(event) {
// add W3C standard event methods
event.preventDefault = fixEvent.preventDefault;
event.stopPropagation = fixEvent.stopPropagation;
return event;
};
fixEvent.preventDefault = function() {
this.returnValue = false;
};
fixEvent.stopPropagation = function() {
this.cancelBubble = true;
}
// Dean's forEach: http://dean.edwards.name/base/forEach.js
/*
forEach, version 1.0
Copyright 2006, Dean Edwards
License: http://www.opensource.org/licenses/mit-license.php
*/
// array-like enumeration
if (!Array.forEach) { // mozilla already supports this
Array.forEach = function(array, block, context) {
for (var i = 0; i < array.length; i++) {
block.call(context, array[i], i, array);
}
};
}
// generic enumeration
Function.prototype.forEach = function(object, block, context) {
for (var key in object) {
if (typeof this.prototype[key] == "undefined") {
block.call(context, object[key], key, object);
}
}
};
// character enumeration
String.forEach = function(string, block, context) {
Array.forEach(string.split(""), function(chr, index) {
block.call(context, chr, index, string);
});
};
// globally resolve forEach enumeration
var forEach = function(object, block, context) {
if (object) {
var resolve = Object; // default
if (object instanceof Function) {
// functions have a "length" property
resolve = Function;
} else if (object.forEach instanceof Function) {
// the object implements a custom forEach method so use that
object.forEach(block, context);
return;
} else if (typeof object == "string") {
// the object is a string
resolve = String;
} else if (typeof object.length == "number") {
// the object is array-like
resolve = Array;
}
resolve.forEach(object, block, context);
}
};
and the secont script is condition.js
function contition() {
var list = new Array();
list[0] = "calmbfr^<img src='wr-el-calm.png' width='40'>";
list[1] = "---bfr^<img src='wr-el-calm.png' width='40'>";
var j, k, find, item, page, repl;
for (var i=0; i<list.length; i++) {
item = list[i].split("^");
find = item[0];
repl = item[1];
page = document.body.innerHTML;
while (page.indexOf(find) >= 0) {
var j = page.indexOf(find);
var k = find.length;
page = page.substr(0,j) + repl + page.substr(j+k);
document.body.innerHTML = page;
}
}
}
the second script run only with body onload="contition()"
if i run seerate the scripts its ok but when i run together in html and give body onload="contition()" work only the secont script and not the sortable.js
below is the html code
<?php
mysql_connect("localhost", "username", "password") or die("Error connecting to database: ".mysql_error());
/*
localhost - it's location of the mysql server, usually localhost
root - your username
third is your password
if connection fails it will stop loading the page and display an error
*/
mysql_select_db("database") or die(mysql_error());
/* database is the name of database we've created */
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="el-gr" lang="el-gr" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="contnow.css" rel="stylesheet"/>
<link href="meteogram_table.css" rel="stylesheet"/>
<script src="sorttable.js" type="text/javascript"></script>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.3.js'></script>
<script>
//<![CDATA[
function contition() {
var list = new Array();
list[0] = "calmbfr^<img src='/ajaxImages/wr-el-calm.png' width='40'>";
list[1] = "---bfr^<img src='/ajaxImages/wr-el-calm.png' width='40'>";
var j, k, find, item, page, repl;
for (var i=0; i<list.length; i++) {
item = list[i].split("^");
find = item[0];
repl = item[1];
page = document.body.innerHTML;
while (page.indexOf(find) >= 0) {
var j = page.indexOf(find);
var k = find.length;
page = page.substr(0,j) + repl + page.substr(j+k);
document.body.innerHTML = page;
}
}
}
//]]>
</script>
</head>
<body onload="contition()"
bgcolor="#CCCCCC">
<div id="menu">
<ul>
<li id="button1"><a href="view_wu_metars_GR.php" title="">
Ελλάδα</a></li>
<li id="button2"><a href="view_wu_metars_NGR.php" title="">
Βόρεια Ελ.</a></li>
<li id="button3"><a href="view_wu_metars_WGR.php" title="">
Δυτικη Ελ.</a></li>
<li id="button4"><a href="view_wu_metars_CGR.php" title="">
Κεντρική Ελ.</a></li>
<li id="button5"><a href="view_wu_metars_SGR.php" title="">
Νότια Ελ.</a></li>
<li id="button6"><a href="view_wu_metars_Islands.php" title="">
Νησιά</a></li>
<li id="button7"><a href="view_wu_metars_Airports.php" title="">
Αεροδρόμια</a></li>
<li id="button8"><a href="view_wu_metars_Balkans.php" title="">
Βαλκάνια</a></li>
</ul>
</div>
<table class='sortable' width="1000px" height="" border="1" bgcolor="#ecf9ff" bordercolor="#008080" style="font-size: 13px;">
<thead bgcolor="#66CCFF">
<tr>
<th>Καιρικές <br> συνθήκες</th>
<th>Περιοχή</th>
<th>Πόλη/ <br> περιοχή</th>
<th style width="110px">Ενημέρωση</th>
<th>Θερμοκρασία <br> (°C)</th>
<th>Υγρασία <br> (%)</th>
<th>Σημείο <br> Δρόσου <br> (°C)</th>
<th>Πίεση <br> (hpa)</th>
<th>Υετός <br> ώρας</th>
<th>Υετός <br> (mm)</th>
<th>Διεύθυνση <br> Ανέμου</th>
<th>Άνεμος <br> (Bfr)</th>
<th>Τύπος <br> Σταθμού</th>
<th><a>Υψό-<br>μετρο<br>m</a></th>
</tr>
</thead>
<tr align='center'>
<?php
$result = mysql_query('SELECT *
FROM wuMETAR_icon_LGTS
ORDER BY id DESC
LIMIT 1;') or die('Invalid query: ' . mysql_error());
//print values to screen
while ($row = mysql_fetch_assoc($result)) {
echo "
<td>---bfr</td>
";
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
<?php
$result = mysql_query('SELECT *
FROM wu_AgionOros_MoniMegistisLavras
ORDER BY id DESC
LIMIT 1;') or die('Invalid query: ' . mysql_error());
//print values to screen
while ($row = mysql_fetch_assoc($result)) {
echo "
<td><b>Άγιον όρος</b></td>
<td><b>Μονή Μεγίστης Λάυρας</b></td>
<td><b style='font-size: 10px;'>".$row['observation_time']."</b></td>
<td style='font-size: 22px; font-weight: bold;'>".$row['temp_c']."</td>
<td style='font-size: 20px; font-weight: bold;'>".$row['relative_humidity']."</td>
<td><b>".$row['dewpoint_c']."</b></td>
<td>".$row['pressure_mb']."</td>
<th>".$row['precip_1hr_metric']."</th>
<td><img width='35px' height='50px' src='/DFS/data/wu/CURRENTXML/mm/".$row['precip_today_metric'].".gif'/></td>
<td><img width='50px' height='50px' src='".$row['wind_dir'].".gif'/></td>
<td><img width='55px' height='55px' src='".$row['wind_mph'].".gif'/></td>
<td><img width='50px' height='50px' src='".$row['station_type'].".gif'/></td>
<td><b>142</b></td>
";
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
</tr>
</body>
</html>
html is bigest but 30000 characters can upload here
my question is how can run this scripts together in html page?
i found the problem is sortable.js run without body onload but the second script need body onload.
can anyone tell me how change the script code for condition.js to work without body onload?
ps: the script condition.js i need to run in the same table with sortable table and i change only the first td of every tr
please help me because the other solution is to create 600000 weather icons but with condition.js is better
thanks
i found a similar solution to work together sortable.js with script to change text to image
$(document).ready(function () {
$("td:contains('40.0clear 0')").html('<img src="/CURRENTXML/Clear.gif" height="40px" width="50px"/>');
});
$(document).ready(function () {
$("td:contains('40.0clear 1.png')").html('<img src="/CURRENTXML/rain.gif" alt="40.0clear 1.png" height="40px" width="50px"/>');
});
$(document).ready(function () {
$("td:contains('2.0clear 1.png')").html('<img src="/CURRENTXML/snow.gif" alt="40.0clear 1.png" height="40px" width="50px"/>');
});

1120: Access of undefined property (With 8 Errors)

I am a university student currently doing a project on a game on AS3
When i run my game i get 8 errors regarding "1120: Access of undefined property...." I don't know what I'm doing wrong so can anyone help me with this?
here is my code(yeah i know its long):
package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.getTimer;
public class PlatformGamess extends MovieClip {
// movement constants
static const gravity:Number=.004;
// screen constants
static const edgeDistance:Number=100;
// object arrays
private var fixedObjects:Array;
private var otherObjects:Array;
// hero and enemies
private var hero:Object;
private var enemies:Array;
// game state
private var playerObjects:Array;
private var gameScore:int;
private var gameMode:String="start";
private var playerLives:int;
private var lastTime:Number=0;
// start game
public function startPlatformGamess(){
playerObjects=new Array();
gameScore=0;
gameMode="play";
playerLives=3;
}
public function startGameLevel(){
createHero();
addEnemies();
examineLevel();
this.addEventListener(Event.ENTER_FRAME,gameLoop);
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
gameMode="play";
addScore(0);
showLives();
}
// creates the hero object and sets all properties
public function createHero() {
hero=new Object();
hero.mc=gamelevel.hero;
hero.inAir=false;
hero.direction=1;
hero.animstate="stand";
hero.walkAnimation=new Array(2)
hero.animstep=0;
hero.jump=false;
hero.moveLeft=false;
hero.moveRight=false;
hero.jumpSpeed=.8;
hero.walkSpeed=.15;
hero.width=20.0;
hero.height=40.0;
hero.startx=hero.mc.x;
hero.starty=hero.mc.y;
}
public function addEnemies() {
enemies = new Array();
var i:int=1;
while (true) {
if (gamelevel["enemy"+i]==null) break;
var enemy=new Object();
enemy.mc=gamelevel["enemy"+i];
enemy.dx=0.0;
enemy.dy=0.0;
enemy.inAir=false;
enemy.direction=1;
enemy.animstate="stand"
enemy.walkAnimation = new Array(2);
enemy.animstep = 0;
enemy.jump = false;
enemy.moveRight = true;
enemy.moveLeft = false;
enemy.jumpSpeed = 1.0;
enemy.walkSpeed = .08;
enemy.width = 30.0;
enemy.height = 30.0;
enemies.push(enemy);
i++;
}
}
public function examineLevel(){
fixedObjects=new Array();
otherObject=new Array();
for (var i:int=0;i<this.gamelevel.numChildren;i++) {
var mc=this.gamelevel.getChildAt(i);
if ((mc is Floor) || (mc is Wall)) {
var floorObjects:Object=new Object();
floorObject.mc=mc;
floorObject.leftside=mc.x;
floorObject.rightside=mc.x+mc.width;
floorObject.topside.mc.y;
floorObject.bottomside=mc.y+mc.height;
fixedObjects.push(floorObject);
} else if ((mc is Treasure) || (mc is Key) ||
(mc is Door) || (mc is Chest)) {
otherObjects.push(mc);
}
}
}
public function keyDownFunction(event:KeyboardEvent) {
if (gamemode != "play") return; // don't move until in play mode
if (event.keyCode==37){
hero.moveLeft=true;
} else if (event.keyCode==39) {
hero.moveRight==true;
} else if (event.keyCode==32){
if (!hero.inAir){
hero.jump=true;
}
}
}
public function keyUpFunction(event:KeyboardEvent) {
if (event.keyCode == 37) {
hero.moveLeft = false;
} else if (event.keyCode == 39) {
hero.moveRight = false;
}
}
public function gameLoop(event:Event) {
if (lastTime==0)lastTime=getTimer();
var timeDiff:int=getTimer()-lastTime;
lastTime+=timeDiff;
if (gameMode=="play"){
moveCharacter(hero,timeDiff);
moveEnemies(timeDiff);
checkCollisions();
scrollWithHero();
}
}
// loop through all enemies and move them
public function moveEnemies(timeDiff:int) {
for(var i:int=0;i<enemies.length;i++) {
// move
moveCharacter(enemies[i],timeDiff);
// if hit a wall, turn around
if (enemies[i].hitWallRight) {
enemies[i].moveLeft=true;
enemies[i].moveRight=false;
} else if (enemies[i].hitWallLeft) {
enemies[i].moveLeft=false;
enemies[i].moveRight=true;
}
}
}
public function moveCharacter(char:Object,timeDiff:Number) {
if (timeDiff < 1) return;
var verticalChange:Number=char.dy*timeDiff+timeDiff*gravity;
if (verticalChange>15.0) verticalChange=15.0;
char.dy+=timeDiff*gravity;
var horizontalChange=0;
var newAnimState:String="stand";
var newDirection:int=char.direction;
if (char.moveLeft){
// wa
horizontalChange = -char.walkSpeed*timeDiff;
newAnimState="walk";
newDirection=-1;
} else if (char.moveRight){
// walk right
horizontalChange = char.walkSpeed*timeDiff;
newAnimState="walk";
newDirection=1;
}
if (char.jump) {
// start jump
char.jump = false;
char.dy = -char.jumpSpeed;
verticalChange = -char.jumpSpeed;
newAnimState = "jump";
}
// assume no wall hit, and hanging in air
char.hitWallRight = false;
char.hitWallLeft = false;
char.inAir = true;
// find new vertical position
var newY:Number = char.mc.y + verticalChange;
// loop through all fixed objects to see if character has landed
for(var i:int=0;i<fixedObjects.length;i++) {
if ((char.mc.x+char.width/2 > fixedObjects[i].leftside) && (char.mc.x-char.width/2 < fixedObjects[i].rightside)) {
if ((char.mc.y <= fixedObjects[i].topside) && (newY > fixedObjects[i].topside)) {
newY = fixedObjects[i].topside;
char.dy = 0;
char.inAir = false;
break;
}
}
}
// find new horizontal position
var newX:Number = char.mc.x + horizontalChange;
// loop through all objects to see if character has bumped into a wall
for(i=0;i<fixedObjects.length;i++) {
if ((newY > fixedObjects[i].topside) && (newY-char.height < fixedObjects[i].bottomside)) {
if ((char.mc.x-char.width/2 >= fixedObjects[i].rightside) && (newX-char.width/2 <= fixedObjects[i].rightside)) {
newX = fixedObjects[i].rightside+char.width/2;
char.hitWallLeft = true;
break;
}
if ((char.mc.x+char.width/2 <= fixedObjects[i].leftside) && (newX+char.width/2 >= fixedObjects[i].leftside)) {
newX = fixedObjects[i].leftside-char.width/2;
char.hitWallRight = true;
break;
}
}
}
// set position of character
char.mc.x = newX;
char.mc.y = newY;
// set animation state
if (char.inAir) {
newAnimState = "jump";
}
char.animstate = newAnimState;
// move along walk cycle
if (char.animstate == "walk") {
char.animstep += timeDiff/60;
if (char.animstep > char.walkAnimation.length) {
char.animstep = 0;
}
char.mc.gotoAndStop(char.walkAnimation[Math.floor(char.animstep)]);
// not walking, show stand or jump state
} else {
char.mc.gotoAndStop(char.animstate);
}
// changed directions
if (newDirection != char.direction) {
char.direction = newDirection;
char.mc.scaleX = char.direction;
}
}
public function scrollWithHero(){
var stagePosition:Number = gamelevel.x+hero.mc.x;
var rightEdge:Number = stage.stageWidth-edgeDistance;
var leftEdge:Number = edgeDistance;
if (stagePosition > rightEdge){
gamelevel.x -= (stagePosition-rightEdge);
if (gamelevel.x < -(gamelevel.width-stage.stageWidth)) gamelevel.x = -(gamelevel.width-stage.stageWidth);
}
if (stagePosition < leftEdge){
gamelevel.x += (leftEdge-stagePosition);
if (gamelevel.x > 0)gamelevel.x=0;
}
}
public function checkCollisions(){
// enemies
for(var i:int=enemies.length-1;i>=0;i--){
if (hero.mc.hitTestObject(enemies[i].mc)){
if (hero.inAir && (hero.dy>0)){
enemyDie(i);
} else {
heroDie();
}
}
}
for(i=otherObjects.length-1;i>=0;i--) {
if (hero.mc.hitTestObject(otherObjects[i])) {
getObject(i);
}
}
}
public function enemyDie(enemyNum:int) {
var pb:PointBurst = new PointBurst(gamelevel,"Zetsu Extinct!",enemies[enemyNum].mc.x,enemies[enemyNum].mc.y-20);
gamelevel.removeChild(enemies[enemyNum].mc);
enemies.splice(enemyNum,1);
}
public function heroDie() {
// show dialog box
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
if (playerLives == 0) {
gameMode = "gameover";
dialog.message.text = "Game Over!";
} else {
gameMode = "dead";
dialog.message.text = "Yoi Failed...";
playerLives--;
}
hero.mc.gotoAndPlay("die");
}
public function getObject(objectNum:int) {
if (otherObjects[objectNum] is Treasure) {
var pb:PointBurst = new PointBurst(gamelevel,100,otherObjects[objectNum].x,otherObjects[objectNum].y);
gamelevel.removeChild(otherObjects[objectNum]);
otherObjects.splice(objectNum,1);
addScore(100);
} else if (otherObjects[objectNum] is Key) {
pb = new PointBurst(gamelevel,"Got Key!" ,otherObjects[objectNum].x,otherObjects[objectNum].y);
playerObjects.push("Key");
gamelevel.removeChild(otherObjects[objectNum]);
otherObjects.splice(objectNum,1);
} else if (otherObjects[objectNum] is Door) {
if (playerObjects.indexOf("Key") == -1) return;
if (otherObjects[objectNum].currentFrame == 1) {
otherObjects[objectNum].gotoAndPlay("open");
levelComplete();
}
} else if (otherObjects[objectNum] is Chest) {
otherObjects[objectNum].gotoAndStop("open");
gameComplete();
}
}
public function addScore(numPoints:int) {
gameScore += numPoints;
scoreDisplay.text = String(gameScore);
}
// update player lives
public function showLives() {
livesDisplay.text = String(playerLives);
}
// level over, bring up dialog
public function levelComplete() {
gameMode = "done";
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
dialog.message.text = "Level Complete!";
}
public function gameComplete() {
gameMode = "gameover";
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
dialog.message.text = "You Got the Treasure!";
}
public function clickDialogButton(event:MouseEvent) {
removeChild(MovieClip(event.currentTarget.parent));
// new life, restart, or go to next level
if (gameMode == "dead") {
// reset hero
showLives();
hero.mc.x = hero.startx;
hero.mc.y = hero.starty;
gameMode = "play";
} else if (gameMode == "gameover") {
cleanUp();
gotoAndStop("start");
} else if (gameMode == "done") {
cleanUp();
nextFrame();
}
// give stage back the keyboard focus
stage.focus = stage;
}
// clean up game
public function cleanUp() {
removeChild(gamelevel);
this.removeEventListener(Event.ENTER_FRAME,gameLoop);
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
}
}
}
here are the list of errors in the coding:
*Line 103, Column 4 1120: Access of undefined property otherObject.
*Line 109, Column 6 1120: Access of undefined property floorObject.
*Line 110, Column 6 1120: Access of undefined property floorObject.
*Line 111, Column 6 1120: Access of undefined property floorObject.
*Line 112, Column 6 1120: Access of undefined property floorObject.
*Line 113, Column 6 1120: Access of undefined property floorObject.
*Line 114, Column 24 1120: Access of undefined property floorObject.
*Line 124, Column 8 1120: Access of undefined property gamemode.
can please someone help me with this i have been scratching my head over it forever
thanks
Your code is full of typos.ActionScript is case-sensitive, and variables need to be spelled correctly!
Line 103:Change otherObject=new Array(); to otherObjects=new Array();
Line 108:Change var floorObjects:Object=new Object(); to var floorObject:Object=new Object();
Line 124:Change if (gamemode != "play") to if (gameMode != "play")

Javascript 'console' infinite loop

I'm experimenting with javascript programs and I hit a snag. The program suddenly lags my browser (infinite loop maybe), dunno why.
function fullscreen() {
if (document.body.requestFullScreen) {document.body.requestFullScreen();}
else if (document.body.webkitRequestFullScreen) {document.body.webkitRequestFullScreen();}
else if (document.body.mozRequestFullScreen) {document.body.mozRequestFullScreen();}
}
var bash = document.createElement('span');
bash.setAttribute('id', 'bash');
document.body.appendChild(bash);
var cursor = document.createElement('span');
cursor.setAttribute('id', 'bashCursor');
cursor.textContent = '_';
cursor.style.display = 'none';
cursor.style.fontWeight = 'bold';
document.body.appendChild(cursor);
window.Bash = {};
window.Bash.printing = false;
window.Bash.queue = Array();
window.Bash.span = bash;
window.Bash.span.cursor = cursor;
delete bash; delete bash;
function bashPrint() {
window.Bash.writing = true;
var bash = window.Bash.span
var i;
while (window.Bash.queue.length) {
if (window.Bash.queue[0] == undefined) {
i = 0;
while (i < window.Bash.queue.length) {
window.Bash.queue[i] = window.Bash.queue[i+1];
console.log('l:'+window.Bash.queue.length);
console.log(window.Bash.queue);
delete window.Bash.queue[i+1];
window.Bash.queue.splice(i,1);
i++;
}
} else if (window.Bash.queue[0]['type'] == 'instant') {
bash.textContent += window.Bash.queue[0]['value'];
delete window.Bash.queue[0];
window.Bash.queue.splice(0,1);
} else if (window.Bash.queue[0]['type'] == 'wait') {
setTimeout(bashPrintWaiting, window.Bash.queue[0]['wait']);
break;
} else if (window.Bash.queue[0]['type'] == 'cursor') {
if (window.Bash.queue[0]['value']) {
window.Bash.span.cursor.style.display = 'inline';
} else {
window.Bash.span.cursor.style.display = 'none';
}
}
}
window.Bash.writing = false;
}
function bashPrintWaiting() {
window.Bash.writing = true;
var bash = window.Bash.span;
bash.textContent += window.Bash.queue[0]['value'];
delete window.Bash.queue[0];
window.Bash.queue.splice(0,1);
window.Bash.writing = false;
setTimeout(bashPrint, 0);
}
function bashWrite(string) {
var array = Array();
array['type'] = 'instant';
array['value'] = string;
window.Bash.queue[window.Bash.queue.length] = array
}
function bashPause(times, string) {
if (!string) {string='';}
while (times > 0) {
var array = Array();
array['type'] = 'wait';
array['value'] = string;
array['wait'] = 50 + Math.floor(Math.random()*450);
window.Bash.queue[window.Bash.queue.length] = array;
times--;
}
}
function bashCursor(enabled) {
var array = Array();
array['type'] = 'cursor';
array['value'] = enabled;
window.Bash.queue[window.Bash.queue.length] = array;
}
bashWrite('Uncompressing');
bashPause(12, '.');
bashWrite('OK\n');
bashPause(3);
bashWrite('Build v. 0.1.01-release (x86_64-pc)\n');
bashPause(2);
bashWrite('Connecting');
bashPause(35, '.');
bashWrite('Error, unknown user. See connect.log for futher information.\n');
bashPause(2);
bashWrite('none#m ~ $ >>');
bashCursor(true);
bashPrint();
I uploaded it on jsFiddle - http://jsfiddle.net/uQcCP/
Program freezes between:
bashWrite('Error, unknown user. See connect.log for futher information.\n');
and
bashPause(2);
Please, can you help me? Thanks a lot.
The infinite loop starts on line 51: while (window.Bash.queue.length) {
It then ends up in the if statement on line 74, and within this the queue is never shortened:
else if (window.Bash.queue[0]['type'] == 'cursor') {
if (window.Bash.queue[0]['value']) {
window.Bash.span.cursor.style.display = 'inline';
If you find yourself having infinite loop problems in Chrome, open up your development tools and go to the script tab before you open up the page. After you open up the page and it starts looping, you can click the pause button to throw a breakpoint wherever the code is currently executing. From there it's a lot easier to divine where you're getting your error.

Categories

Resources