Simple GUI script with a list
Good day
As my first Powershell project i'd like to write a script which will present to the user a GUI with a list of servers. The user then chooses a server and on click of the OK button connects to it with MSTSC. The window can look like this:
Probably a script accomplishing a similar task already exists. Can you point it out? Also i'd like to learn more about developing specifically GUI scripts. Can you direct me to a source of information on that subject? A book maybe?
Regards
Kamil
I know you want to learn how to build GUI, but what you asked for can actually be accomplished with just a few lines of code. The downside is you will not have any control over the layout.
You can load the list of servers from CSV:
$CSV = @"
"Name","OperatingSystem","Description"
"SERVER01","Windows Server 2008 R2","File Server"
"SERVER02","Windows Server 2012 R2","Domain Controller"
"SERVER03","Windows Server 2012","Print Server"
$Servers = ConvertFrom-Csv $CSV
$Servers | Out-GridView -Title "Select a server" -PassThru | Select Name |
%{Start-Process "$env:windir\system32\mstsc.exe" -ArgumentList "/v:$($_.Name)"}
Or you can get them directly from Active Directory:
Get-ADComputer -Filter 'Name -like "SERVER*"' -Properties OperatingSystem, Description |
Select Name, OperatingSystem, Description |
Out-GridView -Title "Select a server" -PassThru | Select Name |
%{Start-Process "$env:windir\system32\mstsc.exe" -ArgumentList "/v:$($_.Name)"}
Similar Messages
-
Using AppleScript to re-format with GUI scripting
Background:
I use Pages 4.1 under Mac OSX 10.6.8.
I use medical practice software called Genie, built on 4D. When I create a new letter based on a template in Genie, some formatting is required before the letter is sent. This is repetitive and frequent - just the sort of task for scripting. With help from many people on Apple discussions, I now have a script that converts the text in Pages from A (starting and ending with =====) to B (starting and ending with +++++). The text and the script are edited, as there are about 30 lines in the real Mental State Exam.
The script uses Styles within Pages to change the formatting of the headings. It uses GUI scripting with find and replace to add spaces before measurement abbreviations. It use GUI scripting to italicise some sub-headings.
I tried to use GUI scripting of the Advanced tab of the Find & Replace window, but I was unsuccessful, as I don't know how to find out the names of the various items in the Find & Replace window. (E.g. Where it says "Style:" with a dropdown menu starting with "Any", I don't know how to refer to this dropdown menu).
Although this script works, it's slower than I would like, and it's a bit clunky because of the way I have incorporated elements of scripts more knowledgable users, and cobbled them together.
I would appreciate any advice on how to improve the script.
Thanks,
Peter
=====
MEDICATIONS:
Lexapro 10mg Tablets one daily with the evening meal
Panadol Osteo 665mg Modified release tablets ii mane
Seroquel 102mg Tablets one nocte
MENTAL STATE EXAMINATION
Appearance and Behaviour
General appearance: Casually dressed.
Patient Attitude: Cooperative
Psychomotor Activity: Normal
Insight and Judgement
Insight: Good
Aware of abnormal phenomena: Yes
Attributes to Illness: Yes
Willing to accept treatment: Yes
Judgement: Consistent with personality
=====
+++++
MEDICATIONS:
Lexapro 10 mg Tablets one daily with the evening meal
Panadol Osteo 665 mg Modified release tablets ii mane
Seroquel 102 mg Tablets one nocte
MENTAL STATE EXAMINATION
Appearance and Behaviour
General appearance: Casually dressed.
Patient Attitude: Cooperative
Psychomotor Activity: Normal
Insight and Judgement
Insight: Good
Aware of abnormal phenomena: Yes
Attributes to Illness: Yes
Willing to accept treatment: Yes
Judgement: Consistent with personality
+++++
Script:
property replacements : {¬
{"0mg ", "0 mg "}, ¬
{"1mg ", "1 mg "}, ¬
{"2mg ", "2 mg "}, ¬
{"3mg ", "3 mg "}, ¬
{"4mg ", "4 mg "}, ¬
{"5mg ", "5 mg "}, ¬
{"6mg ", "6 mg "}, ¬
{"7mg ", "7 mg "}, ¬
{"8mg ", "8 mg "}, ¬
{"9mg ", "9 mg "}, ¬
{" ", " "}, ¬
{" ", " "} ¬
tell application "Pages" to activate
tell application "System Events" to tell process "Pages"
keystroke "f" using command down
repeat until exists window "Find & Replace"
end repeat
tell window "Find & Replace"
repeat with thisReplacement in replacements
set {X, Y} to thisReplacement
set value of text area 1 of scroll area "Find:" of tab group 1 to X
set value of text area 1 of scroll area "Replace:" of tab group 1 to Y
click button "Replace All" of tab group 1
end repeat
click button 1
end tell
end tell
property styleHeadings : {¬
{"MENTAL STATE", "MSE Heading 1"}, ¬
{"Appearance and B", "MSE Heading 2"}, ¬
{"General appe", "Indent-single"}, ¬
{"Patient attit", "Indent-single"}, ¬
{"Psychomotor ", "Indent-single"}, ¬
{"Rapport:", "Indent-single"}, ¬
{"Insight and j", "MSE Heading 2"}, ¬
{"Insight:", "Indent-single"}, ¬
{"Judgement:", "Indent-single"}, ¬
{"Aware of abn", "Indent-double"}, ¬
{"Attributes to i", "Indent-double"}, ¬
{"Willing to acc", "Indent-double"} ¬
on stylise()
tell application "Pages"
tell document 1
set paragraphTexts to paragraphs of body text
repeat with p from (count paragraphTexts) to 1 by -1
set paraText to item p of paragraphTexts
repeat with k from 1 to (count styleHeadings)
set {marker, styleName} to item k of styleHeadings
if (paraText begins with marker) then
set paragraph style of paragraph p of body text to paragraph style styleName
exit repeat
end if
end repeat
end repeat
end tell
end tell
end stylise
stylise()
set italicHeadings to {"General appearance:", "Patient Attitude:", "Psychomotor activity:", "Rapport:", ¬
"Insight:", "Aware of abnormal phenomena:", "Attributes to Illness:", ¬
"Willing to accept treatment:", "Judgement:"}
tell application "Pages" to activate
tell application "System Events" to tell process "Pages"
repeat with findPhrase in italicHeadings
keystroke "f" using command down
repeat until exists window "Find & Replace"
end repeat
tell window "Find & Replace"
set value of text area 1 of scroll area "Find:" of tab group 1 to findPhrase
click button "Next" of tab group 1
keystroke "w" using command down
keystroke "i" using command down
end tell
end repeat
end tellHi,
This can be done without "Gui Scripting" when the document does not contain many lines, otherwise it's much slower.
Here is an example:
tell application "Pages" to tell document 1
set tWords to (words whose it ends with "mg")
repeat with i from (count tWords) to 1 by -1
set thisWord to item i of tWords
if (length of thisWord) > 2 and text -3 of thisWord is in "1234567890" then
set (word i whose it ends with "mg") to (text 1 thru -3 of thisWord) & " mg"
end if
end repeat
set L to character offset of characters whose it = " " or it = " "
set n to -2
repeat with i from (count L) to 1 by -1
set n2 to item i of L
if n - 1 = n2 then delete character n2
set n to n2
end repeat
set styleHeadings to {{"MENTAL STATE", "Sous-section 2"}, ¬
{"Appearance and B", "MSE Heading 2"}, ¬
{"General appe", "Indent-single"}, ¬
{"Patient attit", "Indent-single"}, ¬
{"Psychomotor ", "Indent-single"}, ¬
{"Rapport:", "Indent-single"}, ¬
{"Insight and j", "MSE Heading 2"}, ¬
{"Insight:", "Indent-single"}, ¬
{"Judgement:", "Indent-single"}, ¬
{"Aware of abn", "Indent-double"}, ¬
{"Attributes to i", "Indent-double"}, ¬
{"Willing to acc", "Indent-double"}}
repeat with k from 1 to (count styleHeadings)
set {marker, styleName} to item k of styleHeadings
set paragraph style of (paragraphs whose it begins with marker) to paragraph style styleName
end repeat
set italicHeadings to {"General appearance:", "Patient Attitude:", "Psychomotor Activity:", "Rapport:", ¬
"Insight:", "Aware of abnormal phenomena:", "Attributes to Illness:", ¬
"Willing to accept treatment:", "Judgement:"}
repeat with findPhrase in italicHeadings
set len to length of findPhrase
tell (first paragraph whose it begins with findPhrase) to if exists then
set italic of characters 1 thru len to true
-- you can add other line to change properties of this paragraph or properties of specific word in this paragraph
end if
end repeat
tell (paragraphs whose it contains "MENTAL STATE EXAMINATION" or it contains "Insight and Judgement") to if exists then
set underline type to single underline
-- you can add other line to change properties of these paragraphs or properties of specific word in these paragraphs
end if
end tell -
Hi there,
I'm trying to script a small app called Deeper (that doesn't work natively with ascript).
I tried GUI scripting with apple script editor but I'm not how it works so I put that aside and went trying with UI Element Inspector.
So I'm trying to select something from a scroll menu, and then click a start button.
What it does is it activates the Flurry screensaver as a background, but some bugs turn it off, so I wanted that by running this script, it would use Deeper to turn it back on without having to do it manually.
I tried as best as I can to stick with the example given in the UIElementInspector page, but I am really a starter in scripting.
First, I did:
tell application "Deeper"
activate
end tell
tell application "System Events"
tell process "Deeper"
tell menu "PopUpButton"
But then I found out there was no way to distinguish that pop up menu from others (with UIElementInspector) other than by the size and location of the menu in the app.
So first I'd need help finding out how to tell the script wich menu to go check in, and then probably stick with the example page.
As you can see, I'll really trying to learn applescript from the start, because it looks so useful.
Thanks to anyone for helping!You shouldn't need this:
"open application file "Deeper.app" of folder "Applications" of startup disk"
as this activates your app for you:
"activate application "Deeper""
activate application "Deeper"
delay 1
tell application "System Events"
tell process "Deeper"
click button "General" of tool bar 1 of window "Deeper"
delay 0.5
tell pop up button 4 of window "Deeper"
click
click menu item "Flurry" of menu 1
end tell
delay 0.5
click button "Start" of window "Deeper"
delay 0.5
tell application "Finder"
quit application "Deeper"
end tell
end tell
end tell
Budgie -
Both side chatting with simple GUI ,,helps pls?
guys I'm Java application programmer i don't have well knowledge in network programing ,,my question ,,,from where should i start to design a simple GUI client*s* server chat program ,i mean some thing like simple yahoo messenger the program should include also adding contact and make that contact appears ON if he login or OFF if he sign out like red color for ON-line contact and and white color for off-line contact ...........
another thing that chat system should include shared folder all the contact can enter it and upload file or download file ...
please guys i run to you to help me i have 2 weeks only to do that thing please don't let me down i need your help ....TIPS,code,any thing full code :) ,,any thing will be really appreciated .
guys for more information the program includes only the chat of course its both sides chat between the clients and these is no conference room
or audio or video nothing ,,just text only nothing else except the folder shearing service and the colors of the contacts for login or not .
guys once more help me give me codes or any thing useful i count on you guys.
thx a lot in advance
RSPCPro
Edited by: RSPCPRO on Oct 3, 2008 6:25 PMRSPCPRO wrote:
Dude , u r right ,,,but still its simple GUI issueI'm not sure why you are getting this impression. It's not a simple "GUI issue." Yes, you can simply create the GUI for this, but will it be functional? No. Furthermore, if it was so simple, why are you posting asking for help?
For an instant message chat program, in addition to GUI programming, you need to know how client / server systems work and you need to implement one. A server should be running on one system and the client(s) will connect to it. The server usually maintains the buddy list and passes the messages to/from different clients. This presents several problems that you will need to solve:
1. How will you develop a protocol between the client / server for communication?
2. How will you authenticate users?
3. How will you maintain the buddy list on the server (data structure, database, file)?
4. How will you pass messages from one client to another (simple string message, serialized data object, etc.)?
5. etc.
Now, I'm not saying this is "impossible" so please don't take it that way. I'm simply trying to help you realize that there are a lot of factors to consider when developing this type of application.
RSPCPRO wrote:
and for the "FTP?" ,,,its folder shearing as i said earlier every one of your friends can access it not FTP .....Talking about "folder sharing" is a whole other issue. What I meant by saying "FTP?" is, how do you plan on implementing "folder sharing" remotely? One option is FTP. How would you do it?
RSPCPRO wrote:
and one thing please don't assume any thing u don't knowIf you ask a very broad question and ask for code, I can only assume one thing.
RSPCPRO wrote:
be cooler with others and u will get what u want.I agree. You should take your own advice. I'm not the one looking for help, you are.
RSPCPRO wrote:
thx dude for ur advice and for the link have a good day.You're welcome, and good luck. -
Need help with GUI Scripting Audio Midi Setup
I want to read the value of the sampling frequency set by default in Audio Midi Setup.
If there is an easy unix way to gleen this, please let me know. Otherwise, I am trying to get it via GUI scripting. I think I am almost there, but am doing something stupid.
Here is what I have:
tell application "Audio MIDI Setup"
activate
end tell
tell application "System Events"
activate
tell application process "Audio MIDI Setup"
select window 1
select group
select tab group
select group
select combo box
set FrequencyValue to contents of combo box
end tell
end tell
Basically, this comes down to the question of how to extract the default text field from the combo box.Once you click on the combo box to get the list of items, you can do stuff with the results. The easiest thing would probably be to use the up and down arrows to change the selection, since the text field is not editable. You can compare the list of items with the current value and do something from there - how do you plan to choose the item to change to?
<pre style="
font-family: Monaco, 'Courier New', Courier, monospace;
font-size: 10px;
font-weight: normal;
margin: 0px;
padding: 5px;
border: 1px solid #000000;
width: 720px;
color: #000000;
background-color: #DAFFB6;
overflow: auto;"
title="this text can be pasted into the Script Editor">
tell application "Audio MIDI Setup" to activate
tell application "System Events" to tell application process "Audio MIDI Setup"
set comboBox to combo box 1 of group 1 of tab group 1 of group 1 of window "Audio Devices"
set frequencyValue to value of comboBox -- get current value
click button 1 of comboBox -- perform action "AXPress" to drop the list
set theChoices to value of text fields of list 1 of scroll area 1 of comboBox -- get all the values
-- keystroke (ASCII character 31) -- down arrow
-- keystroke (ASCII character 30) -- up arrow
-- keystroke return -- select and dismiss the list
end tell
activate me
choose from list theChoices default items {frequencyValue} -- just show the results
</pre> -
Example code for java compiler with a simple GUI
There is no question here (though discussion of the code is welcome).
/* Update 1 */
Now available as a stand alone or webstart app.! The STBC (see the web page*) has its own web page and has been improved to allow the user to browse to a tools.jar if one is not found on the runtime classpath, or in the JRE running the code.
* See [http://pscode.org/stbc/].
/* End: Update 1 */
This simple example of using the JavaCompiler made available in Java 1.6 might be of use to check that your SSCCE is actually what it claims to be!
If an SSCCE claims to display a runtime problem, it should compile cleanly when pasted into the text area above the Compile button. For a compilation problem, the code should show the same output errors seen in your own editor (at least until the last line of the output in the text area).
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.EventQueue;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;
import java.util.ArrayList;
import java.net.URI;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
/** A simple Java compiler with a GUI. Java 1.6+.
@author Andrew Thompson
@version 2008-06-13
public class GuiCompiler extends JPanel {
/** Instance of the compiler used for all compilations. */
JavaCompiler compiler;
/** The name of the public class. For 'HelloWorld.java',
this would be 'HelloWorld'. */
JTextField name;
/** The source code to be compiled. */
JTextArea sourceCode;
/** Errors and messages from the compiler. */
JTextArea output;
JButton compile;
static int pad = 5;
GuiCompiler() {
super( new BorderLayout(pad,pad) );
setBorder( new EmptyBorder(7,4,7,4) );
/** A worker to perform each compilation. Disables
the GUI input elements during the work. */
class SourceCompilation extends SwingWorker<String, Object> {
@Override
public String doInBackground() {
return compileCode();
@Override
protected void done() {
try {
enableComponents(true);
} catch (Exception ignore) {
/** Construct the GUI. */
public void initGui() {
JPanel input = new JPanel( new BorderLayout(pad,pad) );
Font outputFont = new Font("Monospaced",Font.PLAIN,12);
sourceCode = new JTextArea("Paste code here..", 15, 60);
sourceCode.setFont( outputFont );
input.add( new JScrollPane( sourceCode ),
BorderLayout.CENTER );
sourceCode.select(0,sourceCode.getText().length());
JPanel namePanel = new JPanel(new BorderLayout(pad,pad));
name = new JTextField(15);
name.setToolTipText("Name of the public class");
namePanel.add( name, BorderLayout.CENTER );
namePanel.add( new JLabel("Class name"), BorderLayout.WEST );
input.add( namePanel, BorderLayout.NORTH );
compile = new JButton( "Compile" );
compile.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
(new SourceCompilation()).execute();
input.add( compile, BorderLayout.SOUTH );
this.add( input, BorderLayout.CENTER );
output = new JTextArea("", 5, 40);
output.setFont( outputFont );
output.setEditable(false);
this.add( new JScrollPane( output ), BorderLayout.SOUTH );
/** Compile the code in the source input area. */
public String compileCode() {
output.setText( "Compiling.." );
enableComponents(false);
String compResult = null;
if (compiler==null) {
compiler = ToolProvider.getSystemJavaCompiler();
if ( compiler!=null ) {
String code = sourceCode.getText();
String sourceName = name.getText().trim();
if ( sourceName.toLowerCase().endsWith(".java") ) {
sourceName = sourceName.substring(
0,sourceName.length()-5 );
JavaSourceFromString javaString = new JavaSourceFromString(
sourceName,
code);
ArrayList<JavaSourceFromString> al =
new ArrayList<JavaSourceFromString>();
al.add( javaString );
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStreamWriter osw = new OutputStreamWriter( baos );
JavaCompiler.CompilationTask task = compiler.getTask(
osw,
null,
null,
null,
null,
al);
boolean success = task.call();
output.setText( baos.toString().replaceAll("\t", " ") );
compResult = "Compiled without errors: " + success;
output.append( compResult );
output.setCaretPosition(0);
} else {
output.setText( "No compilation possible - sorry!" );
JOptionPane.showMessageDialog(this,
"No compiler is available to this runtime!",
"Compiler not found",
JOptionPane.ERROR_MESSAGE
System.exit(-1);
return compResult;
/** Set the main GUI input components enabled
according to the enable flag. */
public void enableComponents(boolean enable) {
compile.setEnabled(enable);
name.setEnabled(enable);
sourceCode.setEnabled(enable);
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
public void run() {
JFrame f = new JFrame("SSCCE text based compiler");
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
GuiCompiler compilerPane = new GuiCompiler();
compilerPane.initGui();
f.getContentPane().add(compilerPane);
f.pack();
f.setMinimumSize( f.getSize() );
f.setLocationRelativeTo(null);
f.setVisible(true);
EventQueue.invokeLater(r);
* A file object used to represent source coming from a string.
* This example is from the JavaDocs for JavaCompiler.
class JavaSourceFromString extends SimpleJavaFileObject {
* The source code of this "file".
final String code;
* Constructs a new JavaSourceFromString.
* @param name the name of the compilation unit represented
by this file object
* @param code the source code for the compilation unit
represented by this file object
JavaSourceFromString(String name, String code) {
super(URI.create(
"string:///" +
name.replace('.','/') +
Kind.SOURCE.extension),
Kind.SOURCE);
this.code = code;
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}Edit 1:
Added..
f.setMinimumSize( f.getSize() );Edited by: AndrewThompson64 on Jun 13, 2008 12:24 PM
Edited by: AndrewThompson64 on Jun 23, 2008 5:54 AMkevjava wrote: Some things that I think would be useful:
Suggestions reordered to suit my reply..
kevjava wrote: 2. Line numbering, and/or a line counter so you can see how much scrolling you're going to be imposing on the forum readers.
Good idea, and since the line count is only a handful of lines of code to implement, I took that option. See the [line count|http://pscode.org/stbc/help.html#linecount] section of the (new) [STBC Help|http://pscode.org/stbc/help.html] page for more details. (Insert plaintiff whining about the arbitrary limits set - here).
I considered adding line length checking, but the [Text Width Checker|http://pscode.org/twc/] ('sold separately') already has that covered, and I would prefer to keep this tool more specific to compilation, which leads me to..
kevjava wrote: 1. A button to run the code, to see that it demonstrates the problem that you wish for the forum to solve...
Interesting idea, but I think that is better suited to a more full blown (but still relatively simple) GUId compiler. I am not fully decided that running a class is unsuited to STBC, but I am more likely to implement a clickable list of compilation errors, than a 'run' button.
On the other hand I am thinking the clickable error list is also better suited to an altogether more abled compiler, so don't hold your breath to see either in the STBC.
You might note I have not bothered to update the screenshots to show the line count label. That is because I am still considering error lists and running code, and open to further suggestion (not because I am just slack!). If the screenshots update to include the line count but nothing else, take that as a sign. ;-)
Thanks for your ideas. The line count alone is worth a few Dukes. -
Help with simple Automator script
I have a simple Automator script for updating a specified folder with files from another folder. It consists of only two actions:
1. Get Folder Contents (from the folder I drop on the Automator executable).
2. Copy Finder Items.
I left the option "replace existing files" unchecked because there's no point in replacing a bunch of files that already exist (we're talking about 4000-5000 files in the source folder). I assumed that meant to ignore any existing files but, on the contrary, I found out that the script is copying duplicates of all the existing files -- making my target folder about 9000 files strong!
How do I get a command into the middle of this script to restrict the Copy Finder Items command to files that do not already exist in the target folder? (It would be even nicer if it could check for files that are older than the files being copied and actually replace (only) those as well.)
Any ideas?If you need the Terminal window to stay open, then you're looking at scripting Terminal. You can do this with Automator's run applescript action, or you can just use Script Editor (in Applications > AppleScript). Either way you will need to save the workflow/script as an application and drag it to your Login Items (in System Preferences > Accounts).
click here to open this script in your editor<pre style="font-family: 'Monaco', 'Courier New', Courier, monospace; overflow:auto; color: #222; background: #DDD; padding: 0.2em; font-size: 10px; width:400px">tell application "Terminal"
activate
set commands to "cd /Users/lenny/ventrilo/
/Users/lenny/ventrilo/ventrilo_srv"
do script commands in front window
end tell</pre>
PowerMac G5 (June 2004) 2x1.8GHz 1.25GB, PowerBook G4 (12-inch DVI) 1x1GHz 768MB Mac OS X (10.4.3) -
Creating simple shell script packages to deploy with ARD and TaskServer
I am looking for a simple step by step on how to create a package that can be deployed using ARD, to run a simple shell script like
"softwareupdate -i -a"
A brief search here returned nothing, but perhaps I was not using the correct terms.
Ultimately, I want to use ARD to run software update on ~400 Macs.
Thanks in advance for your help.
BillIf I send it as a unix command, it will run only on machines that are currently awake and responding to ARD.
If I can set it up as a package, then I can use Task Server to "deploy" the command to machines that are not currently online. When the machines next contact the Task Server, they will be told to run softwareupdate. -
Hey
Im looking for a simple AppleScript i can run on client workstations , The Script ideally needs to do the following ..
- Find any files in the User's Home folder with a Creation date older than 3 years ago.
- Display the files and allow user to delete.
Im sure this is quite simple for someone who knows what there doing with AppleScript ! , anyone have any simple scripts they could suggest ?
CheersWell, getting a list of files is one thing (there are several shell utilities), getting them in a Finder window so you can do various things with them is another. There isn't much AppleScript support for the Finder's Find…, and saved searches don't appear to be portable. GUI scripting is more akin to voodoo, but I figured I would give it a shot to see if I could get close.
The following script pastes the appropriate search term in the Search item in a Finder window's toolbar. Getting the search to start in a specific place is a bit goofy, but if you have navigated to the desired folder, running the script should start the search from there:
<pre style="
font-family: Monaco, 'Courier New', Courier, monospace;
font-size: 10px;
margin: 0px;
padding: 5px;
border: 1px solid #000000;
width: 720px; height: 340px;
color: #000000;
background-color: #FFDDFF;
overflow: auto;"
title="this text can be pasted into the Script Editor">
-- enter a search term in the Finder's search toolbar item
-- set the search date
tell ((current date) as «class isot» as string)
(get text 1 thru 4) - 3 -- the current year - 3
set SearchDate to text 6 thru 7 & "/" & text 9 thru 10 & "/" & result
end tell
-- make sure there is a Finder window and the toolbar is showing
tell application "Finder"
activate
if (get windows) is {} then set target of (make new Finder window) to path to home folder
if not toolbar visible of front window then set toolbar visible of front window to true
end tell
-- enter the search term into the search text field, if present
tell application "System Events"
if UI elements enabled then
get value of attribute "AXRoleDescription" of text field 1 of group 1 of tool bar of front window of application process "Finder"
if (result as text) is "search text field" then -- toolbar search item exists
set value of text field 1 of group 1 of tool bar of front window of application process "Finder" to "created:<=" & SearchDate
else -- oops
activate
display dialog "This script needs to use the Search item on the toolbar - please customize the Finder toolbar to include Search." with title "Find by creation date" buttons {"OK"} default button 1
end if
else
tell application "System Preferences"
activate
set current pane to pane "com.apple.preference.universalaccess"
display dialog "This script needs UI element scripting enabled. Check \"Enable access for assistive devices\" and try again." with title "Find by creation date" buttons {"OK"} default button 1
end tell
end if
end tell
</pre>
HTH -
Hi everyone , i am building a simple GUI playing mp3 files in a certain directory.
A bug or something wrong with the codes listed down here is very confusing me and makes me desperate. Can anyone help me please ?
import javax.swing.*;
import javax.media.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
class PlayMP3Thread
extends Thread
private URL url;
String[] filenames ;
File[] files ;
boolean condition=true;
boolean pause=false;
int count ;
public PlayMP3Thread() { }
public PlayMP3Thread(File[] files)
//try
this.files = files;
filenames = new String[files.length];
count = -1;
// this.url = mp3.toURL();
//catch ( MalformedURLException me )
public void run()
try
while (condition)
count++;
if (count > (filenames.length - 1)) {
count = 0;
this.url = files[count].toURL();
MediaLocator ml = new MediaLocator(url);
final Player player = Manager.createPlayer(ml);
/*player.addControllerListener(
new ControllerListener()
public void controllerUpdate(ControllerEvent event)
if (event instanceof EndOfMediaEvent)
player.stop();
player.close();
player.realize();
player.start();
catch (Exception e)
e.printStackTrace();
public void stops()
//stop the thread
condition=false;
pause=false;
public void pause()
while(!pause)
//pause the thread
try
wait();
catch(Exception ex){}
pause=true;
public void resumes()
while(pause)
notify();
pause=false;
} // end of class MP3Thread
public class mp3Play extends JFrame {
JTextField direcText ;
JFileChooser fc;
static final String
TITLE="MP3 PLAYER",
DIRECTORY="Directory : ",
BROWSE="Browse...",
START="Start up",
STOP="Stop",
PAUSE="Pause",
RESUME="Resume",
EXIT="Exit";
public static void main(String args[])
PlayMP3Thread play = new PlayMP3Thread();
mp3Play pl = new mp3Play();
} // End of main()
public mp3Play() {
setTitle(TITLE);
Container back = getContentPane();
back.setLayout(new GridLayout(0,1));
back.add(new JLabel(new ImageIcon("images/hello.gif")));
fc = new JFileChooser();
fc.setFileSelectionMode(fc.DIRECTORIES_ONLY);
JPanel p1 = new JPanel();
p1.add(new JLabel(DIRECTORY, new ImageIcon("images/directory.gif"), JLabel.CENTER));
p1.add(direcText = new JTextField(20));
JButton browseButton = new JButton(BROWSE, new ImageIcon("images/browse.gif"));
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showOpenDialog(mp3Play.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
direcText.setText(fc.getSelectedFile().toString());
File[] files = (new File(direcText.getText())).listFiles(this);
p1.add(browseButton);
back.add(p1);
JPanel p2 = new JPanel();
JPanel butPanel = new JPanel();
butPanel.setBorder(BorderFactory.createLineBorder(Color.black));
JButton startButton = new JButton(START, new ImageIcon("images/start.gif"));
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
PlayMP3Thread play = new PlayMP3Thread(files);
play.start();
butPanel.add(startButton);
p2.add(butPanel);
JButton stopButton = new JButton(STOP, new ImageIcon("images/stop.gif"));
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
play.stops();
p2.add(stopButton);
JButton pauseButton = new JButton(PAUSE, new ImageIcon("images/pause.gif"));
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
play.pause();
p2.add(pausetButton);
JButton resumeButton = new JButton(RESUME, new ImageIcon("images/resume.gif"));
resumeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
play.resumes();
p2.add(resumeButton);
back.add(p2);
JButton exitButton = new JButton(EXIT, new ImageIcon("images/exit.gif"));
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
p2.add(exitButton);
back.add(p2);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
pack();
setVisible(true);
}Actually I don't know much about fixing technical error or logical error.
When it compiled , there are 6 errors showed up :
can't resolve symbol : method listFiles (<anonymous java.awt.event.ActionListener>)
location: class java.io.File
File[] files = (new File(direcText.getText())).listFiles(this);
can't resolve symbol: variable files
PlayMP3Thread play = new PlayMP3Thread(files);
can't resolve symbol: variable play
play.stops();
can't resolve symbol: variable play
play.pause();
^
can't resolve symbol : variable pausetButton
location: class mp3Play
p2.add(pausetButton);
^
can't resolve symbol: variable play
play.resumes();
Any suggestions ? -
How Do i create a list that will show in a dropdown box with the list being pulled from another tab and not the cell data format junk?
I currently run OS X 10.10.1
Now i have been trying to work on this for a while now and what i want to do should be simple but its apparently not.
Here is an example of what i want to happen.
I will have 2 tabs: Contact | Sales
Now Contacts will have the list of names and various information about a customer, While Sales will have one drop-down box for each Cell Row that will show the names of the person in tab contacts
for what i am wanting to do i cant use the data format pop-up menu because the list is edited everyday several times a day.
Now how do i do this, Excel can do this so how can numbers do it?Hi Shegra,
Paste this into a applescript editor window and run it from there. In the script you may need to adjust the four properties to agree with your spreadsheet. Let me know if you have any questions.
quinn
Script starts:
-- This script converts column A in one table into an alphabetized list of popups. It copies the last cell in that column. Then reverts the column to text. It then refreshes popups in column A of a data table starting with a user defined row.
property DataEntrySheet : "Sheet 1" --name of sheet with popups to be refreshed
property DataEntryTable : "Sales" --name of table with popups to be refreshed
set copyRange to {}
property PopValueSheet : "Sheet 1" --name of sheet with popup values table
property PopValueTable : "Contacts" --name of table with popup values
set PopStartRow to {}
tell application "Numbers"
set d to front document
set ps to d's sheet PopValueSheet
set pt to ps's table PopValueTable
set s to d's sheet DataEntrySheet
set t to s's table DataEntryTable
set tf to t's filtered --this records filter setting on data Entry Table
display dialog "Start from row #..." default answer "" with icon 1 -- with icon file "Path:to:my.icon.icns" --a Week # row
set PopStartRow to {text returned of result}
tell pt --convert list to alphabetized popups
set ptRows to count rows
set copyRange to ("A2:" & name of cell ptRows of column "A")
set selection range to range copyRange
set selection range's format to text
sort by column 1 direction ascending
set selection range's format to pop up menu
-- popupsmade
set selection range to cell ptRows of column 1 of pt
set v to value of cell ptRows of pt
end tell
activate application "Numbers"
tell application "System Events" to keystroke "c" using command down
tell pt
set selection range to range copyRange
set selection range's format to text
end tell
tell t
set filtered to false
set tRows to count rows
set pasteRange to ((name of cell PopStartRow of column "A") & ":" & (name of cell tRows of column "A"))
set selection range to range pasteRange
tell application "System Events" to keystroke "v" using command down
set filtered to tf
end tell
end tell -
Execute a procedure with a list of array in sql server 2008
HI all,
I have a procedure which has a list of values passed as an array . How can i execute my procedure with array list? how to implement this?Please help me.
Thanks in advance
DeepaHi Deepa,
basically Microsoft SQL Server does not support arrays as data types for procedures. What you can do is creating a type which represents a table definition. This type can than be used in a procedure as the following demo will show:
The first script creates the environment which will be used for the execution
-- 1. create the table as a type in the database
CREATE TYPE OrderItems AS TABLE
ItemId int PRIMARY KEY CLUSTERED
GO
-- 2. demo table for demonstration of results
CREATE TABLE dbo.CustomerOrders
Id int NOT NULL IDENTITY (1, 1) PRIMARY KEY CLUSTERED,
CustomerId int NOT NULL,
ItemId int
GO
-- 3. Insert a few records in demo table
INSERT INTO dbo.CustomerOrders
(CustomerId, ItemId)
VALUES
(1, 1),
(2, 1),
(3, 3),
(1, 3);
GO
-- 4. Create the procedure which accepts the table variable
CREATE PROC dbo.OrderedItemsList
@Orders AS OrderItems READONLY
AS
SET NOCOUNT ON;
SELECT o.*
FROM dbo.CustomerOrders AS O INNER JOIN @Orders AS T_O
ON (o.ItemId = T_O.ItemId);
SET NOCOUNT OFF;
GO
The above script creates the table data type and a demo table with a few demo data. The procedure will accept the table data type as parameter. Keep in mind that table variable parameters have to be READONLY as parameter for procedures!
The second script demonstrates the usage of the above scenario
When the environment has been created the usage is a very simple one as you can see from the next script...
-- 1. Fill the variable table with item ids
DECLARE @o AS OrderItems;
INSERT INTO @o (ItemId)
VALUES
(1), (3);
-- 2. Get the list of customers who bought these items
EXEC dbo.OrderedItemsList @Orders = @o;
MCM - SQL Server 2008
MCSE - SQL Server 2012
db Berater GmbH
SQL Server Blog (german only) -
Documentation on GUI scripting
I am looking for some detailed documentation on GUI scripting. I am trying to figure out the click command so that I may use it in fireFox.
RobertChances are, your problem isn't with click because its options are very straightforward:
click
click (verb)cause the target process to behave as if the UI element were clicked (from Processes Suite)
function syntax
set theResult to click UI element ¬
at list
result
UI element
direct parameter optional UI element The UI element to be clicked.
at optional list when sent to a "process" object, the { x, y } location at which to click, in global coordinates
The problem is more likely to be how to work out the UI Element you want to click. Many applications make this less than obvious since it's often an object in a pane of a window and you need to know all the parts. If that is the case, get a copy of Prefab's UI Browser which does all the hard work of working out the UI element. -
Simple bash scripting help needed..
I want to learn som simple bash scripting in order to automate various tasks.. Im totally noob, so bear with me
First of all I would like to set configs without using nano.. is there a simple command for this? For example if i want change my hostname in /etc/rc.conf.. how can i print the current vallue and how can i change it`?
i was thinking something like this to get the current value:
# cat /etc/rc.conf | grep HOSTNAME=
which returns HOSTNAME="myhostname"
how can i change this value with one or more commands whitout touching the rest of the file?abesto wrote:
A slightly naive solution:
CHOICE="lisa"
NAMES="homer marge lisa bart maggie"
if [ "`echo \" $NAMES \" | grep \" $CHOICE \"`" ]; then
echo "this is how you do it"
fi
The extra spaces inside the escaped quotes are to ensure that only a whole word is "matched".
You can also replace the elif's with a loop through a list of "the other variables". Then you'd use the loop variable instead of $CHOICE above.
grep can check on word-bounderies with \< and \>, or with the -w switch. The -q switch suppresses any messages and exits with exit-code 0 when the first match is found:
if echo "${NAMES}" | grep -qw "${CHOICE}"; then
Nice and readable, should work, but i haven't tested it
EDIT:
Procyon wrote:CHOICE="lisa"
NAMES="homer marge lisa bart maggie"
if [[ $NAMES =~ $CHOICE ]]; then echo match; fi
This one also matches elisa, ie. no check on word bounderies. You should be carefull with that
Last edited by klixon (2009-04-23 09:40:22) -
Simple beginner script problem
I'm reading Scripting InDesign CS3/4 with Javascript from O'Reilly and this simple example doesn't seem to work. Can someone please see what's up?
Another useful application of split () and join () is processing paragraphs in a text frame. To see how this works, create a new InDesign document; draw a text frame big enough to hold about half a dozen names; and type a list of half a dozen names, one a line. Select the text frame or place the cursor somewhere in the list. The following script sorts the list alphabetically:
// check that a story is selected
if (app.selection[0].parentStory.constructor.name!="Story")
exit ( );
// create an array of paragraphs by splitting the story on hard returns
myArray = app.selection[0].parentStory.contents.split ("\r");
// sort the array
myArray.sort ( );
// join the array as one string separated by hard returns
myString = myArray.join ("\r");
// replace the contents of the selected story with myString
app.selection[0].parentStory.contents = myString;It highlights
if (app.selection[0].parentStory.constructor.name!="Story")
and says undefined is not an object
Edit: solution, I had to choose Adobe InDesign CS5 from the ESTK menu instead of ESTK CS5
Maybe you are looking for
-
Satellite Pro A200 - Where to get new recovery disk?
On Thursday of last week ended up with the Blue page of death, tried to use the product recovery disk and found to my horror it has a large crack in it . Can anyone tell me were I can upload a new disk from? Have managed at cost to get the laptop up
-
I want to move SQ01 to another system
Hi experts, I have a quest to move SQ01 to another system. Since it is a standard transaction,it has a lot of screens , includes and so on. 1 Should I change all the standard includs name to customer namespace? 2 Is there any brief step by step docum
-
Please ..give me some example APDU for writing data to java card
morning everybody .. :) I need some example APDUs for writing data to java card. (CLA || INS || P1 || P2 etc).. please..thank for your attention .. god blessing u.
-
How long should it take a well-qualified server admin to migrate from Tiger to Lion... For a small company, if the Tiger server is running on a G4 Tower: -Roughly 500GB in user files -Data resides on old-school ATA drives -OD Master - Kerberized -AFP
-
Hi I have an application where I am maintaining a list of items e.g. say a resturarant menu which can have items added/deleted and so on, the menu would only be about 40 items at most. As I have a limited number of items, i imagine a file would be co