Set string to clipboard

Hi,
Photoshop JSX noob here.
I want to do a very basic thing: copy a selection rectangle as text.
Ideally if I can get the location of the mouse and copy it to the clipboard, that would be great,
but bounds is ok as well.
I've managed to output selection coordinates:
$.writeln(app.activeDocument.selection.bounds);
how can I get those coordinates copied into the system clipboard ?
note: I am using osx 10.5.8.

Christof, this is related to another post 'Brush Opacity on the mac' but as you have CS4 would you be kind enough to test this…
#target photoshop
// Must be Foremost to accept the key commands
app.bringToFront();
// If you have the brush tool selected
// This should keystroke 'enter'
var sh = app.system("osascript -e 'tell application \"System Events\" to keystroke (ASCII character 3)'");
sh ? alert('Failed?') : alert('Done…');
// This should keystroke string value '36'
var sh = app.system("osascript -e 'tell application \"System Events\" to keystroke \"36\"'");
sh ? alert('Failed?') : alert('Done…');
// This should keystroke 'tab'
var sh = app.system("osascript -e 'tell application \"System Events\" to keystroke tab'");
sh ? alert('Failed?') : alert('Done…');
// This should keystroke string value '64'
var sh = app.system("osascript -e 'tell application \"System Events\" to keystroke \"64\"'");
sh ? alert('Failed?') : alert('Done…');
// This should keystroke 'enter' again
var sh = app.system("osascript -e 'tell application \"System Events\" to keystroke (ASCII character 3)'");
sh ? alert('Failed?') : alert('Done…');
You can comment out the dialog stuff. This all works as AppleScript without issue but someone wanted to know if there was a mac workaround with JavaScript…

Similar Messages

  • Unable to set string in prepared statement

    Hi all,
    I just want to set an string to a prepared stmt.
    the setting string is in the format..... the integers with comma saparated....
    str="23,55,22"
    ps.setString(1,str)
    The prepare statement is taking only the first integer... i.e. 23
    can any one help me out..........
    thanks in advance,
    prakhyath

    if i am not mistaken.... If I create the Prepared
    Statement after receiving the arguments that are to
    be provided to it.... the actual purpose.. Of using
    a prepared statement is not served at all....Not creating a new Statement each time, is only one of the purposes of PreparedStatement. In this case, since the arguments should be ints (and I hope you are checking that), then it doesn't make much of a difference. But a PreparedStatement is alos used to easily facilitate the proper quoting and escaping of the parameters set, which almost eliminates any chance of an SQL injection attack. There are also a few other convienences associated with a PreparedStatement, but, in this case, you are probabyl right in that there is no advantage of PreparedStatement over Statement (as long as you are checking that the arguments provided are actually ints, otherwise you are opening yourself up to an injection attack).

  • Set String keySet = props.keySet() not compiled, can someone explain why?

    I just ran into a problem with javac, this code compiles fine in jdeveloper 10.1.3 but doesn't compile with the javac task in Ant 1.6.5
    Compiling these 2 lines
    Properties props = new Properties();
    Set<String> keySet2 = props.keySet();
    results in this error.
    incompatible types
    [javac] found : java.util.Set<java.lang.Object>
    [javac] required: java.util.Set<java.lang.String>
    [javac] Set<String> keySet2 = props.keySet();
    Given the assignment context, why can't the compiler infer that the Set returns by keySet is a Set<String>?
    However, casting p to a Map before calling keySet() compiles fine.
    Properties props = new Properties();
    Set<String> keySet2 = ((Map)props).keySet();
    This is really weird. Could it be just a bug in the javac implementation that comes with Ant? I'm wondering if there's some fundamental about generics that I'm missing. Can anyone shed some light on this?
    Edited by: 982572 on Jan 17, 2013 12:25 PM

    Ah, thanks. I think that answers some of what I didn't get. The part about discarding the generic information makes sense.
    There's something else I'm not understanding.
    Consider this line of code
    Set<String> keySet2 = (Set<String>)props.keySet();
    JDeveloper 10.1.3.3. for some reason is able to compile this code (it's using jdk 1.5.0_06).
    I tried the same code in Eclipse with jdk 1.6.0_26 and it doesn't compile.
    I believe the latter is correct. Set<String> and Set<Object> aren't related so the compiler shouldn't have allowed a cast from one to the other ... but somehow the code is compiling in JDeveloper 10.1.3.3. This is really throwing me off ...
    What's also really weird is that JDeveloper can't compile this line
    Set<String> keySet2 = props.keySet();
    but to me this is pretty much identical to
    Set<String> keySet2 = (Set<String>)props.keySet(); // although it's an explicit cast
    and JDeveloper can compile this fine ...
    So anyway, if props.keySet() returns Set<Object> and at compile time the compiler doesn't allow casting to Set<String>, how would I go about putting everything in the Set<Object> returned by keySet() into a Set<String>? I know I can iterate through the Set<Object> returned and then just add each String to Set<String>.
    This would work,
    Set<? super String> keySet = props.keySet();
    but then it's not really accurate ... even though Object is the only ancestor of the String class, the <? super String> bound suggests that one can put something other than String into keySet and operate on the elements as though they are String, which is not the correct message to convey.
    I wonder why Properties doesn't extend Hashtable<String,String> ... but there's probably a reason and given that it extends Hashtable<Object, Object> instead, is there no way to assign the return value of Properties.keySet() to a Set<String> by using some Java generic notation/syntax?
    I know this would work as well, but that's just discarding the generic information in the first place
    Set<String> keySet = (Set<String>)(Set)props.keySet();
    I suppose going back to the iterator is the only way to basically copy props.keySet() into a Set<String>?
    Edited by: 982572 on Jan 17, 2013 1:56 PM
    Edited by: 982572 on Jan 17, 2013 2:19 PM
    Edited by: 982572 on Jan 17, 2013 2:37 PM
    Edited by: 982572 on Jan 17, 2013 2:38 PM
    Edited by: 982572 on Jan 17, 2013 2:42 PM

  • (Class ? extends Set String ) Class.forName("example.SetImpl").asSubclass

    Is there a way to do the following without an Unchecked cast?
    Class<? extends Set<String>> clazz;
    clazz = (Class<? extends Set<String>>) Class.forName("example.SetImpl").asSubclass(Set.class);
    Set<String> mySet = clazz.newInstance();
    cheers,
    reto

    No. The last line will always generate that warning making the second line pointless. There is no way to create a new instance of a generic class because there is (for most intents and purposes) no such thing as a generic class at runtime.

  • How to copy string to clipboard w/o keystroke?

    I want to copy short strings into another program.
    Currently I write to a String Indicator, highlight with the mouse, then copy.
    Is there a way to write the string directly to the OS's clipboard?

    You could also try this attachment
    Joe.
    "NOTHING IS EVER EASY"
    Attachments:
    clipboard.llb ‏61 KB

  • Error 1082 when setting Strings[] property of a menu ring control via property node.

    I've attached a VI in which I attempt to set the Strings[] property of a menu ring control via a property node.  Can anybody figure out what I'm doing wrong here?  I'm using LabView version 7.1.
    Thanks,
    Mark Moss
    Attachments:
    Bug Test.llb ‏69 KB

    Open up your Stations Parameters Control.ctl file and change it from a Strict Type Def. to just an ordinary Type Def. (the pull down menu is located next to the font selector).

  • Copy String to Clipboard

    Can this be done? In a simple way? It's not very important, but if i could do it it would be fairly helpful...

         try {
              BufferedReader read = new BufferedReader(new FileReader("SecretMessage.txt"));
              String readMessage = read.readLine();
              StringSelection ss = new StringSelection(readMessage);
              Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, ss);
              JOptionPane.showMessageDialog(null,"Your Encoded//Decoded Message is:\n\n" + readMessage + "\n\nMessage has also been copied to the clipboard.\nPress \"CTRL+V\" to paste this message.");
              read.close();
         catch (IOException e) {}Gives me:
    SecretMessage.java:173: cannot find symbol
    symbol : class StringSelection
    location: class SecretMessage
              StringSelection ss = new StringSelection(readMessage);
              ^
    SecretMessage.java:173: cannot find symbol
    symbol : class StringSelection
    location: class SecretMessage
              StringSelection ss = new StringSelection(readMessage);
              ^
    SecretMessage.java:174: cannot find symbol
    symbol : variable Toolkit
    location: class SecretMessage
              Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, ss);
              ^
    Am I missing some packages or something?

  • Set string control: error1 invoke node

    Hello all,
               I'm trying to set the string control values  from the gethisto.vi into sd.vi. I come across the error: error 1 invode node. I'm not sure what I'm doing wrong though all the data types are the same. Please advise.
    thanks.
    Attachments:
    Get_histo.vi ‏43 KB
    SD.vi ‏103 KB

    Hi gsajja,
    so you start a subVI with a while loop set to run forever and then you use vi server to stop that subVI???
    You use vi server to set inputs of the subVI and also to read the result of a calculation???
    Why not bundle all inputs in a cluster (typedef'ed of course), wire that cluster to SD.vi and connect the "left std" to the connector pane of SD.vi to output the result? Why not get rid of the while loop?
    Does the user need to see SD.vi or is it ok to run in background? From it's front panel look I would guess the user doesn't need to see it
    Btw. where exactly do you get this error?
    Message Edited by GerdW on 02-10-2010 06:45 PM
    Message Edited by GerdW on 02-10-2010 06:47 PM
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Set clipboard content using html text

    Hi,
    I have a html text store in a string variable as mentioned below. I want to set this to the clipboard. But when I set this to clipboard I get the same HTML text and not a readable one.
    private
    var str:String
    = "SALE&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;22&amp;nbsp;&amp;nbsp;&amp;nbsp;CASH040&amp;nbsp;07:26&amp;nbsp;AM";
    I tried to create a text area and set clipboard content from that but I am getting an error "TypeError: Error #2007: Parameter text must be non-null."
    I tried like
    var textArea:TextArea = new TextArea();
    textArea.htmlText = str;
    System.setClipboard(textArea.text);
    Kindly help me in resolving this.
    I want to set the readable text to clipboard and not the html text
    Thanks,
    Tamil

    Hi,
    I have a html text store in a string variable as mentioned below. I want to set this to the clipboard. But when I set this to clipboard I get the same HTML text and not a readable one.
    private
    var str:String
    = "SALE&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;22&amp;nbsp;&amp;nbsp;&amp;nbsp;CASH040&amp;nbsp;07:26&amp;nbsp;AM";
    I tried to create a text area and set clipboard content from that but I am getting an error "TypeError: Error #2007: Parameter text must be non-null."
    I tried like
    var textArea:TextArea = new TextArea();
    textArea.htmlText = str;
    System.setClipboard(textArea.text);
    Kindly help me in resolving this.
    I want to set the readable text to clipboard and not the html text
    Thanks,
    Tamil

  • Problem in setting vector or string[] as the "value object" in hashmap

    Hey I am new to this forum.
    I am doing a project in which i need to store a array of strings as "value object" for a unique key in hashmap.
    as I populate the hashmap from external file according to key and setting the string[]. The hashmap is taking the value field same for each entry i.e the last field as i keep updating the same variable and then putting it into hashmap.
    Please give solution to my problem???
    if question not clear,please tell me- i will add more information
    Edited by: AnkitNahar on Apr 4, 2009 8:06 AM

    I tried using the method suggested by you...but it is of same case as using the string[].
    I need to loop the statements in which the hashmap is populating so cant change the variable names in the dd.put() statements. When the below code executes it shows the same set of string for both the keys, that was the problem i was facing with string[].
    here is the example with two entries....same thing in looping.
    HashMap<String,Set<String>> dd=new HashMap<String,Set<String>>();
    String word = "Hello";
    Set<String> alternativeWords = new HashSet<String>();
    alternativeWords.add("Hi");
    alternativeWords.add("Yo");
    dd.put(word, alternativeWords);
    alternativeWords.clear();
    alternativeWords.add("hey");
    word="yep";
    dd.put(word,alternativeWords);
    System.out.println(dd.get("Hello").toString());
    System.out.println(dd.get("yep").toString());

  • Using sets with Strings

    Hello, I'm in a dilemma here
    I'm using a Set to store Strings:
    private Set<String> X;
    I have a class that receives a String and first check if the string is allready on the set and if not it adds it:
    public boolean method (V e) {
    if(X.contains(e.getString()) )
    return false;
    Y.add(e.getString());
    return true;
    So I got confussed when looking at the properties of a Set, (i.e. do I need to check if the string is allready there, or it'll do it for me?)
    and if I have to check it myself can I use .contains() to compare the given string to all strings in the set?
    Thanks
    Edited by: edsc86 on Nov 18, 2008 7:03 PM
    Edited by: edsc86 on Nov 18, 2008 7:04 PM
    Edited by: edsc86 on Nov 18, 2008 7:05 PM

    Dude! Do NOT screw around with the colors like that. It makes you post way hard to read. Use the CODE button or [[code] and [[/code] tags for sections of code, and an occasional italic or bold for emphasis, and the quote button or a > for quoting.
    You don't need to check if it's there. Read the docs for Set. They tell you that it will add it if it's not there, and return true if the set was modified (that is, if it wasn't already there).
    Set<String> set = new HashSet<String>();
    boolean b1 = set.add("x"); // adds x, returns true
    boolean b2 = set.add("x"); // does nothing to the set, returns false

  • Issue Using C# to Get RTF Text From Clipboard to Outlook With Formatting and Without Encoding Tags

    I have created a little application that gathers data from various text boxes and then combines the data into a formatted richTextBox.  A person using the tool asked if I could then add a button that would allow that text (with formatting) to be copied
    and pasted into an Outlook Email.  When I do this, I can get the text into an email, but I either strip out the formatting or I get all the RTF encoding tags to come along with it. 
    I have tested to see that the copy of the data from the richTextBox has indeed made it to the clipboard correctly.  This has been verified by the fact that I can manually press "ctrl" + "v" and I can past the text with proper
    formatting into the mail body.
    I do know that I can brute force things by trying to manually wrap HTML tags around my textBox fields and then pipe that into an HTMLBody property.  In fact I can get a lot of things to work with the HTMLBody property, but while it is nice that will
    work, I feel that I must be missing something really simple while trying to work with RTF.
    I currently am pasting (using the Clipboard.GetText(TestDataFormat.RTF)) the RTF data into the Body property of the mail item.  This is bringing in all the RTF encoding tags.  I have tried to paste this directly into the RTFBody of the mail item,
    yet an execption gets thrown when executed.  Oddly, though, if I change RTFBody to HTMLBody, I do not get the exception, but I still have the RTF encoding tags in it.  Though if I feed the HTMLBody property straight, HTML text with the encoding tags,
    it will render properly.
    This has me confused then why if I feed HTMLBody HTML text with the encoding tags that it will render, but if I try and do the same for RTFBody and feed it RTF text with encoding tags it still throws an exception.  Any help in the matter would be greatly
    appreciated.  I have included the code snippet below for sending the richTextBox information to the clipboard and then attempting to retrieve it and paste it into an Outlook email.
    Thanks for the help.
    Some pertinent information:
    Blend for Visual Studio 2015 CTP6 (I switched from VS2012 as intellisense was added to Blend in 2015)
    Because of this Systems.Windows.Forms is not in use
    private void buttonEmail_Click(object sender, RoutedEventArgs e)
    //Copy richTextBox information to Clipboard
    Clipboard.Clear();
    richTextBox.SelectAll();
    richTextBox.Copy();
    //Get current date to add to email subject line
    DateTime myNewDate = new DateTime();
    myNewDate = DateTime.Now;
    //Create Email
    Outlook.Application myNewApplication = new Outlook.Application();
    Outlook.MailItem myNewMailIoI = myNewApplication.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
    myNewMailIoI.To = " "; //An attempt to ensure that the focus moves down to the body field
    myNewMailIoI.Subject = "IoI - " + myNewDate.Date.ToString("d");
    myNewMailIoI.BodyFormat = Outlook.OlBodyFormat.olFormatRichText;
    //Pasting data into body of email
    myNewMailIoI.Body = Clipboard.GetText(TextDataFormat.Rtf); //This will past the text with encoding tags into email
    //If this section is uncommented, it will add a properly formatted HTML text to the email
    //myNewMailIoI.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
    //myNewMailIoI.HTMLBody = "<p>This stinks!!!</p>" + "<p style='color: green; font-size:10pt; font-family:arial'>different font and color</p>";
    myNewMailIoI.Display(); //Allow for window to be minimized
    myNewMailIoI.Display(true);

    Ok, I found the solution.  Part of the issue was caused by the confusion of the HTML body property acting as a text encoder for HTML text when a string is passed in vs the RTF Body property needing to have a plain text file taken and encoded into a
    byte stream.  Even though the RTF text is in readable text (albeit with the RTF Encoding Tags) it needs to be reencoded into a series of bytes. 
    This is where I failed to understand the previous answers.  I knew that RTF Body needed to have a array of bytes, and the previous answers seemed to indicate that the data in the clipboard was already in this byte format (this may have just been my
    misunderstanding) and that I needed to somehow take this byte array and do something with it.  My misunderstanding was that all the methods for getting values from the clipboard returned strings and not bytes.
    after some digging last night and with the few hints that were offered before, I came across a post on CodeProject (apparently I cannot post links, so I will try and include this so that you can find the postcodeproject(DOTCOM)/Questions/766917/How-to-convert-richtextbox-output-into-bytearray). 
    This showed that I needed to take the raw, RTF text with its RTF encoding tags from the clipboard and and encode it to a byte array and then pass this into the RTF Body property.  Included below is the final code such that I hope that it helps some other
    person as there seem to be a lot of searches for this on the web, but not a lot of direct answers.
    using System.Text;
    using Outlook = Microsoft.Office.Interop.Outlook;
    private void buttonEmail_Click(object sender, RoutedEventArgs e)
    //Copy richTextBox information to Clipboard
    Clipboard.Clear();
    richTextBox.SelectAll();
    richTextBox.Copy();
    //Get current date to add to email subject line
    DateTime myNewDate = new DateTime();
    myNewDate = DateTime.Now;
    //Create Email
    Outlook.Application myNewApplication = new Outlook.Application();
    Outlook.MailItem myNewMailIoI = myNewApplication.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
    //Add Subject
    myNewMailIoI.Subject = "IoI - " + myNewDate.Date.ToString("d");
    //Set Body Format to RTF
    myNewMailIoI.BodyFormat = Outlook.OlBodyFormat.olFormatRichText;
    //Converting RAW RTF data from string to bytes. THIS IS THE FIX THAT WAS NEEDED TO MAKE IT WORK
    string myNewText = Clipboard.GetText(TextDataFormat.Rtf);
    byte[] myNewRtfBytes = Encoding.UTF8.GetBytes(myNewText); //This line cost me way too many hours of lost sleep!!!
    //Inserting RTF bytes into RTFBody property
    myNewMailIoI.RTFBody = myNewRtfBytes;
    myNewMailIoI.Display(); //Displays the newlycreated email
    //If this section is uncommented, it will add a properly formatted HTML text to the email
    //myNewMailIoI.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
    //myNewMailIoI.HTMLBody = "<p>This works for the HTMLbody property!!!</p>" + "<p style='color: green; font-size:10pt; font-family:arial'>this renders properly</p>";

  • Copying BufferedImage to clipboard fails

    The clipboard is giving me some trouble... If I copy an image selection with transparency data and then create a BufferedImage from the clipboard contents (paste), then everything works fine everywhere. However if I have a BufferedImage with transparency data that I want to SET to the clipboard (copy) then I observe two different behaviors between Ubuntu and Windows XP -- both incorrect.
    On Ubuntu:
    getTransferDataFlavors of my Transferable is called once. isDataFlavorSupported and getTransferData are never called. The clipboard is unaltered. No exception is thrown -- nothing. It just silently fails to do anything. Calling Toolkit.getDefaultToolkit().getSystemClipboard().getAvailableDataFlavors() shows me that DataFlavor.imageFlavor is indeed present.
    On Windows:
    My getTransferData is indeed called and the clipboard is modified. However, the image is set on a BLACK background -- the transparency data is lost.
    Relevant code portions look like:
    btnCopy.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        CopyableImage img = new CopyableImage(frame.getImage());
                        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(img, null);
              });Where frame.getImage is a BufferedImage of type ARGB, with a transparent background
    private static class CopyableImage implements Transferable {
            private BufferedImage image;
            public CopyableImage(BufferedImage image) {
                this.image = image;
            // Returns supported flavors
            public DataFlavor[] getTransferDataFlavors() {
                return new DataFlavor[]{DataFlavor.imageFlavor};
            // Returns true if flavor is supported
            public boolean isDataFlavorSupported(DataFlavor flavor) {
                return DataFlavor.imageFlavor.equals(DataFlavor.imageFlavor);
            // Returns image
            public BufferedImage getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
                if (!DataFlavor.imageFlavor.equals(flavor)) {
                    throw new UnsupportedFlavorException(flavor);
                return image;
        }Any ideas...?
    Additional Notes:
    I'm am running Java 1.6
    My paste destination is in GIMP, on a new image with transparent background.
    Edited by: MichaelDGagnon on Dec 14, 2008 11:18 AM

    A fully self contained example which continues to replicate the problems observed for me is as follows. Paste works (slowly) and copy fails
    import java.io.IOException;
    import java.net.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.imageio.*;
    import java.awt.datatransfer.*;
    public class CopyTest extends JPanel{
         public static void main(String args[]) throws Exception{
              final CopyTest copyTest = new CopyTest();
              JFrame f = new JFrame();
              f.addWindowListener(new WindowListener(){
                   public void windowClosed(WindowEvent e){}
                   public void windowClosing(WindowEvent e){ System.exit(0); }
                   public void windowIconified(WindowEvent e){}
                   public void windowDeiconified(WindowEvent e){}
                   public void windowActivated(WindowEvent e){}
                   public void windowDeactivated(WindowEvent e){}
                   public void windowOpened(WindowEvent e){}
              f.setLayout(new BorderLayout());
              JButton btnCopy = new JButton("Copy");
              JButton btnPaste = new JButton("Paste");
              JPanel southPanel = new JPanel();
              southPanel.add(btnCopy);
              southPanel.add(btnPaste);
              f.add(copyTest, BorderLayout.CENTER);
              f.add(southPanel, BorderLayout.SOUTH);
              btnCopy.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){ copyTest.copy(); }
              btnPaste.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){ copyTest.paste(); }
              f.setSize(320, 240);
              f.setVisible(true);
         private static final int SQUARE_SIZE=6;
         private BufferedImage image;
         // Constructor
         public CopyTest() throws Exception{
              this.image = ImageIO.read(new URL("http://forums.sun.com/im/duke.gif"));
         // Copy
         public void copy(){
              Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
                        new Transferable(){
                             public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[]{DataFlavor.imageFlavor}; }
                             public boolean isDataFlavorSupported(DataFlavor flavor) { return DataFlavor.imageFlavor.equals(DataFlavor.imageFlavor); }
                             public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
                               if(!DataFlavor.imageFlavor.equals(flavor)){ throw new UnsupportedFlavorException(flavor); }
                               return image;
                        , null);
         // Paste
         public void paste(){
              // Get the contents
              BufferedImage clipboard = null;
              Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
              try {
                if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
                     clipboard = (BufferedImage)t.getTransferData(DataFlavor.imageFlavor);
            } catch (Exception e) { e.printStackTrace(); }
            // Use the contents
            if(clipboard != null){
                   image = clipboard;
                   repaint();
         // Paint
         public void paint(Graphics g){
              // Paint squares in the background to accent transparency
              g.setColor(Color.LIGHT_GRAY);
              g.fillRect(0, 0, getWidth(), getHeight());
              g.setColor(Color.DARK_GRAY);
              for(int x=0; x<(getWidth()/SQUARE_SIZE)+1; x=x+1){
                   for(int y=0; y<(getHeight()/SQUARE_SIZE)+1; y=y+1){
                        if(x%2 == y%2){ g.fillRect(x*SQUARE_SIZE, y*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE); }
              // Paint the image
              g.drawImage(image, 0, 0, this);
    }

  • What's the best way to do this (searching inside strings)

    Hello. I am trying to do something pretty trivial but the way I've set out to do it seems overly complicated and I bet there's a much easier more efficient way of doing it.
    Basically I want to parse a string which is fairly small in size but contains many line breaks. Take the following text for exemple :
    ====
    Session 4042312
    Room 1 is the active room
    Total number of friends : 2
    Room 1: Bariachi ( away )
    Room 2: Concaveman ( busy )
    ====
    This whole text, in it's above form, is copied into my string. The way I do that is simply copy it and then read it from the clipboard as such :
    public String getClipboard()
      Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
      try
         currentText = (String)c.getContents(this).getTransferData(DataFlavor.stringFlavor);
      catch(Exception e)
      currentText = "empty";
      System.out.print(currentHand);
      return currentText ;
      } once this is done, I want to be able to parse the string in order to retrieve, as in the above exemple, the session number. the number of friends and the names.
    So here what I want to do but I don't know exactly how :
    search for "Session "
    sessionNumber = copydown untill next line break
    search for "friends : "
    noFriends = copydown numerical characters untill you hit a character that's not numerical
    search for "Room %: "
    name1 = copydown untill next space character
    search for next "Room %: "
    name1 = copydown untill next space character
    I don't know wether it's possible to use wildcards (like in "Room %: ") when searching for a substring but I assume it must be, I just don't know how. Is it also possible to tell java to "copy down X following numerical characters and to stop when the next character isn't numerical"
    also when searching for substrings.. does it always start from the top? or can you tell it to just continue on from where it last stopped?

    If this is to submit as homework then the prof. will probably not accept my solution and if he does then you will have to justify the result so ...
    import java.util.regex.*;
    public class Fred800
        public static void main(String[] args)
            try
                String record = "====\n" +
                        "Session 4042312\n" +
                        "Room 1 is the active room\n" +
                        "Total number of friends : 2\n" +
                        "Room 1: Bariachi ( away )\n" +
                        "Room 2: Concaveman ( busy )\n" +
                        "====\n";
                Pattern sessionExtractPattern = Pattern.compile("Session +([^\\s]+)");
                Matcher sessionExtractMatcher = sessionExtractPattern.matcher(record);
                int currentPosition = 0;
                if (sessionExtractMatcher.find(currentPosition))
                    System.out.println("Session\t" + sessionExtractMatcher.group(1));
                    currentPosition = sessionExtractMatcher.end(1);
                Pattern countExtractPattern = Pattern.compile("Total number of friends : +([^\\s]+)");
                Matcher countExtractMatcher = countExtractPattern.matcher(record);
                if (countExtractMatcher.find(currentPosition))
                    System.out.println("Count\t" + countExtractMatcher.group(1));
                    currentPosition = countExtractMatcher.end(1);
                Pattern namesExtractPattern = Pattern.compile("Room +(\\d+): +([^ ]+)");
                Matcher namesExtractMatcher = namesExtractPattern.matcher(record);
                while (namesExtractMatcher.find(currentPosition))
                    System.out.println(namesExtractMatcher.group(2) + "\t" + namesExtractMatcher.group(1));
                    currentPosition = namesExtractMatcher.end(2);
            catch (Exception e)
                e.printStackTrace();
    }

  • SSRS Report Returning Double Quote string from a Single Quote String

    Hi, I'm getting weird thing in resultset from SSRS report when executed. When I pass parameter to a report, which passes String that has single quote value to a split function , it returns rows with double quote. 
    For example  following string:
    'N gage, Wash 'n Curl,Murray's, Don't-B-Bald
    Returns: 
    ''N gage, Wash ''n Curl,Murray''s, Don''t-B-Bald
    through SSRS report.
    Here is the split function Im using in a report.
    CREATE Function [dbo].[fnSplit] (
    @List varchar(8000), 
    @Delimiter char(1)
    Returns @Temp1 Table (
    ItemId int Identity(1, 1) NOT NULL PRIMARY KEY , 
    Item varchar(8000) NULL 
    As 
    Begin 
    Declare @item varchar(4000), 
    @iPos int 
    Set @Delimiter = ISNULL(@Delimiter, ';' ) 
    Set @List = RTrim(LTrim(@List)) 
    -- check for final delimiter 
    If Right( @List, 1 ) <> @Delimiter -- append final delimiter 
    Select @List = @List + @Delimiter -- get position of first element 
    Select @iPos = Charindex( @Delimiter, @List, 1 ) 
    While @iPos > 0 
    Begin 
    -- get item 
    Select @item = LTrim( RTrim( Substring( @List, 1, @iPos -1 ) ) ) 
    If @@ERROR <> 0 Break -- remove item form list 
    Select @List = Substring( @List, @iPos + 1, Len(@List) - @iPos + 1 ) 
    If @@ERROR <> 0 Break -- insert item 
    Insert @Temp1 Values( @item ) If @@ERROR <> 0 Break 
    -- get position pf next item 
    Select @iPos = Charindex( @Delimiter, @List, 1 ) 
    If @@ERROR <> 0 Break 
    End 
    Return 
    End
    FYI: I'm getting @List value from a table and passing it as a string to split function. 
    Any help would be appreciated!
    ZK

    Another user from TSQL forum posted this code which is returning the same resultset but when I execute both codes in SQL server it works and return single quote as expected.
    https://social.msdn.microsoft.com/Forums/sqlserver/en-US/8d5c96f5-c498-4f43-b2fb-284b0e83b205/passing-string-which-has-single-quote-rowvalue-to-a-function-returns-double-quoate?forum=transactsql
    CREATE FUNCTION dbo.splitter(@string VARCHAR(MAX), @delim CHAR(1))
    RETURNS @result TABLE (id INT IDENTITY, value VARCHAR(MAX))
    AS
    BEGIN
    WHILE CHARINDEX(@delim,@string) > 0
    BEGIN
    INSERT INTO @result (value) VALUES (LEFT(@string,CHARINDEX(@delim,@string)-1))
    SET @string = RIGHT(@string,LEN(@string)-CHARINDEX(@delim,@string))
    END
    INSERT INTO @result (value) VALUES (@string)
    RETURN
    END
    GO
    ZK

Maybe you are looking for

  • How to handle Dynamic Fiscal calendar

    Hi FolksWe have designed our cubes in such a way that the time dimension is actually split into 2 time dimensions "Fiscal Year" and "Fiscal Time". The "Fiscal Time" changes every four years, in that, it has an extra week. So usually the Month Februar

  • In iPhoto, the thumbnails do not match the real photo, they repeat often the same 15 photos over and over

    My iPhoto 9.3.2 (670..63) in Mountain Lion is repeating a grouping of thummnails whose photos when you click do not match.  I have called Apple Care and have reinstalled a new iPhoto library and still have the problem.  We did al this after the updat

  • Using iPhone 4 with my car radio

    I have a car radio which can connect to the standard iPhone (or iPod or iPad) connector/charger port and the music from the device can then be played through the car speakers. The tracks and playlists are listed on the radio and you control the devic

  • Starting Xnest on Solaris 10 Sparc

    I cannot get an Xnest server to start under CDE or java/gnome on a Sun Blade running Solaris 10. I keep getting errors related like: Fatal server error: Failed to establish all listening sockets My $DISPLAY is :0.0 I have tried many commands includin

  • Update PA0008 in sap abap hr

    Hi Experts, I want to update the existing record in table PA0008. In table, for one existing pernr, it has wage types(LGA01). I want to add one or two wage for that existing pernr without effecting the  existing wage type and other values. How to get