Nativescript OCR fails with generic error - ocr

I am trying to use the nativescript-ocr plugin, and keep on getting this error message
CONSOLE ERROR file:///app/newcard/newcard.component.js:133:34: {
"error": "Recognize failed, check the log for possible details."
}
It is very unhelpful, and i have been stuck on it for too long.
Bellow you can see how i am implementing the ocr:
doRecognize(source: string): void {
console.log({source});
let img: ImageSource = new ImageSource()
img.fromResource(source).then((success: boolean) => {
if (success) {
this.ocr.retrieveText({
image: img,
language: 'eng',
onProgress: (percentage: number ) => {
console.log(`Decoding progress: ${percentage}%`);
}
}).then(
(result: RetrieveTextResult) => {
console.log(`Result: ${result.text}`);
},
(error) => {
})
}
});
}
The source string looks like so:
CONSOLE LOG file:///app/newcard/newcard.component.js:122:20: {
"source":
"file:///Users/georgekyr/Library/Developer/CoreSimulator/Devices/0723299A-7C8B-40C3-AE74- FEE8E08BB52D/data/Media/DCIM/100APPLE/IMG_0007.PNG"
}
Looking around, I find that there are cases wehere the folder app/tesseract/tessadata was created in the wrong way, so i have double checked that the folder exists in the right place with the right data in it.

Related

Get array inside JSON API response

I'm trying to make an application with both front-end and back-end. I have finished both, but now I'm having some trouble trying to connect them. I keep getting this error:
catalog.component.ts:45 ERROR Error: NG0900: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
at DefaultIterableDiffer.diff (core.mjs:28514:19)
First, I'm trying to get the array response, where the products are located:
product.service.ts
public getAll(): Observable<Product[]> {
return this.http.get<Response["response"]>(this.productsUrl);
}
This method receives the following response:
{
"httpCode": 200,
"message": "OK",
"response": [
{
"pieceName": "Mini Figure Trophy",
"pieceImageURL": "https://www.lego.com/cdn/product-assets/element.img.lod5photo.192x192/6335932.jpg",
"piecePrice": 0.3,
"pieceTag": "Bestseller",
},
{
"pieceName": "Animal No. 17 Dog",
"pieceImageURL": "https://www.lego.com/cdn/product-assets/element.img.lod5photo.192x192/6076467.jpg",
"piecePrice": 2.76,
"pieceTag": "Bestseller",
}
]
}
Then, when my catalog page opens, I run these two functions:
catalog.component.ts
ngOnInit(): void {
this.getProducts();
this.searchSubject.subscribe(value => this.searchService.setSearchValue(value));
this.searchService.searchValue$.subscribe(value => {
this.productService.getProductByNameLike(value).subscribe(productsCalled => {
this.products = productsCalled})
})
}
getProducts(): void {
this.productService.getAll().subscribe({ <- Line where the error occurs
next: (productsCalled: Product[]) => {
this.products = productsCalled
this.checkProductsOnCart()
},
error: (err) => console.log(err),
complete: () => console.log("completo")
});
}
But I keep getting the NG0900 error. I believe it might be because I'm not reading the array where the products are.
I have changed the getAll method, as originally it was:
public getAll(): Observable<Product[]> {
return this.http.get<Product[]>(this.productsUrl);
}
I also tried searching for other responses here, but none seem to be applicable to my problem, or maybe I'm just too much of a newbie to see the relation. Does anyone know what am I doing wrong here? Thanks in advance.
Your JSON response is an object.
export interface ProductListResponse {
httpCode: Number;
message: string;
response: Product[];
}
Work with map from rxjs to return the array from the response property.
import { map } from 'rxjs';
public getAll(): Observable<Product[]> {
return this.http.get<ProductListResponse>(this.productsUrl)
.pipe(map((data) => data.response));
}

How to ask a confirmation before uploading a file (primeng)?

I'm trying to ask for a confirmation before upload the file so the server, currently I have this HTML code:
<p-fileUpload mode="basic" name="file" url="{{urlUpload}}" chooseLabel="Upload CSV (onBeforeSend)="onBeforeSend($event)">
Then, I have this TS code:
onBeforeSend (event): void {
const token = this.service.getTokenSession();
event.xhr.setRequestHeader('Authorization', 'Bearer ' + token);
this.confirmationService.confirm({
message: 'Are you sure to continue?',
header : 'Confirmation',
accept : () => {
this.service.showLoader();
this.onUpload(event);
},
reject: () => {}
});
}
onUpload(event): void {
this.msgsPage = [];
try {
const response = JSON.parse(event.xhr.response);
console.log(response)
if (!response.ok) {
this.errorModalService.show('There was an error');
this.flagResultLoadErrors = true;
let c = 0;
for (let msg of response.map.errors) {
c++;
this.msgsPage.push({
detail : msg,
severity: 'error',
summary : 'Error ' + c,
});
}
}
} catch (e) {
this.errorModalService.show('Unknown error');
console.log(e)
} finally {
this.service.hideLoader();
}
}
With this, I tried to block the request, but it didn't happen, what I got is that the file is sent to the server before the confirmation dialog.
Also, I'm getting this error when I tried to get the response:
SyntaxError: Unexpected end of JSON input
Hope you can help me.
You can't block from that event. It is just an event emitted from the component.
https://github.com/primefaces/primeng/blob/master/src/app/components/fileupload/fileupload.ts#L367
You will need to use the custom uploadHandler.
<p-fileUpload name="myfile[]" customUpload="true" (uploadHandler)="myUploader($event)"></p-fileUpload>
myUploader(event) {
//event.files == files to upload
}
SyntaxError: Unexpected end of JSON input
This one means the response you are getting from the xhr response is not JSON, but you are trying to parse it. Check network tab to see what the response from the server is.

how to print only error message in Angular

I'm trying to find out a way to print only the "message" part from my api call error but not sure how to get only that part so I would be really appreciated if I can get any suggestion or help.
So this is what it show me in the network tab when there is error in the api call (pic)
saveChartClick(err: any) {
// update the chart data here
if(!this.isTextChart && !this.isFigure && !this.isGrid){
this.chartService.updateChart(this.chart).pipe(takeUntil(this.death$)).subscribe((updated) => {
if(updated) {
this.chart = updated;
this.snackbar.open("Chart has been updated.", " ", {duration: 2500});
this.store.dispatch(updateChart({chart: this.chart}));
} else {
this.snackbar.open(err.message, "close ", { duration: 2500 });
}
}, err => {
this.snackbar.open(err.message, "close ", { duration: 2500 });
})
}
else{
// save the new data here
this.store.dispatch(saveChartData({ guid: this.chart.guid, data: this.chartData }));
}
}
Right now it showing me this, which is not what I want to display since it doesn't really tell what is the error.
Error Message it showing me right now (pic)
This is hard coded but this one example of what I want to display (pic)
The errors are handle in the backend and I can get different error message sometime so I don't want to hard code it.
In Angular's HttpErrorResponse object, this is how the message property looks like. What you want isn't
this.snackbar.open(err.message, "close ", { duration: 2500 });
but
this.snackbar.open(err.error.message, "close ", { duration: 2500 });
Or maybe, to be on the safe side (error can be null),
const errorMessage = err.error ? err.error.message : err.message;
this.snackbar.open(errorMessage, "close ", { duration: 2500 });

How to properly insert uploaded image with Jodit editor?

I'm currently having an issue trying to insert an image after it has been uploaded. I've followed the documentation on https://xdsoft.net/jodit/, but still having issues.
Here is my config object:
{
readonly: false,
enableDragAndDropFileToEditor: true,
uploader: {
url: this.url_upload,
data: {
dir: this.dir
},
baseurl: relativePathURL,
process: (response) => {
let files = [];
response.list.map((file) => {
files.push(file.name);
});
return {
files,
path: relativePathURL,
baseurl: '/content/assets',
error: (response.success ? 0 : 1),
msg: response.message
};
},
defaultHandlerSuccess: (response) => {
if (response.files && response.files.length) {
for (let i = 0; i < response.files.length; i++) {
let full_file_path = response.path + response.files[i];
this.selection.insertImage(full_file_path);
}
}
}
}
}
I understand the return object from process is the response passed on to defaultHandlerSuccess where the file gets inserted. However, I keep getting this o is undefined error every time.
I'm looking for some insight on how to properly insert the image. What is it that I'm doing wrong?
I ended up doing some further testing to diagnose the problem.
I renamed the original node_modules/jodit/build/jodit.min.js to node_modules/jodit/build/_jodit.min.js, and node_modules/jodit/build/jodit.js to node_modules/jodit/build/jodit.min.js, so I can truly understand the issue.
After doing this, the error was in the insertImage function, line 671,defaultWidth was undefined.
https://github.com/xdan/jodit/blob/master/src/modules/Selection.ts#L655
So the change was simply providing the other two parameters when calling the insertImage function as so:
this.selection.insertImage(full_file_path, null, 250);
In the provided example (https://xdsoft.net/jodit/v.2/doc/tutorial-uploader-settings.html), there is no mention of the parameters being required.
Hope this helps anyone else with the same issue.

Elasticsearch js Bulk Index TypeError

Background
Recently, I have been working with the Elasticsearch Node.js API to bulk-index a large JSON file. I have successfully parsed the JSON file. Now, I should be able to pass the index-ready array into the Elasticsearch bulk command. However, using console log, it appears as though the array shouldn't be causing any problems.
Bugged Code
The following code is supposed to take an API URL (with a JSON response) and parse it using the Node.js HTTP library. Then using the Elasticsearch Node.js API, it should bulk-index every entry in the JSON array into my Elasticsearch index.
var APIUrl = /* The url to the JSON file on the API providers server. */
var bulk = [];
/*
Used to ready JSON file for indexing
*/
var makebulk = function(ParsedJSONFile, callback) {
var JSONArray = path.to.array; /* The array was nested... */
var action = { index: { _index: 'my_index', _type: 'my_type' } };
for(const item of items) {
var doc = { "id": `${item.id}`, "name": `${item.name}` };
bulk.push(action, doc);
}
callback(bulk);
}
/*
Used to index the output of the makebulk function
*/
var indexall = function(madebulk, callback) {
client.bulk({
maxRetries: 5,
index: "my_index",
type: "my_type",
body: makebulk
}, function(err, resp) {
if (err) {
console.log(err);
} else {
callback(resp.items);
}
});
}
/*
Gets the specified URL, parses the JSON object,
extracts the needed data and indexes into the
specified Elasticsearch index
*/
http.get(APIUrl, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var APIURLResponse = JSON.parse(body);
makebulk(APIURLResponse, function(resp) {
console.log("Bulk content prepared");
indexall(resp, function(res) {
console.log(res);
});
console.log("Response: ", resp);
});
});
}).on('error', function(err) {
console.log("Got an error: ", err);
});
When I run node bulk_index.js on my web server, I receive the following error: TypeError: Bulk body should either be an Array of commands/string, or a String. However, this doesn't make any sense because the console.log(res) command (From the indexall function under http.get client request) outputs the following:
Bulk content prepared
Response: [ { index: { _index: 'my_index', _type: 'my_type', _id: '1' } },
{ id: '5', name: 'The Name' }, ... },
... 120690 more items ]
The above console output appears to show the array in the correct format.
Question
What does TypeError: Bulk body should either be an Array of commands/string, or a String indicate is wrong with the array I am passing into the client.bulk function?
Notes
My server is currently running Elasticsearch 6.2.4 and Java Development Kit version 10.0.1. Everything works as far as the Elaticsearch server and even my Elaticsearch mappings (I didn't provide the client.indices.putMapping code, however I can if it is needed). I have spent multiple hours reading over every scrap of documentation I could find regarding this TypeError. I couldn't find much in regards to the error being thrown, so I am not sure where else to look for information regarding this error.
Seems a typo in your code.
var indexall = function(**madebulk**, callback) {
client.bulk({
maxRetries: 5,
index: "my_index",
type: "my_type",
body: **makebulk**
Check the madebulk & makebulk.