Friday, April 20, 2012

Consistent grid headers with Flexigrid for jQuery

So I'm trying to use the flexigrid plugin. It looks like it's going to work great aside from the fact that it looks like you have to manually set the column widths. Otherwise, the column headers do not match up with the body columns.



Is there any way of automatically matching these up, while still allowing the column widths to be defined by the length of the content in the columns (as is the normal table behavior).



Thanks!





"Lazy initialization" of jdbc connections from jndi datasource/connection pool: feasibility

I have a main controller servlet in which i instantiate a datasource. The servlet opens and closes the connections. Mainly, the servlet instantiates a command from the application using the "factory pattern". here is some code to explain:



public void init() throws ServletException {
super.init();
try {
datasource =(DataSource) getServletContext().getAttribute("DBCPool");
}
catch (Exception e) {

}
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//some code...
connection = getConnection();//where getConnection is a method: datasource.getconnection();
//now a command (a java class) is instantied, to which the CONNECTION obj is passed as parameter
cmdFactory.getInstance().getCommand(Cmd).execute(tsk,connection);

//Then wherever there is catch exception i close() the connection
// and it is always closed in finally
finally {
if(connection!=null)
connection.close()
}

}


Now , this works fine However now i got some new cases where some commands might not need to open a db connection because the data it is seeking for are cached in an identity map.



I tried to pass the "Connection" obj as a "null" parameter in the .execute(tsk,connection); and then in the corresponding java class to open a connection if needed



--> it did open the connection, however when process goes back to servlet : "Connection" is null as thus not closed.

What can i do to make the "Connection" obj's value get updated so that when back in servlet it is not "Null" anymore and i'd be able to close it?



I generally prefer to use a controller servlet that opens/close db connections, so what would be the best way to deal this kind of scenario where you have to do some sort of "lazy loading" a db connection from the pool and at the same time keep the opens/close of db connection assigned to the servlet?



Update (to explain further):




  • say i have a command : X.java

  • this command might/might not need a db connection (depends if the data searched for are in the identity map or not)



The system that i would like to have is:



(1)"client request"



(2)---> "Servlet": command.execute(connection)//where connection = null for now



(3) ---> "Command X": Do i need to go to database or record is in identity map?

(3.a) Case where it is needed to go to the database:

(3.a.1)connection = datasource.getconnection

(3.a.2) go get the data



(4)--->back to servlet: close "connection" in "Servlet"



Right now it is working until (3.a.2), but once back in (4) it appears that connection is still "null" and thus the code:



finally { 
if(connection!=null)
connection.close()
}


Does not work (doesn't close the connection) and thus the db pool get drained like that.
How could connection - which starts as "null" and changes inside command "X"- get "globaly" updated to the its new value, and not only "updated" inside the scope of command "X"?





What is causing this in android webView?

I am getting the following exception and not able to debug it.



Please help.



    04-20 10:55:58.052: WARN/dalvikvm(9255): threadid=8: thread exiting with uncaught exception (group=0x400207d8)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): FATAL EXCEPTION: WebViewCoreThread
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.view.ViewRoot.checkThread(ViewRoot.java:2812)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.view.ViewRoot.invalidateChild(ViewRoot.java:607)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:633)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.view.ViewGroup.invalidateChild(ViewGroup.java:2505)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.view.View.invalidate(View.java:5115)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.webkit.WebView.viewInvalidate(WebView.java:2565)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.webkit.WebView.invalidateContentRect(WebView.java:2584)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.webkit.WebView.access$6200(WebView.java:304)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.webkit.WebView$PrivateHandler.handleMessage(WebView.java:7860)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.os.Handler.dispatchMessage(Handler.java:99)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.os.Looper.loop(Looper.java:123)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:637)
04-20 10:55:58.092: ERROR/AndroidRuntime(9255): at java.lang.Thread.run(Thread.java:1096)
04-20 10:55:58.102: WARN/ActivityManager(172): Force finishing activity com.Hy5/.activity.Hy5CanvasActivity


thanks
Sneha





Xcode : How to display json image array in UITableView using multithreading?

I have few images on my server whose names are stored in the phpmysql table. The table contains two fields: id and images. I have prepared a php to fetch the images in json encoded formatted as mentioned:



jsonFetch.php



<?php
$dbhost = "localhost";
$dbname = "userauth";
$dbuser = "root";
//$DB_Pass = "root";
$dbtable = "images";

@mysql_connect($dbhost, $dbuser);
$db = mysql_select_db($dbname);


$sql = "SELECT * FROM $dbtable";
$query = mysql_query($sql);

while($row = mysql_fetch_array($query))
{
$rows[] = array(
//"id" => $row[0],
"image" => $row[1]
//"description" => $row['description']);
);
}

$json = json_encode($rows);
$callback = $_GET['images'];
echo $callback.$json ;
//print_r($json);

?>


Now, when i hit the url, i am getting following response:



[{"image":"./95462"},{"image":"./8838upload_image.jpg"}{"image":"./43185upload_image.jpg"},{"image":"/17426upload_image.jpg"}]



I am getting json array as above.



The next step is to display the above array in multithreaded manner in UITableView.
I am getting the images from url when i hardcode them but when it comes to json parse, i am a noob. I have tried every possible manner in which json can be parsed so for you reference, i am posting the .m file. :



#import "json.h"

@interface profilePhotos(Private)
- (void) initialize;
- (void) loadImage:(id)arg;
- (void) updateTableView:(id)arg;
- (void) addImagesToQueue:(NSArray *)images;
- (void) addImagesToQueue:(NSArray *)arrayImages;
- (void) addImagesToQueue:(NSArray *)arrayDataFromServer;
- (void) showcommentView;
- (void) hidecommentView;
@end

@implementation profilePhotos
@synthesize photosTable;
@synthesize addPhotos;
@synthesize deletePhotos;
@synthesize back;
@synthesize imageQueue, loadedImages, imageLoaderOpQueue, commentView;
//@synthesize photosView;


-(void)initializeWith:(int)buttonTag{

tag = buttonTag;

NSLog(@"tag = %d", tag);
}

- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
if (!(self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
return self;
}

[self initialize];
return self;
}

- (void) awakeFromNib
{
NSLog(@"AsyncImageLoadingViewController::awakeFromNib called");
[super awakeFromNib];
[self initialize];
}

- (void) viewDidLoad
{
NSLog(@"AsyncImageLoadingViewController::viewDidLoad called");
[super viewDidLoad];
}

- (void) viewDidAppear:(BOOL)animated
{
NSLog(@"AsyncImageLoadingViewController::viewDidAppear called");
[super viewDidAppear:animated];


NSArray *images = [NSArray arrayWithObjects:
@"http://dl.dropbox.com/u/9234555/avatars/ava01.gif",
@"http://dl.dropbox.com/u/9234555/avatars/ava02.gif",
@"http://dl.dropbox.com/u/9234555/avatars/ava03.gif",
@"http://dl.dropbox.com/u/9234555/avatars/ava04.gif",
@"http://dl.dropbox.com/u/9234555/avatars/ava05.gif", nil];

[self addImagesToQueue:images];
NSLog(@"addImagesToQueue: %@",self);


}


#pragma mark -
#pragma mark Private Methods

/*!
@method
@abstract initializes class variables
*/
- (void) initialize
{
NSLog(@"AsyncImageLoadingViewController::initialize called");

NSMutableArray *a = [[NSMutableArray alloc] init];
self.imageQueue = a;
//[a release];

a = [[NSMutableArray alloc] init];
self.loadedImages = a;
//[a release];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
self.imageLoaderOpQueue = queue;
//[queue release];
}

/*!
@method
@abstract updates tableview for the newly downloaded image and scrolls the tableview to bottom
*/
- (void) updateTableView:(id)arg
{
NSLog(@"AsyncImageLoadingViewController::updateTableView called");

if ((arg == nil) || ([arg isKindOfClass:[UIImage class]] == NO)) {
return;
}

// store the newly downloaded image
[self.loadedImages addObject:arg];
//[arg release];

// refresh tableview
[self.photosTable reloadData];

// scroll to the last cell of the tableview
NSIndexPath *lastRow = [NSIndexPath indexPathForRow:([self.loadedImages count] - 1) inSection:0];
[self.photosTable scrollToRowAtIndexPath:lastRow
atScrollPosition:UITableViewScrollPositionBottom
animated:YES];
}

/*!
@method
@abstract downloads images, this is the method that dispatches tasks in the operation q ueue
*/
- (void) loadImage:(id)arg
{
NSLog(@"AsyncImageLoadingViewController::loadImage called");

if ((arg == nil) || ([arg isKindOfClass:[NSString class]] == NO)) {
return;
}

// create a local autorelease pool since this code runs not on main thread
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

// fetch the image
NSLog(@"AsyncImageLoadingViewController::loadImage - will download image: %@", arg);
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:arg]];
UIImage *image = [UIImage imageWithData:data];
NSLog(@"image: %@",image);

// update tableview with the downloaded image on main thread
[self performSelectorOnMainThread:@selector(updateTableView:) withObject:image waitUntilDone:NO];

//[pool release];
}

/*!
@method
@abstract adds images to the queue and starts the operation queue to download them
*/
- (void) addImagesToQueue:(NSArray *)images
{
NSLog(@"AsyncImageLoadingViewController::addImagesToQueue called");

[self.imageQueue addObjectsFromArray:images];
NSLog(@"addImagesToQueue Array: %@", self);

// suspend the operation queue
[self.imageLoaderOpQueue setSuspended:YES];

// add tasks to the operation queue
for (NSString *imageUrl in self.imageQueue) {
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadImage:) object:imageUrl];
[self.imageLoaderOpQueue addOperation:op];
// [op release];
}

// clear items in the queue and resume the operation queue to start downloading images
[self.imageQueue removeAllObjects];
[self.imageLoaderOpQueue setSuspended:NO];
}


#pragma mark -
#pragma mark UITableViewDataSource Methods

- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{

return [self.loadedImages count];



}

- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

static NSString *CellIdentifier = @"CellIdentifier";

cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
//cell = [[[UITableViewCell alloc] initWithStyle:UITableViewStyleGrouped reuseIdentifier:CellIdentifier] autorelease];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewStyleGrouped reuseIdentifier:[NSString stringWithFormat:@"cellID%d",indexPath.row]];

cell.accessoryType =UITableViewCellAccessoryNone;
//cell.accessoryType =UITableViewCellAccessoryDisclosureIndicator;




}

for(UIView *subviews in cell.subviews)
[subviews removeFromSuperview];


UIImageView *photo;
photo=[[UIImageView alloc] init];
[photo setImage:[self.loadedImages objectAtIndex:indexPath.row]];
[photo setFrame:CGRectMake(0, 5, 150, 120)];
[cell addSubview:photo];
return cell;
}





-(void)aMethod:(UIButton *)sender{

//[sender tag];

NSIndexPath *indexPath = [photosTable indexPathForCell: (UITableViewCell*)[[sender superview]superview]];

NSLog(@"[sender tag] is %d",[sender tag]);



if([sender tag]==indexPath.row){

textField = (UITextField*)[cell viewWithTag:[sender tag]];
textField.hidden=NO;
}
//}


}



#pragma mark -
#pragma mark UITableViewDelegate Methods

-(void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

[tableView deselectRowAtIndexPath:indexPath animated:YES];


}




- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload{
// [self setPhotosView:nil];
[self setPhotosTable:nil];
[self setAddPhotos:nil];
[self setDeletePhotos:nil];
[self setBack:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:( UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


I believe that something is needed to be done in viewDidAppear method but what is it i don't understand.



Kindly, help me out. I have tried every possible json method . May be i am making some errors in that but i am all the way frustrated. Please help me please.





(Solved) Jquery, activate a script when a hash is in url

So I have some images that are positioned absolutely above a page set to hidden that display inherit when you click on the appropriate link triggering the event that displays them.



Now, here's where my question comes in. Say I assign an image an ID of "example" - is there any way that when someone enters the site with a hash tag #example or clicks on a link with the hash tag #example in the url, that the event would trigger for an image with the same ID? I'm really stumped on this one



What I had been using is this:



$("#activate1").click(function () {
$("#flyer1").css("display", "inherit");


});



Which worked fine but now I'll have to add flyers each week which would mean I need to change that unless I want to write the above code for each unique case. But on top of that, I also now have to send them to people through a link so the script now has to trigger when they click the link - I figured the best way to tackle this would probably be implementing a hash tag trigger





Can you use Stylus, Jade, and Coffeescript for development with a native mobile wrapper like Trigger.io?

I'm excited to be starting on my first project, and just wondering if you have any experience or pointers about the best way to use Stylus, Jade, and Coffeescript for development?



I'm sure I can figure something out, but thought I'd see if there was a recommended/fastest way.





How to make custom title bar for my android application?

I want to make custom title bar for my application for cahnging the color of my applicatin name.How can i do this?





CakePHP Validation Regex

I have a quick regex question that I figured someone might know off the top of their head. What would the regex be for CakePHP's validation be if I only want to allow upper/lower alphanumber, spaces, punctuation, and quotes? This is what I have, but it's off:



 'rule' => array('custom', '/[a-z0-9\x20\x21\x2E\x3A\x3B\x3F\x2C\x27\x22]{0,600}/i'),


From what I get, the a-z0-9 covers alphanumeric, but shouldn't the \xXX cover the punctuation with the ASCII hex codes? And then the {0,600] means a length of 0-600 characters, and i means upper and lower. What am I missing?



For example: valid: This is a "valid text", which contains ' and punctuation!



invalid: This is an obvious XSS attempt





How to tell if iPad is black or white via code?

I was wondering if there was a way to tell if an iPad is black or white via code?
A simple Google search hasn't turned up anything.



Thanks!



-Shredder2794





How to use ggplot to group and show top X categories?

I am trying to use use ggplot to plot production data by company and use the color of the point to designate year. The follwoing chart shows a example based on sample data:
enter image description here



However, often times my real data has 50-60 different comapnies wich makes the Company names on the Y axis to be tiglhtly grouped and not very asteticly pleaseing.



What is th easiest way to show data for only the top 5 companies information (ranked by 2011 quanties) and then show the rest aggregated and shown as "Other"?



Below is some sample data and the code I have used to create the sample chart:



# create some sample data
c=c("AAA","BBB","CCC","DDD","EEE","FFF","GGG","HHH","III","JJJ")

q=c(1,2,3,4,5,6,7,8,9,10)
y=c(2010)
df1=data.frame(Company=c, Quantity=q, Year=y)

q=c(3,4,7,8,5,14,7,13,2,1)
y=c(2011)
df2=data.frame(Company=c, Quantity=q, Year=y)

df=rbind(df1, df2)

# create plot
p=ggplot(data=df,aes(Quantity,Company))+
geom_point(aes(color=factor(Year)),size=4)
p


I started down the path of a brute force approach but thought there is probably a simple and elegent way to do this that I should learn. Any assistance would be greatly appreciated.





How to implement a Security token in a WCF soap response?

I am implementing an API from a bank and they require a security token to be provided. In the header of every soap message there is something which looks as follows:



<soapenv:Header>
<tpw:BinarySecurityToken ValueType="MAC" Id="DesMacToken" EncodingType="Base64" Value="**xvz**"/>
</soapenv:Header>


According to their documentation I need to generate an 8 byte MAC value on the body of each message. The MAC is generated by the CBC-MAC algorithm and DES as the block cipher. The contents of the soapenv:Body tag of each message is used as the data for the MAC calculation.



So my question is how do I get WCF to do this? I have put the following code together to create the MAC value, but am unsure how to get this into the header of every message.



private string GenerateMAC(string SoapXML)
{
ASCIIEncoding encoding = new ASCIIEncoding();

//Convert from Hex to Bin
byte[] Key = StringToByteArray(HexKey);
//Convert String to Bytes
byte[] XML = encoding.GetBytes(SoapXML);

//Perform the Mac goodies
MACTripleDES DesMac = new MACTripleDES(Key);
byte[] Mac = DesMac.ComputeHash(XML);

//Base64 the Mac
string Base64Mac = Convert.ToBase64String(Mac);

return Base64Mac;
}

public static byte[] StringToByteArray(string Hex)
{
if (Hex.Length % 2 != 0)
{
throw new ArgumentException();
}

byte[] HexAsBin = new byte[Hex.Length / 2];
for (int index = 0; index < HexAsBin.Length; index++)
{
string bytevalue = Hex.Substring(index * 2, 2);
HexAsBin[index] = Convert.ToByte(bytevalue, 16);
}

return HexAsBin;
}


Any help will be greatly appreciated.



More info:
The bank has provided a WSDL which I have used as a service reference. An example of a response that is sent:



[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.MessageContractAttribute(WrapperName="LogonRequest", WrapperNamespace="http://webservice.com", IsWrapped=true)]
public partial class LogonRequest {

[System.ServiceModel.MessageHeaderAttribute(Namespace="http://webservice.com")]
public DataAccess.BankService.BinarySecurityToken BinarySecurityToken;


The BinarySecurityToken (that goes in the header) looks as follows:



 [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.233")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://webservice.com")]
public partial class BinarySecurityToken : object, System.ComponentModel.INotifyPropertyChanged {

private string valueTypeField;

private string idField;

private string encodingTypeField;

private string valueField;

public BinarySecurityToken() {
this.valueTypeField = "MAC";
this.idField = "DesMacToken";
this.encodingTypeField = "Base64";
}




In MIPS, how do I divide register contents by two?

Let's say I have $t0, and I'd like to divide its integer contents by two, and store it in $t1.



My gut says: srl $t1, $t0, 2



... but wouldn't that be a problem if... say... the right-most bit was 1? Or does it all come out in the wash because the right-most bit (if positive) makes $t0 an odd number, which becomes even when divided?



Teach me, O wise ones...





Azure Web Role stuck initializing

I have an MVC web role I am trying to deploy to Azure. It keeps bouncing from Starting > Initializing. I have done my research, and found two main causes for this.




  1. One of the assemblies I am using does not have Copy Local = True set

  2. The diagnostics connection string is wrong.



I Have triple checked my diagnostics connection and it is fine. I can use the exact same connection string in a Worker Role and it starts just fine So I assume the problem is related to #1 above.



This was a standard MVC project I added an azure deployment project to, so my guess is I am missing something an "Azure web role project" would automatically do for me. I already selected the "Add deployable assemblies" option from the projects context menu so the MVC bits should be set up, right?



Here is a list of my references, the items highlighted have Copy Local = true. Am I missing one? What else do I need to do to get this to deploy? Are there any diagnostics tools I can use to help me figure it out?



update:

I love when I find more information :)



So I was finally able to catch it in a state when I can remote into the server. I opened IIS and saw everything was there that should be. I tried to hit the site locally, but I get this error.




Could not load file or assembly 'System.Web.WebPages' or one of its
dependencies. The located assembly's manifest definition does not
match the assembly reference. (Exception from HRESULT: 0x80131040)




So there is (at least one of) my error.....but why? The site runs fine in IIS express, and it runs fine in development fabric. I feel like a noob here. What did I do wrong?



enter image description here





How to return promise that will resolve with the result of several functions?

I'm developing a jQuery plugin, which pretends to translate elements on the page, automatically depending on the user's browser language. Translations will be stored in .json files.



When you call the plugin, you pass a package name (or an Array of them) and then it will try to load the language file in the following way:




  • If the browser's language is simple, for example 'en' and you only have indicated a package, it will try to load the following: packageName-en.json

  • If the browser's language is composed, for example 'en-US' it will try to load the same as before but with: packageName-en.json AND packageName-en-US.json

  • If more than one package is indicated, it will try to follow one of the two previous path for each package.



So, in the plugin I have this:



$.fn.Translator = function(pkg, options){
Translator.initialize(pkg, options).done(function(){
return this.each(Translator.translate);
});
};


So, somewhere in my initialize function, I have this:



loadLanguages : function(){
$.each(self.options.packages,function(i, pkg){

});
}


Which will call this function :



getLanguage : function(pkg, language){
var self = this, url;
if (self.options.path)
url = self.options.path + '/';
url += [pkg, language].join('-');

return $.ajax ({
url : url,
dataType : "json",
cache : self.options.cache
});
}


The problem is that since that function will be called probably multiple times, I don't know how to make initialize to return a promise which will be resolved once ALL of the functions have been called.





Eclipse JBoss Visual Editor: 64 bit

I'm using windows 64bit, JDK 64bit and Eclipse 64bit version, and I receive error that doesn't support 64bit.



My question is: which "64bit thing" that Visual Editor doesn't support: Windows/IDE/or Compiler.



I ask this because I want to know the real problem behind to fix it.



Thanks :)





Lower triangular matrix and upper triangular matrix give me wrong answer

I'm working in LU Decomposition in C.My code is very simple
Algorithm can be parallelized using two loops one for updating lower triangular matrix and one for
updating upper triangular matrix ,but it seems I miss understand something :(



//////////////////////////////////////////////////////////////////////////////
//Those loops have to execute in parallel.//


for (i=0 ; i<N ; i++){
A[i][i]=1;
for (j=i+1 ;j<N ;j++){
L[j][i] = A[j][i]/A[i][i]; //*Update L*//
}
for (j=i+1;j<N;j++){
for(k=i+1 ;k<N;k++){
A[j][k] = A[j][k] - A[i][k] * U[j][i];//*Update U*//
}
}
}

/////////////////////////////////////////////////////////////////////////

//******** Displaying LU matrix**********//

printf("\n Matrix after L transformation: \n");

for(i=0;i<=N;i++)
{
for(j=0;j<=N;j++)
printf("%6.0f\t",L[i][j]);
printf("\n");
}
printf("\n");

for(i=0;i<=N;i++)
{
for(j=0;j<=N;j++)
printf("%6.0f\t",U[i][j]);
printf("\n");
}


This is what I should to get ?! what I'm doing wrong



L =

1.0000 0 0 0 0
0.2000 1.0000 0 0 0
0.2000 0.1667 1.0000 0 0
0.2000 0.1667 0.1429 1.0000 0
0.2000 0.1667 0.1429 0.1250 1.0000


U =

50.0000 10.0000 10.0000 10.0000 10.0000
0 48.0000 8.0000 8.0000 8.0000
0 0 46.6667 6.6667 6.6667
0 0 0 45.7143 5.7143
0 0 0 0 45.0000


but what I got is



 Source Matrix :
50 10 10 10 10
10 50 10 10 10
10 10 50 10 10
10 10 10 50 10
10 10 10 10 50

Matrix after L transformation:

0 0 0 0 0 10
10 0 0 0 0 10
10 10 0 0 0 10
10 10 10 0 0 10
10 10 10 10 0 0
0 0 0 0 0 0

0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0


Thanks





why javascript mouseover event doesn't work in chrome?

Suppose I have a select tag and some option tag in it,then I want add mouseover event on option tag,I have tried some ways,but all doesn't work chrome:



method 1:



function showtrail(){
console.log("mouseover");
}

var el=document.querySelectorAll('#select option');
for(var i=0;i<el.length;i++){
el[i].addEventListener("mouseover",showtrail,false);
}


method 2:



<option onmouseover="showtrail()"  value="d">d</option>


method 3:
off course I tried jquery hover method



all this doesn't work in chrome ,only work in firefox



how can I solve this problem ?add hover or mouseover event on option tag ,and could work fine in chrome





Java Socket API: How to tell if a socket has been closed?

I am running into some issues with the java Socket API. I am trying to display the number of players currently connected to my game. It is easy to determine when a player has connected. However, it seems unecessarily difficult to determine when a player has disconnected using the socket API.



Calling isConnected() on a socket that has been disconnected remotely always seems to return true. Similarly, calling isClosed() on a socket that has been closed remotely always seems to return false. I have read that to actually determine whether or not a socket has been closed data must be written to the output stream and an exception must be caught. This seems like a really unclean way to handle this situation. We would just constantly have to spam a garbage message over the network to ever know when a socket had closed.



Is there any other solution?





Mysql query for matching month and year

I have form with 4 fields namely(start month, start year, end month, end year)
and MySQL table structure is like id, customer id, amount, month, year



Now, I need to display the rows with matching condition as between the start month and year and end month and year.



I tried this query



select id,customer id,concat(month,'-',year) as d1 from payroll where
empid='$_POST[emp_id]' and (STR_TO_DATE(d1,'%m-%Y') between
STR_TO_DATE('$_POST[fmonth]-$_POST[fyear]','%m-%Y') and
STR_TO_DATE('$_POST[tmonth]-$_POST[tyear]','%m-%Y'))


Please advise....





How to close a branch WITHOUT removing it from history in git?

I'd like to make a commit and close its branch, without removing it from history.



With mercurial I'd commit --close-branch, then update to a previous one, and go on working. With git... I'm confused.





How to push to Heroku without putting the app down

Just wondering how everyone pushes updates to their production server on Heroku, without bringing the app down for a few couple of seconds?



Pushing to Heroku (especially using something like Unicorn), takes a while for the web app to load. Especially when there are end-users trying to access the site. They end up with 503 pages.It takes up to 30 secs to a minute for Unicorn processes to load.





Facebook PHP SDK - is user "liking" my app?

I have two things:
- how to do: using PHP SDK for Facebook check that user is liking my app?



I need this because client want it.



 $isLike = /* Code to check this */

if ($isLike){

//if user like my app
}else{

//if not

include 'generate.php';
}


And what I should ask this question in "valid" english?





Is there any hard-wired limit on recursion depth in C

The program under discussion attempts to compute sum-of-first-n-natural-numbers using recursion. I know this can be done using a simple formula n*(n+1)/2 but the idea here is to use recursion.



The program is as follows:



#include <stdio.h>

unsigned long int add(unsigned long int n)
{
return (n == 0) ? 0 : n + add(n-1);
}

int main()
{
printf("result : %lu \n", add(1000000));
return 0;
}


The program worked well for n = 100,000 but when the value of n was increased to 1,000,000 it resulted in a Segmentation fault (core dumped)



The following was taken from the gdb message.



Program received signal SIGSEGV, Segmentation fault.
0x00000000004004cc in add (n=Cannot access memory at address 0x7fffff7feff8
) at k.c:4


My question(s):




  1. Is there any hard-wired limit on recursion depth in C? or does the recursion depth depends on the available stack memory?


  2. What are the possible reasons why a program would receive a reSIGSEGV signal?






using signal handler for ctrl-c - need help on infinite loops

I am using signal handler for ctrl-c signal. i.e whenever ctrl-c signal is generated instead of exiting the application I do some action.



Let us suppose if my application hangs due to while(1) loop (any error condition) is it possible for me to exit application only in that case?



ex:



void handle()
{
/*do some action*/
----
----
---

if ( while(1) detected)
{
exit(0);
}
}


main()
{
struct sigaction myhandle;
myhandle.sa_handler = handle;
sigemptyset(&myhandle.sa_mask);
myhandle.sa_flags = 0;
sigaction(SIGINT, &myhandle, NULL);

while(1);
}


Thanks





Login from a site to another site in https

i'm new to stackoverflow and I have a question for you:



I have to do an automatic login from my wesite to another external website (not mine).



This site use https and when i go on the site address it ask me (with the classical popup form) to enter username and password.
I've tried to do a POST in this way



http://www.terminally-incoherent.com/blog/2008/05/05/send-a-https-post-request-with-c/



where in the string post_data I have put "Username=xxxx&Password=xxxx"



but doesn't work; the code returned was 401: Unauthorized.



Any suggestions?



Thank you!





Conditionally sorting elements by multiple properties in multiple tables with LINQ

I have recently needed to sort a list of pages and navigation menu entries, which are each associated with the other.



Each Navigation has a Page property. Each Page has a Navigation property. They are foreign key references in my database.



I have a list of Navigation items as well as a list of every Page item. The problem is that regardless of a Page being associated with a Navigation, it is stored in the list of Page items.



I want to produce a sorted list of Page items like so: Items with a non-null Navigation are sorted by the Page.Navigation.Index property. Items with a null Navigation are sorted by the Page.Title property and then the Page.ID property.



Below is what we currently do and it works for the most part, with a few exceptions.
The problem I have with this is it does not handle duplicated titles for pages without a navigation associated to them.



List<Page> page1 = db.Navigations.OrderBy(n => n.Index).Select(n => n.Page).ToList();

List<Page> page2 = db.Pages.Where(p => !db.Navigations.Contains(p.Navigation)).ToList();

model.Pages = page1.Concat(page2).ToList();


Here's some example data and expected results



Pages Table (PageID, Title, Content)
0, "Home", "<html>This is a home page</html>"
3, "Some Page", "<html>This is some page.</html>"
2, "Some hidden page", "<html>This is some hidden page.</html>"
4, "Products", "<html>We've got products!</html>"
5, "aaaaa", "<html>This should be sorted to the top of pages with no nav</html>"

Navigations Table (PageID, Index)
0, 0
3, 2
4, 1

Output (PageID, Title, Content)
0, "Home", "<html>This is a home page</html>"
4, "Products", "<html>We've got products!</html>"
3, "Some Page", "<html>This is some page</html>"
5, "aaaaa", "<html>This should be sorted to the top of pages with no nav</html>"
2, "Some hidden page", "<html>This is some hidden page.</html"


I'm curious if this is possible to do in a nicer looking way and also in the query syntax instead of the procedural syntax.





Error:beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS

I inherited this application from a developer who no longer with the company.
After I get latest and run the app, I get the following error:



Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.



Parser Error Message: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.



Source Error:



Line 170:  <location path="winLogin.aspx">
Line 171: <system.web>
Line 172: <authentication mode="Windows" />
Line 173: <authorization>
Line 174: <allow users="*" />


The error mentions IIS however since this is a VS 2005 project I am using the default web browser.



Any ideas on how to resolve?





Binding To Singleton Class Observable Collection Member

I just can't seem to figure this out. I found some similar Questions here but either I can't figure out the right direction for my approach or I am doing something completly wrong.



My Application has a Singleton Class Logger, which saves Log messages from every class in my program.



public class Logger
{
private Logger()
{

}

private static volatile Logger instance;

public static Logger GetInstance()
{
// DoubleLock
if (instance == null)
{
lock (m_lock)
{
if (instance == null)
{
instance = new Logger();
}
}
}
return instance;
}

//Helper for Thread Safety
private static object m_lock = new object();

private ObservableCollection<string> _Log;

public ObservableCollection<string> Log
{
get { return _Log; }
}

public void Add(string text)
{
if (_Log == null)
_Log = new ObservableCollection<string>();

Log.Add(DateTime.Now.ToString() + " " + text);
}

public void Clear()
{
_Log.Clear();
}

}


Now I want to bind Log to ListBox in my MainWindow, but I can't figure out the right Binding



<ListBox Name="lstboxLog" Grid.Row="2" Margin="10,0,10,10" ItemsSource="{Binding Source={x:Static tools:Logger.Log}}" Height="100" />


tools is the namespace of the singleton class in my XAML. I'm sure this is simpler than I think, but I am just overlooking something.





jquery not working in IE after ajax call

I am using organictabs plugin, which I initiate in every page load in this form:



    $(function() {
$("#example-one").organicTabs();

$("#example-two").organicTabs({
"speed": 200
});
});


The tabs work fine in all browsers, and then I perform an ajax call which regenerates the tabs with the following code:



if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText,'page-wrap');

$(function() {
$("#example-two").organicTabs({
"speed": 200
});

});
}


Again, the tabs are regenerated properly and everything works fine in all browsers EXCEPT in IE, when I try to switch tabs it doesn't work. I am initiating the jquery code onreadystate change, and i really can't figure out what can the problem be with IE?



Any help will be greatly appreciated.



All the best





Javascript, for-loop, not carrying the value

The form that fetches the value:



<input name="validatecard" type="text" id="myCardNumber"> 
<input onclick="isLuhn()" type="button" value="Check Credit Card" />


The Javavascript:



function isLuhn(cardnumber) {
var number_element = document.getElementById('myCardNumber');
var cardnumber = number_element.value;

e= '';
i= '';
var sum1 = 0;
var sum2 = 0;
for(i = cardnumber.length; i > 0; i -=2){
sum1 = sum1 * i;

for (e = cardnumber.length; e > 0; e -=2){
sum2 = sum2 + e;
}}}


I want this loop to for the value of cardnumber, say 4000 0000 0000 0302, start at the second to last number in the first loop and the last number and iterate backwards to 0.
I want every number that the loop iterates over to be added to sum1/sum2.
So if the above number assumed, iterating from the last
sum1 = 2 + 3 + 0 + 0 + 0 + 0 + 0 + 0. Right now it is working the the length of the cardumber which is 16 and goes 14, 12, 10, 8, 6 etc.. How do I set it right?