Can gnuplot be aware of which OS is the host, other than via environment variables? - operating-system

I need to develop a script in gnuplot that is usable under both Windows and Linux.
To decide which OS I have, I wrote
OS=system("echo %OS%")
print "OS = ", OS
if (OS eq "Windows_NT") \
...; \
else \
...;
and it worked.
Is there an alternative way, native to gnuplot, which does not depend on environment variables?

you could use the internal variable GPVAL_SYSNAME:
gnuplot> print GPVAL_SYSNAME
Windows_NT-10.0
which is on Windows initialized in eval.c as:
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
snprintf(s, 30, "Windows_NT-%ld.%ld", osvi.dwMajorVersion, osvi.dwMinorVersion);
fill_gpval_string("GPVAL_SYSNAME", s);
In order to test if this string starts with "Windows", one could use the Gnuplot's internal strstrt function as:
if (strstrt(GPVAL_SYSNAME, "Windows") == 1) {
....
}
In addition, there is also GPVAL_MACHINE:
gnuplot> print GPVAL_MACHINE
x86_64

Related

How to exit a REPL from the command line

I'm currently learning Lua and also learning how to work with CMD.
I know how to change a directory path and run my codes and files from that path
but what I don't know and I'm here to ask for is how to get out of a programming language REPL when you start it in CMD
For example to jump into the Lua REPL you should type:
lua53 (--like python3 for the Python language)
then you changed the CMD environment to a Lua compiler and can't access CMD commands such as
dir, cd, cls etc. and everytime when I need to access these commands I have to close the CMD window and open a new one.
Now can you guys tell me am I able to access CMD commands while in the Lua REPL? Or do I have to exit Lua first, and is there any command to exit a REPL?
I'd recommend EOF (Ctrl + D on Unix) rather than SIGKILL (Ctrl + C) because some REPLs (node and python) choose to ignore the latter (perhaps because it's often used for copying text?); python will just print KeyboardInterrupt whereas node will only exit if you press Ctrl + C twice (it will send a message telling you this the first time).
EOF (Ctrl + D) on the other hand immediately exists all REPLs I have used so far.
The Lua REPL stops immediately when it receives either EOF or SIGKILL, so you can use both here.
Edit: As Sowban points out, EOF apparently is entered as Ctrl + Z then Enter in powershell.
You could type ctrl c to exit the process that's running generally.
I suggest to write a REPL by yourself.
But be warned :-)
The main loop with a prompt and the interpreting and executing function/method is mostly the easiest part.
99.99999% is the errorhandling thing.
One of my earliest interpreter language is (A)REXX.
A REPL without any errorhandling is done with...
/* REXX have to start with a comment */
do forever
parse pull input
interpret input
end
Now Lua sandboxed to an _ENV with io and os library and a little bit of errorhandling...
#!/usr/bin/env -S readline-editor /usr/local/bin/lua
-- ^--SHEBANG for Linux --------------------------------------------------------------------------------------
-- interpreter.lua
-- Sandboxed to io and os
-- Lua 5.4 >>-because-> goto label <const> load()
--------------------------------------------------------------------------------------------------------------
local Lua = function(...)
-- Info about OS
io.write(("%s\n"):format(io.popen('uname -a'):read())):flush()
-- Global Setting
debug.setmetatable((1), {__index = math}) -- Add math library to number as methods (like string for strings)
os.setlocale('de_DE.UTF8')
os.setlocale('en_US.UTF8', 'time')
io.write(os.date("[%c]\n" .. ("%s\n"):format(os.setlocale():gsub("%;", "\n")))):flush()
-- io.write(("%s\n"):format(_VERSION)):flush()
-- Label for goto
::lua::
-- Local Setting
local args <const> = args or {...}
local Lua = Lua or true
local cmd = cmd or ""
--------------------------------------------------------------------------------------------------------------
local env <const> = env or setmetatable({os = os, io = io}, -- The _ENV for load()
{__call = function(self, ...)
local self, t = ({...})[1] or self, "" -- First argument becomes self if one
if ({...})[1] == "help" then self = getmetatable(({...})[2]).__index end -- Showing metamethod __index (table)
for k, v in pairs(self) do
t = t .. ("%s => %s\n"):format(k, v)
end
return t
end,
__index = {cg = collectgarbage,
gt = getmetatable,
pairs = pairs,
tn = tonumber,
ts = tostring,
_V = ("%s \27[1;" .. (31):random(36) .. "m(sandboxed)\27[0m"):format(_VERSION)},
__tostring = function(self) return self._V end}) -- end env
--------------------------------------------------------------------------------------------------------------
local prompt = prompt or setmetatable({}, {__tostring = function() return getmetatable(env).__index._V .. "> " end})
local name <const> = name or _VERSION
local result = result or true
--------------------------------------------------------------------------------------------------------------
while Lua do
io.write(tostring(prompt))
cmd = io.read() or 'quit'
if cmd == "quit" then Lua, result = true, true break end
Lua, result = pcall(load("return " .. cmd or false, name, "t", env))
if Lua and result then
io.write(("%s"):format(tostring(result)))
else
goto exception
end
end
--------------------------------------------------------------------------------------------------------------
-- Errorhandler
::exception::
io.write(("%s\n"):format("Exception"))
if not Lua or not result then
io.output(io.stderr)
io.write(("[%s][%s][%s]\n\27[1;31m>>-Exception->\27[0m %s\n"):format(os.date(), _VERSION, cmd, result)):flush()
io.output(io.stdout)
collectgarbage()
goto lua
end
goto lua
end
--------------------------------------------------------------------------------------------------------------
-- EXAMPLE ---------------------------------------------------------------------------------------------------
-- Lua = require("interpreter")
Lua() -- UNCOMMENT-> For direct execution like: /bin/lua interpreter.lua
return Lua -- UNCOMMENT-> For: Lua = require("interpreter")
Ctrl&C quits hardly
Ctrl&D is only an exception
...and os.exit(0) do an clean exit with returncode 0.
Impression

Preview app doesn't open since I installed MACOS Catalina

import PIL
img = PIL.Image.new("RGB", (100,100))
img.show()
The error message:
FSPathMakeRef(/Applications/Preview.app) failed with error -43.
Following from Sean True's answer, an even quicker but temporary fix is to simply make a symbolic link to Preview.app in the old location. In the terminal run
ln -s /System/Applications/Preview.app /Applications/Preview.app
This fixed the problem for me.
There's an official fix in github for Pillow 7, but I'm still on 6.
This appears to be a PIL ImageShow issue, with the PIL MacViewer using /Applications/Preview.app as an absolute path to the OSX Preview app.
It's not there in Catalina. I did a quick hack to ImageShow.py changing /Applications/Preview.app to just Preview.app and the issue went away. That might or might not still work on pre-Catalina OSX, but I don't have an easy way to test.
It has apparently moved to /System/Applications/Preview.app so a quick check at run time would probably cover both cases.
elif sys.platform == "darwin":
class MacViewer(Viewer):
format = "PNG"
options = {'compress_level': 1}
preview_locations = ["/System/Applications/Preview.app","/Applications/Preview.app"]
preview_location = None
def get_preview_application(self):
if self.preview_location is None:
for pl in self.preview_locations:
if os.path.exists(pl):
self.preview_location = pl
break
if self.preview_location is None:
raise RuntimeError("Can't find Preview.app in %s" % self.preview_locations)
return self.preview_location
def get_command(self, file, **options):
# on darwin open returns immediately resulting in the temp
# file removal while app is opening
pa = self.get_preview_application()
command = "open -a %s" % pa
command = "(%s %s; sleep 20; rm -f %s)&" % (command, quote(file),
quote(file))
return command
def show_file(self, file, **options):
"""Display given file"""
pa = self.get_preview_application()
fd, path = tempfile.mkstemp()
with os.fdopen(fd, 'w') as f:
f.write(file)
with open(path, "r") as f:
subprocess.Popen([
'im=$(cat);'
'open %s $im;'
'sleep 20;'
'rm -f $im' % pa
], shell=True, stdin=f)
os.remove(path)
return 1

How to change a mac address using the command line parameters in the linux kernel

I want to change a mac address at the u-boot level like the following.
# setenv bootargs 'console=ttyAMA0,115200n8 root=/dev/ram0 rw initrd=0x40000000 ethaddr=${ethaddr}'
# setenv ethaddr 11:22:33:44:55:66
# saveenv
And at the driver,
static unsigned char my_ethaddr[MAX_ADDR_LEN];
/* need to get the ether addr from armboot */
static int __init ethaddr_setup(char *line)
{
char *ep;
int i;
printk("command line : %s\n", line);
memset(my_ethaddr, 0, MAX_ADDR_LEN);
/* there should really be routines to do this stuff */
for (i = 0; i < 6; i++)
{
my_ethaddr[i] = line ? simple_strtoul(line, &ep, 16) : 0;
if (line)
line = (*ep) ? ep+1 : ep;
printk("mac[%d] = 0x%02Xn", i, my_ethaddr[i]);
}
return 0;
}
__setup("ethaddr=", ethaddr_setup);
When booting, the log message is like following.
[ 0.000000] Kernel command line: console=ttyAMA0,115200n8 root=/dev/ram0 rw initrd=0x40000000 ethaddr=${ethaddr}
[ 0.000000] command line : ${ethaddr}
[ 0.000000] mac[0] = 0x00, mac[1] = 0x00, mac[2] = 0x0E, mac[3] = 0x00, mac[4] = 0xDD, mac[5] = 0x00
The command line message is ${ethaddr}, is it right?
The mac address isn't correct.
How can I fix it?
You are using single quotes in:
setenv bootargs '... ethaddr=${ethaddr}'
so ${ethaddr} is not expanded and the bootargs variable contains the literal string ethaddr=${ethaddr}, which is then passed into the kernel and is what you see in your debug output. See the U-Boot documentation on How the Command Line Parsing Works for more details.
You could use double quotes, or no quotes at all, in which case ${ethaddr} would be expanded when assigning to bootargs, although you would need to set it first:
# setenv ethaddr 11:22:33:44:55:66
# setenv bootargs console=ttyAMA0,115200n8 root=/dev/ram0 rw initrd=0x40000000 ethaddr=${ethaddr}
# printenv bootargs
bootargs=console=ttyAMA0,115200n8 root=/dev/ram0 rw initrd=0x40000000 ethaddr=11:22:33:44:55:66
Note that in some systems the ethaddr variable is used by U-Boot itself to configure the MAC address of the first network device, and the Linux network driver may continue to use that address, so you don't need to explicitly pass it into the kernel. See the documentation on U-Boot Environment Variables.
In addition U-Boot may be configured to prevent modification of the ethaddr variable, although that's probably not the case here because when it is U-Boot prints the error message:
Can't overwrite "ethaddr"

subprocess: stdout and stderror seem interchanged or mixed

i'm trying to automate interactive ssh calls (see note 1) as follows:
SSHBINARY = '/usr/bin/ssh'
ASKPASS = '/home/mz0/checkHost/askpass.py'
def sshcmd(host,port,user,password,cmd):
env0 = {'SSH_ASKPASS': ASKPASS, 'DISPLAY':':9999'}
ssh = subprocess.Popen([SSHBINARY,"-T","-p %d" % port,
"-oStrictHostKeyChecking=no", "-oUserKnownHostsFile=/dev/null",
"%s#%s" % (user,host), cmd],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env0,
preexec_fn=os.setsid
)
error = ssh.stderr.readlines()
result = ssh.stdout.readlines()
return error,result
host = 'localhost'
port = 22
user = 'try1'
password = '1try' # unused, hardcoded in ASKPASS
cmd = 'ls'
result1, error1 = sshcmd(host,port,user,password,cmd)
if result1 : print "OUT: %s" % result1
if error1 : print "ERR: %s" % error1
It turns i'm doing something stupid since i get this:
OUT: ["Warning: Permanently added 'localhost' (RSA) to the list of known hosts.\r\n"]
ERR: ['['Desktop\n', ..., 'Videos\n']']
Obviously stdout and stderr are swapped (note 2). Can you kindly point me my error?
note 1: i'm well aware of password-less ssh, dangers of ignoring host key etc. and hate requests on automating interactive ssh as much as you.
note 2: running the same command in shell confirms that stdout and stderr are swapped in my code
ssh -o 'UserKnownHostsFile /dev/null' -o 'StrictHostKeyChecking no' \
try1#localhost ls > ssh-out 2> ssh-error
return error,result
and
result1, error1 = sshcmd(...)
Just swap either of those around.

Why can I drive InstallShield with Win32::GuiTest on XP but not Windows 7?

I'm trying to use Win32::GuiTest to test an InstallShield-based uninstall process. I can open the Control Panel, find the application, and invoke InstallShield but nothing I do seems to let me pick the Remove button in the installer. So far, I've got:
sub uninstall($;$) {
my ($name, $force) = #_;
if (! defined($force)) {
$force=0;
}
my #windows;
# Control Panel window
my $cpwin;
my $w;
my $text;
# Install Shield window
my $iswin;
# Run the Control Panel (In windir, do `control appwiz.cpl`)
system("cd %windir% && control appwiz.cpl");
sleep 1;
print("Opened control panel\n");
# Get the Window ID of the control panel
# FIXME - this label is system specifie (W7)
#windows = FindWindowLike(undef, "Programs and Features", "");
$cpwin = $windows[0];
printf("Found CP window ID %x\n", $cpwin);
# Get the Folder View window of the control panel
# Find the list of applications
#windows = FindWindowLike($cpwin, "FolderView");
$w = $windows[0];
# Find program in the list
if (Win32::GuiTest::SelListViewItemText($w, $name) == 0) {
printf("Could not find '$name'.\n");
return -1;
}
# Invoke the installer for by pressing [Return]
Win32::GuiTest::SendKeys("~");
# Wait for the "initializing the wizard" window
#windows = Win32::GuiTest::WaitWindow("InstallShield Wizard", 5);
# Wait for the real installer window
sleep 10;
#windows = Win32::GuiTest::WaitWindow("InstallShield Wizard", 3);
$iswin = $windows[0];
# Win32::GuiTest::WaitWindow("Remove");
printf("Found IS window ID %x\n", $iswin);
# Win32::GuiTest::SetFocus($iswin);
#windows = FindWindowLike($iswin, "&Remove", "Button");
my $remove = $windows[0];
printf("Found remove button %x\n", $remove);
Win32::GuiTest::PushButton($remove);
# Win32::GuiTest::SetFocus($remove);
# Win32::GuiTest::SendKeys("%r");
# Win32::GuiTest::MouseClick("Remove",$iswin);
# Win32::GuiTest::CheckButton($remove);
# Win32::GuiTest::SendKeys("{DOWN}{DOWN}");
# Win32::GuiTest::MouseClick("Next",$iswin);
# Win32::GuiTest::PushChildButton($iswin, "Cancel");
None of the things I've tried (commented out, at the end) seem to have any effect.
I'm using ActivePerl and Win32::GuiTest on Windows 7 if any of that matters.
(Be kind. My Perl probably sucks. I have >25 years experience programming but less than a month in Perl.)
The fact that I'm trying to drive an installer, appears to be a red herring. On XP (even in a VM), this works fine. I suspect that the issue is that the installers present dialog boxes whereas Notepad presents a window and those are somehow handled differently in W7 than XP. I'll come back to why W7 doesn't work but XP is what I have to do right now so that's enough.
The Win32::GuiTest::PushButton method takes the button Text or ID as parameter, not a window/control object. So you don't need to invoke FindwindowLike method at all.
But Win32::GuiTest::PushButton is looking up buttons from the foreground window only, which might be not properly for all the cases. The Win32::GuiTest::PushChildButton should be used.
Please try this way:
##windows = FindWindowLike($iswin, "&Remove", "Button");
#my $remove = $windows[0];
#printf("Found remove button %x\n", $remove);
sleep 10;
Win32::GuiTest::PushChildButton($iswin, "&Remove", 50);