Help with Applescript and Admin Privelages

I just started using Applestript a few months ago and I can't figure out how to give my script Admin rights. Basically, it turns on and off my internet sharing and file sharing through dialog boxes. I copied and pasted the whole code below if you want to test it, but this is the part that is giving me trouble. There are 4 lines similar to this, the actions that turn on or off the services.
do shell script "/bin/launchctl load -w /System/Library/LaunchDaemons/com.apple.InternetSharing.plist" with administrator privileges
I've tried adding "with password _____" and "password_____" but neither worked. Can anyone help me make this script authenticate itself so I don't need to keep typine in my password? I could easily make a keystroke in system events to type it in but it doesn't always ask for it so I don't know how I'd make the script know when it needs to enter the password. any help is much appreciated!
Some things to clarify: The first shell script is there to invoke the "authentication" dialog so I can sign in once I launch the app and get right into the settings. However, I'd like to make it so the script doesn't even need admin permission to run, or make it somehow have my password built in to it. Security is not an issue, its my personal computer that nobody else has access to so I really don't care if my password is written in the code. Also, if you have any tips on how to streamline the Quit/Hide/Resume dialog I'd appreciate that too. Resume is there because there's a chance I won't have to sign in again if the app does not quit, however more often than not I have to sign in anyways. Thanks again in advance, sorry this post is so long but like I said, I'm pretty new to all this so I don't know exactly what you need to be able to help me.
The Whole Script:
-- Variables and Authentication
set done to "n"
set quitapp to "no"
display dialog "Please enter your password to allow Sharing Manager to make changes to your settings." with icon caution
do shell script "/bin/launchctl unload -w /System/Library/LaunchDaemons/com.apple.AppleFileServer.plist" with administrator privileges
delay 0.2
-- Repeats
repeat while quitapp is "no"
          repeat while done is "n"
  -- Choose Setting
                    display dialog "Choose Setting to Edit" buttons {"Internet", "File Sharing", "Exit"} default button 3
                    set the button_pressed to the button returned of the result
                    if the button_pressed is "Internet" then
  -- Commands for Internet Settings
                              display dialog "Internet Sharing" buttons {"On", "Off", "Cancel"} default button 3
                              set the button_pressed to the button returned of the result
                              if the button_pressed is "On" then
                                        do shell script "/bin/launchctl load -w /System/Library/LaunchDaemons/com.apple.InternetSharing.plist" with administrator privileges
                              else if the button_pressed is "Off" then
                                        do shell script "/bin/launchctl unload -w /System/Library/LaunchDaemons/com.apple.InternetSharing.plist" with administrator privileges
                              end if
                    else if the button_pressed is "File Sharing" then
  -- Commands for Sharing Settings
                              display dialog "File Sharing" buttons {"On", "Off", "Cancel"} default button 3
                              set the button_pressed to the button returned of the result
                              if the button_pressed is "On" then
                                        do shell script "/bin/launchctl load -w /System/Library/LaunchDaemons/com.apple.AppleFileServer.plist" with administrator privileges
                              else if the button_pressed is "Off" then
                                        do shell script "/bin/launchctl unload -w /System/Library/LaunchDaemons/com.apple.AppleFileServer.plist" with administrator privileges
                              end if
                    else
                              set done to ""
                    end if
          end repeat
  -- Confirm Quit/Hide
          display dialog "Really quit? You will have to reenter admin info next time." buttons {"Quit", "Hide", "Resume"} default button 1
          if the button returned of the result is "Quit" then
                    set quitapp to ""
          else if the button returned of the result is "Hide" then
                    tell application "System Events"
  keystroke "h" using command down
                    end tell
          else
                    set done to "n"
                    set quitapp to "no"
          end if
end repeat

with respect to general improvements, a couple of points:
If I'm reading this script correctly, it looks like you're putting up an applescript alert and leaving it hanging until it's dismissed.  This is an atypical approach (applescripts aren't really meant to hang around indefinitely waiting for a respons).  If I were doing this I would either go whole-hog and create an applescript application in XCode with a proper interface, or remove the hanging dialog and create a set of toggle scripts that I could use from the script menu.  if you really want to keep the hanging dialog, though, you can streamline it by absorbing the secondary dialogs into the main dialog.  that's like so:
set netSharingStatus to checkService("com.apple.InternetSharing")
set fileSharingStatus to checkService("com.apple.AppleFileServer")
display alert "Current Settings" message "Click to change settings" buttons {"Internet " & netSharingStatus, "File Sharing " & fileSharingStatus, "Exit"} default button 3
-- choose next action based on the button clicked and the status vairable
on checkService(service)
          do shell script "launchctl list"
          if the result contains service then
                    return "On"
          else
                    return "Off"
          end if
end checkService
using handlers like the above can also streamline the rest of your script.  the following construction means you only have to write the do shell script line once, rather than the four times you currently do, and makes for much cleaner reading.
if the button_pressed starts with "Internet" then
          toggleService("com.apple.InternetSharing", netSharingStatus)
else if the button_pressed starts with "File Sharing" then
          toggleService("com.apple.AppleFileServer", fileSharingStatus)
else
  --exit routine
end if
on toggleService(service, currentState)
          if currentState in "On" then
                    set action to "unload"
          else
                    set action to "load"
          end if
          set command to "/bin/launchctl " & action & " -w /System/Library/LaunchDaemons/" & service & ".plist"
          do shell script command user name "adminusername" password "password" with administrator privileges
end toggleService

Similar Messages

  • Need help with applescript and Xcode 4.3.2

    I'm trying to write my first application that will involve a GUI. I can code applescript using script editor with a bit of effort, but I'm want to have users input more than one piece of information in the pop up. So, I download xcode, create my first applescript cocoa project go to MainMenu.xib and add a bunch of labels, text fields and buttons. Looks fairly nice... Go to start it and... nothing (well the window pops up, but it doesn't do anything). Unfortunately, I haven't figured out how to link the window to the applescript... So, how do I...
    * Have the applescript prepopulate data in the text fields and pulldowns
    * Once the user changes the data in the fields tell the applescript
    * Tell the window to close and pass the control back to the applescript once either the cancel or submit button is pressed.
    More detailed...
    * What's an outlet and how do I use it here? Which of the 18 outlet(s) do i use for this?
    * What's a property (referenced on one of the web pages I saw around applescript and cocoa) and do I need them here?
    Looking at the documentation with xcode, there isn't a lot about xcode and applescipt. Looking at the web, the top links are a few years old. So, links to good relevent documentation would be very nice as well as direct answers to the questions
    Thanks,
    Scott

    I'm not sure why you are closing it, but the NSApplication class is what keeps track of the windows.  If you don't want to connect the window to an outlet from the interface editor, you can use something like
    set theWindow to current application's NSApplication's sharedApplication's mainWindow()
    ...and from there you can use whatever NSWindow methods, for example
    theWindow's performClose_(me)

  • Help with Applescript - filenames

    Hi!
    I hope there is someone who can help me. I have very little experience with Applescript, and have spent a couple of days scouring these forums amongst others without any luck...
    I have a folder (titled XLS) with about 1000 excel files in it. They are numbered basen on some parametric calculations (1111.xls, 1112.xls, 1113.xls, etc). I have constructed an Automator rutine which, one at a time, can open each excel file, copy some cells and then paste the data into an empty xml-file in TextWrangler. The empty xml-file is also in the XLS folder.
    What I am looking for is an applescript which can rename the open xml-file with the same filename as the xls-file. So, when 1111.xls is open, the xml-file gets renamed 1111-xml; when 1112.xls is open, the xml-file gets renamed 1112-xml, etc. Each new xlm-file is to be saved into a folder XLM, whivh is also in the XLS folder.
    Thanks in advance....
    Rob

    Se below; there are two folders on the desktop; "xls" (with xls-files in) and "xml", as well as the empty Template.xml file. Here it is!:
      --3 XLS to XML
              tell application "Finder"
                        set fileList to every file of entire contents of ("YourHD:Users:You:Desktop:xls" as alias)
              end tell
              repeat with i from 1 to number of items in fileList
                        set currentFile to (item i of fileList)
                        tell application "Microsoft Excel"
                                  set screen updating to false
      open currentFile
      activate currentFile
      activate object worksheet 1
                                  copy range range ("YourRange")
                        end tell
                        tell application "Finder"
                                  copy file "YourHD:Users:You:Desktop:Template.xml" to folder "YourHD:Users:You:Desktop:xml"
                        end tell
                        tell application "Microsoft Excel"
                                  set docName to name of window 1
                        end tell
                        tell application "Finder"
                                  set docName2 to text 1 thru ((offset of "." in docName) - 1) of docName
                                  set theFile to "YourHD:Users:You:Desktop:xml:Template.xml" as alias
                                  set the name of theFile to docName2 & ".xml"
      open file theFile
                        end tell
                        tell application "TextWrangler"
      activate
      paste
      close text document 1 saving yes
                        end tell
                        tell application "Microsoft Excel"
      activate
      close active workbook saving no
                        end tell
              end repeat
              tell application "Microsoft Excel"
                        set screen updating to true
      quit
              end tell
              tell application "TextWrangler"
      quit
              end tell

  • Help with writing and retrieving data from a table field with type "LCHR"

    Hi Experts,
    I need help with writing and reading data from a database table field which has a type of "LCHR". I have given an example of the original code but don't know what to change it to in order to fix it and still read in the original data that's stored in the LCHR field.
    Basically we have two Function modules, one that saves list data to a database table and one that reads in this data. Both Function modules have an identicle table which has an array of fields from type INT4, CHAR, and type P. The INT4 field is the first one.
    Incidentally this worked in the 4.7 non-unicode system but is now dumping in the new ECC6 Unicode system.
    Thanks in advance,
    C
    SAVING THE LIST DATA TO DB
    DATA: L_WA(800).
    LOOP AT T_TAB into L_WA.
    ZDBTAB-DATALEN = STRLEN( L_WA ).
    MOVE: L_WA to ZDBTAB-RAWDATA.
    ZDBTAB-LINENUM = SY-TABIX.
    INSERT ZDBTAB.
    READING THE DATA FROM DB
    DATA: BEGIN OF T_DATA,
                 SEQNR type ZDBTAB-LINENUM,
                 DATA type ZDBTAB-RAWDATA,
               END OF T_TAB.
    Select the data.
    SELECT linenum rawdata from ZDBTAB into table T_DATA
         WHERE repid = w_repname
         AND rundate = w_rundate
         ORDER BY linenum.
    Populate calling Internal Table.
    LOOP AT T-DATA.
    APPEND T_DATA to T_TAB.
    ENDLOOP.

    Hi Anuj,
    The unicode flag is active.
    When I run our report and then to try and save the list data a dump is happening at the following point
    LOOP AT T_TAB into L_WA.
    As I say, T_TAB consists of different fields and field types whereas L_WA is CHAR 800. The dump mentions UC_OBJECTS_NOT_CONVERTIBLE
    When I try to load a saved list the dump is happening at the following point
    APPEND T_DATA-RAWDATA to T_TAB.
    T_DATA-RAWDATA is type LCHR and T_TAB consists of different fields and field types.
    In both examples the dumps mention UC_OBJECTS_NOT_CONVERTIBLE
    Regards
    C

  • Help with count and sum query

    Hi I am using oracle 10g. Trying to aggregate duplicate count records. I have so far:
    SELECT 'ST' LEDGER,
    CASE
    WHEN c.Category = 'E' THEN 'Headcount Exempt'
    ELSE 'Headcount Non-Exempt'
    END
    ACCOUNTS,
    CASE WHEN a.COMPANY = 'ZEE' THEN 'OH' ELSE 'NA' END MARKET,
    'MARCH_12' AS PERIOD,
    COUNT (a.empl_id) head_count
    FROM essbase.employee_pubinfo a
    LEFT OUTER JOIN MMS_DIST_COPY b
    ON a.cost_ctr = TRIM (b.bu)
    INNER JOIN MMS_GL_PAY_GROUPS c
    ON a.pay_group = c.group_code
    WHERE a.employee_status IN ('A', 'L', 'P', 'S')
    AND FISCAL_YEAR = '2012'
    AND FISCAL_MONTH = 'MARCH'
    GROUP BY a.company,
    b.district,
    a.cost_ctr,
    c.category,
    a.fiscal_month,
    a.fiscal_year;
    which gives me same rows with different head_counts. I am trying to combine the same rows as a total (one record). Do I use a subquery?

    Hi,
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    user610131 wrote:
    ... which gives me same rows with different head_counts.If they have different head_counts, then the rows are not the same.
    I am trying to combine the same rows as a total (one record). Do I use a subquery?Maybe. It's more likely that you need a different GROUP BY clause, since the GROUP BY clause determines how many rows of output there will be. I'll be able to say more after you post the sample data, results, and explanation.
    You may want both a sub-query and a different GROUP BY clause. For example:
    WITH    got_group_by_columns     AS
         SELECT  a.empl_id
         ,     CASE
                        WHEN  c.category = 'E'
                  THEN  'Headcount Exempt'
                        ELSE  'Headcount Non-Exempt'
                END          AS accounts
         ,       CASE
                        WHEN a.company = 'ZEE'
                        THEN 'OH'
                        ELSE 'NA'
                END          AS market
         FROM              essbase.employee_pubinfo a
         LEFT OUTER JOIN  mms_dist_copy             b  ON   a.cost_ctr     = TRIM (b.bu)
         INNER JOIN       mms_gl_pay_groups        c  ON   a.pay_group      = c.group_code
         WHERE     a.employee_status     IN ('A', 'L', 'P', 'S')
         AND        fiscal_year           = '2012'
         AND        fiscal_month          = 'MARCH'
    SELECT    'ST'               AS ledger
    ,       accounts
    ,       market
    ,       'MARCH_12'          AS period
    ,       COUNT (empl_id)       AS head_count
    FROM       got_group_by_columns
    GROUP BY  accounts
    ,            market
    ;But that's just a wild guess.
    You said you wanted "Help with count and sum". I see the COUNT, but what do you want with SUM? No doubt this will be clearer after you post the sample data and results.
    Edited by: Frank Kulash on Apr 4, 2012 5:31 PM

  • MOVED: [Athlon64] Need Help with X64 and Promise 20378

    This topic has been moved to Operating Systems.
    [Athlon64] Need Help with X64 and Promise 20378

    I'm moving this the the Administration Forum.  It seems more apporpiate there.

  • If you need help with CPS and Contribute

    After over a month of contacting support, I have come to the conclusion that Adobe does not offer advance support for CPS. The only thing that the low level tech support agents are capable of doing is
    1. transferring you to someone else,
    2. Sending you links to the online manual and livedocs that you have probably already read.
    After spending over a month and roughly 100+ hours I have determine that CPS cannot handle multiple client certificates sent via a Department of Defense Common Access Card. I did learn the following info that you might find useful.
    1.      Contribute must be able to write a file to the root (when you 1st connect it writes TMPjaisd8ua89ua.htm then deletes it) If this failes for any reason, contribute gives you the ever so helpful could not connect error
    2.      contribute must be able to write / delete files in root/_mm
    3.      If you want users to send drafts contribute must have access to root/MMWIP
    4.      If you are using Contribute CS3 or newer and you remove a connection from a computer, the connection isn't really removed 100%, you must go into regedit, current user, software, adobe, contribute41 and clear out keystore, trusted CPS Server, Admin Servers. Just leave the defaults. This might be different for version 5
    5.      Work with an LDAP admin to get the correct LDAP settings so CPS can view the directory
    6.      If using multi LDAP servers ensure that replication is working correctly on them all otherwise your users won't be able to access the site if connected to a faulty LDAP server. Also make sure users can get to the directory via windows if using local/Network connection
    7.      Work with Network admin to have security logging enable on the web server so anytime contribute gives an error they can check the log to see exactly what your account was trying to do at the time of the error.
    8.      Read the Manuals, in fact memorize them.
    http://help.adobe.com/en_US/Contribute/4.1_CPS/help.html?content=con_overview_ov_3.html
    http://help.adobe.com/en_US/Contribute/4.1_CPS/help.html?content=con_setup_install_si_18.h tml
    http://livedocs.adobe.com/contribute/311/deploying_en/wwhelp/wwhimpl/js/html/wwhelp.htm?hr ef=00000049.htm#134387
    I hope this will shed a little light on CPS and contribute or if not then at least give you some direction on how to debug your problems since Adobe will never help you.

    Addition:
    9.      Create a folder on your desktop called "ctnetperformancelog" and then launch Contribute.  Information logged in these files can provide invaluable insight in pinpointing where problems originate.
    For example:
    135 07/05/11 12:31:53 PM mmoreno netio/LAN PutData ACCESS_DENIED 5 5 0.0017 file://webdev/Dev/ /Dev/_mm/contribute.xml
    This was the result of /_mm/contribute.xml inadvertently being marked read-only due to a dreamweaver misconfiguration.
    See http://kb2.adobe.com/cps/195/tn_19506.html for more details.
    Don't forget to delete or rename this folder (e.g. "ctnetperformancelog-DISABLED") after debugging since the log files can grow quite large.

  • Help with applescript...newbie...no idea what I'm doing...

    Apple Script: I got this applescript off of a forum for RapidCart for Rapidweaver.  It allows the user to upload multiple thumbnails to each e-commerce page with the code...I don't know how to make this work for my files tho...can anyone help...this is what the person said to put into applescript and then run it...please help...
    display dialog "Item número" default answer "" buttons {"OK"} default button 1
    set numitem to text returned of the result
    display dialog "Número de fotos" default answer "2" buttons {"OK"} default button 1
    set contador to text returned of the result
    tell application "TextEdit"
        activate
        make new document
        repeat with counter from 1 to contador
            if counter = 1 then
                make new word at end of text of document 1 with data "<a href=%resource(Labe/L" & numitem & ".jpg)% rel=\"remooz\" title=\"Ref. L" & numitem & " foto " & counter & "\"><img class=\"imageStyle\" alt=\"\" src=%resource(Labe/L" & numitem & ".jpg)% width=\"40\" height=\"40\"></a>" & return
            else
                make new word at end of text of document 1 with data "<a href=%resource(Labe/L" & numitem & "_0" & counter & ".jpg)% rel=\"remooz\" title=\"Ref. L" & numitem & " foto " & counter & "\"><img class=\"imageStyle\" alt=\"\" src=%resource(Labe/L" & numitem & "_0" & counter & ".jpg)% width=\"40\" height=\"40\"></a>" & return
            end if
            set counter to counter + 1
        end repeat
    end tell

    First of all, I know nothing about RapidCart, RapidWeaver
    I've cut and pasted the script into the Applescript editor, compiled it and ran it
    the first dialog prompts for "Item number" - so I typed "5"
    the second dialog prompts for "Number of Photos" - so I typed "2"
    Here's the output
    <a href=%resource(Labe/L5.jpg)% rel="remooz" title="Ref. L5 foto 1"><img class="imageStyle" alt="" src=%resource(Labe/L5.jpg)% width="40" height="40"></a>
    <a href=%resource(Labe/L5_02.jpg)% rel="remooz" title="Ref. L5 foto 2"><img class="imageStyle" alt="" src=%resource(Labe/L5_02.jpg)% width="40" height="40"></a>
    the generated HTML is meaningful to RapidCart.
    Now, the author should have explained that this script is specific to his needs and MUST be customized for your use.
    I don't know how familiar you are with HTML but the "resource" tag refers to a file - a jpg file in this case.

  • Help with applescript to quit certain processes by name?

    Hey, for anyone who knows how to program applescripts well, I could use some help with the script below.
    I'm very new to applescripting and I'm trying to write a script that would automatically quit up to 100 instances of the Google Chrome Renderer process.
    Thanks to google, I found a script similar to what I wanted, and after some tinkering I thought I had it just right. The thing is, if I only set the app_name to Google Chrome, it quits Chrome just fine, but when I try it like this, it doesn't receive any data from grep or awk.
    If anyone can help I'd really appreciate it.
    repeat 100 times
              set app_name to "Google Chrome Renderer"
              set the_pid to (do shell script "ps ax | grep " & (quoted form of app_name) & " | grep -v grep | awk '{print $1}'")
              set new_pid to first word of the_pid
              try
                        if new_pid is not "0" or "1" then do shell script ("kill -9 " & new_pid)
              end try
    end repeat

    try this:
    tell application "System Events"
              set procs to (every process whose name is "Google Chrome Renderer")
              if (count of procs) > 100 then
                        set max to 100
              else
                        set max to count of procs
              end if
              repeat with i from 1 to max
                        tell (item i of procs) to quit
              end repeat
    end tell

  • Export PDF Workflow with Applescript and CS3

    Hello,
    I am setting up some PDF workflow with Applescript.
    On a given moment, as my script runs and after getting some user-input answers to questions in some dialogs, my script tells InDesign CS3 to open the Export Adobe PDF window for the current document. I copied and pasted that small part of the script:
    tell application "Adobe InDesign CS3"
    tell document 1
    export format PDF type to "Macintosh_HD:Test01.pdf" using "somePreset" with showing options
    end tell
    end tell
    When you run this small part of my Applescript, InDesign opens the Export Adobe PDF window (as expected) waiting for me to click on "Export". That is exactly what I want, since the user is given here a last opportunity to change some values (for example page range, or spreads). When all is set, the user can click on Export to close the dialog and finish the script.
    Problem: I was hoping that the Adobe PDF Preset "somePreset" would be selected in the first pull-down menu of the Export Adobe PDF window when this window is opened by the script. Unfortunately the last used preset is always selected by default. Anyone suggestions or help?
    Kind regards,
    Bertus Bolknak.

    My operators enter the page range and filename into a dialog box. Then I set those in the script. I use the Press Quality preset to start with and then set the changes I want into a export variable. I set things like bleed, marks, page range, etc.
    Here is an example:
    set theProps to properties of PDF export preset "[Press Quality]"
    try
    delete PDF export preset "Schmidt PDF"
    end try
    set theStyle to {name:"Schmidt PDF", acrobat compatibility:acrobat 7, bleed top:"0.125i", bleed bottom:"0.125i", bleed inside:"0.125i", bleed outside:"0.125i", page marks offset:"0.125i", include ICC profiles:Include None, effective PDF destination profile:use no profile, effective PDF X profile:"No Color Conversion"} & theProps
    make PDF export preset with properties theStyle
    set properties of PDF export preferences to theStyle
    set color bitmap sampling of PDF export preferences to none
    set grayscale bitmap sampling of PDF export preferences to none
    set page range of PDF export preferences to (item i of myPageList) as string
    export document 1 format PDF type to (PrinergyFolder & myJobNumFinal & "_" & VerCode & ".pdf") as Unicode text without showing options
    I am also doing this in Quark.

  • Problems with AppleScript and MS Office 2011

    The script below used to work great for converting MS Word files to PDF files.  However, sometime during the last few months it has stopped working and will no longer compile without error.  Possibly after upgrading to Mavericks but I'm not exactly sure when it stopped working, could have been an update to Office.  Anyway, the error I'm getting when I compile is a Syntax Error, "Expected end of line but found class name".  The editor highlights "document" in the line "set the_doc to active document".  I'm not very familiar with Applescript but I have opened the scripting dictionary for Microsoft Word in the Applescript editor and I do see "active document" as a property of the "document" object.  So why doesn't the compiler recognize it?  Am I missing something obvious or was there some sort of change in Mavericks that broke this functionality?
    I've been pulling my hair out trying to get this script working again  but I have not had any luck.  I've tried uninstalling and reinstalling Microsoft Office per instructions from Microsoft.  I have all the latest updates and patches. Any help would be greatly appreciated.
    Here is the original code which used to work just fine.
    -- Stephen Norum
    -- [email protected]
    property pdf_ext : ".pdf"
    on remove_extension(file_path)
        -- remove the extension if it exists
        set stripped to do shell script ("F=" & quoted form of file_path & " ; echo ${F%.*}")
        return stripped
    end remove_extension
    on get_pdf_path(doc_path)
        set doc_path to remove_extension(doc_path)
        -- Try the simple name first
        set pdf_path to (doc_path & pdf_ext)
        -- Otherwise, number the pdfs
        set counter to 1
        tell application "Finder"
            repeat while (exists pdf_path)
                set pdf_path to (doc_path & " " & counter & pdf_ext)
                set counter to counter + 1
            end repeat
        end tell
        return pdf_path
    end get_pdf_path
    on run {input, parameters}
        repeat with file_name in input
            tell application "Microsoft Word"
                open file_name
                set the_doc to active document
                set doc_path to path of the_doc
            end tell
            set pdf_path to get_pdf_path(doc_path)
            tell application "Microsoft Word"
                save as active document file name pdf_path file format format PDF
                close active document
            end tell
        end repeat
        tell application "Finder"
            activate
        end tell
        return input
    end run

    try this syntax:
                        tell application "Microsoft Word"
      save as (active document) file name pdf_path file format PDF
                        end tell
    Apparently they changed the enumeration label from format PDF to just plain old PDF without bothering to update the scripting dictionary or ensure backward compatibility. If you want to know how they managed to do that, they are still not using sdef or even scriptSuite xml files, but are loading the scripting information from old-school (i.e. os 8 or os 9 style) resource files.
    I've occasionally considered writing Microsoft a proposal to redo the Office scripting dictionaries so they are less crazy-making, but I'm not sure I'd survive the attempt.

  • Help with Mathscipt and for loop

    I have a code in Mathscript/matlab and I need to output the array out. One option is my first code,the other option is using a for loop, but I am only getting the last ouput out. I need to get the whole output out.
    Any help.
    Thanks
    Solved!
    Go to Solution.
    Attachments:
    Help with Mathscript_for loop.vi ‏115 KB
    Help with Mathscript_for loop2.vi ‏84 KB

    Here's how it should look like.
    Message Edited by altenbach on 10-30-2008 05:12 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    MathscriptInFOR.png ‏15 KB

  • Need help with JTextArea and Scrolling

    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.swing.*;
    public class MORT_RETRY extends JFrame implements ActionListener
    private JPanel keypad;
    private JPanel buttons;
    private JTextField lcdLoanAmt;
    private JTextField lcdInterestRate;
    private JTextField lcdTerm;
    private JTextField lcdMonthlyPmt;
    private JTextArea displayArea;
    private JButton CalculateBtn;
    private JButton ClrBtn;
    private JButton CloseBtn;
    private JButton Amortize;
    private JScrollPane scroll;
    private DecimalFormat calcPattern = new DecimalFormat("$###,###.00");
    private String[] rateTerm = {"", "7years @ 5.35%", "15years @ 5.5%", "30years @ 5.75%"};
    private JComboBox rateTermList;
    double interest[] = {5.35, 5.5, 5.75};
    int term[] = {7, 15, 30};
    double balance, interestAmt, monthlyInterest, monthlyPayment, monPmtInt, monPmtPrin;
    int termInMonths, month, termLoop, monthLoop;
    public MORT_RETRY()
    Container pane = getContentPane();
    lcdLoanAmt = new JTextField();
    lcdMonthlyPmt = new JTextField();
    displayArea = new JTextArea();//DEFINE COMBOBOX AND SCROLL
    rateTermList = new JComboBox(rateTerm);
    scroll = new JScrollPane(displayArea);
    scroll.setSize(600,170);
    scroll.setLocation(150,270);//DEFINE BUTTONS
    CalculateBtn = new JButton("Calculate");
    ClrBtn = new JButton("Clear Fields");
    CloseBtn = new JButton("Close");
    Amortize = new JButton("Amortize");//DEFINE PANEL(S)
    keypad = new JPanel();
    buttons = new JPanel();//DEFINE KEYPAD PANEL LAYOUT
    keypad.setLayout(new GridLayout( 4, 2, 5, 5));//SET CONTROLS ON KEYPAD PANEL
    keypad.add(new JLabel("Loan Amount$ : "));
    keypad.add(lcdLoanAmt);
    keypad.add(new JLabel("Term of loan and Interest Rate: "));
    keypad.add(rateTermList);
    keypad.add(new JLabel("Monthly Payment : "));
    keypad.add(lcdMonthlyPmt);
    lcdMonthlyPmt.setEditable(false);
    keypad.add(new JLabel("Amortize Table:"));
    keypad.add(displayArea);
    displayArea.setEditable(false);//DEFINE BUTTONS PANEL LAYOUT
    buttons.setLayout(new GridLayout( 1, 3, 5, 5));//SET CONTROLS ON BUTTONS PANEL
    buttons.add(CalculateBtn);
    buttons.add(Amortize);
    buttons.add(ClrBtn);
    buttons.add(CloseBtn);//ADD ACTION LISTENER
    CalculateBtn.addActionListener(this);
    ClrBtn.addActionListener(this);
    CloseBtn.addActionListener(this);
    Amortize.addActionListener(this);
    rateTermList.addActionListener(this);//ADD PANELS
    pane.add(keypad, BorderLayout.NORTH);
    pane.add(buttons, BorderLayout.SOUTH);
    pane.add(scroll, BorderLayout.CENTER);
    addWindowListener( new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    public void actionPerformed(ActionEvent e)
    String arg = lcdLoanAmt.getText();
    int combined = Integer.parseInt(arg);
    if (e.getSource() == CalculateBtn)
    try
    JOptionPane.showMessageDialog(null, "Got try here", "Error", JOptionPane.ERROR_MESSAGE);
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Got here", "Error", JOptionPane.ERROR_MESSAGE);
    if ((e.getSource() == CalculateBtn) && (arg != null))
    try{
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 1))
    monthlyInterest = interest[0] / (12 * 100);
    termInMonths = term[0] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 2))
    monthlyInterest = interest[1] / (12 * 100);
    termInMonths = term[1] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 3))
    monthlyInterest = interest[2] / (12 * 100);
    termInMonths = term[2] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Invalid Entry!\nPlease Try Again", "Error", JOptionPane.ERROR_MESSAGE);
    }                    //IF STATEMENTS FOR AMORTIZATION
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 1))
    loopy(7, 5.35);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 2))
    loopy(15, 5.5);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 3))
    loopy(30, 5.75);
    if (e.getSource() == ClrBtn)
    rateTermList.setSelectedIndex(0);
    lcdLoanAmt.setText(null);
    lcdMonthlyPmt.setText(null);
    displayArea.setText(null);
    if (e.getSource() == CloseBtn)
    System.exit(0);
    private void loopy(int lTerm,double lInterest)
    double total, monthly, monthlyrate, monthint, monthprin, balance, lastint, paid;
    int amount, months, termloop, monthloop;
    String lcd2 = lcdLoanAmt.getText();
    amount = Integer.parseInt(lcd2);
    termloop = 1;
    paid = 0.00;
    monthlyrate = lInterest / (12 * 100);
    months = lTerm * 12;
    monthly = amount *(monthlyrate/(1-Math.pow(1+monthlyrate,-months)));
    total = months * monthly;
    balance = amount;
    while (termloop <= lTerm)
    displayArea.setCaretPosition(0);
    displayArea.append("\n");
    displayArea.append("Year " + termloop + " of " + lTerm + ": payments\n");
    displayArea.append("\n");
    displayArea.append("Month\tMonthly\tPrinciple\tInterest\tBalance\n");
    monthloop = 1;
    while (monthloop <= 12)
    monthint = balance * monthlyrate;
    monthprin = monthly - monthint;
    balance -= monthprin;
    paid += monthly;
    displayArea.setCaretPosition(0);
    displayArea.append(monthloop + "\t" + calcPattern.format(monthly) + "\t" + calcPattern.format(monthprin) + "\t");
    displayArea.append(calcPattern.format(monthint) + "\t" + calcPattern.format(balance) + "\n");
    monthloop ++;
    termloop ++;
    public static void main(String args[])
    MORT_RETRY f = new MORT_RETRY();
    f.setTitle("MORTGAGE PAYMENT CALCULATOR");
    f.setBounds(600, 600, 500, 500);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    }need help with displaying the textarea correctly and the scroll bar please.
    Message was edited by:
    new2this2020

    What's the problem you're having ???
    PS.

  • Help with encapsulation and a specific case of design

    Hello all. I have been playing with Java (my first real language and first OOP language) for a couple months now. Right now I am trying to write my first real application, but I want to design it right and I am smashing my head against the wall with my data structure, specifically with encapsulation.
    I go into detail about my app below, but it gets long so for those who don't want to read that far, let me just put these two questions up front:
    1) How do principles of encapsulation change when members are complex objects rather than primitives? If the member objects themselves have only primitive members and show good encapsulation, does it make sense to pass a reference to them? Or does good encapsulation demand that I deep-clone all the way to the bottom of my data structure and pass only cloned objects through my top level accessors? Does the analysis change when the structure gets three or four levels deep? Don't DOM structures built of walkable nodes violate basic principles of encapsulation?
    2) "Encapsulation" is sometimes used to mean no public members, othertimes to mean no public members AND no setter methods. The reasons for the first are obvious, but why go to the extreme of the latter? More importantly HOW do you go to the extreme of the latter? Would an "updatePrices" method that updates encapsulated member prices based on calculations, taking a single argument of say the time of year be considered a "setter" method that violates the stricter vision of encapsulation?
    Even help with just those two questions would be great. For the masochistic, on to my app... The present code is at
    http://www.immortalcoil.org/drake/Code.zip
    The most basic form of the application is statistics driven flash card software for Japanese Kanji (Chinese characters). For those who do not know, these are ideographic characters that represent concepts rather than sounds. There are a few thousand. In abstract terms, my data structure needs to represent the following.
    -  There are a bunch of kanji.
       Each kanji is defined by:
       -  a single character (the kanji itself); and
       -  multiple readings which fall into two categories of "on" and "kun".
          Each reading is defined by:
          -  A string of hiragana or katakana (Japanese phoenetic characters); and
          -  Statistics that I keep to represent knowledge of that reading/kanji pair.Ideally the structure should be extensible. Later I might want to add statistics associated with the character itself rather than individual readings, for example. Right now I am thinking of building a data structure like so:
    -  A Vector that holds:
       -  custom KanjiEntry objects that each hold
          -  a kanji in a primitive char value; and
          -  two (on, kun) arrays or Vectors of custom Reading objects that hold
             -  the reading in a String; and
             -  statistics of some sort, probably in primitive valuesFirst of all, is this approach sensible in the rough outlines?
    Now, I need to be able to do the obvious things... save to and load from file, generate tables and views, and edit values. The quesiton of editting values raises the questions I identified above as (1) and (2). Say I want to pull up a reading, quiz the user on it, and update its statistics based on whether the user got it right or wrong. I could do all this through the KanjiEntry object with a setter method that takes a zillion arguments like:
    theKanjiEntry.setStatistic(
    "on",   // which set of readings
    2,      // which element in that array or Vector
    "score", // which statistic
    98);      // the valueOr I could pass a clone of the Reading object out, work with that, then tell the KanjiEntry to replace the original with my modified clone.
    My instincts balk at the first approach, and a little at the second. Doesn't it make more sense to work with a reference to the Reading object? Or is that bad encapsulation?
    A second point. When running flash cards, I do not care about the subtlties of the structure, like whether a reading is an on or a kun (although this is important when browsing a table representing the entire structure). All I really care about is kanij/reading pairings. And I should be able to quickly poll the Reading objects to see which ones need quizzing the most, based on their statistics. I was thinking of making a nice neat Hashtable with the keys being the kanji characters in Strings (not the KanjiEntry objects) and the values being the Reading objects. The result would be two indeces to the Reading objects... the basic structure and my ad hoc hashtable for runninq quizzes. Then I would just make sure that they stay in sync in terms of the higher level structure (like if a whole new KanjiEntry got added). Is this bad form, or even downright dangerous?
    Apart from good form, the other consideration bouncing around in my head is that if I get all crazy with deep cloning and filling the bottom level guys with instance methods then this puppy is going to get bloated or lag when there are several thousand kanji in memory at once.
    Any help would be appreciated.
    Drake

    Usually by better design. Move methods that use the
    getters inside the class that actually has the data....
    As a basic rule of thumb:
    The one who has the data is the one using it. If
    another class needs that data, wonder what for and
    consider moving that operation away from that class.
    Or move from pull to push: instead of A getting
    something from B, have B give it to A as a method
    call argument.Thanks for the response. I think I see what you are saying.. in my case it is something like this.
    Solution 1 (disfavored):
    public class kanjiDrill{ // a chunk of Swing GUI or something
         public void runDrill(Vector kanjiEntries){
              KanjiEntry currentKanjiEntry = kanjiEntries.elementAt(0); // except really I will pick one randomly
              char theKanji = currentKanjiEntry.getKanji();
              String theReading = currentKanjiEntry.getReading();
              // build and show a flashcard based on theKanji and theReading
              // use a setter to change currentKanji's data based on whether the user answers correctly;
    }Solution 2 (favored):
    public class kanjiDrill{ // a chunk of Swing GUI or something
         public void runDrill(Vector kanjiEntries){
              KanjiEntry currentKanjiEntry = kanjiEntries.elementAt(0); // except really I will pick one randomly
              currentKanji.buildAndShowFlashcard(); // method includes updating stats
    }I can definitely see the advantages to this, but two potential reasons to think hard about it occur to me right away. First, if this process is carried out to a sufficient extreme the objects that hold my data end up sucking in all the functionality of my program and my objects stop resembling natural concepts.
    In your shopping example, say you want to generate price tags for the items. The price tags can be generated with ONLY the raw price, because we do not want the VAT on them. They are simple GIF graphics that have the price printed on a an irregular polygon. Should all that graphics generating code really go into the item objects, or should we just get the price out of the object with a simple getter method and then make the tags?
    My second concern is that the more instance methods I put into my bottom level data objects the bigger they get, and I intend to have thousands of these things in memory. Is there a balance to strike at some point?
    It's not really a setter. Outsiders are not setting
    the items price - it's rather updating its own price
    given an argument. This is exactly how it should be,
    see my above point. A breach of encapsulation would
    be: another object gets the item price, re-calculates
    it using a date it knows, and sets the price again.
    You can see yourself that pushing the date into the
    item's method is much beter than breaching
    encapsulation and getting and setting the price.So the point is not "don't allow access to the members" (which after all you are still doing, albeit less directly) so much as "make sure that any functionality implicated in working with the members is handled within the object," right? Take your shopping example. Say we live in a country where there is no VAT and the app will never be used internationally. Then we would resort to a simple setter/getter scheme, right? Or is the answer that if the object really is pure data are almost so, then it should be turned into a standard java.util collection instead of a custom class?
    Thanks for the help.
    Drake

  • Can anyone help with iPlayer and Sky Mobile?

    Ok, I'm so close to giving up with this useless phone. There are 3 apps on my N97 which give me a constant headache.
    BBC iPlayer
    Sky Mobile*
    YouTube
    *I should point out that I only use Sky Mobile to set recordings on my Sky+. I do not use it for, nor have any desire to use it for actually watching Mobile TV.
    All of these apps work absolutely fine over my home WiFi network. It's when I try to use them over 3G (my Vodafone Live! connection) that I start running in to trouble.
    All 3 give me connection problems, errors, and simply refuse to load half the time when on 3G. I got so annoyed I just did a hard reset the other week, and magically all three started working again. However, now 2 of them are failing me again. YouTube (touch wood) is working fine at the moment, but iPlayer and Sky Mobile just aren't.
    iPlayer sometimes works. But sometimes I get script errors (unable to load content), and sometimes it says something about checking my connection settings. I wouldn't mind but it's not actually possible to access any options for the iPlayer. Even in application settings there are no options you're able to set.
    Sky Mobile simply flat out refuses to work ever on 3G. But it did after I did a hard reset for a couple of weeks, now it just stopped working! It wont even load. It just gives the error message 'Unable to connect to network - please check connection settings" or something along those lines.
    I've tried so many different things. Tried setting my internet connections to 'always ask', tried setting it to default to Vodafone Live! all the time, tried setting my video streaming settings to WAP, all sorts. Every combination I can think of.
    I just can't wait to get rid of this phone. I've put so many people off buying one. They see it and think it's all swish and cool, and I just say 'Don't. You'll regret it'. I can't wait for my contract to be up so I can upgrade to an iPhone now Vodafone have got them.
    Can anyone help with these problems? Thanks in advance, but I don't hold out much hope...

    About iPlayer.
    Have a chat with Vodaphone. Streaming iPlayer over 3G IS allowed on Vodaphone contract, unlike my O2 contract. As long as your contract allows it, and you have the correct AP address, it should be fine. Vodaphone should be able to give you the setting.
    Mine only works over Wlan.
    FWIW, "... streaming over 3G is not currently available on iPhone handsets on any mobile network".
    p.s. Just to be clear. You say  "Tried setting my internet connections to 'always ask', tried setting it to default to Vodafone Live!".
    iPlayer uses the Nokia browser "Web". So that's where you should make the setting "Ask when needed". It should then offer you the choice of whatever you've set in Destinations> Internet> then select whatever you've chosen as your GPRS connection.(as advised, or sent to you by Vodaphone).

Maybe you are looking for

  • I can no longer burn Cd"s

    I have been using my computer for about a year and now the the cd won't burn in itunes. Out of 13-15 songs only the 1st song will burn. I get no message just completed burn. Is there a way to find recommended speed for my dvd ram drive ?

  • ITunes will not open - coregraphics.dll error

    I have a 32-bit Windows 7, and was using iTunes without problems for a bout a year before today. Everytime I try to run iTunes, it gives me an error saying: "C:\Program Files\Common Files\Apple\Apple Application Support\Coregraphics.dll is either not

  • Help with "Admin user requires valid username and password" on fms2_console.swf page

    Just installed FMS2 on Debian (etch, 2.16.5-1 kernel). When I connect to localhost:1111/fms2_console.swf and get the infamous XML output which includes the text, "Admin user requires valid username and password." The *.xml and *.ini files haven't bee

  • Material Group Case Insensitive

    Hi specialists, Is there an easy way to search for material groups in ME21N in a way that the description is not case sensitive (by default, it is case sensitive)? Thanks!

  • Code to embed my video in other sites?

    Hello folks! I will be putting video on my website using iWeb. Simple enough (I hope!) However, I need to be able to provide code to my customers so that they can embed the video into their own website... the same way that YouTube allows you to do th