Wednesday, May 23, 2012

iPhone Sencha Touch: In which JS / HTML file I need to start my application?

I have started implementing my application using phone gap and Sencha Touch.



I have added sencha touch sdk to my application using kitchen sink application.



When I execute the app it displays a list of user interfaces, etc on left side and a home page for sencha touch kitchen sink app on right side.



When I select any rows they shows buttons, lists, pickers and different types of demos as shown in kitchensink demo.



But I need to create my own views rather than kitchen sink demo views.



Here i have bundle of .JS & HTML files in wich file i need to start my application,



How should i create a basic panel as initial step in which .JS file?





Architecture and Serialisation advice

I need a bit of a architecture help, I think what I've been doing may not necessarily be the best approach.



Things to note:




  • This is not an android specific question.

  • Android does however require that I need to serialise objects across 'screens'.



Consider the following:



I'm currently working on a game for android where a character class needs to be passed between different screens. In order to do this I need to serialise the objects. Taking into account that are different types of characters that will be needed I'd like to create a class that inherits for each of these. Where I have static characters I'd like to inherit from the Character class and set the defaults such as 'Name', and 'Description' within the constructor.



Current implementation:



I'm passing the serialised sub class objects around. ( Eg: UserCharacter with a base of Character ) Ideal situation would for me to be able to deserialise the object as it's base class however that doesn't seem to me work. The only working solution I have for this at the moment is by doing the following when trying to do serialise:



new XmlSerializer(typeof (Character, new [] { typeof(CharacterUser)}));


This allows me to pass in multiple sub types. This however is not feasible in the long term as it just means code duplication across my application as well as everytime a new character sub class is created I need to add at it any point I would need to deserialise. I'd rather have the code written and working where I leave it to do it's own thing. I'm sure you can understand that.



Another thing I've tried is to do is use IXmlSerializable on the character object and deal with the Reading and Writing independantly. I think that this however requires implementation of a list to work correctly? Currently my ReadXml never gets called. (Great idea, but it's not worked for me so far)



Anyone got any ideas I could try?



I think it's quite an open question, please let me know if I need to scope a little differently.





Simple script for tracking products sales , refunds etc

I need a script for tracking the product sales , refunds etc. ,& it should save the customers emails/pay pal address . This is for iPhone unlocking website , the customer hits on checkout button , purchase the product . Then after purchasing , the sale record must be saved with his pay pal email.



Please take a look on live website , I need something similar to this



http://tinyurl.com/coz8vg9



check the back end functionality of script here



http://tinyurl.com/dyq8a8k



username - nee
pass - testpass



It's a simple script , tracked all the orders in this website. I need to use the similar script or plugin in my word press website so if someone pointed me to word press script/ plugin , which can do same things then it will be useful., Or if someone just tell me the name of the script , which is used in above domain then it will be much useful, so I will purchase it .



Thanks





C# game development after XNA

I am a game developer who made games in .Net languages with XNA for the past four versions of it.



I am surveying the ecosystem of game engines, looking for something that supports coding in Visual Studio (I use F# heavily, believe it or not!) and I am having trouble finding something that is high quality, still alive, and high performance to replace XNA. Unity for example misses the mark because it only allows for scripting in MonoDevelop, while I want a more developer friendly experience.



So what is a good replacement for XNA?





TableView does not always resize the columns

I have a TableView with CONSTRAINED_RESIZE_POLICY column resize policy.
It works great when I resize the window manually, but when I maximize it or restore it from a maximized state, the columns do not adjust.



Is there a way to force a "refresh" on the TableView so columns resize in these cases?





Repeater inside a Repeater

I have a Repeater inside a Repeater, how can a use the code below:



<input type="hidden" value='<%# Container.ItemIndex %>' />


pointing to the first repeater?





asp.net mvc3,c#

I want separate friends facebook and twitter.
Like this :



Twitter Facebook



EditorTemplates: FriendModel.cshtml



@model App.Web.Models.FriendModel
<div>
<input type="checkbox" name="saveInputs" value="@Model.FriendID"/>
<img alt="" src="@Model.ProfileImageUrl" />
<strong>@Model.Name</strong> Friends: <strong>@Model.FriendsCount</strong>
</div>
<br />


Views: FriendTeam.cshtml



@model App.Web.Models.FriendTeamModel
@{
ViewBag.Title = "FriendTeam";
}
<h2>
FriendTeam</h2>

@using (@Html.BeginForm())
{ @Html.ValidationSummary(true)
<h3>Twitter</h3>
<br />
@Html.EditorFor(model => model.Friends.Where(x=>x.SocialNetworkName=="Twitter"))

<h3>Facebook</h3>
<br />
@Html.EditorFor(model => model.Friends.Where(x=>x.SocialNetworkName=="Facebook"))
}
<div>
@Html.ActionLink("Back to List", "Index")




FriendTeamModel:



   public class FriendTeamModel
{
public long FriendTeam{ get; set; }
public IEnumerable<FriendModel> Friends { get; set; }
}


FriendModel:



public class FriendModel
{
public string FriendID { get; set; }
public string SocialNetworkName { get; set; }

public string Name { get; set; }
public int FriendsCount { get; set; }
public string ProfileImageUrl { get; set; }
}


error :
Models can only be used with expressions access field of homeownership, the index of one-dimensional array or custom indexer single parameter.



Thanks,





why in file server program socket write as "Socket s =null"?

here , i am creating file server program .in this i have noticed that socket s= null is written.i want to know actual reason why null is given.I thought that it is either related to the ObjectInputStream or Scanner.is it true it related to the ObjectInputStream or Scanner .Here the code for



Server.java 

public class Server{
public static void main(String[] args){
Socket s=null;
ServerSocket ss=null;
ObjectInputStream ois=null;
ObjectOutputStream oos=null;
Scanner sc=new Scanner(System.in);


try
{
ss = new ServerSocket(1234);
System.out.println("server is created");

}
catch(Exception e)
{
System.out.println(e.getMessage());
}



try {
s=ss.accept();
System.out.println("connected");
oos = new ObjectOutputStream(s.getOutputStream());
oos.writeObject("Welcome");
ois= new ObjectInputStream(s.getInputStream());
}catch(Exception e)
{
e.printStackTrace();
}
try{
String fil=(String)ois.readObject();
FileInputStream fis = new FileInputStream(fil);
int d;
String data="";
while(true)
{
d=fis.read();
if(d==-1)
break;
data = data+(char)d;
}
oos.writeObject(data);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}


can anyone explain actual reason? Thanks in advance .





line chart using jfreechart

I have created line chart using jfreeChart API inside jsp and servlet.



Following is the code in servlet



// Get the output stream from the response object:
OutputStream out = response.getOutputStream();

// Set the HTTP Response Type:
response.setContentType("image/png");

XYSeries series = new XYSeries("Average Weight1233");
series.add(1.48, 20.0);
series.add(1.52, 25.0);
series.add(2.02, 50.0);
series.add(2.05, 65.0);
series.add(3.30, 2);
series.add(3.52, 50);
XYDataset xyDataset = new XYSeriesCollection(series);

// Create chart:
JFreeChart chart
= ChartFactory.createXYLineChart("XYLine Chart using JFreeChart",
"Age", "Weight",xyDataset,
PlotOrientation.VERTICAL,
true, true, false);

// Write the data to the output stream:
ChartUtilities.writeChartAsPNG(out, chart, 400, 300);


It creates horizontal number automatically from values that I have added on XYSeries But I want to set that value manually.



Is it possible? How?





Which memory is used for external process run from java - java heap space or OS memory?

If I run the following line



final String[] command = new String[]{ffmpeg -y -i /home/user/video.mov -ss 0 -t 20 -vcodec libx264 -vpre slow -crf 18 -f flv -bf 0 -g 10 -vsync 1 -r 30 -an -threads 0 -s 1920x1080 /home/user/video0.flv};

final Process process = Runtime.getRuntime().exec(command, null, null);


It will start ffmpeg and convert first 20 seconds of a video.mov to video.flv. But sometimes with high resolution videos, OutOfMemory is thrown. Obviously ffmpeg takes too much memory.



My question is the following - are external processes started from java taking memory from java heap space or from OS memory?



Knowing this, I will know how to adjust -Xms and -Xmx parameters. If external processes take from OS memory, I will leave -Xms and -Xmx with low values(leaving OS with more free memory). Otherwise, I will set -Xms and -Xmx to high values, giving the Java process more memory.





Where to write down the update infomation when submitting a update in app hub?

I just submitting a update version of my app in App Hub.



But what confused me a lot is that all the steps for updating is as same as when I submit a new app.



So I just don't know where to write down the update infomation.



I check the MSDN but found no answer with this, so,er,need help -_-





Struts2 - How to create a <s:form> for each row in <display:table>

I was trying to show a displaytag table and I wish to map each row on a different s:form.
Each row show all the attributes of my System object and I wish to choose one row and act on the related object.
I tryed to put multiple display:column in one form, but when I load the JSP, I don't find any form tag.



Any suggestion?



My code:



<display:table name="${systemList}" uid="row" pagesize="20" sort="list" requestURI="" >

<display:column title="System ID" property="systemID" sortable="true" />

... other columns ...

<s:form action="provision.action" method="post" name="provisionForm%{#attr.row.systemID}">

<display:column title="IP" >
<s:textfield name="systemList[%{#attr.row_rowNum - 1}].ip" />
</display:column>

<display:column>
<s:submit type="image" src='image.png' name='submit' />
</display:column>
</s:form>

</display:table>


Thanks in advance





How and why does the compiler replace extern functions with a null function?

Consider the following code in linux/drivers/usb/hid-core.c:



static void hid_process_event (struct hid_device *hid,
struct hid_field *field,
struct hid_usage *usage,
__s32 value)
{
hid_dump_input(usage, value);
if (hid->claimed & HID_CLAIMED_INPUT)
hidinput_hid_event(hid, field, usage, value);
#ifdef CONFIG_USB_HIDDEV
if (hid->claimed & HID_CLAIMED_HIDDEV)
hiddev_hid_event(hid, usage->hid, value);

slideToggle: Change the text a second time (open -> close -> open -> close...)

<div id="sidebar_archive_infoline_bottom"><a id="showallnews" href="#">SHOW ALL NEWS</a></div>     

<script>
$('#newsdiv').hide();
$('#showallnews').click(function () {
$('#newsdiv').slideToggle('fast');
$('#showallnews').text('CLOSE')
}); </script>


The text "SHOW ALL NEWS" changes to "CLOSE" after clicking the first time on it. Now I need a method to change it from "CLOSE" to "SHOW ALL NEWS" and so on...



Best regards!





call function before scrolling to the bottom of page

I know how to call a function when scrolling hits the bottom of the page.



$(window).scrollTop() == $(document).height() - $(window).height()


But I would like to do it a little bit before it hits the bottom. How would I accomplish this?





Using a checkbox outside of a datagrid to affect its contents

I am using a Checkbox outside of a datagrid. When i select the check box autopostback is true, and this would then show the image, but i cant access the images within the datagrid with that script. If i use a seperate image outside of the datagrid the script works. How can i get this script to work finding when the checkbox out side of the datagrid is checked to then show the image within the datagrid?



The script i am using is



<script runat="server">

Sub Check(sender As Object, e As EventArgs)
If checkShowImages.Checked Then
img.Visible = True

Else
img.Visible = False
End If
End Sub

</script>




Twitter API - Reply to a retweet

I am writing a little twitter API (using Elliot Haughin's library) and I want to reply to a retweet that the app posts.



I have read the docs for statues/update, and have tried using '*in_reply_to_status_id*' with the value taken from '*user_mentions*', but it doesn't seem to work.



What am I doing wrong, or is there a better way to do it?



Code sample;



$answer = '@'.$retweet->entities->user_mentions[0]->screen_name.' thanks!!';
$this->tweet->call('post', 'statuses/update', array('status' => $answer, 'in_reply_to_status_id' => $retweet->id));




Extended class running from super via same method (Java)

The title is pretty confusing I know but I could not think of another way of wording it.



So, what I am trying to achieve: I have seen some java programs have a load of subclasses that have a method in their super class, and they all run when the supers method is called.



I have tried multiple things and I've googled a lot but what I've found doesn't work for me.



Here is what I have: The SUPER class



public class Synchroniser 
{
public Synchroniser()
{
RunAll();
}

protected void RunAll()
{
System.out.println("RunAll");
}
}


The SUBCLASS:



import org.lwjgl.input.Keyboard;

public class ArrayList extends Synchroniser
{
public ArrayList()
{

}

public static void Keybind(Info info)
{
info.Toggle();
}

@Override
protected void RunAll()
{
System.out.println("Ran ArrayList");
}
}




Remove partial string in Shell Script

How can I remove price from following data in Shell Script? I am printing labels and don't want to show price.



Input:



Order: 12
Name: Raj K
ABC Inc
123 Main St
Edison NJ

1 Printer - $50.09
Router - $30.00
2 AirPrint - $56.10


Output



Order: 12
Name: Raj K
ABC Inc
123 Main St
Edison NJ

1 Printer
Router
2 AirPrint


Any ideas?





how Deploy asp.net application on windows azure..?

I have created a media player in asp.net and now I want to deploy this application on windows azure. Which role can I use to deploy this application? Also, can anyone tell me the procedure for this?





More than one type in @Category annotation

The GWT AutoBean page says:




The @Category annotation may specify more than one category type.




The following syntax gives Syntax error on token ",", / expected :



@Category(FooCategory.class, BarCategory.class)
public interface FooBarFactory extends AutoBeanFactory {
...
}


What is the syntax for specifying multiple category classes?





Sorting array of custom objects in JavaScript

Say I have an array of Employee Objects:



var Employee = function(fname, age) {
this.fname = fname;
this.age = age;
}

var employees = [
new Employee("Jack", "32"),
new Employee("Dave", "31"),
new Employee("Rick", "35"),
new Employee("Anna", "33")
];





At this point, employees.sort() means nothing, because the interpreter does not know how to sort these custom objects. So I pass in my custom sort function.



employees.sort(function(employee1, employee2){
return employee1.age > employee2.age;
});




Now employees.sort() works dandy.



But what if I also wanted to control what field to be sorted on, passing it in somehow during runtime? Can I do something like this?



employees.sort(function(employee1, employee2, on){
if(on === 'age') {
return employee1.age > employee2.age;
}
return employee1.fname > employee2.fname;
});


I can't get it to work, so suggestions? Design pattern based refactoring perhaps?





Calculating six dimensional integral in Fortran 90

I want to calculate a six dimensional integral with multivariable (six variables). I don't know how to do it in Fortran 90. I want to calculate the integral using the trapezoid rule. The function to integrate is six dimensional.



I attached the image file that is the formula I want to calculate. This is part of my code for calculating this integral.



Integral





zabbix reporting error string

Let's say a storage is monitored with zabbix through an agent. We want that when the storage fails for zabbix to email us with the error description, produced by some script. Is it possible for zabbix to get string output(ala nagios) and report it (not just string monitoring and report found/notfound) or does reporting only work with integers?





retrieveRequestToken(CommonsHttpOAuthConsumer,CALLBACK_URI) functions throws OAuthCommunicationException

I want to make an android app which will update status in twitter.
I am using signpost-core-1.2.1.1 and signpost-commonshttp4-1.2.1.1 jar files.I have given internet uses permission and i have registered app in twitter giving read,write and direct messages permission. Also filled up the callback Url.



code snippet:



private  static  final  String CALLBACK_URI = "app://twitter";
private static final String REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token";
private static final String ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token";
private static final String AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize";

String CONSUMER_KEY = "I4bwezijxf6VwpU8x0tygg";
String CONSUMER_SECRET = "Y6vSdZs3zWBrNogXZWSHKZ590RSXqB5wBwj8vFaayk";

private static CommonsHttpOAuthConsumer consumer;
private static CommonsHttpOAuthProvider provider;

consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
provider = new DefaultOAuthProvider(REQUEST_TOKEN_URL,ACCESS_TOKEN_URL, AUTHORIZE_URL);
String authUrl="";

authUrl = provider.retrieveRequestToken(consumer,CALLBACK_URI);


I am totally stuck with this.Please reply.





Tuesday, May 22, 2012

Service.onUnbind() called even if there are active clients?

The point of the exercise is: keep the service alive, passing it from one activity to another.




  1. Activity A calls bindService() on service S;

  2. S.onBound() called;

  3. A.serviceConnection.onServiceConnected() is called;

  4. Activity A starts activity B;

  5. Activity B calls bindService() on service S;

  6. B.serviceConnection.onServiceConnected() is called;
    5a: from onServiceConnected() activity B calls A.finish();

  7. Activity A is stopping, calling unbindService(S) from its onDestroy() method.



Expected behavior: Service S continues to exist happily until activity B calls unbindService()



Actual behavior:




  1. S.onUnbind() is called;

  2. S.onDestroy() is called;

  3. B.serviceConnection.onServiceDisconnected() is called;



thus destroying the link and contradicting the documentation.



Why? What am I missing?



Update: Solved. From http://developer.android.com/reference/android/app/Service.html:




A service can be both started and have connections bound to it. In
such a case, the system will keep the service running as long as
either it is started or there are one or more connections to it with
the Context.BIND_AUTO_CREATE flag
.




Here's the code:



public class A extends Activity {

private final Logger logger = LoggerFactory.getLogger(getClass().getSimpleName());

private String serviceClassName;
private ServiceConnection feedConnection;
private Messenger feedMessenger;

private void bind(String argument) {

serviceClassName = TheService.class.getName();
Intent intent = new Intent(serviceClassName);

intent.putExtra(Keys.ACCOUNT, argument);

feedConnection = new FeedConnection();

if (!bindService(intent, feedConnection, Context.BIND_AUTO_CREATE)) {
throw new IllegalStateException("Failed to bind to " + argument);
}

logger.debug("bindService(" + serviceClassName + ") successful");
}

private void forward() {

Intent intentB = new Intent();

intentB.setClassName(B.class.getPackage().getName(), B.class.getName());
intentB.putExtra(Keys.SERVICE_CLASS_NAME, serviceClassName);

startActivity(intentB);
}

@Override
protected void onDestroy() {
super.onDestroy();

unbindService(feedConnection);
}


private class FeedConnection implements ServiceConnection {

@Override
public void onServiceConnected(ComponentName className, IBinder service) {

A.this.feedMessenger = new Messenger(service);
}

@Override
public void onServiceDisconnected(ComponentName className) {

A.this.feedMessenger = null;
logger.error("Crashed " + Integer.toHexString(hashCode()));
}
}
}

public class B extends Activity {

private final Logger logger = LoggerFactory.getLogger(getClass().getSimpleName());
private ServiceConnection feedConnection;
private Messenger feedMessenger;
private A activityA;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

bindFeed();
}

private void bindFeed() {

Intent startingIntent = getIntent();

String serviceClassName = startingIntent.getStringExtra(Keys.SERVICE_CLASS_NAME);

Intent intent = new Intent(serviceClassName);

feedConnection = new FeedConnection();
// FIXME: BIND_AUTO_CREATE flag is missing
if (!bindService(intent, feedConnection, 0)) {
throw new IllegalStateException("Failed to bind to " + serviceClassName);
}

logger.debug("bindService(" + serviceClassName + ") successful");
}

private class FeedConnection implements ServiceConnection {

@Override
public void onServiceConnected(ComponentName className, IBinder service) {

B.this.feedMessenger = new Messenger(service);

logger.debug("bound " + className);

// Finish the previous activity only after the service is bound
activityA.fileList();
}

@Override
public void onServiceDisconnected(ComponentName className) {

B.this.feedMessenger = null;
logger.error("Crashed " + className);
}
}
}




Run a cPAddon automatically on account creation?

I am working on writing my own system to automatically provision cPanel accounts upon payment.
One of my requirements is to automatically install WordPress on certain Accounts.
What would be the easiest way to do this?
My preferred scripting language is PHP...
I have the WordPress cPAddon installed on my server and I figured it may be the easiest way to do it if it is possible to invoke them via php.



Thanks in Advance





Putting contact info into Phone Book from Blackberry

In my application I need to add contact info from my app into phonebook of BlackBerry.
How can I achieve it?



I have referred to the Java development guide "Create a contact and assign it to a contact list"





Save attribute of a UIButton

I need some help with my code.
I have an UIAlert that pops up the first time that you open the app, in that pop up I have two buttons and the user will choose one of those. I want the app to remember what button the user chose to execute some code or other. The thing is I have this code right here :



-(void)changeLabel{


progressView.progress += 0.25;
scan.hidden = YES;


if (progressView.progress == 1 ) {
label.hidden = YES;

progressView.hidden = YES;

[timer invalidate];

imagesText.hidden = NO;


int randomNumber = arc4random() % 4;

switch (randomNumber) {
case 0:


imagesText.image = [UIImage imageNamed:@"image1.png"];


break;

case 1:


imagesText.image = [UIImage imageNamed:@"image2.png"];


break;

case 2:

imagesText.image = [UIImage imageNamed:@"image3.png"];

break;
case 3:

imagesText.image = [UIImage imageNamed:@"image4.png"];

default:
break;

}
}
}


So I want to make it in some way that if the user selected the first button the app will do the switch between cases 0,1 and 2 and if he selected the second button it'll do it between 3 and others. But I want the beginning of the code to be the same for both cases.
I tried some stuff but it doesn't work how I wanted.
Thank you for your help!





How to store universities and departments in database in an efficient way?

Basically I would like to create a web site about universities. My problem is trying to find an efficient way to store departments and universities in tables. For example Koc University has departments Computer Engineering, Business Administration, Economics. But Sabanci University has also Computer Engineering and Economics in its departments. I was thinking that having a table which has university ID's and department ID's but I'm not sure that it is the best idea. Do you have any ideas ?



Thanks





Javascript form won't submit

I have been using the uploader as provided by http://www.hoppinger.com/blog/2010/05/28/file-upload-progress-bar-with-phpapc-and-javascript/ and have since applied it to one of my forms and whilst the progress meter works, the submit function doesn't fire on successful upload.



The full code of what I am using is below:



JS

get_progress.php

uploader.php



As far as I can tell, in my limited experience, this is the function that handles the submit:



postUpload : function(o_data)
{
// Loop through every input and set json response in hidden input
this.a_inputs.each((function(o_input)
{
var s_name = o_input.get('name');
var s_value = '';

if(o_file = o_data.files[s_name])
{
s_value = JSON.encode(o_file);
}


var o_jsonInput = new Element('input',{'type': 'hidden','name':o_input.origName,'value':s_value}).replaces(o_input);


}).bind(this));

// Make form "original" again by purging elements and resetting attributes
this.revertSubmit();
this.o_form.submit();
},


I noticed that the submit was this.o_form.submit(); rather than this.form.submit(); and checked it out and he has declared o_form : {} at the top of the class, so I assume that his syntax is correct but I have no real idea.



Prior to my implementing this progress tracker the form worked perfectly, so this has got me quite frustrated.



Essentially what has gone wrong, I can only assume that it's something as simple as a missing ; or similar mistake.



If you get a 404 on the submit that means it worked. I have temporarily unblocked the page for troubleshooting.



As it may be relevant, my site uses WordPress.





Are there any organizations that provide training in iOS Development?

I was kinda hoping there was already an answer to this question. It seems like the iPad/iPod/iPhone/iYaddaYaddaYadda has enough of a consumer base that you would expect some organization to offer a formal training course on doing Development for them. Anybody know where you can get classes on iOS development and Objective C?





Socket input stream hangs on final read. Best way to handle this?

I'm a bit stumped on how to avoid my socket hanging on read. Here's my code:



    Socket socket = new Socket("someMachine", 16003);
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
try {
outputStream.write(messageBuffer.toByteArray());
outputStream.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer response = new StringBuffer();
int result;
while ((result = in.read()) != -1) {
response.append(Character.toChars(result));
System.out.println(result);
}
System.out.println("Done!"); //never gets printed
} catch (...) {}


The above code successfully reads all the data from the stream but then hangs. Reading up on the net I was expecting to receive a -1 from the server (which I can't control) to indicate that I had reached the end of stream but instead I get this:



(Lots of data above this point)
57
10
37
37
69
79
70
10


It then hangs. So, my questions are:



1) Have I coded this wrong or is there an issue with the server's response?



2) If there is an issue with the server's response (i.e. no -1 being returned), how can I work around this (i.e. to stop reading when it hangs).



Any help appreciated!





Navigation with li and jquery not working

I have the following code:



HTML



<ul id="navigation">
<li class="quickHelp"><a href="" title="Ayuda Rápida"></a>
<div>
Sed lacus. Donec lectus. Nullam pretium nibh ut turpis. Nam bibendum. In nulla tortor, elementum vel, tempor at, varius non, purus. Mauris vitae nisl nec metus placerat consectetuer. Donec ipsum. Proin imperdiet est. Phasellus dapibus semper urna. Pellentesque ornare, orci in consectetuer hendrerit, urna elit eleifend nunc, ut consectetuer nisl felis ac diam. Etiam non felis. Donec ut ante. In id eros. Suspendisse lacus turpis, cursus egestas at sem. Mauris quam enim, molestie in, rhoncus ut, lobortis a, est.
</div>
</li>
</ul>


CSS



ul#navigation {
position: fixed;
margin: 0px;
padding: 0px;
top: 10px;
left: 0px;
list-style: none;
z-index:9999;
}
ul#navigation li {
width: 100px;
}
ul#navigation li a {
display: block;
margin-left: -2px;
width: 300px;
height: 350px;
background-color:#CCC;
background-repeat:no-repeat;
background-position:center center;
border:1px solid #AFAFAF;
-moz-border-radius:0px 10px 10px 0px;
-webkit-border-bottom-right-radius: 10px;
-webkit-border-top-right-radius: 10px;
-khtml-border-bottom-right-radius: 10px;
-khtml-border-top-right-radius: 10px;
/*-moz-box-shadow: 0px 4px 3px #000;
-webkit-box-shadow: 0px 4px 3px #000;
opacity: 0.6;*/
filter:progid:DXImageTransform.Microsoft.Alpha(opacity=60);
}
ul#navigation .quickHelp a{
background-image: url(../Content/images/info/leftBanner.png);
background-position: right;
}

ul#navigation div{
position: absolute;
}?


JS



$('#navigation a').stop().animate({ 'marginLeft': '-275px' }, 1000);

$('#navigation > li').hover(
function () {
$('a', $(this)).stop().animate({ 'marginLeft': '-2px' }, 200);
},
function () {
$('a', $(this)).stop().animate({ 'marginLeft': '-275px' }, 200);
}
);


What I'm trying to achieve is that I want the content of the <div> to be displayed inside the <li> not below...



Here is a live example of it...



Thanks in advance!





Objective-c EXC_BREAKPOINT (SIGTRAP) exception without trackback to iPhone app

I have tried

(1) cleaning build folder,

(2) deleting app from the simulator and from my iphone,

(3) rebooting,

(4) and enabling NSZombieEnabled but it does not appear to be doing anything.

(5) using debugger lldb and gdb

(6) and gaurd malloc



I have xcode 4.3.2. This bug occurs on both the simulator and my iphone.
(on the simulator it says EXC_BAD_INSTRUCTION code=i386 subcode=0x0 and on the device it says EXC_BREAKPOINT (SIGTRAP).

Here are two crashes logs:



http://pastie.org/3941419



http://pastie.org/3941427



In the log it prints:



Trace/BPT trap: 5

Segmentation fault: 11



As you can see in the crashes, there is no traceback to any of my ViewControllers. I did a lot of googling before asking (link), but a lot of other people(link) with this error have a traceback to thier app. What are common causes of this app and where should I start looking for a bug? There is not one thing I can do to reproduce, just run a piece of my code like 10 times and it will crash at least once. Thanks!



EDIT:
heres some code



outputPipe = [[NSPipe alloc] init];


[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getDataOut:) name:NSFileHandleReadToEndOfFileCompletionNotification object:[outputPipe fileHandleForReading]];



[[NSNotificationCenter defaultCenter] removeObserver:self name:NSFileHandleReadToEndOfFileCompletionNotification object:[outputPipe fileHandleForReading]];



I do release outputPipe later in my code.



EDIT 2: changing [NSPipe pipe]; to [[NSPipe alloc] init]; did not fix it.



Code to switch between observers:



 buttondone.title=@"Done";
//dlog(@"last output notification inbound");
stdoutisdone=YES;

[[NSNotificationCenter defaultCenter] removeObserver:self name:NSFileHandleReadCompletionNotification object:[outputPipe fileHandleForReading]];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getDataOut:) name:NSFileHandleReadToEndOfFileCompletionNotification object:[outputPipe fileHandleForReading]];

[[outputPipe fileHandleForReading] readToEndOfFileInBackgroundAndNotify];




Ruby scraper. How to export to CSV?

I wrote this ruby script to scrape product info from the manufacturer website. The scraping and storage of the product objects in an array works, but I can't figure out how to export the array data to a csv file. This error is being thrown:
scraper.rb:45: undefined method `send_data' for main:Object (NoMethodError)



I do not understand this piece of code. What's this doing and why isn't it working right?



  send_data csv_data, 
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment; filename=products.csv"


Full code:



#!/usr/bin/ruby

require 'rubygems'
require 'anemone'
require 'fastercsv'

productsArray = Array.new

class Product
attr_accessor :name, :sku, :desc
end

# Scraper Code

Anemone.crawl("http://retail.pelicanbayltd.com/") do |anemone|
anemone.on_every_page do |page|

currentPage = Product.new

#Product info parsing
currentPage.name = page.doc.css(".page_headers").text
currentPage.sku = page.doc.css("tr:nth-child(2) strong").text
currentPage.desc = page.doc.css("tr:nth-child(4) .item").text

if currentPage.sku =~ /#\d\d\d\d/
currentPage.sku = currentPage.sku[1..-1]
productsArray.push(currentPage)
end
end
end

# CSV Export Code

products = productsArray.find(:all)
csv_data = FasterCSV.generate do |csv|
# header row
csv << ["sku", "name", "desc"]

# data rows
productsArray.each do |product|
csv << [product.sku, product.name, product.desc]
end
end

send_data csv_data,
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment; filename=products.csv"




Set up notifications when Biztalk send/receive ports stop or are disabled

We have a Biztalk 2006 R2 server, and from time to time, the receive ports will change to "Disabled" status for any one of a number of reasons - most commonly, server maintenance elsewhere on the network causes the file share they point to to become unavailable, so it stops the port. This causes trouble when transmissions we expect to happen every day no longer happen due to the stopped port, since it doesn't automatically start up again on its own.



Is there a native way to set up alerts when these ports stop, or do I need to write a job that queries the SQL Server directly and emails me when the port status changes in the database?





Why is -freciprocal-math unsafe in GCC?

-freciprocal-math in GCC changes the following code
double a = b / c;
to
double tmp = 1/c;
double a = b * tmp;



In GCC manual, it's said that such an optimization is unsafe and is not sticked to IEEE standards. But I cannot think of an example. Could you give an example about this? Thank you.





any wrong on this DELETE procedure. can we write like this or is there any better way to write same proc

Here we are just deleting the records from master and child table prior to 90days history records. Assume that tables have more than 20k records are there to delete. And here I put commit for each 5k records. Please let me know if I am wrong here?



create or replace Procedure PURGE_CLE_ALL_STATUS  ( days_in IN number ) 
IS

reccount NUMBER := 0;

CURSOR del_record_cur IS

SELECT EXCEPTIONID FROM EXCEPTIONREC
WHERE trunc(TIME_STAMP) < trunc(sysdate - days_in );


BEGIN
FOR rec IN del_record_cur LOOP

delete from EXCEPTIONRECALTKEY -- child table
where EXCEPTIONID =rec.EXCEPTIONID ;

delete from EXCEPTIONREC -- master table
where EXCEPTIONID =rec.EXCEPTIONID;


reccount := reccount + 1;

IF (reccount >= 1000) THEN
COMMIT;
count := 0;
END IF;
commit;
END LOOP;
COMMIT;
DBMS_OUTPUT.PUT_LINE('Deleted ' || total || ' records from <OWNER>.<TABLE_NAME>.');
END;
/




Is the Samsung S-pen input the same as your fingers?

I have no actual Galaxy Note on-hand and no access to such device so
I would like to ask if the S-Pen behaves the same way as a Finger on a SurfaceView?
Basing from the behavior of S-Pen SDK samples when run on an emulator, it seems that the S-Pen's input is the same with finger inputs only that it is very precise. (noticing that when run on the emulator, its impossible to detect if input came from a finger or S-Pen since touch input is emulated via the mouse cursor)



I'd like to confirm if the gestures I can do with my finger is also doable using the S-Pen?
If this is the case, is it safe to say that the S-Pen is comparable to a very thin finger?
The only difference it can make, is that when an app is coded with specific functionality using the SDK that samsung provides?



Thanks





Nokia S40 Application Development

I am an Android Developer. I want to develop apps for my Nokia c2-00 phone. I dont know anything about nokia application but i am very interested to do apps. So friends can any one guide me from where i start reading for applications development and also suggest me important links for the source codes as well.



Friends let me clarify



1) In which language apps will be developed.
2) which **IDE** can be used for application development.
3) which database can be used to store data.


Thanks in Advance





How to implement user_loader in Flask-Login (flask site authentication)

I am trying to use the Flask-Login extension for user authentication in python/flask, and I'm stuck on how to implement the @login_manager.user_loader callback function when retrieving a user account from a database (rather than from a dictionary of User objects provided within the source code itself, as shown by the Flask-Login example).



The documentation says I need to pass this function a User ID number, and return the corresponding User object. Something to this effect:



@login_manager.user_loader
def load_user(userid):
return User.get(userid)


But because this function (apparently) must reside outside the scope of the /login route, this doesn't work when you need to check the user account against a database at the time that the /login form data is received:



@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST" and "username" in request.form:
username = request.form["username"]

# query MongoDB for the existence of the entered username:
database_result = users_collection.find_one({ 'username' : username})
User = UserClass(username, testdb['userid'], active=True)

if username == database_result['username']:
login_user(User)
return url_for("index")
else:
flash("Username not found.")
else:
flash("Error logging in.")
return render_template("login.html")


This is a rough excerpt. But for our purposes, let's say this code would fail at the callback function, and generate the error: "NameError: global name 'User' is not defined".



How do I correctly pass a User object to the user_loader callback on the fly, when the User object only gets created within the /login route's scope after it's located in the database?



Thanks for any guidance. I hope I'm explaining this clearly enough. I've been reading and re-reading the Flask-Login documentation, and it seems simple, except when I try to pull user data from anything other than a pre-determined dictionary at the top of the python source file.





Why Wont TIdIRC Connect to channel? Is there a better componant?

Iv been struggling with the crap documentation off Google and cant get the program to join the channel even though it connects to the server fine. (It says Connected to server)



//On Form Make
procedure TForm2.FormCreate(Sender: TObject);
begin
IdIRC1.Connect();
end;

//on connected
procedure TForm2.IdIRC1Connected(Sender: TObject);
begin
ShowMessage('Connected to server');
IdIRC1.Join('#TheChannel', 'password');
end;


Once i close the form an error comes up saying:



Project raised exception class EIdException with message 'Not Connected'


Also once connected what functions do i use to talk on the channel/check input?
And what other IRC connection options (components) are there for Delphi applications?



ANY HELP WOULD BE APPRECIATED, GOOGLE HAS NOTHING ON THIS REALLY.
All i want is to be able to connect/check channel chat messages & talk on the chat; Simple String IO through IRC...





Not giving an 'out' argument

It is possible to assign default values to normal arguments to a function, such that



bool SomeFunction(int arg1 = 3, int arg2 = 4)


can be called in any of the following ways.



bool val = SomeFunction();
bool val = SomeFunction(6);
bool val = SomeFunction(6,8);


Is there a way of doing something similar (other than just creating an unused variable) such that



bool SomeOtherFunction(int arg1, out int argOut)


can be called in either of the following ways?



int outarg;
bool val = SomeOtherFunction(4,outarg);
bool val = SomeOtherFunction(4);


Is this at all possible, or if not, what are good workarounds? Thanks.





Node.js + mongoose [RangeError: Maximum call stack size exceeded]

I am new to Node and im facing an error : [RangeError: Maximum call stack size exceeded]



im not able able to solve the problem because most of the stack problems in others stackoverflow questions about node deals with hundreds of callback but i have only 3 here,



first a fetch (findbyid) then an update an later a save operation !



my code is :



app.post('/poker/tables/:id/join', function(req,res){
var id = req.params.id;

models.Table.findById(id, function (err, table) {
if(err) { console.log(err); res.send( { message: 'error' }); return; }

if(table.players.length >= table.maxPlayers ) {
res.send( { message: "error: Can't join ! the Table is full" });
return;
}
console.log('Table isnt Full');

var BuyIn = table.minBuyIn;
if(req.user.money < table.maxPlayers ) {
res.send( { message: "error: Can't join ! Tou have not enough money" });
return;
}
console.log('User has enought money');

models.User.update({_id:req.user._id},{ $inc:{ money : -BuyIn }}, function(err, numAffected) {
if(err) { console.log(err); res.send( { message: 'error: Cant update your account' }); return; }
console.log('User money updated');


table.players.push( {userId: req.user._id, username: req.user.username, chips:BuyIn, cards:{}} );


table.save(function (err) {
if(err) { console.log(err); res.send( { message: 'error' });return; }

console.log('Table Successfully saved with new player!');
res.send( { message: 'success', table: table});

});
});

})});


The error occurs during the save operation at the end !



I use MongoDb with mongoose so 'Table' and 'User' are my database collections.



This is from my first project with nodejs,expressjs and mongodb so i probably have made huge mistakes in the async code :(



thx for your help !






EDIT: i tried to replace the save with an update :



models.Table.update({_id: table._id}, { '$push': { players : {userId: req.user._id, username: req.user.username, chips:BuyIn, cards:{}} } }, function(err,numAffected) {

if(err) { console.log(err); res.send( { message: 'error' });return; }

console.log('Table Successfully saved with new player!');
res.send( { message: 'success', table: table});


});


But it doesnt help the error is still coming and i dont know how to debug it :/






Last edit: i post the answer here because iam new to this site and it doesnt want me to answer due to the spam protection probably ( or i would have to wait 4 hours and i prefer not !)



I finally got it !



In fact i created another mongoose schema and model for the player witch is an embedded document in the table document but trying to save it directly as an object didnt worked i had to create a specific model instance for the player first and then add it to the table doc so my code is now



... update user money ... then 

var player = new models.Player({userId: req.user._id, username: req.user.username, chips:BuyIn, cards:{}});

models.Table.update({_id: this._id}, { '$push': { 'players' : player } }, function(err,numAffected) {
if(err) { console.log(err); res.send( { message: 'error during update', error: err });return; }

this.players.push( {userId: req.user._id, username: req.user.username, chips:BuyIn, cards:{}} );
res.send( { message: 'success', table: this});

}.bind(this));


I dont really know why mongoose send me a stack size error due to this but it solved the problem !!!





How can I detect whether a type is a visible base of another type?

If I do



struct A{};
struct C:private A{};

typedef char (&yes)[1];
typedef char (&no)[2];

template <typename B, typename D>
struct Host
{
operator B*() const;
operator D*();
};

template <typename B, typename D>
struct is_base_of
{
template <typename T>
static yes check(D*, T);
static no check(B*, int);

static const bool value = sizeof(check(Host<B,D>(), int())) == sizeof(yes);
};

int main(){
std::cout<<is_base_of<A,C>::value<<std::endl;
}


I get a 1. I would like to get a 0 when C is a private A, and a 1 when C is a public A



[the code is derived from How `is_base_of` works? ]





Why do we need the directly call in a thread-safe call block?

Refer the thread-safe call tutorial at MSDN, have a look at following statments:



// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired) {
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
} else {
this.textBox1.Text = text;
}


Of course, I've used it many times in my codes, and understand a little why to use it.
But I still have some unclear questions about those statements, so anybody help me to find them out, please.



The questions are:




  1. Will the code can run correctly with the statements in the if body only? I tried and seems it just cause the problem if the control is not initialize completely. I don't know is there more problem?

  2. Which the advantage of calling method directly (else body) instance via invoker? Does it save resource (CPU, RAM) or something?



Thanks!





Setting a custom design size for a UITabViewController (in Storyboard)

I want to modify an app that currently has a UITabBarController as its initial view controller.



The goal is to have a custom status bar in the top area of the screen that will always be shown no matter which tab is selected. The current UITabBarController may not use the full height of the screen:



/----------------------------\
|Custom Status bar (50 px) |
| |
|----------------------------|
| |
|----------------------------| ---
| | |
| | |
|View of the selected tab | |
| | |
| | |
| | |
| | |
| | smaller height of the UITabBarController
| | |
|----------------------------| |
|Tab bar | |
| | |
\----------------------------/ ---


I use storyboards. I cannot set a (design) size in the Size Inspector window even with simulated metrics size set to 'freeform'.





displaying the dynamically growing list

UPDATE1: Updated the JS fiddle link sorry set interval was not working as I wanted it to



I have a array which is dynamically growing (number getting added every 1 sec). I have to split this list and display it in columns, I am actually have problem displaying the list inside the ul and li(yes only ul and li no tables). The user can specify the max number of columns(Stop adding columns once there are this many) and the minimum column height(No added column may contain fewer than this many items). Also, the number of items in any added column must be either the same as, or 1 fewer than for the previous column. The output for max column =3 and min column height =3



enter image description here



What I was able to do so far is:




  1. use set interval to add number every 1 sec


  2. put the incoming numbers in an array like [1] , [1,2] ... [1,2,3,4] after 4 sec. This array is called range


  3. split the main array (range) into sub array (new_range) for eg if the main array



    (range) = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]



    new_range (after 1st loop) = [1, 2, 3, 4]



    new_range (after 2nd loop) = [5, 6, 7]



    new_range (after 3rd loop) = [8, 9, 10]


  4. so now I need to display each new range vertically using ul and li so i tried doing something like $('ul').append('<li>' + new_range[j] + '</li>'); were j is the new_range array index




I have problem displaying the li items next to each other like the sample output using CSS, It would be great if someone could tell me how to display the li items after each iteration next to each other



JS fiddle link





Error Message: emulator-arm.exe has stopped working

I have been having issues running my first android app. Yesterday, i came close to running it but my happiness was dashed when i encountered this error:



emulator-arm.exe has stopped working


What do i do? I want to run this 'Hello World'



My Console Display:



[2011-07-28 10:46:52 - HelloAndroid] Android Launch!
[2011-07-28 10:46:52 - HelloAndroid] adb is running normally.
[2011-07-28 10:46:52 - HelloAndroid] Performing com.bestvalue.hello.HelloAndroid activity launch
[2011-07-28 10:46:52 - HelloAndroid] Automatic Target Mode: Preferred AVD 'my_avd' is not available. Launching new emulator.
[2011-07-28 10:46:52 - HelloAndroid] Launching a new emulator with Virtual Device 'my_avd'
[2011-07-28 10:47:13 - Emulator] emulator: emulator window was out of view and was recentred
[2011-07-28 10:47:13 - Emulator]
[2011-07-28 10:47:14 - HelloAndroid] New emulator found: emulator-5554
[2011-07-28 10:47:14 - HelloAndroid] Waiting for HOME ('android.process.acore') to be launched...
[2011-07-28 10:47:28 - HelloAndroid] emulator-5554 disconnected! Cancelling 'com.bestvalue.hello.HelloAndroid activity launch'!




Asking git to look for different key other than id_rsa

I not sure why but even though I mention properly in ssh config to look for identity file with name viren.pub for github



git still considering id_rsa as default and it does not seem to work unless an until i rename viren.pub and viren to id_rsa.pub and id_rsa



Here my ssh config look like



Host [Amazon server]
Hostname github.com
User git
IdentityFile /root/.ssh/viren


Can anyone help





Grab euro dollar conversion rate in Java

I have an application that has to convert dollar to euro and vice versa. Is there an interface or API I can use to grab the current conversion rate?





Issue on a do-while form in Strings

Ok, i'm a student in his first experiences with programmaing so be kind ;) this is the correct code to print "n" times a string on screen...



#include <stdio.h>
#include <string.h>

#define MAX 80+1+1 /* 80+\n+ */

int main(void)
{
char message[MAX];
int i, n;

/* input phase */
printf("Input message: ");
i = 0;
do {
scanf("%c", &message[i]);
} while (message[i++] != '\n');
message[i] = '';

printf("Number of repetitions: ");
scanf("%d", &n);

/* output phase */
for (i=0; i<n; i++) {
printf("%s", message);
}

return 0;
}


why in the do-while form he needs to check if message[i++] != '\n' and not just message[i] != '\n'??





Making multiple query to mysql in one java event

I'm having and error when trying to make multiple queries in one event. I have a table where I have a list of all the films with the main actor, producer, genre etc.



The actor, producers and genres are stocked as an int which in another table refers to a String. I'm therefore making multiple queries to print out all the data in a textarea.
However i keep getting the error



Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at tp2.MainPage.jList1ValueChanged(MainPage.java:231)
at tp2.MainPage.access$300(MainPage.java:24)
at tp2.MainPage$4.valueChanged(MainPage.java:106)


I refered to all the lines mentioned, line 24 and 106 are generated by netbeans so i doubt the error comes from there. Line 231 is mentioned in the code below.



    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
String npays = "null",titre= "null",nacteurPrincipal= "null",oscar= "null",realisateur= "null";
try {
String url = "jdbc:mysql://localhost/mycinema";
Class.forName("com.mysql.jdbc.Driver");
Connection connexion = DriverManager.getConnection(url, "root", "");
Statement inst = connexion.createStatement();
titre = jList1.getSelectedValue().toString(); //LINE 231
ResultSet resultat = inst.executeQuery("SELECT * FROM film WHERE titre = '" + titre + "'");
while (resultat.next()) {
npays = resultat.getString("npays");
realisateur = resultat.getString("realisateur");
nacteurPrincipal = resultat.getString("nacteurPrincipal");
oscar = resultat.getString("oscar");
}
resultat = inst.executeQuery("SELECT * FROM pays WHERE npays =" + npays);
while (resultat.next()) {
npays = resultat.getString("nom");
}

resultat = inst.executeQuery("SELECT * FROM acteur WHERE nacteur =" + nacteurPrincipal);
while (resultat.next()) {
nacteurPrincipal = resultat.getString("prenom") + resultat.getString("nom");
}

jTextArea3.setText(titre + " : un film par " + realisateur + "\n" + npays);
} catch (ClassNotFoundException ex) {
Logger.getLogger(MainPage.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(MainPage.class.getName()).log(Level.SEVERE, null, ex);
}
}


If somebody can spot my error pleas point in out thankyou :)



P.S the variables are in french. srry for that :/





Issue on a do-while form in Strings

Ok, i'm a student in his first experiences with programmaing so be kind ;) this is the correct code to print "n" times a string on screen...



#include <stdio.h>
#include <string.h>

#define MAX 80+1+1 /* 80+\n+ */

int main(void)
{
char message[MAX];
int i, n;

/* input phase */
printf("Input message: ");
i = 0;
do {
scanf("%c", &message[i]);
} while (message[i++] != '\n');
message[i] = '';

printf("Number of repetitions: ");
scanf("%d", &n);

/* output phase */
for (i=0; i<n; i++) {
printf("%s", message);
}

return 0;
}


why in the do-while form he needs to check if message[i++] != '\n' and not just message[i] != '\n'??





.htaccess mod_rewrite pretty URLs with subdomain

I'm trying to get my URLs from this:



hxxp://m.newsite.com/index.php?id=12345



To this:



hxxp://m.newsite.com/12345



The trouble I have is I have a shared hosting account and I'm hosting a new domain, so the above URL w/subdomain is technically accessible from:



hxxp://www.originalsite.com/newsite.com/mobile



I've tried a variety of different combinations for mod_rewrite, but I'm afraid I'm just not there! Help!





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.