How do I modify elements of an HTML file with Go? - html

I've been trying to figure this out for a few days and I've kind of exhausted even the most effective of google searching. What I've been trying to do is to open a file of the type HTML and with Go's library (http://golang.org/x/net/html) modify the img tags and their source to a known directory and set of files. So far I've been able to find the elements using this,
//Open the file and return a variable called file.
file, _ = os.Open(file.Name())
//Create the doc
doc, err := html.Parse(file)
//Check for err when generating the doc
check(err)
//Look for tags with img using an anonymous function.
var f func(*html.Node)
f = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "img" {
for _, img := range n.Attr {
if img.Key == "src" {
str := breakdownURL(img.Val) //Gets the ../../resource/(thing.h23.jpg) <-- That
//Creating a static address to add to the dynamic one
address := filepath.Join(filepath.Join("Resources", getFileNotExt(file)), str)
img.Val = address
break
}
}
}
for at := n.FirstChild; at != nil; at = at.NextSibling {
f(at)
}
}
f(doc)
That's been able to find the elements and append the correct directory but it's only modifying this doc file. I have no clue how to append it to the actual file. The only thought that I have is opening the doc as some kind of writing way and copying the new data from the doc to the file. Any help is greatly appreciated! Thank you so much for taking your time :).

You should definitely save the edited document.
First, open the file for read/write and truncate:
file, err := os.OpenFile("sample.html", os.O_RDWR | os.O_TRUNC, 0644)
And after you finish processing, override the original file:
html.Render(file, doc)

Related

Minio: how to get right link to display image on html

I need to get images from Minio bucket, but I cannot display that image.
I found out that problem was in link. I cannot open it even with browser. So, here is the problem:
GET https://127.0.0.1:9000/myphotos/Jungles.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=7PAB237ARMGX7RTYHUSL%2F20221202%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20221202T133028Z&X-Amz-Expires=604800&X-Amz-Security-Token=eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NLZXkiOiI3UEFCMjM3QVJNR1g3UlRZSFVTTCIsImV4cCI6MTY3MDAyNzIyNiwicGFyZW50IjoiS2VtYWxBdGRheWV3In0.okb2wO_iLhOlwWeNbixec4R5MRgGw2_KCY_SB9NfuseUI3g9gzTccycbaA6UnZiuuLzbpxPM5tR_hnxa_Y8zWQ&X-Amz-SignedHeaders=host&versionId=null&X-Amz-Signature=281fab24bbe3d651f89c160f5a613512f5e4503f40300ef0008ac94bd9c8f90b
net::ERR_CONNECTION_REFUSED
My code that has been used to upload that file:
package main
import (
"context"
"log"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
func main() {
ctx := context.Background()
endpoint := "play.minio.io"
accessKeyId := "KemalAtdayew"
secretAccessKey := "K862008971a!"
useSSL := true
// init minio client object
minioClient, err := minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(accessKeyId, secretAccessKey, ""),
Secure: useSSL,
})
if err != nil {
log.Fatalln(err)
}
// make a new bucket called myphoto
bucketName := "photobucket"
location := "us-east-1"
err = minioClient.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{Region: location})
if err != nil {
// check to see if we already own this bucket
exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
if errBucketExists == nil && exists {
log.Printf("We already own %s\n", bucketName)
} else {
log.Fatalln(err)
}
} else {
log.Printf("Successfully created %s\n", bucketName)
}
// upload you photos
objectName := "Jungles.jpeg"
filePath := "/minio-1/Jungles.jpeg"
contentType := "image/jpeg"
// upload the zip file FPutObject
info, err := minioClient.FPutObject(ctx, bucketName, objectName, filePath, minio.PutObjectOptions{ContentType: contentType})
if err != nil {
log.Fatalln(err)
}
log.Printf("Successfully uploaded %s of size %d\n", objectName, info.Size)
}
I also gave permission and made it public. Still nothing.
<!DOCTYPE html>
<html>
<head>
<title> Minio </title>
<meta charset="utf-8">
</head>
<body>
<div>
<img src="https://127.0.0.1:9000/myphotos/Jungles.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=7PAB237ARMGX7RTYHUSL%2F20221202%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20221202T124101Z&X-Amz-Expires=604800&X-Amz-Security-Token=eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NLZXkiOiI3UEFCMjM3QVJNR1g3UlRZSFVTTCIsImV4cCI6MTY3MDAyNzIyNiwicGFyZW50IjoiS2VtYWxBdGRheWV3In0.okb2wO_iLhOlwWeNbixec4R5MRgGw2_KCY_SB9NfuseUI3g9gzTccycbaA6UnZiuuLzbpxPM5tR_hnxa_Y8zWQ&X-Amz-SignedHeaders=host&versionId=null&X-Amz-Signature=5027bd8021a58548ce6be5dead3b622afd951f157a289320ef7dab7701baa7d2" alt="Photo from Minio">
</div>
</body>
</html>
Tried to change html code. Then, found out that it's not html problem.
Tried to share in any other possible way except than, "bucket->click on photo -> click on share"
Link is invalid, but there is no other proper way to get link to that image in bucket.
The path to your local image seems to be strange. Verify if you can open your image manually, and remove all the parameters after the image extension, it should be Forest.jpg
The path to your local image seems to be strange. Verify if you can open your image manually, and remove all the parameters after the image extension, it should be Forest.jpg
If you have Minio running in a container, it is always a mess with 127.0.0.1 or localhost.
Try to generate the link with the minioclient.
mc alias set myminio http://localhost:9000 user password
mc share download myminio/mybucket/object.txt
it will return something like this:
mc share download --recursive minio/testbucket
URL: http://localhost:9000/testbucket/KUBERNETES_AN_ENTERPRISE_GUIDE.pdf
Expire: 7 days 0 hours 0 minutes 0 seconds
Share: http://localhost:9000/testbucket/KUBERNETES_AN_ENTERPRISE_GUIDE.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=minioadmin%2F20221207%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20221207T130336Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=8668da57727f04e7c7e8b15f5d8852fa3801e323cfbc6198384737b77f54cb0b
That link you can open in your Browser.
Note --recursive generate links for all the uploaded files in the bucket.
To get one specific use:
mc share download myminio/testbucket/object.txt.
In production mode as you will use full qualified domain names and not 127.0.0.1 or localhost.
Take a look here about the mc command for generating the link.
https://min.io/docs/minio/linux/reference/minio-mc/mc-share-download.html
If you have a backend and according to your programming language you can also generate links through the api.
Here you find a example for javascript:
https://min.io/docs/minio/linux/developers/javascript/API.html#presignedUrl

How to pass a JSON object inside a QTextEdit

I have a small GUI that I use to load/save json configuration files, the most important parameters are in the gui below:
![conf]
The problem I have been trying to solve is that I am not able to create an object inside a QTextEdit and am not sure why despite I am following official documentation on how to do that.
Below a snippet of code both for the load and save button.
Also for the sake of brevity I only kept how I did the spinbox and, of course, the textedit:
void SettingsForm::on_loadBtn_clicked()
{
// Opening file dialog....
if(listDocksConfig.isEmpty())
{
QMessageBox::information(this, tr("Message"), tr("Please Open Configuration"));
}
else
{
QJsonDocument doc;
QJsonObject obj;
QByteArray data_json;
QFile input(listDocksConfig);
if(input.open(QIODevice::ReadOnly | QIODevice::Text))
{
data_json = input.readAll();
doc = doc.fromJson(data_json);
obj = doc.object();
const double xposValue = obj["X Pos"].toDouble();
QTextEdit textEdit = QTextEdit::setText(obj["comments"]); // <- Error Here
ui->doubleSpinBox_XPos->setValue(xposValue);
ui->textEdit->setText(textEdit); // <- Error Here
}
else
{
// do something
}
}
}
void SettingsForm::on_saveBtn_clicked()
{
// saving configuration with file dialog....
if(listDocksConfig.isEmpty())
{
// do something...
}
else
{
const double xposValue = ui->doubleSpinBox_XPos->value();
QTextEdit textEdit = ui->textEdit->setPlainText(); // <- Error Here
QJsonDocument doc;
QJsonObject obj;
obj["X Pos"] = xposValue;
obj["comments"] = textEdit.toString(); // <- Error Here
doc.setObject(obj);
QByteArray data_json = doc.toJson();
QFile output(listDocksConfig);
}
}
What I have done so far:
I consulted the official documentation on how to solve this problem, but could not figure out why that was not working. I also went ahead and try to use an alternative such as setText but still no luck.
I came across this source which I used as guidance for my example and solved almost all problems but the QTextEdit one.
This additional post was useful but still couldn't solve the problem.
Thanks for pointing to the right direction for solving this problem.
this line is wrong!!
QTextEdit textEdit = ui->textEdit->setPlainText();
setPlainText() needs const QString &text as parameter
you cant do that, read the official doc here
the method is void, ie. it returns nothing so you can not use void to init a QTextEdit object
update:
you already have a textEdit in the layout, so no reason to redefine one...
you can do:
ui->textEdit->setPlainText(obj["comments"].toString());

mxGraph -Save functionality not working locally

I downloaded https://github.com/jgraph/mxgraph open source code from Git,this application Save functionality not working in the locally. Is there any possible for run the save functionality in Locally?. is there any configuration required for that? please help me.
After save button click getting below error message
I provide the code snippets for local save && upload of the saved file
code to export the xml of the current graph object
let encoder = new mxCodec();
let result = encoder.encode(graph.getModel());
let xml = mxUtils.getXml(result);
//workaround for the xml export, do not include the <mxGraphModel> tags
xml = xml.substring(xml.indexOf("<mxGraphModel>")+"<mxGraphModel>".length, xml.indexOf("</mxGraphModel>"));
code to upload the xml to re-generate the saved state of the graph
let doc = mxUtils.parseXml(xml);
let codec = new mxCodec(doc);
codec.decode(doc.documentElement, graph.getModel());
let elt = doc.documentElement.firstChild;
let cells = [];
while (elt != null)
{
let cell = codec.decode(elt)
if(cell != undefined){
if(cell.id != undefined && cell.parent != undefined && (cell.id == cell.parent)){
elt = elt.nextSibling;
continue;
}
cells.push(cell);
}
elt = elt.nextSibling;
}
graph.addCells(cells);
You can save locally by using the mxCodec class found in the IO package. Check out the example code here.
I'm not sure how to tie it into that specific button, but find the function that is called when you click save and add/replace it with the three lines needed to encode as xml.
As for how to get that xml code to save as a file, I'm not sure. Perhaps you'll find that code when you modify the save button functionality. The easy way would be to create a div and replace its innerhtml with the xml data, then just copy it and save it yourself.

Efficient way to append JSON-object without parse it

I wrote a small script listening on an udp-port and stores all incoming messages (one JSON object) inside a single file. The empty file contains an array in JSON format.
I'm looking for an efficient way to store all (concurrently) incoming messages from multiple clients inside this single file.
The files size can be multiple hundred of megabytes large. Parsing the file and appending the new object wouldn't be efficient as needed.
Do you have an approach?
EDIT
My solution, based on #t-j-crowder approach:
var dgram = require("dgram");
var fs = require("fs");
var udp_server = dgram.createSocket("udp4");
var udp_server_port = 5000
udp_server.on("message", function (msg, rinfo) {
var json_part = "{\"message\": " + msg + "}";
fs.open('./data/stats.json','r+',function(err,fd){
if(err) throw err
fs.fstat(fd,function(err,stats){
if(err) throw err
if(stats.size>2){
json_part = new Buffer(','+json_part+']','utf-8');
var pos = parseInt(stats.size)-1;
}else{
json_part = new Buffer('['+json_part+']','utf-8');
var pos = 0;
}
fs.write(fd,json_part, 0, json_part.length, pos, function(err,written,buffer){
if(err) throw err
fs.close(fd,function(){
});
});
});
});
});
udp_server.bind(udp_server_port);
Regards, Marcus
Fundamentally, you'll need to:
Open the file using a seekable, writable stream.
Seek to the end of it.
Back up one character (over the closing ] of the array).
Write out a comma (if this isn't the first entry) and the JSON of your new entry.
Write a closing ].
Close the file.
Looking at the NodeJS docs, it looks like Steps 2-4 (and arguably 5) are done all together, using the position argument of fs.write. (Be sure you open the file using r+, not one of the "append" modes.)

Reading a project text file windows phone 8

I'm having trouble accessing a text file that is packaged with my Windows Phone 8 app.
Here is the code:
var ResrouceStream = Application.GetResourceStream(new Uri("Data-Test.docx", UriKind.Relative));
if (ResrouceStream != null)
{
Stream myFileStream = ResrouceStream.Stream;
if (myFileStream.CanRead)
{
// logiic here
retrun "Hi";
}
}
else
{
return "hello";
}
Seems simple but the app always returns "hello". i have placed the file in root and also in assets, changed it to content - copy and do not copy, resource copy and do not copy but always it returns "hello".
Spent several hours on this and all solutions I can find show the solution or very similar above!
What am I doing wrong?
EDIT: Returns "hello" when I deploy to phone or emulator.
also tried "/Data-Test...", #"\Data-Text..., #/"Data-Test...!
UPDATE 1:
string aReturn = "";
var asm = Assembly.GetExecutingAssembly();
//Use this to verify the namespacing of the "Embedded Resource".
//asm.GetManifestResourceNames()
// .ToList()
// .ForEach(name => Debug.WriteLine(name));
var ResourceStream = asm.GetManifestResourceStream("ContosoSocial.Assets.QuizQuestions.QuizQuestions-Test1.docx");
if (ResourceStream != null) // <--CHECKED AND DOES NOT EQUAL NULL
{
Stream myFileStream = ResourceStream;
if (myFileStream.CanRead) // <-- CHEACKED AND CAN READ
{
StreamReader myStreamReader = new StreamReader(myFileStream);
LOGIC & EXCEPTION HERE...?
string myLine = myStreamReader.ReadLine();
}
else
{
aReturn = "myFileStream.CanRead = true";
}
}
else
{
aReturn = "stream equals null";
}
Debug.WriteLine(aReturn);
}
The assignment of myFileStream to a StreamReader object is throwing the exception null pointer. I thought I would wrap myFileStream to a StreamReader so I can read a line at a time..? This is my first c# project and I'm unfamiliar with it's syntax and classes.
UPDATE 2:
OK I added...
Debug.WriteLine(aReturn);
...following...
string myLine = myStreamReader.ReadLine();
...and noticed it was retrieving only the 2 characters 'PK' !
So saved the .docx file as .txt and reinserted adn changed build copy to embedded - do not copy...Happy days it now pulls off the first line in the file.
Thanks to OmegaMan for your help with this one :-)
Change file type in the project to Embedded Resource
Extract the resource by working the namespace to its location. Here is an example code where I pull in an XSD:
Code:
var asm = Assembly.GetExecutingAssembly();
// Use this to verify the namespacing of the "Embedded Resource".
// asm.GetManifestResourceNames()
// .ToList()
// .ForEach(name => Debug.WriteLine(name));
var f1 = asm.GetManifestResourceStream("UnitTests.Resources.NexusResponse.xsd");
Note this is not tested on WP8, but GetExecutingAssembly is stated to work within .Net. If you get the namespace wrong, uncomment out the code and display or debug to determine the resources and their namespace.