Code not indenting properly. Is there a solution? - r

It seems that the python code in R reticulate is not indenting automatically. E.g. when I write
if x < 0:
print("negative")
else:
print("positive")
the third line should move automatically at the same level of if but, it actually does not and I get the message IndentationError: unexpected indent (<string>, line 1)
Is this bug or can it be corrected?

This can be solved by correcting the indentation of you code, following Python rules :
You need to unindent the else so it's indentation match the if ones. Rstudio don't indent correctly for Python to this day.
if x < 0:
print("negative")
else:
print("positive")

Related

Exclude source file line range from a single lintr (NOT all lintr)

To check the code quality of my package I am using the package lintr using the command
lintr::lint_package()
and get one result that I want to ignore:
functions should have cyclomatic complexity of less than 15
How can I ignore this single "false positive" lintr result of a single lintr (cyclocomp_linter)
for a file (line number range)?
Edit 1: Currently I am using this .lintr config file as a workaround (by disabling the lintr completely):
linters: with_defaults(
cyclocomp_linter = NULL # instead of NULL I could use: cyclocomp_linter(16)
)
Although it doesn't solve your problem exactly, you can wrap that function with # nolint start then # nolint end to prevent any linter from flagging that function.
The syntax for preventing a specific linter from flagging a specific set of lines is currently under development - see https://github.com/jimhester/lintr/pull/660 . This will be present in the next major lintr release (3.0.0).

How to suppress unwanted Plot figure object information in Jupyter Notebook

I want to suppress any text output when I run Jupyter Notebook cell. Specifically I output some figures and each is accompanied by something like:
<Figure size 432x288 with 0 Axes>
I have seen that if I put a ; at the end of a line, it should suppress the output, but it is not working in my case.
The code:
for i in tqdm_notebook(range(data.shape[0])):
print('BIN:',i)
fig = plt.figure(figsize=(15,4))
plt.tight_layout()
gs = gridspec.GridSpec(2,1)
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(match[window_begin:window_end],'k')
plt.vlines(i,-np.max(match[window_begin:window_end])*0.05,np.max(match[window_begin:window_end])*1.05,'r',linewidth=4,alpha=0.2)
ax1.set_xlim(0-1,post_bin_match_median[window_begin:window_end].shape[0])
ax1.set_ylim(-np.max(match[window_begin:window_end])*0.05,np.max(match[window_begin:window_end])*1.05)
plt.tick_params(axis='y', which='both', left=True, labelleft=False)
ax1.tick_params(axis='x', which='both', bottom=False, labelbottom=False)
plt.grid()
ax2 = fig.add_subplot(gs[1, 0])
fig.subplots_adjust(hspace=0.0)
ax2.plot(gp_mjds[:],gp_data[i,:],'k')
ax2.errorbar(remain, all[i,:], yerr=all_noise[i], fmt=".k", capsize=0);
ax2.fill_between(gp[:], gp2[i,:] - np.sqrt(gp_var[i,:]), gp2[i,:] + np.sqrt(gp_var[i,:]),color="k", alpha=0.2)
ax2.set_xlim(gp[0],gp[-1])
plot_y_min = np.minimum(np.min(gp2[:,:] - np.sqrt(gp_var[:,:])),np.min(all_profile_residuals[:,:]-y_noise))
plot_y_max = np.maximum(np.max(gp2[:,:] + np.sqrt(gp_var[:,:])), np.max(all[:,:]+y_noise))
ax2.set_ylim(plot_y_min,plot_y_max)
plt.grid()
plt.show()
plt.clf()
plt.close(fig);
The semi-colon would work if the typical output from the last line of the cell is what you are trying to suppress. As succinctly summarized by #kynan here, "The reason this works is because the notebook shows the return value of the last command. By adding ; the last command is "nothing" so there is no return value to show."
However, you have a loop inside a cell generating objects.
The culprit seems to be plt.clf(). Comment out that line or remove it from your code, and it should fix it.
Plus, I'd remove plt.show() as it isn't necessary when plt.clf() is removed, and I am seeing it being in the loop causing fig = plt.figure(figsize=(15,4)) to also show output text like you posted in your issue.
(I'll add for others looking at this later, that it is important have %matplotlib inline or %matplotlib notebook at the start of the cell (or at the start of a cell somewhere above this one.))
A complete guide on how to hide or remove content in Jupyter is available from the official documentation: https://jupyterbook.org/interactive/hiding.html#
For removing the single output line, you can tweak the command lines by adding a _ = [command ] assignment as suggested in this blog: https://www.tutorialguruji.com/python/suppress-output-in-matplotlib/.
The underscore there is a throwaway variable, actually an unidentified variable "when not in interactive mode". See the official Python documentation: https://docs.python.org/3.9/reference/lexical_analysis.html#reserved-classes-of-identifiers

Python Interpreting things from document

So, I am essentially just dreaming up ideas right now.
I was wondering if it was possible to make a python program that can read a document, take a line from the document, make an if/else statement with it (Like if the text on that line is equal to Hello, than say hello back), and then continue onto the next line. I have already kind of done this in a shell fashion but I want to see if it is possible to have python read the line of a document, interpret it, display something, and move on to the next line of the document.
(I am prepared for this post to get tons of -1's for not knowing how to program a lot of python, and probably just not being clear enough. So before you -1, just add a comment saying what you need me to be clear about.)
The version of python of my choice would be 2.5.
Since you don't know any Python, try this:
with open("file.txt") as f:
for line in f:
if line.strip() == "Hello":
print "Hello back"
or without the exception-safe clause:
for line in open("file.txt"):
if line.strip() == "Hello":
print "Hello back"
the strip() removes the ending newline \n from the line
That is actually a very simple task in Python:
file = open("file.txt") # open the file
while True:
word = file.readline() # read a line from the file
print word # print it to the console
if word == "": # if out of words...
file.close() # ...close the file
break # and break from while loop and exit program

Emacs ESS Mode TAB stops indenting

I'm using Emacs 24 on Windows to write some R code. Up until about 30 minutes ago, whenever I would write a new function, ESS would automatically indent the lines following the function declaration and pressing the tab key on a new blank line would jump me to the appropriately indented starting position inside the declaration.
EG:
foo <- function() {
first line started here
second line here. .etc
}
Now, it is hard wrapping everything to the left, and not responding by automatically indenting after the function declaration or when I hit the tab key.
foo <- function() {
first line
second line
}
I've googled, but my google-fu is failing me on this. Anyone know how to restore default tab behavior to ESS in Emacs?
just for the record. Whenever such things happens, select the whole buffer C-x h and press C-M-\ to indent the whole region. This will show unambiguously the syntax error.
Try to add a space after "#".
I don't think ESS-mode handles # as a comment unless you have space after it.
I just came across the same problem you describe.
None of the above seemed to work, but I narrowed it down to using a carriage return and then an open parenthesis inside a string, like so:
### indent ( <tab> ) working fine up to here
s1 <- "string
(then this in brackets)"
### now indent does nothing!
The fact that it's balanced later doesn't help. I think EMACS reads this as opening a new expression/ block in spite of the fact that it occurs in a quoted string. This seems to apply also to expression openers { and [. It only seems to happen when the 'open expression' symbol appears at the start of the line...
In my case the string was part of a plot label, so the solution was to use \n instead.

Customize zsh's prompt when displaying previous command exit code

Zsh includes the ability to display the return code/exit code of the previous command in the prompt by using the %? escape sequence.
However I would like to have the following prompt:
user#host ~ [%?] %
when the exit code is different from 0 and:
user#host ~ %
when exit code is 0.
If I use %? alone it is always displayed, even if %? is 0.
In addition I want the square brackets but only when the exit code not 0.
What is the simplest way to do this?
Add this in the position in PS1 where you want the exit code to appear:
%(?..[%?] )
It's a conditional expression. The part between the two dots (nothing in this case) is output if the expression before the first dot is true. The part after the second dot is output if it's false.
For example:
PS1='%n%m %~ %(?..[%?] )%# '
Alternatively, you can:
setopt PRINT_EXIT_VALUE
to always print a newline showing previous return value.
I don't prefer this for ordinary use, but it is often good for debugging shell scripts.

Resources