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.

SQL Server 2008 Reporting Services permissions

I'm having trouble with SQL Server 2008 (Express with Advanced Services) Reporting Services permissions. I'm running this on Vista Ultimate at home - standalone machine with no servers, no domain or active directory.

When I go to the ReportServices site, I get this:

The permissions granted to user 'localmachine\Scott' are insufficient for performing this operation. (rsAccessDenied)

I don't remember having a problem at the office with SQL Standard on Windows 2008.

From stackoverflow
  • Try running IE as admin and then going to the page. Then under settings add your user and give it permissions. You should be able to run IE not as admin after that. This worked for me using SSRS 2005 under vista.

    If not that, then check which user account the service is running as.

    See the MSDN page about How to Configure Reporting Services on Vista and Server 2008

    ScottStonehouse : Strange. I had already tried logging in as administrator, but that didn't work. Running IE as admin did work. Is this documented?
    ScottStonehouse : Found the documentation: http://technet.microsoft.com/en-us/library/bb630430.aspx
    Ray : Cool :) Incorporated your link into the answer, so other people can see it straight away.
    Phillip Wells : I have the same problem. I've tried running IE as admin then going to the page, but I'm still getting the access denied error. Any suggestions?
  • Phillip Wells said: "I have the same problem. I've tried running IE as admin then going to the page, but I'm still getting the access denied error. Any suggestions?"

    I also have this problem. I run IE as Administrator but still get the access denied error. It seems that IE still not run as Administrator. Then I tried to use other browser (I tried Google Chrome) as Administrator. Then boom! The Home Page of SQL Server Reporting Services Manager is shown up with the tab Properties. I click it. I add my account to become the Content Manager. Then I open IE as usual (not as Administrator), and then I can browser and manage the SSRS Manager site.

    Hope this helps, -Fu-

Visual Studio 6.0 to Visual Studio 2008

When version VC++ 6.0 application is converted to VC++ 2008, there are LINK2001 / LNK2019 linkage errors.

But the same code compiled and linked and runs without any problem in VC++ 6.0

How can I resolve this?

From stackoverflow
  • Looks like your project is depending on another external library. In VC6, you set the paths properly from Options/Settings, but you missed that in VC2008. That's just a wild guess though..

  • Jumping from VC6 to VS2008 means dealing with breaking changes in VS2003, VS2005 and VS2008. Read more here and here. Just a guess though - need more details.

Annotated Table of Contents in LaTeX

I'd like to use LaTeX's \tableofcontents command (or some equivalent) to automatically generate a table of contents, but I'd also like to add a sentence or two to each line in the table of contents that describes what the referenced section is about. How can I do this?

From stackoverflow
  • Try

    \addcontentsline{toc}{section}{sample text}
    
  • I expect you can brute force and ignorance something using addcontentsline. eg:

    \addcontentsline{toc}{section}{text}
    

    however, this will conflict with automagically generated lines if you don't use the starred versions of sections it refers to.

    Anything more clean will require messing about with the relevant macros....unless I'm missing something.

  • Follwoing Oliver and simon's advice:

    You could redefine the sectioning commands to take a second (possibly optional) argument, and use that to build your argument to \addtocontentsline, and then involk the cooresponding section* command.

    Andreas : Thanks! Using your method, I can make it look like this: http://i43.tinypic.com/34jcaat.png -- not perfect, since it would be preferable if the page numbers and dots were in line with the headings, but much better than no annotations!
  • The tocloft package and its \cftchapterprecistoc command solved my problem.

    Will Robertson : The memoir class also provides this functionality (since it's by the same author)
  • Does anybody know how to eliminate de name of a section or subsection in the table of contents? I have proved *\section{name of the section} but this eliminates de number od the section in the document and I don't want this happen.

    Any ideas?

    Thanks!

  • I would change the {section} part to {subsection}.

    \addcontentsline{toc}{subsection}{sample text}
    

Count bits in the number.

Duplicate:

Best algorithm to count the number of set bits in a 32-bit integer?


Suppose you have a number. Is there any way to count the bits which equals to 1 in binary representation of that number, not using iteration? I mean, is there any way to do it in constant time using some bitwise operators and masks. I need solution which will work well for both architectures 32 bit and 64 bit. Ah almost forgot, I need it for C language or assembler is also good.

From stackoverflow
  • There is a bit counting algorithm without a loop at http://graphics.stanford.edu/~seander/bithacks.html. Lots of bit counting algorithms at http://gurmeetsingh.wordpress.com/2008/08/05/fast-bit-counting-routines/

  • Yes, you can do that by using a look up table.

  • Well, of course there is, but you're not going to like it.

    You could, of course, build a lookup table with all the correct values in it:

    table[1] = 1, table[2] = 1, table[3] = 2, etc.

    So, this would give you a really fast answer, but it's a completely useless solution by itself, since the table would have to be very, very large.

    You could optimize this a bit, but it requires just a little iteration. Simply create an 8-bit version of the table solution, a mere 256-entry table, then iterate over each BYTE in the value to be checked, summing the results of the table lookup. Something like:

    short int tableLookup[256] = { 0, 1, 1, 2, 1, ... };
    unsigned int valueToCheck = 89392491;
    int result = 0;
    while ( valueToCheck != 0 ) {
       result += tableLookup[ (valueToCheck & 0xFF) ];
       valueToCheck >>= 8;
    }
    // result should now have the correct bit count, if the table is correct.
    

    Hmm, seems this is well known (and here I was doing this off the top of my head): http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive

    Charlie Martin : Bill, there are some slicker ways to do it; follow the link to the dup.
    RBerteig : Clear answer but you probably want unsigned int valueToCheck otherwise the right shift is arithmetic and would preserve the sign bit which will prevent the loop from terminating. If valueToCheck is a bignum of some kind, you want to use a logical right shift to do this.
    Bill James : Sure, sure, there're bound to be other ways to do it. @RBerteig, you're probably right, it's been a while since I had to deal with C's ambiguous shifting.

ASP.NET MVC / DDD architecture help

I am creating a Web application using ASP.NET MVC, and I'm trying to use domain-driven design. I have an architecture question.

I have a WebControl table to store keys and values for lists so they can be editable. I've incorporated this into my business model, but it is resulting in a lot of redundant code and I'm not sure it belongs there. For example, in my Request class I have a property called NeedType. Because this comes from a list, I created a NeedType class to provide the values for the radio buttons. I'm showing just one example here, but the form is going to have probably a dozen or so lists that need to come from the database.

[edit, to clarify question] What's a better way to do this? Are these list objects really part of my domain or do they exist only for the UI? If not part of the domain, then they don't belong in my Core project, so where do they go?

public class Request : DomainObject
{
   public virtual int RequestId { get; set; }
   public virtual DateTime SubmissionDate { get; set; }
   public virtual string NeedType { get; set; }
   public virtual string NeedDescription { get; set; }
   // etc.
}

public class NeedType : DomainObject
{
    public virtual int NeedTypeId { get; set; }
    public virtual string NeedTypeCode { get; set; }
    public virtual string NeedTypeName { get; set; }
    public virtual int DisplayOrder { get; set; }
    public virtual bool Active { get; set; }
}

public class RequestController : Controller
{
    private readonly IRequestRepository repository;

    public RequestController()
    {
        repository = new RequestRepository(new HybridSessionBuilder());
    }

    public RequestController(IRequestRepository repository)
    {
        this.repository = repository;
    }

    public ViewResult Index(RequestForm form)
    {
        ViewData.Add("NeedTypes", GetNeedTypes());
        if (form == null)
        {
            form = new RequestForm();
            form.BindTo(repository.GetById(125));
        }
    }

    private NeedType[] GetNeedTypes()
    {
        INeedTypeRepository repo = new NeedTypeRepository(new HybridSessionBuilder());
        return repo.GetAll();
    }
}
From stackoverflow
  • If it comes from a list, then I'm betting this is a foreign key. Don't think about your UI at all when designing your domain model. This is simply a case where NeedType is a foreign key. Replace the string NeedType with a reference to an actual NeedType object. In your database, this would be a reference to an id.

    When you're building your list of NeedType choices, you simply need to pull every NeedType. Perhaps keeping it cached would be a good idea if it doesn't change much.

    Leslie : I understand what you are saying (there are considerations related to migrating data from a previous version that caused me to decide to store the text rather than the ID). But because this table exists solely to support making the lists on the form editable, I wasn't sure it belonged in the domain model.
  • Create a seperate viewmodel with the data you need in your view. The Model in the M of MVC is not the same as the domainmodel. MVC viewmodels are dumb DTO's without behaviour, properties only. A domain model has as much behaviour as possible. A domain model with get;set; properties only is considered an anti-pattern called "anemic domain model". There are 2 places where most people put the viewmodels: in the web layer, close to the views and controllers, or in a application service layer.

    Edit:

    When you only need to display a list of all needtypes in the database and one request in your view, I would indeed create one viewmodel with the request and the list of needtypes as properties. I don't think a call to multiple repositories in a controller is a smell, unless you have a larger application and you might want a seperate application service layer that returns the whole viewmodel with one method call.

    I think it might also be a good idea to follow the advise of Todd Smith about value object. When the needtypes can be added or edited by users at runtime, needtype should be an entity. When the needtypes are hardcoded and only changed with new releases of the project, needtype should be a value object and the list of needtypes could be populated by something like NeedType.GetAll() and stored in the database by adding a column to the request table instead of a seperate needtype table.

    Todd Smith : An "anemic domain model" isn't always a bad thing. For example my validation rules for a domain object might change depending on the process they're used in. By having my validation rules separate from my model it makes the model anemic yet more configurable.
    Paco : A domain model is not just about entities. Factories, value-objects, repositories, domain-services (not application services like an authentication-service) are also part of the domain. I use validation in different places and for different purposes, but that does not mean that I have to make my domain model anemic.
    Paco : It's about object-oriented programming versus procedural programming.
    Leslie : I do have a viewmodel, notice that the controller references a RequestForm object, not a Request object. The calls to other repositories are a smell that tells me I don't have this set up right. Do I make NeedTypes[] part of the Request object? This doesn't quite make sense to me because the Request object doesn't care about all the need types it isn't, only about the type it is. I only need NeedType[] to populate the lists on the view.
    Paco : @Leslie: see edit
    Leslie : @Paco Thanks for your help
  • Your NeedType looks like a value object to me. If it's read-only data then it should be treated as a value object in a DDD architecture and are part of your domain.

    A lot of people run into the "omg so much redundancy" issue when dealing with DDD since you're no longer using the old Database -> DataTable -> UI approach.

    Leslie : This is how I have it set up. I was more worried about the redundancy in the sense that every list will have the exact same five properties. I could make them inherit from a base type, but that base type is about lists on the view, not the domain really. I thought there might be another way to set this up.

FastCgi crashes -- Want to catch all exceptions but how?

Hi,

I have a django app running on apache with fastcgi (uses Flup's WSGIServer).

This gets setup via dispatch.fcgi, concatenated below:

#!/usr/bin/python

import sys, os

sys.path.insert(0, os.path.realpath('/usr/local/django_src/django'))

PROJECT_PATH=os.environ['PROJECT_PATH']

sys.path.insert(0, PROJECT_PATH)

os.chdir(PROJECT_PATH)

os.environ['DJANGO_SETTINGS_MODULE'] = "settings"

from django.core.servers.fastcgi import runfastcgi

runfastcgi(method="threaded",daemonize='false',)

The runfastcgi is the one that does the work, eventually running a WSGIServer on a WSGIHandler.

Sometimes an exception happens which crashes fastcgi.

EDIT: I don't know what error crashes fastcgi, or whether fastcgi even crashes. I just know that sometimes the site goes down--consistently down--until I reboot apache. THe only errors that appear in the error.log are the broken pipe and incomplete headers ones, listed below.

Incomplete headers:

note: I've replaced sensitive information or clutter with "..."

[Sat May 09 ...] [error] [client ...] (104)Connection reset by peer: FastCGI: comm with server ".../dispatch.fcgi" aborted: read failed
[Sat May 09 ...] [error] [client ...] FastCGI: incomplete headers (0 bytes) received from server ".../dispatch.fcgi"
[Sat May 09 ...] [error] [client ...] (32)Broken pipe: FastCGI: comm with server ".../dispatch.fcgi" aborted: write failed,

Broken pipe:

note: this happens to be for a trac site not a django app, but it looks the same.

Unhandled exception in thread started by <bound method Connection.run of <trac.web._fcgi.Connection object at 0xb53d7c0c>>
Traceback (most recent call last):
  File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 654, in run
    self.process_input()
  File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 690, in process_input
    self._do_params(rec)
  File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 789, in _do_params
    self._start_request(req)
  File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 773, in _start_request
    req.run()
  File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 582, in run
    self._flush()
  File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 589, in _flush
    self.stdout.close()
  File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 348, in close
    self._conn.writeRecord(rec)
  File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 705, in writeRecord
    rec.write(self._sock)
  File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 542, in write
    self._sendall(sock, header)
  File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 520, in _sendall
    sent = sock.send(data)
socket.error: (32, 'Broken pipe')

I've looked through /var/log/apache2/error.log, but I can't seem to find the cause of the crashing. I sometimes have memory swapping problems, but I think this is different. (Please excuse my ignorance. I am willing to learn how to implement and debug server admin stuff better.)

I'd like to wrap the the runfastcgi with a try/except. What is the best way to handle random exceptions (until I figure out the actual cause(s))?

I believe the WSGIServer handles many requests. If I catch an exception, can I re-call runfastcgi without fear of an infinite loop? Should I return an Error HttpRequest for the offending, exception-calling request? I'm not even sure how to do that.

I've been looking through django/core/servers/fastcgi.py and django/core/handlers/wsgi.py and django/http/init.py

I haven't been able to make progress understanding flup's side of things.

Have ideas or experiences I might learn from?

Thanks!

From stackoverflow
  • This is probably a Flup bug. When a flup-based server's client connection is closed before flup is done sending data, it raises a socket.error: (32, 'Broken pipe') exception.

    Trying to catch the exception by a try catch around runfastcgi will not work. Simply because the exception is raised by a thread.

    OK, I'll explain why the wrapping your own code in a try catch won't work. If you look closely at the exception traceback you'll see that the first statement in the trace is not runfastcgi. That's because the exception is happening in a different thread. If you want to catch the exception you need to wrap any of the statements listed by the trace in a try/catch like this:

    # in file /usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 654, in run
    try:
        self.process_input()
    except socket.error:
        # ignore or print an error
        pass
    

    The point is, you can catch the error by modifing Flup's code. But I don't see any benefit from this. Especial because this exception seems to be harmless and there already is a patch for it.

    Nadia Alramli : Have you tried applying the patch mentioned in the bug ticket? It might solve your issue. Is the error causing the request to fail? or is it just showing in the logs with no notable side effects?
    Nadia Alramli : OK, I added more details to the answer, hopefully that will make things clearer
  • Broken pipe usually doesn't come deterministically. You get a Broken pipe if a write operation on a pipe or socket fails because the other end has closed the connection. So if your FastCGI gets a Broken pipe, it means that the webserver has closed to connection too early. In some cases this is not an problem, it can be ignored silently.

    As a quick hack, try to catch and ignore the socket.error with Broken pipe. You may have to add an except: clause to many more places.

Large initial memory footprint for native app

Hi,

I've noticed that the native C++ application I'm working on has quite a large memory footprint (20MB) even before it enters any of my code.

(I'm referring to the "private bytes" measure in Windows, which as I understand it is the most useful metric).

I've placed a break point on the first line of the "main()" function and sure enough, the footprint is at 20MB when it reaches that.

The size of the EXE is only a couple of meg so that doesn't account for it.

I also deliberately removed all of the DLLs just to prove they weren't the cause. As expected it gets a "Dll not found" message, but the footprint is still 20MB!

So then I wondered that maybe it was the statically initialised objects which were the cause.

So, I added breakpoints to both "new" and "malloc". At the first hit to those (for the first static initialiser), the memory is already 20MB.

Anyone got any ideas about how I can diagnose what's eating up this memory?

Because it seems to be memory outside of the usual new/malloc paradigm, I'm struggling to understand how to debug.

Cheers,

John

From stackoverflow
  • You might compile your app without debug information and see if this changes something, debugging ability eats quiet some memory.

    anon : Debug information should not show up in "private bytes".
    John : Yes sorry I should have said I got the same result in Release code.
  • On my system, a simple MFC app and an empty Delphi app both take about the same number of private bytes - around 400K. So if your app is grabbing 20Mb, it is definitely sometyhing that your application is doing, and not some OS bloat. You need to post more details of what your app does, what libraries it uses etc.

    John : The app is a fairly complex backup application and uses a whole bunch of third party libraries including openssl, crypto++, sqlite etc etc. I absolutely agree that it's my application, but what I'd really want to understand is how do I find out *where* in my application? I think I've ruled out "my" code, so the finger is pointing at the third party libraries. Any ideas about how to debug that?
  • It might be that you're pulling a lot of libraries with your app. Most of them get initialized before execution is handed over to your main(). Check for any non-standard libraries you're linking against.

    EDIT: A very straightforward solution would be to create a new project and just link the libraries you're using one by one, checking memory usage each time. Even though it's an ugly approach, you should find the culprit this way.

    There's probably a more elegant solution out there, so you might want to spare some time googling for (free) memory profiling solutions.

    John : Good point - see comment in main question above.

Writing a __init__ function to be used in django model

Hi,

I'm trying to write an init function for one of my models so that I can create an object by doing

p = User('name','email')

When I write the model, I have

    def __init__(self, name, email, house_id, password):
            models.Model.__init__(self)
            self.name = name
            self.email = email

This works, and I can save the object to the database, but when I do 'User.objects.all()', it doesn't pull anything up unless I take out my __init__ function. Any ideas?

From stackoverflow
  • Django expects the signature of a model's constructor to be (self, *args, **kwargs), or some reasonable facsimile. Your changing the signature to something completely incompatible has broken it.

  • Relying on Django's built-in functionality and passing named parameters would be the simplest way to go.

    p = User(name="Fred", email="fred@example.com")
    

    But if you're set on saving some keystrokes, I'd suggest adding a static convenience method to the class instead of messing with the initializer.

    # In User class declaration
    def create(name, email)
      return User(name=name, email=email)
    create = staticmethod(create)
    
    # Use it
    p = User.create("Fred", "fred@example.com")
    
    Carl Meyer : Yeah, a factory method is the way to go here. You could also consider putting it on the Manager. Messing with the constructor signature will definitely break things.
    PirosB3 : Thanks man!! helped me a lot
    Wahnfrieden : @classmethod on create is also nicer

Is there a difference between an "instance variable" and a "property" in objective-c / cocoa / cocoa-touch?

I'm not very sure about this. I think that an "property" is an instance variable that has accessor methods, but I might think wrong...

From stackoverflow
  • A property is a more abstract concept. An instance variable is literally just a storage slot, like a slot in a struct. Normally other objects are never supposed to access them directly. A property, on the other hand, is an attribute of your object that can be accessed (it sounds vague and it's supposed to). Usually a property will return or set an instance variable, but it could use data from several or none at all. For example:

    @interface Person : NSObject {
        NSString *name;
    }
    
        @property(copy) NSString *name;
        @property(copy) NSString *firstName;
        @property(copy) NSString *lastName;
    @end
    
    @implementation Person
        @synthesize name;
    
        - (NSString *)firstName {
            [[name componentsSeparatedByString:@" "] objectAtIndex:0];
        }
        - (NSString *)lastName {
            [[name componentsSeparatedByString:@" "] lastObject];
        }
        - (NSString *)setFirstName:(NSString *)newName {
            NSArray *nameArray = [name componentsSeparatedByString:@" "];
            NSArray *newNameArray [[NSArray arrayWithObjects:newName, nil] arrayByAddingObjectsFromArray:[nameArray subarrayWithRange:NSMakeRange(1, [nameArray size]-1)]];
            self.name = [newNameArray componentsJoinedByString:@" "];
        }
        - (NSString *)setLastName:(NSString *)newName {
            NSArray *nameArray = [name componentsSeparatedByString:@" "];
            NSArray *newNameArray [[nameArray subarrayWithRange:NSMakeRange(0, [nameArray size]-2)] arrayByAddingObjectsFromArray:[NSArray arrayWithObjects:newName, nil]];
            self.name = [newNameArray componentsJoinedByString:@" "];
        }
    @end
    

    (Note: The above code is buggy in that it assumes the name already exists and has at least two components (e.g. "Bill Gates" rather than just "Gates"). I felt that fixing those assumptions would make the actual point of the code less clear, so I'm just pointing it out here so nobody innocently repeats those mistakes.)

  • A property is a friendly way of implementing a getter/setter for some value, with additional useful features and syntax. A property can be backed by an instance variable, but you can also define the getter/setter to do something a bit more dynamic, e.g. you might define a lowerCase property on a string which dynamically creates the result rather than returning the value of some member variable.

    Here's an example:

    // === In your .h ===
    
    @interface MyObject {
        NSString *propertyName;
    
    }
    
    // ...
    
    @property (nonatomic, retain) NSString *propertyName;
    
    // === In your .m @implementation ===
    
    @synthesize propertyName /* = otherVarName */;
    

    The @property line defines a property called propertyName of type NSString *. This can be get/set using the following syntax:

    myObject.propertyName = @"Hello World!";
    NSLog("Value: %@", myObject.propertyName);
    

    When you assign to or read from myObject.propertyName you are really calling setter/getter methods on the object.

    The @synthesize line tells the compiler to generate these getter/setters for you, using the member variable with the same name of the property to store the value (or otherVarName if you use the syntax in comments).

    Along with @synthesize you can still override one of the getter/setters by defining your own. The naming convention for these methods is setPropertyName: for the setter and propertyName (or getPropertyName, not standard) for the getter. The other will still be generated for you.

    In your @property line you can define a number of attributes in parens for the property that can automate things like thread-safety and memory management. By default a property is atomic meaning the compiler will wrap @synthesized get/set calls with appropriate locks to prevent concurrency issues. You can specify the nonatomic attribute to disable this (for example on the iPhone you want to default most properties to nonatomic).

    There are 3 attribute values that control memory management for any @synthesized setters. The first is retain which will automatically send release to old values of the property, and retain to the new values. This is very useful.

    The second is copy which will make a copy of any values passed in rather than retaining them. It is good practice to use copy for NSString because a caller could pass in an NSMutableString and change it out from under you. copy will make a new copy of the input which only you have access to.

    The third is assign which does a straight pointer assign without calling retain/release on the old or new object.

    Lastly you can also use the readonly attribute to disable the setter for the property.

php5 soap client in wsdl mode how to access different svc endpoint than the one specified in the wsdl

I´m a newbie to soap with php5...

I need to use a wsdl provided by a third party company, where, for testing purposes I´m supposed to use a different access address location for the service I´m needing, than the one specified in the wsdl document.

Is there any way I can create my soap client in wsdl mode, and override the specified address location in the wsdl for a different one?

Thanks in advance, Pablo

From stackoverflow
  • Pass location using the optional second parameter like this:

    $sc = new SoapClient('urlofmywsdl', array('location' => 'urltowebservice'));
    

Pushing out a PDF file to IE from an ASP.NET 3.5 site

My application pushes out a PDF file to a popup (e.g. no menu/toolbar) browser window (in response to the user clicking a button). This works for every browser out there except for IE7. In IE7, all I get is a blank window.

Here is the server-side code that pushes out the PDF:

private void StreamPDFReport(string ReportPath, HttpContext context)
{
    context.Response.Buffer = false;
    context.Response.Clear();
    context.Response.ClearContent();
    context.Response.ClearHeaders();        

    // Set the appropriate ContentType.
    context.Response.ContentType = "application/pdf";
    context.Response.AddHeader("Content-Disposition", "inline; filename=Report.pdf");
    context.Response.Cache.SetCacheability(HttpCacheability.NoCache);        

    // Write the file directly to the HTTP content output stream.
    context.Response.WriteFile(ReportPath);
    HttpContext.Current.ApplicationInstance.CompleteRequest();
    //context.Response.End();
}

On the client side, when the user presses the button, the following happens in the onClick handler:

onclick="window.open('RptHandler.ashx?RptType=CaseInfo', 'Report', 'top=10,left=10,width=1000,height=750')

Am I missing something really basic? Why does it work in every browser but not IE?

From stackoverflow
  • With IE7 we found you needed to add an additional header 'content-length' set to the size of the PDF your sending. something like:

    Response.AddHeader("content-length", {size of the pdf});

    AngryHacker : What you said is true, but that ain't it.
  • It turns out that the following statement causes IE to not display the PDF:

    context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    

    Not sure why.

    wweicker : Is this running under HTTPS?
    AngryHacker : No, it does not.
  • Seems like "context.Response.Cache.SetCacheability(HttpCacheability.NoCache);" will only work when using IIS7.

    I changed it to "context.Response.AddHeader("Cache-Control", "no-cache");" and it seems to be working with IE7 and IE8.