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!