Monday, February 21, 2011

ServletContext and Session object

Hi,

Is the ServletContext and Session object which we get from request object (HttpServletRequest) behave the same ?

From stackoverflow
  • Sessions are user specific.

    Servlet contexts are essentially global (within the context of that servlet), meaning all users who hit that servlet will share the same servlet context.

  • do some reading

Need help with Apache's mod_rewrite to fetch file based on url

So say I have a url being requested:

sub.domain/file.bin

and I wanted this file to be fetched:

domain/hosted/sub/file.bin

How would I structure the rewrite directives? I've been working on this for days, and it just gives me a headache...

The subdomains are numerous and are added and removed often, so I'm trying to find a solution that works for all of them.

From stackoverflow
  • In sub.domain's httpd config:

    RewriteCond %{HTTP_HOST} ([^\.]+).domain
    RewriteRule ^/file.bin$ http://domain/hosted/%1/file.bin
    
    Cypher : Hrm, getting close. How could I make the "sub" dynamic based on whatever the subdomain is in the initial url?
  • Assuming the home directory for www.domain.com is domain/ and that - given any subdomain sub.domain.com - you want the files for the home directories for that sub-domain to be in domain/hosted/sub/

    Try something like this:

    RewriteEngine on
    
    // If the host is just mydomain.com, do nothing more
    // this is to prevent some recursion problems I've read of...
    RewriteCond %{HTTP_HOST} ^(www\.)?mydomain\.com$ [NC]
    RewriteRule ^.*$ - [L]
    
    // Otherwise strip off everything before mydomain
    // And add it to the start of the request
    RewriteCond %{HTTP_HOST} ^(.*?)\.(www\.)?mydomain\.com$ [NC]
    RewriteRule ^.*$ %1%{REQUEST_URI} [QSA]
    
    // Then prefix with 'hosted'
    RewriteRule ^(.*)$ hosted/$1 [QSA,L]
    

    You may also need a wildcard entry in your DNS or something... but I will admit DNS and htaccess mod rewrite are some of my weaker points. See also http://www.webmasterworld.com/forum92/138.htm

  • Try this rule:

    RewriteCond %{HTTP_HOST} ^([^/.]+)\.example\.com$
    RewriteCond %1 !=www
    RewriteRule !^hosted/ hosted/%1%{REQUEST_URI} [L]
    

Saving addressbookUI data to an array

I'm trying to save the kABFirstNamePropert, kABLastNameProperty and kABAddressProperty all saved into an array for recall later, I'm just not getting it, can anyone lend me a hand or point me in the right direction? Thanks. I'm a super NOOb on this.

For the naming the strings:

// setting the first name
firstName.text = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);

// setting the last name
lastName.text = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);

For setting the addressLabel:

NSString *address;
    address = [NSString stringWithFormat:@"%@, %@, %@, %@ %@",
               [theDict objectForKey:(NSString *)kABPersonAddressStreetKey],
               [theDict objectForKey:(NSString *)kABPersonAddressCityKey],
               [theDict objectForKey:(NSString *)kABPersonAddressStateKey],
               [theDict objectForKey:(NSString *)kABPersonAddressZIPKey],
               [theDict objectForKey:(NSString *)kABPersonAddressCountryKey]];

    self.addressLabel.text = address;

Saving the Array: What I have that's not working. ;(

- (IBAction)saveData {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *recipient = [NSString stringWithFormat:@"%@/arraySaveFile", documentsDirectory];

    NSMutableArray *array = [[NSMutableArray alloc] init];
    [array addObject:firstName];
    [array addObject:lastName];
    [array addObject:addressLabel];

    [array writeToFile:recipient atomically:NO];

}
From stackoverflow
  • This:

    [array addObject:firstName]; 
    

    needed to be:

    [array addObject:firstName.text];
    

    Thanks Everyone.

How to assign text size in sp value using java code..

If I assign an integer value to change a certain text size of a TextView using java code, the value is interpreted as pixel (px), now does anyone know how to assign in sp?

thanks.

-mario_blizz

From stackoverflow
  • You can use a DisplayMetrics object to help convert between pixels and scaled pixels with the scaledDensity attribute.

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    pixelSize = (int)scaledPixelSize * dm.scaledDensity; 
    

Border in jasper report

Hi ,

I am creating a jasper report .In that I want apply border to the each page.Can any one provide me some help on this.Border height should depend on the contents height of that page.

Thanks.

From stackoverflow
  • You can do this by creating a frame or a rectangle in an outer report and then put inside it a supreport. The subreport should be allowed to expand as it wants and the rectangle should be set to Stretch to the band height.

Serving up snippets of html and using urlfetch

I'm trying to "modularize" a section of an appengine website where a profile is requested as a small hunk of pre-rendered html

Sending a request to /userInfo?id=4992 sends down some html like:

    <div>
    (image of john) John
    Information about this user
    </div>

So, from my google appengine code, I need to be able to repeatedly fetch results from this URL when displaying a group of people.

The only way I can do it now is send down a collection of <iframes> like

    <iframe src="/userInfo?id=4992"></iframe>
    <iframe src="/userInfo?id=4993"></iframe>
    <iframe src="/userInfo?id=4994"></iframe>

The iframes work to request the data.

I tried using urlfetch.fetch() but it keeps timing out on me.

Am I doing this right? I thought this would be handy-dandy (url that serves up a snippet of html) but it turns out its looking like a design error.

From stackoverflow
  • You're currently serializing urlfetch requests, which ends up summing their wait times and may easily push you beyond your latency deadline. I'm afraid that you'll need to switch to async urlfetch requests -- an advanced technique which may suit your architecture better!

sum and union all query using mysql and java

I have a table with following fields Service_type and consumer_feedback.for example:

Service_ID  consumer_feedback
31           1
32           -1
33            1
31            1
32            1.

I want to find the sum of consumer_feedback for each Service_ID through java code

ResultSet res = st.executeQuery("SELECT SUM(consumer_feedback) 
                                   FROM  consumer1 
                                  where Service_ID=31 
                                 union  
                                 SELECT SUM(consumer_feedback)  
                                   FROM consumer1 
                                  where Service_ID=32 
                                 union  
                                 SELECT SUM(consumer_feedback)  
                                   FROM consumer1 
                                 where Service_ID=33") ;
    while (res.next()) {
      int c1 = res.getInt(1);           
      sum1 = sum1 + c1;        
    }

    System.out.println("Sum of column "   +sum1);

    while (res.next()) {
      int c2 = res.getInt(1);           
      sum2 = sum2 + c2;                  
    }

    System.out.println("Sum of column "   +sum2);

    while (res.next()) {
      int c3 = res.getInt(1);
      sum3 = sum3 + c3;
    }

    System.out.println("Sum of column "   +sum3);
}

But this code is working for2 Service_ID's and not for three Service_ID's.Please help me out

From stackoverflow
  • Your query should be

    select service_id,sum(consumer_feedback) from consumer1 group by service_id
    

    This will eliminate the need to do the unions.

Powershell, how to update several dns records

I have the following script, but am getting an error -

Script -

$CNAMES = Get-Content "C:\Temp\alias.txt" $Query = "Select * from MicrosoftDNS_CNAMEType" $Record = Get-WmiObject -Namespace "root\microsoftdns" -Query $Query -ComputerName 10.10.10.1 | Where-Object{$_.Ownername -match $CNAME} Foreach($CNAME in $CNAMES) { $Record.RecordData = "some.server.net" $Record.put() }

Error -

Property 'RecordData' cannot be found on this object; make sure it exists and is settable. At C:\temp\DNSUpdateCNAMETarget_02.ps1:7 char:9 + $Record. <<<< RecordData = "some.server.net" + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : PropertyAssignmentException

Method invocation failed because [System.Object[]] doesn't contain a method named 'put'. At C:\temp\DNSUpdateCNAMETarget_02.ps1:8 char:12 + $Record.put <<<< () + CategoryInfo : InvalidOperation: (put:String) [], RuntimeExcept ion + FullyQualifiedErrorId : MethodNotFound

TIA

From stackoverflow
  • I didn't try (cause i don't have a MS-DNS at hand right now) but i'd suspect that you need

    $Record.PSBase.Put()
    

    to make it work.

    EDIT:

    As it looks $Record holds an array of System.Object so will have to cast it a suitable type to access .RecordData and .Put()

    Your script queries for records of type MicrossoftDNS_CNAMEType which only support CreateInstanceFromPropertyData.

    I would try sending you $Record to Get-Member

    Get-WmiObject -Namespace "root\microsoftdns" -Query $Query -ComputerName 10.10.10.1 | Get-Member
    

    to find out, what you are dealing with.

    audiphilth : this change had no effect

Eclipse ignoring source when deploying webapp

Hey,

I'm running eclipse with tomcat 5.5. For some unknown reason from one day to the other eclipse stoped compiling my beans and java files that are in the source folder.

If I go to the work directory, I find all the JSP compiled, the folders of the packadges i have, but no classes compiled inside of them. Neither eclipse, nor tomcat give errors. (Except when i try to access the non existing classes)

Anyone has any idea why this happens and how to fix it?

/fmsf

From stackoverflow
  • You might have "Build automatically" disabled. You can find it in the Project menu.

    fmsf : it's enabeled, the JSP are being compiled, it's just the java files, beans and such that are being ignored
    nfechner : Maybe the sources are no longer part of the build path?
  • I've faced with such a scenario once. In addition it did not detect the local changes w.r.t the code repository. Honestly I don't know the reason but use of a new eclipse installation (Extraction) on same workspace resolved the issue.

  • Found the problem:

    One of the files came out of SVN without read access. Eclipse blocked reading it and wouldn't compile.

    +1 to all tks

How to start Camel routes on slave ActiveMQ only when slave becomes active in failover?

I have a durable consumer to a remote JMS queue in embedded Camel routing. Is it possible to have this kind of routing with master-slave configuration? Now it seems that the Camel routes are started and activated already when slave ActiveMQ is started and not when the actual failover happens.

Now it causes the slave instance to receive the same messages that are also sent to master and this causes duplicate messages to arrive to the queue on failover.

I'm using ActiveMQ 5.3 along with Apache Camel 2.1.

From stackoverflow
  • this shouldn't be an issue because the Camel context/routes on the slave will not start until it becomes the master (when the message store file lock is released by the master)

Disabling "Just -In-Time Debugger" error messages

Since installing Visual Studio, I often get this kind of error messages when apps crash instead of the regular ones:

Just-In-Time Debugger How can I disable this? I've already uninstalled Visual Studio.

From stackoverflow

Storing the IMEI from an Android phone on an American Server.

Is it legally OK to store an SHA1 Hash of a user IMEI on a server?

I have asked the user for permission before sending the IMEI.

From stackoverflow
  • As long as the operation is not reversible you should be fine. I've had the same kind of issues in the past while writing an application that needed a unique ID from the user to be stored in the server. After putting it past through legal it was fine as long it wasn't possible to get from the hash back to the exact user.

Incorrect comments set for php in vim

My vim used to auto-continue comments in php. For example:

/* |  <- cursor here

Then, pressing Enter gives me:

/*
 * |  <- cursor here

and again, gives me:

/*
 *
 * |  <- cursor here

etc...

As far as I understand it, this is controlled by the comments and formatoptions options. However, whenever I open a php file now, comments is set to:

s:<!--,m: ,e:-->

I've looked all over my ~/.vim folder, as well as the $VIMRUNTIME folder, and I can't find out where/why this changed, and why the comments option is being set incorrectly.

Here's a link to my .vimrc

http://pastebin.com/f1509ce65

From stackoverflow
  • The php.vim file should be in your ftplugin folder in $VIMRUNTIME.

    In version 7.2 of vim, the comments line is line 74 in that file.

    Did that file get deleted or moved?

    Bryan Ross : No, it's still there. Maintainer: Dan Sharp URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
    John Weldon : do you have any files in your personal .vim/ftplugin that could be overriding the comments? Or your .vim/filetype.vim for that matter?
    Bryan Ross : Found it. see answer
  • Found it. I had a funky .vim/indent/php.vim file that somehow was screwing it up.

    Deleted it, and the functionality I was looking for returned. Thanks tho!

Lat Long to Minutes and Seconds?

Google Maps gives me the Lat and Long of a location in decimal notation like this:

38.203655,-76.113281

How do I convert those to Coords (Degrees, Minutes , Seconds)

From stackoverflow
  • Decimal Degrees to Degrees Minutes Seconds

  • Co-ordinate systems and conversions are explained here, with pseudocode: Co-ordinate conversion (from Wikipedia)

  • 38.203655 is a decimal value of degrees. There are 60 minutes is a degree and 60 seconds in a minute (1degree == 60min == 3600s).

    So take the fractional part of the value, i.e. 0.203655, and multiply it with 60 to get minutes, i.e. 12.2193, which is 12 minutes, and then repeat for the fractional part of minutes, i.e. 0.2193 = 13.158000 seconds.

    Example in python:

    def deg_to_dms(deg):
        d = int(deg)
        md = abs(deg - d) * 60
        m = int(md)
        sd = (md - m) * 60
        return [d, m, sd]
    
    print deg_to_dms(38.203655)
    print deg_to_dms(-76.113281)
    

Why does registering a new user using the ACEGI plugin for GRAILS give a "Default Role not found." error.

Perhaps put a different way, how do I set up a default security role for newly registered users in Grails using teh ACEGI plug-in?

I have followed the acegi/grails tutorial here and am using controller annotations - although I haven't secured anything yet.

I added a second role called WEB_USER and have successfully added a User to that role.

When I use the register controller fro another new user, however, I get an error message from Grails saying "Default role not found".

I could see how I could code my way roughly out of this by either handling a null role list in the appropriate create method, or even posting a default role name back as a hidden field from the registration view, but they feel un-Grails.

I think I ought to be able to define this either in the User domain class itself or somehow in the relationship in the database between the user and role tables.

What's the intended means to define a default role, and why am I getting this message.

Oh, and how do you pronounce acegi?

From stackoverflow
  • I found the answer. Typically of Grails, there is a default role called ROLE_USER. When you register a new user it looks for a role with that name and if it finds one it assigns it to the user.

    The message "Default Role not found" is ambiguous in how it can be read.

    I first thought it meant "you need to define a default role somewhere so that newly registered users are assigned to it".

    However I think it really means "you need to create the database row in your roles table which is called ROLE_USER so that the normal configuration works".

    It strikes me that part of the grails generation of the security features ought just to add a ROLE_ADMIN and ROLE_USER to the database bootstrap somehow and have done with the possiblity of the error.

  • This is a documentation issue. The register page doesn't allow you to select roles since it's expected that it'll be a public signup page. At least one role is required when creating a user so it expects that there's a 'default' role configured for this workflow.

    You can set the default role in SecurityConfig.groovy with the 'defaultRole' attribute. By default it's 'ROLE_USER' but it can be whatever you want. There has to be an Authority instance with this value before users can register.

    The pronunciation is in the FAQ - http://www.acegisecurity.org/faq.html

    Simon : thanks Burt, a great help

XSLT: Use of template tag variable and break condition in for-each loop

I am using an XSLT where I have created <xsl:template> tag which does some validation using an <xsl:for-each> statement and sets the value of <xsl:variable> or <xsl:param> to true or false.

  1. Is there any way to break the statement in for-each if condition is true?
  2. Can we use the value of Template variable or param from main calling routine?

Example:

<!-- Main Xslt -->
<xsl:template>
  <xsl:call-template name ="TestTemplate">
    <!--  
      Here I want to use the variable or param that 
      is defined in TestTemplate, is it possible?
    -->
  </xsl:call-template>
</xsl:template>

<xsl:template name ="TestTemplate">
  <xsl:param name="eee"/>
  <xsl:for-each select ="//RootNode/LeafNode">
    <xsl:choose>
      <xsl:when test ="@Type='ABC'">
        <xsl:value-of select ="true"/>
      </xsl:when>
      <xsl:otherwise>false</xsl:otherwise>
    </xsl:choose>
  </xsl:for-each>
</xsl:template>
From stackoverflow
  • ad 1. I think that it is not possible but I am not sure

    ad 2. Yes, you can use parameter but pay attention on it because it is constant. All variables and parameters in XSL are constants. Look at W3School - variable

    cite:

    Once you have set a variable's value, you cannot change or modify that value!

    The same thing is for parameters.

    You can call template with ( constant ) parameter:

    <call-template name="myTemplate">
       <xsl:with-param name="name" select="expression">
    </call-template>
    

    Look at W3School - with parameter it is really good reference page.

  • To your questions:

    Is there any way to break the statement in for-each if condition is true ?

    No, and normally this is also unnecessary. XSLT is not an imperative programming language, and imperative approaches do not really work well here.

    What you seemingly want to do is expressing "find the first <LeafNode> where @Type='ABC', and return true or false depending on whether there is one.

    The way to do this in traditional languages is like your approach: for each node, check condition, if condition satisfied then return.

    In XSLT you simply select the node with XPath:

    //RootNode/LeafNode[@Type='ABC']
    

    either the result of this contains a node, or it does not. No need for a for-each at all.

    Can we use the value of Template variable or param from main calling routine ?

    No. Variables and params are strictly scoped. They go out of scope once processing leaves their parent element. They are also constant, once declared they cannot be changed.

    The way to do what you want here is making the template output the desired value and capture it in a variable:

    <xsl:template>
      <xsl:variable name="returnValue">
        <xsl:call-template name="TestTemplate" />
      </xsl:variable>
    </xsl:template>
    
    <xsl:template name="TestTemplate">
      <!-- the following expression emits true or false -->
      <xsl:value-of select="
        count(//RootNode/LeafNode[@Type='ABC']) gt; 0
      " />
    </xsl:template>
    

    Two last hints:

    • avoid the '//' operator at all costs. Most of the time its use is not necessary
    • the first, top-most element in a document is not the "root node", it is the "document element"

    This is an important distinction. The "root node" comes before the document element, so the XPath above should be more like this (semantically):

    /DocumentElement/LeafNode
    ^------ *this* slash represents the "root node"
    

Providing auto height and width to dailog in jquery UI modal dailog box.

I am trying to put auto height and width to modal dailog box (provided by jquery UI). But some how the position of my dailog is getting disturbed. it is not coming in center. Everytime i click on the link to open the dailog box , the dailog opens at different position. Could anybody please suggest how to resolve this issue...

From stackoverflow
  • u can main div

    { margin:0 auto; } or { margin:auto auto; }

    ==========

    Othervise u can set a left and top javascript dailog box position set...

    thanks suresh

.NET Error Record

Hi. I am using .NET 2.0. My Csharp Application will cursh sometime. And there are some .net error logs at the "System" Category from Event Viewer explorer.

Error Log Sample.

Error, such as:
11/24/2009      3:21:17 PM      .NET Runtime 2.0 Error Reporting        Error  
None    5000    N/A     MyCompany-9BDDB24555 EventType clr20r3, P1 myApp.exe, P2
1.0.0.0, P3 4abf097c, P4 system.windows.forms, P5 2.0.0.0, P6 4333aefa, P7
47f1, P8 96, P9 system.invalidoperationexception, P10 NIL.

And recently, when my App crushed, there was no any .NET 2.0 error log on one customer side pc (WindowXP & .net 2.0 installed). Is there any SERVICE need to be enabled for recording the error message at Event Viewer? thank you.

From stackoverflow
  • This looks a bit like an IIS log error you've shown. I can tell you that I've seen the IOException when making web service calls that time out. Otherwise, no, you'll probably need to catch the error in your application and write it tthe event log.

    Nano HE : Thank you sir. :)

Web App GPS Polling

So it looks like mobile phones these days are capable of providing gps data ;)

I'm building a django app with a mobile edition that I want to be location aware.

My question is, how does one access GPS data? Is there a standard, or do you have to custom code for android/iphone/other.

Ideally, I'd imagine it being provided in the HTTP request in the same way you get information such as the IP Address and User Agent.

From stackoverflow
  • There's a really good blog post about this topic, covering a variety of methods @

    http://hitching.net/2009/11/10/location-aware-mobile-web-apps-using-google-maps-v3-geolocation/

  • Server side API will be common for all platforms (just standard HTTP requests).

    GPS access is platform depend and typically You will have to write custom code for all platforms. However you can try use http://www.appcelerator.com/ - framework for crating mobile apps using Web based techniques (there is common appi for GPS access).

  • Your code is going to be used on a mobile client, you know it is going to be a specific kind of phone. Yes you do need to code for a specific device as the API for iPhone is not the same as for Android. Android I don't know yet - for iPhone, you need to use Core Location - the CLLocation class is a good place to start reading in the developer docs once you have Xcode open, and the Locations sample code is a nice starting point that shows how to get a series of position fixes. Maybe you can get some kind of fix back from the server but I don't think you'll find it at all accurate - that is to say not incorrect but with a very large circle of uncertainty.

  • Don't forget Google Gears which provides access to geolocation and other goodies.

Caching problem.

I have a web page with a set of images and java script files.

I want to cache all the images+java script other than a single image which is the logo.

Is this possible ? and how would I do it ?

I am using IIS server.

From stackoverflow
  • Yes. Just configure your server to have a default cache configuration for images and JS, and then override it for the logo. Possibly with a <file> block if you are using Apache.

    See this decent caching tutorial.

How do I get SVN to realize a binary file's changed if the filesize is fixed.

I'm working with a program that writes data to fixed-size binary files that I store in a subversion archive.

The problem, however, is SVN (both the command-line client and TortiseSVN) thinks that since the size of the file didn't change, the file itself didn't change and it shouldn't commit it.

Is there a way to change what diffing method is used, or do I have to resort to hacks such as adding a dummy property to the files?


EDIT: Turns out the solution wasn't becuase of the file-size thing. I just automatically assumed that would be the case, since most nieve diffing altorithims do this all the time. [weasel words]

From stackoverflow
  • Are you absolutely sure that the files did change? Subversion can and does handle binary files and they have an actual diffing algorithm for them; it's not just a look at the file size. Subversion detects file changes to binary files just fine here, even though the size did not change.

    Si : Hahaha, you beat me by 3 seconds :)
    Joey : I would have been faster, but I read the part in the Subversion book again :)
  • Are you sure the file has changed? i.e. different bytes. I'm pretty sure subversion uses a binary diff algorithm, and doesn't rely on file size.

    Kevin Reid : Subversion *does* compare timestamps, and assumes the file is unchanged if the timestamp has not changed. If the timestamp has changed, it will compare the entire content of the file.
    Si : Thanks Kevin, edited.
  • Resoved on my own.

    Turns out that the program that changed the files was also messing with the file's metadata in a way that confused SVN.

  • See here for a description on how SVN determines whether a file is modified or not.

PIP complains when I try to install a module into another virtualenv

I have a module installed in the main python install, however, I'd like to install this module into my virtualenv and I'd like it to be portable, how can I do that?

I'm getting this error:

(v_env)[nubela@nubela-desktop zine-ified]$ pip -E v_env install pyfacebook
Requirement already satisfied (use --upgrade to upgrade): pyfacebook in /home/nubela/...
From stackoverflow
  • To force pip installing a package when it's already been detected, you need to use the -I or --ignore-installed flag. In your case, the command would be:

    pip -E v_env install -I pyfacebook
    

    pip will then install it into your virtualenv.

form_for with nested resources

I have a two-part somewhat noob question about form_for and nested resources. Let's say I'm writing a blog engine and I want to relate a comment to an article. I've defined a nested resource as follows:

map.resources :articles do |articles|
    articles.resources :comments
end

The comment form is in the show.html.erb view for articles, underneath the article itself, for instance like this:

<%= render :partial => "articles/article" %>
<% form_for([ :article, @comment]) do |f| %>
    <%= f.text_area :text %>
    <%= submit_tag "Submit" %>
<%  end %>

This gives an error, "Called id for nil, which would mistakenly etc." I've also tried

<% form_for @article, @comment do |f| %>

Which renders correctly but relates f.text_area to the article's 'text' field instead of the comment's, and presents the html for the article.text attribute in that text area. So I seem to have this wrong as well. What I want is a form whose 'submit' will call the create action on CommentsController, with an article_id in the params, for instance a post request to /articles/1/comments.

The second part to my question is, what's the best way to create the comment instance to begin with? I'm creating a @comment in the show action of the ArticlesController, so a comment object will be in scope for the form_for helper. Then in the create action of the CommentsController, I create new @comment using the params passed in from the form_for.

Thanks!

From stackoverflow
  • Include a hidden article_id form field, populated with the article's ID. On submission, the comment should set up the association all by itself.

    Dave Sims : That sorta defeats the idea of using the nested resource path /articles/[id]/comments doesn't it?
  • Basically you are doing the same as in this guide with your second try, only thing is that you use the same field name for the post text and the comment text.

    Although I do not understand why this is not working, it seems easy to change the comment field name into comment instead of text. So <%= f.text_area :comment %> is not matching with the text field of post any more.

    Looking at the guide seems reasonable as well, since they tend to achieve the result you are looking for with your example.

    For your second question: that is also explained in the guide. Using

    @comment = Comment.new
    

    for the new action and

    @comment = Comment.new(params[:comment])
    @comment.save
    

    for the create actions, seem their way of working.

  • You don't need to do special things in the form. You just build the comment correctly in the show action:

    class ArticlesController < ActionController::Base
      ....
      def show
        @article = Article.find(params[:id])
        @new_comment = @article.comments.build
      end
      ....
    end
    

    and then make a form for it in the article view:

    <% form_for @new_comment do |f| %>
       <%= f.text_area :text %>
       <%= f.submit "Post Comment" %>
    <% end %>
    

    by default, this comment will go to the create action of CommentsController, which you will then probably want to put redirect :back into so you're routed back to the Article page.

Getting an error when initialising the Membership.Provider for the first time after an app restart

We're using MS Commerce Server's Microsoft.CommerceServer.Runtime.Profiles.UpmMembershipProvider and sometimes where it gets initialised for the first time after an app restart we get this error:

System.Configuration.ConfigurationErrorsException - System.Web, Object reference not set to an instance of an object. (C:\Inetpub\web.config line 425)
   at System.Web.Security.Membership.Initialize()
   at System.Web.Security.Membership.get_Provider()
   ...

Line 425 is the membership provider specification :

<membership defaultProvider="UpmMembershipProvider">
  <providers>
    <clear />
    <add name="UpmMembershipProvider"
      applicationName="app"
      enablePasswordRetrieval="false"
      enablePasswordReset="true"
      logonNameProperty="GeneralInfo.logon_name"
      requiresQuestionAndAnswer="true"
      requiresUniqueEmail="true"
      enableCreateDate="true"
      enableEmailAddress="true"
      enableLastLoginDate="true"
      profileDefinition="UserObject"
      passwordFormat="Hashed"
      maxInvalidPasswordAttempts="5"
      passwordAttemptWindow="1"
      type="Microsoft.CommerceServer.Runtime.Profiles.UpmMembershipProvider" />
  </providers>
</membership>

We took a memory dump and this is what we got:

0:025> !dumpstack
OS Thread Id: 0x1080 (25)
Current frame: kernel32!RaiseException+0x53
ChildEBP RetAddr  Caller,Callee
1213e5d8 7d4e237e kernel32!RaiseException+0x53, calling ntdll!RtlRaiseException
1213e5ec 79e8002c mscorwks!Binder::RawGetClass+0x20, calling mscorwks!Module::LookupTypeDef
1213e5fc 79e8068f mscorwks!Binder::IsClass+0x23, calling mscorwks!Binder::RawGetClass
1213e608 79ef2a0f mscorwks!Binder::IsException+0x14, calling mscorwks!Binder::IsClass
1213e618 79ef2a36 mscorwks!IsExceptionOfType+0x23, calling mscorwks!Binder::IsException
1213e620 79ef2bbc mscorwks!RaiseTheExceptionInternalOnly+0x2a8, calling kernel32!RaiseException
1213e668 79e81e3d mscorwks!SetObjectReferenceUnchecked+0x19
1213e680 79fccf80 mscorwks!JIT_Throw+0xfc, calling mscorwks!RaiseTheExceptionInternalOnly
1213e6b8 79295aea (MethodDesc 0x791aad5c +0xa System.Collections.CompatibleComparer.Equals(System.Object, System.Object)), calling (MethodDesc 0x791aad50 +0 System.Collections.CompatibleComparer.Compare(System.Object, System.Object))
1213e6d4 792e5fcd (MethodDesc 0x7910c3d0 +0xcd System.Collections.Hashtable.get_Item(System.Object))
1213e6f4 79fcced5 mscorwks!JIT_Throw+0x1e, calling mscorwks!LazyMachStateCaptureState
1213e70c 792861dc (MethodDesc 0x791a5f58 +0x1c System.RuntimeType.IsPrimitiveImpl()), calling mscorwks!TypeHandle::GetSignatureCorElementType
1213e724 7a57b600 (MethodDesc 0x7a4abadc +0x70 System.Configuration.SettingsBase.GetPropertyValueByName(System.String)), calling (MethodDesc 0x7a4ac288 +0 System.Configuration.SettingsPropertyValue.get_PropertyValue())
1213e744 66918ad7 (MethodDesc 0x65f9871c System.Web.Security.Membership.Initialize()), calling mscorwks!JIT_Throw
1213e7a0 6673ecb9 (MethodDesc 0x65f985a0 +0x5 System.Web.Security.Membership.get_Provider()), calling (MethodDesc 0x65f9871c +0 System.Web.Security.Membership.Initialize())
...

Anyone come across anything like this before? It doesn't happen every time the app restarts, and it doesn't seem to be on one particular server (site is running on multiple servers behind a load balancer)

From stackoverflow
  • have you ever test this configration (not just membership, I mean entire application configuration) on another machine ?

    and are you sure that your application meet all of the Commerce Server requirements ? finally I recommand to install you commerce server on a virtual machine from the baseanconfiure it as you configure for the first time ( do not copy configuration file- ceae a new one ) and test if there is an error or not ? if your problem resolved (replace you currentconfiguration file with virtual machine configuration file,

    if your error still remains, it means that your comfiguration have problem and you should change it.

    let me know what's happen after reinstalling in another (virtual) machine.

    Glenn Slaven : We're running this on 20+ machines, the servers meet the requirements. The config file is for the whole application, I can't create a new one from scratch, it needs to contain everything that's in there for the app to run
    Nasser Hadjloo : so if you can not create a new configuration frm the scratch so please change the applicationName="app" with applicationName="/" or any other name that you think tou application does, as I undrestand from your (stack trace) log file, your meber ship cannot find the application with the name "app",note that most of developers do not name his/hers appication and usually the application name is "/" so try with changig the "app" wit "/" or any string that you think it may be your correct application name. let mw know whats happen
    Nasser Hadjloo : Glenn I also recommand to use from your virtual directory name for you application instad of applicationName="app"
    Glenn Slaven : It isn't actually 'app', I changed that from what our app name actually is
  • I've had the same problem using the SQL Membership Provider with ASP.NET.

    It was a configuration problem. Some parameter was set incorrectly.

    Maybe this article will help you.

    http://blogs.law.harvard.edu/brandonhaynes/2008/04/27/using-commerce-servers-upmmembershipprovider-with-dotnetnuke/

    What I can think (at this moment) is that you have a problem with the type attribute, or maybe you didn't copy all of the required dependencies to your Bin..

    Good luck

  • I ran into a similar issue before. The issue was due to using an InProc session state with multiple web servers. When one application wen't offline, the load balancer tried to forward all the sessions to a new server. The new server did not have the sessions from these users so we got an Object Not Set to... error when the Membership Provider tried to access the session object.

    To fix the issue, we set up a SQL Server to manage the sessions. You can see how to do that here.

  • Doesn't the type as specified in the web.config at

    type="Microsoft.CommerceServer.Runtime.Profiles.UpmMembershipProvider"
    

    have to follow the convention as specified in the documentation to System.Type.GetType(string typeName), i.e. doesn't it have to include the assembly and maybe also version number and all that jazz? As in at least something like:

    type="Microsoft.CommerceServer.Runtime.Profiles.UpmMembershipProvider, Microsoft.FancyCommerceServerAssembly"
    

    or even

    type="Microsoft.CommerceServer.Runtime.Profiles.UpmMembershipProvider, Microsoft.FancyCommerceServerAssembly, Version=6.6.6.0, Culture=neutral, PublicKeyToken=..."
    

    ?

Moving a div into another div

i have 2 main div:

    <div id="div1">
<div id="minidiv1">a</div>
<div id="minidiv2">b</div>
   </div>
   <div id="div2"></div>

I want move the minidiv1 into the div2 with jquery

how can i do?

From stackoverflow
  • You can simply append it to the div2, and it will change its location in the DOM:

    $('#minidiv1').appendTo('#div2'); 
    // or
    $('#div2').append('#minidiv1');
    

    The difference of the above two lines is what is returned, appendTo returns the #minidiv element, append will return the #div2 element.

    Use the one you find most useful if you want to make more actions (by chaining).

  • $('#minidiv1').appendTo('#div2');
    

    or

    $('#div2').append($('#minidiv1'));
    
  • $("#minidiv1").appendTo("#div2")
    

Adding Javascript EventListener only if no other listener is present?

Hello,

I'm a relative tyro in the Javascript programming arena, so please go easy on me. :-)

I am trying to add an eventListener to various DOM elements on a page. However, some of the elements I'm adding my event to already have an eventListener, and I don't want to supersede that one; I only want to add my event to an element that doesn't already have an event associated with it.

I've looked through a bunch of stuff relating to addEventListener, event.StopPropagation, event bubbling, and so forth, but haven't figured out any way to accomplish this yet.

Is there a way to detect other event listeners on a given element, or some other way to get where I want?

From stackoverflow
  • You can check if the on[event] property of that given element is set by using:

    if (typeof(document.getElementById("element-id").onclick) == "undefined") {
      // event undefined
    }
    
    if (typeof(document.getElementById("element-id").onclick) == "function") {
      // event defined
    }
    

    Notice that this won't work if a javascript library such as jQuery were used to define the event (e.g. by using $("#element-id").click()). I'd recommend you to use jQuery, you can handle events easily with it.

    edit: uh, well, afaik it doesn't work if you're using addEventHandler too. It only works if you set your event by using yourElement.onclick = anyFunction

    Hellion : As it turns out, the event that I'm trying to detect is defined via jQuery (as a live() event). I do have jQuery at my own disposal, but rummaging through the API info at the jQuery.com site, I still don't see anything about detecting pre-existing events, only info on how to bind my own events.
    raphael : oh, in this case: http://stackoverflow.com/questions/1236067/test-if-event-handler-is-bound-to-an-element-in-jquery
    Hellion : thanks, raphael!

Writing a filter for incoming connections

I'm using C++/boost::asio under Win7.

I'm trying to "sniff" trafic over a given TCP/IP port. Hence, I'd like to listen on that port, receive messages, analyze them, but also immidately allow them to flow further, as if I never intercepted them. I want them to sink into the program that normally listens and connects on that port. Imagine a transparent proxy, but not for HTTP.

I'd rather find a code-based solution, but barring that, maybe you would suggest a tool?

From stackoverflow
  • what you are trying to do is basically a firewall program.

    On windows there is several approach to do that, you can hook winsock. The better (or not hacky) is to use TDI filter (you take a look a this) or to make a NDIS filter.

    Microsoft also introduced new API, WPF and LSP. I think you have better to use it because the TDI filter and NDIS wrapper involve driver programming which complicated and can be time consuming.

    Kornel Kisielewicz : I don't want to do any more work that is needed -- I only need to do the hook for an analyze phase, after which I want to intercept the messages and handle them by myself (a server). Hence, getting bogged down into an API just for an analyse phase seems pointless :/
    RageZ : in all the case you would have to some kernel - user space communication on some interprocess communication, making a firewall is really an easy task
  • If this is for a product you are developing you may want to take a look at the WinPcap library http://www.winpcap.org/ which you can embed into your own program.

    If you just need to analyze for yourself, use one of the tools that uses WinPcap, I have had great success with WireShark; but check out the WinPcap site for other tools

    You cannot use boost::asio (or any other socket based library) for this as it consumes all the traffic.

webpage has expired in ie7 no back button involved

Our legacy web app is an xml-xslt combo served by Tomcat. Recently we added some new features that includes psuedo popups. We have come across a very SPOOKY problem. In ie7 we see the "Web Page Has Expired error" for only a single page for this upgrade although the same feature is working in other pages. But hold on! The spooky part is that this error only shows up from certain computers in our network and not in others! We guessed it could be some IE setting, but all the settings are identical. Any ideas?

From stackoverflow
  • It probably happens when POST request page has javascript that tries to modify html while it has not yet loaded until the end. For example if you have thickbox component call that is not inside jQuery's document.ready block. Weird IE validation bug

In SVN you can check out a portion of the file structure, can you do the same in GIT

In SVN you can checkout a portion of a repository ie:

http://some-url.com/repo/app1/trunk/plugins/plugin1

Can you do the same when you git clone? As I cannot get this to work

Thanks

From stackoverflow
  • No. When you clone, you get the whole repository. In Git, a repository is viewed as a contiguous element that shouldn't be split up any further. If people frequently need to get only "part" of the repository, the Git way of thinking suggests that it should be split off, and you should consider using submodules instead.

    Piper : thanks to everyone for the reply but the link was very useful to understanding why I cant do a partial checkout in git - thanks to all
    Piper : I have just recently converted an old company svn repo which has a bunch of projects. from within this git repo how would you recommend creating a submodule of a particular project
  • No you cannot, git treats the entire repository as a unit and must be checked out in its entirety.

integrate ms access and mysql in java

Hi,

I have a problem connecting to MS Access and MySQL using Java. My problem is that I cannot find the driver for MySQL. Here is my code:

<%@ page import="java.sql.*" %>

<%
   Connection odbcconn = null;
   Connection jdbcconn = null;
   PreparedStatement readsms = null;
   PreparedStatement updsms = null;
   ResultSet rsread = null;

   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  //load database driver
   odbcconn = DriverManager.getConnection("jdbc:odbc:SMS");  //connect to database
   readsms = odbcconn.prepareStatement("select * from inbox where Status='New'");
   rsread = readsms.executeQuery();
   while(rsread.next()){
        Class.forName("com.mysql.jdbc.Driver");
        jdbcconn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bakme", "root", "");  //connect to database
        updsms = jdbcconn.prepareStatement("insert into inbox(sms,phone) values (?,?)");
        updsms.setString(1, rsread.getString("Message"));
        updsms.setString(2, rsread.getString("Phone"));
        updsms.executeUpdate();
   }

%>
From stackoverflow
  • Thus, you get a ClassNotFoundException on the MySQL JDBC driver class? Then you need to put the MySQL JDBC driver JAR file containing that class in the classpath. In case of a JSP/Servlet application, the classpath covers under each the webapplication's /WEB-INF/lib folder. Just drop the JAR file in there. Its JDBC driver is also known as Connector/J. You can download it here.

    That said, that's really not the way how to use JDBC and JSP together. This doesn't belong in a JSP file. You should be doing this in a real Java class. The JDBC code should also be more robust written, now it's leaking resources.

    : thank you..my problem have been solve..by the way i didn`t understand which your statement "The JDBC code should also be more robust written, now it's leaking resources."can you give me an example or explain..i in the process of learning java
    BalusC : Check duffymo's answer for that. More information can be found in the Sun JDBC tutorial: http://java.sun.com/docs/books/tutorial/jdbc/index.html and in this blog article: http://balusc.blogspot.com/2008/07/dao-tutorial-data-layer.html
  • BalusC is spot on: this is not the way you should write something like this.

    Connection, Statement, and ResultSet all represent finite resources. They are not like memory allocation; the garbage collector does not clean them up. You have to do that in your code, like this:

    // Inside a method
    Connection connection = null;
    Statement statement = null;
    ResultSet rs = null;
    
    try
    {
        // interact with the database using connection, statement, and rs
    }
    finally
    {
        // clean up resources in a finally block using static methods, 
        // called in reverse order of creation, that don't throw exceptions
        close(rs);
        close(statement);
        close(connection);
    }
    

    But if you do decide to move this to a server-side component, you're bound to have huge problems with code like this:

    while(rsread.next())
    {
        Class.forName("com.mysql.jdbc.Driver");
        jdbcconn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bakme", "root", "");  //connect to database
        updsms = jdbcconn.prepareStatement("insert into inbox(sms,phone) values (?,?)");
        updsms.setString(1, rsread.getString("Message"));
        updsms.setString(2, rsread.getString("Phone"));
        updsms.executeUpdate();
    }
    

    Registering the driver, creating a connection, without closing it, and repeatedly preparing a statement inside a loop for every row that you get out of Access shows a serious misunderstanding of relational databases and JDBC.

    You should register the driver and create connections once, do what needs to be done, and clean up all the resources you've used.

    If you absolutely MUST do this in a JSP, I'd recommend using JNDI data sources for both databases so you don't have to set up connections inside the page. You should not be writing scriptlet code - better to learn JSTL and use its <sql> tags.

    : thank you for your explaination.
  • You can use this link to download the MySql Driver. Once you download it, you need to make sure it is on the class path for the web server that you are using. The particulars of configuring JDBC drivers for a server vary from server to server. You may want to edit your question to include more details to get a better answer.