wkhtmltopdf, encoding cyrillic from perl pipe - perl

So, i'm running wkhtmltopdf command script from perl's system method. I need it to pass a custom value (span class) to pdf via command line:
my $time = "Время";
my $command = "./wkhtmltopdf ...blablabla... gen_date \"$time\" ...blablabla...";
but when i run this - i have encoding garbage in output .pdf like that: - Ð​ÑÐμмÑ.
Tried almost everything i know to encode/decode the $time string, but nothing.
my javascript snippet is common for wkhtmltopdf, so....
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<head>
<script>
function subst() {
var vars = {};
var query_strings_from_url = document.location.search.substring(1).split('&');
for (var query_string in query_strings_from_url) {
if (query_strings_from_url.hasOwnProperty(query_string)) {
var temp_var = query_strings_from_url[query_string].split('=', 2);
vars[temp_var[0]] = decodeURI(temp_var[1]);
}
}
var css_selector_classes = ['gen_date', 'page'];
for (var css_class in css_selector_classes) {
if (css_selector_classes.hasOwnProperty(css_class)) {
var element = document.getElementsByClassName(css_selector_classes[css_class]);
for (var j = 0; j < element.length; ++j) {
element[j].textContent = vars[css_selector_classes[css_class]];
}
}
}
}
</script>
</head>
Can you help me to solve it?

After finding a rason why does it happen, i realiased that JS is more likely to operate with its format of byte-array. Now, cyrillic string is encoded to be look like %u0000%u0000... and then in javascript, this string goes through built-in unescape function, and now i have normal cyrillic string in pdf.
Oh, my...

Related

Simple Javascript tax calculator

I am working on a tax calculator, and i don't get it to work. The only result i get is NaN, and I can't find what's wrong with my code. If the users input is 450 000 or more, the output is supposed to be 32% of their salary else 28%.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="Skatt">
<meta name="author" content="Gandalf">
<title>Taxes</title>
</head>
<body>
<input type="text" id="salary" value="0" />
<button id="button">Calculate tax!</button>
<h2 id="salaryOut">Your salary is NOK:</h2>
<h2 id="taxOut">You should pay taxes with the amount of:</h2>
<script>
var button = document.getElementById("button");
button.onclick = function() {
var salary = document.getElementById("salary");
salary.value = 0;
var salaryOut = document.getElementById("salaryOut");
salaryOut.value = salary;
var salaryOut = document.getElementById("taxOut");
taxOut.value = parseFloat(salaryOut.value);
if(salaryOut.value<450000) {
taxOut.value = salaryOut.value * .28;
}
else {
taxOut.value = salaryOut.value * .32;
}
salaryOut.innerHTML = ("Your salary is NOK: " + salary.value + ",-");
skattUt.innerHTML = "You should pay NOK: " + taxOut.value + ",-";
}
</script>
</body>
</html>
You're performing all of your calculations right away as soon as the page loads, when there are no actual values to calculate. The only thing you're doing in your click handler is displaying the values that were already calculated.
Since there were no values to calculate when the page first loaded, that result is NaN.
Put all of your logic in the click handler:
var knapp = document.getElementById("knapp");
knapp.onclick = function() {
var lonn = document.getElementById("lonn");
var lonnUt = document.getElementById("lonnUt");
var skattUt = document.getElementById("skattUt");
var result = 0;
if(lonn.value<450000) {
result = lonn.value * .28;
}
else {
result = lonn.value * .32;
}
lonnUt.innerHTML = ("Lønnen din er kr: " + lonn.value + ",-");
skattUt.innerHTML = "Skatten din er kr: " + result + ",-";
}
That way you give the user a chance to input numbers before you try to perform calculations on those numbers.
(Note: I keep re-editing this because I'm having a lot of trouble deciphering the actual logic of what you're trying to do. The variable names don't help, since I don't speak that language. It's certainly possible that there are other problems here as well. But the main one is that you need to perform the calculations after the user types the values, not before.)
Edit: I've further modified the code here after finding another significant issue. You were trying to access a .value property on h2 elements, which doesn't exist. You were also trying to store information in those elements as though they were variables.
Instead, just declare a variable to store the result of your calculation. Get the input (lonn), perform the calculation and get a result (result), write the output to the HTML elements (lonnUt and skattUt).

jsTree customize <li> using the alternative JSON format along with AJAX

I am using the alternative JSON format along with AJAX to load data in tree. Now there is a new ask, I am required to add a new element at the end of <li> tag.
I have created sample URL to display what I am currently doing.
Tree crated using alternative JSON format along with AJAX
And how the new LI should appear
Tree created using hard coded HTML but shows how the LI should look like
I think I should be able to do this if I use HTML Data but since the project is already live with JSON format this would require me to change a lot so before I start making this major change I just wanted to check if this is possible using JSON and AJAX format or not.
So I got answer from Ivan - Answer
In short there is misc.js in the src folder which has question mark plugin, this is the best example of what I wanted to do.
I tweaked its code for my needs and here is the new code.
(function ($, undefined) {
"use strict";
var span = document.createElement('span');
span.className = 'glyphicons glyphicons-comments flip jstree-comment'
$.jstree.defaults.commenticon = $.noop;
$.jstree.plugins.commenticon = function (options, parent) {
this.bind = function () {
parent.bind.call(this);
};
this.teardown = function () {
if (this.settings.commenticon) {
this.element.find(".jstree-comment").remove();
}
parent.teardown.call(this);
};
this.redraw_node = function (obj, deep, callback, force_draw) {
var addCommentIcon = true;
var data = this.get_node(obj).data;
//....Code for deciding whether comment icon is needed or not based on "data"
var li = parent.redraw_node.call(this, obj, deep, callback, force_draw);
if (li && addCommentIcon) {
var tmp = span.cloneNode(true);
tmp.id = li.id + "_commenticon";
var $a = $("a", li);
$a.append(tmp);
}
return li;
};
};
})(jQuery);

Querying MongoDB with values from a text file

I've been handed a list of 500+ email addresses in a text file and been asked to find out how many of them exist as customer emails in our MongoDB database.
What is the quickest way of finding out which of those emails in the text file currently exist in the "Customer.Email" field of my collection?
Can I use text file of emails as parameters for a query, for instance?
Thanks,
Adam
This should do the trick,
I am assuming your txt file is in this format,
test1#test.com
test2#test.com
test3#test.com
test4#test.com
test5#test.com
test6#test.com
test7#test.com
test8#test.com
test9#test.com
test10#test.com
upload the text.txt file to the server for to convert it to an js array
you can do that with something like this,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>File Reader</title>
</head>
<body>
<p>
<script>
function getData() { //this will read file and send information to other function
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
var lines = xmlhttp.responseText;
intoArray(lines);
}
}
xmlhttp.open("GET", "text.txt", true);
xmlhttp.send();
}
getData();
function intoArray(lines) {
var lineArr = lines.split('\n');
//just to check if it works output lineArr[index] as bellow*
lineArr.forEach(function(arrayItem) {
console.log(arrayItem);
});
}
</script>
</body>
</html>
At this point the email address in the txt file will be in an array so you can query the mongodb with the $in Operator like this,
db.Customers.find( {CustomerEmail: { $in [$myArray] } })

How to generate typescript interfaces/definitions for breeze entities

I’m new to SPA and I’m learning it with durandal and breeze. Recently I have switched my solution to Typescript and I’m wondering is there any good solution to generate typed breeze entities in TypeScript basing on EF model on the server. Only thing I have found is this post Breeze.js typed entities but this is only small piece of code and not even a real project. I’m wondering is there any better solution to this issue?
Below is a page you can drop in your site to generate typescript interface definitions. The page fetches the breeze metadata then iterates through all of the types and outputs a typescript interface declaration for each type. The output of this page can then be pasted in any typescript file (*.ts) or typescript definition file (*.d.ts). Enclose the results in a module declaration if you want to namespace the interfaces: declare module northwind { ... paste interfaces here... }.
Before using the page you'll need to make one edit: change the entity manager's controller url from "api/northwind" to whatever your breeze controller's url is.
The generated interfaces have a dependency on the Knockout.js typescript definitions which you can grab here: https://github.com/borisyankov/DefinitelyTyped/tree/master/knockout/
Using the northwind example from learn.breezejs.com, the output of this definitions generator page would be something like this:
export interface Employee extends breeze.Entity {
FirstName: KnockoutObservable<string>;
LastName: KnockoutObservable<string>;
}
you could then execute a query using breeze and cast the results to an array of employees like this:
var manager = new breeze.EntityManager('api/northwind');
var query = new breeze.EntityQuery()
.from("Employees");
manager.executeQuery(query).then(data => {
// ***cast the results to a strongly typed array of Employee***
var employees = <Employee[]>data.results;
}).fail(e => {
alert(e);
});
below is the definitions generator page- add a new html file to your project named "definitions.html", run the project and navigate to the page.
<html>
<head>
<title>Typescript Definition Generator</title>
<style>
code {
white-space: pre;
}
</style>
<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/knockout/knockout-3.0.0.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/q.js/1.0.0/q.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/breezejs/1.4.4/breeze.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var entityManager = new breeze.EntityManager('api/northwind');
entityManager.fetchMetadata()
.then(function () {
var html = '',
types = entityManager.metadataStore.getEntityTypes(),
type,
i,
j,
property,
crlf = String.fromCharCode(13),
code = document.createElement('code'),
script = document.createElement('script');
function getJSType(metadataType) {
if (/(Int64)|(Int32)|(Int16)|(Byte)|(Decimal)|(Double)|(Single)|(number)/.test(metadataType))
return 'number';
else if (/(DateTime)|(DateTimeOffset)|(Time)|(Date)/.test(metadataType))
return 'Date';
else if (/(Boolean)/i.test(metadataType))
return 'boolean';
return 'string';
}
for (i = 0; i < types.length; i++) {
// type declaration
var type = types[i];
html += 'export interface ' + type.shortName;
// base type
html += ' extends ';
if (type.hasOwnProperty('baseEntityType')) {
html += type.baseEntityType.shortName;
} else {
html += 'breeze.Entity';
}
html += ' {' + crlf;
// data properties
for (j = 0; j < type.dataProperties.length; j++) {
property = type.dataProperties[j];
if (type.baseEntityType && type.baseEntityType.dataProperties.filter(function (p) { return p.name === property.name; }).length > 0)
continue;
html += ' ' + property.name;
//if (property.isNullable)
// html += '?';
html += ': KnockoutObservable<';
html += getJSType(property.dataType.name);
html += '>; //' + property.dataType.name + crlf;
}
// navigation properties
for (j = 0; j < type.navigationProperties.length; j++) {
property = type.navigationProperties[j];
if (type.baseEntityType && type.baseEntityType.navigationProperties.filter(function (p) { return p.name === property.name; }).length > 0)
continue;
html += ' ' + property.name;
//if (property.isNullable)
// html += '?';
if (property.isScalar)
html += ': KnockoutObservable<';
else
html += ': KnockoutObservableArray<';
html += property.entityType.shortName;
html += '>;' + crlf;
}
html += '}' + crlf + crlf;
}
code.innerHTML = html;
$(code).addClass('prettyprint');
document.body.appendChild(code);
script.setAttribute('src', '//google-code-prettify.googlecode.com/svn/loader/run_prettify.js');
document.body.appendChild(script);
})
.fail(function (reason) {
alert(reason);
});
});
</script>
</head>
<body>
</body>
</html>

Pass parameter to GWT bootstrap .nocache.js script

Is there any way to pass parameters to the .nocache.js script file generated by GWT and evaluate them in the onModuleLoad function? Like so:
<script type="text/javascript" src="application/Application.nocache.js?appId=461333815262909"></script>
The host page URL should be completely separated from the GWT stuff working inside, so passing the appId parameter as a query parameter for the host page and accessing it with Window.Location.getParameter is not an option. I know that I could hide such parameters e.g. in hidden DIVs and then query them from the script, but if it's possible, I'd love to avoid any further dependency in the host page.
Thanks!
Lisa
Instead of hiding information in hidden divs which could get messy, an easy way to pass arguments is via the HTML meta tags.
In the HTML page that calls the GWT script, add a meta tag as follows:
<html>
<head>
<meta name="appId" content="461333815262909">
...
Then, in your module's entry point, parse it as follows:
#Override
public void onModuleLoad() {
NodeList<Element> metas = Document.get().getElementsByTagName("meta");
for (int i=0; i<metas.getLength(); i++) {
MetaElement meta = (MetaElement) metas.getItem(i);
if ("appId".equals(meta.getName())) {
Window.alert("Module loaded with appId: " + meta.getContent());
}
}
}
Granted, it's not quite as simple as passing the argument in the src URL of the script tag but I believe it to be a bit cleaner than hiding divs in the document content and less error-prone than artificially re-parsing the script tag's source attribute.
No, but this article may be helpful in passing parameters from the server to the client-side script for evaluation on page load.
There appears to be no native support in GWT for that, but I came up with the following solution lately:
Assuming that your script always follows the naming convention "/<moduleName>.nocache.js", you can fetch all <script> elements from the host page and search for the one which references this in the src attribute. You can then pull the URL-encoded attributes from there.
Here's my sample implementation, meant to be called with GWT.getModuleName() as the first parameter.
/**
* Fetches a parameter passed to the module's nocache script.
*
* #param moduleName the module's name.
* #param parameterName the name of the parameter to fetch.
* #return the value of the parameter, or <code>null</code> if it was not
* found.
*/
public static native String getParameter( String moduleName, String parameterName ) /*-{
var search = "/" + moduleName + ".nocache.js";
var scripts = $doc.getElementsByTagName( "script" );
for( var i = 0; i < scripts.length; ++i ) {
if( scripts[ i ].src != null && scripts[ i ].src.indexOf( search ) != -1 ) {
var parameters = scripts[ i ].src.match(/\w+=\w+/g);
for( var j = 0; j < parameters.length; ++j ) {
var keyvalue = parameters[ j ].split( "=" );
if( keyvalue.length == 2 && keyvalue[ 0 ] == parameterName ) {
return unescape( keyvalue[ 1 ] );
}
}
}
}
return null;
}-*/;
Suggestions for improvement are welcome.