Thursday, May 5, 2011

Text Field disabling in NetBeans

I want to ask if there is a way to make the text field active and inactive according to the radio button.

For example, the textfield will be inactive and when the user click on the radio button, the textfield will be active.

I am using Java language and NetBeans program

From stackoverflow
  • You could have two radio buttons for representing the active/inactive state. Add an action listener to each and when the 'active' one is pressed you call setEditable(true) on the JTextField and when the 'inactive' JRadioButton is called you call setEditable(false).

    JTextField textField = new JTextField();
    JRadioButton activeButton = new JRadioButton("Active");
    JRadioButton inactiveButton = new JRadioButton("Inactive");
    activeButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            textField.setEditable(true);
        }
    });
    inactiveButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            textField.setEditable(false);
        }
    });
    
    3yoon af : It is work .. Thank you for help ..
    willcodejavaforfood : No problems mate :)
  • neceito que cuando le oprima al boton....toda la informacion digitada en unos text.... sea cojida para hacer unas operaciones..podria ayudarme?

Writing AVI files in OpenCV

There example on the net and code given in Learn OpenCv,Orielly.

After many attempts the out.avi file is written with 0 bytes. I wonder where i went wrong.

The following are the code i used...

int main(int argc, char* argv[]) {
    CvCapture* input = cvCaptureFromFile(argv[1]);
    IplImage* image = cvRetrieveFrame(input);

    if (!image) {
        printf("Unable to read input");
        return 0;
    }


    CvSize imgSize;
    imgSize.width = image->width;
    imgSize.height = image->height;



    double fps = cvGetCaptureProperty(
            input,
            CV_CAP_PROP_FPS
            );

    CvVideoWriter *writer = cvCreateVideoWriter(
            "out.avi",
            CV_FOURCC('M', 'J', 'P', 'G'),
            fps,
            imgSize
            );


    IplImage* colourImage;
    //Keep processing frames...
    for (;;) {

        //Get a frame from the input video.
        colourImage = cvQueryFrame(input);
        cvWriteFrame(writer, colourImage);

    }

    cvReleaseVideoWriter(&writer);
    cvReleaseCapture(&input);

}
From stackoverflow
  • Maybe you could try inserting a printf("Frame found\n") inside the for(;;) to see if it is actually capturing frames. Or even better:

    if(colourImage == NULL) {
        printf("Warning - got NULL colourImage\n");
        continue;
    }
    cvNamedWindow( "test", 1);
    cvShowImage( "test", colourImage );
    cvWaitKey( 0 );
    cvDestroyWindow( "test" );
    

    Then see if you get any windows, and if they contain the right contents.

  • My bet is that cvCreateVideoWriter returns NULL. Just step through it to see if it's true. In that case, the problem is probably with CV_FOURCC(..) which doesnt find the codec and force a return 0;

    you can try using -1 instead of CV_FOURCC. There is gonna be a prompt during runtime for you to chose the appropriate codec

    : Thanks Eric you are right
  • I've a problem under MacOs 10.4. When I try to execute this row

    CvVideoWriter *writer = cvCreateVideoWriter(
                "out.avi",
                CV_FOURCC('M', 'J', 'P', 'G'),
                fps,
                imgSize
                );
    

    i've this problem:

    OpenCV ERROR: Internal error (Cannot create data reference from file name) in function icvCreateVideoWriter, cvcap_qt.cpp(1291) Terminating the application...

    any idea?

    Eric : if you have another problem please make a separate question
  • When i google this problem i meet an answer: "OpenCV on mac os x don`t support avi write until it will be compiled with a ffmpeg"

    For me seem to wrok this solution http://article.gmane.org/gmane.comp.lib.opencv/16005

    You need to provide the full path to the file with the movie in cvCreateVideoWriter. I don't know whether it's only an Mac OS X port issue, but might be, since QTNewDataReferenceFromFullPathCFString from the QT backend is used.

  • Friends I faced the same problem; the methods suggested by Eric does work. The problem, i think lies with the availability of the codecs. Thanks to all of you....

  • Hi ,

    I have the following code , and NONE of the functions are returning NULL, so I guess everything is proper.

    But still the file size of the test.avi file is 0 bytes

            CvCapture *pCapturedImage = cvCreateCameraCapture(0); // get the default camera, for me it is a webcam
    

    // Get the avi file name CString strFileName = objFileDlg.GetPathName()+".avi"; // test.avi

            int isColor = 1;
            int fps     = 25;  // or 30
            int frameW  = 640; // 744 for firewire cameras
            int frameH  = 480; // 480 for firewire cameras
            CvVideoWriter *pVideoWriter = cvCreateVideoWriter(strFileName.GetBuffer(),
    

    -1, // I am choosing the uncompressed format** fps,cvSize(frameW,frameH),isColor);

    // pVideoWriter does not return NULL , that means its succesful

            cvNamedWindow("mainWin",CV_WINDOW_AUTOSIZE);
            IplImage *pImage = 0;
    
            int nFrames = 50;
            for(int i=0;i<nFrames;i++)
            {
                  cvGrabFrame(pCapturedImage);          // capture a frame
                  pImage=cvRetrieveFrame(pCapturedImage);  // retrieve the captured frame
                  cvWriteFrame(pVideoWriter,pImage);      // add the frame to the file
    
                  cvShowImage("mainWin",pImage);     // NO IMAGE SHOWS UP
                  cvWaitKey(20);
    
            }
    
            cvDestroyWindow("mainWin");
            cvReleaseVideoWriter(&pVideoWriter);
    

    Please let me know what am I missing out.

    Thanks, Sujay

  • hey This code works in DevC++ try it:

      #include<cv.h>
      #include<highgui.h>
      #include<cvaux.h>
      #include<cvcam.h>
      #include<cxcore.h>
    
      int main()
      {
      CvVideoWriter *writer = 0;
      int isColor = 1;
      int fps     = 5;  // or 30
      int frameW  = 1600; //640; // 744 for firewire cameras
      int frameH  = 1200; //480; // 480 for firewire cameras
      //writer=cvCreateVideoWriter("out.avi",CV_FOURCC('P','I','M','1'),
      //                           fps,cvSize(frameW,frameH),isColor);
      writer=cvCreateVideoWriter("out.avi",-1,
                           fps,cvSize(frameW,frameH),isColor);
      IplImage* img = 0; 
    
      img=cvLoadImage("CapturedFrame_0.jpg");
      cvWriteFrame(writer,img);      // add the frame to the file
      img=cvLoadImage("CapturedFrame_1.jpg");
      cvWriteFrame(writer,img);
      img=cvLoadImage("CapturedFrame_2.jpg");
      cvWriteFrame(writer,img);
      img=cvLoadImage("CapturedFrame_3.jpg");
      cvWriteFrame(writer,img);
      img=cvLoadImage("CapturedFrame_4.jpg");
      cvWriteFrame(writer,img);
      img=cvLoadImage("CapturedFrame_5.jpg");
      cvWriteFrame(writer,img);
    
      cvReleaseVideoWriter(&writer);
      return 0;
      }
    

    I compiled it and ran it, works fine. (I did not see above whether you got your answer or not .. but for this particular thing I worked very hard earlier and suddenly I just did it, from some code snippets.)

  • This code worked fine:

    cv.h highgui.h cvaux.h cvcam.h cxcore.h

    int main(){

    CvVideoWriter *writer = 0;
    int isColor = 1;
    int fps     = 5;  // or 30
    IplImage* img = 0; 
    img=cvLoadImage("animTest_1.bmp");
    int frameW  = img->width; //640; // 744 for firewire cameras
    int frameH  = img->height; //480; // 480 for firewire cameras
    
    writer=cvCreateVideoWriter("out.avi",-1,
     fps,cvSize(frameW,frameH),1);
    
    cvWriteFrame(writer, img);      // add the frame to the file
    
    char *FirstFile,fF[20]="",*fileNoStr,fns[4]="";
    fileNoStr=fns;
    for(int fileNo;fileNo<100;fileNo++){
     FirstFile=fF;   
     itoa(fileNo,fileNoStr,10);
     FirstFile=strcat ( FirstFile,"animTest_");
     FirstFile=strcat ( FirstFile,fileNoStr);
     FirstFile=strcat ( FirstFile,".bmp");
    
     printf(" \n%s .",FirstFile);
     img=cvLoadImage(FirstFile);
    
     cvWriteFrame(writer, img);
    
    }
    cvReleaseVideoWriter(&writer);
    
    return 0;
    

    }

  • I think the problem you're encountering is that your "for" loop never ends; therefore, "cvReleaseVideoWriter(&writer);" and "cvReleaseCapture(&input);" never get called. Try something like "for(int i=0; i<200; i++)" and see if you end up with a working video.

    Often video is written to a temporary files before being finalized on disk. If your file isn't finalized, there won't be anything to see.

    Hope that helps.

Relational Database Options that work with .Net framework aside SQL (Possibly using Linq)?

Exactly what the title says...........any thoughts on other good options for relational database implementation aside from SQL Server DB's.

It's necessary for the .Net Framework to be able to communicate with it also.

From stackoverflow
  • Oracle, Postgres, MySql... the list goes on...

    .NET has native libraries for communicating with SqlServer but you can connect to any DB that has ODBC/OLEDB Support under windows.

  • Depending on what you need it to do, you could use Oracle, Firebird SQL, SQLite, MySQL, BerkeleyDB or a good few others.

  • Plenty of those: Firebird, PostgreSQL, SQLite, MySQL to name a few.

    Don't know about LINQ support over there, though.

methods with the same soapaction

Hi,

I'm doing contract-first development of a SOAP server. The wsdl declares the same soapAction for several methods. Now svcutil produces code that declares the same value for the OperationContractAttribute.Action property of several methods. This causes a runtime error which says that every operation must have a unique action value.

How can I solve this? When I change the value of the Action property my server no longer accepts requests from clients.

Update
It turns out that the soapaction has to be unique if the routingstyle is set to soapaction, which is the default. So I tried setting it to RequestElement. Unfortunately, this causes the server to no longer recognize the client's messages. I had hoped that the Routingstyle would only change the server's internal behavior.

Any tips would be highly appreciated.

Thanks, regards, Miel.

From stackoverflow
  • There is no solution for this in WCF.

    Trying to change the routingstyle as I did, applies to ASMX, not WCF.

    A workaround may be possible, but there's no standard solution.

How can i use ' when - between ' statement in sql?

This query gives me syntax error in when-between line. how can i solve them?

alter FUNCTION [dbo].[fn_GetActivityLogsArranger]
(
@time AS nvarchar(max)
)

RETURNS  nvarchar(max)
AS
BEGIN
declare @Return varchar(30)

select @Return = case @time
when between '15:00' and '15:30' then '15:00-15:30'
when between '15:30' and '16:00' then '15:30-16:00'
when between '16:00' and '16:30' then '16:00-16:30'
when between '16:00' and '16:30' then '16:00-16:30' 
when between '16:30' and '17:00' then '16:30-17:00' 
when between '17:00' and '17:30' then '17:00-17:30' 
when between '17:30' and '18:00' then '17:30-18:00'
else 'Unknown'
 Return @Return
end
From stackoverflow
  • You can't use that format of the case syntax. You will have to do a case which does checks:

    select @Return = case 
    when @time between '15:00' and '15:30' then '15:00-15:30'
    when @time between '15:30' and '16:00' then '15:30-16:00'
    when @time between '16:00' and '16:30' then '16:00-16:30'
    when @time between '16:00' and '16:30' then '16:00-16:30' 
    when @time between '16:30' and '17:00' then '16:30-17:00' 
    when @time between '17:00' and '17:30' then '17:00-17:30' 
    when @time between '17:30' and '18:00' then '17:30-18:00'
    else 'Unknown' END
    
    Return @Return
    

    Also, you were missing an END at the end of your case statement (see END in uppercase above).

  • Well for starters you need to pass your @variable in each when statement

    select @Return = case 
    when @time between ('15:00' and '15:30') then '15:00-15:30'
    when @time between ('15:30' and '16:00') then '15:30-16:00'
    when @time between ('16:00' and '16:30') then '16:00-16:30'
    when @time between ('16:00' and '16:30') then '16:00-16:30' 
    when @time between ('16:30' and '17:00') then '16:30-17:00' 
    when @time between ('17:00' and '17:30') then '17:00-17:30' 
    when @time between ('17:30' and '18:00') then '17:30-18:00'
    else 'Unknown'
    
  • alter FUNCTION [dbo].[fn_GetActivityLogsArranger]
    (
        @time AS varchar(30)
    )
    RETURNS  
    varchar(30)AS
    BEGIN
    declare @Return varchar(30)
    select @Return = case 
    when @time between '15:00' and '15:30' then '15:00-15:30'
    when @time between '15:30' and '16:00' then '15:30-16:00'
    when @time between '16:00' and '16:30' then '16:00-16:30'
    when @time between '16:00' and '16:30' then '16:00-16:30' 
    when @time between '16:30' and '17:00' then '16:30-17:00' 
    when @time between '17:00' and '17:30' then '17:00-17:30'
    when @time between '17:30' and '18:00' then '17:30-18:00'
    else 'Unknown' 
    end
    Return @Return
    end
    
    Mitch Wheat : would downvoter mind leaving a comment please. Thanks
    Phsika : Thank alot. you are correct. Look please another ques.http://stackoverflow.com/questions/829089/how-to-call-user-defined-function-in-order-to-use-with-select-group-by-order-by
  • You need to have the variable in each WHEN clause eg.

    case 
        when @time between '15:00' and '15:30' then '15:00-15:30'
        when @time between '15:30' and '16:00' then '15:30-16:00'
    
  • case syntax : CASE WHEN Boolean_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ] END

  • You should not use this function, you should have a table or table valued function of time buckets so you can do a pure join against it. See my other post for an example. The join will outperform by far the approach of calling your function on a row set.

How to refactor these 2 similar methods into one?

Hello,

I've seen some samples of using 'T' to make a method reuseable for generic collections of different classes, but I've never really gotten into it or understood the samples.

I wonder if it would be possible to put the 2 methods below into one and what the downsides of doing this would be (performance-wise).

Anyone?

        [NonAction]
        public List<SelectListItem> ToSelectList(IEnumerable<Department> departments, string defaultOption)
        {
            var items = departments.Select(d => new SelectListItem() { Text = d.Code + " - " + d.Description, Value = d.Id.ToString() }).ToList();
            items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" });
            return items;
        }

        [NonAction]
        public List<SelectListItem> ToSelectList(IEnumerable<Function> functions, string defaultOption)
        {
            var items = functions.Select(f => new SelectListItem() { Text = f.Description, Value = f.Id.ToString() }).ToList();
            items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" });
            return items;
        }


SOLUTION

The solution that I used:

usage

var departmentItems = departments.ToSelectList(d => d.Code + " - " + d.Description, d => d.Id.ToString(), " - ");
var functionItems = customerFunctions.ToSelectList(f => f.Description, f => f.Id.ToString(), " - ");

with

 public static class MCVExtentions
    {
        public static List<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, string> text, Func<T, string> value, string defaultOption)
        {
            var items = enumerable.Select(f => new SelectListItem() { Text = text(f), Value = value(f) }).ToList();
            items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" });
            return items;
        }
    }
From stackoverflow
  • The old school way would be to create a common interface for both Department and Function:

    interface A
    {
    int ID{get;}
    string Description{get;}
    }
    

    You implement Description on Department to return d.Code + " - " + d.Description. and write the function to use this interface instead of concrete classes:

    [NonAction]
        public List<SelectListItem> ToSelectList(IEnumerable<A> as, string defaultOption)
        {
            var items = as.Select(a => new SelectListItem() { Text = a.Description, Value = a.Id.ToString() }).ToList();
            items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" });
            return items;
        }
    

    EDIT: Regarding using generics, its not going to help much in this case, because

    • the objects you are passing needs to implement Id and Description
    • you are not returning these objects, so in this respect you don't have to care about type safety of generics
    Thomas Stock : Ofcourse! Thanks. I was too stuck thinking about those samples with 'T' that I didn't realize an interface was all I needed. Thanks a lot.
    Svish : I would say using generics and functions would be a better thing to do in this case. Then you don't have to force a bunch of classes into implementing an interface. You might want to use that ToSelectList function on a class that does not have an ID or Description, and where adding it would be not very logical (or for example the Description property should really be called something else).
    Thomas Stock : Thanks Svish. Good point.
  • In fact you can do it with a combination of generics and functions, something along the lines of this (untested may not even compile).

    [NonAction]
    public List<SelectListItem> ToSelectList<T>(IEnumerable<T> en, 
                                                Function<string, T> text, 
                                                Function<string, T> value, 
                                                string defaultOption)
    {
        var items = en.Select(x => new SelectListItem() { Text = text(x) , Value = value(x) }).ToList();
        items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" });
        return items;
    }
    

    Then you can dispatch to it with the appropriate lambda functions (or call directly).

    [NonAction]
    public List<SelectListItem> ToSelectList(IEnumerable<Department> departments, 
                                             string defaultOption)
    {
        return ToSelectList<Department>(departments, d =>  d.Code + '-' + d.Description, d => d.Id.ToString(), defaultOption);
    
    }
    
  • Without implementiong a common interface like @Grzenio suggested, you could use a generic method like this:

        public List<SelectListItem> ToSelectList<T>(IEnumerable<T> enumerable, Func<T, string> text, Func<T, string> value, string defaultOption)
        {
            var items = enumerable.Select(f => new SelectListItem() { Text = text(f), Value = value(f) }).ToList();
            items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" });
            return items;
        }
    
        // use like
    
        t.ToSelectList(departments, d => d.Code + " - " + d.Description, d => d.Id.ToString(), "default");
        t.ToSelectList(functions, f => f.Description, f => f.Id.ToString(), "default");
    
    Thomas Stock : Thanks! This was what I was looking for in the first place. I'll try to implement yours and see if I like working with it
    Motti : Hey my answer is identical and posted three minutes before this answer yet this answer gets 3 votes and mine zero! OK I'll up-vote it anyway, if only for having the generic parameters for Function in the right order...
    idursun : ToSelectList can also be made an extension method.
    Thomas Stock : I'm sorry Motti, but I found your answer to be less clear. I immediatly understood bruno's post because of the usage examples. Will upvote yours now.
    Thomas Stock : I implemented this with an extension method and it looks and feels great! thanks for the help, everybody.

Email to IM gateway, and other ways to send Instant Messages programmatically.

It's very easy to send an email programmatically. For example, in Perl you can do this:

open(MAIL, "|/usr/sbin/sendmail -oi -t") or die;
print MAIL "From: ...\n";
print MAIL "To: ...\n";
print MAIL "Subject: ...\n";
print MAIL "\n";
print Mail "... body ...";
close(MAIL);

I'd like to collect simple, self-contained snippets of code for programmatically sending an instant message (IM) in various languages (especially Perl) and for various protocols (especially jabber/gmail and AIM and Yahoo). See this question for a failed attempt in Perl for gchat: http://stackoverflow.com/questions/799648/error-using-perl-jabber

Or of course if there were an email-to-IM (instant message) gateway then sending an IM would be as easy as email. Perhaps no such thing exists but if anyone makes one, this would be a good place to point to it!

(Keywords to make this question more searchable: email, IM, instant messaging, jabber, xmpp, AIM, yahoo messenger, gmail, gchat, msn.)

PS: It's been over a year now and I suspect these answers are a little stale. Is there a better way to encourage updated answers besides re-asking the question?

From stackoverflow
  • You would need to have an account on the various IM networks, then find an API that can use the account and send messages on that network programmaticly.

    One multi-network library is libpurple (its used by the AdiumX and Pidgin IM clients), there appears to be a couple language bindings to the library:

    A quick search on Google gave me the impression of the availability of bindings for Python and Perl also.

  • Instant Messaging and Email are two different modalities, so you would need to have a custom gateway. This is how I would imagine it would work:

    1. You would create a bot using an API for a particular network: http://dev.aol.com/aim/bots for AOL.
    2. The bot would run as a service and be signed in and would receive emails.
    3. The bot would then create an Instant Messaging conversation with the target and send the message off.
    dreeves : Thanks; smart. I'm holding out hope that I can get something off the shelf to do this. Snippets of code for sending IMs in various protocols would also suffice for me.
  • I think your best bet is to take a look at an open source project and use their code! It saves you the trouble of having to code up each IM provider independently and you know you're getting a tested code base. Win Win!

    Take a look at pidgin it's an open source IM that supports AIM, Google Talk, IRC, MSN, ICQ, Yahoo! and others. And here's their source code information, I believe it is written in C, so you should have no problems interfacing it with Perl.

    dreeves : Has anyone used the libpurple code to make a command line utility to send IMs? That would solve my problem.
  • There is http://sendxmpp.platon.sk/ -- something like sendmail, but for xmpp. Then, from xmpp, you can set up transports for other IM networks.

    I guess this is the simplest method here. However if your program is more like a daemon, sendxmpp will be very slow -- and you'll benefit more from using a proper xmpp library.

  • Or of course if there were an email-to-IM (instant message) gateway then sending an IM would be as easy as email. Perhaps no such thing exists but if anyone makes one, this would be a good place to point to it!

    I'd turn this around - you don't need an email-to-IM gateway as much as you need an interface which sends 'a message' to 'an endpoint' where the endpoint would encode both the user's address and the means (possibly several, with fallbacks) of delivery. Thus, you'd be wrapping up several sending mechanisms (in Perl, pre-existing CPAN modules) with an interface that decides which mechanism to use. Thus all your snippets would end up brought together in a single CPAN module and other people would use it directly.

    While an email-to-IM gateway does solve the problem, who administrates it? If it's on the net somewhere, it's an independent point of failure (and one that sounds ripe for spam forwarding, so it wouldn't be around for long); if it's you, it's a separate component, and one that you'd probably find annoying when you got to the stage of testing your applications.

    dreeves : Excellent points; thanks! Love the meta-CPAN-module idea. Anyone?
    1. I know of a stealth mode startup working on an appliance that does exactly what you seek. It will sell in the $30K range.

    2. You will need an account for each of the IM networks.

    3. The appliance will have the additional capability of receiving IM replies and forwarding back via email.

    Unknown : Are you serious? Amazingly I have code to do this. If I can really sell it for $30k, I guess I should just keep it to myself instead of posting the answer here.
    dreeves : I'll give you 550 reputation points for it. :) I suppose I'd throw in some actual money too, but not thousands of dollars.
  • I know that ColdFusion's latest (and upcoming) version include a SMS Gateway for doing what you seek, but not in the languages that you are looking for. I'll see if I can find out more information for you and try to point you in the right direction. Cheers!

    Kevin Bomberry : Ah, I just remembered that I think I have a bit of code somewhere that has all of the telecom's SMS total length and email to SMS filters. Using this you can trim your message to the length, then send an email to the phone-number/email address and it gets delivered as an SMS (EX. 18005551212@mycinglarwireless.com). If you 'd like I can look for the file or find a posting for you on line and send you a link. Cheers!
    dreeves : As you noted, I was asking about IM rather than SMS. But that sounds extremely useful as well; I'd love to see that.
    Kevin Bomberry : @dreeves: Here's a short list for you: Carrier/Max-chars/email Alltel/300/10-digit-number@message.alltel.com AT&T Wireless/160/10-digit-number@mmode.com Boost Mobile/500/10-digit-number@myboostmobile.com Cingular/150/10-digit-number@mobile.mycingular.com OR 10-digit-number@cingularme.com Metrocall/80-200 depending on plan/10-digit-number@page.metrocall.com Nextel/140/10-digit-number@messaging.nextel.com Sprint PCS/160/10-digit-number@messaging.sprintpcs.com T-Mobile/140/10-digit-number@tmomail.net Verizon/160/10-digit-number@vtext.com Virgin Mobile USA/160/10-digit-number@vmobl.com
  • Here's CPAN modules for all the networks you requested.

    XMPP/Jabber/Google Talk:

    AOL Instant Messanger:

    MSN Messenger:

    Yahoo Messenger:

    dreeves : Thanks! This is the best answer so far. I had tried Jabber::SimpleSend to no avail. I'll try these.
    fiXedd : Thanks, I don't have a lot of experience with these, so I don't have a lot of code examples to offer. Hopefully their docs will prove useful.
  • I was going to add a comment onto fiXedd, but here's some actual sample Perl NET:AIM code from about 10 years ago.

    http://pedram.redhive.com/code/pedbot/

Quartz repeat execution 5 times every day

Hi, I am using quartz to schedule my jobs, I need to execute a job at 2:00am every day and repeat the execution 5 times every 10 minutes, any ideas? the result should be: 2:00 2:10 2:20 2:30 2:40

Thanks in advance.

From stackoverflow
  • I would look at the Quartz CronTrigger, and particularly the usage of / to specify every 'n' minutes/hours whatever.

    I think you would need

    0 0,10,20,30,40 2 * * ?
    

    to fire at 2am and then 2.10am-2.40am every 10 minutes.

  • Just specify the schedule times as a cron string for the CronTrigger like this:

    0 0,10,20,30,40 2 * * *
    
  • A simple solution would be to simply have 5 tasks, one for every 10 minutes.

  • Use a CronTrigger with a cron expression that describes the exact times you want it run. For every day at 2:00, 2:10, 2:20, 2:30, 2:40, use:

    0 0,10,20,30,40 2 * * ?
    

List a dictionary

In a list appending is possible. But how I achieve appending in dictionary?

    Symbols from __ctype_tab.o:
Name                  Value   Class        Type         Size     Line  Section
__ctype             |00000000|   D  |            OBJECT|00000004|     |.data
__ctype_tab         |00000000|   r  |            OBJECT|00000101|     |.rodata

Symbols from _ashldi3.o:
Name                  Value   Class        Type         Size     Line  Section
__ashldi3           |00000000|   T  |              FUNC|00000050|     |.text

Symbols from _ashrdi3.o:
Name                  Value   Class        Type         Size     Line  Section
__ashrdi3           |00000000|   T  |              FUNC|00000058|     |.text

Symbols from _fixdfdi.o:
Name                  Value   Class        Type         Size     Line  Section
__fixdfdi           |00000000|   T  |              FUNC|0000004c|     |.text
__fixunsdfdi        |        |   U  |            NOTYPE|        |     |*UND*

How can I create a dictionary like:

dictOfTables {'__ctype_tab.o':{'__ctype': Name:...,Value:...,Class:...,Type:...,Size:...,Line:...,Section:...}} etc.

for the above text?

From stackoverflow
  • Look into using an ordered dictionary. I don't think this is in official Python yet, but there's a reference implementation available in the PEP.

  • Appending doesn't make sense to the concept of dictionary in the same way as for list. Instead, it's more sensible to speak in terms of inserting and removing key/values, as there's no "end" to append to - the dict is unordered.

    From your desired output, it looks like you want to have a dict of dicts of dicts, (ie {filename : { symbol : { key:value }}. I think you can get this from your input with something like this:

    import re
    
    header_re = re.compile('Symbols from (.*):')
    
    def read_syms(f):
        """Read list of symbols from provided iterator and return dict of values"""
        d = {}
        headings=None
        for line in f:
            line = line.strip()
            if not line: return d  # Finished.
    
            if headings is None:
                 headings = [x.strip() for x in line.split()]
                 continue # First line is headings
    
            items = [x.strip() for x in line.split("|")]
            d[items[0]] = dict(zip(headings[1:], items[1:]))
        return d
    
    f=open('input.txt')
    d={}
    for line in f:
        m=header_re.match(line)
        if m:
            d[m.group(1)] = read_syms(f)
    
    flight : The final dict would look like this: {'_ashrdi3.o': {'__ashrdi3': {'Section': '.text', 'Value': '00000000', 'Line': '', 'Type': 'FUNC', 'Class': 'T', 'Size': '00000058'}}, '_ashldi3.o': {'__ashldi3': {'Section': '.text', 'Value': '00000000', 'Line': '', 'Type': 'FUNC', 'Class': 'T', 'Size': '00000050'}}, '_fixdfdi.o': {'__fixdfdi': {'Section': '.text', 'Value': '00000000', 'Line': '', 'Type': 'FUNC', 'Class': 'T', 'Size': '0000004c'}, '__fixunsdfdi': {'Section': '*UND*', 'Value': '', 'Line': '', 'Type': 'NOTYPE', 'Class': 'U', 'Size': ''}}}

How do i secure a web server's image upload directory ?

For my web application, people can upload images from a web form to my web server.

What should I set the CHMOD settings for that image upload directory so that people can upload images (from the web server) to that directory but not execute any files they upload for security reasons.

Would the chmod settings be? :

chmod 744 directory/
From stackoverflow
  • Chmod on the directory can't do this, and moreover your web server may interpret .php as executable no matter what the mode is. You'll probably want to specify what server you're using, there may be a .htaccess or similar directive you can use.

    Note that 'execute' on directories means 'can access files inside the directory', so that must be set if you want your web server to have access to the files inside...

  • There are two possible meanings for "executable" in this context, and both are things you need to configure against.

    1. An executable binary file that may run from the command line by typing the file's name into a shell

    2. A file that may be read and processed as script by a web server.

    Handling binary-executable

    To configure against case 1 on a un*x system, you need to ensure that your upload directory, and files therein, are owned by the web server user and only readable by that user. The directory must be executable; this means that the files inside that directory can be accessed). If the web user needs to list the files in the directory, it must also be readable. It, of course, must also be writable to allow new files to be created.

    Thus the octal set you want would be

    chown <web-server-user> <upload-dir>
    chmod 0700 <upload-dir>
    

    The files must not be executable and should only be readable and writable by the web server,so these should be

    chmod 0600 <uploaded-file>
    

    Please note that this means that only the web server user will be able to see these files. This is the best situation for security. However, if you really do need other local users to be able to see these files,then use

    chmod 0755 <upload-dir>
    chmod 0644 <uploaded-file>
    

    Handling web-server excutable

    Coding against case 2 is web server specific.

    One option is to place the upload directory outside of the webroot, dissalowing direct URL access to the uploaded files completely and only to serve them via server-side code. Your code reads and echoes the file content, thus ensuring it is never processed as script by the web server

    The other option is to configure your web server to not allow script processing of files in the upload directory. This configuration is web-server specific. However, for example, in Apache you can achieve this this by entering into your server configuration:

    <Directory "path-to-upload-dir">
      AllowOverride None
      Options -ExecCGI
    </Directory>
    

    AllowOverride None is important, as it stops anyone uploading a .htaccess file to your uploads directory and re-configuring the web server permissions for that directory.

Exclusionary Set Syntax with Linq, VB

I'd like to do a subtraction of sets based on criteria. A pseudo-query would look like:

select table1.columnn1
      ,table1.column2
  from table1, table2
 where (table1.column1.value1 not in table2.column1
        and
        table1.column2.value2 not in table2.column2)

I can make it to about here:

dim list = From tbl1 In table1 Where tt.column1 ...

And from there I don't know what to do.

From stackoverflow
  • Have a look at the Except standard query operator in LINQ. This produces the set difference of two sequences.

    http://msdn.microsoft.com/en-us/library/system.linq.enumerable.except.aspx

    You might also use the Contains operator to achieve what you want, as per the sample below:

    dim table2Col1 = from t in table2 select t.column1
    dim table2Col2 = from t in table2 select t.column2
    
    dim results = _
       from t in table1 _
       where not table2Col1.Contains(t.column1) _
       and  not table2Col2.Contains(t.column2) _
       select new with { .column1=t.column1, .column2=t.column2 }
    
    hypoxide : Thanks much, you definitely steered me in the right direction.

Delphi - Invalid namespace URI in IXMLNode

I am trying to parse a response from a SOAP web service, but part of the data has an invalid xmlns element and I think it is causing me no end of trouble.

The part of the XML that I am working with is as follows.

<soap:Body xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <ResponseData xmlns="http://www.example.com/WebServices/Schemas/1">
     <ResponseDataResult>
      <Messages xmlns="http://www.example.com/WebServices/Schemas/2">
       <Message>...</Message>
      </Messages>
     </ResponseDataResult>
     ...
    </ResponseData>
</soap:Body>

The xmlns URI in the soap:Body node is OK, its the one in ResponseData that is invalid, it points to a none existent document. It should be noted that the web service is not under my control so fixing this is out of the question :(.

my Delphi (2007) code look, at present, something like this.

var l_tmp,l_tmp2,FSOAPBody:IXMLNode;

begin
    ...

    FSOAPBody := FSOAPEnvelope.ChildNodes.FindNode('Body','http://schemas.xmlsoap.org/soap/envelope/');
    //returns the xml above.
    if (FSOAPBody = nil) then exit;

    l_tmp := FSOAPBody.ChildNodes.FindNode('ResponseData','');
    if (l_tmp = nil) or (not l_tmp.HasChildNodes) then exit;

    l_tmp2 := l_tmp.ChildNodes.FindNode('ResponseDataResult','');

    ...
end;

In the above code, I have had to add the blank namespace url to the FindNode('ResponseData','') code as with out it, it will not find anything and returns nil, with it however it reutrns the expected XML.

The problem is that the next find node (ChildNodes.FindNode('ResponseDataResult','')) raises an access violation when trying to access the ChildNodes of l_tmp, I can look at the xml using l_tmp.xml and see that it is the XML I would expect.

I suspect that it is due to the missing namespace, so I have tried to remove it, but get more errors saying it is a read-only attribute.

Is there anyway to remove the xmlns attribute or select nodes regardless of there NS? or am I going about this wrong?

From stackoverflow
  • It is not expected that all namespace URIs refer to actual resources. They are used primarily as unique identifiers so XML from multiple sources can use the same names without interfering with each other. They are not required to point to the schema that describes the valid element and attribute values for the namespace; XML doesn't even require that such a schema exist.

    If you want to search for elements without regard for namespace, then call the one-argument version of FindNode.

    l_tmp := FSOAPBody.ChildNodes.FindNode('ResponseData');
    

    The two-argument version requires a namespace, and when you specify an empty string, it means you're requesting only nodes that have empty namespaces. Since you apparently know what the namespace is, you could call the two-argument version anyway, just like you used it to get the body element:

    l_tmp := FSOAPBody.ChildNodes.FindNode('ResponseData',
               'http://www.example.com/WebServices/Schemas/1');
    

Generating tests from run-time analysis

We have a large body of legacy code, several portions of which are scheduled for refactoring or replacement. We wish to optimise parts that currently impact on the user-experience, facilitate reuse in a new product being planned, and hopefully improve maintainability too.

We have quite good/comprehensive functional tests for an existing product. These are a mixture of automated and manually-driven GUI tests, but they can take a developer more than half a day to run fully. The "low-level domain logic" has a good suite of unit tests (NUnit) with good coverage. Unfortunately, the remainder of the code has no unit tests (or, at least, no worthy unit tests).

What I'd like to find is a tool that automatically generates unit tests for specific methods/classes and maybe specific interfaces based on their use and behaviour in the functional tests. These unit tests would be invaluable for refactoring, and would also be run as part of our C.I. system to detect regressions much earlier than is currently happening (and to localise regressions much better than "button X doesn't work.").

Do any such tools exist? Do you have any recommendations for me?

I've come across Parasoft .TEST, which looks like it might do want I want. Do you have any comments on that, with respect to my situation?

I don't think something that just generates test code from a static analysis, ala NStub, is useful here. I suppose it is actually the generation of representative test data that is really important.

Please ignore the merits, or lack of, of automated test generation - it is not something I'd usually advocate. (Not least because you get tests that pass for broken code!)

From stackoverflow
  • Well, you could look at PEX - but I believe that invents its own data (it doesn't watch your existing tests, AFAIK).

  • Try Pex:

    Right from the Visual Studio code editor, Pex finds interesting input-output values of your methods, which you can save as a small test suite with high code coverage. Pex performs a systematic analysis, hunting for boundary conditions, exceptions and assertion failures, which you can debug right away. Pex enables Parameterized Unit Testing, an extension of Unit Testing that reduces test maintenance costs.

Small Windows Form Chat application ideas?

I have a small application that I am building a Chat application into, so far I have the functionality to post messages!

I don't need a login as there will only be a small number of users and I will use their windows username for identification.

Has anyone done anything similiar? What else do I need to add? It doesn't need to be all singing and dancing as it is just for use within a small development team.

Any ideas would be great!

Thanks

From stackoverflow
  • Couple Thoughts:

    1. System Tray Icon, easily hidden/restored, etc.
    2. Since you have the Windows Accounts, send them an email (if you have exchange/ad email integration), if they're offline.
    3. Auto-start on windows startup
    4. Click-once / Auto Update
    5. Web-based and/or Mobile-based versions.
    6. Copy/Paste (with ability to paste images)
    7. Not sure if it is useful, but it'd be cool: sending a message to a given "bot" ... fake username... such as a Distribution Group Name, sends an email to the Distribution Group and then emails sent to that distribution group get posted to that conversation
    8. "Show other user my screen" -> mini screen-cap, etc.
    9. Source-Control / Bug-Tracking Aware.

    Just some random thoughts, let me know how it turns out.

  • filesharing, webcam, auto away, timestamp!(this is where Live Messenger fails big time ;)

  • Chat Histoty ;)

    SSL enabled communication

    Requirement : It should not add unnecessary vulnerabilities to the system, Since it a related with Windows Authentication + There are open ports So there is a good chance of going something wrong.

    • searchable chat history - searchable from the desktop search
    • ability to chat to multiple people in the same conversation
    • status notifications for /away or /busy
  • It would be useful to bring new messages to your users attention without stealing focus, perhaps implementing a hook into the Snarl messaging program which is similar to Growl on Mac OS X?

    This does mean that you would need to have the Snarl system installed on each of your workstations.

Redirecting URL's

How can I redirect www.mysite.com/picture/12345 to www.mysite.com/picture/some-picture-title/12345? Right now, "/picture/12345" is rewritten on picture.aspx?picid=12345 and same for second form of url (picture/picture-title/12323 to picture.aspx?picid12323) I can't just rewrite first form of url to second because i have to fetch picture title from database.

On the first hand, problem looks very easy but having in mind time to parse every request, what would be the right thing to do with it?

From stackoverflow
  • Not knowing what is the ASP.NET technology (Webforms or MVC) I will assume it's WebForms.

    You can have a look at URL Redirecting and build you own rules. And you do this one time only to apply to all of the links that look like you want.

    Scott Guthrie has a very nice post about it.

    If what you want is to when it comes to that address redirect to a new one, it's quite easy as well.

    First of all let's reuse the code, so you will redirect first to a commum page called, for example, redirectme.aspx

    in that page you get the REFERER address using the ServerVariables or passing the Url in a QueryString, it's your chooise and then you can attach the title name, like:

    private void Redirect()
    {
        // get url: www.mysite.com/picture/12345
        string refererUrl = Request.ServerVariables["HTTP_REFERER"];    // using the ServerVariables or Request.UrlReferrer.AbsolutePath;
        //string refererUrl = Request.QueryString["url"];                 // if you are redirecting as Response.Redirect("redirectme.aspx?" + Request.Url.Query);
    
        // split the URL by '/'
        string[] url = refererUrl.Split('/');
    
        // get the postID
        string topicID = url[url.Length-1]; 
    
        // get the title from the post
        string postTitle = GetPostTitle(topicID);
    
        // redirect to: www.mysite.com/picture/some-picture-title/12345
        Response.Redirect(
            String.Format("{0}/{1}/{2}",
                refererUrl.Substring(0, refererUrl.Length - topicID.Length),
                postTitle,
                topicID));
    }
    

    to save time on the server do this on the first Page event

    protected void Page_PreInit(object sender, EventArgs e)
    {
        Redirect();
    }
    
  • I'm presuming you need a common pattern here and not just a once off solution. i.e. you'll need it to work for 12345 & 12346 & whatever other IDs as well. You're probably looking for URLRedirection and applying a Regular Expression to identify a source URI that will redirect to your Target URI

    Ante B. : yes, that's my problem.. what is THE solution?
    Eoin Campbell : go and read the article by Scott Guthrie that the balexandre posted. It requires several hundred lines of code, that I'm not going to post in an answer. All the sample code/examples you need are in that article.
  • If you're running IIS7 then (for both webforms and MVC) the URL rewriting module (http://learn.iis.net/page.aspx/460/using-url-rewrite-module/) is worth looking at.

    Supports pattern matching and regular expressions for redirects, state whether they're temporary or permanent, plus they're all managable through the console. Why code when you don't have to?

    John Clayton : The URL Rewrite module is by far the easiest if you are running on IIS7. The catch would be to make sure that the new URL is used when you render the pages.

Connect Bluetooth device to an unknown device

Is it possible to connect a Bluetooth device to an unknown device? I thought all Bluetooth devices had to be paired with another Bluetooth device before they could be used together. Someone mentioned a possible application where a Bluetooth device (most likely a Windows Mobile phone as the iPhone SDK doesn't support Bluetooth connections) can be used to say read electric meters in a given area. I thought the phone would have to be paired with each meter before any other communication could take place. Is this correct? Can the phone receive arbitrary data from a Bluetooth provider before they are paired?

From stackoverflow
  • If you know the MAC address of a bluetooth device and it is connectable you can talk to it directly.

  • Hai Dear,

    I have apple i phone 2g, how to connected bluetooth to other device like iphone to mobile phone

  • You don't have to have security set up (no pin code) so you could have a bluetooth device that is always discoverable and will always connect/pair. So this could be used for the 'read a meter' type application.

    Also, in Bluetooth 2.1, you have Extended Inquiry data so you could get the meter reading by having the meter encode the reading into the Extended Inquiry response. Then you don't even have to connect/pair. Just have a device that does an inquiry and gets the data that way.

    There are some new standards coming for BlueTooth for Low Energy devices that would basically act like sensors, which are specifically targeted at this type of application.

    There is more info then you could possibly want at www.bluetooth.org

  • Talking to a device, and having it understand what you are saying are two different things.

    The device on the other end of the line must support the function that you are trying to achieve. There's no point sending realtime video to a bluetooth enabled thermostat whose only function is to control and report the temperature.

Strip Html from Text in JavaScript except p tags?

I need to change RichEditor and TextEditor modes with JavaScript, now I need to convert Html to Text which is actually still in Html editor mode, so I need just p tags, but other Html can be stripped off.

From stackoverflow
  • This should help

    var html = '<img src=""><p>content</p><span style="color: red">content</span>';
    html.replace(/<(?!\s*\/?\s*p\b)[^>]*>/gi,'')
    

    explanation for my regex:

    replace all parts

    1. beginning with "<",
    2. not followed by (?!
      • any number of white-space characters "\s*"
      • optional "/" character
      • and tag name followed by a word boundary (here "p\b")
    3. containing any characters not equal ">" - [^>]*
    4. and ending with ">" character
    Tomalak : +1 for thinking about the white space.
  • Regex replace (globally, case-insensitively):

    </?(?:(?!p\b)[^>])*>
    

    with the empty string.

    Explanation:

    <          # "<"
    /?         # optional "/" 
    (?:        # don't capture group
      (?!      # a position not followed by...
        p\b    # "p" and a word bounday
      )
      [^>]*    # any char but ">"
    )*         # as often as possible
    >          # ">"
    

    This is one of the few situations where applying regex to HTML can actually work.

    Some might object and say that the use of a literal "<" within an attribute value was actually not forbidden, and therefore would potentially break the above regex. They would be right.

    The regex would break in this situation, replacing the underlined part:

    <p class="foo" title="unusual < title">
                                  ---------
    

    If such a thing is possible with your input, then you might have to use a more advanced tool to do the job - a parser.

    Pim Jager : It's great that you added the explanation.
    Steerpike : Yeah, seconded on the explanation breakdown. Thanks for the clarity.
    Tomalak : @JavaCoder: Is this a "give me teh codez" question? There are literally *tons* of JavaScript regex tutorials available on the internet. I am sure you manage to find one that tells you how to accomplish a replace, if only you went looking for one. Even Rafael's answer below shows you how to do it. But if you are asking how to make a JavaScript function, you might not yet be ready to use regular expressions at all. And your nickname would be wrong.

Custom handler working on Asp.NET Development server but not on IIS 5.1??

Hi guys, ive got a stupid problem.

My Custom handler is working 100% on Asp.NET Development server but when i publish the site to IIS 5.1 whenever i try to run Comment/Find (which finds a user via an AJAX call) (i know the naming of my handler sux!!! :)

I get this error:

The page cannot be displayed The page you are looking for cannot be displayed because the page address is incorrect.

Please try the following:

* If you typed the page address in the Address bar, check that it is entered correctly.
* Open the home page and then look for links to the information you want.

HTTP 405 - Resource not allowed Internet Information Services

Technical Information (for support personnel)

* More information:
  Microsoft Support

My code for the AJAX call is:

 function findUser(skip, take) {

        http.open("post", 'Comment/FindUser', true);
        //make a connection to the server ... specifying that you intend to make a GET request
        //to the server. Specifiy the page name and the URL parameters to send
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.setRequestHeader('Criteria', document.getElementById('SearchCriteria').value);
        http.setRequestHeader("Skip", skip);
        http.setRequestHeader("Take", take);
        http.setRequestHeader("Connection", "close");

        //display loading gif
        document.getElementById('ctl00_ContentPlaceHolder1_DivUsers').innerHTML = 'Loading, Please Wait...<br /><img src="Images/loading.gif" /><br /><br />';

        //assign a handler for the response
        http.onreadystatechange = function() { findUserAction(); };

        //actually send the request to the server
        http.send(null);

}

Please can anyone help me??

From stackoverflow
  • On IIS not all calls will be processed by the asp.net handler (unlike cassini the development server) unless the call ends in .aspx, .ashx etc. the .NET isapi dll will not process the call.

    The clue is in the

    HTTP 405 - Resource not allowed Internet Information Services

    You will need to also map the handler in the web.config if there is not a corresponding .ashx file in the file system.

  • Make sure you have allowed the extension on the IIS server. The development server does this automatially for you.

    If you open up the properties of the web site then go to the Home Directory Tab and click the configuration button.

    In there try adding the extension you are using for the handler pointing. Set the executable to the aspnet_isapi.dll (look at the standard .aspx extension to find where it is on your computer) and uncheck "Check that file exists".

    I have been burned by this a couple of time and this sorted the problem

    Colin G

    The_Butcher : Hey Colin, thanks a lot for your input!!! However, after unchecking "Check that file exists" I still have the same error. Maybe it has something to do with the fact that I cannot run the CommentHandler.ashx file in IIS it gives the Error the the XML cannot be parsed for CommentHandler.ashx?
    Colin G : @The_Butcher What type of data are you returning eg. json, html, xml? it sounds like there is something wrong with the data more than the service. If you have any code i could look at send it down to pythonandchips at gmail.com
    The_Butcher : thanks man! but i sorted out the problem have a look it was silly. Still think its a bit of a hack though!
  • Thanks for the feedback!!

    Tried both of the suggestions unfortunately they just dont work.....
    adgADGAHADHADHADHADH!!!!! :/

    Knife theKnife = new Knife("jagged_edges");
    Speed theSpeed = new Speed("fast");
    
    slitWrists(theKnife,theSpeed);
    
    //slits wrists according to the given params
    public static void slitWrists(Knife theKnife,Speed theSpeed)
    {
         //NSFW!!!!
    }
    
  • Hey guys I got it!!! The problem was that when i was calling the handler on the dev. server i was calling it liek this

    http.open("post", 'Comment/Rate', true);

    because in my web.config i instructed it to catch all "Comment/" Urls and call the CommentHandler.ashx to handler it.

     <add verb="*" path="Comment/*" type="CoffeeMashup2.CommentHandler"/>
    

    However for some reason in IIS it didnt work so i changed the above call to

    http.open("post", 'CommentHandler.ashx/Rate', true);
    

    and its worked 100%

    thanks a lot guys for your help