Tuesday, March 15, 2011

WPF - Cannot convert '<null>' from type '<null>' to type 'System.Uri'

I have a simple user control to display a hyperlink in a textblock:

LinkTextBlock.xaml:

<TextBlock >
    <Hyperlink NavigateUri="{Binding Url, ElementName=root}" >
        <TextBlock Text="{Binding Text, ElementName=root}" />
    </Hyperlink>   
</TextBlock>

LinkTextBlock.xaml.cs:

public static readonly DependencyProperty UrlProperty = DependencyProperty.Register("Url", typeof (string), typeof (LinkTextBlock));
public string Url
{
    get { return (string) GetValue(UrlProperty); }
    set { SetValue(UrlProperty, value); }
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof (string), typeof (LinkTextBlock));
public string Text
{
    get { return (string) GetValue(TextProperty); }
    set { SetValue(TextProperty, value); }
}


Then, in a DataTemplate for a ListBox I have:

<Controls:LinkTextBlock Text="{Binding Email}" Url="{Binding Email}" />


When I run the application, it seems to work perfectly. The control shows the hyperlinks correctly and there are no apparent problems. However, when I look at the Output window I get exceptions, one for each ListBox item:

System.Windows.Data Error: 22 : Cannot convert '' from type '' to type 'System.Uri' for 'en-US' culture with default conversions; consider using Converter property of Binding. NotSupportedException:'System.NotSupportedException: UriTypeConverter cannot convert from (null). at System.ComponentModel.TypeConverter.GetConvertFromException(Object value) at System.ComponentModel.TypeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) at System.UriTypeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) at MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward)'

Why is this happening? I know the binding error is a result of the binding to NavigateURI. Do you have any suggestions for me? What can I do about it? I really appreciate your inputs.

Thanks

From stackoverflow
  • Shouldn't this

    <TextBlock >
        <Hyperlink NavigateUri="{Binding Url, ElementName=root}" >
            <TextBlock Text="{Binding Text, ElementName=root}" />
        </Hyperlink>   
    </TextBlock>
    

    be this?

    <TextBlock  Text="{Binding Text, ElementName=root}">
        <Hyperlink NavigateUri="{Binding Url, ElementName=root}" />
    </TextBlock>
    
    Gustavo Cavalcanti : Not really. Hyperlink doesn't have a visual representation. So if you do what you're suggesting, you're going to end up with just a TextBlock without anything to click on.
    Gustavo Cavalcanti : And, on top of not working visually, your suggestion does not address my issue, which is the exceptions. Thanks.
  • I figured it out. The problem is when performing an implicit conversion from string to Uri, since NavigateUri is of type Uri. I needed to create a converter to convert string to Uri, change my property from String to Uri, and it all worked fine without exceptions.

App dock icon in wxPython

In wxPython on Mac OS X is it possible to display a custom icon when an application is launched. Right now when I launch the app I wrote, a blank white icon is displayed in the dock. How would I go about changing it?

From stackoverflow
  • I have this in my setup file to add an icon:

    from setuptools import setup
    
    APP = ['MyApp.py']
    DATA_FILES = []
    OPTIONS = {'argv_emulation': True, 
        'iconfile': 'MyAppIcon.icns' }
    
    setup(
        app=APP,
        data_files=DATA_FILES,
        options={'py2app': OPTIONS},
        setup_requires=['py2app'],
    )
    

    I think you have to use an icns file. I used img2icns to create one.

FxCop + MVP: "Properties should not be write only"

Suppose I'm implementing an MVP pattern and I have a view interface as such:

interface IView {

    string SuperRadString { set; }
}

There's no reason for the presenter to ever need to retrieve this string from the view, so can I safely ignore this error?

From stackoverflow
  • Well, yes...

    However, semantically it would make more sense to have a method for setting the value than a "black hole property".

  • Well... I think that write only Password properties are OK.

Flex Custom Components Tutorial

I'm just getting started out with flex. Are there any easy to follow tutorials that give examples of creating custom components that pass data with custom events?

From stackoverflow

XPaths and <? ?>

I have a WIX file that I need to modify using MSBuild. It starts like this:

<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
     xmlns:iis="http://schemas.microsoft.com/wix/IIsExtension">

  <?--... Removed Params ...-->

  <?define ProductVersion = "1.0.1"?>

  <?--... Removed Params ...-->

  <Product Id='$(var.ProductCode)'
    UpgradeCode='$(var.UpgradeCode)'
    Name='$(var.AppName)' Language="1033" Version='$(var.ProductVersion)'
    Manufacturer='$(var.Manufacturer)'>
    <Package Id='$(var.PackageCode)' InstallerVersion="200" 
    Compressed="yes" />

  <?--... Rest of the WIX XML file ...-->

My problem is that I don't know what the XPath would to the <?define ProductVersion = "1.0.1"?> would be. Is there a way to reference that via XPath so I can use the SDC SetValue MSBuild Task to change it? It is not a node (I think) so I am not sure how to reference it.

Vaccano

From stackoverflow
  • It looks like /Wix/processing-instruction('define') may work for an XPath (whether or not MSBuild recognizes that, I don't know).

    By plugging that into SketchPath, I was able to click around in it and test various XPaths to see what would select that element.

  • //processing-instruction('define')

  • <?define> is a processing instruction node, so you should be able to address it using an XPath expression such as

    //processing-instruction('define')
    
  • Another approach would be to define the parameter via the command-line to candle:

    candle -dProductVersion=1.0.1
    

Format number as money

How do I format a number to look like this: 9,000 my database field is in money data type, when I pull it up I see it like this: 9000.0000 that don't look right to me (I would like it to look like a real money format)

Sorry folks, forgot to mention technology it would be in C#

Thanks!

From stackoverflow
  • decimal money = 1000;
    Response.Write(string.Format("{0:C}", money));
    

    The above is an example in C#.

    Joseph : Response.Write(string.Format("{0:C}", money)) would also be the equivalent in VB .NET since its really the framework doing the formatting, not the language
  • These might help, Read'em.

    http://www.onlamp.com/pub/a/onlamp/2001/09/13/aboutSQL.html http://www.informit.com/guides/content.aspx?g=sqlserver&seqNum=54

  • You need to do a "formatting" function (in whatever language you're using) that will return the data in a currency format. Another answer already describes the code in C#. Here's vbscript:

    Dim Amount
    Amount = 2000
    Response.Write(FormatCurrency(Amount))
    

    How your database viewing application reads the data and how it is actually stored in the database may be two different things.

  • While you could call string.format, I think it's easier to just call ToString on it.

    decimal money = 9000m;
    string formattedMoney = money.ToString("C");
    

DBUnit - Creating parital datasets of dependent tables

Hi,

Is there a way to create a partial dataset of the dependent tables in DBUnit? For example I need to create a dataset of the primary table as well as the dependent tables each with say, 25 rows (As the data in the tables is huge).

Thanks, R

From stackoverflow
  • Hi,

    the database subsetting tool Jailer (jailer.sourceforge.net) may help you

Clearing the log associated with a tracelistener after each run ?

I'm using TextWriterTraceListener for logging, which is being configured into the app using app.config as shown below.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.diagnostics>
    <trace autoflush="true" indentsize="100"  >
      <listeners>
        <add name="myListener" type="System.Diagnostics.TextWriterTraceListener" 
             initializeData="MyLog.log" />
        <remove name="Default" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>

How do I ensure that the logging starts afresh (clearing the previous contents) after each run, rather than appending to the contents to the existing log ?

From stackoverflow
  • Imo, log4net gives you a lot more options and configurability than the Trace system. The RollingLogFileAppender is what you're looking for.

  • The best way would be to derive your own Custom TraceListener from the TextWriterTraceListener class. Here's a sample that rolls a new log file at every interval. You should be able to modify this implementation.

Is there a way to override action scripts operators, in particular I would like to override the equals operator

Is it possible to override the equals() operator (ie. for customer classes where equality may be determined by 2 or more fields matching).

From stackoverflow
  • if you mean overloading "==" as a synonym for equals() then you can't, as ActionScript doesn't offer operator overloading. Just write an equals() method for your class and use that...

Why does VS 2008 sp1 install abort on Win7 RC?

What can you do if you get the following error when installing Visual Studio 2008 sp1 in Windows 7 RC?

Operation Aborted
From stackoverflow
  • while installing Visual Studio 2008 SP1 on Windows 7 RC 7100, run this as administrator:

    reg delete HKLM\SOFTWARE\Microsoft\SQMClient\Windows\DisabledSessions /va /f
    

    Afterwards Visual Studio 2008 SP1 will install correctly.

    I copied this from the original question, just to make it a proper question/answer... marked as community wiki

  • Download this update and install it before you install sp1 on to visual studio 08

Backup Algorithm

I am looking at writing a program (.Net)for backing up files on a computer. How would I go on about knowing what files have changed to backup (I don't really want to scan the last modified dates each time.

Are there any backup algorithms for backing up only the bits of a file have changed. What are the O notations for the algorithm?

From stackoverflow
  • Could I suggest searching for 'rsync for windows' in your favourite search engine?

  • Here's a very good simple stuff I'm using for backups in my scripts: http://www.mikerubel.org/computers/rsync_snapshots/.

    Based on this, the first approach would be to build a database of file modification times and compare/update them each time you're making a backup copy. Apart of datetime, I would also keep file size and add it to the comparison.

  • Check the archive bit out. It may be what you want.

    In .NET it's System.IO.FileAttributes.Archive, which can be used with SetAttr in VB, or System.IO.FileInfo.Attributes or System.IO.File.SetAttributes().

    Any algorithm that checks the last modified time or archive bit will depend on the number of directories on the drive. Since both attributes are stored in the directory, the timing will depend on the filesystem and its level of caching. A more efficient way to analyse backup efficiency may be to look at the number of blocks that have changed.

PHP SID not showing

Hi, I cannot get my SID working ...

<?php
session_start();
// Or maybe pass along the session id, if needed
echo '<br /><a href="page2.php?' . SID . '">page 2</a>';?>

does not show up SID number but session_id is working not sure if I am missing something. THnks

From stackoverflow
  • It says... boolean true what next...

  • page 1:

    <?php
        session_start();
        // why use it in a url?
        echo session_id();
        echo '<br /><a href=page2.php target=_blank>page 2</a>';
    ?>
    

    page 2:

    <?php
        session_start();
        // page 2
        echo session_id();
        echo '<br> <br> on page 2 ';
    ?>
    
  • You need to have session.use_trans_sid enabled to have PHP accept a session ID passed by either GET or POST.

  • The SID constant will show an empty string if a a cookie with the name of session.name has been detected by PHP. See the manual page. That means, that SID will contain a useful string only before the session cookie has been sent to the browser.

    That also means that if a browser refuses cookies the SID constant will work. Provided that seesion.use_trans_id is enabled, as Gumbo said.

  • Where possible, avoid passing session identifiers in URLs; for cases where this is needed (e.g. where the client rejects the session cookie), let the built-in URL rewriting routines alter the HTML.

    Passing session identifiers around in URLs means that you're exposing implementation detail in URLs. Purist views aside, this can lead to practical problems with users copy-pasting and sharing URLs which contain session information, inadvertently exposing their sessions to friends, or anyone else they share the URL with.

  • convert mp4 to mp3

Objective-C 2.0; Assigning a Property; Leaking Memory?

I'm still learning about Objective-C memory management. I'm trying to implement several simple classes in an example program that I'm building.

As an example, say I have the following class definition:

 #import <UIKit/UIKit.h>

 @interface customViewController : UIViewController 
 {
    customObject *myCustomObject;
 }

 @property (retain) customObject *myCustomObject;

 - (void)replaceCustomObject:(customObject *)newObject;

 @end

For the property, I use the standard synthesize keyword...

@synthesize myCustomObject;

Then please assume that in the instance of customViewController the myCustomObject is already set with a valid value and is in use. Then the method replaceCustomObject is defined as:

 - (void)replaceCustomObject:(customObject *)newObject
 {
     //Does this cause a memory leak because I just assign over
     //the existing property? 
     self.myCustomObject = newObject;
 }

As the comment asks, does this leak memory? Or is this the valid way to replace a previous object with a new object?

Thank you,
Frank

From stackoverflow
  • That's perfectly valid, and does not leak memory. The synthesized accessors manage retain counts correctly.

    (As an aside, you don't need that replaceCustomObject: method; since your property is readwrite by default, you have an auto-generated setCustomObject: method that clients of your class can use, and which follows the normal Cocoa naming conventions.)

    Frank V : I know I don't need the replaceCustomObject: method. That was just a way for me to illustrate my overall goal. As you can imagine, where I'm using this is much more than just assigning a property. :-) Thank you for answering my question.
  • the property accessor syntax

    self.x = y;
    

    has the same effect as calling the setter method explicitly:

    [self setX:y];
    

    The accessor method will do whatever it has been written to do. In your case, for a @property(retain) property that has been @synthesized, the accessor will release the old object and retain the new one.

    So, calling the setter, whether explicitly or through the '.' syntax, will do the right thing - including the right memory management.

    So in short: no, this will not leak memory.

  • According to this, if you use (retain) in your declaration, the synthesized method will release the old value first, then retain the new one:

    if (property != newValue) {
        [property release];
        property = [newValue retain];
    }
    
  • As others have mentioned, your code is perfectly valid and won't leak memory when assigning to the property.

    If you have forgotten to implement a proper dealloc method, the last object assigned will be leaked when your customViewController is destroyed. A proper dealloc implementation would look like so:

    - (void)dealloc
    {
        self.myCustomObject = nil;
        [super dealloc];
    }
    
    Frank V : Can you explain further? I've never seen setting a property to nil. Is this equal to doing [self.myCustomObject release] ? This is how I learend to take care of this in the dealloc method...
    rpetrich : Sending [self.myCustomObject release] is dangerous because after doing so, self.myCustomObject still points to the now-released object! In the dealloc method it is probably safe since self is being destroyed anyway, but I dislike having special rules to remember. To be safe, you could also do the following instead: [myCustomObject release]; myCustomObject = nil;

What is the mysql command to pipe all command line input to a file on Fedora OS?

I run several queries from mysql command line on my linux box (Fedora Os). I would like to capture all these automatically to a file. I know there is command in Linux called history and then you can pipe it to a file. Is there anything similar for MYSQL. I would like to save all my scripts and sql query just for reference sake at a later point in time.

Help Appreciated.

From stackoverflow
  • MySQL stores your query history in the file ~/.mysql_history. Certain characters are escaped in this file. Space becomes \040; backslash becomes \\. You can replace these escape sequences using sed or your favorite text editor.

    CodeToGlory : for some reason, I cannot see this file.
    Barry Brown : If it's like most other history files written by processes like bash, pgsql, and so forth, it doesn't get written unless you exit cleanly from the mysql command line. If you just close your terminal window or kill the mysql process, nothing will get saved.
    Ayman Hourieh : Also, what is the output of 'echo $MYSQL_HISTFILE'? Is it set to /dev/null by any chance?
  • Alternatively, turn on the mysql query log.

    in your /etc/mysql/my.cnf file (or wherever your OS puts it), put a section in the config like:

    [mysqld]
    log=/var/log/mysql/mysqld.log
    

    Then, every query will be logged to this file.

Best practices for managing pricing/discount business rules on rails

I am fairly new to Rails and I have never developed a large application. A friend of mine and I are developing two separate applications and we found out we both have a need for a way to generically manage pricing / discount rules.

Scenario: Say you have a conference registration application and depending on who uses the application, they may choose to offer different pricing plans. $50 1 attendee $40 >5 attendees Exhibitor gets 3 free attendees and $30 each additional

Instead of baking in the specifics of these rules, it would be nice to abstract it in some way so rules can change over time and by conference.

What are the best practices for handling this? Are there Rails plugins? We have both searched, but have yet to find the solution.

From stackoverflow
  • I also don't know of an existing plugin for this but since you have at least two apps that need this why not try and make it a rails engine?

    That way you and your friend can halve your effort and have something you can open source and show off and improve via community feedback.

    noel_g : we are both newbies, so it may be something we can do when we gain more experience.
  • I think you should have a look at RuleBy. I haven't used it myself, but am still meaning to find the time to experiment with it. It should solve precisely these problems.

How can I make my old Dbase 2 progs run under SQL?

How can I make my old Dbase 2 progs run under SQL?

I want to do two things.

  1. have my old Dbase progs run under windows with huge datasets on my personal computer (so it would have no internet need)

and 2. Have my old dbase progs run from an sql server on the internet where I could log on form the internet and work the program and database.

From stackoverflow

Raise button (or any control) click event manually. C#

Can anyone tell me how to raise click event of button control (or for that matter for any event).

Platform: .net 2.0/3.0/3.5 Language: c# Domain: Windows Application, WinForms, etc.

From stackoverflow
  • You can use the Button.PerformClick method.

    Adam Robinson : +1. As for any other events, the Event structure is specifically designed to make the owner of the event the only object capable of directly invoking it. The Button class exposes PerformClick to allow you to simulate a click, but not all events will have this (for good reason).
    Asad Malik : thanks buddy... so simple and yet.... :D you are a life saver... :D
  • You can also look into Windows Accessibility or some UI automation framework that allows you to programmatically cause UI controls to respond to user gestures. If a control does not offer a way for its events to be programmatically triggered like PerformClick, you can derive from that control and expose a public method like PerformnXXX that when called internally invokes the event handlers subscribed to a particular event.

  • Maybe the solution is much more simple:

    Maybe you don't really want your code "to click the button".
    Do you just want to run the code which is behind the button from another place in the form?

    If yes, put the code into a separate method (like "DoActionXXX") and call the method from the button and from everywhere else where you need it.

where is the ActiveDirectoryMembershipProvider source

I had heard a rumour that the ActiveDirectoryMembershipProvider source code was available.

I'm having some difficulty troubleshooting the our setup of the out-of-the-box provider, and stepping through the source would have been really handy.

From stackoverflow

How to enable membership provider for sql server express database.

Hi,

I am playing with ASP.NET MVC with visual webdeveloper express edtion 2008 and sql server express edition. I am creating a site that will use membership provider for that i want to use my own databse not the application services database. I have created my database in app_data folder but still I am not able to register it using aspnet_regsql command. It is not showing that in list.Can any one suggest the way for enabling my database for membership provider

From stackoverflow
  • You should be able to run the aspnet_regsql from the command line, like this:

    aspnet_regsql -A all -C "Data Source=.\SQLEXPRESS;Integrated Security=True;User Instance=True" -d "C:\MyProject\APP_DATA\aspnetdb.mdf"
    

    Replace the -d switch with the correct path to your APP_DATA folder.

    Dan Atkinson : Not worthy of its own answer but, as José says, you can use aspnet_regsql.exe from the command line. If you don't supply any switched (eg just aspnet_regsql.exe) then it will open a wizard which will guide you through the process of setting up the features.

MySQL: Fulltext indexing previous records?

Hi All,

I added a FULLTEXT index on three of my columns, after I already had a bunch of records...does that mean the FULLTEXT won't index them and will only index records inserted after the FULLTEXT index was added? If so, anyway to reindex the whole database?

From stackoverflow
  • When you do ALTER TABLE ADD INDEX, old records get indexed immediately (and new records get indexed as soon as they are INSERTed). That's true for FULLTEXT indexes as well.

    Please note however, that sometimes (e.g. when you change options ft_min_word_len, ft_max_word_len, or ft_stopword_file) you have to rebuild a FULLTEXT index, see http://dev.mysql.com/doc/refman/5.1/en/fulltext-fine-tuning.html for details.

    Jasie : Thank you for your help! The article was very helpful.
  • It's MySQL's responsibility, not yours, to ensure that indexes are consistent with the data they are indexing.

    When you add an index on existing data, MySQL will build the index according to that existing data.

    FULLTEXT indexes are no exception.

    You should only need to rebuild an index if you suspect your table has been corrupted somehow, or you have done some other advanced tweaking to the way MySQL builds its indexes.

    Jasie : Thank you for your help!

Are there any Ajax(Prototype or JQuery Plugin) sample for stackoverflow-like voting?

any good ajax samples for implementing voting similar to the up and down buttons of stackoverflow.com

From stackoverflow
  • You create a page for voting like yoursite.com/vote?postid=1234&direction=up that saves the vote in the database. Then you create buttons or links for voting and perform an Ajax request when the user clicks the link:

    jquery:

    $.post("vote", { postid: the_id, direction: "up" })
    
    tranced_UT3 : any idea how to do that in GSP pages?
    Jules : I'm sorry, I have never used GSP (I didn't even know it existed).

Is WPF an ECMA standard library?

Is WPF an ECMA standard library? Or it is just a part of MS .net implementation? Any references please?

From stackoverflow
  • it is not.

    the C# and CLR is ECMA, but WPF is not.

    In more detail, BCL is ECMA but FCL is not.

    WPF & WinForms should be FCL.

    Sam Saffron : BCL is ecma as well

What is the best way to scale images in Java?

I have a web application written in Java (Spring, Hibernate/JPA, Struts2) where users can upload images and store them in the file system. I would like to scale those images so that they are of a consistent size for display on the site. What libraries or built in functions will offer the best results? I will consider the following criteria in making my decision (in this order):

  • Free/Open Source (essential)
  • Easy to implement
  • Quality of results
  • Performance
  • Size of executable
From stackoverflow

WPF: A TextBox that has an event that fires when the Enter Key is pressed

Instead of attaching a PreviewKeyUp event with each TextBox in my app and checking if the pressed key was an Enter key and then do an action, I decided to implement extended version of a TextBox that includes a DefaultAction event that fires when an Enter Key is pressed in a TextBox.

What I did was basically create a new Class that extends from TextBox with a public event DefaultAction, like such:

public class DefaultTextBoxControl:TextBox
{
    public event EventHandler<EventArgs> DefaultAction = delegate { };

    public DefaultTextBoxControl()
    {
        PreviewKeyUp += DefaultTextBoxControl_PreviewKeyUp;
    }

    void DefaultTextBoxControl_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (e.Key != Key.Enter)
        {
            return;
        }
        DefaultAction(this, EventArgs.Empty);
    }
}

I then use this custom textbox from my app like such (xaml):

<Controls:DefaultTextBoxControl  DefaultAction="DefaultTextBoxControl_DefaultAction">
</Controls:DefaultTextBoxControl>


Now in my little experience I've had in learning WPF I've realized that almost most of the time there is a "cooler" (and hopefully easier) way to implement things

...so my question is, How can I improve the above control? Or maybe is there another way I can do the above control? ...maybe using only declarative code instead of both declarative (xaml) and procedural (C#) ?

From stackoverflow
  • Have a look at this blog post from a few months back where I attach a 'global' event handler to TextBox.GotFocus to select the text.

    Essentially you can handle the KeyUp event in your App class, like this:

    protected override void OnStartup(StartupEventArgs e)
    {
        EventManager.RegisterClassHandler(typeof(TextBox),
            TextBox.KeyUpEvent,
            new System.Windows.Input.KeyEventHandler(TextBox_KeyUp));
    
        base.OnStartup(e);
    }
    
    private void TextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (e.Key != System.Windows.Input.Key.Enter) return;
    
        // your event handler here
        e.Handled = true;
        MessageBox.Show("Enter pressed");
    }
    

    ... and now every TextBox in your application will call the TextBox_KeyUp method as users type into them.

    Update

    As you've pointed out in your comment, this is only useful if every TextBox needs to execute the same code.

    To add an arbitrary event like an Enter keypress, you might be better off looking into Attached Events. I believe this can get you what you want.

    Andreas Grech : But with this, how do you assign what happens when the enter key is pressed ? because every TextBox does something different
    Matt Hamilton : Oh! I'll update the answer.

PHP MySQL syntax for inserting date,time

Hi, I am trying to insert to date,time fields using a php script but I am getting a syntax error. Can someone please tell me, where I am doing the mistake. Thanks fellows

INSERT INTO calendar(event,from,to,day) VALUES ('".$_REQUEST['event']."', '".$_REQUEST['from_time']."', '".$_REQUEST['to_time']."', '".$_REQUEST['date_event']."')

From stackoverflow
  • Never insert string data into your sql statement without sanitizing the data or you end up with sql injections (intentional or unintentional injections), see http://php.net/mysql_real_escape_string
    If you do not have a debugger installed, let php print the sql statement so you can inspect it.

    Format and indent your sql queries. They are much easier to read and debug that way.

    Always check the return value of mysql_query(). If it's FALSE the query failed and mysql_errno() or mysql_error() can tell you more about the cause of the error.

    If you want to use an identifier that is also a reserved word for MySQL you almost always must put it in backticks (`) or double_quotes (in ansi mode).

    The format of date/time literals understood by MySQL is explained at http://dev.mysql.com/doc/refman/5.0/en/date-and-time-types.html

    Using _REQUEST for INSERT operations may be questionable ...but I leave that to others to answer ;-)

    <?php
    $mysql = mysql_connect...

    $query = " INSERT INTO `calendar` (`event`, `from`, `to`, `day`) VALUES ( '" . mysql_real_escape_string($_REQUEST['event'], $mysql) ."', '" . mysql_real_escape_string($_REQUEST['from_time'], $mysql) ."', '" . mysql_real_escape_string($_REQUEST['to_time'], $mysql) ."', '" . mysql_real_escape_string($_REQUEST['date_event'], $mysql]) ."' ) "; echo '<pre>$query=', htmlspecialchars($query), '</pre>'; $result = mysql_query($query, $mysql); if ( !$result ) { echo 'error: ', mysql_error($mysql); }

    And btw: Use prepared statements instead.

  • To insert into mySQL datetime fields, the string has to be in a certain format for mySQL to understand it. The problem is that php has its own thoughts and ideas on how dates are represented. When dealing with dates between the two you have to translate.

    If in php you are dealing with a time object you can do this to get a string mySQL will like:

    $mysqlDateString = date('Y-m-d H:i:s', $phpdate);
    

    or if you are dealing with a string date you can do this:

    $mysqlDateString = date('Y-m-d H:i:s', $strtotime("08/09/2009"));
    

    If you get a datetime string from mySQL you can do this to deal with it in PHP:

    $phpTime = strtotime($mysqlDateString);
    

    Just came across this problem myself, so hopefully this will work for you as well.

    Michael Mao : @Mike : Hi Mike. just found a tiny typo in your code snippet here : $mysqlDateString = date('Y-m-d H:i:s', $strtotime("08/09/2009")); The $ should be removed from $strtotime("08/09/2009"). :)

Control Internet connection data

I want to control internet connection programmatically, (I use Visual Studio .net (c#)). I want to process all the requests that are sent to the internet.

For example, if a user on any browser type "google.com", I want to get this request before it's sent to the internet.

Simply, it's a process that Windows uses to send and retreive data from a communication port, please do any one have a simple article that explain this process, also does any one have an idea how to control the data flow on communication ports using dot net

From stackoverflow
  • You may want to check out how Fiddler, a transparent proxy that automatically adds itself to the WININET chain so that it can see every request being made, works.

    According to this MSDN article:

    ...the program registers itself as the system proxy for Microsoft Windows Internet Services (WinInet), the HTTP layer used by Internet Explorer, Microsoft Office, and many other products.

    Additionally, take a look at the answers to this question - How to create a simple Proxy in C#.

jQuery double animation using the jquery easing plugin

Hi guys,

I want to implement something like this page does: link text

Look at the Clicker box. The box has two animations going on. One for the easeInQuad, then the other animation is for the easeInOutSine.

How can I implement something like that in my own function?

$(function() {
     var iH = window.innerHeight + 80;
     var position = $(window).scrollTop();
     $(window).scroll(function() {
      var scroll = $(window).scrollTop();
      if(scroll > position) {
       $("body").animate({
        scrollTop: iH
       },
       1000,
       "easeInOutQuart"
       ).animate({
        scrollTop: parseInt($(window).scrollTop()) - 80
       },
       1000,
       "easeInOutQuart"
       )

      } else if(scroll < position) {
       $("body").get(0).scrollTop = 0;
      }
      position = $(window).scrollTop();
     })
    })

The second animate doesn't work quite well. But it does scroll it up. But it scroll it up too much not just 80 pixels. It scroll it up to the top, then the animation got an infinite loop. After the second .aminate it will continue to animate it again and again and again. Non stop.

From stackoverflow

C/C++ Machine Learning Libraries for Clustering

What are some C/c++ Machine learning libraries that supports clustering of multi dimensional data? (for example K-Means)

So far I have come across

I am tempted to roll-my-own, but I am sure pre-existing ones are far better performance optimized with more eyes on code.

From stackoverflow

Simple iterator looping gives unexpected result

I am sure it's an obvious error with my logic, but I can't seem to work out what I am doing wrong. Quite simply I have an array list of security codes, I want to compute the correlation between each combination of security codes. My code is as follows:

private void crossCorr(ArrayList<String> codes, HashMap<String, Stock> stockMap){

 // iterate through the codes list and get all the cross correlations:

 Iterator<String> itr1 = codes.iterator();
 while(itr1.hasNext()){
  String code1 = itr1.next();
System.out.println("  -----  " +code1);
  Iterator<String> itr2 = codes.iterator();
  ArrayList<Double> corrs = new ArrayList<Double>();
  HashMap<String, Double> codeCorr = new HashMap<String, Double>();
  String code2="";
  double corr=-2;
  while(itr2.hasNext()){
   code2 = itr2.next();
   Maths calcs = new Maths();  
   corr = calcs.getCorrelation(stockMap.get(code1).getRorHistory(), stockMap.get(code2).getRorHistory());
   corrs.add(corr);  // we order this list and then use this ordered list
        // to find the codes for the stocks with the highest
        // correlation for any given stock
   codeCorr.put(code2, corr);
   System.out.println(code1+" - "+code2+" - Correlation is "+corr);
  }
  orderCorrs(6, codeCorr, corrs, code1);
 }

}

The output I get is --

----- GOOG
GOOG - GOOG - Correlation is 1.0000000000000002
GOOG - YHOO - Correlation is 0.6986623807707519
GOOG - MSFT - Correlation is 0.7275411317567286
GOOG - CSCO - Correlation is 0.8122979333663799
GOOG - AAPL - Correlation is 0.8217785260604609
GOOG - ADBE - Correlation is 0.6102679356472099
GOOG - DISH - Correlation is 0.644852624453125
GOOG - NSOL - Correlation is 0.11600387177879072
GOOG - SBUX - Correlation is 0.6694306410719489
GOOG - PSFT - Correlation is -0.09921822861087544
GOOG - XOM - Correlation is 0.6728272039489009
GOOG - WMT - Correlation is 0.4004364090315347
GOOG - IBM - Correlation is 0.7559988282095168
GOOG - JPM - Correlation is 0.7085525367336528
GOOG - DNA - Correlation is 0.13628949379947575
GOOG - HPQ - Correlation is 0.7819350018750656
GOOG - KO - Correlation is 0.5700932682157461
GOOG - VZ - Correlation is 0.737881573641585
GOOG - INTC - Correlation is 0.7654127298771953
GOOG - SPY - Correlation is 0.8042488406758052
GOOG - PEP - Correlation is 0.6297924741882344
GOOG - WFC - Correlation is 0.5064491351161948
GOOG - ABT - Correlation is 0.238752389446595
GOOG - QCOM - Correlation is 0.726356709262025
GOOG - COP - Correlation is 0.570604981251932
GOOG - MCD - Correlation is 0.5434872575410538

But I never get

YHOO - GOOG - Correlation is .... etc. etc.

I am sure this is a simple error and for some reason I am not picking it up.

I know I am doing the correlation calculations twice, I will fix this once I get this part working as intended.

Please let me know if I need to provide more info.

From stackoverflow
  • A quick test application having removed references to code we don't know about works fine for me.

    Is it possible that something's throwing an unchecked exception which you're not handling? If you could post a short but complete program demonstrating the problem, that would help immensely. Take a copy of your full project, and just remove bits (e.g. hard-coding data and return values) until you can't take anything else away without the problem going away too. At that point you may well have found the problem for yourself, of course.

    By the way, if you're using Java 1.5 or greater, it's simpler to use an extended for loop than explicitly using an iterator. You'd do:

    for (String code1 : codes) {
        // ...
        for (String code2 : codes) {
            // ...
        }
    }
    
    Ankur : Jon, do you mean for(String code1 : codes) { ... with the extra "s". If not what is code? Sorry for my ignorance
    Jon Skeet : Oops, yes. Fixing...
    Ankur : Np, I checked your edit. That's probably the way to go, commenting out what is non essential, and then slowly adding each piece to isolate the issue. Thanks, I'll get there.

How to get text right clicked + ctrl from any program and use it in my own program?

what I wanna do is similar to any text hooking app like Runtimeeditor and many more. But the difference is that I am making a dictionary and want to add a functionality of quickly searching words from any program. So I wanted to make some hooking stuff to get the text which is right clicked and ctrl is pressed at the same time. I mean this is the combination. Now I dont care about any language you can give me this in. Whether C# C++ or VB. Any if you want add the .nets also. Please explain every part of code you provide thnks.

From stackoverflow

ZedGraph labels

In ZedGraph how to show text labels for each point and in the XAxis all together?

EDIT:

If I do

myPane.XAxis.Type = AxisType.Text;
myPane.XAxis.Scale.TextLabels = array_of_string;

I get labels on the XAxis like this

alt text

And if I do

for (int i = 0; i < myCurve.Points.Count; i++)
{
    PointPair pt = myCurve.Points[i];
    // Create a text label from the Y data value
    TextObj text = new TextObj(pt.Y.ToString("f0"), pt.X, pt.Y + 0.1,
        CoordType.AxisXYScale, AlignH.Left, AlignV.Center);
    text.ZOrder = ZOrder.A_InFront;
    text.FontSpec.Angle = 0;
    myPane.GraphObjList.Add(text);
}

I get labels on the curve, like this

alt text

But if I do both at the same time, labels on the curve disappear.

Is there a way to combine both kind of labels?

From stackoverflow
  • I've changed my answer after you clarified the question. You just have to remember to position the labels correctly:

    <%
      System.Collections.Generic.List<ZedGraphWebPointPair> points = new System.Collections.Generic.List<ZedGraphWebPointPair>();
      for (int i = 0; i < 15; i++)
      {
        // Let's have some fun with maths
        points.Add(new ZedGraphWebPointPair
        {
          X = i,
          Y = Math.Pow(i - 10, 2) * -1 + 120
        });
      }
    
      System.Collections.Generic.List<string> XAxisLabels = new System.Collections.Generic.List<string>();
    
      TestGraph.CurveList.Add(new ZedGraphWebLineItem { Color = System.Drawing.Color.Red });
      TestGraph.XAxis.Scale.FontSpec.Size = 9;
    
      int j = 1;
      foreach (ZedGraphWebPointPair point in points)
      {
        // Add the points we calculated
        TestGraph.CurveList[0].Points.Add(point);
    
        // Add the labels for the points
        TestGraph.GraphObjList.Add(new ZedGraphWebTextObj
        {
          Location =
          {
            CoordinateFrame = ZedGraph.CoordType.XChartFractionYScale,
            // Make sure we position them according to the CoordinateFrame
            X = Convert.ToSingle(j) / points.Count - 0.05f,
            Y = Convert.ToSingle(point.Y) + 3f,
            AlignV = ZedGraph.AlignV.Top
          },
          Text = point.Y.ToString(),
          FontSpec = { Angle = 90, Size = 9, Border = { IsVisible = false } }
        });
    
        // Add the labels for the XAxis
        XAxisLabels.Add(String.Format("P{0}", j));
    
        j++;
      }
    
      TestGraph.RenderGraph += delegate(ZedGraphWeb zgw, System.Drawing.Graphics g, ZedGraph.MasterPane mp)
      {
        ZedGraph.GraphPane gp = mp[0];
        gp.XAxis.Type = ZedGraph.AxisType.Text;
        gp.XAxis.Scale.TextLabels = XAxisLabels.ToArray();
      };
    
    %>
    

    That code will produce this graph:

    ZedGraph sample

  • if the axis type is text the code below is easier to get x coordinate of the points ;)

    for (int tPoint = 0; tPoint < curve.Points.Count; tPoint++) { TextObj text = new TextObj(curve.Points[tPoint].Y.ToString(), curve.Points[tPoint].X, curve.Points[tPoint].Y + 10); }