React setState not working, getting error - java

I get the following error when trying to use setState:
Uncaught TypeError: Cannot read property 'setState' of null
I don't know where I am going wrong, could someone point me in the right direction please.
Here's my code:
export default React.createClass({
getInitialState: function () {
return {
name: '',
address: '',
phone: '',
email: '',
}
},
componentWillMount(){
this.getUserDetails();
},
getUserDetails: function(){
var personID = 'ABC123';
if(personID.length > 0){
new Firebase('https://xxxxxxxxxx.firebaseio.com/users/' + personID).on('value', function(snap) {
this.setState({
name: snap.val().Name + " " +snap.val().Surname
});
});
}
},
render() {
return ( ... );
}
});

Like people have been saying above, if you just edit this to an arrow function it will change the context of this from Firebase to the outer scope - which is the component.
new Firebase('https://xxxxxxxxxx.firebaseio.com/users/' + personID).on('value', (snap) => {
this.setState({
name: snap.val().Name + " " +snap.val().Surname
});
});

This is happening because the context of this is not the component anymore. You need this of the component. Check how I grab this of the component.
export default React.createClass({
getInitialState: function () {
return {
name: '',
address: '',
phone: '',
email: '',
}
},
componentWillMount(){
this.getUserDetails();
},
getUserDetails: function(){
var that = this
var personID = 'ABC123';
if(personID.length > 0){
new Firebase('https://xxxxxxxxxx.firebaseio.com/users/' + personID).on('value', function(snap) {
that.setState({
name: snap.val().Name + " " +snap.val().Surname
});
});
}
},
render() {
return ( ... );
}
});

Related

functionally combine list of same object

I have a set of alerts that I need to combine and output. I'm struggling to see how I can do this functionally. I have everything I need I just want to combine format a little and output.
orderedStatuses contains a set of alerts
data class Alert(
val status: String,
val recordId: String
)
This is what I'm currently returning
Alerts:
Status1 :
000000000000
Status1 :
111111111111
Status2 :
222222222222
Status2 :
333333333333
Status3 :
444444444444
Status3 :
555555555555
this is what I want:
Alerts:
status1 :
('00000', '111111')
status2 :
('222222', '333333')
status3 :
('444444', '55555')
current code:
val alert = if (orderedStatuses.isEmpty()) {
"No alerts found for status"
} else {
"Records:\n" + orderedStatuses.joinToString("\n") { it ->
"\t${it.status} : \n" + it.recordId
}
}
data class Alert(
val status: String,
val recordId: String
)
val alerts = listOf(
Alert("Status1", "00000"),
Alert("Status1", "111111"),
Alert("Status2", "222222"),
Alert("Status2", "333333"),
Alert("Status3", "444444"),
Alert("Status3", "55555")
)
alerts
.groupBy { it.status }
.map { map -> map.key + " : \n('" + map.value.joinToString("', '") { it.recordId } + "')\n" }
.forEach { print(it) }
This will print:
Status1 :
('00000', '111111')
Status2 :
('222222', '333333')
Status3 :
('444444', '55555')
This might be more readable:
alerts
.groupBy(Alert::status)
.map { (key, value) ->
key + " : \n('" + value.joinToString("', '", transform = Alert::recordId) + "')\n"
}
.forEach(::print)
Detailed example on Kotlin Playground

What is the default value for spark.sql.columnNameOfCorruptRecord?

I have read the documentation but can not get spark.sql.columnNameOfCorruptRecord default value even with google searching.
The second question - how PERMISSIVE mode works when spark.sql.columnNameOfCorruptRecord is empty or null?
According to the code (19/01/2021) it's _corrupt_record:
val COLUMN_NAME_OF_CORRUPT_RECORD = buildConf("spark.sql.columnNameOfCorruptRecord")
.doc("The name of internal column for storing raw/un-parsed JSON and CSV records that fail " +
"to parse.")
.version("1.2.0")
.stringConf
.createWithDefault("_corrupt_record")
Regarding how PERMISSIVE mode works, you can see this in FailSafeParser[T]:
def parse(input: IN): Iterator[InternalRow] = {
try {
rawParser.apply(input).toIterator.map(row => toResultRow(Some(row), () => null))
} catch {
case e: BadRecordException => mode match {
case PermissiveMode =>
Iterator(toResultRow(e.partialResult(), e.record))
case DropMalformedMode =>
Iterator.empty
case FailFastMode =>
throw new SparkException("Malformed records are detected in record parsing. " +
s"Parse Mode: ${FailFastMode.name}. To process malformed records as null " +
"result, try setting the option 'mode' as 'PERMISSIVE'.", e)
}
}
private val toResultRow: (Option[InternalRow], () => UTF8String) => InternalRow = {
if (corruptFieldIndex.isDefined) {
(row, badRecord) => {
var i = 0
while (i < actualSchema.length) {
val from = actualSchema(i)
resultRow(schema.fieldIndex(from.name)) = row.map(_.get(i, from.dataType)).orNull
i += 1
}
resultRow(corruptFieldIndex.get) = badRecord()
resultRow
}
} else {
(row, _) => row.getOrElse(nullResult)
}
}
If it isn't specified, it'll fallback to the default value defined in the configuration.

OrientDB - don't release memory after insert

I use NodeJS for insert 8.000.000 records into my orientdb database, but after about 2.000.000 insert records my app is stopped and show error "Java Heap".
Is there a way for release memory after every record inserted?
Ram usage:
-befor start app: 2.6g
-after insert 2milions records: 7.6g
My app.js (NodeJS):
var dbConn = [];
var dbNext = 0;
var dbMax = 25;
for (var i = 0; i <= dbMax; i++) {
var db = new ODatabase({
host: orientdb.host,
port: 2424,
username: 'root',
password: orientdb.password,
name: 'test',
});
dbConn.push(db);
}
//---------------------------------------------------
//Start loop
// record = {name: 'test'}
record["#class"] = "table";
var db = nextDB();
db.open().then(function () {
return db.record.create(record);
}).then(function (res) {
db.close().then(function () {
//----resume loop
});
}).error(function (err) {
//------
});
// end loop - iteration loop
//---------------------------------------------------
function nextDB() {
if (++dbNext >= dbMax) {
dbNext -= dbMax;
}
return dbConn[dbNext];
}
OrientJS wasn't efficient for insert massive data from SqlServer to OrientDB. I used ETL module for massive insert, that is fastest way and good idea for transpot massive data without increase memory more than 2GB.
I could transported 7.000 records per minute.
My ETL's config.json:
{
"config": {
log : "debug"
},
"extractor" : {
"jdbc": { "driver": "com.microsoft.sqlserver.jdbc.SQLServerDriver",
"url": "jdbc:sqlserver://10.10.10.10;databaseName=My_DB;",
"userName": "sa",
"userPassword": "123",
"query": "select * from My_Table"
}
},
"transformers" : [
{ "vertex": { "class": "Company"} }
],
"loader" : {
"orientdb": {
"dbURL": "plocal:D:\DB\Orient_DB",
dbUser: "admin",
dbPassword: "admin",
"dbAutoCreate": true,
"tx": false,
"batchCommit": 1000,
"wal" : false,
"dbType": "graph"
}
}
}
From the documentation, for massive insertion you should declare your intention :
db.declareIntent( new OIntentMassiveInsert() );
// YOUR MASSIVE INSERTION
db.declareIntent( null );
But by now it seems not implemented in orientJS driver.
Another thing is that you should not open/close your database for each new record created. This is in general bad practise.
I do not have the node.js environment by now but something like this should do the trick:
db.open().then(function () {
// when available // db.declareIntent( new OIntentMassiveInsert() );
for (var i = 0; i < 8000000; i++) {
// create a new record
myRecord = { "#class" : "myClass", "attributePosition" : i };
db.record.create(myRecord);
}
// when available // db.declareIntent( null );
}).then(function () { db.close() });

Making an AJAX POST on websocket message is causing timeout exceptions

So I have a program that basically allows two users two chat back and forth and do other things via websocket with javascript and java server endpoints. When one of the users presses a button I have a listener that fires off a message to the other user which invokes a function. During this function I want to be able to call an AJAX POST with JQuery to update my database but this is causing a java.util.concurrent.TimeoutException. Any idea why this occurs? I imagine it has something to do with the fact that the websocket connection doesn't stay open long enough for the ajax call to go through.
So I've done the research and I've seen that websocket and AJAX are not exactly something that should be mixed (I think). However I can't seem to figure out an alternative even to update my database. There is a lot of code for this so I will try and only post the important parts.
Here is the part of the code for when the button is pressed (it is an agree button so both users must have pressed it hence the '**' and '--' characters).
fAgree.addEventListener("click", function() {
// selects this button
if (aStr == "**" && (yStr == "**" || oStr == "**")) {
if (fStr == "--") {
fStr = "*-";
//redirect to another page
} else if (fStr == "-*") {
fStr = "**";
if(secondTransaction == false) {
var firstCoordUpload = document.getElementById("yourPos").innerHTML;
var secondCoordUpload = document.getElementById("othersPos").innerHTML;
var firstLatUpload = parseFloat(firstCoordUpload.split(",")[0]);
var firstLonUpload = parseFloat(firstCoordUpload.split(",")[1]);
$.ajax({
url: "../../309/T11/setSaleData/" + getURLParameter("saleID") + "/" + firstLatUpload + "/" + firstLonUpload + "/" + firstCoordUpload + "/" + secondCoordUpload + "/" + secondSeller,
type: "POST",
headers: {
"Authorization" : getCredentials(),
},
success: function (result) {
window.location.href = '../../frontEnd/profilePage/index.html?username='+ getUsername();
console.log(result);
},
error: function (dc, status, err) {
console.log(err);
console.log(status);
}
});
}
}
agreeBut.socket.send("a,f");
htmlChange(fStr, fStar);
}
});
Here is the part of the code that is called at the end of the code above (the agreeBut.socket.send()).
agreeBut.socket.onmessage = function(message) {
// check [0]: a for agree buttons,
// m for map,
// l of location buttons,
// t for trade
var mess = message.data.split(",");
if (mess[0] == "a") {
// second a shows the agree button was pressed, changes aStr
// accordingly and displays
if (mess[1] == "a") {
if (aStr == "--") {
aStr = "-*";
} else if (aStr == "*-") {
aStr = "**";
}
htmlChange(aStr, aStar);
// shows the final agree button has been pressed, changes fStr
// accordingly and displays
} else if (mess[1] == "f") {
if (fStr == "--") {
fStr = "-*";
//redirect
} else if (fStr == "*-") {
fStr = "**";
alert("on this");
if(secondTransaction == true) {
alert("doing it");
var firstCoordUpload = document.getElementById("yourPos").innerHTML;
var secondCoordUpload = document.getElementById("othersPos").innerHTML;
var firstLatUpload = parseFloat(firstCoordUpload.split(",")[0]);
var firstLonUpload = parseFloat(firstCoordUpload.split(",")[1]);
$.ajax({
url: "../../309/T11/setSaleData/" + getURLParameter("saleID") + "/" + firstLatUpload + "/" + firstLonUpload + "/" + firstCoordUpload + "/" + secondCoordUpload + "/" + secondSeller,
type: "POST",
headers: {
"Authorization" : getCredentials(),
},
success: function (result) {
console.log(result);
alert("Got it");
window.location.href = '../../frontEnd/profilePage/index.html?username='+ getUsername();
},
error: function (dc, status, err) {
console.log(err);
console.log(status);
}
});
}
//window.location.href = '../../frontEnd/profilePage/index.html?username='+ getUsername();
}
htmlChange(fStr, fStar);
}
}
};
It turns out I was getting this problem because of the timeout that was set on my java ServerEndpoint. In the class I used the setMaxIdleTimeout(0) function on the session variable to have no idle timeout. This seemed to solve my problem (however I feel like this is really just a workaround for poor websocket and ajax implementation on my end).

jQuery Select2 and Struts 2 JSON plugin

I'm trying to populate with Struts2 JSON and Select2 a select. Server is returning a JSON like this:
{"orphanets":[{"idDiagOrphanet":11509,"nomDiagOrphanet":"FACOMATOSIS CESIOFLAMMEA"},{"idDiagOrphanet":21782,"nomDiagOrphanet":"AUTOINFLAMMATION"}]}
How can I format/parse the result to make it work? I know it expects id and text fields, but cant get it working:
$("#selCodOrphanet").select2({
quietMillis: 300,
placeholder: "Buscar diag. Orphanet...",
minimumInputLength: 4,
ajax: {
url: '../json/getOrphanets',
dataType: 'json',
data: function (term, page) {
return {
term: term
};
},
results: function (data, page) {
return { results: data.orphanets };
},
id: function(item) {
return item.idDiagOrphanet;
},
formatResult: function(item) {
return "<div class='select2-user-result'>" + item.nomDiagOrphanet + "</div>";
}
}
});
I tried a bit searching but didn't found id: function(item) {
Anyways, here's a quick-fix
Consider the response as a normal string
replace idDiagOrphanet with id and nomDiagOrphanet with text and then return this string instead of return { results: data.orphanets };
Here's another way :
Modifying a JSON object by creating a New Field using existing Elements
var ornts= data.orphanets;
var new_obj ;
for(var i=0; i<data.orphanets.length; i++){
var person = persons[i];
new_obj.push({
id: ornts.idDiagOrphanet,
text: ornts.nomDiagOrphanet,
});
}
return new_obj;
Try
$("#selCodOrphanet").select2({
placeholder: "Buscar diag. Orphanet...",
minimumInputLength: 4,
ajax: {
url: '<s:url namespace="/json" action="getOrphanets"/>',
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term
};
},
results: function (data, page) {
return { results: data.orphanets };
},
id: function(item) {
return item.idDiagOrphanet;
},
formatResult: function(item) {
return "<div class='select2-user-result'>" + item.nomDiagOrphanet + "</div>";
}
escapeMarkup: function (m) { return m; }
}
});
Added the qualified URL mapping to getOrphanets action with namespace /json. Corresponding configuration should be made. Don't escape markup since you are displaying HTML in results.

Categories

Resources