ion-input type number becomes unresponsive when holding down the delete key on device - html

I'm having an issue with an ion-input, which drops this error below when holding down the delete key.
"Error: Invalid argument '' for pipe 't'
at new Error (native)
at Error.v (file:///android_asset/www/build/polyfills.js:3:4864)
at e [as constructor] (file:///android_asset/www/build/main.js:94:11171)
at new e (file:///android_asset/www/build/main.js:14:10469)
at n (file:///android_asset/www/build/main.js:9:10302)
at t.transform (file:///android_asset/www/build/main.js:9:11000)
at file:///android_asset/www/build/main.js:1:17764
at e.detectChangesInternal (file:///android_asset/www/build/main.js:125:10032)
at e.t.detectChanges (file:///android_asset/www/build/main.js:4:8847)
at e.t.internalDetectChanges (file:///android_asset/www/build/main.js:4:8640)
at e.detectChangesInternal (file:///android_asset/www/build/main.js:120:27362)
at e.t.detectChanges (file:///android_asset/www/build/main.js:4:8847)
at t.detectChangesInNestedViews (file:///android_asset/www/build/main.js:4:28534)
at e.detectChangesInternal (file:///android_asset/www/build/main.js:80:24234)
at e.t.detectChanges (file:///android_asset/www/build/main.js:4:8847)", source: file:///android_asset/www/build/main.js (29)
This one below is my ion-input:
<ion-input color="primary_light" [(ngModel)]="montco_ui" type="number
(keyup)="formataNumero()"></ion-input>
Also, I'm using this algorithm to handle 2 decimal places, which is working fine, since I guess the issue is related to the type number property on the ion-input.
formataNumero(separador: string = '.', decimais: number = 2) {
console.log('formataNumero called');
let a: any = this.montco_ui.split('');
let ns: string = '';
a.forEach((c: any) => { if (!isNaN(c)) ns = ns + c; });
ns = parseInt(ns).toString();
if (ns.length < (decimais + 1)) {
ns = ('0'.repeat(decimais + 1) + ns);
ns = ns.slice((decimais + 1) * -1);
}
let ans = ns.split('');
let r = '';
for (let i = 0; i < ans.length; i++)
if (i == ans.length - decimais) {
r = r + separador + ans[i]; else r = r + ans[i];
}
this.montco_ui = r;
}
Finally, this is the variable that keeps the value:
P.S.: I'm using Ionic 2 for my project.
public montco_ui: string = "0.00";

Related

adding top 10 to a leveling system leaderboard

So I'm trying to add top 10 for my leaderboard this is the code that I'm using for the leveling system and leaderboard but I dont know how to add the top 10 and I need it because when you type the command it just spams because a lot of people have talked so please help.
client.on("message", async (message) => {
if (message.author.bot) return;
if (message.channel.type === "dm") {
return;
}
const dm = client.users.cache.get(message.author.id);
if (!db[message.author.id])
db[message.author.id] = {
userid: message.author.id,
xp: 0,
level: 0,
};
db[message.author.id].xp++;
let userInfo = db[message.author.id];
if (userInfo.xp > 99) {
userInfo.level++;
userInfo.xp = 0;
dm.send(
new Discord.MessageEmbed()
.setTitle(
`${levelup}Level up${levelup}\n${levelup}Level: ${userInfo.level} ${levelup}`
)
.setColor("#E2DF09")
.setTimestamp()
);
}
if (
message.content.toLowerCase().startsWith(prefix + "rank") ||
message.content.toLowerCase().startsWith(prefix + "level")
) {
let userInfo = db[message.author.id];
let member = message.mentions.members.first();
let embed = new Discord.MessageEmbed()
.setColor("#E2DF09")
.addField("Level", `${info}` + userInfo.level + `${info}`)
.addField("XP", `${info}` + userInfo.xp + "/100" + `${info}`)
.setFooter(
`${message.author.tag}`,
`${message.author.avatarURL({ dynamic: true })}`
);
if (!member) return message.channel.send(embed);
let memberInfo = db[member.id];
let embed2 = new Discord.MessageEmbed()
.setColor("#E2DF09")
.addField("Level", `${info}` + memberInfo.level + `${info}`)
.addField("XP", `${info}` + memberInfo.xp + "/100" + `${info}`);
message.channel.send(embed2);
} else if (
message.content.toLowerCase().startsWith(prefix + "leaderboard") ||
message.content.toLowerCase().startsWith(prefix + "lb")
) {
const embed = new Discord.MessageEmbed()
.setTitle("Leaderboard")
.setColor("#E2DF09");
const c = Object.entries(db).sort((a, b, d) => b[1].level - a[1].level);
for (const [key, value] of c) {
embed.addField(
`\u200B`,
`<#${value.userid}>\nLevel: ${value.level} | XP: ${value.xp}`
);
}
message.channel.send(embed);
}
fs.writeFile("./db/database.json", JSON.stringify(db), (error) => {
console.error();
});
});
and also this is how the json file looks like
I use the userid for the leaderboard tag
{"630812692659044352":{"userid":"630812692659044352","xp":31,"level":32}
This is how the leaderboard looks like but I want to add the numbers next to the username and for the 1st, 2nd, 3rd i want to add like a trophy or something but its not working out on my side .
Here is something I think would work (I tested it on an online site)
var ranks = {
'SOMEUSERID': {
userid: 'SOMEUSERID',
rank: 0,
xp: 45
},
'ANOTHERUSERID': {
userid: 'THEUSERID',
rank: 0,
xp: 70
}
}
//^^EXAMPLE RANKS, DONT ADD THESE^^
var leaderboard = []
for(const i in ranks) {
var person = ranks[i];
leaderboard.push(person)
}
//^^LOOP THROUGH ALL USERS^^
leaderboard.sort((b, a) => ((a.rank+1)*(a.xp)) - ((b.rank+1)*(b.xp)))
//^^SORT BY (RANK+1)*XP, in descending order^^
var ranksSorted = leaderboard.map(u => u.rank);
var xpSorted = leaderboard.map(u => u.xp)
var usersSorted = leaderboard.map(u => u.userid)
//ranksSorted, xpSorted, and usersSorted are synced
//...
//top 10 leaderboard within one string
var str = '';
for(let i = 0; i<=10 && i<leaderboard.length;i++) {
str += usersSorted[i] + '\n' + ranksSorted[i] + ' | ' + xpSorted[i] + '\n'
//YOU CAN ALSO ACCESS WHICH PLACE THEY ARE WITH i+1
}
So you don’t have to save it on string, instead of adding it to the string, you can do add embed field, like this:
for(let i = 0; i<=10 && i<leaderboard.length;i++) {
someEmbed.addField(client.users.cache.get(usersSorted[i]).tag, ranksSorted[i] + ' | ' + xpSorted[i])
}
EDIT: rank*xp wouldn’t work well. 1*28 for example is more than 2*13. Do Math.pow().
leaderboard.sort((b, a) => ((a.rank+1)*(a.xp)) - (Math.pow((b.rank+1), 10)*(b.xp)))
//instead of the previous leaderboard.sort
This way, rank 1 xp 99 is less than rank 2 xp 1

how to get real direction steps using Flutter? (draw real route)

I'm working with taxi app. Is it possible to draw real route on real road using flutter?
I used this way: https://developers.google.com/maps/documentation/directions/intro#ExampleRequests
getDirectionSteps(double destinationLat, double destinationLng) {
network
.get("origin=" +
location.latitude.toString() +
"," +
location.longitude.toString() +
"&destination=" +
destinationLat.toString() +
"," +
destinationLng.toString() +
"&key=api_key")
.then((dynamic res) {
List<Steps> rr = res;
print(res.toString());
ccc = new List();
for (final i in rr) {
ccc.add(i.startLocation);
ccc.add(i.endLocation);
}
mapView.onMapReady.listen((_) {
mapView.setMarkers(getMarker(location.latitude,location.longitude,destinationLat,destinationLng));
mapView.addPolyline(new Polyline("12", ccc, width: 15.0));
});
_screenListener.dismissLoader();
showMap();
}).catchError((Exception error) => _screenListener.dismissLoader());
}
my output look like this:
But I need like this: (draw destination route on real road)
to find the exact route you have to get points out of the polylineoverview from the json from directions api.
This is how I extracted the exact route just like you show in the second image.
Its is a function that return points as a string
Future<String> getRouteCoordinates(LatLng l1, LatLng l2) async {
String url =
"https://maps.googleapis.com/maps/api/directions/json?origin=${l1.latitude},${l1.longitude}&destination=${l2.latitude},${l2.longitude}&key=${Constants.anotherApiKey}";
http.Response response = await http.get(url);
Map values = jsonDecode(response.body);
ProjectLog.logIt(TAG, "Predictions", values.toString());
return values["routes"][0]["overview_polyline"]["points"];
}
you will get a string of points somewhat similiar to this
u|umDs`gwML}A_GGgFGAWwDEm#TcFGsAAa#BeA\QDe#AYISOKHKJGFw#^?jAAnAEnOA|GAhHEx#?jA#tC?XFLLf#Bf##t#?xAA|E?dEEj_#GxMChG#tCIvl##tAK`DQlA?zBApE?lBExNAlH#rMAtGJdDJnATfB`AnEdAzEj#~B|#lEF\xAvGnAlF~#lEv#`DvAxFxAxGzCdN`H`ZnEnRr#hDnB|IhDlNvKnd#vDhPrFzUzGjYxBtH|#hCdAzBXl#fAhBtAtBjBhCfArAdAhAvBtBlB|AjGfFhLzJfEzDzCvDz#pA`BpC`ApBbAzBxCrIr#rBjNta#x#nBbAlBzCbI|R|j#hA`FBVC`ASpD?lA[FiMpCaBVgABiAPoE~#cIdBiLfCcHdBsCl#yJvBmDt#y#l#{#X_#P[VGJGZCd#r#tCf#rBTbAV`BB`#?n#GdA#XHj#bAxBl#hBPjADf#?v#Ej#Ml#Ut#[r#]h#sA`C{#lAMZGl#KjECbDGhBuGMsJKcCGw#CqJCiECAd#ALoBbKs#jDM^x#j#vPfLvCnB~DnCx#f#R#RAd#GDIbBmDv#y#LId#On#A~EJX#pDJrADb#QFC
Now you will add the polyline in the set of polylines like this
_polyLines.add(Polyline(
polylineId: PolylineId(Constants.currentRoutePolylineId),//pass any string here
width: 3,
geodesic: true,
points: Utils.convertToLatLng(Utils.decodePoly(encodedPoly)),
color: ConstantColors.PrimaryColor));
here encodedPoly is the same string that extracted from previous method.
In the function above you have to convert the points\encodedPoly into the list of latlng. Like i did using utils function.
Both functions that i used are
decodePoly :
// !DECODE POLY
static List decodePoly(String poly) {
var list = poly.codeUnits;
var lList = new List();
int index = 0;
int len = poly.length;
int c = 0;
// repeating until all attributes are decoded
do {
var shift = 0;
int result = 0;
// for decoding value of one attribute
do {
c = list[index] - 63;
result |= (c & 0x1F) << (shift * 5);
index++;
shift++;
} while (c >= 32);
/* if value is negative then bitwise not the value */
if (result & 1 == 1) {
result = ~result;
}
var result1 = (result >> 1) * 0.00001;
lList.add(result1);
} while (index < len);
/*adding to previous value as done in encoding */
for (var i = 2; i < lList.length; i++) lList[i] += lList[i - 2];
print(lList.toString());
return lList;
}
and convertToLatLng() :
static List<LatLng> convertToLatLng(List points) {
List<LatLng> result = <LatLng>[];
for (int i = 0; i < points.length; i++) {
if (i % 2 != 0) {
result.add(LatLng(points[i - 1], points[i]));
}
}
return result;
}
This would make a exact route like i did in my app :
Here is the screenshot :

In the Arduino IDE, why does the second call of a function change the previous call results?

I tried to write a function that converts a string of hex values into a string of Unicode UTF-8 characters. When this function is called once, everything is fine. But when the function is called twice in succession with the same or different arguments, both output strings are meaningless.
void HEX2String(String* HEXstr, String* str) {
String s2 = "", s3 = "";
long c, c1, c0;
char ch[2] = { 0 };
for (int i = 0; i <= HEXstr->length() - 4; i = i + 4) {
s2 = HEXstr->substring(i, i + 1) + "x" + HEXstr->substring(i + 1, i + 4);
c = (hex2long(&s2));
if (c < 255)
*str += String((char)c);
else {
c1 = (128 + (c & B111111));
c0 = (192 + (c >> 6));
ch[1] = c1;
ch[0] = c0;
str->concat(ch);
}
}
}
String str1 = "0628064700200646062706450020062E062F0627000A0633064406270645000A064806310648062F0020062806470020063306CC0633062A06450020062A064806330637";
String str = "0628064700200646062706450020062E062F0627000A0633064406270645000A064806310648062F0020062806470020063306CC0633062A06450020062A064806330637000A00730061006C0061006D0020006200610072002000730068006F006D0061";
String msg = "";
void setup() {
Serial.begin(9600);
//First call
HEX2String(&str, &msg);
Serial.println(msg);
msg = "";
//Second call
HEX2String(&str1, &msg);
Serial.println(msg);
}
void main() {
//
}
If I comment the second call, the output in the serial monitor is:
سلام
ورود به سیستم توسط
salam bar shoma
It is correct. If the second call is not commented, the output in the serial monitor is:
ب⸮⸮ه⸮⸮ ن⸮⸮ا⸮⸮م⸮⸮ خ⸮⸮د⸮⸮ا⸮⸮
س⸮⸮ل⸮⸮ا⸮⸮م⸮⸮
و⸮⸮ر⸮⸮و⸮⸮د⸮⸮ ب⸮⸮ه⸮⸮ س⸮⸮ی⸮⸮س⸮⸮ت⸮⸮م⸮⸮ ت⸮⸮و⸮⸮س⸮⸮ط⸮⸮
salam bar shomaب⸮⸮ه⸮⸮ ن⸮⸮ا⸮⸮م⸮⸮ خ⸮⸮د⸮⸮ا⸮⸮
س⸮⸮ل⸮⸮ا⸮⸮م⸮⸮
و⸮⸮ر⸮⸮و⸮⸮د⸮⸮ ب⸮⸮ه⸮⸮ س⸮⸮ی⸮⸮س⸮⸮ت⸮⸮م⸮⸮ ت⸮⸮و⸮⸮س⸮⸮ط⸮⸮
C-strings need to be null terminated. Your ch is not.
Define it as 3 characters:
char ch[3] = { 0 };
and add a null terminator:
ch[0] = c0;
ch[1] = c1;
ch[2] = 0;

Execute Code as Fast as Possible

I am using node.js with my WebStorm IDE to parse a large JSON file (~500 megabytes). Here is my code:
fs = require("fs");
fs.readFile('C:/Users/.../Documents/AAPL.json', 'utf8', function (err,data) {
for (i = 0; i < 1000; i++) {
var hex = JSON.parse(data)[i]._source.layers.data["data.data"];
var askPrice = parseInt(hex.substring(215, 239).split(":").reverse().join(""),16);
var bidPrice = parseInt(hex.substring(192, 215).split(":").reverse().join(""),16);
var symbol = hex.substring(156, 179);
var timestamp = hex.substring(132, 155);
var askSize = hex.substring(240, 251);
var bidSize = hex.substring(180, 191);
var price = String((+bidPrice+askPrice)/2);
var realprice = price.slice(0, price.length - 4) + "." + price.slice(price.length - 4);
function hex2a(hexx) {
var hex = hexx.toString();
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
if(JSON.parse(data)[i]._source.layers.data["data.len"] == 84 && realprice.length == 8 && +realprice <154 && +realprice >145) {
console.log(i + " " + hex2a(symbol.replace(/:/g, "")) + " sold for " + realprice + " at " + parseInt(timestamp.split(":").reverse().join(""), 16));
}
}
});
The problem I am running into however is that my IDE is parsing this file at an extremely slow speed, roughly 1 iteration a second. I do not think this is because I have a slow computer, for I have a high end rig with a core i7 7700k and a gtx 1070. I tried executing the code in the console with the same result. I tried trimming down the code and again I achieved the same speed:
fs = require("fs");
fs.readFile('C:/Users/Brandt Winkler Prins/Documents/AAPL.json', 'utf8', function (err,data) {
for (i = 0; i < 12000; i++) {
var hex = JSON.parse(data)[i]._source.layers.data["data.data"];
var askPrice = parseInt(hex.substring(215, 239).split(":").reverse().join(""),16);
var bidPrice = parseInt(hex.substring(192, 215).split(":").reverse().join(""),16);
var price = String((+bidPrice+askPrice)/2);
var realprice = price.slice(0, price.length - 4) + "." + price.slice(price.length - 4);
if(+realprice <154 && +realprice >145) {
console.log(realprice);
}
}
});
How should I execute my code to get my data as fast as possible?
You're running JSON.parse(data) every iteration, that might take quite some time for a 500MB json file.
The solution would be to move it out of the loop and reuse the parsed object:
var obj = JSON.parse(data);
for (...

json not matching model

In EXTJS i will use a model and store for my grid. Now is the problem that sometimes the json will not match the model. There will be less information then in my model. When this happens EXTJS will not show any data in the grid. So i looked for a fix and found this:
Ext.define('App.Reader', {
extend: 'Ext.data.reader.Json',
extractData: function(root) {
var me = this,
values = [],
records = [],
Model = me.model,
i = 0,
length = root.length,
idProp = me.getIdProperty(),
node, id, record;
if (!root.length && Ext.isObject(root)) {
root = [root];
length = 1;
}
for (; i < length; i++) {
node = root[i];
values = me.extractValues(node);
id = me.getId(node);
record = new Model(values, id, node);
records.push(record);
if (me.implicitIncludes) {
me.readAssociated(record, node);
}
}
return records;
},
extractValues: function(data) {
var fields = this.getFields(),
i = 0,
length = fields.length,
output = {},
field, value;
for (; i < length; i++) {
field = fields[i];
value = this.extractorFunctions[i](data);
if(value === undefined)
{
Ext.iterate(fields, function(key, val) {
if (data[key] === undefined & i==val) {
console.log( "Model field <" + key.name + "> does not exist in data/node.");
value = "INVALID OR MISSING FIELD NAME";
var p = 0;
for(var prop in data) {
if(p==i){
if(data.hasOwnProperty(prop))console.log("Instead of <" + key.name + "> we have <" + prop + "> with value <" + data[prop]+ ">");
}
p++;
}
}
}, this);
}
output[field.name] = value;
}
return output;
}
});
var myReader = new App.Reader({
type:'json'
});
i found this online. But when i use this with EXTJS 4.1.1 there is an error in ext-all: TypeError: j is undefined.
Where should i look for the fix for this?
There's no need to do something complicated to solve this trivial problem. Read up on Ext.data.Model and Ext.data.Field, configure your Model properly and you're all set.