Friday, May 6, 2011

DateGrid View - As and unBound control

Hi

Trying to use a DataGridView like the old VB6 FlexGrid, and add the coloumns manually via addrow (built a Row containing TextCells) and my Coloums are all added (and display ok) but as soon as I try to add a row I get the message "Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound." But for love nore god can I see a way of setting it as a unbound control (I've not set the datasourc to anything)

So two questions really,

  1. is there a better control to use ?
  2. is there way to set a DataGridView to be an unbound control

And a final third question

  1. How do you add row manually ?

Snippet of how I've done it do far

Thanks in advance

                  Dim lRow As New DataGridViewRow

                    Dim lCell As New DataGridViewTextBoxCell
                    lCell.Value = "Cell 1"
                    lRow.Cells.Add(lCell)

                    lCell = DataGridViewTextBoxCell
                    lCell.Value = "Cell 2"
                    lRow.Cells.Add(lCell)

                    DataGridView1.Rows.Add(lRow)
From stackoverflow
  • Is there a better control to use?

    A bit subjective but I would say no. DataGridview is going to give you the most flexibility for building a grid like structure. It's extremely flexible and almost certainly fit your scenario

    Is there a way to set a DataGridView to be an unbound control

    Yes. Make sure the DataSource property is set to Nothing. This will force it into an unbound mode. As soon as you set this property to anything it will become a bound control

    DataGridView1.DataSource = Nothing ' force unbound
    

    How do you add a row manually?

    Exactly as you've done. Once it's unbound this will work.

    spacemonkeys : Ta, Code was exactly wright but once I'd stopped the datasource issue all feel into place, ta

debugging "register_activation_hook" in WordPress [closed]

Originally posted on the WordPress forums but no-one answered... so I'll try my luck here...

Hi all,

I'm trying to learn to write a WordPress plugin by setting myself a goal of witting a user generated glossary plugin after I asked people on Twitter what would be useful (well I may as well use my learning experience to be useful for more than just me).

Anyway, on installation the plugin sets up a database table, and adds some test data to it. Then when the content is displayed a foreach loop changes each phrase and replaces it with a DHTML floaty box.

The problem is, however, I can't work out what's going on with the register_activation_hook; it may be being called and the SQL is failing or it may not be being called (either way I don't have an extra table in the database after I activate the plugin).

The hook looks like this:

register_activation_hook(__FILE__, "bot_install");

And the bot_install code like this

function bot_install()
{
    global $wpdb;
    $table = $wpdb->prefix."sh_gloss";

    $structure = "CREATE TABLE $table (
        id INT(9) NOT NULL AUTO_INCREMENT,
        phrase VARCHAR(80) NOT NULL,
        desc VARCHAR(255) NOT NULL,
    UNIQUE KEY id (id)
    );";
    $wpdb->query($structure);

    // Populate table
    $wpdb->query("INSERT INTO $table(phrase, desc)
        VALUES('Scott Herbert', 'Rockstar Programmer')");

}

OK so firstly please forgive the ego database entry, it's just for testing...

Secondly is there something I should have seen that I've missed? And thirdly (and most importantly) how can I debug "bot_install"? Can I just add statements like:

echo "in xxxx";

or will that mess up the headers (since I guess all this code is ran before the main output).

Thanks in advance Scott

From stackoverflow
  • I know nothing about WordPress, but...since there is no error handling in the code, how do you know that $wpdb is a valid database connection handle, and how could the code detect that something is not working - for example, the CREATE TABLE statement failed? The code apparently blindly (blithely) assumes nothing can or will go wrong, but my experience is that things can and do go wrong.


    I'm still not the expert, but the URL referenced says:

    Run Any Query on the Database

    The query function allows you to execute any SQL query on the WordPress database. It is best to use a more specific function (see below), however, for SELECT queries.

    <?php $wpdb->query('query'); ?>
    

    query

    (string) The SQL query you wish to execute.

    The function returns an integer corresponding to the number of rows affected/selected. If there is a MySQL error, the function will return FALSE. (Note: since both 0 and FALSE can be returned, make sure you use the correct comparison operator: equality == vs. identicality ===).

    [...]

    Examples

    Delete the 'gargle' meta key and value from Post 13.

       $wpdb->query("
           DELETE FROM $wpdb->postmeta WHERE post_id = '13'
                 AND meta_key = 'gargle'");
    

    So, presumably, if the CREATE TABLE operation fails, you will get a FALSE back from it, which you can test with the appropriate operator - I'm not sure which one it is.

    Further down, on the subject of errors, the page says:

    Show and Hide SQL Errors

    You can turn error echoing on and off with the show_errors and hide_errors, respectively.

    <?php $wpdb->show_errors(); ?>
    <?php $wpdb->hide_errors(); ?>
    

    You can also print the error (if any) generated by the most recent query with print_error.

    <?php $wpdb->print_error(); ?>
    

    Finally, for debugging while under initial development, it won't matter too much if the response is garbled as long as you can see the information.

    Scott Herbert : $wpdb is a global wordpress variable assuming the database exists it poits to it (well a class that handles it as far as I can tell). I agree there's no error handleing, that what I want! the idea behind this project is to learn so I'd rather fix it myself than get someone to tell me whats wrong. But since this function is called before anything is displayed, displaying anything will kill the HTML headers.. So how do I test?
    Scott Herbert : no room to cite links in the orginal comment so... re $wpdb see http://codex.wordpress.org/Function_Reference/wpdb_Class and re the debuging, see the last three paragraphs in the questron. Thanks
    Scott Herbert : OK thanks for the additional points. I'd missed them.
  • I had to deal with this a while back. There is something tricky with register_activation_hook, for some reason running queries did not work for me, use the dbDelta function.

    function bot_install()
    {
        global $wpdb;
        $table = $wpdb->prefix."sh_gloss";
    
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    
        $structure = "CREATE TABLE $table (
            id INT(9) NOT NULL AUTO_INCREMENT,
            phrase VARCHAR(80) NOT NULL,
            desc VARCHAR(255) NOT NULL,
         UNIQUE KEY id (id));";
    
        dbDelta($structure);
    
    
        // Populate table
        $wpdb->query("INSERT INTO $table(phrase, desc)
            VALUES('Scott Herbert', 'Rockstar Programmer')");
    
    }
    

    Let me know if that doesn't work.

Degradable HTML layout for comparing two images

How to create web page for comparing two images, preferably using only (X)HTML and CSS, without JavaScript and DHTML / AJAX?

The simplest solution would be to put two images side by side together, either touching or almost touching and centered both, or each centered in its own half of page. The problem in robust solution is with degradable part.

  • the two images in question doesn't need to have the same size, for example one can be resized version of the other image; one question would be whether to use HTML attributes to scale them to the same visual size, and whether to center two images or align them to center of the page if they have unequal width:

    |_______|_______|
    |___[xx][xxxx]___|
    

    (centered as a whole) vs

    |_______|_______|
    |____[xx][xxxx]__|
    

    (aligned to center of page)

  • the images might be wider than half of the page; I'd rather avoid horizontal scrolling, so perhaps in such case images instead of being side by side would be one above another, and this should be automatic, without using JavaScript to compare width of image with the width of browser window and changing layout on the fly.

    The layout in this case should look roghly like below:

    |____[xxxxxxx]___|
    |_____[xxxxx]____|
    

The goal of this is to have a way to compare images in a web interface for version control system.

From stackoverflow
  • I wouldn't want them scaled to the same visual size in a version control diff system, but you could use:

    <img width='x' height='y'>
    

    to do that (or just specify width if you wanted each image to maintain its aspect ratio).

    To make one fall below the other when they didn't fit horizontally, just float one of them to the left:

    <html><body><p align='center'>
    <img src='http://stackoverflow.com/content/img/so/logo.png' float='left'>
    <img src='http://stackoverflow.com/content/img/so/logo.png'>
    </p></body></html>
    

    (The purists won't like align='center' etc. - please imagine I've done that properly using CSS 8-)

    Mark : Yeah.. floating them will make them appear side by side when they fit, or fall below when they don't. You can use server side technologies (PHP, Python, RoR) if you need more control but are concerned about client-side compatibility.

How do I intercept messages being sent to a window?

I want to intercept messages that are being sent to a window in a different process. What is the best way to do this? I can't see the messages when I use the WH_GETMESSAGE hook, and I'm not sure if I can subclass across processes? Any help would be much appreciated.

From stackoverflow
  • If the message is sent rather than posted WH_GETMESSAGE won't see it. You need WH_CALLWNDPROC. If you're working across processes you'll need a system-wide hook in a DLL. You don't mention how you invoked SetWindowsHookEx, so I don't know if your hooking failed because it wasn't global, or because the message you were looking for was sent.

    If you haven't worked with system-wide hooks before, I have an example of a system-wide hook on my website here. That's a keyboard hook, but the principle is the same.

    Stop me if I'm unintentionally talking down here - your question was so short I can't infer your expertise level. But messing around with hooks does imply some experience...

    Jon Tackabury : Sorry, I should have provided more detail. I did get WH_CALLWNDPROC to read the messages, but I how can I remove the message from the queue using that? I want to prevent some messages from reaching the target window.
    Bob Moore : Then don't pass the message to CallNextHookEx
    Jon Tackabury : It doesn't matter if I call CallNextHookEx or not, the message always reaches the target window. :(
    Bob Moore : From MSDN: "The CallWndProc hook procedure can examine the message, but it cannot modify it. After the hook procedure returns control to the system, the message is passed to the window procedure". That implies that you can prevent the message going to the next hookproc, but not the recipient window. Bummer...
    Bob Moore : It's possible to swallow keystrokes (I've done this), but it looks like you can't swallow a sent message. Sorry it took so long to get around to looking at this, I've been out delivering wedding invitations. No, not _my_ wedding :-)
    Jon Tackabury : Thanks for following up. :) I'll keep hunting for a good solution.
  • You'll need to set a system wide message hook. Here is a tutorial.

  • You need to inject your own code into the process that owns the windows you wish to intercept messages from. Fortunately, SetWindowsHookEx() makes this fairly easy, although you may have a bit of trouble at first if you've only used it for in-process hooking up to now.

    I can recommend two excellent articles on the subject:

    1. Joseph Newcomber's Hooks and DLLs
    2. Robert Kuster's Three Ways to Inject Your Code into Another Process

How to determine if a web application has been installed and set up ?

I am not sure to be enough be by my question... Well i'm developping a CMS in PHP with Zend Framework. I would like to have a nice web gui to install and set up the application after unpacked it somewhere... Some CMS or whatever the application is, offer this way to do by simply entering an 'install url' like 'http://localhost/app/install'

I'd like to do the same but i don't want to let any users to set it up, so i am looking for a way to determine if the application has been set up or no.

Inspired by the pid file in the unix world, i though to do the same with an InstallState file. Writing any boolean value inside and then check could be an idea..

What do you think about that ? Do you have better ideas ?

From stackoverflow
  • You could write a value your database somewhere or simply have the file delete itself after the installation is complete. A lot of software ask users to delete the /install file after it is complete. To force this, you could check if the install directory exists and make the admin delete it before the rest of the script can run.

    Boris Guéry : thanks for your answer but i don't think it's the best ideas since i think my application doesn't have to be dependant of the database. I mean especially for its setup step...
  • Currently a lot of web applications have a config-like file somewhere, where they store stuff like database login info and so on. On a freshly installed application the code might check for existence of config file or some variables in it and if it's not present, redirect to the install script.

    Same script could later refuse to work if the config file is present. Also it's common practice to tell the user to delete the install script / folder after setting up. Some even go lengths to force deletion by not working at all if the files are present.

    There are other ways to do what you want, but I found this to be the most common among open-source web apps.

  • Though I upvoted Sam152's answer, I felt the need to give some further clarification (that just didn't really fit in a comment). The practice I use for these situations is as follows:

    1. Let the user run the installer.
    2. Upon successful completion, generate some form of lock file (many applications just create an 'installer.lock' file, with nothing in it). The presence of this file should stop the user running the installer again.
    3. Prevent the main script from executing (even after a successful setup) until the entire installation directory is removed from the server.

    This provides safeguards on two levels. It prevents the installer being run again (which may or may not be a problem for your application), and it prevents the product being run. You can use the presence of the locking file to tell the user that they've already compleed the install successfully, they don't need to install again, and that they should remove the directory.

    Simple, safe, sorted. :)

    Mark : I don't get why apps don't just delete the install directory automatically? Why force the admin to do extra work?
    James Burgess : That is a possibility - but there are usually two obstacles to this. Either you don't want to force the user to give liberal permissions to the install script itself, or the user is unable to grant them to the install script (due to host set-up, etc). The best compromise is to try to delete automatically, but to tell them to remove it themselves if not... however, many FTP clients simply don't give suitable permissions by default, and many users would be confused by being asked to change these permissions. Best to keep it simple, even if it's not the "shortest" way to do it.
    James Burgess : Of course, the ultimate simplicity would be to put the installer 'in line' with the main application, and then show it the first time... and then create a file or DB entry to say the software is installed. However, this poses a security problem if the DB were to be modified, or the file deleted accidentally, as you then run the risk of displaying the installer to end-users, and that's just asking for trouble. There are other solutions, but they're usually more hassle (for the user, and for the developer) than they're worth.
    Sam152 : Great advice James. +1
    Alix Axel : Installers could use something like this if (exists('install') && writable('install')): delete install else print 'you have to manually delete the install directory'
  • Using Drupal's installation script as an example...

    if ( ! config_file_exists()) {
        tell_user_to_write_config_file();
    } elseif ( ! can_connect_to_db()) {
        tell_user_to_fix_config_file();
    } elseif ( ! check_db_if_installed() ) {
        do_install_stuff();
    } else {
        tell_user_system_installed()
    }
    

    Obviously, the magic happens in do_install_stuff() - in the case of Drupal, it checks for the existance of a row in a settings table (variable) called install_task. As long as that's the last thing written when you do the initial system install, you'd be good to go.

Wordpress Custom Plug (how to call multiple javascript files)

I decided to try to create a plugin that calls forth a couple of javascript files and a css file using the Wordpress Plugin Generator. It is working somewhat - it's calling one of the javascript files but not the other two.

I am using the wp_enqueue_script function, but probably wrong. Any help would be greatly appreciated!

<?php

/*
Plugin Name: Tab Header Code
Plugin URI: [insert the plugin uri here]
Description: Inserts appropriate javascript and css libraries for tabs
Author: Jesse Wallace
Version: 0.1
Author URI: http://www.enticent.com
Generated At: www.wp-fun.co.uk;
*/ 

if (!class_exists('tabstyles')) {
    class tabstyles {

 /**
 * PHP 4 Compatible Constructor
 */

 function tabstyles(){$this->__construct();}

 /**
 * PHP 5 Constructor
 */  

 function __construct(){
 add_action("init", array(&amp;$this,"add_script1"));
 add_action("init", array(&amp;$this,"add_script2"));
 add_action("init", array(&amp;$this,"add_script3"));
 add_action("wp_head", array(&amp;$this,"add_css"));
 }

 /**
 * Tells WordPress to load the scripts
 */

 function add_script1(){
 wp_enqueue_script('tab_header_code_script1', '/wp-content/plugins/tab-header-code/js/tabview-min.js', NULL , 0.1);
 }

 function add_script2(){
 wp_enqueue_script('tab_header_code_script2', '/wp-content/plugins/tab-header-code/js/element-min.js', NULL , 0.1);
 }

 function add_script3(){
 wp_enqueue_script('tab_header_code_script3', '/wp-content/plugins/tab-header-code/js/yahoo-dom-event.js', NULL , 0.1);
 }

 /**
 * Adds a link to the stylesheet to the header
 */

 function add_css(){
 echo '<link rel="stylesheet" href="'.get_bloginfo('wpurl').'/wp-content/plugins/tab-header-code/css/tabstyle.css" type="text/css" media="screen"  />';
 }
}
}

//instantiate the class
if (class_exists('tabstyles')) {
    $tabstyles = new tabstyles();
}

?>
From stackoverflow
  • Hi! I think the correct method should be something like this:

    <?php
    
    if (!class_exists('tabstyles')) {
        class tabstyles {
    
            /**
            * PHP 4 Compatible Constructor
            */
    
            function tabstyles(){$this->__construct();}
    
            /**
            * PHP 5 Constructor
            */              
    
            function __construct(){
                add_action("init", array(&$this,"on_init"));
            }
    
            /**
            * Tells WordPress to load the scripts
            */
    
            function on_init(){
       // scripts
                wp_enqueue_script('tab-view-min', get_bloginfo('wpurl').'/wp-content/plugins/tab-header-code/js/tabview-min.js');
                wp_enqueue_script('element-min', get_bloginfo('wpurl').'/wp-content/plugins/tab-header-code/js/element-min.js');
                wp_enqueue_script('yahoo-dom-event', get_bloginfo('wpurl').'/wp-content/plugins/tab-header-code/js/yahoo-dom-event.js');
    
       //css
                wp_enqueue_style('tabstyle', get_bloginfo('wpurl').'/wp-content/plugins/tab-header-code/css/tabstyle.css');
    
            }
    
        }
    }
    
    //instantiate the class
    if (class_exists('tabstyles')) {
        $tabstyles = new tabstyles();
    }
    

    ?>

    I'm more of a theme developer than plugin developer but I think that you can enqueue everything from just one callback.

    Cheers

    cori : Aye, a single callback should work fine.
  • why not use

    add_action('wp_head', 'insert_head');
    

    then have a insert_js function

    function insert_head() {
        ?>
        <script type="text/javascript" src="<?php bloginfo('wpurl') ?>/wp-content/plugins/tab-header-code/js/tabview-min.js"></script>
        <script type="text/javascript" src="<?php bloginfo('wpurl') ?>/wp-content/plugins/tab-header-code/js/element-min.js"></script>
        <script type="text/javascript" src="<?php bloginfo('wpurl') ?>/wp-content/plugins/tab-header-code/js/yahoo-dom-event.js"></script>
        <link type="text/css" src="<?php bloginfo('wpurl') ?>/wp-content/plugins/tab-header-code/css/tabstyle.csss"></link>
        <?php
    }
    
  • wp_enqueue_script is the right way of doing it. You could do the same thing Scott suggested, but the purpose of wp_enqueue_script is to avoid conflicts, which is something WP automatically handles.

    Are you loading this on the front end or back end?

    If back-end, I highly recommend limiting your JS files to only loading on your plugin pages, here's how you do that:

    add_action('admin_menu', 'add_pages');
    
    function add_pages() {
        $my_plugin_page = add_menu_page('Plugin Name', 'Plugin Name',  8,__FILE__, 'invoice_overview',"images/plugin_icon.png");
    
        // This is the trick, notice the "$my_plugin_page" being tacked on the end of admin_print_scripts
        add_action( "admin_print_scripts-$my_plugin_page", 'admin_head');
    
    }
    
    function admin_head() {
        global $path_to_your_files;
    
        // You may notice array('jquery') at the end, that means jQuery is required to make that particular file function, and WP will include it automatically
        wp_enqueue_script('jquery.whatever',$path_to_your_files . "/js/jquery.whatever.js", array('jquery'));
        wp_enqueue_script('jquery.autocomplete',$path_to_your_files . "/js/jquery.autocomplete.js", array('jquery'));
        wp_enqueue_script('your_custom_file',$path_to_your_files . "/js/your_custom_file.js", array('jquery'));
    
    }
    

    For the front-end its more difficult to isolate your JS files to specific pages. The correct way to insert js files is similar, except I typically load them into the init, just as you did.

    One more thing, be careful using __construct in your PHP code because it doesn't work in PHP4, in case you plan on distributing your plugin, keep in mind some people are still using PHP4.

    Good luck.

Write a Program Which Recognizes a Sound and Performs Action

I would like to write a program which is capable of storing a sound pattern, such as a train whistle, horn (beep beep)...listening for the sound via the microphone...and then taking some action when the sound is heard. I know a little python and have programmed a long time ago in VB. Mainly I am an Oracle, PLSQL guy. The program will require a modest UI.

What is the best solution combination (language, third party add-ons etc..) to tackle this problem?

From stackoverflow
  • Sphinx is a speech recognition system. It may be able to be modified or even trained to work in the way you are expecting.

  • My guess is that the path of least resistance in this case is to use a third-party audio recognition library in combination with a high level language (such as Java or one of the .NET family languages such as C# or VB.NET).

    You can start by doing some research in the areas of Digital Sound Processing and Audio Recognition.

    When you find a library or framework that has the capabilities you're interested in, and bindings in your language of choice, start implementing with it.

    See MARF (a Java library) and maybe Microsoft's work in this area withe the System.Speech.Recognition namespace (which if I remember correctly has been integrated with the newer Windows operating systems)

    EDIT - Desktop vs. Run From Web

    In the comments you asked about using Flash or Silverlight in order for your solution to be able to work both on the Desktop or from the web.

    First off, I would like to point out that both Flash and Silverlight actually run on the client computer. The difference is that they run in the context of a web browser, and that the user doesn't have to install the application. Otherwise they are not much different than a desktop application, and the user obviously has to have the Flash of Silverlight plugin installed for their browser.

    If that's what you're after (i.e. the user to not have to install your application) than you can look into Flash, Silverlight or Java Web Start. Actually JAVA Web Start would probably be a good candidate because you could leverage the MARF framework.

    However if you do decide to go with Flash, Silverlight, or Java Web Start there are some security issues that you might have to deal with because accessing client system resources is bound to require some privileges that most "web-based apps" don't typically require.

  • If you're listening for a particular recording of a horn or a train whistle, that the program knows about beforehand, then it is likely that if the sounds are sufficiently distinctive, you will be able to detect and distinguish between them reliably.

    Classifying a new sound that the program hasn't heard before (as sounding like a horn, or like a train whistle, etc.) is a much harder problem.

    In either case, sound identification algorithms will generally look at the frequency spectrum of recorded sound (see Miky D's link on digital sound processing), and perform some pattern recognition on this data, rather than on the recorded waveform itself.

    As for language and third-party libraries, go for something which allows you to get at the recorded audio data with a minimum of fuss. Java seems good in this respect (see also the Java machine learning algorithm WEKA). While there are programs/libraries around for speech and music analysis, I don't know of one designed for arbitrary sounds, so you may end up having to write the analysis algorithm yourself.

  • Most algorithms I know of use the spectrogram (i.e. the spectum vs. time) for distinguishing sounds. How hard this problem will be can be estimated by how different your spectrograms look.

    An aspect of your sounds that might make them easier to distinguish from speech is that they will likely have clear harmonic structure (i.e. look more like the violin than the voice in the wikipedia link). This harmonic structure can be super useful in distinguishing sounds, and could be helpful in your problem. This brings to mind another place to look: there's a lot of work in distinguishing bird songs, which have clear harmonic structure, and many published algorithms, though I don't know of free software that can be extended to your needs. Still, it might be useful to use birdsong analysis software to just take a look at your sound files. See the Raven project, for example, though there are many other free spectrogram packages.