Wednesday, May 16, 2012

Specified cast is not valid when getting Datatable Column Value

The above error message appears when I am trying to get Column Value from Datatable.



This is what I find in the stacktrace:




System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()

at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable
1
source)




 and this in the TargetSite when debugging:



{ Boolean b__0(System.Data.DataRow)}




Here is my code:
DataTable hr = new DataTable();



            hr.Columns.Add("BookingDate");
hr.Columns.Add("BookingId");
hr.Columns.Add("BookingSource");
hr.Columns.Add("CheckInDate");
hr.Columns.Add("CheckOutDate");


for (int i = 0; i < gmisc.GetModifiedBookings(gmoreq).Bookings.Length; i++)
{
hr.Rows.Add();
hr.Rows[i]["BookingDate"] = Convert.ToDateTime(gmisc.GetModifiedBookings(gmoreq).Bookings[i].BookingDate.ToString());
hr.Rows[i]["BookingId"] = Convert.ToInt64(gmisc.GetModifiedBookings(gmoreq).Bookings[i].BookingId.ToString());
hr.Rows[i]["BookingSource"] = gmisc.GetModifiedBookings(gmoreq).Bookings[i].BookingSource.ToString();
hr.Rows[i]["CheckInDate"] = Convert.ToDateTime(gmisc.GetModifiedBookings(gmoreq).Bookings[i].CheckInDate.ToString());
hr.Rows[i]["CheckOutDate"] = Convert.ToDateTime(gmisc.GetModifiedBookings(gmoreq).Bookings[i].CheckOutDate.ToString());



}
Int64 BookingId = (from DataRow dr in hr.Rows
where (Int64)dr["BookingId"] == BookId
select (Int64)dr["BookingId"]).FirstOrDefault();
TextBox1.Text = Convert.ToString(BookingId);


Where did I go wrong, if somebody can please tell me.





place a jlabel(s) at a desired location giving its coordinates

I have a JPanel in which I need to add bunch of JLabels at a required coordinates. These JLabels will have key Listeners assigned to them that will determine new position using arrow keys.



To be more specific I know how to do it when there is only one JLabel but whenever I put a more of them the things mess up. while I use arrow key the first JLabel moves but all other JLabel disappears.



Can Anyone give me some hints to write a method to put a JLabel in a specific coordinate and also move them using arrow key later without making other JLabels dissapear?



Huge Thanks in Advance





Mobile jquery web app doesnt work on android browser

It doesn't work on my android handset, see for yourself if it does: appaboutapps.co.uk



please trouble shoot this using the 'view source' option and get back to me.





ASP.NET Membership Database vs. Membership AND User Database

Is there any reason why I shouldn't add contact and extended data to the users database with a custom membership provider?



What is the advantage of keeping separate one-to-one tables for user data and membership data? As I understand it, the common method is to keep separate tables. I'm thinking it would be better to have one table for users to keep SQL statements simple and custom code the membership provider.





join omitting output lines when input sorted numerically

i have two files, aa and bb:



 $ cat aa 
84 xxx
85 xxx
10101 sdf
10301 23

$ cat bb
82 asd
83 asf
84 asdfasdf
10101 22232
10301 llll


i use the join command to join them:



 $ join aa bb
84 xxx asdfasdf


but what expected is 84, 10101 and 10301 all joined.
Why only 84 has been joined?





how to get count of ratings in the past 24hrs using django datetime?

I have a model name Ratings where there is a timestamp. I want to limit the user to only 3 ratings per day. how do I get a count of ratings for a particular user the past 24hrs?



class Ratings(models.Model):   
user = models.ForeignKey(User)
book = models.ForeignKey('Books')
rating = models.IntegerField(max_length=150)
timestamp = models.DateTimeField(auto_now_add=True)
is_checkedin_rating = models.BooleanField()


edit*
To be more clear, I want to find the count of ratings by a particular user in 24hrs. So from let's say 5/13 12AM to 5/14 12AM, get the count of ratings.





iPad application with multiple DetailView and have navigation in detailview

i search for a way to have multiple detail view in iPad application and i find the sample code in apple developer site http://developer.apple.com/library/ios/#samplecode/MultipleDetailViews/Introduction/Intro.html , but now i want to have navigation in detail view which this sample does not cover, i add uinavigationcontroller to detail view as :



-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
ReportsViewController_iPad *master = [[ReportsViewController_iPad alloc] initWithNibName:@"ReportsViewController_iPad" bundle:nil];

DetailViewController_iPad *detail = [[DetailViewController_iPad alloc] initWithNibName:@"DetailViewController_iPad" bundle:nil];

UINavigationController *masterNavController = [[[UINavigationController alloc] initWithRootViewController:master ] autorelease];

UINavigationController *detailNavController = [[[UINavigationController alloc] initWithRootViewController:detail ] autorelease];

splitViewController.viewControllers = [NSArray arrayWithObjects:masterNavController , detailNavController, nil];

[window addSubview:splitViewController.view];
[window makeKeyAndVisible];

return YES;
}


but when i run the sample i got error



[UINavigationController showRootPopoverButtonItem:]: unrecognized selector sent to instance...



showRootPopoverButtonItem is a method define in a protocol in RootViewController



@protocol SubstitutableDetailViewController
- (void)showRootPopoverButtonItem:(UIBarButtonItem *)barButtonItem;
- (void)invalidateRootPopoverButtonItem:(UIBarButtonItem *)barButtonItem;
@end



So Thanks inadvance





Required field validator for User control not working

Hi I have created user control for re-sizable text box.



<asp:Panel ID="PanelText" runat="server" CssClass="frameText">
<asp:TextBox runat="server" ID="TextBoxResizable" CssClass="noborder" Width="100%"
Height="100%" TextMode="MultiLine">
</asp:TextBox>
</asp:Panel>
<cc1:ResizableControlExtender ID="ResizableTextBoxExtender" runat="server" TargetControlID="PanelText"
ResizableCssClass="resizingText" HandleCssClass="handleText" OnClientResizing="OnClientResizeText" />


And have created Validator property for this control like:



[ValidationProperty("Text")]
public partial class ResizableTextBoxControl : System.Web.UI.UserControl
{ public string Validator
{
get { return this.TextBoxResizable.Text; }
}
protected void Page_Load(object sender, EventArgs e)
{

}
}


In aspx page I am using this control like:



<uc1:ResizableTextBoxControl ID="tbDescription" MinimumHeight="50" MinimumWidth="100"
MaximumHeight="300" MaximumWidth="400" runat="server" onKeyPress="javascript:Count(this,1500);" onKeyUp="javascript:Count(this,1500);" ValidationGroup="vgSubmit" ></uc1:ResizableTextBoxControl>

<asp:RequiredFieldValidator ID="rfvDescription" runat="server" controlToValidate="tbDescription" ValidationGroup="vgSubmit" ErrorMessage="Description" Text="*" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>


When I click on submit, "tbDescription" does not appear to be mandatory.
What can be wrong with the code?





Base64 encoding in Sproutcore

I need to invoke restful webservices in Sproutcore which requires authentication header for http request. I write a code like in Sproutcore:



authHeader: function () {
var userAndPass = "username:password";
var auth = "Basic " + Base64.encode(userAndPass);
return auth;
},


However, when I run it, sadi Base64 is not defined.



Anybody knows how to fix it or do it in sproutcore. Thanks





download file from database through browser in java desktop (non web)

is it possible to download file from database through browser (ex: mozilla,chrome) in java desktop application (non web app) ? can you explain me with an example code ?

thanks in advance,





How to sign a PDF

I am looking for the easiest way in your opinions to digitally sign a pdf file in order to verify the file integrity in C#. I have found this http://www.nitropdf.com/help/using_digital_signatures.htm but nothing that I can run using C#
But, let me explain my situation...I have the command prompt outputting some computer specific data to a text file, which I wish to upload to a file signing server to sign. I was thinking convert the text file to pdf, and sign, but can anyone think of a better way? thanks!





MSDN like help for python programmers

I am new to python, coming from C# world. Is there any MSDN like help available for python programmers where I can search for classes, their methods properties etc.



Thanks,
Taimoor.





Large number of WebSocket connections

I am writing an application that keeps track of content pushed around between users of a certain task. I am thinking of using WebSockets to send down new content as they are available to all users who are currently using the app for that given task.



I am writing this on Rails and the client side app is on iOS (probably going to be in Android too). I'm afraid that this WebSocket solution might not scale well. I am after some advice and things to consider while making the decision to go with WebSockets vs. some kind of polling solution.



Would Ruby on Rails servers (like Heroku) support large number of WebSockets open at the same time? Let's say a million connections for argument sake. Any material anyone can provide me of such stuff?



Would it cost a lot more on server hosting if I architect it this way?



Is it even possible to maintain millions of WebSockets simultaneously? I feel like this may not be the best design decision.



This is my first try at a proper Rails API. Any advice is greatly appreciated. Thx.





How can I get radio buttons to output HTML in my Drupal Form?

Inside of a Drupal module I'm writing, I created a form that outputs a set of radio buttons. Each of these buttons represents a palette of colors. I would like to add some blocks of color next to each label to show which colors are in the selected palette.



However, it seems like the Drupal form API is pretty strict as to what can be used as select options. An array of strings and nothing else?



Here is the code:



$form['palette_options'] = array(
'#type' => 'radios',
'#title' => 'Palette Options',
'#prefix' => '<div id="palette_options_replace">',
'#suffix' => '</div>',
'#options' => getPalettesfromTheme($xml, $theme_options[$value_checkboxes_first]),
'#default_value' => isset($form_state['values']['palette_options'])
? $form_state['values']['palette_options']
: '',
);


The most ideal situation would be to make an array of divs with inline styles that the form would output, but I think Drupal won't let me.



What else is possible here?



Thanks in advance!





How to restrict webservice access to public user in asp.net?

How to restrict webservice access to public user in asp.net





Which color space the IOS devices is used?

When I use the MAC Digital Color Meter to detect the RGB color of the screen, the RGB values can be shown in sRGB, Adobe RGB, original RGBs spaces, etc. And they are slightly different.



I want to use these values in the iOS Xcode platform, and use UIColor class to represent them, which color space should I choose in the Digital Color Meter?



Thanks.





Cross platform file modification tracking

I'd like to be able to track file modifications to a set of files in a platform-agnostic way.
I don't need any particular information, just the file's full path will do.



I'd prefer to avoid:




  • Looping constantly over the files. That's just horrible!


  • Writing platform-specific code. Especially for Windows or Mac OS X,
    since I have no access to machines running any of those.







Disclaimer: I've noticed similar questions on SO, but since most are over 4 years old, I feel this may have changed a lot since then, and they may be outdated.





Import MySQL dump to PostgreSQL database

I tried several ways through internet and scripts to use MySQL dump "xxx.sql" and ORACLE dump "xxx.dump" to postgresql database. Nothing worked for me. Kindly anyone suggest me to do this.



I want to import xxx.dump from ORACLE and xxx.sql from MySQL to postgresql database.





Error with bat file token or for loop: not recognized as an internal or external command, operable program or batch file

Need Windows .bat file tech support.
I am having trouble running Win 7 bat files which loop through tokens and variables. The script below works on my wifes PC, and should on all PCs, but does not on mine.



** I am running Windows 7 in VMWare off my Mac.



The file is located at the root of c:



This short little script, and any others like it with tokens gives me errors ( I copied the script below out of the .bat file ):



setLocal ENABLEDELAYEDEXPANSION
set SCHEMA_one= first
set SCHEMA_two= second
set SCHEMA_three= third

@ECHO ON
FOR /F "tokens=2* delims=_=" %%A IN ('set SCHEMA_') DO (
echo "looping through " %%A
)
endLocal


I get the following error:



C:\>FOR /F "tokens=2* delims=_=" %A IN ('set SCHEMA_') DO (echo "looping through " %A ) 'set SCHEMA_' is not recognized as an internal or external command, operable program or batch file.


Ideas???



Many thanks in advance. I have been stuck for hours and hours...





how to create a folder in tomcat webserver using java program?

i want to know how to create a folder in webserver(tomcat 7.0) in java.



iam recently start one project.In that project i need to upload files into server from the client machine.In this each client has his own folder in server and upload the files into them.



And in each user folder we have more than two jsp files.when user request the server to show their content by an url (eg:ipaddress:portnumber/userid/index.jsp) using that files i want to show his uploaded data.



is it possible.?



please,guide me to solve this problem.
thanks.





Scalabilty of Java middleware between Core banking and ATM Server

I have a requirement to build a Java module which will act as a router between ATM Server or any other Point of Sale which accept cards, and a core banking system.
This module should interpret requests from the end points and do some processing before it communicate with the core baking system. The communication will be through the java implementation of TCP IP Sockets. The end points like ATM will be the server & this middle ware will be the client. This application will keep on listening for the server messages & should be capable of interpreting simultaneous requests in range of 1k to 2k.



The idea is to have one client socket thread listening for server messages and handle each of the received messages in different threads. Is there any issue in my basic idea?



Is there is any open source application available to cater my requirements?
Thanks in advance for your advice.





Best way to create dynamic list of links/buttons in iOS5 view controller

I want to create a dynamic set of links/buttons in an iOS5 view controller and am trying to figure out what might be the best way to do this.



For eg:



Item 1
Item 2
Item 3
:
:
Item N



Each of the Items is a link/button that is clickable and will do some action, like load another screen etc based on the link.



I don't know ahead of time how many items there might be so if all the items don't fit on the screen, I need to be able to scroll to view.



My question:
1. What is a better way of doing this? I could just create the labels and buttons dynamically but this seems rather cumbersome and I'm not entirely sure how I would differentiate between the different buttons (essentially I'd need some index to find out which Item was clicked).
2. Alternatively, I was wondering if I can just render this page as HTML and just have links? I've never done this and not sure how I'd associate a button with a link.



Any suggestions?



AK





Output Using Masm

this is a simple Assembly program. I am trying to output the Emp1 And Num1 in the following format:



Jow Blow



600 763 521



i get the following output:



Jow Blow



x



Also i want to output the total of the three numbers



 .386
.MODEL FLAT

ExitProcess PROTO NEAR32 stdcall, dwExitCode:DWORD
Include io.h

.STACK 4096 ; reserve 4096-byte stack

.DATA ; reserve storage for data

Emp1 byte 'Jow Blow',13,10,0
Num1 DWORD 600,763,521



.CODE ; start of main program code
_start:
mov eax, Num1 ; first number to EAX
add eax, 158 ; add 158
mov sum, eax ; sum to memory


output Emp1
output Num1





INVOKE ExitProcess, 0 ; exit with return code 0

PUBLIC _start ; make entry point public

END ; end of source code




AWK: Recursive Descent CSV Parser

In response to a Recursive Descent CSV parser in BASH, I (the original author of both posts) have made the following attempt to translate it into AWK script, for speed comparison of data processing with these scripting languages. The translation is not a 1:1 translation due to several mitigating factors, but to those who are interested, this implementation is faster at string processing than the other.



Originally we had a few questions that have all been quashed thanks to Jonathan Leffler.



This code is now ready for showdown.



Basic Features




  • Empty Fields

  • Literal Quoted Fields via double quote "

  • Backslash Escaped: Commas, Quotes, Backslashes1

  • ANSI C Escape Sequences: Tab, Newline1

  • No imposed limitations on input length, field length, or field count



1 Quoted fields have literal content, and neither backslash escapes nor ANSI C escape sequence expansions are performed on quoted content. One can however concatenate quotes, plain text and interpreted sequences in a single field to achieve the desired effect. For example:



one,two,three:\t"Little Endians," and one Big Endian Chief


Is a three field line of CSV where the third field is equivalent to:



three:        Little Endians, and one Big Endian Chief





Special Thanks to all Members of the SO community whose experience, time and input led me to create such a wonderfully useful tool for information handling.



Code Listing: csv.awk



# This script accepts and parses a single line of CSV input
# from STDIN. The ouput is seperated by command line
# variable 'delim'

# Special thanks to Jonathan Leffler, whose wisdom, and
# knowledge defined the output logic of this script.

function NextSymbol() {

strIndex++;
symbol = substr(input, strIndex, 1);

return (strIndex < parseExtent);

}

function Accept(query) {

# print "query: " query " symbol: " symbol
if ( symbol == query ) {
#print "matched!"
return NextSymbol();
}

return 0;

}

function Expect(query) {

# case: empty string...
if ( query == nothing && symbol == nothing ) return 1;

# case: else
if ( Accept(query) ) return 1;

msg = "csv parse error: expected '" query "': found '" symbol "'";
print msg > "/dev/stderr";

return 0;

}

function PushValue() {

item[itmIndex++] = value;
value = nothing;

}

function Quote() {

while ( symbol != quote && symbol != nothing ) {
value = value symbol;
NextSymbol();
}

Expect(quote);

}

function BackSlash() {

if ( symbol == quote || symbol == comma || symbol == backslash) {
value = value symbol;
} else if (symbol == "n") { # newline
value = sprintf("%s\n", value);
} else if (symbol == "t") { # tab
value = sprintf("%s\t", value);
} else {
value = value backslash symbol;
}

}

function Line() {

if ( Accept(quote) ) {
Quote();
Line();
}

if ( Accept(backslash) ) {
BackSlash();
NextSymbol();
Line();
}

if ( Accept(comma) ) {
PushValue();
Line();
}

if ( symbol != nothing ) {
value = value symbol;
NextSymbol();
Line();
} else if ( value != nothing ) PushValue();

}

BEGIN {

# State Variables
symbol = ""; value = ""; strIndex = 0; itmIndex = 0;

# Control Variables
parseExtent = 0;

# Symbol Classes
nothing = "";
comma = ",";
quote = "\"";
backslash = "\\";

getline input;
parseExtent = (length(input) + 2);
NextSymbol();
Line();

}

END {

if (itmIndex) {

itmIndex--;

for (i = 0; i < itmIndex; i++)
{
printf("%s", item[i] delim);
}

print item[i];

}

}





How to Run The Script "Like a Pro"



# Spit out some CSV "newline" delimited:
echo 'one,two,three,AWK,CSV!' | awk -v delim=$'\n' -f csv.awk

# Spit out some CSV "tab" delimited:
echo 'one,two,three,AWK,CSV!' | awk -v delim=$'\t' -f csv.awk

# Spit out some CSV "ASCII Group Seperator" delimited:
echo 'one,two,three,AWK,CSV!' | awk -v delim=$'\29' -f csv.awk


If you need some custom control seperators but aren't sure what to use consult this chart





minimalistic python service layer

I plan to have mysql/postgres database along with a thin service layer which I basically would like to us to receive restful requests and return results in json format. I'd like to use python for latter. Since I am new to python frameworks, if I'd use any for this thin layer which one would that be? The more minimalistic (thinner) the better of course.



Thanks for sharing your experience.



Juergen



PS: If it dealt with authentication/auhorization that would be a bonus.





iOS camera's image rotation got in AS3

I'm developing a non-native iOS App using AS3 over Flash CS5.5. The app has the feature of taking photos with both cameras (obviously one at any time, not at the same time), and my problem consists in I don't know how to deal with the rotation of the image i'm seeing on my device.



I'm looking for a solution but don't have any which solves my problem.



Here is my code:



package
{
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.ActivityEvent;
import flash.events.MouseEvent;
import flash.media.Camera;
import flash.media.Video;

public class Main extends Sprite
{

private var cam:Camera;
private var vid:Video;


public function Main()
{
super();

// support autoOrients
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
cam = Camera.getCamera();

if (!cam)
{
trace("No camera is installed.");
}
else
{
connectCamera();
}
}

private function connectCamera():void
{
cam.setMode(320, 480, 25);
cam.setQuality(0,100);
vid = new Video();
vid.width = cam.width;
vid.height = cam.height;
vid.attachCamera(cam);
addChild(vid);
}
}
}





First of all thanks for your time. I've already updated the autoOrientation settings, and this is the code I'm managing:



    package 
{
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.ActivityEvent;
import flash.events.MouseEvent;
import flash.media.Camera;
import flash.media.Video;
import flash.events.StageOrientationEvent;
import flash.display.StageOrientation;


public class Main2 extends Sprite
{

private var cam:Camera;
private var vid:Video;
public var _currentOrientation:String;




public function Main2()
{
cam = Camera.getCamera();

if (! cam)
{
trace("No camera is installed.");
}
else
{
connectCamera();
}
stage.addEventListener(StageOrientationEvent.ORIENTATION_CHANGING, orientationChangeListener);
}

private function connectCamera():void
{
cam.setMode(480, 320, 25);
cam.setQuality(0,100);
vid= new Video();
vid.width = cam.width;
vid.height = cam.height;
vid.attachCamera(cam);
addChild(vid);

}

private function orientationChangeListener(e:StageOrientationEvent):void
{
switch (e.afterOrientation)
{
case StageOrientation.DEFAULT :
_currentOrientation = "DEFAULT";
//set rotation value here
stage.rotation = 0;
break;

case StageOrientation.ROTATED_RIGHT :
_currentOrientation = "ROTATED_RIGHT";
//set rotation value here
stage.rotation = -90;
break;

case StageOrientation.ROTATED_LEFT :
_currentOrientation = "ROTATED_LEFT";
//set rotation value here
stage.rotation = 90;
break;

case StageOrientation.UPSIDE_DOWN :
_currentOrientation = "UPSIDE_DOWN";
//set rotation value here
stage.rotation = 180;
break;
}
}


}
}


Despite of the switch-case sentences, when you launch the "app" you see the image of the camera 90degrees rotated, and when you put the device (iPhone 4) to landscape (right or left) the image puts well. And when you rotate back, the image gets bad as the launching one.



Thank you in advance.



PS: Sorry for my English.
PS2: Edited.





Delegation to SecondViewController inside a NavigationController presented Modally

I'm really not sure how to express this question in the fewest and clearest words possible. But I'll try my best.



I have a class ShoppingCartVC and I want to add products to it. So I modally present a CategoriesVC modally. When I select a category in the tableView row, it segues to a ProductsVC containing all the products in that category. So now I can select a product. But how do I send that selected object back to ShoppingCartVC? I was able to successfully implement this before using delegation but that was when I didn't have the CategoriesVC. I just segue directly to the ProductsVC so before I segue, I can set ShoppingCartVC(the presenting VC) as the delegate of ProductsVC and dismiss it whenever a product is selected.



But now since ProductsVC is 1VC further down the VC hierarchy in my navigationController, I cannot do that.



I tried searching about NSNotification but that doesn't seem to be the right solution.



How do I solve this? Hopefully you can give me some sample codes.





Application close while changing mode

I have create a application which have to run in both mode. But while changing the mode of application, application is closed. How can I solve this problem





How to shield Android 4.0 HOME Key

Does anybody know how to shield the HOME key in Android 4.0?



The code below only works in 2.2 and 2.3, so how would I change this so it can work in 4.0?



/* FIXME:  How does it works within Android 4.0? */
@Override
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}




Extracting info from Twitter XML to Wordpress

I'm wanting to use raw data from Facebook and Twitter on my website. I've worked out extracting data from the Facebook XML (with help from a nice bloke) and I've installed a nice slider thing. Here is the details of that...



$url = "http://api.facebook.com/restserver.php?method=links.getStats&urls=www.dori.co.nz".urlencode($source_url);

$xml = file_get_contents($url);
$xml = simplexml_load_string($xml);
$shares = $xml->link_stat->share_count;
$likes = $xml->link_stat->like_count;
$comments = $xml->link_stat->comment_count;
$total = $xml->link_stat->total_count;
$max = max($shares,$likes,$comments);


Now I want to do the same for Twitter. Here is the XML page for Twitter, but I can't seem to make it work no matter what I do. Any tips? Is there an issue with plucking details from two different XML pages/files within the one .php file?



Thank you!!