I am using React-Native's Location.getCurrentPositionAsync() to retrieve a user's location when they arrive at a site and also when they depart from the site. However, even though the user is in the exact same location the geolocation data is different.
I am using BingMaps to pull the address and a map of the location and the address is sometimes several blocks away from the user's actual location. I set the location accuracy to LocationAccuracy.Highest but still get some odd results.
Any help fixing this is much appreciated!
`
export async function GetPosition() {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
console.log('Permission to access location was denied');
return;
}
return new Promise((resolve, reject) => {
Location.getCurrentPositionAsync({accuracy:LocationAccuracy.Highest}).then(pos => {
console.log(pos); resolve(getCoordsFromPosition(pos));
}, reject);
});
}
`
`
function getCoordsFromPosition(position) {
const coords = position.coords;
return coords;
}
`
function getAddressByPoint(address) {
const name = address.resourceSets[0].resources[0].name;
return name;
}
`
export async function FindLocationByPoint (latitude, longitude) {
return new Promise(async (resolve, reject) => {
await fetch("https://dev.virtualearth.net/REST/v1/Locations/"+ latitude + "," + longitude + "?key=" + bing_maps_key, {
method: 'GET',
headers: new Headers({
Accept: 'application/json'
}),
}).then(res => res.json()).then(data => {
console.log(data);
resolve(getAddressByPoint(data));
}, reject)
});
}
`
`
var startPos = await GetPosition().then((res) => startPos = res);
var startLoc = await FindLocationByPoint(startPos.latitude, startPos.longitude).then((data) => startLoc = data);
var stopPos = await GetPosition().then((res) => stopPos = res);
var stopLoc = await FindLocationByPoint(stopPos.latitude, stopPos.longitude).then((data) => stopLoc = data);
`
I tried setting location accuracy to the highest setting and expected accuracy within a few addresses but I am getting addresses several blocks away
In this scenario that are a couple of things that contribute to this situation:
Location sensor accuracy. The coordinates returned from the getCurrentPositionAsync and the highest setting is dependent on the sensors available on the end device (both physically, and connection at the time). GPS accuracy typically has an accuracy of 15 meters. While cell tower triangulation can is between 0.5KM and 1.5KM.
Reverse geocoders return an approximate address for a coordinate. The address accuracy is 100% dependent on the level of accuracy of the location data for the area the user is in. Most address location data in the word is approximated based on building number, and address ranges between "city blocks". For example, if a section of road has an address range of 1 and 100, a building with number 50 would be estimated to be positioned in the middle of that road section, but in reality, that may not be the case. In some parts of the world, "rooftop" accurate data is available. This type of data has a high accurate position for buildings (gathered either manually or through AI on street level imagery). Details on geographic coverage levels in Bing maps can be found here: https://learn.microsoft.com/en-us/bingmaps/coverage/geographic-coverage
Related
I'm using Tensorflow js in react native and I'm getting the correct predictions for my model but it takes a lot of time to give results. For eg I'm using a custom model created by me in teachable machine by Google. But the .datasync() takes time approx. 1 second whole to give results. This causes a physical lag in the camera I want to get results instantly. This is my code below: -
<TensorCamera
style={styles.camera}
flashMode={Camera.Constants.FlashMode.off}
type={Camera.Constants.Type.back}
resizeWidth={224}
resizeHeight={224}
resizeDepth={3}
onReady={handleCameraStream}
autorender={true}
/>
//
const handleCameraStream = (imageAsTensors) => {
try {
} catch (e) {
// console.log("Tensor 1 not found!");
}
const loop = async () => {
// && detected == true
if (model !== null) {
if (frameCount % makePredictionsEveryNFrames === 0) {
const imageTensor = imageAsTensors.next().value;
await getPrediction(imageTensor);
// .catch(e => console.log(e));
}
}
frameCount += 1;
frameCount = frameCount % makePredictionsEveryNFrames;
requestAnimationFrameId = requestAnimationFrame(loop);
};
loop();
//loop infinitely to constantly make predictions
};
//
const getPrediction = async (tensor) => {
// if (!videoLink) {
if (!tensor) {
console.log("Tensor not found!");
return;
}
//
const imageData2 = tensor.resizeBilinear([224, 224]);
// tf.image.resizeBilinear(tensor, [224, 224]);
const normalized = imageData2.cast("float32").div(127.5).sub(1);
const final = tf.expandDims(normalized, 0);
//
console.time();
const prediction = model.predict(final).dataSync();
console.timeEnd();
console.log("Predictions:", prediction);
}
I heard about using .data() instead of .datasync() but I don't know how to implement .data() in my current code. please help.
predict is what takes time - and that is really up to your model
maybe it can run faster on different backend (no idea which backend you're using, default for browsers would be webgl), but in reality it is what it is without rearchitecting the model items.
datasync simply downloads results from wherever tensors are (e.g. in gpu vram) to your variable in js.
yes, you could use data instead which is an async call, but difference is couple of ms at best - its not going to speed up model execution at all.
btw, you're not releasing tensors anywhere - your application has some serious memory leaks.
For a few days now i have been trying to extract images from a pdf, modify them, and then replace them in my pdf document. It works perfectly when working with jpeg images, but when it comes to png... I'm able to modify the image and then save it correctly, but when changing the buffer in the pdf, it turns all black. So there's my code :
try {
(async () => {
let imageData = imgTab.type === 'jpg' ? imgTab.data : await savePng(imgTab);
console.log(imgTab.type);
let typeJimp = "image/png";
if(imgTab.type === 'jpg'){
typeJimp = "image/jpeg";
}
const img = await Jimp.read(imageData).then(async function (image) {
image.color([
{ apply: 'hue', params: [90] }]);
*//HERE, the image saved is okay! It is modified as I want it to be*
image.write("testimage"+objIdx+"."+imgTab.type);
let data = fs.readFileSync("testimage"+objIdx+"."+imgTab.type);
let bufferData = Buffer.from(data);
*//The problem is when i do this to replace the buffer of my original image*
pdfObject.contents = bufferData;
fs.writeFileSync('client/public/test_modified.pdf', await pdfDoc.save());
}).catch(function (err) {
//return Promise.reject(err);
console.log(err);
});
})();
}
The main code to extract the images can be found here : pdf-lib extract images
I don't know if there's something special to do to make the buffer work, but if you do, feel free :)
Thanks in advance !
////
Okay, so for now, i just use it that way :
const img = await Jimp.read(imageData).then(async function (image) {
image.color([
{ apply: 'hue', params: [90] }]);
let data = await image.getBufferAsync('image/jpeg')
var res = await pdfDoc.embedJpg(data);
res.ref = pdfRef;
var test = await res.embed();
fs.writeFileSync('client/public/test_modified.pdf', await pdfDoc.save());
})
My pdfRef is the ref of the initial object i was trying to modify.
I’m currently making a bot that informs me when a card is moved to the list titled Passed Applications.
I have already made the code and it basically sends a message once a card is moved to the specific list, however, it will randomly send a message and pull a card minutes/hours after it has already been pulled and sent the message.
What I’ve done so far is:
trello.js
var Trello = require("node-trello"),
EventEmitter = require("events").EventEmitter,
extend = require("extend"),
config,
trello,
timer,
e;
module.exports = function(options) {
var defaults = {
pollFrequency: 1000 * 60,
minId: 0,
trello: {
key: "",
token: "",
boards: []
},
start: true
};
e = new EventEmitter();
config = extend(true, defaults, options);
trello = new Trello(
process.env.TRELLO_API_KEY,
process.env.TRELLO_OAUTH_TOKEN
);
if (config.start) {
process.nextTick(function() {
start(config.pollFrequency, true);
});
}
function start(frequency, immediate) {
if (timer) {
return;
}
frequency = frequency || config.pollFrequency;
timer = setInterval(poll, frequency);
if (immediate) {
poll();
}
}
function poll() {
config.trello.boards.forEach(function(boardId) {
getBoardActivity(boardId);
});
}
function getBoardActivity(boardId) {
trello.get("/1/boards/" + boardId + "/actions", function(err, resp) {
if (err) {
return e.emit("trelloError", err);
}
var boardActions = resp.reverse();
var actionId;
for (var ix in boardActions) {
actionId = parseInt(boardActions[ix].id, 16);
if (actionId <= config.minId) {
continue;
}
var eventType = boardActions[ix].type;
e.emit(eventType, boardActions[ix], boardId);
}
config.minId = Math.max(config.minId, actionId);
e.emit("maxId", config.minId);
});
}
index.js
const conf = JSON.parse(fs.readFileSync("trelloconfig.json"));
let latestActivityID = fs.existsSync("./latestActivityID") ?
fs.readFileSync("./latestActivityID") :
0;
const eventEnabled = type =>
conf.enabledEvents.length > 0 ? conf.enabledEvents.includes(type) : true;
const TrelloEvents = require("./trello.js");
const events = new TrelloEvents({
pollFrequency: 60000,
minId: latestActivityID,
start: false,
trello: {
boards: conf.boardIDs,
key: process.env.TRELLO_API_KEY,
token: process.env.TRELLO_OAUTH_TOKEN
}
});
client.on("ready", () => {
events.start();
console.log(`[STATUS CHANGE] ${client.user.username} is now online.`);
client.user.setActivity("Cookout Grill");
});
events.on("updateCard", (event, board) => {
if (event.data.old.hasOwnProperty("idList")) {
if (!eventEnabled(`cardListChanged`)) return;
if (event.data.listAfter.name === "Passed Applications") {
let robloxId = event.data.card.name.split(" | ")[0];
client.channels.get("730839109236424756").send(robloxId);
if (database.find(x => x.RobloxUser === robloxId)) {
let data = database.find(x => x.RobloxUser === robloxId);
const person = client.users.get(data.DiscordID);
let embed = new discord.RichEmbed()
.setThumbnail(
"https://www.roblox.com/bust-thumbnail/image?userId=" +
data.RobloxID +
"&width=420&height=420&format=png"
)
.setTitle("APPLICATION RESULTS | Passed")
.setColor("3ef72d")
.setFooter("Cookout Grill", client.user.avatarURL)
.setDescription(
"Greetings, **" +
data.RobloxUser +
"**!\n\nAfter extensive review by our Management Team, we have decided to accept your Trainee Application at Cookout Grill. We believe that your application showed that you’re ready to become a staff member at our establishment.\n\nWe would like to congratulate you on passing your Trainee Application. Your application met our critical expectations and requirements in order to pass.\n\nIn order to work your way up throughout the staff ranks, you must attend a training at [Cookout Grill’s Training Center](https://www.roblox.com/groups/5634772/Cookout-Grill#!/about) during the specific session times. If you’re unable to attend one of our designated sessions, feel free to schedule a private session with a member of our Management Team.\n\nWe wish you the best of luck in continuing throughout the staff ranks at Cookout Grill. If you have any further questions, please do not hesitate to create a ticket in our main Discord Server."
)
.addField("**NEW RANK**", "`Trainee`");
person.send(embed);
roblox.message(
event.data.card.name.split(" | ")[1],
"APPLICATION RESULTS | Passed",
"Greetings, **" +
data.RobloxUser +
"**!\n\nAfter extensive review by our Management Team, we have decided to accept your Trainee Application at Cookout Grill.\n\nWe would like to congratulate you on passing your Trainee Application. Your application met our critical expectations and requirements in order to pass.\n\nIn order to work your way up throughout the staff ranks, you must attend a training at Cookout Grill’s Training Center during the specific session times. If you’re unable to attend one of our designated sessions, feel free to schedule a private session with a member of our Management Team.\n\nWe wish you the best of luck in continuing throughout the staff ranks at Cookout Grill."
);
}
let embed2 = new discord.RichEmbed()
.setTitle(`Card list changed!`)
.setDescription(
`**CARD:** ${
event.data.card.name
} — **[CARD LINK](https://trello.com/c/${
event.data.card.shortLink
})**\n\n**EVENT:** Card moved to list __${
event.data.listAfter.name
}__ from list __${event.data.listBefore.name}__ by **[${
conf.realNames
? event.memberCreator.fullName
: event.memberCreator.username
}](https://trello.com/${event.memberCreator.username})**`
);
client.channels.get("730839109236424756").send(embed2);
Trello.addCommentToCard(
event.data.card.id,
"User has been ranked.",
function(error, trelloCard) {
console.log(error);
}
);
} else return;
} else return;
});
I use the code proposed as an example in the documentation for Domino AppDev Pack 1.0.4 , the only difference is the reading of a text file (body.txt) as a buffer, this file containing only simple long text (40Ko).
When it is executed, the document is created in the database and the rest of the code does not return an error.
But finally, the rich text field was not added to the document.
Here the response returned:
response: {"fields":[{"fieldName":"Body","unid":"8EA69129BEECA6DEC1258554002F5DCD","error":{"name":"ProtonError","code":65577,"id":"RICH_TEXT_STREAM_CORRUPT"}}]}
My goal is to write very long text (more than 64 Ko) in a rich text field. I use in the example a text file for the buffer but it could be later something like const buffer = Buffer.from ('very long text ...')
Is this the right way or does it have to be done differently ?
I'm using a Windows system with IBM Domino (r) Server (64 Bit), Release 10.0.1FP4 and AppDevPack 1.0.4.
Thank you in advance for your help
Here's code :
const write = async (database) => {
let writable;
let result;
try {
// Create a document with subject write-example-1 to hold rich text
const unid = await database.createDocument({
document: {
Form: 'RichDiscussion',
Title: 'write-example-1',
},
});
writable = await database.bulkCreateRichTextStream({});
result = await new Promise((resolve, reject) => {
// Set up event handlers.
// Reject the Promise if there is a connection-level error.
writable.on('error', (e) => {
reject(e);
});
// Return the response from writing when resolving the Promise.
writable.on('response', (response) => {
console.log("response: " + JSON.stringify(response));
resolve(response);
});
// Indicates which document and item name to use.
writable.field({ unid, fieldName: 'Body' });
let offset = 0;
// Assume for purposes of this example that we buffer the entire file.
const buffer = fs.readFileSync('/driver/body.txt');
// When writing large amounts of data, it is necessary to
// wait for the client-side to complete the previous write
// before writing more data.
const writeData = () => {
let draining = true;
while (offset < buffer.length && draining) {
const remainingBytes = buffer.length - offset;
let chunkSize = 16 * 1024;
if (remainingBytes < chunkSize) {
chunkSize = remainingBytes;
}
draining = writable.write(buffer.slice(offset, offset + chunkSize));
offset += chunkSize;
}
if (offset < buffer.length) {
// Buffer is not draining. Whenever the drain event is emitted
// call this function again to write more data.
writable.once('drain', writeData);
}
};
writeData();
writable = undefined;
});
} catch (e) {
console.log(`Unexpected exception ${e.message}`);
} finally {
if (writable) {
writable.end();
}
}
return result;
};
As of appdev pack 1.0.4, the rich text stream accepts writing data of valid rich text cd format, in the LMBCS character set. We are currently working on a library to help you write valid rich text data to the stream.
I'd love to hear more about your use cases, and we're excited you're already poking around the feature! If you can join the openntf slack channel, I usually hang out there.
I'm trying to add data to my "data" returned in express. Here my snippet, I'm trying to add currentPage and count variables:
app.get("/blog/page/:pageTargeted", (req,res) => {
var rangeScoped = (req.params.pageTargeted * 8);
Posts.find().sort({ date: -1}).skip(rangeScoped).limit(8).exec(function (err, data) {
data.currentPage= req.params.pageTargeted || 1 ;
data.count = Posts.estimatedDocumentCount();
if (err) return console.error(err);
console.log(data);
res.status(200).send(data)
})
});
I have also tried:
currentPage= req.params.pageTargeted || 1 ;
count = Posts.estimatedDocumentCount();
if (err) return console.error(err);
console.log(data);
res.status(200).send(data currentPage, count)
It doesn't works, currentPage and count aren't add in the res.send toward the browser. I have just the data corresponding to the database get's request. So what it going wrong ? I just can't figure out it. Because to me I have well injected the data into the object so, it should works. If anybody has an hint, would be great.
If I am right data is an array and you can't create a new key in array like that. Try sending an Object instead.
app.get("/blog/page/:pageTargeted", (req,res) => {
var rangeScoped = (req.params.pageTargeted * 8);
Posts.find().sort({ date: -1}).skip(rangeScoped).limit(8).exec(function (err, data) {
if (err) return console.error(err);
console.log(data);
res.status(200).json({data: data, currentPage: req.params.pageTargeted || 1, count: Posts.estimatedDocumentCount()})
})
});