I am new to Python and I am having issues when breaking a line of code. I am using Python 3.6 on Spyder.
When I try to break any line and I run the code, Python reads only until before the backslash and retrieves and error. For example, I want to break
a = 1 + 2 + 3
into
a = (a + b \
+ 3)
It gives me the error SyntaxError: unexpected EOF while parsing.
I have checked with and without the backslash, and with different indentations in the second line.
I have read the way of breaking a line of code is this one...is there anything I have to activate on my IDE or something like that?
If you use parenthesis the line break is implicit, so you could break your line after the plus sign like so:
a = (a + b +
3)
Or like so:
a = (a + b
+ 3)
By the guidelines the backslash needs only to be used if necessary, otherwise please use the implicit one.
Related
I'm trying to parse indented blocks with pyparsing and indentedBlock
Here my code
from pyparsing import *
indent_stack = [1]
line = ungroup(restOfLine)
block = ungroup(indentedBlock(line, indent_stack))
# Work
data = """ foo
bar
tar
"""
block.parseString(data).pprint()
The problem is that parseString won't return. It seems to be waiting for more input or maybe I hit an infinite loop. If I put an unidnented line in the block start to work
data = """ foo
bar
tar
end
"""
But I want to be able to parse up to unindented line (the working case), or to the end of string (the not working case)
This is a bug in pyparsing. indentedBlock uses OneOrMore internally to implement the repetition of the embedded lines. But restOfLine does not fail if it is at the end of a line, and so once you get to the end of the string, indentedBlock's repetition just keeps finding empty restOfLines, and so indentedBlock just loops forever.
A workaround for now, until this bug gets fixed and released, is to change your definition of line from:
line = ungroup(restOfLine)
to
line = ungroup(~StringEnd() + restOfLine)
I couldn't figure out exactly why the code is doing this. I even tried running it in Debug mode and pausing, but it wouldn't even pause so that I could see where it was getting stuck.
A workaround you could use for now is modifying the data to add an unindented line:
from pyparsing import *
indent_stack = [1]
line = ungroup(restOfLine)
block = ungroup(indentedBlock(line, indent_stack))
# Work
data = """ foo
bar
tar
"""
block.parseString(data + "\nend").pprint()
# Result: [['foo'], ['bar'], ['tar']]
I am learning from the book Learn Python The Hard Way 3.6, by Zed Shaw
There are a series of 6 target.write commands towards the bottom of the script and he wants me to simplify them into a single target.write command using strings formats and escapes. However, I am stuck.
Here is the original code:
from sys import argv
script, filename = argv
print(f"We're going to erase {filename}")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")
input("?")
print("Opening the file...")
target = open(filename,'w')
print("Truncating the file. Goodbye!")
target.truncate()
print("Now I'm going to ask you for three lines")
line1 = input("line 1:")
line2 = input("line 2:")
line3 = input("line 3:")
print("Im going to write these to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finnaly, we close it")
target.close()
So far I have tried
target.write(line1),(line2),(line3)
but this gives a logical error of only writing to one line not all three.
target.write(line1) + (line2) + (line3)
with this one I get error
'unsupported operand types for +: 'int' + 'str'
target.write(line1),\n,(line2)\n(line3),\n
with this one I get error:
unexpected character after line continuation character
(<string>,line 22)
I have been googling and searching here for answers but have not found anything. One person posted a very similar question except for Zed's 2.7 book. However I am reading Zed's 3.6 book so the answers were no help to me unfortunately.
I'm not sure what you have and haven't covered so far in the book as I'm not familiar with it but one way to do what you want is to format the string first and then pass it to the write method like this:
target.write("{0}\n{1}\n{2}\n".format(line1, line2, line3))
I'm doing text parsing in Julia and need to test if certain strings are blank (in order to parse into floats). I have been using isblank() booleans in <0.4 Julia, but after upgrading to 0.4, I get the following warning:
julia> isblank(q)
WARNING: isblank(s::AbstractString) is deprecated, use all((c->begin
c == ' ' || c == '\t'
end),s) instead.
in depwarn at deprecated.jl:73
in isblank at deprecated.jl:50
while loading no file, in expression starting on line 0
true
What replaced isblank()? Is the above really the replacement? My googling didn't turn up anything useful.
Yes, that is the replacement.
Basically in #5939 and related issues, it was revealed that answering isblank is a lot harder than it might first appear given Unicode complexities.
The deprecation occurred in #8233.
Everything looks natural, it must be a replacement in new version, you can add the line bellow in your code and replace (using Ctrl+H) all isblank( with isblk(. I wish it works for you.
isblk(s)=all((c->begin c == ' ' || c == '\t' end),s)
now isblk([]) # => true
I am using lintr to ensure my code meets good R style guidelines, but for some reason, the commas_linter does not catch it when I do not put a space after a comma if there is a blank line preceding the erroneous line. Am I doing something wrong, or is this a bug in the package?
Here's a MWE
file: Test.r
#random comment
a <- c(4,5)
b = 7
Then, I run the following:
lintr::lint("./Test.r", linters = list(spacesAfterCommas = commas_linter,
useArrowForAssignments = assignment_linter))
The only error I get is the following:
./Test.r:4:3: style: Use <-, not =, for assignment.
b = 7
^
Why is the commas_linter not catching my error?
I need a QR code generator that generates 21500 unique serial number with a QR stamp, and export every 1000 code on a one PDF file, so we'll have 22 PDF file.
How can I do that?
Some time ago I've done a similar thing using Python, qrencode and LaTeX. I've modified my old code to fit your needs. I assumed you want A4 pages. The contents of the QR Codes are the PMY00001 to PMY22000 ASCII strings.
#!/usr/bin/env python
import random, base64, string, os, sys
width=7.7
height=7
print "\\documentclass[a4paper,10pt]{report}"
print "\\usepackage[absolute]{textpos}"
print "\\usepackage{nopageno}"
print "\\usepackage{graphicx}"
print "\\setlength{\\TPHorizModule}{1mm}"
print "\\setlength{\\TPVertModule}{1mm}"
print "\\textblockorigin{10mm}{10mm}"
print "\\setlength{\\parskip}{0pt}"
print "\\setlength{\\parindent}{0pt}"
print "\\setlength{\\fboxsep}{0pt}"
print "\\setlength{\\tabcolsep}{0pt}"
print "\\renewcommand{\\baselinestretch}{0.8}"
print ""
print "\\begin{document}"
idx=int(sys.argv[1])
for i in range(0,25):
for j in range(0,40):
b = 'PMY%05d' % idx
f = os.path.join("codes", b + ".png")
ff = os.popen("qrencode -lH -o " + f, "w")
ff.write(b)
ff.close()
print "\\begin{textblock}{" + str(width) + "}(" + str(width * i) + "," + str(height * j) + ")"
print "\\includegraphics[height="+str(height)+"mm]{" + f + "}"
print "\\end{textblock}"
idx=idx+1
print "\\end{document}"
To use it, write it as e.g. qrgen.py, add execution permissions chmod +x qrgen.py, create codes directory: mkdir codes and run ./qrgen.py 0 >codes.tex to generate the codes.tex document and then pdflatex codes.tex to generate codes.pdf file. The 0 argument is the starting serial number.
To get 22 such sheets it's best to use a loop:
for ((i=0;i<22;i++)); do ../qrgen.py $((i*1000+1)) >$i.tex; pdflatex $i.tex; done
Of course this is not the optimal solution - you can probably get a much faster one using Python qrencode library bindings instead of launching external qrencode program and some library for generating PDFs from Python directly instead of using pdflatex.
You can write a script in your language of choice that uses Google's QR code generator in a loop to generate all the codes you'll need and save them to a pdf. You'll need to provide more details if you need a more specific answer.