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.
I've only really started using this site and alredy I am very impressed by the community here!
This is my third question in less than three days. Hopefully I'll be able to start answering questions soon instead of just asking them!
I'm fairly new to jQuery and can't find a decent tutorial on Arrays.
I'd like to be able to create an array that targets several ID's on my page and performs the same effect for each.
For example I have tabs set up with the following:
$('.tabs div.tab').hide();
$('.tabs div:first').show();
$('.tabs ul li:first a').addClass('current');
$('.tabs ul li a').click(function(){
$('.tabs ul li a').removeClass('current');
$(this).addClass('current');
var currentTab = $(this).attr('href');
$('.tabs div.tab').hide();
$(currentTab).show();
return false;
});
I've used the class .tag to target the tabs as there are several sets on the same page, but I've heard jQuery works much faster when targetting ID's
How would I add an array to the above code to target 4 different ID's?
I've looked at
var myArray = new Array('#id1', 'id2', 'id3', 'id4');
And also
var myValues = [ '#id1', 'id2', 'id3', 'id4' ];
Which is correct and how do I then use the array in the code for my tabs...?
Hello,
I have a SwingWorker thread with an IOBound task which is totally locking up the interface while it runs. Swapping out the normal workload for a counter loop has the same result. The SwingWorker looks basically like this:
public class BackupWorker extends SwingWorker<String, String> {
private static String uname = null;
private static String pass = null;
private static String filename = null;
static String status = null;
BackupWorker (String uname, String pass, String filename) {
this.uname = uname;
this.pass = pass;
this.filename = filename;
}
@Override
protected String doInBackground() throws Exception {
BackupObject bak = newBackupObject(uname,pass,filename);
return "Done!";
}
}
The code that kicks it off lives in a class that extends JFrame:
public void actionPerformed(ActionEvent event) {
String cmd = event.getActionCommand();
if (BACKUP.equals(cmd)) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final StatusFrame statusFrame = new StatusFrame();
statusFrame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run () {
statusFrame.beginBackup(uname,pass,filename);
}
});
}
});
}
}
Here's the interesting part of StatusFrame:
public void beginBackup(final String uname, final String pass, final String filename) {
worker = new BackupWorker(uname, pass, filename);
worker.execute();
try {
System.out.println(worker.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
So far as I can see, everything "long-running" is handled by the worker, and everything that touches the GUI on the EDT. Have I tangled things up somewhere, or am I expecting too much of SwingWorker?
Hi there, back again with some more SQLAlchemy shenanigans.
Let me step through this.
My table is now set up as so:
engine = create_engine('sqlite:///:memory:', echo=False)
metadata = MetaData()
students_table = Table('studs', metadata,
Column('sid', Integer, primary_key=True),
Column('name', String),
Column('preferences', Integer),
Column('allocated_rank', Integer),
Column('allocated_project', Integer)
)
metadata.create_all(engine)
mapper(Student, students_table)
Fairly simple, and for the most part I've been enjoying the ability to query almost any bit of information I want provided I avoid the error cases below.
The class it is mapped from is:
class Student(object):
def __init__(self, sid, name):
self.sid = sid
self.name = name
self.preferences = collections.defaultdict(set)
self.allocated_project = None
self.allocated_rank = 0
def __repr__(self):
return str(self)
def __str__(self):
return "%s %s" %(self.sid, self.name)
Explanation: preferences is basically a set of all the projects the student would prefer to be assigned. When the allocation algorithm kicks in, a student's allocated_project emerges from this preference set.
Now if I try to do this:
for student in students.itervalues():
session.add(student)
session.commit()
It throws two errors, one for the allocated_project column (seen below) and a similar error for the preferences column:
sqlalchemy.exc.InterfaceError: (InterfaceError) Error binding parameter 4
- probably unsupported type. u'INSERT INTO studs (sid, name, allocated_rank,
allocated_project) VALUES (?, ?, ?, ?, ?, ?, ?)'
[1101, 'Muffett,M.', 1, 888 Human-spider relationships (Supervisor id: 123)]
If I go back into my code I find that, when I'm copying the preferences from the given text files, it actually refers to the Project class which is mapped to a dictionary, using the unique project id's (pid) as keys. Thus, as I iterate through each student via their rank and to the preferences set, it adds not a project id, but the reference to the project id from the projects dictionary.
students[sid].preferences[int(rank)].add(projects[int(pid)])
Now this is very useful to me since I can find out all I want to about a student's preferred projects without having to run another check to pull up information about the project id. The form you see in the error has the object print information passed as:
return "%s %s (Supervisor id: %s)" %(self.proj_id, self.proj_name, self.proj_sup)
My questions are:
I'm trying to store an object in a database field aren't I?
Would the correct way then, be copying the project information (project id, name, etc) into its own table, referenced by the unique project id? That way I can just have the project id field for one of the student tables just be an integer id and when I need more information, just join the tables? So and so forth for other tables?
If the above makes sense, then how does one maintain the relationship with a column of information in one table which is a key index on another table?
Does this boil down into a database design problem?
Are there any other elegant ways of accomplishing this?
Apologies if this is a very long-winded question. It's rather crucial for me to solve this, so I've tried to explain as much as I can, whilst attempting to show that I'm trying (key word here sadly) to understand what could be going wrong.
Hello!
I want to make a fourier-transformation of an image.
But how can I change the picture to an array?
And after this I think I should use numpy.fft.rfft2 for the transformation.
And how to change back from the array to the image?
Thanks in advance.
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 people, I'm trying to validate an age field in a form but I'm having some problem. First I tried to make sure that the field will not be send empty. I don't know JavaScript so I searched some scripts and adapted them to this:
function isInteger (s)
{
var i;
if (isEmpty(s))
if (isInteger.arguments.length == 1)
return 0;
else
return (isInteger.arguments[1] == true);
for (i = 0; i < s.length; i++)
{
var c = s.charAt(i);
if (!isDigit(c))
return false;
}
return true;
}
function isEmpty(s)
{
return ((s == null) || (s.length == 0))
}
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if ((validate_required(age,"Age must be filled out!")==false) ||
isInteger(age,"Age must be and int number")==false))
{email.focus();return false;}
}
}
//html part
<form action="doador.php" onsubmit="return validate_form(this)" method="post">
It's working fine for empty fields, but if I type any letters or characters in age field, it'll be sent and saved a 0 in my database. Can anyone help me?
Sorry for any mistake in English, and thanks in anvance for your help.
"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.
I have the following code:
foo :: Int -> [String] -> [(FilePath, Integer)] -> IO Int
foo _ [] _ = return 4
foo _ _ [] = return 5
foo n nameREs pretendentFilesWithSizes = do
result <- (bar n (head nameREs) pretendentFilesWithSizes)
if result == 0
then return 0 -- <========================================== here is the error
else foo n (tail nameREs) pretendentFilesWithSizes
I get an error on the line with the comment above, the error is:
aaa.hs:56:2:
parse error (possibly incorrect indentation)
I'm working with emacs, there's no spaces, and i do not understand what did i do wrong.
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
Hi,
I have started learning Ruby recently and I was trying out the following piece of code.
a=[1,2]
b='slam dunk'
a.each { |b| c=a*b; puts c;}
I am getting the following output. I have no clue why. I expected an error or something to be thrown. Can someone explain me why this happens?
1
2
1
2
1
2
Thanks
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?
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.
I understand the gist of the code, that it forms permutations; however, I was wondering if someone could explain exactly what is going on in the return statement.
def perm(l):
sz = len(l)
print (l)
if sz <= 1:
print ('sz <= 1')
return [l]
return [p[:i]+[l[0]]+p[i:] for i in range(sz) for p in perm(l[1:])]
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);
}
}
}
}
I have some code that I would like to use to append an edge to a Node data structure:
import Data.Set (Set)
import qualified Data.Set as Set
data Node = Vertex String (Set Node)
deriving Show
addEdge :: Node -> Node -> Node
addEdge (Vertex name neighbors) destination
| Set.null neighbors = Vertex name (Set.singleton destination)
| otherwise = Vertex name (Set.insert destination neighbors)
However when I try to compile I get this error:
No instance for (Ord Node)
arising from a use of `Set.insert'
As far as I can tell, Set.insert expects nothing but a value and a set to insert it into. What is this Ord?
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.
I was just wondering, can I decompose a tuple type into its components' types in Scala?
I mean, something like this
trait Container {
type Element
}
trait AssociativeContainer extends Container {
type Element <: (Unit, Unit)
def get(x : Element#First) : Element#Second
}
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 ?
Hi there,
I'm back again with my ongoing saga of Student-Project Allocation questions. Thanks to Moron (who does not match his namesake) I've got a bit of direction for an evaluation portion of my project.
Going with the idea of the Assignment Problem and Hungarian Algorithm I would like to express my data in the form of a .csv file which would end up looking like this in spreadsheet form. This is based on the structure I saw here.
| | Project 1 | Project 2 | Project 3 |
|----------|-----------|-----------|-----------|
|Student1 | | 2 | 1 |
|----------|-----------|-----------|-----------|
|Student2 | 1 | 2 | 3 |
|----------|-----------|-----------|-----------|
|Student3 | 1 | 3 | 2 |
|----------|-----------|-----------|-----------|
To make it less cryptic: the rows are the Students/Agents and the columns represent Projects/Task. Obviously ONE project can be assigned to ONE student. That, in short, is what my project is about. The fields represent the preference weights the students have placed upon the projects (ranging from 1 to 10). If blank, that student does not want that project and there's no chance of him/her being assigned such.
Anyway, my data is stored within dictionaries. Specifically the students and projects dictionaries such that:
students[student_id] = Student(student_id, student_name, alloc_proj, alloc_proj_rank, preferences)
where preferences is in the form of a dictionary such that
preferences[rank] = {project_id}
and
projects[project_id] = Project(project_id, project_name)
I'm aware that sorted(students.keys()) will give me a sorted list of all the student IDs which will populate the row labels and sorted(projects.keys()) will give me the list I need to populate the column labels. Thus for each student, I'd go into their preferences dictionary and match the applicable projects to ranks. I can do that much.
Where I'm failing is understanding how to create a .csv file. Any help, pointers or good tutorials will be highly appreciated.
Is there such a thing as a paid (or free would be GREAT, but unlikely I'm thinking) resource that could help a newbie with guidance and help as I create my first app (C# with SQLite db)?
Stackoverflow is great, but a one-on-one person who was familiar with exactly what I'm doing would be even better.
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've only just dipped my toe in the world of Haskell as part of my journey of programming enlightenment (moving on from, procedural to OOP to concurrent to now functional).
I've been trying an online Haskell Evaluator.
However I'm now stuck on a problem:
Create a simple function that gives the total sum of an array of numbers.
In a procedural language this for me is easy enough (using recursion) (c#) :
private int sum(ArrayList x, int i)
{
if (!(x.Count < i + 1)) {
int t = 0;
t = x.Item(i);
t = sum(x, i + 1) + t;
return t;
}
}
All very fine however my failed attempt at Haskell was thus:
let sum x = x+sum in map sum [1..10]
this resulted in the following error (from that above mentioned website):
Occurs check: cannot construct the infinite type: a = a -> t
Please bear in mind I've only used Haskell for the last 30 minutes!
I'm not looking simply for an answer but a more explanation of it.
Thanks in advanced.