MATLAB to read in a password - bash

I'm building a MATLAB application that authenticates a user's credentials.
I want to read in his password, and I want to hide his typed credentials somehow.
Some constraints:
I have to account for windows as well as linux/mac users.
I can't be assured of any programs (perl/python/VBS) in the user system.
Here's what I've tried:
Straight-up GUIDE
Works, but not an option as the user is likely to be running matlab in -nodesktop (or -nodisplay) mode.
MATLAB + Java
console.readPassword. This messes up my terminal horribly.
system() calls
Essentially I call bash or dos scripts based on OS.
I have the following call for linux/mac:
[status cred] = system('stty -echo; read cred; stty echo;echo ""; echo "$cred"');
This is supposed to pick up the user credentials and dump that on to 'cred'. I've checked that it works in the regular terminal, but executing it in MATLAB causes nothing to be output, and a Ctrl-C is required to bring back the >> prompt.
MATLAB Perl
The Windows MATLAB packages Perl, as pointed out in comments. I tried the following snippet:
use Term::ReadKey;
use Term::ReadLine;
ReadMode('noecho');
$yesnoline = Term::ReadLine->new("foo");
$pass = $yesnoline->readline();
printf "$pass";
ReadMode('restore');
And then called it as [result status] = perl('my_perl.pl'). Works great on Linux.
On Windows:
res =
GetConsoleMode failed, LastError=|6| at ReadKey.pm line 264.
sta =
9
My searches so far suggest that it's a problem related to the packaged version of perl for windows.
Any idea what's happening in the above approaches?

I suggest that you detect Windows installation (ispc), and handle them differently than Unix-like systems, by creating a MATLAB GUI or something similar..
Here is one possible solution for Windows using .NET Windows Forms from inside MATLAB:
function pass = getPasswordNET()
%# password return value
pass = '';
%# hidden figure used to wait for button press
fig = figure('Visible','off', ...
'IntegerHandle','off', 'HandleVisibility','off');
%# create and show the Windows Forms GUI
[handles,lh] = InitializeComponents();
handles.frm.Show();
%# block execution until figure is closed
waitfor(fig)
%# remove the listeners
delete(lh);
return;
%# create GUI
function [handles,lh] = InitializeComponents()
%# import assembly
NET.addAssembly('System.Windows.Forms');
%# form
frm = System.Windows.Forms.Form();
frm.SuspendLayout();
%# textbox
tb = System.Windows.Forms.TextBox();
tb.Dock = System.Windows.Forms.DockStyle.Fill;
tb.Text = '';
tb.PasswordChar = '*';
tb.MaxLength = 14;
%# button
bt = System.Windows.Forms.Button();
bt.Dock = System.Windows.Forms.DockStyle.Bottom;
bt.Text = 'Submit';
%# setup the form
frm.Text = 'Password';
frm.ClientSize = System.Drawing.Size(250, 40);
frm.Controls.Add(tb);
frm.Controls.Add(bt);
frm.ResumeLayout(false);
frm.PerformLayout();
%# add event listeners
lh(1) = addlistener(bt, 'Click', #onClick);
lh(2) = addlistener(frm, 'FormClosing', #onClose);
%# return handles structure
handles = struct('frm',frm, 'tb',tb, 'bt',bt);
end
%# event handlers
function onClick(~,~)
%# get password from textbox
pass = char(handles.tb.Text);
%# close form
handles.frm.Close();
end
function onClose(~,~)
%# delete hidden figure (to unblock and return from function)
close(fig)
end
end
I tested the above on my machine, and it worked even when MATLAB was started in headless mode:
matlab.exe -nodesktop -noFigureWindows
then called it as:
>> pass = getPasswordNET()
pass =
secret_password
It should be straightforward to do something similar in Java using Swing's JPasswordField

Java getPassword
I haven't yet managed to get the getPassword approach to return the console to the normal state - I'm assuming your code looks something like:
import java.lang.*
cs = System.console()
a = cs.readPassword()
Could you confirm this?
Python solution
If the solution has to be multi-platform, and you don't mind Python being a dependency, I would suggest writing a very simple python script and using this with a Matlab system call, something like
file: usergetpass.py
import getpass
import os
os.sys.stdout.write(getpass.getpass())
then in matlab
[status,pass] = system('python usergetpass.py');
You would then have to (trivially) parse pass though, the actual password is contained on line 3 of pass.
So you could put the above into your own mini matlab function,
function out = getpass()
[status, pass] = system('python usergetpass.py');
out = pass(13:end-1);
Note: I can use this because the password always occurs at that point in the pass variable.

Related

My toplevel window in tkinter is no longer being destroyed. It was working fine until I tried changing other aspects of my function

I'm trying to get a popup window to display random text and a picture every time a button is pressed in tkinter. My original code was going to use an if/elif statement to do this. It worked as intended but I thought it might be easier to pair the data in a dictionary since there would be 50 elif statements otherwise (is it frowned upon to use so many? I actually found it easier to read).I was able to get this working but now the toplevel window in tkinter is not being destroyed like it was in the original function. A new Label is just being created on top of it and I can't figure out why. The function code is below. Thanks in advance, any help would be appreciated!
def Add_Gemstone2():
global Addstone
#destroy the previous window if there is one.
try:
AddStone.destroy()
except(AttributeError, NameError):
pass
#create the window.
AddStone=Toplevel()
AddStone.configure(bg='White', height=200, width=325)
AddStone.geometry('325x180+10+100')
# add gemstones to list from file.
gem_stones = open('gemstones.txt')
all_gem_stones = gem_stones.readlines()
gemstones = []
for i in all_gem_stones:
gemstones.append(i.rstrip())
# Add pictures to list.
path = r'C:\Users\Slack\Desktop\PYTHON WORKS\PYTHON GUI PROJECT\gems'
gempictures = []
# r=root, d=directories, f = files
for r,d,f in os.walk(path):
for file in f:
if '.gif' in file:
gempictures.append(os.path.join(r, file))
#create dictionary from lists.
gemdiction = dict(zip(gemstones, gempictures))
key, val = random.choice(list(gemdiction.items()))
# create the labels.
glbl1 = Label(AddStone, text=key, bg='gold', wraplength=300)
glbl1.pack()
image = ImageTk.PhotoImage(Image.open(val))
glbl2 = Label(AddStone, image=image)
glbl2.image = image
glbl2.pack()

print pdf silently in c#

I am trying to print pdf silently using adobe reader.
I have taken the example from the following location:
http://www.codeproject.com/Tips/598424/How-to-Silently-Print-PDFs-using-Adobe-Reader-and
I am able to work as desired with the above example code in my localhost.
But when I deploy my application on the server,I am unable to print the PDFs.
In my localhost on button click event,I am creating the PDFs and saving it to one location and printing the same.While printing adobe window opens and prints the PDFs and exits automatically.
The same doesn't work in my server.I am able to create and save PDFs,but adobe is not opening and printing my file.I am not even getting any exception/error.It simply doesn't show up adobe window.
Did anyone face the same issue.
Any help in this regard.
Thanks in advance.
EDIT:
If you are running on a Web Server using ASP.NET or in general IIS the new process executes on the Web server with restricted permissions. I point you out this answer that could explain the cause of your problem.
However the code you are using doesn't print any error message. You probably don't have access to the directory where the AcroRd32.exe is located.
Let's take this function from the article you posted:
public static Boolean PrintPDFs(string pdfFileName)
{
try
{
Process proc = new Process();
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.Verb = "print";
//Define location of adobe reader/command line
//switches to launch adobe in "print" mode
proc.StartInfo.FileName =
#"C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe";
proc.StartInfo.Arguments = String.Format(#"/p /h {0}", pdfFileName);
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
if (proc.HasExited == false)
{
proc.WaitForExit(10000);
}
proc.EnableRaisingEvents = true;
proc.Close();
KillAdobe("AcroRd32");
return true;
}
catch
{
return false;
}
}
PrintPDFs uses a process, which is called by the .NET framework using the Process class. In the StartInfo option you look carefully two options are set:
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
The first redirect the standard output stream to your application while the second hides the cmd window. The former is handy to use process without showing to the user a command window but the latter hide the console window. The main drawback is, if you're debugging, that you probably won't see error coming through.
One way to debug it would require to add the following to lines:
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
Console.WriteLine(proc.StandardOutput.ReadToEnd());
Another property you can look at is ExitCode. If that is greather than zero means that your process exit with some error.
hope it helps.
A silent printing can be achieved with an Acroread command line parameters or with a PDF JavaScript event handler (of course, if your PDF producer tool has a possibility to define/inject PDF's OpenAction handler).
See http://pd4ml.com/cookbook/pdf_automated_printing.htm
With the JavaScript approach you are not bound to a printer driver, network name or IP address. On the other hand, JavaScript in Acroread can be disabled, for example, by a corporate security policy.
use this with Ghostscript that is GNU:
ProcessStartInfo info = new ProcessStartInfo();
var FileName = #"C:\ResultadoFormulario_CClastMovements.pdf";
var pathPrinter = #"\\Server\namePrinter";
info.CreateNoWindow = true;
var pathGsw = #"path gswin64c here\";
info.WindowStyle = ProcessWindowStyle.Hidden;
string strCmdText = $"{pathGsw}gswin64c.exe -sDEVICE=mswinpr2 -dBATCH -dNOPAUSE -dNOPROMPT -dNoCancel -dPDFFitPage -sOutputFile=\"%printer%{direccionImpresora}\" \"{FileName}\"";
Process.Start("CMD.exe", strCmdText);

Dynamically changing the command window title in Matlab

I want to change the title of the the command window in matlab to state the current branch I am working on.
I know where to find the current branch name.
I need that every time this file is changed to note on a new branch, the title of the command window will be updated with the new branch name.
Any thoughts?
I have this M-file laying around (I think I got it from here). It might suit your needs:
function idetitle(Title)
%IDETITLE Set Window title of the Matlab IDE
%
% Examples:
% idetitle('Matlab - Foo model')
% idetitle(sprintf('Matlab - some big model - #%d', feature('getpid')))
win = appwin();
if ~isempty(win)
win.setTitle(Title);
end
end
function out = appwin()
%APPWIN Get main application window
wins = java.awt.Window.getOwnerlessWindows();
for ii = 1:numel(wins)
if isa(wins(ii), 'com.mathworks.mde.desk.MLMainFrame')
out = wins(ii);
return
end
end
out = [];
end

Want to move a slider and all the others update in Matlab?

I have GUI in Matlab that I have made using the Programmatic approach. It has 6 sliders and I want to be able to move one of them and have the others update as if i clicked them again but to stay in the same place. I am guessing I will need to use the set() function. Is there some function to do this in matlab already? I have been looking around. Any suggestions or something to point me in the right direction?
If you are using guide, you can access the other sliders from the handles variable that is available in each callback.
Set the Value property for them.
function Slider1_CallBack(hObj,evt,handles)
set(handles.Slider1,'Value',10);
set(handles.Slider2,'Value',10);
% etc..
end
In case you are using it programmaticaly, you can store the handles manually.
function main
handles.Figure1 = figure(..);
handles.Slider1 = uicontrol(...);
handles.Slider2 = uicontrol(...);
guidata(handles.Figure1,handles);
end
And your slider callback should be:
function Slider1_CallBack(hObj,evt)
handles = guidata(hObj);
set(handles.Slider1,'Value',10);
set(handles.Slider2,'Value',10);
% etc..
end
Edit A good practice in writing UI is separating the GUI logic from the actual data. You always change the data, and call updateGUI routine.
Therefore, you can write your program like this:
function main
handles.gui.Figure1 = figure(..);
handles.gui.Slider1 = uicontrol(...);
handles.gui.Slider2 = uicontrol(...);
handles.data.x = 1;
guidata(handles.Figure1,handles);
end
function UpdateGui(handles)
%Based on the data, update the GUI
set(handles.Slider1,'Value',handles.data.x);
set(handles.Slider2,'Value',handles.data.x+1);
end
And the callback should look like:
function Slider1_CallBack(hObj,evt)
handles = guidata(hObj);
handles.data.x = handles.data.x + 1;
UpdateGui(handles);
guidata(hObj,handles);
% etc..
end

MATLAB date selection popup calendar for gui

Does anyone know of a method to display a popup date selection calendar in a MATLAB gui? I know the financial toolbox has a uicalendar function, but unfortunately I don't have that toolbox.
I have a hunch I'm going to have to use some Java or some other language for this one, which I know nothing about.
I'm looking for something similar to this:
(source: welie.com)
which would return a date string after the user selects the date.
Here are two approaches that would give you a professional-looking calendar component in Matlab without too much programming work:
Use a Java calendar component (for example, one of these or these). Once you download the relevant Java class or Jar-file, add it to your static Java classpath (use the edit('classpath.txt') command from the Matlab Command Prompt). Finally, use the built-in javacomponent function to place the component in your Matlab figure window.
If you are using a Windows OS, you can embed any Active-X calendar control that is available. Use the built-in actxcontrolselect function to choose your favorite calendar control (for example, Microsoft Office's "Calendar Control 11.0" - MSCAL.Calendar.7 - which is automatically installed with Office 2003; or "Microsoft Date and Time Picker Control 6.0" - MSComCtl2.DTPicker.2, or ...). Then use the actxcontrol function to place the component in your Matlab figure window.
Matlab has some pretty useful built-in calendar (date-selection) controls - I posted an article about them today
I don't have much time for a more complete answer, unfortunately, but I'd try uitable to create a table and to define the CellSelectionCallback to get the date.
Here's a bit to get you started:
dates = calendar;
dates(~any(dates,2),:) = [];
fh = figure;
uh = uitable('parent',fh,'data',dates,'ColumnWidth',repmat({20},1,7),...
'ColumnName',{'S','M','T','W','T','F','S'});
I'd start with the calendar() function which outputs a matrix containing the calendar for any month. I assume you could combine this with a user-clickable interface to retrieve a specific date?
The following code is really ugly, but could help you get started...
WINDOW_WIDTH = 300;
WINDOW_HEIGHT = 200;
f= figure('Position',[300 300 WINDOW_WIDTH WINDOW_HEIGHT]);
NB_ROWS = 6;
NB_COLS = 7;
width = round(WINDOW_WIDTH/NB_COLS);
height = round(WINDOW_HEIGHT/NB_ROWS);
buttons = nan(NB_ROWS,NB_COLS);
dates = calendar();
for row = 1:NB_ROWS
for col = 1:NB_COLS
if dates(row,col) == 0
mydate = '';
else
mydate = sprintf('%i', dates(row,col));
end
buttons(row,col) = uicontrol('Style', 'PushButton', ...
'String', mydate, ...
'Position', [(col-1)*width (NB_ROWS - row)*height width height]);
end
end

Resources