Is it possible to display a console warning, instead of a console log, from the C/C++?
So far printf("Message") will print on the regular console.log on the JS side, is it possible to print as warning like console.warn?
In generated html file, standard output is mapped to console.log().
For example
var Module = {
preRun: [],
postRun: [],
print: function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
console.warn(text);
},
printErr: function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
console.error(text);
},
https://emscripten.org/docs/api_reference/module.html?highlight=stdout#Module.print
Related
I have created a group bar chart using chartJs.
While showing tooltip on bar, i want to show some part of tooltip string in double quotes ("").
I applied below code:
tooltips: {
displayColors: false,
mode: 'label',
callbacks: {
title: function() {},
label: function(tooltipItem, data) {
var tooltipLabel1 = 'Series '+ '"'+data['datasets'][0]['label']+'" '+
'Point ' + '"'+tooltipItem.label.split(" ")[1] + " " + tooltipItem.label.split(" ")[0]+'"';
var tooltipLabel2 = 'Value: ' + tooltipItem.value;
console.log([tooltipLabel1, tooltipLabel2]); // screenshot attached for this output
return [tooltipLabel1, tooltipLabel3];
}
}
},
It working fine but it is showing one of double quote at start and end double quote is removing.
Attached screenshot for this, what exactly it is showing on mouse-hover as well as in screenshot of console.
As well as, when I write console for this, because of json string, it add output in ""
What I can do? really clueless now.
I wonder if it's possible to exclude character or skip more specific to skip them if they exist. I have JSON file like:
{
"key1": "value1",
"key2": "value2",
"array1": [
{
"key3":"value3",
"key4":"value4"
},
{
"key5":"value5",
"key6":"value6"
},
{
"key7":"value7",
"key8":"value8"
}
]
}
And I want to get output in regex like:
{"key3":"value3","key4":"value4"}
{"key5":"value5","key6":"value6"}
{"key7":"value7","key8":"value8"}
My first version of regex is:
"array1":\[(\{[A-za-z0-9%,:."]+})+
I don't know how to skip "," character if it exists.
To simplify it I work on JSON without whitespaces:
{"key1":"value1","key2":"value2","array1":[{"key3":"value3","key4":"value4"},{"key5":"value5","key6":"value6"},{"key7":"value7","key8":"value8"}]}
So I don't know if it's possible to do what I want with regex or I should just return array1 and process it with for example java to split to strings.
Try replacing the unwanted character:
str = '{"key1":"value1","key2":"value2","array1":[{"key3":"value3","key4":"value4"},{"key5":"value5","key6":"value6"},{"key7":"value7","key8":"value8"}]}';
str = str.split('[');
newStr = str[1].replace(/},/g, '}\n').replace('}]', '');
console.log(newStr);
Regular expressions are not the best tool for this job.
A simple PHP script that decodes the JSON and operates on the data always produces the correct result and it is also able to detect invalid input:
$json = << END
{
"key1": "value1",
"key2": "value2",
"array1": [
{
"key3":"value3",
"key4":"value4"
},
{
"key5":"value5",
"key6":"value6"
},
{
"key7":"value7",
"key8":"value8"
}
]
}
END;
$data = json_decode($json, TRUE);
foreach ($data['array1'] as $value) {
echo json_encode($value), "\n";
}
Validation is not included in the code above but it can be easily added by checking the value returned by json_encode() against NULL.
I'm trying to retain linebreaks made with <br> in an HTML table when exporting it to excel with DataTables. I followed their guide to replace certain things with Regex here: DataTables find and replace during export.
I was able to replace things no problem. But I fail to replace the <br> with newlines that make content in the same cell retain their linebreaks.
This is my JS:
$( document ).ready(function() {
var fixNewLine = {
exportOptions: {
format: {
body: function ( data, column, row ) {
// Strip $ from salary column to make it numeric
return column === 5 ?
// THIS WORKS: data.replace(/test/ig, "blablabla"):
data.replace( /<br\s*\/?>/ig, '"'+"\r\n"+'"' ) :
data;
}
}
}
};
$('#table2excel').DataTable({
dom: 'Bfrtip',
buttons:[
$.extend( true, {}, fixNewLine, {
extend: 'copyHtml5'
} ),
$.extend( true, {}, fixNewLine, {
extend: 'excelHtml5'
} ),
$.extend( true, {}, fixNewLine, {
extend: 'pdfHtml5'
} )
]
});
});
The problem lies in this line:
data.replace( /<br\s*\/?>/ig, '"'+"\r\n"+'"' ) :
It gets saved in excel with only a pair of " " instead of the actual line break.
Note that this also doesn't work:
data.replace( /<br\s*\/?>/ig, "\r\n"):
Any advice?
There is a similar thread here: Export value with Linebreaks into single cell in Excel. jQuery Datatables
But it's outdated as it's a year old and there have been updates to DataTables and "TableTools" has been replaced by "Buttons".
The correct answer is:
data.replace( /<br\s*\/?>/ig, "\n" ) :
However, you need to press the "wrap text" button when opening the excel.
If someone knows a way to have it wrapped automatically, please let me know.
The replace function is built in to javascript. Maybe you'd like to remove the quotations?
data.replace( /<br\s*\/?>/ig, "\r\n")
Works for me in a javascript interpreter.
Its possible that the caller of your formatting function removes newlines and replaces them with spaces
This works for me with auto wrap text in Windows Excel 2016
data.replace( /<br\s*\/?>/ig, "\r") // \r, not \n
And customize buttons
$('#myTable').DataTable( {
buttons: [
{
extend: 'excelHtml5',
customize: function( xlsx ) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
// set cell style: Wrapped text
$('row c', sheet).attr( 's', '55' );
}
}
]
});
More info about button customization: https://datatables.net/reference/button/excelHtml5
I got several files that look something like this:
universe = {
["stars"] = {
["Sun"] = {
["planets"] = "9",
["life"] = "Yes",
["asteroid"] = "9001"
},
["Alpha Centauri"] = {
["planets"] = "3",
["life"] = "No",
["asteroid"] = "20"
},
["Rigel"] = {
["planets"] = "5",
["life"] = "No",
["asteroid"] = "11"
}
}
}
My intention is to find, for instance, every block where ["life"] equals "No". I realize this could be handled better if it was within a database (or something with a structure), but I'm not sure how to convert this data onto that.
I have a bunch of files in this format, and I'd like to run a command that could display the sections (up to the immediate parent bracket) where the condition is true, so for the previous example, I'd like to get:
["Alpha Centauri"] = {
["planets"] = "3",
["life"] = "No",
["asteroid"] = "20"
},
["Rigel"] = {
["planets"] = "5",
["life"] = "No",
["asteroid"] = "11"
}
Can this be done with GREP? Or is there any other tool that could do something like this?
Any help is greatly appreciated. Thanks in advance.
EDIT
Example 2: https://regex101.com/r/jO9dU5/1
Try this Lua program:
local function find(w,t,p)
for k,v in pairs(t) do
if v==w then
print(p.."."..k)
elseif type(v)=="table" then
find(w,v,p.."."..k)
end
end
end
find("No",universe,"universe")
Add the definition of universe before this code.
If you really want to do text processing, try this instead:
S=[[
universe = {
...
}
]]
for w in S:gmatch('%b[] = {[^{]-"No".-},?') do
print(w)
end
Yep, it's possible through grep which supports -P (Perl Regex) parameter.
$ grep -oPz '.*\[[^\[\]]*\]\s*=\s*\{[^{}]*\["life"\]\s*=\s*"No"[^{}]*}.*' file
["Alpha Centauri"] = {
["planets"] = "3",
["life"] = "No",
["asteroid"] = "20"
},
["Rigel"] = {
["planets"] = "5",
["life"] = "No",
["asteroid"] = "11"
}
DEMO
From grep --help
-z, --null-data a data line ends in 0 byte, not newline
-o, --only-matching show only the part of a line matching PATTERN
Update:
\[[^\n]*\]\h*=\h*\{(?!,\s*\[[^\[\]]*\]\h*=\h*{).*?\["fontSize"\]\h*=\h*20,.*?\}(?=,\s*\[[^\[\]]*\]\h*=\h*{|\s*})
DEMO
$ pcregrep -oM '(?s)[^\n]*\[[^\n]*\]\h*=\h*\{(?!,\s*\[[^\[\]]*\]\h*=\h*{).*?\["fontSize"\]\h*=\h*20,.*?\}(?=,\s*\[[^\[\]]*\]\h*=\h*{|\s*})' file
["frame 1"] = {
["fontSize"] = 20,
["displayStacks"] = "%p",
["xOffset"] = 251.000518798828,
["stacksPoint"] = "BOTTOM",
["regionType"] = "icon",
["yOffset"] = 416.000183105469,
["anchorPoint"] = "CENTER",
["parent"] = "Target Shit",
["numTriggers"] = 1,
["customTextUpdate"] = "update",
["id"] = "Invulnerabilities 2",
["icon"] = true,
["fontFlags"] = "OUTLINE",
["stacksContainment"] = "OUTSIDE",
["zoom"] = 0,
["auto"] = true,
["selfPoint"] = "CENTER",
["width"] = 60,
["frameStrata"] = 1,
["desaturate"] = false,
["stickyDuration"] = true,
["font"] = "Emblem",
["inverse"] = false,
["height"] = 60,
}
["frame 2"] = {
["fontSize"] = 20,
["displayStacks"] = "%p",
["parent"] = "Target Shit",
["xOffset"] = 118.000427246094,
["stacksPoint"] = "BOTTOM",
["anchorPoint"] = "CENTER",
["untrigger"] = {
},
["regionType"] = "icon",
["color"] = {
1, -- [1]
1, -- [2]
1, -- [3]
1, -- [4]
},
["desaturate"] = false,
["frameStrata"] = 1,
["stickyDuration"] = true,
["width"] = 60,
["font"] = "Emblem",
["inverse"] = false,
["icon"] = true,
["height"] = 60,
["yOffset"] = 241
}
(?s) DOTALL modifier which makes dots in your regex to match even line breaks.
Using a proper lua parser in perl
This is not a quick'n'dirty snippet, but a robust way to query a lua's DS :
use strict; use warnings;
use Data::Lua; # lua 2 perl parser
use Data::Dumper; # to dump Data Structures (in color)
# retrieving the lua'DS in a perl's DS
my $root = Data::Lua->parse_file('lua.conf');
# iterating over keys of planet's HASH
foreach my $planet (keys $root->{universe}->{stars}) {
print Dumper { $planet => $root->{universe}->{stars}->{$planet} }
if $root->{universe}->{stars}->{$planet}->{life} eq "No";
}
Output
$VAR1 = {
'Rigel' => {
'planets' => '5',
'life' => 'No',
'asteroid' => '11'
}
};
$VAR1 = {
'Alpha Centauri' => {
'asteroid' => '20',
'life' => 'No',
'planets' => '3'
}
};
How To
install Data::Lua if not already installed with # cpan Data::Lua
put the Data Structure in the file lua.conf
put this script in the same dir in by example lua_DS_parser.pl
run the script with $ perl lua_DS_parser.pl
enjoy ;)
You could use something like this
grep -C 2 -E 'life.+= "No"' path_to_file
But in my opinion better way is converting files to some common format.
I have some documents in my Couchbase with the following template:
{
"id": 102750,
"status": 5,
"updatedAt": "2014-09-10T10:50:39.297Z",
"points1": 1,
"points2": -3,
"user1": {
"id": 26522,
...
},
"user2": {
"id": 38383,
...
},
....
}
What I want to do is to group the documents on the user and sum the points for each user and then show the top 100 users in the last week. I have been circling around but I haven't come with any solution.
I have started with the following map function:
function (doc, meta) {
if (doc.user1 && doc.user2) {
emit(doc.user1.id, doc.points1);
emit(doc.user2.id, doc.points2);
}
}
and then tried the sum to reduce the results but clearly I was wrong because I wasn't able to sort on the points and I couldn't also include the date parameter
you need to see my exemple I was able to group by date and show the values with reduce. but calculate the sum I did it in my program.
see the response How can I groupBy and change content of the value in couchbase?
I have solved this issue by the help of a server side script.
What I have done is I changed my map function to be like this:
function (doc, meta) {
if (doc.user1 && doc.user2) {
emit(dateToArray(doc.createdAt), { 'userId': doc.user1.id, 'points': doc.points1});
emit(dateToArray(doc.createdAt), { 'userId': doc.user2.id, 'points': doc.points2});
}
}
And in the script I query the view with the desired parameters and then I group and sort them then send the top 100 users.
I am using Node JS so my script is like this: (the results are what I read from couchbase view)
function filterResults(results) {
debug('filtering ' + results.length + ' entries..');
// get the values
var values = _.pluck(results, 'value');
var groupedUsers = {};
// grouping users and sum their points in the games
// groupedUsers will be like the follwoing:
// {
// '443322': 33,
// '667788': 55,
// ...
// }
for (var val in values) {
var userId = values[val].userId;
var points = values[val].points;
if (_.has(groupedUsers, userId)) {
groupedUsers[userId] += points;
}
else
groupedUsers[userId] = points;
}
// changing the groupedUsers to array form so it can be sorted by points:
// [['443322', 33], ['667788', 55], ...]
var topUsers = _.pairs(groupedUsers);
// sort descending
topUsers.sort(function(a, b) {
return b[1] - a[1];
});
debug('Number of users: ' + topUsers.length + '. Returning top 100 users');
return _.first(topUsers, 100);
}