Thursday, March 3, 2011

Rails: Is there an equivalent to save_without_validation which skips after_save filters?

I have an after_save filter which I dont want to trigger in a specific instance. Is there a way to do this similar to save_without_validation?

Thanks,

From stackoverflow

win32 select all on edit ctrl (textbox)

I am creating my textbox with these options. I can copy/cut/paste/undo, but when i hit select A it doesnt select all. I can right click and click select all but ctrl a doesnt do anything, why?

  wnd = CreateWindow("EDIT", 0,
   WS_CHILD | WS_VISIBLE | ES_MULTILINE | WS_HSCROLL | WS_VSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL,
   x, y, w, h,
   parentWnd,
   NULL, NULL, NULL);
From stackoverflow
  • You need to capture that keystroke and do the select all yourself.

    Here is some C# code for use with a RichTextBox:

        protected override void OnKeyDown(KeyEventArgs e)
        {
            // Ctrl-A does a Select All in the editor window
            if (e.Control && (e.KeyCode == Keys.A))
            {
                this.SelectAll();
                e.Handled = true;
            }
        }
    

    Sorry, I don't have Win32 code for you.

    Sheldon : mine says "does not contain a defintion for "selectALL" and no extension method accepting an argument of a type could be found"
  • Could it be that something else is stealing Ctrl-A? Use Spy++ to verify that it reaches your edit control.

  • I tend to use MFC (forgive me) instead of win32 so I cannot answer this definitively, but I noticed this comment added to a page on an MS site concerning talking with an Edit control (a simple editor within the Edit control):

    The edit control uses WM_CHAR for accepting characters, not WM_KEYDOWN etc. You must Translate() your messages or you ironically won't be able to edit the text in the edit control.

    I don't know if this applies to BoltBait's response, but I suspect it does.

    (I found this at http://msdn.microsoft.com/en-us/library/bb775462(VS.85).aspx)

    acidzombie24 : wow thanks, i wanted to select all so i can copy text faster. That link showed me WM_COPY which copys the text needed. thanks!
  • Why not add an accelerator for Ctrl+a to SelectAll?

    acidzombie24 : i guess i could but thats more code for me to write and learn how to do. BTW i used WM_COPY instead which is what i wanted. To copy the text into the clipboard :)
  • Ctrl-A is not a built-in accelerator like Ctrl-C and Ctrl-V. This is why you see WM_CUT, WM_PASTE and WM_COPY messages defined, but there is no WM_SELECTALL.

    You have to implement this functionality yourself. I did in my MFC app like this:

    static BOOL IsEdit( CWnd *pWnd ) 
    {
        if ( ! pWnd ) return FALSE ;
        HWND hWnd = pWnd->GetSafeHwnd();
        if (hWnd == NULL)
         return FALSE;
    
        TCHAR szClassName[6];
        return ::GetClassName(hWnd, szClassName, 6) &&
             _tcsicmp(szClassName, _T("Edit")) == 0;
    }
    
    BOOL LogWindowDlg::PreTranslateMessage(MSG* pMsg) 
    {
        if(pMsg->message==WM_KEYDOWN)
        {
            if ( pMsg->wParam=='A' && GetKeyState(VK_CONTROL)<0 )
            {
                // User pressed Ctrl-A.  Let's select-all
                CWnd * wnd = GetFocus() ;
                if ( wnd && IsEdit(wnd) )
                    ((CEdit *)wnd)->SetSel(0,-1) ;
            }
        }   
        return CDialog::PreTranslateMessage(pMsg);
    }
    

    Note, I stole IsEdit from this page: http://support.microsoft.com/kb/145616

    I point that out partly because I want to give credit, and partly because I think the IsEdit function (comparing classname strings) is dorky and I want to give blame.

Regex/Textmate Confusion

I'm trying to create a Textmate snippet, but have run into some difficulties. Basically, I want to type in a Name and split it into its parts.

Example,

Bill Gates: (Bill), (bill), (Gates), (gates), (Bill Gates), (Bill gates), (bill Gates), (bill gates)

EDIT**

So I most certainly can produce these results quite simply if I was using a programming language. For example, I could split the words and then call the uppercase or lowercase functions to produce this output.

But in my situation I am using Textmate and it regular expression capabilities to create a tab snippet. I want to type some trigger key, ie doit, press tab and then type in a username. Then the ouput above will be created. This won't save me that much time, but I feel like I come across this sort of stuff in Textmate quite frequently and want to figure it out.

I have been using this as a reference, but still don't know how use regexps to be selective with the words and upper and lowercase the values (\u \U \l \L)

http://manual.macromates.com/en/snippets

From stackoverflow

Properly formatted example for Python iMAP email access?

tldr: Can someone show me how to properly format this Python iMAP example so it works?

from http://www.python.org/doc/2.5.2/lib/imap4-example.html "

import getpass, imaplib

M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()

" Assuming my email is "email@gmail.com" and the password is "password," how should this look? I tried "M.login(getpass.getuser(email@gmail.com), getpass.getpass(password))" and it timed out. Complete newb here, so it's very likely I missed something obvious (like creating an iMAP object first? Not sure).

From stackoverflow
  • Try:

    >>> import getpass
    >>> help(getpass)
    
  • Did you forget to specify the IMAP host and port? Use something to the effect of:

    M = imaplib.IMAP4_SSL( 'imap.gmail.com' )
    

    or,

    M = imaplib.IMAP4_SSL()
    M.open( 'imap.gmail.com' )
    
  • import imaplib
    
    # you want to connect to a server; specify which server
    server= imaplib.IMAP4_SSL('imap.googlemail.com')
    # after connecting, tell the server who you are
    server.login('email@gmail.com', 'password')
    # this will show you a list of available folders
    # possibly your Inbox is called INBOX, but check the list of mailboxes
    code, mailboxen= server.list()
    print mailboxen
    # if it's called INBOX, then…
    server.select("INBOX")
    

    The rest of your code seems correct.

    ocdcoder : Just to save others time who might see this...it's "IMAP4_SSL" not just "IMAP_SSL".
    ΤΖΩΤΖΙΟΥ : @ocdcoder: nice catch, thanks.
  • Here is a script I used to use to grab logwatch info from my mailbox. Presented at LFNW 2008 -

    #!/usr/bin/env python
    
    ''' Utility to scan my mailbox for new mesages from Logwatch on systems and then
        grab useful info from the message and output a summary page.
    
        by Brian C. Lane <bcl@brianlane.com>
    '''
    import os, sys, imaplib, rfc822, re, StringIO
    
    server  ='mail.brianlane.com'
    username='yourusername'
    password='yourpassword'
    
    M = imaplib.IMAP4_SSL(server)
    M.login(username, password)
    M.select()
    typ, data = M.search(None, '(UNSEEN SUBJECT "Logwatch")')
    for num in data[0].split():
        typ, data = M.fetch(num, '(RFC822)')
    #   print 'Message %s\n%s\n' % (num, data[0][1])
    
        match = re.search( "^(Users logging in.*?)^\w",
              data[0][1],
              re.MULTILINE|re.DOTALL )
        if match:
         file = StringIO.StringIO(data[0][1])
         message = rfc822.Message(file)
         print message['from']
         print match.group(1).strip()
         print '----'
    
    M.close()
    M.logout()
    

How can I read from an IO::Socket::INET filehandle only if there is a complete line?

When reading from a IO::Socket::INET filehandle it can not be assumed that there will always be data available on the stream. What techniques are available to either peek at the stream to check if data is available or when doing the read take no data without a valid line termination and immediately pass through the read?

From stackoverflow
  • Set the Blocking option to 0 when creating the socket:

    $sock = IO::Socket::INET->new(Blocking => 0, ...);
    
    Erick : File this one under 'RTFD... correctly'
  • Checkout IO::Select; it's very often what I end up using when handling sockets in a non-blocking way.

encode avi with given output file size

I have an avi file which i want to re-encode to fit on a cd of 650 mb how can i encode it, so that the file size does not succeed the given size, what program to use?

From stackoverflow
  • AutoGK can do this very effectively. Primarily designed for DVD **cough** backup purposes, but it will also accept AVI as source. It's more of a collection of opensource programs with a co-ordinating GUI, so don't worry when the installer installs several items.

  • I assume you want to do this programmatically:

    For Windows:

    You can use directshow to transcode your video by building a filter graph.

    Get (if you don't already have) the platform SDK for windows. Then browse here to check out some of the directshow examples which construct filter graphs for transcoding.

    To build you will need the base classes. You can build them here:

    C:\Program Files\Microsoft SDKs\Windows\v6.1\Samples\Multimedia\DirectShow\BaseClasses
    

    Then check out the examples here:

    C:\Program Files\Microsoft SDKs\Windows\v6.1\Samples\Multimedia\DirectShow
    

    You can also manually create filter graphs to get a hang for how they are used and see how these things make sense (such as the enumeration of the encoders you will learn about in the examples):

    C:\Program Files\Microsoft SDKs\Windows\v6.1\Bin\graphedt.exe
    

    Once you have gone this far and understand how directshow works you can use some math to figure out how to transcode your video to fit in the size you want. To do this you may want to look at how many frames/sec your input video is and how big each frame is.

    Different encoders work in different ways:

    Lets assume you are transcoding avi file to a smaller or lesser quality avi file. Look at your input frame sizes and fps to determine the whole file size, then use some algebra to figure how to either reduce frame size or reduce # of frames per second (or a combination of both) to achieve the desired size (which can be your input variable).

    As for other encoders you may want to see how they work. Lossy encoders such as mp4 perform estimations to find out what video has changed from frame to frame- and that information is stored in the file to reconstruct frames. You will have to read about how they work - or check to see how to use your particular encoder for more details.

    For Linux (and also windows):

    You can use ffmpeg which is an all-in-one for transcoding and other things to video. You can even find prebuilt exe of the command line application, although the main page does not host it (just the source). This application uses open source video libraries to do a lot of the video transcoding as well as many other things. If you can locate a good dependable exe file you should probably check this out if you want something that is easy to use for your application. Check out their homepage here.

    I hope this gets you started.

  • To make it fit a specific size, you must use an appropriate bit-rate.

    For fixed bit-rate video, to get the target bit-rate you would take the target size, in bits, and the length of the source in seconds.

    target bit-rate = size / seconds
    

    For example:

    seconds = (90mins * 60) = 5400
    size = ((650MB * 1024) * 8) = 5324800
    target bit-rate = ~986 kilobytes per second
    

    With variable bit-rate, things are rather more complicated. Not quite sure if there's a way to accurately make the output file a set size. The easiest way is to calculate the maximum bit-rate using the above method,

  • Calculate the number of seconds the AVI is. Then, take the file size and divide by the length. Convert to kilobits per second, and use that as your bitrate median. (Use Google to do the math and conversion easily.)

    You can weigh the video and audio bitrates as you desire. Usually 96 kbps is good enough with AAC, but you may want more or less. Experiment.

Techniques for Caching SQL Query Data

Having read some on this subject:

http://stackoverflow.com/questions/37157/caching-mysql-queries

http://www.danga.com/memcached/

My SQL Caching problem: http://www.petefreitag.com/item/390.cfm

http://framework.zend.com/manual/en/zend.cache.html#zend.cache.introduction

I have a very unique (narrow) set of Queries and I think I could implement some caching quite easily within my current FastCGI C API executables (NOT PHP).

Zend describes their framework as: cache records are stored through backend adapters (File, Sqlite, Memcache...) through a flexible system of IDs and tags.

HOW is this implemented?

Since the same query can return different results if the Table has been changed, I need to monitor not only Queries, but UPDATE, INSERT and DELETE also (MySQL for now) Since this only happens from one of my processes, I could easily add a statement that deletes the cache when a table change is made.

Only SELECTs are permitted by the clients, in which case I could hash the queries and store them in a hash table or btree index along with a pointer to the file containing the results.

Is there a better way?

From stackoverflow
  • Oh man, that is a good question. Being a .NET developer, I have been fortunate enough to not have to worry about this at all over the last 7 years. I don't have to worry because .NET implements a quite powerful caching mechanism to do what you want to do.

    There is no way to do this at a middle tier or presentation tier layer?

  • .NET is certainly convenient for fast development but it has some undesirable consequences as MS makes a deaf bedfellow!

    I also prefer to develop me own solutions as I can tailor them to my needs. I don't need a lot fo sophistication, just some mechanism to tie inbound queries to results sets on the server side. The presentation is don on the client side where a seperate database exists. Requests are really only to update the client side database so in answer to your question, the client side caching is allready implemented.

  • As I think about this, I realize that allthough Caching results to disk is faster, the load on the disk will increase significantly. In my case the DB is not that slow for queries, it is the memory required for the result set that is the biggest issue, up to 3MB per result set. This will eat up server memory in no time If I keep it all in mempry while the xfer proceeds

  • Do I only get one shot at an answer?

Only one return statement per method, even in this scenario?

Hi,

I like the idea of having only 1 return statement per method.

What do you do in this situation though?

public static string ChopText(string Text)
{
   if(String.IsNullOrEmpty(Text)
   {
      // return here ?????//
   }

}

The only alternative I can think of is setting a flag, and then checking for the flag.

Problem is, I don't like having huge if statements that span more than a page. I might ugly nested if statements also as a result of this.

From stackoverflow
  • Frankly, situations like this are why overly rigid rules are bad.

    The point of rules like this is to make code more readable and maintainable, so when they make the code harder to read they should be ignored.

    That doesn't mean that the rule should be discarded entirely, because most of the time it does make the code more readable.

  • Personally I think

    public static string ChopText(string Text))
    {
       if(String.IsNullOrEmpty(Text)
          return Text;
    
       ...
    }
    

    is totally fine, if you don't like those AND if it is getting big.

    James Brooks : I dunno, I'm not keen on mismatched parenthesis. (I kid)
  • It is OK to replace nested conditional with guard clauses.

    Blankman : nice link Marko!
    Will : I do this all the time. I think if your scope goes deeper than two levels you're doing something wrong...
    Marko Dumic : Yes, thanks. I encourage everyone to get themselves familiar with the practices presented on the site and to apply the ones they're comfortable with.
    danimajo : +1 Great! Thanks a lot
    PhiLho : Good! I should show that to colleagues swearing only by The Unique Return... :-)
  • You really have to weigh the costs and benefits of doing something like this. Will the benefits of having only one return statement outweigh the downsides of having to contort a method that should be fairly simple to write?

    I'd go with no for this case.

  • This is a case where the rule should be ignored. It is common to have several guard clauses at the entry point to the method that return or throw an ArgumentException if the arguments passed in are not in the correct format. Just keep these statements clustered at the beginning of your methods.

  • "I like the idea of having only 1 return statement per method." Explain?

    As soon as you know that the parameters passed to your method are invalid, you should return or throw an exception.

    Bad:

    if (Valid) { do lots of stuff}
    else {return};
    

    Clean:

    if (invalid) { return; }
    if (invalid2) {return; }
    

    Another approach:

    if (invalid) {
         throws IllegalArgumentException();
    
  • Code that tries to only have one return per function is far more complex. It's usually a rats nest of if-thens and assignments. I challenge you to look at that kind of code and know the correct value is always been returned from those different paths. No way.

    Having said that, large functions indicate you may need to refactor the code into smaller simpler functions anyway.

  • With exceptions in place there is no "single entry - single exit" rule any more anyway, so there is absolutely no need to follow a strict "one return statement" rule. Control flow can - theoretically - exit the function any time by throwing an exception and unwinding the stack, so even if you implement a strict "single entry - single exit" policy there is no guarantee that it will be followed at all.

    Feel free to exit a function at any time if it suits you!

  • The rule is antiquated. Plain and simple. It exists to help bad programmers write more readable code... and it backfired. Make your code small and readable, and get rid of that silly rule.

  • I strongly believe in "one entry / one exit", with the exception of validating inputs at the top of the function. That has to happen before the real work of the function begins though.

    I think this rule was intended to stop people from exiting in the middle of code that's doing real work simply because they think they're "done".

    The problem with multiple returns is that you can't be sure that required exit processing will be performed, such as closing a socket or releasing some other resource.

  • Your methods should in general terms not span more then "one screen". If they do you should (in general again) try to split them into several methods. This is probably far more important than to have "only one return statement"...

    After all, what we're looking for is readability.

  • I strongly disagree with the idea that "one entry one exit" results in complex code. I've just written an application for Blackberry and Android phones in Java that consists of roughly 100 files and there is not a single method that does not exit at the end. While it is a GUI app and multithreaded none of the code is complicated. Few if any routines are not visible in their entirety on a screen. I've been designing and writing software for 46 years in all but a handful of languages and operating systems, and for me "one entry one exit" makes for very simple, easy to read and maintain code. My $0.02 worth. Sorry if I've ruffled any feathers.

Release notes, what for?

What are release notes for and who reads them? Should/could they be automated by just spitting out bugfixes for the current release, or do they warrant careful human editing? So, anybody with a link to best practices(reasoning behind) in regards to software release notes?

From stackoverflow
  • This really depends on who your application is built for and your organizations goals. However, I tend to believe that release notes need to be a concise listing of important key additions, enhancements, or fixes that are included in the particular release.

    Sometimes a simple dump of the bug tracking system information is enough, other times, I find that they need to be refined.

    The key is that typically Release Notes are believed to be the "Hey look at what we did" type listing of changes.

  • Bugfixes and added features. Users will read them to determine if they should go to the trouble of installing an incremental upgrade, or wait until the next release because this one doesn't add any features they need or fix any bugs in features that they were using.

    I'd say they at least require a human to read through them and make sure that each note is useful. It depends how good the comments on your bug fixes are.

  • Our release notes are human created instead of machine created. The cover three main topics.

    1. What is included in the releases (list of files)

    2. How to install it

    3. What changed since the last version (especially if the changes are not in the manual yet).

    items 1 and 2 don't chnage much from version to version, but they need to be reviewed. Item 3 takes the most work.

    Mitchel Sellers : Interesting take on this Jim. I would typically see items 1 and 2 be included in other documentation and not a release notes file....
  • Release notes and READMEs can be really important if your customer has to take special action in addition to normal procedures in order to upgrade. It also be useful to warn customers/users of any db upgrades that can automatically happen as a result of installing a newer patch. The way I see it, Release Notes and READMEs should be written for the System Administrator audience. So include the kinds of things they would want to know about: summaries of important changes, how to install, known bugs, anything your software might do that would make someone pull their hair out, etc.

  • I habitually read release notes. I tend to want a full comprehensive list of feature changes ( or as good as plausible ) in order to greater empower my utilization of the new product.

    I want to see when certain critical bugs, or critical security issues are solved.

  • Release notes are also very important in production environment.

    They help answering the age-old question:

    What the heck is currently running into production ?

    Or the more refined question: does this bug has actually been fixed in this release ?

  • Release notes are also important to your testing organization (if you have one), so that they know what's changed in the release and needs testing.

    Ville M : I mark this as answer because in practice I don't think the other users as a whole read the notes. Other users tend to read help, or tooltips and otherplaces in app. However QA appreciates detailed release notes for testing and at least in my organization they really do read them. Thanks.
  • Release note depend of your organization.

    I can talk for my organization. We use release note in PDF format and every time we publish a clickonce or a backend version. We send to office manager the Release note. This is a document used by the top administrator of the business (not only IT). This document is a way for them to know what is going on. What have changed, new features that are now in production, bugs fixed, and other thing that they might want to explain to their user.

    This is a document that can be between 3 to 4 pages, describing the job that has been done in this version with brief words.

  • This is of course highly dependent on the type of application/service/whatnot,
    but I've found that reading the release notes of my favorite developing tools etc..
    often make me stumble upon nice, interesting or even killer features that I'd probably miss if I did'nt at least skim the notes.....well, perhaps not killer, but you get my drift ;-)

    As most computer power users(now what kind of expression is that...)
    I never bother much with ordinary documentation, so this gives me
    that little something extra something besides clicking, hovering and faq'ing...

  • Release notes are for testers and users to know what's new/changed. Additionally, release notes can be used as supporting documentation when billing a new "version" of a software for client that you are building for them. v1.31 seems a lot easier to relate and drill into.

    Rather than compile both lists manually, if you can use your release notes to do that for you it's great.

Is there a more elegant way to convert an XML Document to a String in Java than this code?

Here is the code currently used.

public String getStringFromDoc(org.w3c.dom.Document doc)    {
        try
        {
           DOMSource domSource = new DOMSource(doc);
           StringWriter writer = new StringWriter();
           StreamResult result = new StreamResult(writer);
           TransformerFactory tf = TransformerFactory.newInstance();
           Transformer transformer = tf.newTransformer();
           transformer.transform(domSource, result);
           writer.flush();
           return writer.toString();
        }
        catch(TransformerException ex)
        {
           ex.printStackTrace();
           return null;
        }
    }
From stackoverflow
  • The transformer API is the only XML-standard way to transform from a DOM object to a serialized form (String in this case). As standard I mean SUN Java XML API for XML Processing.

    Other alternatives such as Xerces XMLSerializer or JDOM XMLOutputter are more direct methods (less code) but they are framework-specific.

    In my opinion the way you have used is the most elegant and most portable of all. By using a standard XML Java API you can plug the XML-Parser or XML-Transformer of your choice without changing the code(the same as JDBC drivers). Is there anything more elegant than that?

  • This is a little more concise:

    try {
      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      StreamResult result = new StreamResult(new StringWriter());
      DOMSource source = new DOMSource(doc);
      transformer.transform(source, result);
      return result.getWriter().toString();
    } catch(TransformerException ex) {
      ex.printStackTrace();
      return null;
    }
    

    Otherwise you could use a library like XMLSerializer from Apache:

      //Serialize DOM
      OutputFormat format    = new OutputFormat (doc); 
      // as a String
      StringWriter stringOut = new StringWriter ();    
      XMLSerializer serial   = new XMLSerializer (stringOut, 
                                                  format);
      serial.serialize(doc);
      // Display the XML
      System.out.println(stringOut.toString());
    
  • You could use XOM to perhaps do this:

    org.w3c.dom.Document domDocument = ...;
    nu.xom.Document xomDocument = 
        nu.xom.converters.DOMConverter.convert(domDocument);
    String xml = xomDocument.toXML();
    
    Jonik : +1, XOM (and other similar libraries) can really simplify matters.
  • Relies on DOM Level3 Load/Save:

    public String getStringFromDoc(org.w3c.dom.Document doc)    {
        DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
        LSSerializer lsSerializer = domImplementation.createLSSerializer();
        return lsSerializer.writeToString(doc);   
    }
    
  • This is an old question, but still relevent:

    Using the questioner's method (which is the most commonly cited), on my box I got a 35-45ms conversion time.

    By contrast, the LSSerializer and Apache XMLSerializer converted the same XML in 5-15ms

Does Windows Powershell have a Try/Catch or other error handling mechanism?

In a script, when a command-let or other executable statement errors out, is there a try/catch type of mechanism to recover from these errors? I haven't run across one in the documentation.

From stackoverflow
  • Yes!

    Have a read here:

    http://huddledmasses.org/trap-exception-in-powershell/

  • You use a Trap [exception-type] {} block before the code you want to handle exceptions for.

    See http://huddledmasses.org/trap-exception-in-powershell/

  • This MSDN appears to be helpful, also: http://channel9.msdn.com/wiki/windowspowershellquickstart

    casademora : wow, maybe I should stop looking at the technet docs...
  • Here's someone (Adam Weigert) who implemented try/catch/finally using powershell. I use this in place of the built-in trap staement. Seems more natural.

    http://weblogs.asp.net/adweigert/archive/2007/10/10/powershell-try-catch-finally-comes-to-life.aspx

  • I've written about this in my TechNet Magazine column (technetmagazine.com, if you're interested).

    First, PowerShell v2 will have a standard Try...Catch, which is great.

    The existing shell (v1) has support for trap {} constructs. These must be defined prior to the exception happening. Also, most cmdlets require an -EA "STOP" parameter in order for them to generate a trappable exception. Traps can be defined in any scope, and will "bubble" up until trapped or until they hit the global (shell) scope.

    At the end of a trap, execute Continue to return to the next line of code in the same scope as the trap, or execute Break to leave the current scope and toss the exception up.

Help updating an event in Outlook 2007 with an iCalendar file

First of all: There is a previous thread with this question, but it looks dead. The guy that asked the question says he figured it out, and hints at an answer, but I could not get it to work. It doesn't seem like SO users have enough incentive to post to the old thread so I am starting this new one. I am sorry if this is not the right thing to do, but I don't think the question would be answered if I just posted a comment in the other thread :/

This is the problem. I have an ICS file. It validates. It looks like this:

BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//WA//FRWEB//EN
BEGIN:VEVENT
UID:FRICAL201
SEQUENCE:0
DTSTAMP:20081108T151809Z
DTSTART:20081109T121200
SUMMARY:11/9/2008 12:12:00 PM TRIP FROM JFK AIRPORT (JFK)
LOCATION:JFK AIRPORT (JFK)
END:VEVENT
END:VCALENDAR

I double-click it and it goes into Outlook 2007 perfectly. Then, I double-click another ICS file that looks like this:

BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//WA//FRWEB//EN
BEGIN:VEVENT
METHOD:REQUEST
UID:FRICAL201
SEQUENCE:1
DTSTAMP:20081108T161809Z
DTSTART:20081109T121300
SUMMARY:11/9/2008 12:13:00 PM TRIP FROM JFK AIRPORT (JFK)
LOCATION:JFK AIRPORT (JFK)
END:VEVENT
END:VCALENDAR

As explained in the rfc, the UID is the same and the sequence number is one greater, so I expect outlook to update my previous event entry, but all it does is insert a second one. How can I formulate the ICS file so that outlook knows to update the event? The original poster in the thread I referenced above said he got it to respond with METHOD and ORGANIZER but in my experience METHOD has no effect and ORGANIZER causes undesirable behavior where outlook wants to email the event to someone. I just want it to update the calendar.

From stackoverflow
  • I got a hold of Tom Carter, the guy who started the original thread. He had a working example with a request followed by a cancellation. What I had wrong was my METHOD was inside my VEVENT when it should have been outside. So here is a working update!

    Original:

    BEGIN:VCALENDAR
    VERSION:2.0
    PRODID:-//WA//FRWEB//EN
    METHOD:REQUEST
    BEGIN:VEVENT
    UID:FRICAL201
    SEQUENCE:0
    DTSTAMP:20081108T151809Z
    ORGANIZER:donotreply@test.com
    DTSTART:20081109T121200
    SUMMARY:11/9/2008 12:12:00 PM TRIP FROM JFK AIRPORT (JFK)
    LOCATION:JFK AIRPORT (JFK)
    END:VEVENT
    END:VCALENDAR
    

    Update:

    BEGIN:VCALENDAR
    VERSION:2.0
    PRODID:-//WA//FRWEB//EN
    METHOD:REQUEST
    BEGIN:VEVENT
    UID:FRICAL201
    SEQUENCE:1
    DTSTAMP:20081108T161809Z
    ORGANIZER:donotreply@test.com
    DTSTART:20081109T121300
    SUMMARY:11/9/2008 12:13:00 PM TRIP FROM JFK AIRPORT (JFK)
    LOCATION:JFK AIRPORT (JFK)
    END:VEVENT
    END:VCALENDAR
    

    All I did was add the request method (in the correct spot!), and an organizer.

  • So the only thing that is different between the Original and Updated is the Sequence number?

    I tried to do this but when I import, events are still added instead of being updated. I'm using Outlook 2003. Is that what causing this?

Visualization Tools for Huge Graphs

I would like to create a graph (set of vertices connected with edges) and I'm looking for tools or libraries that can help me.

The graph is composed of at least 1000 nodes. Although it may be a little ambitious, I'd like to create one that has 60k nodes.

Obviously the resulting graph is meant to be artistic more than functional. For example, I've seen graphics illustrating a huge graph of IP addresses (would be convenient if I could remember where I had seen it).

Any suggested software or libraries or frameworks?

From stackoverflow

When are API methods marked "deprecated" actually going to go away?

I'm code reviewing a change one of my co-workers just did, and he added a bunch of calls to Date.toMonth(), Date.toYear() and other deprecated Date methods. All these methods were deprecated in JDK 1.1, but he insists that it's ok to use them because they haven't gone away yet (we're using JDK 1.5) and I'm saying they might go away any day now and he should use Calendar methods. Has Sun actually said when these things are going away, or does "@deprecated" just mean you lose style points?

From stackoverflow
  • They're not going away. That said, they're usually deprecated because a) they're dangerous ala Thread.stop(), or b) there is a better or at least more accepted way to do it. Usually deprecated method javadoc will give you a hint as to the better way. In your case, Calendar is the recommended way to do this.

    While it's conceivable that they will be removed at some point in the future, I wouldn't bet on it. If anyone ever forks Java however, they'll probably be the first thing to go...

    Simon : care to elaborate, or justify your position?
    Simon : that's better :-)
  • If the deprecated methods went away, they could break existing code.

    While maintaining a clean API is important, the deprecated methods aren't getting in anyone's way. Sure, there are now better ways to do things, so new methods replace old ones. But there wouldn't be any gain made (besides a cleaner API) by getting rid of the old ones.

    Think of "deprecated" as meaning "outdated", but not necessarily "on the chopping block".

    jjnguy : I hope the core API doesn't use its own deprecated methods.
  • Well, "not gone yet" and "never going away" are two very different things. Thats the whole point of deprecation. They can go away with any future release. Using them is an at your own risk proposition. Just be aware that some future release of the JDK may leave your code in an unusable state.

  • Deprecated features features that are superseded and should be avoided. Although they remain in the JDK, they are discouraged as there are better methods available. The methods are left in the API to support backward compatibility, but should generally be avoided as they could be removed in future versions of the API.

    It is technically ok to use deprecated methods, but generally the reason it was deprecated in the first place was that a better/faster/cleaner API has been developed.

  • Sun tend to be extremely paranoid when it comes to changes that impact backwards compatibility, so I wouldn't expect to see the methods go away any time soon.

    But deprecated methods could go away at any time in the future, and are normally deprecated for a reason - either because they're unreliable, because they have unpleasant side effects, or simply because there's a better or more elegant way of doing things. The JavaDoc for the method will normally detail which of these is the case and what the acceptable way of carrying out the same operation is these days. Quite frequently the deprecated method will have been replaced with an implementation that calls the 'correct' method anyway, so you're just adding a level of indirection anyway.

    You'll also have plenty of compilation warnings if you use these methods, which could be reason enough to avoid them in itself...

  • Regarding the APIs, ... it is not specified they will be removed anytime soon.

    Incompatibilities in J2SE 5.0 (since 1.4.2):

    Source Compatibility

    [...]
    In general, the policy is as follows, except for any incompatibilities listed further below:

    Deprecated APIs are interfaces that are supported only for backwards compatibility. The javac compiler generates a warning message whenever one of these is used, unless the -nowarn command-line option is used. It is recommended that programs be modified to eliminate the use of deprecated APIs, though there are no current plans to remove such APIs – with the exception of JVMDI and JVMPI – entirely from the system.

    Even in its How and When To Deprecate APIs, nothing is being said about a policy regarding actually removing the deprected APIs...

    DoctaJonez : Even though they are unlikely to be removed, it is important to note why they have been deprecated. Usually it is because a method or class does not behave as expected in certain situations. This means that by using a deprecated method or class you risk introducing errors into your code.
  • I've definitely seen deprecated functions go away - from old versions of Java to the current (I started on 1.1, and some stuff distinctly DID NOT WORK in 1.4).

    Other languages handle deprecation differently - Python has been known in the past, for example, to remove deprecated functionality after just a release or two.

  • One problem is you'll see lots of compiler warnings about using deprecated methods. If you also use deprecations to gradually phase out your own code, the compiler warnings will get lost in the noise and lose significance.

  • I have a better recommendation: rather than telling him to use Calendar, you should switch to either JodaTime or JSR-310's pre-release version. Some methods on java.util.Date may be deprecated, but in my opinion the whole class should be deprecated, along with Calendar. The developers of JSR-310 seem to agree, although I doubt they'll ever bite the bullet and deprecate it.

    In no particular order, here's what's wrong with Date:

    • Its internal representation is milliseconds since the epoch; therefore, cannot represent dates before the epoch.

    • All of its useful methods (e.g. toString) first normalize the date according to the local timezone. When working with UTC Date instances, this can get really annoying; you're forced to use Calendar or you will make very bad errors.

    • Calendar. It just stinks. Might win the award for worst API ever.

    • Always represents an instant-in-time. No way to represent specific days, or specific years. No way to represent timezone-less dates values.

    • Has almost no useful methods. See e.g. JodaTime's fluent interface for doing date arithmetic.

    • Should have been named Datetime, considering that it is one.

What are the factors to decide between using Core Data versus rolling out a custom model?

There might be applications that are not suited for Core Data - image manipulation programs like Photoshop or Gimp for example. But for applications that are suited for Core Data, say Address Book or iCal, what is the criteria to choose Core Data over a custom model?

From stackoverflow
  • I recently started a project where I decided to use Core Data for the first time in a real world application. My application is actually version 2.0 of an older app that uses a custom data model, so I spent a lot of time debating this question. Here are some of the things I asked myself.

    • The time to learn how Core Data works in a non-trivial application and fixing the little bugs and idiosyncrasies that pop up when you're learning a new technology. This may include a prototype or two, since you don't want to jump into using something like Core Data that will be responsible for such as large chunk of your application.

    • Whether or not Core Data will solve problems that are hard to address when using a custom data model, for example storing and holding in memory very large sets of data.

    • Whether or not you want to share code with a platform where Core Data is not available, for instance Cocoa Touch. Along the same lines, if you want the resulting data files to be compatible without having to build a separate exporter.

    • If learning Core Data will help improve yourself as a programmer, whether its making your more attractive to Mac development shops or just for your own use.

    • If your data model is simple enough that you don't really need things like undo manager support or relationships, the areas where core data really shines.

    • If you're using external libraries or other technologies such as Distributed Objects, where you might not want to use NSManagedObject.

    1. Are you, for whatever reason, targeting a Mac OS X version before 10.4 as your minimum requirement? If so, no Core Data for you.
    2. Are you going to allow the user to manually order things in a list? If so, no Core Data for you—it doesn't allow ordered relationships. (Supposedly you can create a numeric “sequence” property that you can order by, but keeping that consistent sounds like a tremendous hassle.)
    3. Are you going to be working with a specific file format as your native format? (For example, TextEdit's native format is RTF.) If not, you won't be using Core Data for on-disk storage, so you may not want to use it at all. (You could, but I'm not sure there are enough other reasons.)
    Akbar ibrahim : I am not sure I understood the 3rd point correctly. I shouldn't be using Core Data if I have a native file format, correct?
    Peter Hosey : It's one point against it, yes. One reason *to* use Core Data is that it handles on-disk storage for you, so you don't need to make up a file format; the inverse of that is that if you already have a file format, you don't need Core Data to do it for you. But you may have other reasons to use it.

Coding style... error condition first or last?

Which is better in general in terms of the ordering? Do you put the fault condition at the top or bottom?

if (noProblems == true) {
    // do stuff
} else {
    // deal with problem
}

OR

if (noProblems == false) {
    // deal with problem
} else {
    // do stuff
}
From stackoverflow
  • i like to eliminate error cases first - and return from the function early so that the 'happy path' remains un-nested, e.g.

    if (some error condition)
    {
        //handle it
        return;
    }
    //implicit else for happy path
    ...
    

    if it is easy to identify the conditions leading to the happy path, then by all means put that clause first (thanks Marcin!)

    Patrick McElhaney : Good answer. This pattern is commonly known as a "guard clause."
    Marcin : Sorry, I can't agree with this at all. Please see my answer below.
    John Rudy : +1 for guard clauses.
    Rob Prouse : +1 for happy path :D
    Steven A. Lowe : @DLarsen: answer edited to reflect Marcin's advice also
  • if its 1 or 2 lines and an early return, I'd put it at the top -- especially if its at the start of the function. that almost reads like a contract. otherwise, I go with the "positive conditions before negative" rule.

  • It depends on what is clearer to you. I mean, what makes more sense, that noProblems has a true value or that it has a false value.

    For example for isDeviceEnabled() I would always check for a true result as "Enabled" has implicitly a positive value. For an implicit negative value we could check for example for "isMemoryAvailable()", maybe because you need to check only if there is no more room for new objects/arrays or other data.

  • It's a very individual sort of decision, but I tend to put my error conditions first, under the pretense of grouping like code together. That is, if I do something, and it fails, the check for that failure is really actually part of doing that something; if I put the check for failure and action based on that at the beginning of my code, I've grouped my action and the complex response to that action together (working on the assumption that a failure result is actually a more complex return case than a success).

  • The first seems slightly preferable to me in that it avoids a double negative in the conditional.

    Other than that, you've constructed things so that you can't really

    // do stuff
    

    after you

    // deal with problem
    

    so beyond that one seems as good as the other.

  • As with try/catch I do the normal flow, and then handle exception conditions.

    That doesn't mean error checking/scrubbing doesn't happen first, but that's if I don't trust what's been passed to me.

    e.g.,

    if (foo is null) then
        // bail
    end if
    
    if (bar == foo) then
        // foo hasn't been changed... print the regular report
    else
        // foo has changed, run the reconciliation report instead.
    end if
    

    I like the happy story to flow like a straight line, and the unhappy story to spin off onto its own spur.

  • Maybe this depends on language conventions, or other factors, but I feel that the nominal case should be at the top, and branches should contain the exceptional conditions. It makes the code much easier to read. This is especially true when there are many exceptional conditions, and in most cases there are. You'll be able to easily assume that the author expects this specific path to be taken most of the time, and understand the code easier this way.

    From "Code complete, 2nd edition" section 15.1:

    By putting the most common cases first, you minimize the amount of exception-case handling code someone has to read to find the usual cases. You improve efficiency because you minimize the number of tests the code does to find the most common cases.

    Patrick Huizinga : You might also want to read section 17.1, which says: "Use guard clauses (early returns or exits) to simplify complex error processing"
    Steven A. Lowe : i would agree in the case when it is easy to identify the conditions that lead to the happy path, will edit my answer to reflect your additional wisdom
  • Why not create one exit point from function and do proper cleanup there instead of having multiple returns...

    
    DWORD bRetVal= TRUE;
    if(foo is null) 
    {
       bRetVal = FALSE;
       goto Error;
    }
    else
    {
    // do something
    }
    
    Exit:
     return bRetVal;
    
    
    

How to override background color for WinForm minimize and maximize buttons

Is it possible to override the background color of the minimize and maximized buttons in WinForms?

From stackoverflow
  • Not without writting your own NC_PAINT which is very bad practice by itself.

    You never know when the user will use a new visual style never heard before. Your application will display the old ugly buttons over the existing style and everything will clash.

  • You cannot do it easily.

    The best option is: http://geekswithblogs.net/kobush/articles/CustomBorderForms3.aspx

    You can find more answers here: http://stackoverflow.com/questions/42460/custom-titlebarschrome-in-a-winforms-app

  • The short version is, out of the box, not that I'm aware of.

    The longer version is that there's nothing stopping you from creating a borderless form, then creating your own [minimize|restore]/maximize/close buttons on it. You'll have to draw your own form title bar, and basically take on all the magic of moving onscreen and such, but it's not impossible.

    Consider this article from Code Maverick as a starting point.

  • Hi there, i once tried to something similar. It took too much time, plus there are plenty of third party controls out there. I use the following Krypton Toolkit, its great and the toolkit is free.

  • I had a feeling it wouldn't be easy! Thanks for the responses.