Basically I want to create a rock solid server.
while (keepRunning.get()) {
try {
Socket clientSocket = serverSocket.accept();
... spawn a new thread to handle the client ...
} catch (IOException e) {
e.printStackTrace();
// NOW WHAT?
}
}
In the IOException block, what to do? Is the Server socket at fault so it need to be recreated? For example wait a few seconds and then
serverSocket = ServerSocketFactory.getDefault().createServerSocket(MY_PORT);
However if the server socket is still OK, then it is a pity to close it and kill all previously accepted connections that are still communicating.
EDIT: After some answers, here my attempt to deal with the IOException. Would the implementation be guaranteeing keeping the server up and only re-create server socket when only necessary?
while (keepRunning.get()) {
try {
Socket clientSocket = serverSocket.accept();
... spawn a new thread to handle the client ...
bindExceptionCounter = 0;
} catch (IOException e) {
e.printStackTrace();
recreateServerSocket();
}
}
private void recreateServerSocket() {
while (keepRunning) {
try {
logger.info("Try to re-create Server Socket");
ServerSocket socket = ServerSocketFactory.getDefault().createServerSocket(RateTableServer.RATE_EVENT_SERVER_PORT);
// No exception thrown, then use the new socket.
serverSocket = socket;
break;
} catch (BindException e) {
logger.info("BindException indicates that the server socket is still good.", e);
bindExceptionCounter++;
if (bindExceptionCounter < 5) {
break;
}
} catch (IOException e) {
logger.warn("Problem to re-create Server Socket", e);
e.printStackTrace();
try {
Thread.sleep(30000);
} catch (InterruptedException ie) {
logger.warn(ie);
}
}
}
}
Hi everyone, I am new to asp.net .. i want to learn about web services.. can anyone pls provide me a good link or pdf on web services for reading it from basic.. thanks in advance..
Hi,
I'm trying to transform some XML-data to HTML with XSLT for my bachelor thesis.
My professor wants me to consider XSL-FO too, or at least to write some word about it. But I'm very noob to this.
So my questions are:
Can I combine FO with HTML? Can I use FO istead of HTML and CSS? If yes, how will my browser render this? Are there any examples/tutorials on how to transform xml into web pages with FO?
Thank you very much.
I am learning ruby and practicing it by solving problems from Project Euler.
This is my solution for problem 12.
# Project Euler problem: 12
# What is the value of the first triangle number to have over five hundred divisors?
require 'prime'
triangle_number = ->(num){ (num *(num + 1)) / 2 }
factor_count = ->(num) do
prime_fac = Prime.prime_division(num)
exponents = prime_fac.collect { |item| item.last + 1 }
fac_count = exponents.inject(:*)
end
n = 2
loop do
tn = triangle_number.(n)
if factor_count.(tn) >= 500
puts tn
break
end
n += 1
end
Any improvements that can be made to this piece of code?
My programming experience is limited to xhtml, css, php, sql and some javascript. The books I have are:
Programming in Objective-C 2nd Edition
Beginning iPhone Development
Cocoa(R) Programming for Mac(R) OS X (Paperback)
Is there anything else I will need to get started on my journey into iPhone/OS X development?
Hello, everyone
I cannot get a way to terminate a thread that is hung in a socket.recvfrom() call. For example, ctrl+c that should trigger KeyboardInterrupt exception can't be caught. Here is a script I've used for testing:
from socket import *
from threading import Thread
from sys import exit
class TestThread(Thread):
def __init__(self,host="localhost",port=9999):
self.sock = socket(AF_INET,SOCK_DGRAM)
self.sock.bind((host,port))
super(TestThread,self).__init__()
def run(self):
while True:
try:
recv_data,addr = self.sock.recvfrom(1024)
except (KeyboardInterrupt, SystemExit):
sys.exit()
if __name__ == "__main__":
server_thread = TestThread()
server_thread.start()
while True: pass
The main thread (the one that executes infinite loop) exits. However the thread that I explicitly create, keeps hanging in recvfrom().
Please, help me resolve this.
Hello,
In the code below, I would like to make the word that prints out as the variable "$submittor" a hyperlink to "http://www...com/.../members/index.php?profile=$submittor" .
I can't get it to work; I think I'm doing the formatting wrong.
How can I do it?
Thanks in advance,
John
echo '<div class="sitename3name">Submitted by '.$submittor.' on '.$dt->format('F j, Y &\nb\sp &\nb\sp g:i a').'</div>';
I am trying to use the following code, but I always get an error that I can find little information about:
- (id)initWithNibName:@"MyRidesListView" bundle:nil {
if ((self = [super initWithNibName:@"MyRidesListView" bundle:nil])) {
// Custom initialization
}
return self;
}
Error:
expected identifier before 'OBJC_STRING' token
This seems like a simple method to be calling. This is for a UINavigationController.
Ideas?
Hi,
I was going through an example from Programming in Ruby book. This is that example
def fib_up_to(max)
i1, i2 = 1, 1 # parallel assignment (i1 = 1 and i2 = 1)
while i1 <= max
yield i1
i1, i2 = i2, i1+i2
end
end
fib_up_to(100) {|f| print f, " " }
The above program simply prints the fibonacci numbers upto 100. Thats fine. My question here is when i replace the parallel assignment with something like this,
i1 = i2
i2 = i1+i2
I am not getting the desired output. My question here is, is it advisable to use parallel assignments? (I come from Java background and it feels really wierd to see this type of assignment)
One more doubt is : Is parallel assignment an operator??
Thanks
"8,5,,1,4,7,,,,7,,1,9,3,6,,,8,6,3,9,,2,5,4,,,,,3,2,,,7,4,1,1,,4,,6,9,,5,,,,5,,,1,,6,3,,,6,5,,,,7,4,,1,7,6,,,,8,,5,,,7,1,,3,9,"
I'm doing a programming challenge where i need to parse this sequence into my sudoku script.
Need to get the above sequence into 8,5,0,1,4,7,0,0,0,7,0,1,9,3,6,0,0,8.........
I tried re but without success, help is appreciated, thanks.
Hello, I want to use either http://onehackoranother.com/projects/jquery/tipsy/ or http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/ and I was wondering if lets say I have a div on my page that has a class 'item_info'.
Can I have my tooltip that is created output the div inside the tooltip and formatted properly according to my css?
Is there another plugin I should be looking into?
Thanks. I hope this is clear enough.
New to VBA, please help. I have a range say A2:D10; input causes rows to be added. New entries are being added using NextRow=_. Works perfectly, however, how do I get the formulas in columns C and D to follow each new row being added. I cannot just format entire column due to my sort criteria. Example formula is =IF(ISTEXT($B11),$C$2-$D11,"")
What are the linux developper tools to do the things i do with .NET in my windows environnement :
I would like to port my client server application that runs under winform/nhibernate/sql server.
Language c#
Database SQL server
ORM Nhibernate
Source control SVN / Tortoise
Unit testing Nunit
Continuous integration Cruise Control
Should i go java and eclipse ?
Python and ???
Ruby and ???
Is there some IDE that allow me to manage all these processes under linux ?
Just started learning Java and I am confused about this whole independent platform thingy.
Doesn't independent means that Java code should be able to run on any machine and would need no special software to be installed (JVM in this case has to be present in the machine)?
Like, for example, we need to have Turbo C Compiler in order to compile C/C++ source code and then execute it.. The machine has to have the C compiler.
guess I am confused..Somebody please explain in simple language or may be direct me to a tutorial that explain things in simple language ? that would be great
I am just not getting the concept.
Could anyone explain me why in the last lines, br is not recognized as variable? I've even tried putting br in the try clause, setting it as final, etc. Does this have anything to do with Java not support closures? I am 99% confident similar code would work in C#.
private void loadCommands(String fileName) {
try {
final BufferedReader br = new BufferedReader(new FileReader(fileName));
while (br.ready()) {
actionList.add(CommandFactory.GetCommandFromText(this, br.readLine()));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) br.close(); //<-- This gives error. It doesn't
// know the br variable.
}
}
Thanks
The situation:
Each page I scrape has <input> elements with a title= and a value=
I don't know what is going to be on the page.
I want to have all my collected data in a single table at the end, with a column for each title.
So basically, I need each row of data to line up with all the others, and if a row doesn't have a certain element, then it should be blank (but there must be something there to keep the alignment).
eg.
First page has: {animal: cat, colour: blue, fruit: lemon, day: monday}
Second page has: {animal: fish, colour: green, day: saturday}
Third page has: {animal: dog, number: 10, colour: yellow, fruit: mango, day: tuesday}
Then my resulting table should be:
animal | number | colour | fruit | day
cat | none | blue | lemon | monday
fish | none | green | none | saturday
dog | 10 | yellow | mango | tuesday
Although it would be good to keep the order of the title value pairs, which I know dictionaries wont do.
So basically, I need to generate columns from all the titles (kept in order but somehow merged together)
What would be the best way of going about this without knowing all the possible titles and explicitly specifying an order for the values to be put in?
I have two functions:
def f(a,b,c=g(b)):
blabla
def g(n):
blabla
c is an optional argument in function f. If the user does not specify its value, the program should compute g(b) and that would be the value of c. But the code does not compile - it says name 'b' is not defined. How to fix that?
Someone suggested:
def g(b):
blabla
def f(a,b,c=None):
if c is None:
c = g(b)
blabla
But this doesn't work, because maybe the user intended c to be None and then c will have another value.
Background: I am more of a designer than a programmer, but have hacked templates for many open source CMS's (Drupal, Joomla, Wordpress)
I want to start from scratch in regards to the relations of php and a mysql database.
Lets assume I have a working database and php engine locally.
What would be my first step to connecting to my database and creating a table... (im happy to be led to an appropriate tutorial...)
Many of the tutorials I have seen start with basic php, but I would rather explore the connection between the db and the php.
Hi,
I'm working on my first Django application. In short, what it needs to do is to display a list of film titles, and allow users to give a rating (out of 10) to each film. I've been able to use the {{ form }} and {{ formset }} syntax in a template to produce a form which lets you rate one film at a time, which corresponds to one row in a MySQL table, but how do I produce a form that iterates over all the movie titles in the database and produces a form that lets you rate lots of them at once?
At first, I thought this was what formsets were for, but I can't see any way to automatically iterate over the contents of a database table to produce items to go in the form, if you see what I mean.
Currently, my views.py has this code:
def survey(request):
ScoreFormSet = formset_factory(ScoreForm)
if request.method == 'POST':
formset = ScoreFormSet(request.POST, request.FILES)
if formset.is_valid():
return HttpResponseRedirect('/')
else:
formset = ScoreFormSet()
return render_to_response('cf/survey.html', {
'formset':formset,
})
And my survey.html has this:
<form action="/survey/" method="POST">
<table>
{{ formset }}
</table>
<input type = "submit" value = "Submit">
</form>
Oh, and the definition of ScoreForm and Score from models.py are:
class Score(models.Model):
movie = models.ForeignKey(Movie)
score = models.IntegerField()
user = models.ForeignKey(User)
class ScoreForm(ModelForm):
class Meta:
model = Score
So, in case the above is not clear, what I'm aiming to produce is a form which has one row per movie, and each row shows a title, and has a box to allow the user to enter their score.
If anyone can point me at the right sort of approach to this, I'd be most grateful.
Thanks,
Ben
Hi i would like to filter array in php. for example
$a = ARRAY('a', 'b', 'c', 'd', 'e');
$b = ARRAY('c', 'd');
$a will be filtered by values in array $b
and result is ['a', 'b', 'e']
may I know how to do it in php?
Thank you.
Now following my series of "python newbie questions" and based on another question.
Go to http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables and scroll down to "Default Parameter Values". There you can find the following:
def bad_append(new_item, a_list=[]):
a_list.append(new_item)
return a_list
def good_append(new_item, a_list=None):
if a_list is None:
a_list = []
a_list.append(new_item)
return a_list
So, question here is: why is the "good" syntax over a known issue ugly like that in a programming language that promotes "elegant syntax" and "easy-to-use"?
Why not just something in the definition itself, that the "argument" name is attached to a "localized" mutable object like:
def better_append(new_item, a_list=[].local):
a_list.append(new_item)
return a_list
I'm sure there would be a better way to do this syntax, but I'm also almost positive there's a good reason to why it hasn't been done. So, anyone happens to know why?
I'm trying to create a custom dropdown for a derivative of CComboBox. The dropdown will be a calendar control plus some 'hotspots', e.g.
So I figure the best way to achieve this is to have a simple CWnd-derived class which acts as the parent to the calendar control, and have it paint the hotspots itself.
The window needs to be a popup window - I think - rather than a child window so that it isn't clipped. But doing this causes the dialog (on which the combobox control is placed) to stop being the topmost (foreground?) window, leading to its frame being drawn differently:
This spoils the illusion that the dropdown is part of the combobox since its acting more like a modal dialog at this point. Any suggestions on how I make the custom dropdown behave like the regular dropdown?
Are there any other pitfalls I need to watch out for, e.g. focus and mouse capture issues?
I'm a newcomer to Rails. I want to build a simple form that determines the sort order of a list.
I've implemented a form in the likes of -
<%= radio_button_tag :sort, "rating" %>
<%= label_tag :sort_rating, "order by rating" %>
<%= radio_button_tag :sort, "name" %>
<%= label_tag :sort_name, "order by name" %>
And now I am unsure how to implement the sort at the controller/model level. The aspects I am puzzled about are:
Where should the sort be performed
How could the sort parameter be persisted
How could the code be reused
Right now, I can't even get the selected sort method to remain selected after a submit.
I would most appreciate any guidance or reference to an example.