Transcrypt and FileReader - filereader

I am trying to load a local image file into the browser. The code doesn't work. It always returns null for the result of the Filereader. The code for read_file3.py :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class TestSystem:
def openFile(self, event):
self.inputvar = event.target
console.log("self.inputvar"+self.inputvar)
console.log("self.inputvar.files[0]"+self.inputvar.files[0])
self.freader = __new__(FileReader())
self.freader.onload = self.processInput()
self.freader.readAsDataURL(self.inputvar.files[0])
def processInput(self):
dataURL = self.freader.result
console.log("type:"+type(dataURL))
console.log("dataURL:"+dataURL)
document.getElementById('output').src = dataURL
testSystem = TestSystem()
and the html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="__javascript__/read_file3.js"; charset="UTF-8"></script>
<title>Read local image File</title>
</head>
<body>
<main>
<h1>Read a local image file!</h1>
<p id="p1" class="para1">Read a local image file!</p>
<input type='file' accept='image/*' onchange='read_file3.testSystem.openFile(event)'><br>
<img id='output'>
<p id="demo"></p>
</main>
</body>
</html>

Don't use () when you pass a callback function.
You don't want to call it, just pass the address of the function.
Took me a while to see it as well.
By the way, Transcrypt is no different from JavaScript in this respect.
There also the braces would have to be left out.
Note that you can also simply use print() instead of console.log().
(But in a test I may also have opted for console.log to avoid any surprises)
This works:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class TestSystem:
def openFile(self, event):
self.inputvar = event.target
console.log("self.inputvar"+self.inputvar)
console.log("self.inputvar.files[0]"+self.inputvar.files[0])
self.freader = __new__(FileReader())
self.freader.onload = self.processInput
# No braces, since you don't want to call this function
# but just pass its address...
self.freader.readAsDataURL(self.inputvar.files[0])
def processInput(self):
dataURL = self.freader.result
console.dir (self.freader)
console.log("type:"+type(dataURL))
console.log("dataURL:"+dataURL)
document.getElementById('output').src = dataURL
console.dir (self.freader)
testSystem = TestSystem()

Related

Blazor set CSS file based on request path

I'm attempting to switch out the css file on the fly - based on which part of the web-system the user is in (i.e. if the user is on mydomain/students/page then the page loads with students.min.css, rather than site.min.css).
I've tried doing it within the _Host.cshtml:
#page "/"
#namespace FIS2withSyncfusion.Pages
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#{
Layout = null;
//sniff the requst path and switch the stylesheet accordingly
string path = Request.Path;
string css = "site.min.css";
if (path.ToLowerInvariant().StartsWith("/students"))
{
css = "students.min.css";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Martin's Blazor Testing Site</title>
<base href="~/" />
<link rel="stylesheet" href="css/#(css)" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
<script type="text/javascript">
function saveAsFile(filename, bytesBase64) {
if (navigator.msSaveBlob) {
//Download document in Edge browser
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) {
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
navigator.msSaveBlob(blob, filename);
}
else {
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
</script>
</head>
<body>
<component type="typeof(App)" render-mode="ServerPrerendered" />
<script src="_framework/blazor.server.js"></script>
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
</body>
</html>
However, it doesn't seem to hit this codeblock after the first load of the site; meaning whichever page they first landed on denotes the stylesheet for the entire site.
Do I have to put this codeblock on every page or is there another way of doing this?
another way you could approach this is to create components that respond to different styling that you desire. From there you have two options:
Create dedicated css associate with the component. From the docs
Create a class toggle in the code block of the component, similar to how the NavMenu works.
After further experimentation, I've found that adding this block:
#{
//sniff the requst path and switch the stylesheet accordingly
string path = navManager.Uri;
Uri uri = new Uri(path);
List<string> parts = uri.Segments.ToList();
string module = parts[1].ToLowerInvariant().Trim('/');
string css = "site.min.css";
if (module == "students")
{
css = "students.min.css";
}
}
<head>
<link rel="stylesheet" href="css/#(css)" />
</head>
To the top of MainLayout.razor works perfectly - so long as you remove the equivalent block from _Host.cshtml

FlaskSocketIO retrieve list of all connected clients

I am just beginning to learn Flask SocketIO.
The basic requirement is to gather all the client (along with info) that are connected to server. Below code is written to do just that.
Username is collected on click of a button.
#main.py
from flask import Flask, render_template, request, session, jsonify
from flask_socketio import SocketIO, emit, send
app = Flask(__name__)
socketio = SocketIO(app, manage_session=False)
clients = []
#socketio.on('client_connected', namespace='/connect')
def handle_client_connected_event(username, methods=['GET', 'POST']):
clients.append(
{
'client_session': request.sid,
'client_username': username,
'client_ip': request.access_route
}
)
print(clients)
#app.route('/')
def index(methods=['GET', 'POST']):
return render_template('index.html')
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0')
And Client side code:
//JS
var socket = io.connect('http://' + document.domain + ':' + location.port);
var socket_messages = io.connect('http://' + document.domain + ':' + location.port+'/connect');
$('#send_username').on('click', function(){
socket_messages.emit('client_connected', $('#username').val());
});
and lastly HTML
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script type="text/javascript" src="{{ url_for('static', filename='app.js') }}"></script>
<title>Document</title>
</head>
<body>
<input type="text", id="username">
<button id="send_username">Submit Username</button><br>
<!-- Connected User: -->
</body>
</html>
I am unable to get client info using this piece of code. Any insights as to where I may be going wrong?
Thanks for your help

Exporting as image from mermaid (Gantt)

I'm having an issue trying to export the Gantt chart as a png or any other image format. The Viewer within RStudio shows me the Gantt is rendered. It also gives me the option to save as an image, but I'm finding the image is very pixelated when you zoom in.
Here is what I have tried, but the file comes up empty after running:
library(DiagrammeR)
m1<-mermaid("
gantt
dateFormat MM/DD/YY
title Example Gantt
section Example Section
Process1 :done, task_1, 01/01/01, 01/05/01
Process2 :done, task_2, 02/01/02, 02/05/02
Process3 :done, task_3, 03/01/03, 03/05/03
")
m1$x$config = list(ganttConfig = list(
axisFormatter = list(list(
"%y"
,htmlwidgets::JS(
'function(d){ return d.getDay() }'
)
))
))
png("Example.png")
m1
dev.off()
This is the code that executing that m1 object creates when run from an R console. I don't see an image in the SO viewing window, but apologies since I'm not a particularly knowledgeable user of that facility. You can view this in a browser, which is what RSudio is providing and it can be zoomed up to the browser limits and then screenshots will not be pixelated:
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.8/d3.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script src="lib/htmlwidgets-0.5/htmlwidgets.js"></script>
<script src="lib/d3-3.3.8/d3.min.js"></script>
<script src="lib/dagre-0.4.0/dagre-d3.min.js"></script>
<link href="lib/mermaid-0.3.0/dist/mermaid.css" rel="stylesheet" />
<script src="lib/mermaid-0.3.0/dist/mermaid.slim.min.js"></script>
<link href="lib/DiagrammeR-styles-0.2/styles.css" rel="stylesheet" />
<script src="lib/chromatography-0.1/chromatography.js"></script>
<script src="lib/DiagrammeR-binding-0.8.1/DiagrammeR.js"></script>
</head>
<body style="background-color:white;">
<div id="htmlwidget_container">
<div id="htmlwidget-2084" style="width:960px;height:500px;" class="DiagrammeR"></div>
</div>
<script type="application/json" data-for="htmlwidget-2084">{"x":{"diagram":"\n gantt\n dateFormat MM/DD/YY\n title Example Gantt\n\n section Example Section\n Process1 :done, task_1, 01/01/01, 01/05/01\n Process2 :done, task_2, 02/01/02, 02/05/02\n Process3 :done, task_3, 03/01/03, 03/05/03\n ","config":{"ganttConfig":{"axisFormatter":[["%y","function(d){ return d.getDay() }"]]}}},"evals":["config.ganttConfig.axisFormatter.0.1"]}</script>
<script type="application/htmlwidget-sizing" data-for="htmlwidget-2084">{"viewer":{"width":450,"height":350,"padding":15,"fill":true},"browser":{"width":960,"height":500,"padding":40,"fill":false}}</script>
</body>
</html>

How to parse/download stylesheet from HTML

I am downloading part of an HTML page by:
require 'nokogiri'
require 'open-uri'
doc = Nokogiri::HTML(open('https://example.com/index.html'))
wiki = doc./('//*[#id="wiki"]/div[1]')
and I need the stylesheets in order to display it correctly. They are included in the header like so:
<!DOCTYPE html>
<html lang="en" class="">
<head>
...
<link href="https://example.com/9f40a.css" media="all" rel="stylesheet" />
<link href="https://example.com/4e5fb.css" media="all" rel="stylesheet" />
...
</head>
...
and their naming can be changed. How do I parse/download local copies of the stylesheets?
Something like this:
require 'open-uri'
doc.css("head link").each do |tag|
link = tag["href"]
next unless link && link.end_with?("css")
File.open("/tmp/#{File.basename(link)}", "w") do |f|
content = open(link) { |g| g.read }
f.write(content)
end
end
I'm not a ruby expert but you can go over following steps
You can use .scan(...) method provided with String type to parse and get the .css file names. The scan method will return you an array stylesheet file names. Find more info on scan here
Then download and store the files with Net::HTTP.get(...) an example is here

Unable to insert stylesheet/script into window.open

I have been fighting this issue for quite some time now, and have been (still) unable to print my div with its styling.
Currently, my script is:
$('#printMeButton').click(function () {
//alert("a");
var data = document.getElementById('thisPrintableTable').outerHTML;
var mywindow = window.open('', data);
mywindow.document.write('<html><head><title>Print Me!!!</title>');
// mywindow.document.write('<link rel="stylesheet" type="text/css" href="Site.css" media="screen">');
mywindow.document.write('</head><body>');
mywindow.document.write(data);
mywindow.document.write('</body></html>');
mywindow.document.close();
mywindow.focus();
mywindow.print();
mywindow.close();
return true;
});
which is nested within a $(document).ready function.
When I include the desired stylesheet (currently commented out), Nothing appears in the print preview.
I also have some script that has an effect on the appearance of the table, and, as such, I believe this may hold the key of having these included into the popup window.
How can i include this into the new popup?
Could someone please suggest a way of printing this as it stands?
Edit History
removed space at end of </head><body>
Changed var data to have outerHTML instead of innerHTML
Altered Question/details from better understanding of issue
Try to open a local html file using window.open with css linked within it. And set the content html to be printed to the local html file using js.
Here is the page to be printed:-
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="test.css" rel="stylesheet" type="text/css" />
<script src="jquery.js"></script>
</head>
<body>
<div id="print">
<div class="red">TODO write content</div>
</div>
<button id="print_btn">Print</button>
<script>
$('#print_btn').click(function(){
var newWindow = window.open('print.html','_blank');
$(newWindow).load(function(){
$(newWindow.document).find('body').html($('#print').html());
});
})
</script>
</body>
</html>
The css file test.css is linked here, and I'm opening print.html at the time of window.open, the test.css is also linked in the print.html
Now, in print.html I'll write:-
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="test.css" rel="stylesheet" type="text/css" />
</head>
<body>
</body>
</html>
Since you provide an empty string as a new window's URL (the first parameter of the open function), the page inside it most likely can't figure out where your stylesheet is (as it's address is "relative to nothing"). Try specifying an absolute URL to your stylesheet.
Also, there is media="screen" attribute that should be changed to media="print"
mywindow.document.write('<link rel="stylesheet" type="text/css" href="http://my.site/Site.css" media="print"')
The issue can be solved by introducing some delay time before executing mywindow.close(); method. Seems that some time is needed for CSS to be applied (loaded), like this:
$('#printMeButton').click(function () {
var content = document.getElementById(id).innerHTML;
var mywindow = window.open('', 'Print', 'height=600,width=800');
mywindow.document.write('<!DOCTYPE html><html dir="rtl"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Print</title>');
mywindow.document.write('<link rel="stylesheet" type="text/css" href="/static/css/styles.css" />');
mywindow.document.write('</head><body >');
mywindow.document.write(content);
mywindow.document.write('</body></html>');
mywindow.document.close();
mywindow.focus()
mywindow.print();
// this is needed for CSS to load before printing..
setTimeout(function () {
mywindow.close();
}, 250);
return true;
});
We can use this inline style.
var divToPrint = document.getElementById('DivIdToPrint');
var newWin=window.open('','Print-Window');
newWin.document.open();
newWin.document.write('<html>' +
'<style>' +
".btn-petty-cash-split{display: none}"+
".btn-petty-cash-split{display: none}"+
'</style>' +
'<body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');
newWin.document.close();
setTimeout(function(){
newWin.close();
window.location.reload();
},10);

Resources