Within a Firefox extension, I am opening a database file and displaying the database contents. However, Firefox is showing some characters incorrectly, presumably due to an encoding issue. I tried opening the database file in SQLite Database Browser and the name column displayed correctly.
How can I properly handle this text string so that it outputs characters as I intended (e.g., Caché rather than Caché)?
Code snippet which reproduces this problem:
var StorageService = Cc["#mozilla.org/storage/service;1"]
.getService(Ci.mozIStorageService);
_Conn = StorageService.openDatabase(file);
var stmt = _Conn.createStatement("Select name from data");
var RunQuery = function () {
return {
arr: [],
handleResult: function (aResultSet) {
var row = aResultSet.getNextRow();
alert([row.getResultByName("name"), 'Cach\u00E9']);
},
handleError: function (aError) {},
handleCompletion: function (aReason) {}
};
};
stmt.executeAsync(RunQuery());
Output: Caché,Caché
Intended Output: Caché,Caché
Assuming IDX_NAME is the index of column name, then
alert([row.getUTF8String(IDX_NAME), 'Cach\u00E9']);
will give you the intended result.
This seems to work:
var converter = Cc["#mozilla.org/intl/scriptableunicodeconverter"]
.createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
alert([converter.ConvertToUnicode(row.getString("name")), 'Cach\u00E9']);
Related
I have formatted a string to be used within a putItem call using DynamoDB SDK. This Long string (item I would like to add has lots of information) is stored in a variable and I should be able to use it within the Item {} part of dynamoDdb.putItem() .
However, when the variable is actually processed extra characters are added in causing the formatting to be incorrect for how an Item {} should look.
See below:
itemToAdd = JSON.stringify(marshalled2, null,2)
newString = itemToAdd.slice(4, itemToAdd.length-1)
correct = newString.replaceAll(" ", '');
correct2 = correct.replaceAll("\n", "")
//console.log(newString)
var params = {
TableName: "Music",
Item: {
correct2
}
}
dynamodb.putItem(params, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("Success", data);
}
});
My issue is that the string correct2 has no slashes or \n in it as I have removed them prior however when the string correct2 is used with the params object extra black slashes have been added into the string messing up the formatting.
An example of the string contained in correct2 would be as follows:
"AlbumData":{"S":"2B5C1828-6077-4ED1-89AD-13602A7AC08D"},"label":{"S":"EvolutionMediaMusic"},"Album":{"S":"BleakDrama"},"albumCode":{"S":"EMM101"},"releaseDate":{"S":"21/06/2016"},"description":{"S":"Contemporarynoircrimedrama:coldandforebodingcueswithtwistedsyntheticatmospheresandpulsingrhythms."},"credits":{"S":""},"tracks":{"L":[{"M":{"id":{"S":"984CA56C-3FA8-4F49-9C9E-3F96C237EE7E"},"trackNo":{"S":"1"},"albumCode":{"S":"EMM101"},"albumName":{"S":"BleakDrama"},"lengthOfTrack":{"S":"02:30"}, //more fields would go here
If I was to copy the text above and insert it into where the variable is there is no issue with the code. Using the javascript debug console the variable correct2 is set to the above however
params.Item = \"AlbumData\":{\"S\":\"2B5C1828-6077-4ED1-89AD-13602A7AC08D\"},\"label\":{\"S\":\"EvolutionMediaMusic\"},\"Album\":{\"S\":\"BleakDrama\"}, // and the patten repeats
What is causing the difference between correct2 and params.Item? I would expect them to be the same.
Dude, its ok, just relax. Its called escaping
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences
https://www.geeksforgeeks.org/how-to-use-escape-characters-to-correctly-log-quotes-in-a-string-using-javascript/
What I want to do is change the url.
Replace the Object word with an event parameter called e1.
Replace the word field with the event parameter e2.
I know this code is not working.
But I don't know how to do it.
The following is my code that I just wrote.
function getAllFieldValue(e1,e2) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var url = 'test123.my.salesforce.com/services/data/v44.0/queryAll?q=SELECT Field FROM Object';
var url = url.replace('Object',e1);
var url = url.replace('Field',e2);
var response = UrlFetchApp.fetch(url,getUrlFetchOptions());
var json = response.getContentText();
var data = JSON.parse(json);
var fieldValues = data.records;
for(var i=0;i<fieldValues.length;i++){
var fieldValue = fieldValues[i].e;
ss.getRange(i+1,1).setValue(fieldValue);
}
}
I want to take the data from another database through this code and put it in the Google spreadsheet.
For e1, it means the object value selected in the dropbox.
For e2, it means the field of the object selected in the drop box.
Is there a way to use two event parameters for one function?
I look forward to hearing from you.
====================
Please understand that I am using a translator because I am not good at English.
Checking fieldValues[i] in Logger.log returns the following values:
[{
attributes={
type=Account,
url=/services/data/v44.0/sobjects/Account/0015i00000BS03VAAT
},
Name=University of Arizona
},
{
attributes={
type=Account,
url=/services/data/v44.0/sobjects/Account/0015i00000BS03TAAT
},
Name=United Oil & Gas Corp.
},
{
attributes={
type=Account,
url=/services/data/v44.0/sobjects/Account/0015i00000BS03ZAAT
},
Name=sForce
}]
The issues I am currently experiencing are as follows.
If I select 'Name' from the drop-down list, ec2 becomes 'Name'.
As far as I'm concerned,
var fieldName = fieldValues[i].e2 is
var fieldName = fieldValues[i].Name
It means that.
I think fieldValues[i].e2 should return the values of University of Arizona, United Oil & Gas Corp, sForce.
But in reality nothing is returned.
var fieldName = fieldValues[i].Name works properly.
I think there is a problem with fieldValues[i].e2
This is the problem I'm currently experiencing.
There was no problem with the parameters e1, e2, which I thought was a problem. The reason why the code did not work is because of the for loop var fieldValue = fieldValues[i].e; Because it didn't work properly.
var fieldName = fieldValues[i].e2
to
var fieldName = fieldValues[i][e2]
After modifying it like this, the code works properly.
I have written a code to populate data from a spreadsheet into a google doc and save it to drive using g-sript. Here is the code for the same :
function onOpen() {
const ui = SpreadsheetApp.getUi();
const menu = ui.createMenu('Invoice creator');
menu.addItem('Generate Invoice', 'invoiceGeneratorFunction');
menu.addToUi();
}
function invoiceGeneratorFunction() {
const invoiceTemplate = DriveApp.getFileById('125NPu-n77F6N8hez9w63oSzbWrtryYpRGOkKL3IbxZ8');
const destinationFolder = DriveApp.getFolderById('163_wLsNGkX4XDUiSOcQ88YOPe3vEx7ML');
const sheet_invoice = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('New Invoice Sheet');
const rows = sheet_invoice.getDataRange().getValues();
Logger.log(rows);
rows.forEach(function(row, index) {
if (index === 0) return;
if (row[12] != "") return;
const copy = invoiceTemplate.makeCopy(`${row[1]} VIN Number: ${row[2]}`,destinationFolder);
const doc = DocumentApp.openById(copy.getId());
const body = doc.getBody();
var friendlyDateBilled = new Date(row[0]).toLocaleDateString();
var friendlyDateDelivery = new Date(row[3]).toLocaleDateString();
body.replaceText('{{Date Billed}}',friendlyDateBilled);
body.replaceText('{{Customer Name}}',row[1]);
body.replaceText('{{VIN Number}}',row[2]);
body.replaceText('{{Date of Delivery}}',friendlyDateDelivery);
body.replaceText('{{Package}}',rows[4]);
body.replaceText('{{Price}}',rows[5]);
body.replaceText('{{Output CGST}}',rows[6]);
body.replaceText('{{Output SGST}}',rows[7]);
body.replaceText('{{Discount}}',rows[8]);
body.replaceText('{{Total Price}}',rows[9]);
body.replaceText('{{Balance}}',rows[10]);
body.replaceText('{{Remarks}}',rows[11]);
doc.saveAndClose();
const url = doc.getUrl();
sheet_invoice.getRange(index+1, 13).setValue(url);
})
}
I have created a menu button for the script to run. But when i run it I get an error saying :
Exception: Invalid argument: replacement
at unknown function
at invoiceGeneratorFunction(Code:17:8)
(Here line 32 is body.replaceText('{{Package}}',rows[4]);
and line 17 is the start of forEach)
Interestingly when I comment out the rest of body.replaceText lines after that line, the code works. I can't understand what the problem is, if it's working if I comment out the lines.
In your script, rows is 2 dimensional array retrieved with sheet_invoice.getDataRange().getValues(). When I saw your loop, after the line of body.replaceText('{{Package}}',rows[4]);, rows is used. In this case, rows[4] is 1-dimensional array. It is required to be the string for the arguments of replaceText(searchPattern, replacement). I think that this might be the reason for your issue. In order to remove this issue, how about the following modification?
From:
body.replaceText('{{Package}}',rows[4]);
body.replaceText('{{Price}}',rows[5]);
body.replaceText('{{Output CGST}}',rows[6]);
body.replaceText('{{Output SGST}}',rows[7]);
body.replaceText('{{Discount}}',rows[8]);
body.replaceText('{{Total Price}}',rows[9]);
body.replaceText('{{Balance}}',rows[10]);
body.replaceText('{{Remarks}}',rows[11]);
To:
body.replaceText('{{Package}}',row[4]);
body.replaceText('{{Price}}',row[5]);
body.replaceText('{{Output CGST}}',row[6]);
body.replaceText('{{Output SGST}}',row[7]);
body.replaceText('{{Discount}}',row[8]);
body.replaceText('{{Total Price}}',row[9]);
body.replaceText('{{Balance}}',row[10]);
body.replaceText('{{Remarks}}',row[11]);
Note:
I'm not sure about your actual values of rows. So I'm not sure whether the values of row[4] to row[11] are what you want. If those values are not the values you expect, please check your Spreadsheet again.
Reference:
replaceText(searchPattern, replacement)
I am trying to display Firebase query results in HTML but the browser shows "undefined" instead of the value that I see in the console.
var showData = document.getElementById("showData");
var button1 = document.getElementById("but1");
var usersRef =
firebase.database().ref('stores/').orderByChild("sid").equalTo(123);
function s2_but() { //function gets trigger when button pressed
usersRef.on('value', snap);
function snap(data) {
data2 = data.val();
console.log(data2);
showData.innerHTML = data2.sname; //sname is the name of child key
//whose value I want to show
}
};
Here is what the console shows:
entry1: {prod1: "coffee", prod2: "sandwich", sid: 123,
sname: "Java Coffee"}
__proto__:Object
Therefore, I am able to retrieve the data but I get an undefined in the browser when I use the following code to show the data in HTML.
<p id="showData"></p>
Undefined variable showing in the web-browser
I think the error happens when I am trying to call the exact value from the object using the following code but I am not sure. All the examples I have seen have done it this way. Therefore, I am confused.
showData.innerHTML = data2.sname;
In the HTML file I have both Firebase and jquery appropriately included, initialized etc.
I would greatly appreciate any help. Thanks.
I found the solution:
function snap(data) {
data2 = data.val();
data3 = data2.entry1.sname;
console.log(data3);
showData.innerHTML = data3;
};
Firebase returns a nested object with this query. entry1 is the name of the first level or key of this object. Therefore, its name has to be entered before accessing the value.
What to do if "entry1" were actually defined by a variable?
I think I was able to figure out the best way to do this. It took a while to understand the limitations of Firebase coming from an SQL background.
To query the database, I used this instead of using orderByChild():
var sid = 'entry1';
var usersRef = firebase.database().ref('stores/'
+ sid);
Now I am able to get the value of sname without having to enter the key of it in the chain:
function s2_but() {
usersRef.on('value', snap);
function snap(data) {
data2 = data.val();
data3 = data2.sname;
console.log(data3);
showData.innerHTML = data3;
};
};
This is to query a Firebase database entry that looks like this.
I hope this helps some of you looking to solve a similar problem. If you have any suggestions please let me know.
At the moment, Zotero (even version 5.0 beta) offers a decent CSL Json export, but it is still incomplete. Namely, the tags are not passed to the Json file. Metadata about bibliographic entries is very important because you can then use it to filter and categorise the Json output.
This thread at the Zotero support forums says a hook can be added to the translators file (line 68):
function doExport() {
var item, data = [];
while(item = Z.nextItem()) data.push(ZU.itemToCSLJSON(item));
Z.write(JSON.stringify(data, null, "\t"));}
The tags (already in Zotero as item.tags) need to be passed on as an array. Any suggestion?
Edit: Problem solved in the same thread. Add this function:
function doExport() {
var item, data = [];
while(item = Z.nextItem()) {
var itemJSON = ZU.itemToCSLJSON(item);
itemJSON.keyword = item.tags.map(o => o.tag).join(", ");
data.push(itemJSON);
}
Z.write(JSON.stringify(data, null, "\t"));
}