hf-tikz and sphinx are not playing well together - latex

I am trying to add some color to my matrices in sphinx. I was using hf-tikz for it before. However, when I add it to Sphinx, it renders it incorrectly.
The result that I am trying to get is
The result I am getting is
Here is the code that I have.
main.rst:
.. math::
\left(\begin{array}{cc}
\tikzmarkin[style red]{a}a\tikzmarkend{a}
& \tikzmarkin[style green]{b}b\tikzmarkend{b} \\
\tikzmarkin[style blue]{c}c\tikzmarkend{c}
& \tikzmarkin[style orange]{d}d\tikzmarkend{d} \\
\end{array}\right)
\star
\left(\begin{array}{cc}
\tikzmarkin[style red]{w}w\tikzmarkend{w}
& \tikzmarkin[style green]{x}x\tikzmarkend{x} \\
\tikzmarkin[style blue]{y}y\tikzmarkend{y}
& \tikzmarkin[style orange]{z}z\tikzmarkend{z} \\
\end{array}\right)
=
\left(\begin{array}{cc}
\tikzmarkin[hor=style red]{aw}{a\star w}\tikzmarkend{aw}
& \tikzmarkin[hor=style green]{bx}b\star x\tikzmarkend{bx} \\
\tikzmarkin[hor=style blue]{cy}c\star y\tikzmarkend{cy}
& \tikzmarkin[hor=style orange]{dz}d\star z\tikzmarkend{dz} \\
\end{array}\right)
conf.py
extensions = [
'sphinx.ext.imgmath',
]
# Math configurations (https://tex.stackexchange.com/a/69770/51173)
imgmath_image_format = 'svg'
imgmath_use_preview = True
imgmath_latex_preamble = r'''
\usepackage{xcolor}
\usepackage[customcolors]{hf-tikz}
\colorlet{myred}{red!50!purple!30}
\colorlet{mygreen}{green!50!lime!60}
\colorlet{myblue}{blue!50!white!50}
\colorlet{myorange}{orange!80!red!60}
\colorlet{mycyan}{cyan!90!blue!60}
\colorlet{mymagenta}{magenta!90!red!60}
\tikzset{
style red/.style={
set fill color=myred,
set border color=white,
},
style green/.style={
set fill color=mygreen,
set border color=white,
},
style blue/.style={
set fill color=myblue,
set border color=white,
},
style orange/.style={
set fill color=myorange,
set border color=white,
},
style cyan/.style={
set fill color=mycyan,
set border color=white,
},
style magenta/.style={
set fill color=mymagenta,
set border color=white,
},
%
hor/.style={
above left offset={-0.15,0.31},
below right offset={0.15,-0.125},
#1
},
ver/.style={
above left offset={-0.1,0.3},
below right offset={0.15,-0.15},
#1
}
}
'''
Makefile
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
#$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
#$(SPHINXBUILD) -M $# "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
make.bat
#ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd
EDIT: Added makefile used to build the rst's

I think I found why this was happening: the problem was in the sphinx.ext.imgmath extension + hf-tikz not working well with the DVI files.
When converting the math equations, sphinx creates a very basic latex document, and compiles it using latexpdf into a DVI file. After that the file is converted into an SVG, and the resulting svg file is copied to the sphinx's _build directory. The problem is that dvisvgm (used by imgmath) cannot convert tikz stuff. Alternative would be using extended DVI, but that doesn't work well either.
The solution is to compile everything into PDF, and convert that pdf into SVG. This is slightly problematic, and the only way I found is to use pdf2svg + pdfcrop. I ended up modifying the imgmath.py into a custom extension. Below are the changes that I put in the imgmath.py. The changes require the use of external applications, so I don't think there is a merit in creating a pull request (at least not with a more scalable solution).
Changes in the imgmath.py:
Create a new method:
def convert_pdf_to_svg(pdfpath, builder):
# type: (str, Builder) -> Tuple[str, int]
"""Convert DVI file to SVG image."""
tempdir = ensure_tempdir(builder)
filename = path.join(tempdir, 'math.svg')
name = 'pdfcrop'
command = [name, pdfpath, pdfpath]
run_external_command(command, name)
name = 'pdf2svg'
command = [name, pdfpath, filename]
run_external_command(command, name)
return filename, None
In the compile_math function, inside the try block, replace the return statement with the following
if builder.config.imgmath_pdf2svg:
return path.join(tempdir, 'math.pdf')
else:
return path.join(tempdir, 'math.dvi')
Inside the render_math method, in the block titles # .dvi -> .png/svg, replace the try block with the following
try:
if image_format == 'png':
imgpath, depth = convert_dvi_to_png(dvipath, self.builder)
elif image_format == 'svg':
if self.builder.config.imgmath_pdf2svg:
imgpath, depth = convert_pdf_to_svg(dvipath, self.builder)
else:
imgpath, depth = convert_dvi_to_svg(dvipath, self.builder)
except InvokeError:
self.builder._imgmath_warned_image_translator = True # type: ignore
return None, None
Finally, add a new configuration entry in the very end of the imgmath.py:
app.add_config_value('imgmath_pdf2svg', False, 'html')
After that, you can write in the conf.py to enable the tikz images.
imgmath_image_format = 'svg'
imgmath_latex = 'latexmk'
imgmath_latex_args = ['-pdf']
imgmath_pdf2svg = True # Available only in the custom `imgmath.py`
patch for imgmath extension. Includes some other stuff :)
The patch goes a->b.
--- a/imgmath.py
+++ b/imgmath.py
## -15,7 +15,7 ##
import sys
import tempfile
from hashlib import sha1
-from os import path
+from os import path, symlink
from subprocess import CalledProcessError, PIPE
from typing import Any, Dict, List, Tuple
## -157,6 +157,11 ##
with open(filename, 'w', encoding='utf-8') as f:
f.write(latex)
+ for add_file in builder.config.imgmath_latex_additional_files:
+ filename = path.join(tempdir, path.basename(add_file))
+ if not path.exists(filename):
+ symlink(path.join(builder.confdir, add_file), filename)
+
# build latex command; old versions of latex don't have the
# --output-directory option, so we have to manually chdir to the
# temp dir to run it.
## -165,9 +170,15 ##
command.extend(builder.config.imgmath_latex_args)
command.append('math.tex')
+ output_extension = 'dvi'
+ if builder.config.imgmath_latex == 'xelatex':
+ output_extension = 'xdv'
+ if builder.config.imgmath_pdf2svg:
+ output_extension = 'pdf'
+
try:
subprocess.run(command, stdout=PIPE, stderr=PIPE, cwd=tempdir, check=True)
- return path.join(tempdir, 'math.dvi')
+ return path.join(tempdir, 'math.' + output_extension)
except OSError:
logger.warning(__('LaTeX command %r cannot be run (needed for math '
'display), check the imgmath_latex setting'),
## -177,7 +188,7 ##
raise MathExtError('latex exited with error', exc.stderr, exc.stdout)
-def convert_dvi_to_image(command: List[str], name: str) -> Tuple[bytes, bytes]:
+def run_external_command(command: List[str], name: str) -> Tuple[bytes, bytes]:
"""Convert DVI file to specific image format."""
try:
ret = subprocess.run(command, stdout=PIPE, stderr=PIPE, check=True)
## -203,7 +214,7 ##
command.append('--depth')
command.append(dvipath)
- stdout, stderr = convert_dvi_to_image(command, name)
+ stdout, stderr = run_external_command(command, name)
depth = None
if builder.config.imgmath_use_preview:
## -227,7 +238,7 ##
command.extend(builder.config.imgmath_dvisvgm_args)
command.append(dvipath)
- stdout, stderr = convert_dvi_to_image(command, name)
+ stdout, stderr = run_external_command(command, name)
depth = None
if builder.config.imgmath_use_preview:
## -239,6 +250,21 ##
break
return filename, depth
+
+def convert_pdf_to_svg(pdfpath, builder):
+ # type: (str, Builder) -> Tuple[str, int]
+ """Convert DVI file to SVG image."""
+ tempdir = ensure_tempdir(builder)
+ filename = path.join(tempdir, 'math.svg')
+
+ name = 'pdfcrop'
+ command = [name, pdfpath, pdfpath]
+ run_external_command(command, name)
+
+ name = 'pdf2svg'
+ command = [name, pdfpath, filename]
+ run_external_command(command, name)
+ return filename, None
def render_math(self: HTMLTranslator, math: str) -> Tuple[str, int]:
## -291,7 +317,10 ##
if image_format == 'png':
imgpath, depth = convert_dvi_to_png(dvipath, self.builder)
elif image_format == 'svg':
- imgpath, depth = convert_dvi_to_svg(dvipath, self.builder)
+ if self.builder.config.imgmath_pdf2svg:
+ imgpath, depth = convert_pdf_to_svg(dvipath, self.builder)
+ else:
+ imgpath, depth = convert_dvi_to_svg(dvipath, self.builder)
except InvokeError:
self.builder._imgmath_warned_image_translator = True # type: ignore
return None, None
## -396,8 +425,10 ##
['-gamma', '1.5', '-D', '110', '-bg', 'Transparent'],
'html')
app.add_config_value('imgmath_dvisvgm_args', ['--no-fonts'], 'html')
+ app.add_config_value('imgmath_pdf2svg', False, 'html')
app.add_config_value('imgmath_latex_args', [], 'html')
app.add_config_value('imgmath_latex_preamble', '', 'html')
+ app.add_config_value('imgmath_latex_additional_files', [], 'html')
app.add_config_value('imgmath_add_tooltips', True, 'html')
app.add_config_value('imgmath_font_size', 12, 'html')
app.connect('build-finished', cleanup_tempdir)

Related

How can I ignore MOTD and Banner messages with my Python/Paramiko script?

I have a script that reads a host.csv file with IP addresses and connects to each server in turn and runs some commands. I want the output to go to a file name that I specify in a raw_input in the script. Right now I just print the output, but I want to save all of the output to a file, EXCEPT for the login information(BANNER / MOTD) and the timestamps that occur. I have been working on trying to make it only print the output of the actual commands that I am running on each box, but I haven't been able to make it work.
I've been programming with Python for about 3 months now, and I have had some success but sometimes I run into road blocks that I can't yet work my way through.
from __future__ import print_function
import threading
import paramiko
import getpass
import time
import os
import sys
os.system('clear')
class ssh(object):
shell = None
client = None
transport = None
def __init__(self, address, username, password):
print('Connecting to server on ip', str(address) + '.')
self.client = paramiko.client.SSHClient()
self.client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
self.client.connect(address, username=username, password=password, look_for_keys=False)
self.transport = paramiko.Transport((address, 22))
self.transport.connect(username=username, password=password)
thread = threading.Thread(target=self.process)
thread.daemon = True
thread.start()
def close_connection(self):
if(self.client != None):
self.client.close()
self.transport.close()
def open_shell(self):
self.shell = self.client.invoke_shell()
#self.shell.recv(1000)
def send_shell(self, command):
if(self.shell):
self.shell.send(command + '\n')
else:
print("Shell not opened.")
def process(self):
while True:
# Print data when available
if self.shell is not None and self.shell.recv_ready():
alldata = self.shell.recv(1024)
while self.shell.recv_ready():
alldata += self.shell.recv(1024)
data = alldata.split(os.linesep)
for line in data:
print(line)
header = "################## WHAT DO YOU WANT TO DO?? ##################"
headlen = len(header) - 2
secondline = "|" + (" " * headlen) + "|"
thirdline = "|" + " 1. Run the daily ATM Script." + (" " * 30) + "|"
fourthline = "|" + " 2. Run a single command on the entire ATM network" + (" " * 9) + "|"
print(header)
print(secondline)
print(secondline)
print(thirdline)
print(fourthline)
print(secondline)
print(secondline)
print("#" * len(header))
choice = raw_input("Choose your destiny: ")
while choice:
if choice == "1":
print(' \n##### STARTING PROGRAM #####\n')
sshUsername = getpass.getpass(prompt='ENTER USERNAME: ')
sshPassword = getpass.getpass('ENTER PASSWORD: ')
filename = raw_input("What filename dost thou chooseth?")
writefile = open(filename, 'a')
def main():
with open("host.csv", "r") as r:
for address in r:
print(address)
try:
connection = ssh(address, sshUsername, sshPassword)
try:
connection.open_shell()
time.sleep(1)
connection.send_shell('hardware cecplus timing references show')
time.sleep(1)
connection.send_shell('power')
time.sleep(1)
connection.send_shell('hard port show')
time.sleep(1)
connection.send_shell('sig show')
time.sleep(1)
connection.send_shell('conn spvcc pp show')
time.sleep(1)
connection.send_shell('interface sonet path near total')
time.sleep(1)
except:
print('Failed to run commands on:', r)
except:
print('Failed connection to:', r)
time.sleep(5)
connection.close_connection()
main()
elif choice == "2":
COMMAND = raw_input("INPUT A SINGLE COMMAND TO RUN ON THE ENTIRE ATM NETWORK:" )
if __name__ == '__main__':
print(' \n##### STARTING PROGRAM #####\n')
sshUsername = getpass.getpass(prompt='ENTER USERNAME: ')
sshPassword = getpass.getpass('ENTER PASSWORD: ')
def main():
with open("host.csv", "r") as r:
for address in r:
print(address)
try:
connection = ssh(address, sshUsername, sshPassword)
try:
connection.open_shell()
time.sleep(1)
connection.send_shell(COMMAND)
time.sleep(1)
except:
print('Failed to run commands on:', r)
except:
print('Failed connection to:', r)
time.sleep(1)
connection.close_connection()
main()
else:
print("If thou dost not Enter 1 or 2 thou willest not proceed")
choice = input("Choose your destiny: ")
The current results just print everything, including the banner and motd. If I can get it to only print the output from the commands I know I can write those outputs to a file. I basically want to ignore the MOTD and Banner messages.

Convert a decision tree to a table

I'm looking for a way to convert a decision tree trained using scikit sklearn into a decision table.
I would like to know how to parse the decision tree structure to find the decisions made at each step.
Then I would like ideas on how to structure this table.
Do you know a way or have a idea to do it?
Building on the other answer here. The following traverses the tree in the same way but generates a pandas dataframe as an output.
import sklearn
import pandas as pd
def tree_to_df(reg_tree, feature_names):
tree_ = reg_tree.tree_
feature_name = [
feature_names[i] if i != sklearn.tree._tree.TREE_UNDEFINED else "undefined!"
for i in tree_.feature
]
def recurse(node, row, ret):
if tree_.feature[node] != sklearn.tree._tree.TREE_UNDEFINED:
name = feature_name[node]
threshold = tree_.threshold[node]
# Add rule to row and search left branch
row[-1].append(name + " <= " + str(threshold))
recurse(tree_.children_left[node], row, ret)
# Add rule to row and search right branch
row[-1].append(name + " > " + str(threshold))
recurse(tree_.children_right[node], row, ret)
else:
# Add output rules and start a new row
label = tree_.value[node]
ret.append("return " + str(label[0][0]))
row.append([])
# Initialize
rules = [[]]
vals = []
# Call recursive function with initial values
recurse(0, rules, vals)
# Convert to table and output
df = pd.DataFrame(rules).dropna(how='all')
df['Return'] = pd.Series(values)
return df
Here is a sample code to convert a decision tree into a "python" code. You can easily adapt it to make a table.
All you need to do is create a global variable that is a table that is the size of the number of leaves times the number of features (or feature categories) and fill it recursively
def tree_to_code(tree, feature_names, classes_names):
tree_ = tree.tree_
feature_name = [
feature_names[i] if i != _tree.TREE_UNDEFINED else "undefined!"
for i in tree_.feature
]
print( "def tree(" + ", ".join(feature_names) + "):" )
def recurse(node, depth):
indent = " " * depth
if tree_.feature[node] != _tree.TREE_UNDEFINED:
name = feature_name[node]
threshold = tree_.threshold[node]
print( indent + "if " + name + " <= " + str(threshold)+ ":" )
recurse(tree_.children_left[node], depth + 1)
print( indent + "else: # if " + name + "<=" + str(threshold) )
recurse(tree_.children_right[node], depth + 1)
else:
impurity = tree.tree_.impurity[node]
dico, label = cast_value_to_dico( tree_.value[node], classes_names )
print( indent + "# impurity=" + str(impurity) + " count_max=" + str(dico[label]) )
print( indent + "return " + str(label) )
recurse(0, 1)
code snippet
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_text
iris = load_iris()
X = iris['data']
y = iris['target']
decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)
decision_tree = decision_tree.fit(X, y)
r = export_text(decision_tree, feature_names=iris['feature_names'])
print(r)
listt= [r]
print(listt)
#########OUTPUT###########################
|--- petal width (cm) <= 0.80
| |--- class: 0
|--- petal width (cm) > 0.80
| |--- petal width (cm) <= 1.75
| | |--- class: 1
| |--- petal width (cm) > 1.75
| | |--- class: 2

How can I get the length of a protein chain from a PDB file with Biopython?

I have tried it this way first:
for model in structure:
for residue in model.get_residues():
if PDB.is_aa(residue):
x += 1
and then that way:
len(structure[0][chain])
But none of them seem to work...
Your code should work and give you the correct results.
from Bio import PDB
parser = PDB.PDBParser()
pdb1 ='./1bfg.pdb'
structure = parser.get_structure("1bfg", pdb1)
model = structure[0]
res_no = 0
non_resi = 0
for model in structure:
for chain in model:
for r in chain.get_residues():
if r.id[0] == ' ':
res_no +=1
else:
non_resi +=1
print ("Residues: %i" % (res_no))
print ("Other: %i" % (non_resi))
res_no2 = 0
non_resi2 = 0
for model in structure:
for residue in model.get_residues():
if PDB.is_aa(residue):
res_no2 += 1
else:
non_resi2 += 1
print ("Residues2: %i" % (res_no2))
print ("Other2: %i" % (non_resi2))
Output:
Residues: 126
Other: 99
Residues2: 126
Other2: 99
Your statement
print (len(structure[0]['A']))
gives you the sum (225) of all residues, in this case all amino acids and water atoms.
The numbers seem to be correct when compared to manual inspection using PyMol.
What is the specific error message you are getting or the output you are expecting? Any specific PDB file?
Since the PDB file is mostly used to store the coordinates of the resolved atoms, it is not always possible to get the full structure. Another approach would be use to the cif files.
from Bio import PDB
parser = PDB.PDBParser()
pdb1 ='./1bfg.cif'
m = PDB.MMCIF2Dict.MMCIF2Dict(pdb1)
if '_entity_poly.pdbx_seq_one_letter_code' in m.keys():
print ('Full structure:')
full_structure = (m['_entity_poly.pdbx_seq_one_letter_code'])
print (full_structure)
print (len(full_structure))
Output:
Full structure:
PALPEDGGSGAFPPGHFKDPKRLYCKNGGFFLRIHPDGRVDGVREKSDPHIKLQLQAEERGVVSIKGVSANRYLAMKEDGRLLASKSVTDECFFFERLESNNYNTYRSRKYTSWYVALKRTGQYKLGSKTGPGQKAILFLPMSAKS
146
For multiple chains:
from Bio import PDB
parser = PDB.PDBParser()
pdb1 ='./4hlu.cif'
m = PDB.MMCIF2Dict.MMCIF2Dict(pdb1)
if '_entity_poly.pdbx_seq_one_letter_code' in m.keys():
full_structure = m['_entity_poly.pdbx_seq_one_letter_code']
chains = m['_entity_poly.pdbx_strand_id']
for c in chains:
print('Chain %s' % (c))
print('Sequence: %s' % (full_structure[chains.index(c)]))
It's just:
from Bio.PDB import PDBParser
from Bio import PDB
pdb = PDBParser().get_structure("1bfg", "1bfg.pdb")
for chain in pdb.get_chains():
print(len([_ for _ in chain.get_residues() if PDB.is_aa(_)]))
I appreciated Peters' answer, but I also realized the res.id[0] == " " is more robust (i.e. HIE). PDB.is_aa() cannot detect HIE is an amino acid while HIE is ε-nitrogen protonated histidine. So I recommend:
from Bio import PDB
parser = PDB.PDBParser()
pdb1 ='./1bfg.pdb'
structure = parser.get_structure("1bfg", pdb)
model = structure[0]
res_no = 0
non_resi = 0
for model in structure:
for chain in model:
for r in chain.get_residues():
if r.id[0] == ' ':
res_no +=1
else:
non_resi +=1
print ("Residues: %i" % (res_no))
print ("Other: %i" % (non_resi))
I think you would actually want to do something like
m = Bio.PDB.MMCIF2Dict.MMCIF2Dict(pdb_cif_file)
if '_entity_poly.pdbx_seq_one_letter_code' in m.keys():
full_structure = m['_entity_poly.pdbx_seq_one_letter_code']
chains = m['_entity_poly.pdbx_strand_id']
for c in chains:
for ci in c.split(','):
print('Chain %s' % (ci))
print('Sequence: %s' % (full_structure[chains.index(c)]))

Handle special characters in lua file path (umlauts)

I have a small lua function to check if a file exists
function file_exists( filePath )
local handler = io.open( filePath )
if handler then
io.close( handler )
return true
end
return false
end
However, this will always return false when the file path contains special chars such as German umlauts (äöü). Is there any way around this?
Thanks a lot!
utf8_to_cp1252 = (
function(cp1252_description)
local unicode_to_1252 = {}
for code, unicode in cp1252_description:gmatch'\n0x(%x%x)%s+0x(%x+)' do
unicode_to_1252[tonumber(unicode, 16)] = tonumber(code, 16)
end
local undefined = ('?'):byte()
return
function (utf8str)
local pos, result = 1, {}
while pos <= #utf8str do
local code, size = utf8str:byte(pos, pos), 1
if code >= 0xC0 and code < 0xFE then
local mask = 64
code = code - 128
repeat
local next_byte = utf8str:byte(pos+size, pos+size) or 0
if next_byte >= 0x80 and next_byte < 0xC0 then
code, size = (code - mask - 2) * 64 + next_byte, size+1
else
code, size = utf8str:byte(pos, pos), 1
end
mask = mask * 32
until code < mask
end
pos = pos + size
table.insert(result,
string.char(unicode_to_1252[code] or undefined))
end
return table.concat(result)
end
end
)[[
download
http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT
and insert the whole text here:
#
# Name: cp1252 to Unicode table
# Unicode version: 2.0
# Table version: 2.01
..................................
0xFD 0x00FD #LATIN SMALL LETTER Y WITH ACUTE
0xFE 0x00FE #LATIN SMALL LETTER THORN
0xFF 0x00FF #LATIN SMALL LETTER Y WITH DIAERESIS
]]
Usage:
cp1252_filename = utf8_to_cp1252(your_utf8_filename)
Now you can use cp1252_filename to invoke io.open(), os.rename(), os.execute() and other functions from standard Lua library.
Lua and its tiny standard library is platform neutral and is not aware of correct Windows functions to read full unicode names. You can use winapi module to get some Windows-specific functions for this task. Note that it requires short name generation to be enabled on target disk.
local handler = io.open( winapi.short_path(filePath) )
if handler then
-- etc
end
It can also be easily installed through LuaRocks: luarocks install winapi.

Jenkins dsl pipeline def variable

I'm trying to define a variable into a jenkins pipeline dsl script by reading 3 files and concatenating the output. The 3 files content is:
file1 content is: 127
file2 content is: 0
file3 content is: 1
def var1 = readfile('file1')
def var2 = readfile('file2')
def var3 = readfile('file3')
def concatVar = "${var1} + '_' + ${var2} + '_' + ${var3}"
printin ${concatVar}
The output I expect would be
printIn${concatVar}
127_0_1
instead my output is:
printIn ${concatVar}
127
_0
_1
I know that I am wrong somewhere, but I don't know how to do it. Is there any of you familiar with the Jenkins pipepile dsl/groovy syntax?
Thanks guys
Try this..
def var1 = readfile('file1').trim()
def var2 = readfile('file2').trim()
def var3 = readfile('file3').trim()
def concatVar = "${var1} + '_' + ${var2} + '_' + ${var3}"
println ${concatVar}
I found that readFile does not clip off the end of line character

Resources