I'm using Node.js to access this hdPrivateKey but it look like
<hdPrivateKey...>
Not look like normal JS object.
And console.log(address) looks like
<Address: 19o9ghmkUrNVf4d57tQJuUBb2gT8sbzKyq, type: pubkeyhash, network: livenet>
console.log(Object.keys(address)) look like
[ 'hashBuffer', 'network', 'type' ]
Why the key inside address are different?
var bitcore = require('bitcore');
var HDPrivateKey = bitcore.HDPrivateKey;
var hdPrivateKey = new HDPrivateKey();
console.log(hdPrivateKey)
var retrieved = new HDPrivateKey(hdPrivateKey);
var derived = hdPrivateKey.derive("m/0");
var derivedByNumber = hdPrivateKey.derive(1).derive(2, true);
var derivedByArgument = hdPrivateKey.derive("m/1/2");
var address = derived.privateKey.toAddress();
console.log(Object.keys(address))
console.log(address)
// obtain HDPublicKey
var hdPublicKey = hdPrivateKey.hdPublicKey;
The behavior you're seeing is because the object has its own inspect property which is a function and returns a string. When console.log sees that it's logging an object, it looks for that function and uses it if available. So on Node, this logs <foo>:
const o = {
inspect() {
return "<foo>";
}
};
console.log(o);
That's all that the HDPrivateKey object is doing.
If you want to properly inspect the object, use a debugger. Alternately, use utils.inspect with customInspect set to false.
In Node.js, a console.log call the function inspect of the object. In the bitcore-lib there is this method :
HDPrivateKey.prototype.inspect = function() {
return '<HDPrivateKey: ' + this.xprivkey + '>';
};
And this method:
Address.prototype.inspect = function() {
return '<Address: ' + this.toString() + ', type: ' + this.type + ', network: ' + this.network + '>';
};
Related
Instead of using:
const ref = $location.protocol() + '://' + $location.host();
i try to do it like this:
const { protocol, host } = $location;
const ref = protocol() + '://' + host();
but it does not seem to work. ( protocol() is not returning anything, same for host() )
However, if I try something like this:
const loc = {
protocol: function(){
return 'http';
},
host: function(){
return 'example.com';
},
};
const { protocol, host } = loc;
document.write(protocol() + '://' + host());
it works. Any ideea why?
Ps. Some sample here, just uncomment the second line and it would not work anymore.
The destructuring assignment syntax is a JavaScript expression that
makes it possible to unpack values from arrays, or properties from
objects, into distinct variables.
You loose reference to this when you de-structure methods,$location.protocol and protocol refer to different this
let a = {
myName : 'my name',
nameLogger(){
return this.myName
}
}
let {nameLogger} = a
console.log( 'Hello ' + nameLogger())
nameLogger = nameLogger.bind(a)
console.log( 'Hello ' + nameLogger())
I'm creating a multiuser app and wanted to use keys to product user information. I created a function that updates the child of a database with a generated key. The following function behaves correctly:
unlist(list) {
var postData = {
state: "unlisted",
};
var newPostKey = firebase.database().ref().child('foods').push().key;
var updates = {};
updates['foods' + '/' + list.$key + '/' + 'state' + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);}
I have a separate function that works similarly to this:
changestate(item) {
var postData = {
state: "listed",
};
var newPostKey = firebase.database().ref().child('foods').push().key;
var updates = {};
updates['foods' + '/' + item.$key + '/' + 'state' + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);}
In order to make this work correctly, the key that is created from unlist(list) needs to correspond to var newPostKey in changestate(item) and vice versa. How can I make this work?
cfoster5. What I have understood from your question is that the newPostkey from the unlist function should be passed to the changeState(item) function if that's what you want means you can do that by calling promise in the
firebase.database().ref().update(updates).then(function(){
// You can call changestate function and pass the function like below
_changestate(item,newPostkey);
});
and in your changestate function,
changestate=function(item,passedkey){
var newPostKey = passedkey;
}
See my jsfiddle sample
I am trying to assign a object to a prototype, but I keep getting a error that the object is undefined. I am trying to do this
//x.prototype.y = {};
StreetEasy.prototype.neighborhoodPaths = {};
and at a later point in the code I am trying to access this object in another prototype function and push in new data with
//x.prototype.assignData = function(z, a){
// this.y[z] = a;
//}
StreetEasy.prototype.findNeighborhoodPath = function(areaQuery, callback){
var data = {q: areaQuery, key: this.apiKey, format: this.format};
var query = qs.stringify(data);
var url = AreaSearchUrl + '?' + query;
var areaQ = areaQuery.toLowerCase();
if (this.neighborhoodPaths[areaQ]) {
callback(this.neighborhoodPaths[areaQ].path);
} else {
http.get(url, function(response){
response.setEncoding('utf8');
response.on('data', function (rData){
rData = JSON.parse(rData);
callback(rData);
rData.areas.every(function(element){
-----------error is here-> this.neighborhoodPaths[element.name.toLowerCase()].path = element.path;
});
}).on('error', function(e){
console.error('ERROR: ' + e.message + ' | ' + e.statusCode );
});
});
}
};
Node keeps returning
TypeError: Cannot read property z of undefined. What am I doing wrong?
Edit more of the code:
StreetEasy.prototype.neighborhoodPaths = {};
StreetEasy.prototype.findNeighborhoodPath = function(areaQuery, callback){
var data = {q: areaQuery, key: this.apiKey, format: this.format};
var query = qs.stringify(data);
var url = AreaSearchUrl + '?' + query;
var areaQ = areaQuery.toLowerCase();
if (this.neighborhoodPaths[areaQ]) {
callback(this.neighborhoodPaths[areaQ].path);
} else {
http.get(url, function(response){
response.setEncoding('utf8');
response.on('data', function (rData){
rData = JSON.parse(rData);
callback(rData);
rData.areas.every(function(element){
-----------error is here-> this.neighborhoodPaths[element.name.toLowerCase()].path = element.path;
});
}).on('error', function(e){
console.error('ERROR: ' + e.message + ' | ' + e.statusCode );
});
});
}
};
(See update below, now that you've posted code.)
This is most likely a result of the way you're calling assignData. This would work, for instance:
var obj = new x();
obj.assignData("foo", "bar");
This would not:
var obj = new x();
f = obj.assignData;
f("foo", "bar");
And for the same reason, this would not:
callMeBack(obj.assignData, "foo", "bar");
function callMeBack(method, z, a) {
method(z, a);
}
In both cases, the problem is that this within the call to assignData doesn't refer to the object, it's the global object instead. When you call a function not through a property reference, this is set to the global object (in loose mode; in strict mode it would be undefined). It's the action of calling it through a property reference that sets this to the object the property comes from.
More (on my blog):
Mythical Methods
You must remember this
Update, now that you've posted code. I'm going to assume findNeighborhoodPath is the function you called assignData in your original question.
The problem is indeed that you're losing this, but not quite in the way above.
The callback you're passing http.get will get called with this referring to the global object, not the instance on which findNeighborhoodPath was called; similarly, the callback you're passing into Array#every will have this referring to the global object, because you didn't tell it to do something else.
If you want to use that instance, the simplest way is to declare a variable referring to it, then use the variable:
var self = this; // <== Variable to remember `this`
http.get(url, function(response) {
response.setEncoding('utf8');
response.on('data', function(rData) {
rData = JSON.parse(rData);
callback(rData);
rData.areas.every(function(element) {
self.neighborhoodPaths[element.name.toLowerCase()].path = element.path;
// ^^^^ --- using it
});
}).on('error', function(e) {
console.error('ERROR: ' + e.message + ' | ' + e.statusCode);
});
// ...
});
Alternately, you could use Function#bind and the thisArg argument of Array#every:
http.get(url, function(response) {
response.setEncoding('utf8');
response.on('data', function(rData) {
rData = JSON.parse(rData);
callback(rData);
rData.areas.every(function(element) {
this.neighborhoodPaths[element.name.toLowerCase()].path = element.path;
}, this); // <=== Note passing `this` as the second arg to `every`
}).on('error', function(e) {
console.error('ERROR: ' + e.message + ' | ' + e.statusCode);
});
// ...
}.bind(this)); // <=== Note the .bind(this)
In the next version of JavaScript, ECMAScript6, we'll have "fat arrow" functions which have "lexical this binding," a fancy term meaning that this within the function will be the same as this was in the context in which the function was created. So once V8 supports them, and Node updates to using that version of V8 (both of those will be quite soon), you'll be able to do this (note the two => below):
http.get(url, (response) => {
response.setEncoding('utf8');
response.on('data', function(rData) {
rData = JSON.parse(rData);
callback(rData);
rData.areas.every((element) => {
this.neighborhoodPaths[element.name.toLowerCase()].path = element.path;
});
}).on('error', function(e) {
console.error('ERROR: ' + e.message + ' | ' + e.statusCode);
});
// ...
});
I need a way to replace part of a string with another string using Google Apps Script. I tested the following and it worked:
function test(){
var value = 'https://plus.google.com/117520727894266469000';
var googleimageURL = googlePlus(value);
Logger.log('Returned Result: ' + googleimageURL);
}
function googlePlus(value){
var apiKey = ScriptProperties.getProperty('apiKey');
var re = 'http://'
var theURL = value;
Logger.log('Google+ is called: ' + value);
var replacingItem = 'https://';
var theURL = theURL.replace(re, replacingItem);
Logger.log('Google+ Values 2: ' + value + ' : ' + theURL + ' after ' + replacingItem);
return imageURL;
}
But, when I embedded into the following code, it did not work. Any idea?
//If a Google+ column was not specified,put a flag.
if (googleColumn && column == googleColumn) {
if (value == ""){
columns.push(nogoogleColumn);
values.push(flag);
var googleimageURL="";
} else {
var googleimageURL = googlePlus(value);
Logger.log('Returned Result: ' + googleimageURL);
}
}
The script did not work as I wish. It seems to stop at line:
var theURL = theURL.replace(re, replacingItem);
Additional information: Google notified me with the following message
onFormSubmit
TypeError: Cannot find function replace in object https://plus.google.com/117520727894266469000. (line 536) formSubmit
I found the mistake. It is Type Error. value in the second block is not a "string", while the first block is a "string". Hence to fix the second block, I need to use:
var value = value.toString();
before passing to googlePlus(value)
Inside a web worker, I have an html string like:
"<div id='foo'> <img src='bar'></img> <ul id='baz'></ul> </div>"
Is there any library I can import to easily access id and src attributes of the different tags ? Is regex the only way inside a worker ?
There are two ways to solve this problem efficiently:
Regex
With the risk of getting false positives, you can use something like:
var pattern = /<img [^>]*?src=(["'])((?:[^"']+|(?!\1)["'])*)(\1)/i;
var match = string.match(pattern);
var src = match ? match[2] : '';
Built-in parser & messaging
If getting the HTML right is a critical requirement, just let the browser parse the HTML, by passing the string to the caller. Here's a full example:
Caller:
var worker = new Worker('worker.js');
worker.addEventListener('message', function(e) {
if (!e.data) return;
if (e.data.method === 'getsrc') {
// Unlike document.createElement, etc, the following method does not
// load the image when the HTML is parsed
var doc = document.implementation.createHTMLDocument('');
doc.body.innerHTML = e.data.data;
var images = doc.getElementsByTagName('img');
var result = [];
for (var i=0; i<images.length; i++) {
result.push(images[i].getAttribute('src'));
}
worker.postMessage({
messageID: e.data.messageID,
result: result
});
} else if (e.data.method === 'debug') {
console.log(e.data.data);
}
});
worker.js
// A simple generic messaging API
var callbacks = {};
var lastMessageID = 0;
addEventListener('message', function(e) {
if (callbacks[e.data.messageID]) {
callbacks[e.data.messageID](e.data.result);
}
});
function sendRequest(method, data, callback) {
var messageID = ++lastMessageID;
if (callback) callbacks[messageID] = callback;
postMessage({
method: method,
data: data,
messageID: messageID
});
}
// Example:
sendRequest('getsrc',
'<img src="foo.png">' +
"<img src='bar.png'>" +
'<textarea><img src="should.not.be.visible"></textarea>',
function(result) {
sendRequest('debug', 'Received: ' + result.join(', '));
}
);