I use syntaxhighlighter on my blog to format C++ code. Since last few days I am getting extra blank line after each line after each line of code. Please see this link for more info.
Following is the code I wrote there. I am not seeing any line break in that.
//Define MAX 1 less so that adding 1 doesn't make it 0
#define MAX 0xFFFFFFFE;
unsigned int jump(int *array, int n)
{
unsigned int *result = new unsigned int[n];
int i, j;
//Boundry conditions
if (n == 0 || array[0] == 0)
return MAX;
result[0] = 0; //no need to jump at first element
for (i = 1; i < n; i++)
{
result[i] = MAX; //Initialization of result[i]
for (j = 0; j < i; j++)
{
//check if jump is possible from j to is
if (array[j] >= (i-j))
{
//check if better solution available
if ((result[j] + 1) < result[i])
result[i] = result[j] + 1; //updating result[i]
}
}
}
//return result[n-1]
unsigned int answer = result[n-1];
delete[] result;
return answer;
}
Surprisingly this is happening only for new posts, all old posts are shown currently w/o extra blank lines.
Your source code (before JavaScript) basically looks like this:
<pre>
First line
<br />Another line
<br />Last line
</pre>
If you are using a <pre> tag, you don't need to insert <br /> tags to force line feeds but, if you do, they should replace the original line feed.
Update: I'll make a blind guess with the little information we have. Your code is saved into a local file using Windows line feeds (CR+LF). The server runs Linux and applies a function that replaces Linux line feeds (LF). with <br /> tags so you end up with CR<br />. This is inserted into a <pre> tag so the browser converts this to two consecutive line feeds.
My hypothesis seems likely because, if you save the HTML source code into a file and open it with a text editor that can display line feeds, it'll show the file is using Linux style (LF) everywhere expect in the code snippet, where it's using CR (old MacOS 9 style).
Workaround: save the file as Unix before copying or copy with another editor or copy to another browser.
Related
Question: Is there an automatic way to add the line numbers of the original R Markdown source code to the formatted code portions of the HTML output produced by knitr?
Purpose: My ultimate goal is to be able to quickly move to parts of my source R Markdown code that I identify need editing while reviewing the HTML output. Using line numbers is the fastest way I know to do this, but I welcome hearing others' strategies.
Solutions I've tried:
Although the chunk option attr.source = '.numberLines' will attractively add line numbers to the code parts of the HTML output, that option doesn't provide the source-code line numbers automatically (you must force that manually using .startFrom) -- instead, the lines are renumbered at the beginning of each chunk and after each piece of output. In the following illustration, I've included .startFrom to force the line numbering to start at 10, to match the line number for test_data <- rnorm(10) which is the line number I want to see. A practical solution, however, needs the starting number to be automatic. Also, in the HTML output (shown beneath the code) the hist(test_data) line is renumbered starting with the same starting number, 10. I would want that to be 12, as in the source code.
This question (How can I add line numbers that go across chunks in Rmarkdown?) is related, but the OP just needed any unique identifier for each line, not necessarily the line numbers of the source code, with the solution being sequential numbers unrelated to the source-code line numbers.
Considered option: I've considered preprocessing my code by running an initial script that will add line numbers as comments at the end of lines, but I'd prefer a solution that is contained within the main knitr file.
Reverted to this update based on your request
I'm glad you figured out the issue. I hadn't considered or tested the code for a chunk that only had a single line of code. However, based on your feedback, I've accounted for it now.
If you'd like it accounted for and would like to keep the color in the code, let me know. I'll add it back with the fix for single lines of code. (I'll stick to the ES6.)
This version uses the line numbers you'll see in the source pane of RStudio. You must use RStudio for this to work. The following changes to the RMD are necessary:
The library(jsonlite) and library(dplyr)
An R chunk, which you could mark include and echo as false
A set of script tags outside of and after that chunk
A JS chunk (modified from my original answer)
The R chunk and R script need to be placed at the end of your RMD.
The JS chunk can be placed anywhere.
The R chunk and script tags **in order!
Put me at the end of the RMD.
```{r ignoreMe,include=F,echo=F}
# get all lines of RMD into object for numbering; R => JS object
cx <- rstudioapi::getSourceEditorContext()$contents
cxt <- data.frame(rws = cx, id = 1:length(cx)) %>% toJSON()
```
<script id='dat'>`r cxt`</script>
The JS chunk
This collects the R object that you made in the R chunk, but its placement does not matter. All of the R code will execute before this regardless of where you place it in your RMD.
```{r gimme,engine="js",results="as-is",echo=F}
setTimeout(function(){
scrCx = document.querySelector("#dat"); // call R created JSON*
cxt = JSON.parse(scrCx.innerHTML);
echoes = document.querySelectorAll('pre > code'); // capture echoes to #
j = 0;
for(i=0; i < echoes.length; i++){ // for each chunk
txt = echoes[i].innerText;
ix = finder(txt, cxt, j); // call finder, which calls looker
stxt = txt.replace(/^/gm, () => `${ix++} `); // for each line
echoes[i].innerText = stxt; // replace with numbered lines
j = ix; // all indices should be bigger than previous numbering
}
}, 300);
function looker(str) { //get the first string in chunk echo
k = 0;
if(str.includes("\n")) {
ind = str.indexOf("\n");
} else {
ind = str.length + 1;
}
sret = str.substring(0, ind);
oind = ind; // start where left off
while(sret === null || sret === "" || sret === " "){
nInd = str.indexOf("\n", oind + 1); // loop if string is blank!
sret = str.substring(oind + 1, nInd);
k++;
ind = oind;
oind = nInd;
}
return {sret, k}; // return string AND how many rows were blank/offset
}
function finder(txt, jstr, j) {
txsp = looker(txt);
xi = jstr.findIndex(function(item, j){ // search JSON match
return item.rws === txsp.sret; // search after last index
})
xx = xi - txsp.k + 1; // minus # of blank lines; add 1 (JS starts at 0)
return xx;
}
```
If you wanted to validate the line numbers, you can use the object cx, like cx[102] should match the 102 in the HTML and the 102 in the source pane.
I've added comments so that you're able to understand the purpose of the code. However, if something's not clear, let me know.
ORIGINAL
What I think you're looking for is a line number for each line of the echoes, not necessarily anything else. If that's the case, add this to your RMD. If there are any chunks that you don't want to be numbered, add the chunk option include=F. The code still runs, but it won't show the content in the output. You may want to add that chunk option to this JS chunk.
```{r gimme,engine="js",results="as-is"}
setTimeout(function(){
// number all lines that reflect echoes
echoes = document.querySelectorAll('pre > code');
j = 1;
for(i=0; i < echoes.length; i++){ // for each chunk
txt = echoes[i].innerText.replace(/^/gm, () => `${j++} `); // for each line
echoes[i].innerText = txt; // replace with numbered lines
}
}, 300)
```
It doesn't matter where you put this (at the end, at the beginning). You won't get anything from this chunk if you try to run it inline. You have to knit for it to work.
I assembled some arbitrary code to number with this chunk.
Firstly, apologies if an answer is somewhere around the internet, but I've searched far and wide and found nothing relevant.
So, as most of you are aware, there are limitations from injecting rules in CSS sheets in certain conditions. Mine is that I cannot use a variable inside a .div:nth-child(thejsvariable) {transform: whatever-transform-option;}. But that extends to any style modifications on using JS variable in the CSS string.
I've tried vaaaarious options and ideas. The most recent one is the one with this problem.
I'm trying to modify any style with a simple getElementById, in which the ID consists of the string "hexpod" and the loop variable.
Now, for the loop variable I need it to select specific items that are on each second row of a grid.
So Tried to nest multiple loops with "multiple of" conditionals.
var wholeRowItems = rowIterations.toFixed(0);
for (var r = 1; r <= hexIterations; r++) {
if (r % 15 == 1 ) {
console.log(r);
for (var t = 1; t <= wholeRowItems; t++) {
console.log(t);
}
}
}
For a bit of Context my grid is fully responsive related to the size of the body.
So the var rowIterations returns how many items with fixed size fit in the body on a row. In my case it's 15 with the toFixed(0) method.
The var hexIterations returns how many items fit in the body. In my case it's 134 items.
Console log returns (not an array, but separate numbers) the range between 1 and 15 followed each time by 16, 31, 46 and so on.
At this point I'm just very frustrated and crying for help on solutions or at least ideas.
You can find the entire code here, if you want to see what's up around the problem, just in case it's relevant.
https://jsitor.com/AXU_pOzBD
Edit: I forgot to mention that once I've placed a getElementById('hexpod' + r + t) it selected only 2 rows, starting in the middle of the rows, one at the beginning and one at about the end aand my brain just faded away.
After more neurons grinding I've managed to find the solution, and I'm post it for the record in case anyone else stumbles over this problem.
I've managed to better understand the conditional logic of multiple of number identification. There should've been "0" instead of "1" in r % 30 statement.
Got the getElementById method to identify the string "hexpod" with r (that is set to target each second row) -15 (in order to start from the second row) + t (to use every grid element of the targeted row).
var wholeRowItems = rowIterations.toFixed(0);
for (var r = 1; r <= hexIterations; r++) {
if (r % 30 === 0 ) {
for (var t = 1; t <= 15; t++) {
var rt = document.getElementById("hexpod" + Number(r - 16 + t));
rt.style.transform = "translateX(-100%) translateY(-75%) rotate(-60deg) skewY(30deg) scale(0.95)";
}
}
}
Our JavaScript application fails in very strange ways when running on iOS 10 beta 2 and beta 3 (running on iPhone 6). When looking at logs I can see that arrays contain NaN's and 0x00's in unexpected places. I managed to produce a test program that can quite reliably reproduce the behavior.
I have filled a bug report with Apple but haven't heard back so I am a bit concerned whether this will be fixed or not. So as a first thing, I would like to hear if someone can reproduce it and at least confirm there is a bug (and not just a misunderstanding on my part etc.). I'm fairly sure of this myself, but always good to be on the safe side! Could also be others have encountered it and found a workaround or maybe if some WebKit developers run into it, they might be able to help.
Test program showing bug
Here's the test progarm. The problem doesn't occur every time but the JavaScript code in the page can detect when it occurred and will keep refreshing the page until it occurs. On a non-affected browser, this means the page will keep refreshing. On an affected browser (such as Safari on iOS 10 beta 2 and beta 3 running on an iPhone 6) the refreshing will stop after some iterations (typically 5-10) and the display error.
The program operates by creating an uint8array of size 8192 (it seems smaller array sizes causes the error to be more rare). It will fill this array with dummy values, then call "toStr" which first allocates a new plain Array, then copies the contents of the uint8array to the plain array, narrowing each element along the way. While doing this it builds up a string containing the original value and the copied value. When the error occurs, the element in the target array turns out to be NaN which should not be able to occur since it by construction contains only integers. The doTest() function tests for whether such a NaN value is contained in the resulting string which shows that the error has occurred.
Note that within each refresh, the program runs 20 iterations and here it is also random which iteration that fails. However, I have observed that if the error doesn't occur among the first 20 of iterations, it is not likely to occur at all within this page load even if one ran an indefinite number of iterations, and this is the reason why I added the reload page logic.
Note that the program logic itself is completely deterministic so every run should be the same, which is also the case on other browsers. More detail can be seen by removing the comments from the log() statement in the doTest() function so it prints out the array.
Note that the problem seems to go away if the function "narrow" is inlined rather than being a separate function (even though these two programs should of course be semantically equivalent). Also, if one omits the shift from "state >> 8" the error also seemingly goes away so either the exact array values are significant or this rewrite somehow affects how the JIT operates. Hence, it is critical the exact program structure is used when testing for the problem.
<html>
<head>
<title>Array test page</title>
<script>
log = function(s) {
var ta = document.getElementById("ta");
ta.value += s + "\n";
}
function narrow(x_0) {
return x_0 << 24 >> 24;
}
function toStr(i8bytes) {
var bytes, i, str;
bytes = new Array(i8bytes.length);
str = '';
for (i = 0; i < 16; i++) {
bytes[i] = narrow(i8bytes[i]);
str += '*** (' + i8bytes[i] + ' - ' + bytes[i] + ')';
}
return str;
}
function doTest() {
var sz = 8192;
state = 0;
var i;
var fnd = false;
for (i = 0; i < 20; i++) {
var arr = new ArrayBuffer(sz);
var i8bytes = new Uint8Array(arr, 0, sz);
for (j = 0; j < i8bytes.length; j++) {
state = state + 1;
var v = state >> 8;
i8bytes[j] = narrow(v);
}
var str = toStr(i8bytes);
// log(str); <-- REMOVE COMMENT to show results
if (str.indexOf("NaN") !== -1) {
log("Found NaN at iteration" + i);
log(str);
fnd = true;
break;
}
}
return fnd;
}
function start() {
log("Starting: " + new Date());
if (!doTest()) {
location.reload(true); // <--- REMOVE THIS LINE TO PREVENT RELOAD
}
};
</script>
</head>
<body onload="start()">
<h1>Array test page</h1>
<p>Note that on a non-affected browser this page will reload indefinitely. On an affected browser, it
will stop reloading once the problem is detected.
<p>
<textarea id="ta" rows="10" cols="40"></textarea>
</body>
</html>
I have an array with 2000 arrays which each have 2000 values (to stock a 2000x2000 image) in javascript in an HTA. I have this code to test how many "blue" values there are in the array (the array's name is image):
var bluePixels = 0;
for(i = 0; i < image.length; i++){
for(j = 0; j < image[i].length; j++){
if(image[i][j] == "blue"){bluePixels = bluePixels + 1}
}
}
alert(bluePixels);
The problem is that it shows a message where it says something like "Stop execution of this script? A script on this page is slowing down Internet Explorer. If it continues, your computer might not answer." (I'm not sure of the exact words because my computer is in French) and then, if I click on "no", it does the alert(bluePixels) like it should but if I push on "yes" it doesn't. How can I block this message? (I know that there are workarounds like telling the user in the beginning to press "no" but I want a real solution)
For IE versions 4 to 8, you can do this in the registry. Open the following key in Regedit: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Styles. If this key doesn't exist, create it. In this key, create a DWORD value called MaxScriptStatements and give it the value 0xFFFFFFFF (don't worry if the value changes automatically when you click on OK, that's normal).
You can program JavaScript to do this automatically:
var ws = new ActiveXObject("WScript.Shell");
ws.RegWrite("HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\Styles\\","");
ws.RegWrite("HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\Styles\\MaxScriptStatements",1107296255,"REG_DWORD");
Seems like you have an answer here
From the answer:
"The only way to solve the problem for all users that might be viewing your page is to break up the number of iterations your loop performs using timers, or refactor your code so that it doesn't need to process as many instructions."
So the first approach can be attained using a timeout for each such large iteration.
You need to split the 2000x2000 for-loop's up in smaller pieces of code, eg threads or processes, so the browsers maximum execution time not is becoming exhausted. Here the image array is parsed for one row at a time, controlled by a timer :
var bluePixels = 0,
timer,
i = 0;
function countBluePixels() {
for (var j = 0; j < image[i].length; j++){
if (image[i][j] == "blue") {
bluePixels = bluePixels + 1;
}
}
i=i+1;
if (i>image.length) {
clearInterval(timer);
alert(bluePixels);
}
}
timer = window.setInterval(countBluePixels, 0);
The code is the same, just splitted up in 2000 processes instead of 1.
I'm doing a simple exercise meant to be in JavaScript that consists of turning a binary into its respective decimal value... I feel I'm close to finishing the project but for some reason my for loops wont work after a certain line.
//function is called after the press of a button
function convertToBinary (){
oText= document.all?document.all("inout"):document.getElementById("inout");
//inout represents a textarea
sText= oText.value;
alert(sText);
aText = sText.split(/\n\r|\n|\r/g); //got this line after searching this site for solutions
/*alert(aText[1]);
alert(aText[2]);
alert(aText[3]);*/
aText does have values stored, checked a thousand times, but after this line everything goes down, and i can't seem to find the reason why. Here is the rest of the code copy/pasted from my text editor.
for(y = 0; y < aText.lenght;y++){
alert(aText[y]);
}
iCurrent=0;
aBina= aText[0].split("");
for(var x = aBina.lenght-1; x >= 0; x--){
iCurrent = (iCurrent*2) + parseInt(aBina[x]);
alert(iCurrent);
}
aAsci[0]=iCurrent;
alert(iCurrent); //Alerts 0
}
NOTE: variables and arrays are properly defined in the first few lines of the code, i have used them in a previous function that does the opposite(convert decimals to binary) and that works fine. I was sure to clean each array and variable after the function is done. ("o" is for objects, "s" for strings, "a" for arrays, "i" for int's).
There is no apparent syntax error to be seen. I would appreciate not posting the solution for the exercise unless it is really necessary, i might not be doing it right just yet but I like to think through the algorithms my self :p. My problem is for loops are as if the condition was not met, they are just being skipped. I'm using Opera Next as my web browser and the "inspect element" Console does not show any errors either.
Thank you in advance.
This should be,
for(y = 0; y < aText.length;y++)
and this
for(var x = aBina.length-1; x >= 0; x--){
instead
for(var x = aBina.lenght-1; x >= 0; x--){
for(y = 0; y < aText.lenght;y++)
you mispelled this one, "LENGTH"