HTML5 SQLite Db questions - html

I've got a couple of questions regarding the Sqlite implementations for HTML5 website.
First of all, I'm trying to use the Synchronous Database calling openDatabaseSync method, but it doesn't seem to work... Someone used it already and could help me ?
Also, I'm struggling a bit trying to process the result return by my database query. I'd like my function to return an array of book, like this :
function searchByKeywordId(kw_id, element) {
cleanSearch();
element.innerHTML = "No result...";
var books = new Array();
db.transaction(function (tx) {
tx.executeSql("SELECT b.BK_TITLE,b.BK_URL, b.BK_THUMBNAIL_URL FROM KEYWORDS k INNER JOIN CATALOG_ITEMS c on k.KW_ID = c.KW_ID INNER JOIN BOOKS b on c.BK_ID = b.BK_ID WHERE k.KW_ID = ? GROUP BY b.BK_TITLE,b.BK_URL",[kw_id], function (tx, results) {
if (results.rows.length > 0) {
var html = "";
for (var i = 0; i < results.rows.length; i++) {
var bookId = results.rows.item(i).BK_ID;
var bookUrl = results.rows.item(i).BK_URL;
var bookTitle = results.rows.item(i).BK_TITLE;
var bookThumbnailUrl = results.rows.item(i).BK_THUMBNAIL_URL;
var book = new Book(bookId,bookTitle,bookUrl,bookThumbnailUrl);
books.push(book);
/*html += "<div class='x_container' id='calibre:book:" + bookId + "'>";
html += "<div class='cover'>";
html += "</div></div>";*/
html += "<a href='" + bookUrl + "' title=\"" + bookTitle + "\" target='_new'><img src='" + bookThumbnailUrl + "'></a> ";
}
//html += "</div>";
element.innerHTML = html;
}
});
});
return books; }
obviously, adding books within the callback methods doesn't work ... Do you see a way I could achieve that ? So that I would not have to write in the document from my database methods ...
Thanks !

On stackoverflow a question with javascript and "doesn't work" in it is usually a missing paren :) However I didn't find one in your code. I see some suspicious looking syntax around
,[kw_id], << did we really mean an array here, or are we de-referencing something...
In any case if that's not a mistake I would start by simplifying things, and not multipurposing your functions.
function searchByKeywordId(kw_id, element) {
cleanSearch();
var books = new Array();
db.transaction(function (tx) {
tx.executeSql("SELECT b.BK_TITLE,b.BK_URL, b.BK_THUMBNAIL_URL FROM KEYWORDS k INNER JOIN CATALOG_ITEMS c on k.KW_ID = c.KW_ID INNER JOIN BOOKS b on c.BK_ID = b.BK_ID WHERE k.KW_ID = ? GROUP BY b.BK_TITLE,b.BK_URL",[kw_id], function (tx, results) {
if (results.rows.length > 0) {
var html = "";
for (var i = 0; i < results.rows.length; i++) {
var bookId = results.rows.item(i).BK_ID;
var bookUrl = results.rows.item(i).BK_URL;
var bookTitle = results.rows.item(i).BK_TITLE;
var bookThumbnailUrl = results.rows.item(i).BK_THUMBNAIL_URL;
var book = new Book(bookId,bookTitle,bookUrl,bookThumbnailUrl);
books.push(book);
} // end for loop
} // end if block
} // end execute callback
); // end executeSql call
} // end transaction function argument
); // end db.transaction call
return books;
}
Then somewhere that you called this function do something like this:
var html="";
for (i=0; i<books.length; i++) {
html += "<a href='" + books[i].url + "' title=\"" + books[i].title + "\" target='_new'><img src='" + books[i].thumbnailUrl + "'></a> ";
}
if (html == "") {
html = "No result...";
}
element.innerHTML = html; // consider using jQuery here for browser compatability reasons
This will simplify debugging your code in firebug or whatever and be more readable. Later IF you need the performance, you can try to recombine and use the existing loop as an optimization... Premature optimization is usually a bad idea. Write clear code that works. Even if you know you should optimize it, get it working and then optimize it after it works (preferably after you've demonstrated that you do in fact need to optimize it).
http://www.flounder.com/optimization.htm

Related

Insert/Add Data to Mysql from REST API with nodejs

Is there a way to insert the information i get from the API to MYSQL? i been looking everywhere and can't find nothing about it, google,youtube.... i'm going crazy. This is my code to fetch the data from the api.
from this code i get a ranking with Position, Name, Highscore.
NOTE: I'm not asking for someone to take time out of his day and make me the code, i'm simply asking for directions or a website that teaches you how to do it. THANK YOU IN ADVANCE.
getData();
async function getData() {
const response = await fetch('http://localhost:3008/api/highscore/players')
console.log(response);
const data = await response.json();
const req = await fetch('http://localhost:3008/api/players')
console.log(req);
const info = await req.json();
length = data.players.length;
console.log(data);
var temp = "";
for (i = 0; i < length; i++)
for (j = 0; j < length; j++) {
{
if (info.players[i].id == data.players[j].id) {
temp += "<tr>";
temp += "<td>" + data.players[j].position + "</td>";
temp += '<td>' + info.players[i].name + '</td>'
temp += "<td>" + data.players[j].score + "</td>";
temp += "</tr>";
}
}
}
document.getElementById("data").innerHTML = temp;
}
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("data");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}```
Looking at your code, I can see that it runs in a web browser, so it is a front end code that runs as a client.
First you need back-end code that runs on server side to connect to a MySQL server and run SQL queries. You can use node.js, PHP, Java etc. for this.
Usually, there would be APIs that also run on server side. The purpose of the API is to bridge between clients (web browsers, mobile apps etc.) and the back-end code that perform database queries.
After you have back-end and APIs, then in your front end code (like the one you included in the question), you would call an API endpoint (for example, http://localhost/api/insertTopScorer) and provide the required parameters, when you want to insert new data to database, or read data from database.
You can also learn more details here Can JavaScript connect with MySQL?

xpath in apps script?

I made a formula to extract some Wikipedia data in Google Seets which works fine. Here is the formula:
=regexreplace(join("",flatten(IMPORTXML(D2,".//p[preceding-sibling::h2[1][contains(., 'Geography')]]"))),"\[[^\]]+\]","")&char(10)&char(10)&iferror(regexreplace(join("",flatten(IMPORTXML(D2,".//p[preceding-sibling::h2[1][contains(., 'Education')]]"))),"\[[^\]]+\]",""))
Where D2 is a URL like https://en.wikipedia.org/wiki/Abbeville,_Alabama
This extracts some Geography and Education data from the Wikipedia page. Trouble is that importxml only runs a few times before it dies due to quota.
So I thought maybe better to use Apps Script where there are much higher limits on fetching and parsing. I could not see a good way however of using Xpath in Apps Script. Older posts on the web discuss using a deprecated service called Xml but it seems to no longer work. There is a Service called XmlService which looks like it may do the job but you can't just plug in an Xpath. It looks like a lot of sweating to get to the result. Any solutions out there where you can just plug in Xpath?
Here is an alternative solution I actually do in a case like this.
I have used XmlService but only for parsing the content, not for using Xpath. This makes use of the element tags and so far pretty consistent on my tests. Although, it might need tweaks when certain tags are in the result and you might have to include them into the exclusion condition.
Tested the code below in both links:
https://en.wikipedia.org/wiki/Abbeville,_Alabama#Geography
https://en.wikipedia.org/wiki/Montgomery,_Alabama#Education
My test shows that the formula above used did not return the proper output from the 2nd link while the code does. (Maybe because it was too long)
Code:
function getGeoAndEdu(path) {
var data = UrlFetchApp.fetch(path).getContentText();
// wikipedia is divided into sections, if output is cut, increase the number
var regex = /.{1,100000}/g;
var results = [];
// flag to determine if matches should be added
var foundFlag = false;
do {
m = regex.exec(data);
if (foundFlag) {
// if another header is found during generation of data, stop appending the matches
if (matchTag(m[0], "<h2>"))
foundFlag = false;
// exclude tables, sub-headers and divs containing image description
else if(matchTag(m[0], "<div") || matchTag(m[0], "<h3") ||
matchTag(m[0], "<td") || matchTag(m[0], "<th"))
continue;
else
results.push(m[0]);
}
// start capturing if either IDs are found
if (m != null && (matchTag(m[0], "id=\"Geography\"") ||
matchTag(m[0], "id=\"Education\""))) {
foundFlag = true;
}
} while (m);
var output = results.map(function (str) {
// clean tags for XmlService
str = str.replace(/<[^>]*>/g, '').trim();
decode = XmlService.parse('<d>' + str + '</d>')
// convert html entity codes (e.g.  ) to text
return decode.getRootElement().getText();
// filter blank results due to cleaning and empty sections
// separate data and remove citations before returning output
}).filter(result => result.trim().length > 1).join("\n").replace(/\[\d+\]/g, '');
return output;
}
// check if tag is found in string
function matchTag(string, tag) {
var regex = RegExp(tag);
return string.match(regex) && string.match(regex)[0] == tag;
}
Output:
Difference:
Formula ending output
Script ending output
Education ending in wikipedia
Note:
You still have quota when using UrlFetchApp but should be better than IMPORTXML's limit depending on the type of your account.
Reference:
Apps Script Quotas
Sorry I got very busy this week so I didn't reply. I took a look at your answer which seems to work fine, but it was quite code heavy. I wanted something I would understand so I coded my own solution. not that mine is any simpler. It's just my own code so it's easier for me to follow:
function getTextBetweenTags(html, paramatersInFirstTag, paramatersInLastTag) { //finds text values between 2 tags and removes internal tags to leave plain text.
//eg getTextBetweenTags(html,[['class="mw-headline"'],['id="Geography"']],[['class="wikitable mw-collapsible mw-made-collapsible"']])
// **Note: you may want to replace &#number; with ascII number
var openingTagPos = null;
var closingTagPos = null;
var previousChar = '';
var readingTag = false;
var newTag = '';
var tagEnd = false;
var regexFirstTagParams = [];
var regexLastTagParams = [];
//prepare regexes to test for parameters in opening and closing tags. put regexes in arrays so each condition can be tested separately
for (var i in paramatersInFirstTag) {
regexFirstTagParams.push(new RegExp(escapeRegex(paramatersInFirstTag[i][0])))
}
for (var i in paramatersInLastTag) {
regexLastTagParams.push(new RegExp(escapeRegex(paramatersInLastTag[i][0])))
}
var startTagIndex = null;
var endTagIndex = null;
var matches = 0;
for (var i = 0; i < html.length - 1; i++) {
var nextChar = html.substr(i, 1);
if (nextChar == '<' && previousChar != '\\') {
readingTag = true;
}
if (nextChar == '>' && previousChar != '\\') { //if end of tag found, check tag matches start or end tag
readingTag = false;
newTag += nextChar;
//test for firstTag
if (startTagIndex == null) {
var alltestsPass = true;
for (var j in regexFirstTagParams) {
if (!regexFirstTagParams[j].test(newTag)) alltestsPass = false;
}
if (alltestsPass) {
startTagIndex = i + 1;
//console.log('Start Tag',startTagIndex)
matches++;
}
}
//test for lastTag
else if (startTagIndex != null) {
var alltestsPass = true;
for (var j in regexLastTagParams) {
if (!regexLastTagParams[j].test(newTag)) alltestsPass = false;
}
if (alltestsPass) {
endTagIndex = i + 1;
matches++;
}
}
if(startTagIndex && endTagIndex) break;
newTag = '';
}
if (readingTag) newTag += nextChar;
previousChar = nextChar;
}
if (matches < 2) return 'No matches';
else return html.substring(startTagIndex, endTagIndex).replace(/<[^>]+>/g, '');
}
function escapeRegex(string) {
if (string == null) return string;
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
My function requires an array of attributes for the start tag and an array of attributes for the end tag. It gets any text in between and removes any tags found inbetween. One issue I also noticed was there were often special characters (eg  ) so they need to be replaced. I did that outside the scope of the function above.
The function could be easily improved to check the tag type (eg h2), but it wasn't necessary for the wikipedia case.
Here is a function where I called the above function. the html variable is just the result of UrlFetchApp.fetch('some wikipedia city url').getContextText();
function getWikiTexts(html) {
var geography = getTextBetweenTags(html, [['class="mw-headline"'], ['id="Geography']], [['class="mw-headline"']]);
var economy = getTextBetweenTags(html, 'span', [['class="mw-headline"'], ['id="Economy']], 'span', [['class="mw-headline"']])
var education = getTextBetweenTags(html, 'span', [['class="mw-headline"'], ['id="Education']], 'span', [['class="mw-headline"']])
var returnString = '';
if (geography != 'No matches' && !/Wikipedia/.test(geography)) returnString += geography + '\n';
if (economy != 'No matches' && !/Wikipedia/.test(economy)) returnString += economy + '\n';
if (education != 'No matches' && !/Wikipedia/.test(education)) returnString += education + '\n';
return returnString
}
Thanks for posting your answer.

Render json string from controller to mvc view

My json string is coming as follows:
"[{\"StartTime\":\"09:00\",\"Dates\":\"05-28-2015\",\"Code\":\"DF\",\"LocationCode\":\"NY\"},{\"StartTime\":\"09:30\",\"Dates\":\"05-28-2015\",\"Code\":\"DF\",\"LocationCode\":\"NY\"},{\"StartTime\":\"10:00\",\"Dates\":\"05-28-2015\",\"Code\":\"DF\",\"LocationCode\":\"NY\"},{\"StartTime\":\"10:30\",\"Dates\":\"05-28-2015\",\"Code\":\"DF\",\"LocationCode\":\"NY\"},{\"StartTime\":\"11:30\",\"Dates\":\"05-28-2015\",\"Code\":\"DF\",\"LocationCode\":\"NY\"}]"
I need to parse this json string on view and show the data in a table.
I am new to json. Any help will be really appreciated. Thanks.
$("#divLoad").load("GetAvailableTimeSlots?strProvider=" + provider + "&strFrom=" + from, function (data) {
var newStr = data.replace('"[', '').replace(']"', '').replace('[', '').replace(']', '');
var dataArr = newStr.split('},{');
var jsonArr = new Array(dataArr.length);
for (var i = 0; i < dataArr.length; i++) {
dataArr[i] = '{' + dataArr[i] + '}';
var dataElem = dataArr[i].replace('{{', '{').replace('}}', '}');
var jsonElem = "'" + dataElem + "'";
jsonArr[i] = JSON.parse(jsonElem);
}
$(this).html(jsonArr);
});
If you are using jQuery, you can use the jQuery.parseJSON() method.
http://api.jquery.com/jquery.parsejson/
Just call JSON.parse(data) and manipulate the javascript object instead of performing error-prone string manipulation.
function (data) {
var locations = JSON.parse(data);
var table = $("<ul>");
for (var i = 0; i < locations.length; i++) {
var row = $("<li>").text(locations[i].StartTime + " " + locations[i].Dates + " " ...);
table.append(row);
}
$("#divLoad").empty().append(table); // $(this) won't work
}
This example is using an unordered list but you can easily replace this with table markup.
Here's what it looks like in Chrome dev tools with console.log(locations) after parsing:

Javascript ReGEX for JSON

This is all so confusing, I've seen so many examples of how to do different things and cannot seem to find a valid example for what I am trying to do.
I'm using the YQL for the stock quotes only to get just the major indexes, DOW S&P 500 and NASDAQ.
The project is getting the data and working, but I need to determine if the stock value is returning + or - (up or down).
if the market is up or flat, I want to add a CSS class to set it to green, if it is down, I want to set a CSS to red.
One other issue, this only seems to work when I place the function between the head and body, not in the head, not in the body.
<script type="text/javascript">
function stock_quotes(obj)
{
var items = obj.query.results.quote;
var output = '';
var num_quotes = items.length;
items[0].symbol = "DOW ";
items[1].symbol = "NASDAQ ";
items[2].symbol = "S&P 500 ";
//var posquote = {"\d\.?\d{0,9}\.\d{0,9}\s\+"};
//var negquote = {"\d\.?\d{0,9}\.\d{0,9}\s\-"};
for (var i = 0; i < num_quotes; i++) {
var link = items[i].url;
var symbl = items[i].symbol;
var Change_PercentChange = items[i].Change_PercentChange;
var LastTradePriceOnly = items[i].LastTradePriceOnly;
output += "<table><tr><td>" + "<a href='" + link + "'>" + symbl + "</a>" + LastTradePriceOnly + " " + Change_PercentChange + "</td></tr></table>";
}
// Place news stories in div tag
document.getElementById('results').innerHTML = output;
}
This is the HTML with the query
<div id='results'></div>
<script type="text/javascript" src='http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22DOW%22%2C%22%5EIXIC%22%2C%22%5EGSPC%22)%0A%09%09&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=stock_quotes'></script>
Ideally I'd like to predefine the html elements which would make it easier to set the css class but one headache at a time.
In the end, this seemed to work just fine
var match_nas_neg = nas_result.match(/\-/);

MS Exchange Web-Services: How to get items with 'Flag' set?

Does anyone know how to get all the items that are flagged inside the Inbox using Microsoft Exchange Web-Services?
Apparently they are neither inside Tasks folder (even though they appear there in Outlook), nor do they have IsReminderSet set to true.
Following attempts either return only appointments or true tasks only, but not flagged messages:
var msgsView = new ItemView(100);
var msgsFilter = new SearchFilter.IsEqualTo(ItemSchema.IsReminderSet, true);
var flagged = exSvc.FindItems(WellKnownFolderName.Inbox, msgsFilter, msgsView);
or
var taskView = new ItemView(100);
var tasks = exSvc.FindItems(WellKnownFolderName.Tasks, taskView);
neither work.
I know this question is old, but I just found list sample code which looks like it might do the trick (I haven't tested it myself yet)
source: http://independentsoft.de/exchangewebservices/tutorial/findmessageswithflag.html
IsEqualTo restriction1 = new IsEqualTo(MessagePropertyPath.FlagStatus, "1"); //FlagStatus.Complete
IsEqualTo restriction2 = new IsEqualTo(MessagePropertyPath.FlagStatus, "2"); //FlagStatus.Marked
Or restriction3 = new Or(restriction1, restriction2);
FindItemResponse response = service.FindItem(StandardFolder.Inbox
, MessagePropertyPath.AllPropertyPaths, restriction3);
for (int i = 0; i < response.Items.Count; i++)
{
if (response.Items[i] is Message)
{
Message message = (Message)response.Items[i];
Console.WriteLine("Subject = " + message.Subject);
Console.WriteLine("FlagStatus = " + message.FlagStatus);
Console.WriteLine("FlagIcon = " + message.FlagIcon);
Console.WriteLine("FlagCompleteTime = " + message.FlagCompleteTime);
Console.WriteLine("FlagRequest = " + message.FlagRequest);
Console.WriteLine("-----------------------------------------------");
}
}