Mention 2 modifications that can be done to a linked list data structure
so that it is converted into a binary tree data structure?
It's an A level question. I looked it out on google but only programs are
found. I need theory explanation.
Saturday, 31 August 2013
how to open UIImagePickerControllerSourceTypeCamera into a small popup subview
how to open UIImagePickerControllerSourceTypeCamera into a small popup
subview
I am trying to open a UIImagePickerControllerSourceTypeCamera into a small
popup subview, however every time I try this it simply goes to full screen
camera... This is the first time I have tried using the camera I have read
all of the docs in the developers site and I just cannot find anything
explaning how to do what I would like to do.
Below is my startCamera method, in which i create a subview, then create
the cameraView add the cameraView to the small subview then i load it onto
the main UIView.... however as said above it goes full screen everytime :(
any help making this cameraView look like a small popup view would be
greatly appreciated.
#pragma StartCamera
- (IBAction)startCamera:(id)sender {
if (isCameraViewLoaded == NO) {
// Load View for camera
cameraView = [[UIView alloc] initWithFrame:CGRectMake(100.0,
100.0, 200.0, 100.0)];
cameraView.backgroundColor = [UIColor greenColor];
// imagepicker stuff
// check for rear facing camera to continue
if( [UIImagePickerController
isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear])
{
// load imagePickController into subview
UIImagePickerController
*imagePickController=[[UIImagePickerController alloc]init];
imagePickController.sourceType=UIImagePickerControllerSourceTypeCamera;
imagePickController.delegate=self;
imagePickController.allowsEditing=TRUE;
imagePickController.modalPresentationStyle =
UIModalPresentationCurrentContext;
[cameraView addSubview:imagePickController.view];
}
else {
// if there is no camera on the device give warning
UIAlertView *noCameraAlert = [[UIAlertView alloc]
initWithTitle:@"Incompatible Device" message:@"Sorry, This
feature requiers a rear facing camera" delegate:self
cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[noCameraAlert show];
}
// pass camera View to mainview
[self.view addSubview:cameraView];
isCameraViewLoaded = YES;
}else{
[cameraView removeFromSuperview];
isCameraViewLoaded = NO;
}
}
subview
I am trying to open a UIImagePickerControllerSourceTypeCamera into a small
popup subview, however every time I try this it simply goes to full screen
camera... This is the first time I have tried using the camera I have read
all of the docs in the developers site and I just cannot find anything
explaning how to do what I would like to do.
Below is my startCamera method, in which i create a subview, then create
the cameraView add the cameraView to the small subview then i load it onto
the main UIView.... however as said above it goes full screen everytime :(
any help making this cameraView look like a small popup view would be
greatly appreciated.
#pragma StartCamera
- (IBAction)startCamera:(id)sender {
if (isCameraViewLoaded == NO) {
// Load View for camera
cameraView = [[UIView alloc] initWithFrame:CGRectMake(100.0,
100.0, 200.0, 100.0)];
cameraView.backgroundColor = [UIColor greenColor];
// imagepicker stuff
// check for rear facing camera to continue
if( [UIImagePickerController
isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear])
{
// load imagePickController into subview
UIImagePickerController
*imagePickController=[[UIImagePickerController alloc]init];
imagePickController.sourceType=UIImagePickerControllerSourceTypeCamera;
imagePickController.delegate=self;
imagePickController.allowsEditing=TRUE;
imagePickController.modalPresentationStyle =
UIModalPresentationCurrentContext;
[cameraView addSubview:imagePickController.view];
}
else {
// if there is no camera on the device give warning
UIAlertView *noCameraAlert = [[UIAlertView alloc]
initWithTitle:@"Incompatible Device" message:@"Sorry, This
feature requiers a rear facing camera" delegate:self
cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[noCameraAlert show];
}
// pass camera View to mainview
[self.view addSubview:cameraView];
isCameraViewLoaded = YES;
}else{
[cameraView removeFromSuperview];
isCameraViewLoaded = NO;
}
}
How to rename a column of a pandas.core.series.TimeSeries object?
How to rename a column of a pandas.core.series.TimeSeries object?
Substracting the 'Settle' column of a pandas.core.frame.DataFrame from the
'Settle' column of another pandas.core.frame.DataFrame resulted in a
pandas.core.series.TimeSeries object (the 'subs' object).
Now, when I plot subs and add a legend, it reads 'Settle'.
How can I change the name of a column of a pandas.core.series.TimeSeries
object?
thank you.
Substracting the 'Settle' column of a pandas.core.frame.DataFrame from the
'Settle' column of another pandas.core.frame.DataFrame resulted in a
pandas.core.series.TimeSeries object (the 'subs' object).
Now, when I plot subs and add a legend, it reads 'Settle'.
How can I change the name of a column of a pandas.core.series.TimeSeries
object?
thank you.
explain me a preg_match if clause please
explain me a preg_match if clause please
if(preg_match("/^[\w_.]+$/",stripslashes($_GET['key']))) {
$key = $wpdb->escape(stripslashes($_GET['key']));
}
assuming the key value is = be4e53680e6518cca701ec091258642f0740fe3d
can someone please explain me the if condition ? I`m confused on what
exactly it checks for
if(preg_match("/^[\w_.]+$/",stripslashes($_GET['key']))) {
$key = $wpdb->escape(stripslashes($_GET['key']));
}
assuming the key value is = be4e53680e6518cca701ec091258642f0740fe3d
can someone please explain me the if condition ? I`m confused on what
exactly it checks for
Unpickling bytea columns from Psycopg2
Unpickling bytea columns from Psycopg2
I am storing pickled objects in a PostgreSQL database. Originally I
thought this was a bad idea, but they are seldom accessed and from what
I've learned apparently TOAST makes the performance impact minimal for
storing big blobs in a relational database.
When you INSERT or UPDATE a bytea column it is simple. Just construct a
psycopg2.Binary and pass it to the execute call on the cursor object. In
my case, it's a pickled object.
Whenever you do a SELECT and get back a bytea column you wind up with a
python buffer object. In other words, you can't just do a pickle.loads or
a pickle.load. The best I've come up with is using StringIO
import psycopg2
import cPickle as pickle
import cStringIO as StringIO
conn = psycopg2.connect(user='postgres',database='postgres')
cur = conn.cursor()
cur.execute('Select %s', (psycopg2.Binary(pickle.dumps({'foo':'bar'},-1)), ))
result, = cur.fetchone()
cur.close()
conn.rollback()
result = StringIO.StringIO(result)
print pickle.load(result)
What's the cost of this? Are the StringIO objects just shallow copies of
the original buffer object? Is there a more practical way of doing this?
I'm using Stackless 2.7.5 if it matters.
I am storing pickled objects in a PostgreSQL database. Originally I
thought this was a bad idea, but they are seldom accessed and from what
I've learned apparently TOAST makes the performance impact minimal for
storing big blobs in a relational database.
When you INSERT or UPDATE a bytea column it is simple. Just construct a
psycopg2.Binary and pass it to the execute call on the cursor object. In
my case, it's a pickled object.
Whenever you do a SELECT and get back a bytea column you wind up with a
python buffer object. In other words, you can't just do a pickle.loads or
a pickle.load. The best I've come up with is using StringIO
import psycopg2
import cPickle as pickle
import cStringIO as StringIO
conn = psycopg2.connect(user='postgres',database='postgres')
cur = conn.cursor()
cur.execute('Select %s', (psycopg2.Binary(pickle.dumps({'foo':'bar'},-1)), ))
result, = cur.fetchone()
cur.close()
conn.rollback()
result = StringIO.StringIO(result)
print pickle.load(result)
What's the cost of this? Are the StringIO objects just shallow copies of
the original buffer object? Is there a more practical way of doing this?
I'm using Stackless 2.7.5 if it matters.
SyntaxError: Unexpected end of input (nodejs tcp server)
SyntaxError: Unexpected end of input (nodejs tcp server)
I have a very basic tcp server that can send and receive json data.
See my code:
// Handle incoming messages from clients.
socket.on('data', function (data) {
var obj = JSON.parse(data);
if(obj.type == "register") {
_clientObj[obj.msg] = {
client: 'Client',
socketID: socket.name
}
console.log("Register...");
} else if(obj.type == "message") {
console.log(socket.name + " --> message: " + obj.msg);
}
});
The problem seems to be that sometimes data is not complete and it trows
an error:
SyntaxError: Unexpected end of input
How can i wait before data is finished before i parse out the json?
I have a very basic tcp server that can send and receive json data.
See my code:
// Handle incoming messages from clients.
socket.on('data', function (data) {
var obj = JSON.parse(data);
if(obj.type == "register") {
_clientObj[obj.msg] = {
client: 'Client',
socketID: socket.name
}
console.log("Register...");
} else if(obj.type == "message") {
console.log(socket.name + " --> message: " + obj.msg);
}
});
The problem seems to be that sometimes data is not complete and it trows
an error:
SyntaxError: Unexpected end of input
How can i wait before data is finished before i parse out the json?
Page Redirect Or Stats On same page upon succesfull submittion
Page Redirect Or Stats On same page upon succesfull submittion
i need my web form to redirect Or stays on same page Upon successful
submitting.
Well When user submit the form it struck on www.domain.com/send.php after
alert box.
I need it to come back to previous page OR stays on the current page.
here is my code!!!
if ($success){ echo "<script type='text/javascript'>alert('Message
Successfully Sent!')</script>";}
?>
any idea?
i need my web form to redirect Or stays on same page Upon successful
submitting.
Well When user submit the form it struck on www.domain.com/send.php after
alert box.
I need it to come back to previous page OR stays on the current page.
here is my code!!!
if ($success){ echo "<script type='text/javascript'>alert('Message
Successfully Sent!')</script>";}
?>
any idea?
Issue with HttpWebRequest Google.com
Issue with HttpWebRequest Google.com
I have a c# application that searches on google , after a few hits i see
the captcha message. On this i go to internet explorer enter same page i
see captcha aswell , i enter that and its all good search results are
shown. But in my c# application when i hit the same url i see captcha
again why is that and how to bypass it? I am confused as i have enter
captcha characters and its passed so why i see captcha again on next hit
in c# but not from browser!
I just need to be pointed to the right direction , or some idea or
suggestion.
I have a c# application that searches on google , after a few hits i see
the captcha message. On this i go to internet explorer enter same page i
see captcha aswell , i enter that and its all good search results are
shown. But in my c# application when i hit the same url i see captcha
again why is that and how to bypass it? I am confused as i have enter
captcha characters and its passed so why i see captcha again on next hit
in c# but not from browser!
I just need to be pointed to the right direction , or some idea or
suggestion.
Friday, 30 August 2013
UIButtons don't align correctly upon first load of View Controller
UIButtons don't align correctly upon first load of View Controller
I have a ViewController/View in a TabBar Controller that has 8 UIButtons
in a 2x4 grid, sized 75x75, each with a 75x75 background image set on
them. Currently, I've hard coded the XY positions in the Size Inspector in
Interface Builder.
When I first load the View, by clicking on the tab bar icon, the bottom
two buttons get squished against the row above them - as per this picture:
Each button triggers a segue that launches another ViewController with a
WebView in it :
[self performSegueWithIdentifier:@"playVimeo" sender:sender];
In that WebView, there is a back button that triggers another segue to
return to the thumbnails page :
[self performSegueWithIdentifier:@"returnToThumbnails" sender:sender];
When I press the back button and return to the thumbnail view for a second
time, the buttons snap to the right place, unlike when they first load, as
per this picture:
Here is a screenshot of my Storyboard:
Does anyone have an idea what is going on here ? I am lost...
Thanks in advance!
Jesse
I have a ViewController/View in a TabBar Controller that has 8 UIButtons
in a 2x4 grid, sized 75x75, each with a 75x75 background image set on
them. Currently, I've hard coded the XY positions in the Size Inspector in
Interface Builder.
When I first load the View, by clicking on the tab bar icon, the bottom
two buttons get squished against the row above them - as per this picture:
Each button triggers a segue that launches another ViewController with a
WebView in it :
[self performSegueWithIdentifier:@"playVimeo" sender:sender];
In that WebView, there is a back button that triggers another segue to
return to the thumbnails page :
[self performSegueWithIdentifier:@"returnToThumbnails" sender:sender];
When I press the back button and return to the thumbnail view for a second
time, the buttons snap to the right place, unlike when they first load, as
per this picture:
Here is a screenshot of my Storyboard:
Does anyone have an idea what is going on here ? I am lost...
Thanks in advance!
Jesse
Thursday, 29 August 2013
connect a Flash application with a microsoft database
connect a Flash application with a microsoft database
I would like to ask whether it is possible to connect a microsoft access
database to a flash application please?
I would like to ask whether it is possible to connect a microsoft access
database to a flash application please?
how much white is a frame using OpenCV
how much white is a frame using OpenCV
I have a GRAY image and I want to know the percentage of the white color
on it. I know that I can do these with two for-loop that check the color
of each pixel, but I was wondring if there any better method to do this ?
here is an example the image that I want to analyze :
I have a GRAY image and I want to know the percentage of the white color
on it. I know that I can do these with two for-loop that check the color
of each pixel, but I was wondring if there any better method to do this ?
here is an example the image that I want to analyze :
Wednesday, 28 August 2013
How to reset an image element's width?
How to reset an image element's width?
When I load an image dynamically, it has the correct dimensions. However,
when I scale the image I manually set the width and height values of the
image.
When I load another image, the values are retained from the previous image
and it is deformed. I need to make the element think has no width/height
values so it will take the dimensions of the src I set it to.
When I load an image dynamically, it has the correct dimensions. However,
when I scale the image I manually set the width and height values of the
image.
When I load another image, the values are retained from the previous image
and it is deformed. I need to make the element think has no width/height
values so it will take the dimensions of the src I set it to.
Powerpoint 2007 different header per section
Powerpoint 2007 different header per section
I am trying to create a presentation with different headers depending on
what section of the presentation is currently being shown. At the top of
the slide when viewing a slide that is in section 2 it should show
something like this:
section1 section2 section3 section4
but when viewing a slide in section 1:
section1 section2 section3 section4
Thus creating a section header effect that gives clues to viewers about
current context, similar to many websites.
The "headers and footers" dialogue in the slide master is no use, it only
seems to add headers to the notes page and not to the actual slide.
Meanwhile adding text directly onto the slide master appears universally
on EVERY slide.
Note I am not asking about creating a separate slide to delineate sections.
I'm using Powerpoint 2007 on Windows 7.
I am trying to create a presentation with different headers depending on
what section of the presentation is currently being shown. At the top of
the slide when viewing a slide that is in section 2 it should show
something like this:
section1 section2 section3 section4
but when viewing a slide in section 1:
section1 section2 section3 section4
Thus creating a section header effect that gives clues to viewers about
current context, similar to many websites.
The "headers and footers" dialogue in the slide master is no use, it only
seems to add headers to the notes page and not to the actual slide.
Meanwhile adding text directly onto the slide master appears universally
on EVERY slide.
Note I am not asking about creating a separate slide to delineate sections.
I'm using Powerpoint 2007 on Windows 7.
Did anyone received got a Windows update of Broadcom Corporation Bluetooth Controller in the last days?
Did anyone received got a Windows update of Broadcom Corporation Bluetooth
Controller in the last days?
I received a suspicious update (see below) through Windows Update. I asked
my friends, but none received that update.
So I wanted to ask if someone else also received this update. Because atm
I am worried that Windows Update is infiltrated. Because the description
of this update is so generic and the links are so generic as well.
Broadcom Corporation - Bluetooth Controller - Broadcom Bluetooth 2.0+EDR
USB Dongle
Installation date: ý26-ý08-ý2013 09:45
Installation status: Successful
Update type: Optional
Broadcom Corporation Bluetooth Controller software update released in
August, 2013
More information: http://sysdev.microsoft.com/support/default.aspx
Help and Support: http://support.microsoft.com/select/?target=hub
Controller in the last days?
I received a suspicious update (see below) through Windows Update. I asked
my friends, but none received that update.
So I wanted to ask if someone else also received this update. Because atm
I am worried that Windows Update is infiltrated. Because the description
of this update is so generic and the links are so generic as well.
Broadcom Corporation - Bluetooth Controller - Broadcom Bluetooth 2.0+EDR
USB Dongle
Installation date: ý26-ý08-ý2013 09:45
Installation status: Successful
Update type: Optional
Broadcom Corporation Bluetooth Controller software update released in
August, 2013
More information: http://sysdev.microsoft.com/support/default.aspx
Help and Support: http://support.microsoft.com/select/?target=hub
ubuntu svn post commit not work but manual
ubuntu svn post commit not work but manual
/usr/bin/svn update /var/project2_test/debug --username XXXX--password
XXXX /bin/echo $REV >> /var/project2_test/svn.log
the log has been updated while committing. but working copy never update.
And I run /home/admin/svn/project/hooks/post-commit by hand. IT WORKS!
/usr/bin/svn update /var/project2_test/debug --username XXXX--password
XXXX /bin/echo $REV >> /var/project2_test/svn.log
the log has been updated while committing. but working copy never update.
And I run /home/admin/svn/project/hooks/post-commit by hand. IT WORKS!
What is the difference between innerText and outerText?
What is the difference between innerText and outerText?
After searching through web i understood the difference between innerHTML
and outerHTML.
However i am having hard time understanding the difference between
innerText and outerText. Both appear almost same to me.
Can anyone help me understand this with a nice illustration ?
Thank You !
After searching through web i understood the difference between innerHTML
and outerHTML.
However i am having hard time understanding the difference between
innerText and outerText. Both appear almost same to me.
Can anyone help me understand this with a nice illustration ?
Thank You !
Tuesday, 27 August 2013
Where is the FallbackRoute attribute defined in ServiceStack?
Where is the FallbackRoute attribute defined in ServiceStack?
Here is a potentially simple question that I can seem to find the answer to:
In which namespace is the fallback route attribute defined in
ServiceStack? The wiki shows the following example, but the ServiceHost
namespace (where the Route attribute is defined) does not have a
definition for a fallback.
[FallbackRoute("/{Path}")]
Here is a potentially simple question that I can seem to find the answer to:
In which namespace is the fallback route attribute defined in
ServiceStack? The wiki shows the following example, but the ServiceHost
namespace (where the Route attribute is defined) does not have a
definition for a fallback.
[FallbackRoute("/{Path}")]
Feature Weight Adjustment with SVM
Feature Weight Adjustment with SVM
I want to use Support Vector Machine to adjust the class weight of my
features (zhere are 7 features in my test datas). Is there a method to
extract the optimized class weights from the SVM?
I've tested:
CvSVMParams params;
params.svm_type = CvSVM::C_SVC;
params.kernel_type = CvSVM::LINEAR;
params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 100, 1e-6);
CvSVM SVM;
SVM.train_auto(trainingDataMat, labelsMat, Mat(), Mat(), params);
CvSVMParams optimized=SVM.get_params();
CvMat* weights=optimized.class_weights;
qDebug()<<weights->cols;
But then, the programm crashes
greetings
I want to use Support Vector Machine to adjust the class weight of my
features (zhere are 7 features in my test datas). Is there a method to
extract the optimized class weights from the SVM?
I've tested:
CvSVMParams params;
params.svm_type = CvSVM::C_SVC;
params.kernel_type = CvSVM::LINEAR;
params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 100, 1e-6);
CvSVM SVM;
SVM.train_auto(trainingDataMat, labelsMat, Mat(), Mat(), params);
CvSVMParams optimized=SVM.get_params();
CvMat* weights=optimized.class_weights;
qDebug()<<weights->cols;
But then, the programm crashes
greetings
Rails render not refrshing the page
Rails render not refrshing the page
I am working on ROR app . The app view contain ajax and jquery code :
jQuery.ajax({
data: 'val=' + val,
dataType: 'script',
type: 'post',
url: "/portfolio/update"
});
The update action contain this code:
def update
j=params[:val]
# Buisness logic code
redirect_to root_url,notice:"update done"
end
current View and Root url is same - Portfolio/show Now the button on view
(which is root_url only)is doing the business logic fine , but the page is
not getting refreshed , Whereas other simple form button on views are
doing it. After pressing button i am getting this in rails server :
Rendered portfolio/show.erb (1.5ms) Completed 200 OK in 24ms (Views:
4.1ms)
Any guesses, but the page is not refreshing by its own.
I am working on ROR app . The app view contain ajax and jquery code :
jQuery.ajax({
data: 'val=' + val,
dataType: 'script',
type: 'post',
url: "/portfolio/update"
});
The update action contain this code:
def update
j=params[:val]
# Buisness logic code
redirect_to root_url,notice:"update done"
end
current View and Root url is same - Portfolio/show Now the button on view
(which is root_url only)is doing the business logic fine , but the page is
not getting refreshed , Whereas other simple form button on views are
doing it. After pressing button i am getting this in rails server :
Rendered portfolio/show.erb (1.5ms) Completed 200 OK in 24ms (Views:
4.1ms)
Any guesses, but the page is not refreshing by its own.
aspnet sitemap (only) localization not working
aspnet sitemap (only) localization not working
I have a problem with sitemap localization. Whole app is localized
properly but sitemap is not.
I would like to get any error information or know where to put breakpoint
to know what is wrong.
I've been using this guide
I have a problem with sitemap localization. Whole app is localized
properly but sitemap is not.
I would like to get any error information or know where to put breakpoint
to know what is wrong.
I've been using this guide
Source local, scrolling like YouTube
Source local, scrolling like YouTube
Odd ball question for somebody just getting started with html5 players and
streaming video....
When using YouTube long videos can be scrolled towards then end then
played from there. Assuming YouTube first pulls down metadata like total
video start/stop points and a bunch of thumbnails for scrolling.
Is this possible with videojs? Reason asking is that I have video data
inside a mongo database that I would like to stream similar to the YouTube
player.
Inside mongo I have a bunch of smaller h264 files each in a document:
actual raw h264 usually 1000kb (max 2 seconds), creation timestamp (long),
and potentially a converted format (like mp4) for known clients. Idea is
to query off a time range and order by creation time then piping the
results into readable stream. There is a nice ffmpeg module to take
streams and reformat if needed. Thought about piping the stream to the
client with binaryjs and appending it into the player.
But the source directives in the documentation are usually URLs plus I
need to lock down the start/stop point for the total video being played
plus thumbnails.
Odd ball question for somebody just getting started with html5 players and
streaming video....
When using YouTube long videos can be scrolled towards then end then
played from there. Assuming YouTube first pulls down metadata like total
video start/stop points and a bunch of thumbnails for scrolling.
Is this possible with videojs? Reason asking is that I have video data
inside a mongo database that I would like to stream similar to the YouTube
player.
Inside mongo I have a bunch of smaller h264 files each in a document:
actual raw h264 usually 1000kb (max 2 seconds), creation timestamp (long),
and potentially a converted format (like mp4) for known clients. Idea is
to query off a time range and order by creation time then piping the
results into readable stream. There is a nice ffmpeg module to take
streams and reformat if needed. Thought about piping the stream to the
client with binaryjs and appending it into the player.
But the source directives in the documentation are usually URLs plus I
need to lock down the start/stop point for the total video being played
plus thumbnails.
The server tag is not well formed
The server tag is not well formed
here'is my HTML :
<asp:Label ID="EmployeeIDlbl" runat="server" Text="<%#
GetLabelCaption("Judges", "Employee Number",CaptionType.EditLabel)
%>"></asp:Label>
where: "CaptionStyle" is Enumerator which i previously created , and
"GetLabelCaption" function returns a string fetched from sql database.
I wanna know where is the error ?!!
here'is my HTML :
<asp:Label ID="EmployeeIDlbl" runat="server" Text="<%#
GetLabelCaption("Judges", "Employee Number",CaptionType.EditLabel)
%>"></asp:Label>
where: "CaptionStyle" is Enumerator which i previously created , and
"GetLabelCaption" function returns a string fetched from sql database.
I wanna know where is the error ?!!
no matter what the query is, sometimes it delayed so much
no matter what the query is, sometimes it delayed so much
i programmed at centos(6.2final), mysql 5.1.66 and java jdk 1.6.
this code get me server's result.
public ArrayList confirm(String key, String string){
ArrayList tmp= null;
try{
PreparedStatement prep = null;
try{
prep = Local.prepareStatement("select distinct tags from tagDB
where key=? and string!=?;");
}catch (Exception e) {
}if(prep!=null){
prep.setString(1,key);
prep.setString(2,string);
int count = getRowCount(prep.executeQuery());
if(count>0){
tmp= new ArrayList();
ResultSet rs = prep.executeQuery();
while(rs.next()){
tmp.add(rs.getString("tags"));
}
return tmp;
}
}
}catch(Exception e){
e.printStackTrace();
}
return tmp;
}
and db of server is good. i think so.
if you want to see mysql. i can get it to you.
my log from java is below.
16:2:46:450, turnaround time :26
16:2:46:484, turnaround time :23
16:2:46:514, turnaround time :24
16:2:46:769, turnaround time :23
16:2:46:819, turnaround time :24
16:2:46:845, turnaround time :23
16:2:46:874, turnaround time :23
16:2:47:259, turnaround time :82
16:2:47:290, turnaround time :23
16:2:47:327, turnaround time :24
16:2:47:369, turnaround time :25
16:2:47:665, turnaround time :23
16:2:47:707, turnaround time :24
16:2:47:739, turnaround time :23
16:2:47:776, turnaround time :25
16:2:47:803, turnaround time :25
16:2:49:492, turnaround time :23
16:2:49:524, turnaround time :23
16:2:50:7, turnaround time :24
16:2:50:51, turnaround time :27
16:2:50:136, turnaround time :71
16:2:50:246, turnaround time :106
16:2:50:761, turnaround time :47
16:2:51:848, turnaround time :23
16:2:51:875, turnaround time :25
16:2:51:912, turnaround time :31
16:2:51:965, turnaround time :23
16:2:52:13, turnaround time :45
16:2:52:545, turnaround time :22
16:2:52:573, turnaround time :24
16:2:52:601, turnaround time :22
16:2:52:626, turnaround time :23
16:2:52:963, turnaround time :108
16:2:53:22, turnaround time :54
16:2:58:131, turnaround time :5098
16:2:58:157, turnaround time :22
16:2:58:241, turnaround time :23
16:2:58:271, turnaround time :22
16:2:58:296, turnaround time :23
16:2:58:325, turnaround time :23
**16:3:3:358, turnaround time :5028
16:3:8:423, turnaround time :5027**
16:3:9:525, turnaround time :22
16:3:9:573, turnaround time :46
16:3:9:623, turnaround time :42
16:3:9:656, turnaround time :23
16:3:9:713, turnaround time :51
16:3:9:752, turnaround time :24
16:3:9:799, turnaround time :31
16:3:9:941, turnaround time :23
16:3:9:965, turnaround time :22
16:3:9:993, turnaround time :22
16:3:10:25, turnaround time :23
16:3:10:51, turnaround time :23
16:3:10:97, turnaround time :41
16:3:10:248, turnaround time :64
16:3:15:288, turnaround time :5032
sometimes it delayed 5000ms exactly.
so i think it happend cause of server's mem or buffer setting, like gc of
java.
so i edit my.cnf(config file of mysql). about size of maxconnection,
max_heap_table_size, max_tmp_table_size, thread_cache_size and so on. (i
failed to adjust value of thread_cache_size and some table thing. my.cnf
file doesn't adjust above two value....)
than nothing happened.
mysql's slow query log can't get anything.
... anything i can't do more. so please.. and appreciate so much to read
all....
so much. have a good day you all.
ps. my english is not good.. i know. sorry about that too.^^;
i programmed at centos(6.2final), mysql 5.1.66 and java jdk 1.6.
this code get me server's result.
public ArrayList confirm(String key, String string){
ArrayList tmp= null;
try{
PreparedStatement prep = null;
try{
prep = Local.prepareStatement("select distinct tags from tagDB
where key=? and string!=?;");
}catch (Exception e) {
}if(prep!=null){
prep.setString(1,key);
prep.setString(2,string);
int count = getRowCount(prep.executeQuery());
if(count>0){
tmp= new ArrayList();
ResultSet rs = prep.executeQuery();
while(rs.next()){
tmp.add(rs.getString("tags"));
}
return tmp;
}
}
}catch(Exception e){
e.printStackTrace();
}
return tmp;
}
and db of server is good. i think so.
if you want to see mysql. i can get it to you.
my log from java is below.
16:2:46:450, turnaround time :26
16:2:46:484, turnaround time :23
16:2:46:514, turnaround time :24
16:2:46:769, turnaround time :23
16:2:46:819, turnaround time :24
16:2:46:845, turnaround time :23
16:2:46:874, turnaround time :23
16:2:47:259, turnaround time :82
16:2:47:290, turnaround time :23
16:2:47:327, turnaround time :24
16:2:47:369, turnaround time :25
16:2:47:665, turnaround time :23
16:2:47:707, turnaround time :24
16:2:47:739, turnaround time :23
16:2:47:776, turnaround time :25
16:2:47:803, turnaround time :25
16:2:49:492, turnaround time :23
16:2:49:524, turnaround time :23
16:2:50:7, turnaround time :24
16:2:50:51, turnaround time :27
16:2:50:136, turnaround time :71
16:2:50:246, turnaround time :106
16:2:50:761, turnaround time :47
16:2:51:848, turnaround time :23
16:2:51:875, turnaround time :25
16:2:51:912, turnaround time :31
16:2:51:965, turnaround time :23
16:2:52:13, turnaround time :45
16:2:52:545, turnaround time :22
16:2:52:573, turnaround time :24
16:2:52:601, turnaround time :22
16:2:52:626, turnaround time :23
16:2:52:963, turnaround time :108
16:2:53:22, turnaround time :54
16:2:58:131, turnaround time :5098
16:2:58:157, turnaround time :22
16:2:58:241, turnaround time :23
16:2:58:271, turnaround time :22
16:2:58:296, turnaround time :23
16:2:58:325, turnaround time :23
**16:3:3:358, turnaround time :5028
16:3:8:423, turnaround time :5027**
16:3:9:525, turnaround time :22
16:3:9:573, turnaround time :46
16:3:9:623, turnaround time :42
16:3:9:656, turnaround time :23
16:3:9:713, turnaround time :51
16:3:9:752, turnaround time :24
16:3:9:799, turnaround time :31
16:3:9:941, turnaround time :23
16:3:9:965, turnaround time :22
16:3:9:993, turnaround time :22
16:3:10:25, turnaround time :23
16:3:10:51, turnaround time :23
16:3:10:97, turnaround time :41
16:3:10:248, turnaround time :64
16:3:15:288, turnaround time :5032
sometimes it delayed 5000ms exactly.
so i think it happend cause of server's mem or buffer setting, like gc of
java.
so i edit my.cnf(config file of mysql). about size of maxconnection,
max_heap_table_size, max_tmp_table_size, thread_cache_size and so on. (i
failed to adjust value of thread_cache_size and some table thing. my.cnf
file doesn't adjust above two value....)
than nothing happened.
mysql's slow query log can't get anything.
... anything i can't do more. so please.. and appreciate so much to read
all....
so much. have a good day you all.
ps. my english is not good.. i know. sorry about that too.^^;
Monday, 26 August 2013
How to get working environment in Symfony 1.4
How to get working environment in Symfony 1.4
I have some features that I only want shown when the website is run in dev
mode (or in development environment). How can I programmatically determine
what environment is currently being used?
E.g.
// $inDevEnvironment = ?
if ($inDevEnvironment) {
// DEV feature here
}
I have some features that I only want shown when the website is run in dev
mode (or in development environment). How can I programmatically determine
what environment is currently being used?
E.g.
// $inDevEnvironment = ?
if ($inDevEnvironment) {
// DEV feature here
}
Custom ReCaptcha Login
Custom ReCaptcha Login
I'm trying to add ReCaptcha to my login page. I know there are many many
plugins by per request I cannot use plugins. So far so good, I'm able to
add the Captcha to my login but unable to show errors.
It will error out on me when I enter the wrong password, but if I enter
the right password and do not enter the Captcha I get no errors (which I
should get a Captcha not filled error). So the only time my captcha_errors
function fires is when user name / password is wrong.
How do I get my login form to check the ReCaptcha before checking the
login credentials?
do_action('login_head');
// this function adds captcha to the login form
function addCaptcha() {
if( session_id() == "" )
@session_start();
if (isset( $_SESSION["recaptcha_response_field"] ))
unset( $_SESSION["recaptcha_response_field"] );
?>
<p class="cptch_block">
<div id="cap"></div>
<script type='text/javascript'
src='http://www.google.com/recaptcha/api/js/recaptcha_ajax.js'></script>
<script type='text/javascript'>
Recaptcha.create("pubk", "cap", {theme:"clean", callback:
Recaptcha.focus_response_field});
</script>
<noscript>
<iframe
src='http://www.google.com/recaptcha/api/noscript?k=pubk'
height='300' width='500'></iframe>
<br />
<textarea name='recaptcha_challenge_field' rows='3'
cols='40'></textarea>
<input type='hidden' value='manual_challenge'
name='recaptcha_response_field'/>
</noscript>
</p>
<br />
<?php
return true;
}
function verifyCaptcha($pageid) {
$result = false;
if( session_id() == "" )
@session_start();
$pvk = 'prvk';
if (!empty($pvk) && isset($_POST['recaptcha_response_field'])) {
if(!function_exists('recaptcha_check_answer')) {
require_once 'recaptchalib.php';
}
$resp = recaptcha_check_answer($pvk, $_SERVER['REMOTE_ADDR'],
$_POST['recaptcha_challenge_field'],
$_POST['recaptcha_response_field']);
$result = $resp->is_valid;
}
if(!$result)
return $_SERVER["REQUEST_URI"];
else
return admin_url();
}
// this function checks captcha posted with a login
function captcha_errors( $errors ) {
if ( isset( $_SESSION['cptch_error'] ) )
unset( $_SESSION['cptch_error'] );
// return $errros.'<strong>TEST</strong>';
if ("" == $_REQUEST['recaptcha_response_field'] ) {
return $errors.'<strong>'. __( 'ERROR', 'captcha' ) .'</strong>:
'. __( 'Please fill out The Cpatcha.', 'captcha' );
}
if ( isset( $_REQUEST['recaptcha_response_field'] ) && verifyCaptcha()) {
// captcha was matched
} else {
return $errors.'<strong>'. __( 'ERROR', 'captcha' ) .'</strong>:
'. __( 'Please enter a valid CAPTCHA value.', 'captcha' );
}
return( $errors );
}
add_action( 'login_form', 'addCaptcha' );
add_filter( 'login_redirect', 'verifyCaptcha', 10, 3 );
add_filter( 'login_errors', captcha_errors);
I'm trying to add ReCaptcha to my login page. I know there are many many
plugins by per request I cannot use plugins. So far so good, I'm able to
add the Captcha to my login but unable to show errors.
It will error out on me when I enter the wrong password, but if I enter
the right password and do not enter the Captcha I get no errors (which I
should get a Captcha not filled error). So the only time my captcha_errors
function fires is when user name / password is wrong.
How do I get my login form to check the ReCaptcha before checking the
login credentials?
do_action('login_head');
// this function adds captcha to the login form
function addCaptcha() {
if( session_id() == "" )
@session_start();
if (isset( $_SESSION["recaptcha_response_field"] ))
unset( $_SESSION["recaptcha_response_field"] );
?>
<p class="cptch_block">
<div id="cap"></div>
<script type='text/javascript'
src='http://www.google.com/recaptcha/api/js/recaptcha_ajax.js'></script>
<script type='text/javascript'>
Recaptcha.create("pubk", "cap", {theme:"clean", callback:
Recaptcha.focus_response_field});
</script>
<noscript>
<iframe
src='http://www.google.com/recaptcha/api/noscript?k=pubk'
height='300' width='500'></iframe>
<br />
<textarea name='recaptcha_challenge_field' rows='3'
cols='40'></textarea>
<input type='hidden' value='manual_challenge'
name='recaptcha_response_field'/>
</noscript>
</p>
<br />
<?php
return true;
}
function verifyCaptcha($pageid) {
$result = false;
if( session_id() == "" )
@session_start();
$pvk = 'prvk';
if (!empty($pvk) && isset($_POST['recaptcha_response_field'])) {
if(!function_exists('recaptcha_check_answer')) {
require_once 'recaptchalib.php';
}
$resp = recaptcha_check_answer($pvk, $_SERVER['REMOTE_ADDR'],
$_POST['recaptcha_challenge_field'],
$_POST['recaptcha_response_field']);
$result = $resp->is_valid;
}
if(!$result)
return $_SERVER["REQUEST_URI"];
else
return admin_url();
}
// this function checks captcha posted with a login
function captcha_errors( $errors ) {
if ( isset( $_SESSION['cptch_error'] ) )
unset( $_SESSION['cptch_error'] );
// return $errros.'<strong>TEST</strong>';
if ("" == $_REQUEST['recaptcha_response_field'] ) {
return $errors.'<strong>'. __( 'ERROR', 'captcha' ) .'</strong>:
'. __( 'Please fill out The Cpatcha.', 'captcha' );
}
if ( isset( $_REQUEST['recaptcha_response_field'] ) && verifyCaptcha()) {
// captcha was matched
} else {
return $errors.'<strong>'. __( 'ERROR', 'captcha' ) .'</strong>:
'. __( 'Please enter a valid CAPTCHA value.', 'captcha' );
}
return( $errors );
}
add_action( 'login_form', 'addCaptcha' );
add_filter( 'login_redirect', 'verifyCaptcha', 10, 3 );
add_filter( 'login_errors', captcha_errors);
So what are logical cpu cores (as opposed to physical cpu cores)?
So what are logical cpu cores (as opposed to physical cpu cores)?
I was googling about how I could find the number of CPUs in a machine and
I found some posts but I am confused as some mentioned that you get the
logical cores vs physical cores etc.
So what is the difference between logical and physical cores and is there
a way I could get the physical cores only? Or does it make sense to
include logical cores in our count?
I was googling about how I could find the number of CPUs in a machine and
I found some posts but I am confused as some mentioned that you get the
logical cores vs physical cores etc.
So what is the difference between logical and physical cores and is there
a way I could get the physical cores only? Or does it make sense to
include logical cores in our count?
Getting command line parameters from an assembly program
Getting command line parameters from an assembly program
Reading through the "Professional Assembly Language Book"; it seems that
it provides an erroneous code for reading command-line arguments. I
corrected it a bit and now it went from segfaulting to reading argument
count then segfaulting.
Here's the full code:
.data
output1:
.asciz "There are %d params:\n"
output2:
.asciz "%s\n"
.text
.globl main
main:
movl 4(%esp), %ecx /* Get argument count. */
pushl %ecx
pushl $output1
call printf
addl $4, %esp /* remove output1 */
/* ECX was corrupted by the printf call,
pop it off the stack so that we get it's original
value. */
popl %ecx
/* We don't want to corrupt the stack pointer
as we move ebp to point to the next command-line
argument. */
movl %esp, %ebp
/* Remove argument count from EBP. */
addl $4, %ebp
pr_arg:
pushl (%ebp)
pushl $output2
call printf
addl $8, %esp /* remove output2 and current argument. */
addl $4, %ebp /* Jump to next argument. */
loop pr_arg
/* Done. */
pushl $0
call exit
Code from the book:
.section .data
output1:
.asciz "There are %d parameters:\n"
output2:
.asciz "%s\n"
.section .text
.globl _start
_start:
movl (%esp), %ecx
pushl %ecx
pushl $output1
call printf
addl $4, %esp
popl %ecx
movl %esp, %ebp
addl $4, %ebp
loop1:
pushl %ecx
pushl (%ebp)
pushl $output2
call printf
addl $8, %esp
popl %ecx
addl $4, %ebp
loop loop1
pushl $0
call exit
Compiled it with GCC (gcc cmd.S), maybe that's the problem?
__libc_start_main modifies the stack in some way? Not quite sure...
Even worse, trying to debug it to look at the stack but GDB seems to throw
a lot of printf-related stuff (one of them was printf.c: File not found or
something similar).
Reading through the "Professional Assembly Language Book"; it seems that
it provides an erroneous code for reading command-line arguments. I
corrected it a bit and now it went from segfaulting to reading argument
count then segfaulting.
Here's the full code:
.data
output1:
.asciz "There are %d params:\n"
output2:
.asciz "%s\n"
.text
.globl main
main:
movl 4(%esp), %ecx /* Get argument count. */
pushl %ecx
pushl $output1
call printf
addl $4, %esp /* remove output1 */
/* ECX was corrupted by the printf call,
pop it off the stack so that we get it's original
value. */
popl %ecx
/* We don't want to corrupt the stack pointer
as we move ebp to point to the next command-line
argument. */
movl %esp, %ebp
/* Remove argument count from EBP. */
addl $4, %ebp
pr_arg:
pushl (%ebp)
pushl $output2
call printf
addl $8, %esp /* remove output2 and current argument. */
addl $4, %ebp /* Jump to next argument. */
loop pr_arg
/* Done. */
pushl $0
call exit
Code from the book:
.section .data
output1:
.asciz "There are %d parameters:\n"
output2:
.asciz "%s\n"
.section .text
.globl _start
_start:
movl (%esp), %ecx
pushl %ecx
pushl $output1
call printf
addl $4, %esp
popl %ecx
movl %esp, %ebp
addl $4, %ebp
loop1:
pushl %ecx
pushl (%ebp)
pushl $output2
call printf
addl $8, %esp
popl %ecx
addl $4, %ebp
loop loop1
pushl $0
call exit
Compiled it with GCC (gcc cmd.S), maybe that's the problem?
__libc_start_main modifies the stack in some way? Not quite sure...
Even worse, trying to debug it to look at the stack but GDB seems to throw
a lot of printf-related stuff (one of them was printf.c: File not found or
something similar).
SQL Statement for more than one type of code in the same column
SQL Statement for more than one type of code in the same column
I have a basic query where I am selecting from one table and joining to
another table. On the second table I am using a filter on a column to
exclude records I don't want.
The first table is basic, things like name, ID, address, etc. It contains
no duplicates. The second table (product table) is more like this:
ID Code DESC Date
-----------------------------------------
1234 PG Global 082613
1235 PG National 082613
1236 PS Serv1 082613
1237 PS Serv2 082613
1238 PS Serv3 082613
And my select looks something like this:
Select A.*, B.DESC
from CustTable A
INNER JOIN Prod_Table B
ON A.ID = B.ID
WHERE B.Code = 'PG'
I also have a need to get the records from the Prod_Table where Code = 'PS'.
Is there a way to do this in one query or do I need to make another table
with the 'PS' records and query that?
I have a basic query where I am selecting from one table and joining to
another table. On the second table I am using a filter on a column to
exclude records I don't want.
The first table is basic, things like name, ID, address, etc. It contains
no duplicates. The second table (product table) is more like this:
ID Code DESC Date
-----------------------------------------
1234 PG Global 082613
1235 PG National 082613
1236 PS Serv1 082613
1237 PS Serv2 082613
1238 PS Serv3 082613
And my select looks something like this:
Select A.*, B.DESC
from CustTable A
INNER JOIN Prod_Table B
ON A.ID = B.ID
WHERE B.Code = 'PG'
I also have a need to get the records from the Prod_Table where Code = 'PS'.
Is there a way to do this in one query or do I need to make another table
with the 'PS' records and query that?
Change LogOn properties of a SQL server instance
Change LogOn properties of a SQL server instance
I want to change the logon properties of a sql server 2008 r2 instance by
using code. Manually i can do it in SQL server configuration manager by
right clicking on instance name->Log On. Under Built-in account change
Network service to Local service. Then click on apply. SQL instance will
be restarted to effect the changes.
Now hoe can i do the same(Network service to Local service) using code .I
think it can be done using WMI. So please help me on this.
I want to change the logon properties of a sql server 2008 r2 instance by
using code. Manually i can do it in SQL server configuration manager by
right clicking on instance name->Log On. Under Built-in account change
Network service to Local service. Then click on apply. SQL instance will
be restarted to effect the changes.
Now hoe can i do the same(Network service to Local service) using code .I
think it can be done using WMI. So please help me on this.
Cakephp input prompt text
Cakephp input prompt text
I have the following input field in a form:
echo $this->Form->input('website_name');
Now i want it to display a prompt text that when the user starts to type
disapears
i have tried the following:
echo $this->Form->input('website_name'),array('namespace'=>'Hello world');
echo $this->Form->input('website_name'),array('title'=>'Hello world');
echo $this->Form->input('website_name'),array('placeholder' =>'Hello
world');
but with no luck. Does anyone know how to get a prompt text on these text
fields?
I have the following input field in a form:
echo $this->Form->input('website_name');
Now i want it to display a prompt text that when the user starts to type
disapears
i have tried the following:
echo $this->Form->input('website_name'),array('namespace'=>'Hello world');
echo $this->Form->input('website_name'),array('title'=>'Hello world');
echo $this->Form->input('website_name'),array('placeholder' =>'Hello
world');
but with no luck. Does anyone know how to get a prompt text on these text
fields?
jQuery "Like" with id in HTML as identifier
jQuery "Like" with id in HTML as identifier
I am working on a project, where it's possible for users to like each
others stuff. Right now my jQuery gets the id from the HTML, to identify
what thing to like. But people are able to open an Inspector in the
browser, and edit the id, and that way like a whole other thing.
I am searching for alternative ways to do this.
I've thought of making a unique string, but that's kinda the same, since
they still would be able to copy/paste the string to another element.
Thanks in advance.
I am working on a project, where it's possible for users to like each
others stuff. Right now my jQuery gets the id from the HTML, to identify
what thing to like. But people are able to open an Inspector in the
browser, and edit the id, and that way like a whole other thing.
I am searching for alternative ways to do this.
I've thought of making a unique string, but that's kinda the same, since
they still would be able to copy/paste the string to another element.
Thanks in advance.
Sunday, 25 August 2013
Using TC to throttle client's internet bandwidth not lan bandwidth.
Using TC to throttle client's internet bandwidth not lan bandwidth.
I want to throttle traffic in my network using tc. What I found if 'wlan0'
is from where my internet comes in to my Linux machine and 'eth0' to my
internal network.
I've so far found solution for limiting traffic for controlling my
connection with internal network. Like, applying rule in 'eth0' for
controlling internal network.(using this article
http://atmail.com/kb/2009/throttling-bandwidth/)
But what I need to do is to control over 'internal network going to
wlan0(internet)' so that Server (my computer) can communicate with client
in lan speed and clients can get the bandwidth they need. How to
accomplish this using tc ??
I want to throttle traffic in my network using tc. What I found if 'wlan0'
is from where my internet comes in to my Linux machine and 'eth0' to my
internal network.
I've so far found solution for limiting traffic for controlling my
connection with internal network. Like, applying rule in 'eth0' for
controlling internal network.(using this article
http://atmail.com/kb/2009/throttling-bandwidth/)
But what I need to do is to control over 'internal network going to
wlan0(internet)' so that Server (my computer) can communicate with client
in lan speed and clients can get the bandwidth they need. How to
accomplish this using tc ??
Database Structure involving dynamic fields
Database Structure involving dynamic fields
Im working on a project. Its mostly for learning purposes, i find actually
trying a complicated project is the best way to learn a language after
grasping the basics. Database design is not a strong point, i started
reading up on it but its early days and im still learning.
Here is my alpha schema, im really at the point where im just trying to
jot down everything i can think of and seeing if any issues jump out.
http://diagrams.seaquail.net/Diagram.aspx?ID=10094#
Some of my concerns i would like feedback on:
Notice for the core attributes like area for example, lets say for
simplicity the areas are kitchen,bedroom,garden,bathroom and living room.
For another customer that might be homepage,contact page,about_us,splash
screen. It could be 2 areas and it could be 100, there isn't a need to
limit it.
I created separate tables for the defaults and each is linked to a bug.
Later i came to the problem of custom fields, if someone wants for example
to mark which theme the bug applies to we dont have that, there is
probably a 100 other things so i wanted to stick to a core set of
attributes and the custom fields give people flexibility.
However when i got to the custom fields i knew i had an issue, i cant be
creating a table for every custom field so i instead used 2 tables. custom
fields and custom_field_values. The idea is every field including defaults
would be stored in this table and each would be linked to the values table
which would just have something like this
custom_fields table
id project_id name
01 1 area(default)
12 2 rooms(custom)
13 4 website(custom)
custom_field_values table
id area project_id sort_number
667 area1 1 1
668 area2 1 2
669 area3 1 3
670 area4 1 4
671 bedroom 2 1
672 bathroom 2 2
673 garden 2 3
674 livingroom 2 4
675 homepage 4 1
676 about_us 4 2
677 contact 4 3
678 splash page 4 4
Does this look like an efficient way to handle dynamic fields like this or
is there other alternatives?
The defaults would be hard coded so you can either use them or replace
with your own or i could create a another table to allow users to edit the
name of the defaults which would be linked to their project. Any feedback
is welcome and if there something very obvious with issues in the scheme
please feel free to critique.
Im working on a project. Its mostly for learning purposes, i find actually
trying a complicated project is the best way to learn a language after
grasping the basics. Database design is not a strong point, i started
reading up on it but its early days and im still learning.
Here is my alpha schema, im really at the point where im just trying to
jot down everything i can think of and seeing if any issues jump out.
http://diagrams.seaquail.net/Diagram.aspx?ID=10094#
Some of my concerns i would like feedback on:
Notice for the core attributes like area for example, lets say for
simplicity the areas are kitchen,bedroom,garden,bathroom and living room.
For another customer that might be homepage,contact page,about_us,splash
screen. It could be 2 areas and it could be 100, there isn't a need to
limit it.
I created separate tables for the defaults and each is linked to a bug.
Later i came to the problem of custom fields, if someone wants for example
to mark which theme the bug applies to we dont have that, there is
probably a 100 other things so i wanted to stick to a core set of
attributes and the custom fields give people flexibility.
However when i got to the custom fields i knew i had an issue, i cant be
creating a table for every custom field so i instead used 2 tables. custom
fields and custom_field_values. The idea is every field including defaults
would be stored in this table and each would be linked to the values table
which would just have something like this
custom_fields table
id project_id name
01 1 area(default)
12 2 rooms(custom)
13 4 website(custom)
custom_field_values table
id area project_id sort_number
667 area1 1 1
668 area2 1 2
669 area3 1 3
670 area4 1 4
671 bedroom 2 1
672 bathroom 2 2
673 garden 2 3
674 livingroom 2 4
675 homepage 4 1
676 about_us 4 2
677 contact 4 3
678 splash page 4 4
Does this look like an efficient way to handle dynamic fields like this or
is there other alternatives?
The defaults would be hard coded so you can either use them or replace
with your own or i could create a another table to allow users to edit the
name of the defaults which would be linked to their project. Any feedback
is welcome and if there something very obvious with issues in the scheme
please feel free to critique.
g3d.utils not (anymore) available?
g3d.utils not (anymore) available?
Last week i tried to start coding with the libgdx library. As i would like
to try it's 3d context i rode the tutorial of Xoppa:
http://blog.xoppa.com/basic-3d-using-libgdx-2/
Well, i understood his examples and started to code in eclipse. But as
soon as i got to the modelbuilder usage i stuck:
@Override
public void create() {
...
ModelBuilder modelBuilder = new ModelBuilder();
...
}
i imported a few other classes without problems, but i didn't find
...g3d.utils.modelbuilder
I googled and took a look at their github, where the package g3d.utils.
exists. And now, i don't know anymore. i'm using the latest stable build
0.9.8
I hope you can help me. Thanks for your time!
Last week i tried to start coding with the libgdx library. As i would like
to try it's 3d context i rode the tutorial of Xoppa:
http://blog.xoppa.com/basic-3d-using-libgdx-2/
Well, i understood his examples and started to code in eclipse. But as
soon as i got to the modelbuilder usage i stuck:
@Override
public void create() {
...
ModelBuilder modelBuilder = new ModelBuilder();
...
}
i imported a few other classes without problems, but i didn't find
...g3d.utils.modelbuilder
I googled and took a look at their github, where the package g3d.utils.
exists. And now, i don't know anymore. i'm using the latest stable build
0.9.8
I hope you can help me. Thanks for your time!
error: @tailrec annotated method contains no recursive calls
error: @tailrec annotated method contains no recursive calls
When running this piece of code:
object P01 {
@annotation.tailrec
final def lastRecursive[A] (ls:List[A]):A = {
def lr[A] (l:List[A]):A = l match {
case h :: Nil => h
case _ :: tail => lr(tail)
case _ => throw new NoSuchElementException
}
lr(ls)
}
}
P01.lastRecursive(List(1,2,3))
,in scala 2.10.2 REPL, I get the following error:
scala> :9: error: @tailrec annotated method contains no recursive calls
final def lastRecursive[A] (ls:List[A]):A = {
^
Please help, I don't understand what am I doing wrong.
When running this piece of code:
object P01 {
@annotation.tailrec
final def lastRecursive[A] (ls:List[A]):A = {
def lr[A] (l:List[A]):A = l match {
case h :: Nil => h
case _ :: tail => lr(tail)
case _ => throw new NoSuchElementException
}
lr(ls)
}
}
P01.lastRecursive(List(1,2,3))
,in scala 2.10.2 REPL, I get the following error:
scala> :9: error: @tailrec annotated method contains no recursive calls
final def lastRecursive[A] (ls:List[A]):A = {
^
Please help, I don't understand what am I doing wrong.
Confusing OPT Page Replacement
Confusing OPT Page Replacement
This is from my paper:
A cache is a high speed memory that aims to minimize the access to the
low-speed memory. An effective cache can help to improve the performance
of your computer. In this project, we study a simplified version of memory
cache.
Processor -- Cache -- Memory
Assume that your computer has a cache memory of size S. Assume that your
memory has a set of entries 1, ..., n. When you use your computer, a list
of entry accesses is generated one by one. At any particular time, suppose
you need to access entry f. The computer first checks if it is in the
cache. If yes, we can access the entry f from cache. Otherwise, there is a
cache miss and you will need to request the entry f from the memory. Then,
you can decide if you want to replace one entry in the cache by f. Our aim
is to minimize the number of cache miss.
OPT: This strategy replaces the entry that minimizes the number of cache
miss.
Given the input reference string: 1 2 3 1 4 1 2 3, this is what I work out
http://i.imgur.com/dk0xg9q.jpg The cache miss/page fault is 5
However the answer given was 4 http://i.imgur.com/UtK8eaI.jpg It
apparently shows that the entry "4" was not put into the cache but still
counted as cache miss.
Also, with another example 4 7 1 3 3 2 1 6 2 1 6 2 1 5 1 8 8 8 3 1 7 6 5 1
5 4 1, using the same method, I got the cache miss of 24 but the answer
given was 19.
I do not understand why. I thought Optimal strategy was to replace the
frame page that will not be used for the longest period of time. I hope
someone could explain in detail why.
This is from my paper:
A cache is a high speed memory that aims to minimize the access to the
low-speed memory. An effective cache can help to improve the performance
of your computer. In this project, we study a simplified version of memory
cache.
Processor -- Cache -- Memory
Assume that your computer has a cache memory of size S. Assume that your
memory has a set of entries 1, ..., n. When you use your computer, a list
of entry accesses is generated one by one. At any particular time, suppose
you need to access entry f. The computer first checks if it is in the
cache. If yes, we can access the entry f from cache. Otherwise, there is a
cache miss and you will need to request the entry f from the memory. Then,
you can decide if you want to replace one entry in the cache by f. Our aim
is to minimize the number of cache miss.
OPT: This strategy replaces the entry that minimizes the number of cache
miss.
Given the input reference string: 1 2 3 1 4 1 2 3, this is what I work out
http://i.imgur.com/dk0xg9q.jpg The cache miss/page fault is 5
However the answer given was 4 http://i.imgur.com/UtK8eaI.jpg It
apparently shows that the entry "4" was not put into the cache but still
counted as cache miss.
Also, with another example 4 7 1 3 3 2 1 6 2 1 6 2 1 5 1 8 8 8 3 1 7 6 5 1
5 4 1, using the same method, I got the cache miss of 24 but the answer
given was 19.
I do not understand why. I thought Optimal strategy was to replace the
frame page that will not be used for the longest period of time. I hope
someone could explain in detail why.
Saturday, 24 August 2013
How to refresh the page with an audio tag based on browser after click of hyperlink
How to refresh the page with an audio tag based on browser after click of
hyperlink
I have a requirement where one can see an image or play an audio
(CAPTCHA).I added the div tag around the image and audio and with click of
hyperlink they do change the display of the div but the changes (div) get
lost when page gets redisplayed.
Technology used: Java, JSP, javascript
There is a
section in the jsp which needs to
a) display an image(default) or
b) play an audio when requested
The "src" for both image and audio is a servlet.
<tr>
<td> </td>
<td> <div id="audioPlayerContainer" style="display:none"> </div>
</td>
</tr>
<tr>
<td> </td>
<td><div id="imageContainer">
<img src='MyServlet?mode=image&ts=<%=Math.random()%>' width="100"
height="100"/>
</div>
</td>
</tr>
section in the jsp where links to alternate between requesting image or
audio are present
<a href="#" onclick="switchMode('audio');">Play audio</a> // OR
<a href="#" onclick="switchMode('image');> Show image</a>
javascript on click of link
function switchMode(modeType){
if (modeType=="audio"){
var uri = '/MyServlet?mode=audio&ts='+new Date().getTime();
document.getElementById('audioPlayerContainer').style.display ="block";
document.getElementById('imageContainer').style.display ="none";
//logic to determine the browser type and browser verion- embed tag
or audio
document.getElementById("audioPlayerContainer").innerHTML=
"<embed src='"+uri+"' autostart='true' loop='false' height='100'
width='100'/>";
}else if (modeType=="image"){
document.getElementById("audioPlayerContainer").style.display = "none";
document.getElementById('imageContainer').style.display ="block";
}
//page to reload with updated divs
//window.location.href=window.location.href;
//window.location.reload(0); //Both reloads page, state of div tags comes
bck to default
//document.forms[0].submit();//this doesnt even seem to work
}
`
The issue is dom injection is not working. On initial page load the image
gets displayed fine. However, once the "play audio" is clicked, the js
gets executed. But I dont see any audio player and on right clicking and
checking the "View source" the audioplayercontainer is still with
display:none . Thats the reason I tried adding reload/submit thinking that
maybe if page refreshes then it will load with updated divs.
hyperlink
I have a requirement where one can see an image or play an audio
(CAPTCHA).I added the div tag around the image and audio and with click of
hyperlink they do change the display of the div but the changes (div) get
lost when page gets redisplayed.
Technology used: Java, JSP, javascript
There is a
section in the jsp which needs to
a) display an image(default) or
b) play an audio when requested
The "src" for both image and audio is a servlet.
<tr>
<td> </td>
<td> <div id="audioPlayerContainer" style="display:none"> </div>
</td>
</tr>
<tr>
<td> </td>
<td><div id="imageContainer">
<img src='MyServlet?mode=image&ts=<%=Math.random()%>' width="100"
height="100"/>
</div>
</td>
</tr>
section in the jsp where links to alternate between requesting image or
audio are present
<a href="#" onclick="switchMode('audio');">Play audio</a> // OR
<a href="#" onclick="switchMode('image');> Show image</a>
javascript on click of link
function switchMode(modeType){
if (modeType=="audio"){
var uri = '/MyServlet?mode=audio&ts='+new Date().getTime();
document.getElementById('audioPlayerContainer').style.display ="block";
document.getElementById('imageContainer').style.display ="none";
//logic to determine the browser type and browser verion- embed tag
or audio
document.getElementById("audioPlayerContainer").innerHTML=
"<embed src='"+uri+"' autostart='true' loop='false' height='100'
width='100'/>";
}else if (modeType=="image"){
document.getElementById("audioPlayerContainer").style.display = "none";
document.getElementById('imageContainer').style.display ="block";
}
//page to reload with updated divs
//window.location.href=window.location.href;
//window.location.reload(0); //Both reloads page, state of div tags comes
bck to default
//document.forms[0].submit();//this doesnt even seem to work
}
`
The issue is dom injection is not working. On initial page load the image
gets displayed fine. However, once the "play audio" is clicked, the js
gets executed. But I dont see any audio player and on right clicking and
checking the "View source" the audioplayercontainer is still with
display:none . Thats the reason I tried adding reload/submit thinking that
maybe if page refreshes then it will load with updated divs.
how to overidden drag and drop on columns in jtable
how to overidden drag and drop on columns in jtable
The default behavior of drag and drop on JTable columns is to reorder the
columns. I'd like to change the behavior to copy the source column to the
dropped column. I appreciate any suggestion on how to do this. Thanks.
The default behavior of drag and drop on JTable columns is to reorder the
columns. I'd like to change the behavior to copy the source column to the
dropped column. I appreciate any suggestion on how to do this. Thanks.
How to retrieve the facebook status of the person by using the access token on a localhost or ubuntu terminal?
How to retrieve the facebook status of the person by using the access
token on a localhost or ubuntu terminal?
I want to use either the localhost installe on my pc [xampp] or the ubuntu
terminal to access the person's facebook status but I cannot figure out
the API's I should use for this.
token on a localhost or ubuntu terminal?
I want to use either the localhost installe on my pc [xampp] or the ubuntu
terminal to access the person's facebook status but I cannot figure out
the API's I should use for this.
Creationg Tree Using D3js in MVC4
Creationg Tree Using D3js in MVC4
I am making a project where user can register and can follow other user in
the website so i want to use the layout of tree to show his friends like
he will in the parent node and other friend as children node and all
http://mbostock.github.io/d3/talk/20111018/tree.html
this link is the layout of the tree which i want to implement of d3js.In
this example they are fetching the data of children and root from the
json.js file.
so my question how i will get the parent and childred node from database
in mvc4
I am making a project where user can register and can follow other user in
the website so i want to use the layout of tree to show his friends like
he will in the parent node and other friend as children node and all
http://mbostock.github.io/d3/talk/20111018/tree.html
this link is the layout of the tree which i want to implement of d3js.In
this example they are fetching the data of children and root from the
json.js file.
so my question how i will get the parent and childred node from database
in mvc4
chrome extension file input in popup
chrome extension file input in popup
I am still new to how chrome extensions work and i found out that its not
possible to have file input in the popup dialog due to the fact that the
moment I take the focus off popup the popup window will close. So, I am
thinking how to deal with this problem. I have two solutions that I am
considering:
open a new tab and run the file dialog from there
add the file input to the context of the current page
They both do the exact same thing but which one would be more reliable. I
am guessing the first one but I would want to hear experiences of others.
Also, I have been thinking couple steps ahead and I see that there won't
be any way to access the popup wherever I open it, so how am i suppose to
handle that kind of a situation?
Thanks, Gasim
I am still new to how chrome extensions work and i found out that its not
possible to have file input in the popup dialog due to the fact that the
moment I take the focus off popup the popup window will close. So, I am
thinking how to deal with this problem. I have two solutions that I am
considering:
open a new tab and run the file dialog from there
add the file input to the context of the current page
They both do the exact same thing but which one would be more reliable. I
am guessing the first one but I would want to hear experiences of others.
Also, I have been thinking couple steps ahead and I see that there won't
be any way to access the popup wherever I open it, so how am i suppose to
handle that kind of a situation?
Thanks, Gasim
SSH issue with DISPLAY Variable
SSH issue with DISPLAY Variable
When I am exporting DISPLAY Variable in my shell script. I am getting the
following error while executing shell commands.
# ssh myuser@myhost
Warning: untrusted X11 forwarding setup failed: xauth key data not generated
Warning: No xauth data; using fake authentication data for X11 forwarding.
I changed the following lines in /etc/ssh/sshd_config
X11Forwarding yes
X11UseLocalhost no
But still I am getting that error.
I cannot nullify these errors but I am looking for anything can be done
from ssh config.
When I am exporting DISPLAY Variable in my shell script. I am getting the
following error while executing shell commands.
# ssh myuser@myhost
Warning: untrusted X11 forwarding setup failed: xauth key data not generated
Warning: No xauth data; using fake authentication data for X11 forwarding.
I changed the following lines in /etc/ssh/sshd_config
X11Forwarding yes
X11UseLocalhost no
But still I am getting that error.
I cannot nullify these errors but I am looking for anything can be done
from ssh config.
Display a progress inside a download button on iOS
Display a progress inside a download button on iOS
In my iPhone application I have a button that is responsible for
downloading some file. How can I display a progress bar inside that button
when downloading? I want this button to look like it being filled
gradually as the download progresses.
In my iPhone application I have a button that is responsible for
downloading some file. How can I display a progress bar inside that button
when downloading? I want this button to look like it being filled
gradually as the download progresses.
css: why texts will move up after remove position:absolute
css: why texts will move up after remove position:absolute
<!DOCTYPE html>
<html>
<head>
<style>
h2
{
position:absolute;
}
</style>
</head>
<body>
<h2>This is a heading with an absolute position</h2>
</body>
</html>
Question:
If I remove this line: position:absolute;, the texts in <h2>...</h2> will
move up, why?
<!DOCTYPE html>
<html>
<head>
<style>
h2
{
position:absolute;
}
</style>
</head>
<body>
<h2>This is a heading with an absolute position</h2>
</body>
</html>
Question:
If I remove this line: position:absolute;, the texts in <h2>...</h2> will
move up, why?
Friday, 23 August 2013
pdo search apply and condition
pdo search apply and condition
function getRowFromMatchingValue($table, $field, $val){$suggestedRows =
array();$stH = $this->dbH->prepare("SELECT * FROM $table WHERE $field LIKE
:val");$stH->setFetchMode(PDO::FETCH_OBJ); $stH->bindValue(':val',
'%'.$val.'%', PDO::PARAM_STR);$stH->execute();while($sRow = $stH->fetch())
$suggestedRows[] = $sRow;return $suggestedRows;}I want to apply and
condition $field!=$val how I can do this?
function getRowFromMatchingValue($table, $field, $val){$suggestedRows =
array();$stH = $this->dbH->prepare("SELECT * FROM $table WHERE $field LIKE
:val");$stH->setFetchMode(PDO::FETCH_OBJ); $stH->bindValue(':val',
'%'.$val.'%', PDO::PARAM_STR);$stH->execute();while($sRow = $stH->fetch())
$suggestedRows[] = $sRow;return $suggestedRows;}I want to apply and
condition $field!=$val how I can do this?
Can I specify to vundle where git is
Can I specify to vundle where git is
I have installed git on windows (msysgit) but I have no admin rights so
git location is not in my PATH, can I specify to vundle where my git.exe
is ?
I have installed git on windows (msysgit) but I have no admin rights so
git location is not in my PATH, can I specify to vundle where my git.exe
is ?
Trouble getting time out of TimePicker
Trouble getting time out of TimePicker
I am trying to get the set time form a time picker from for some reason ,
it is not happening.
I am using getCurrentHour and getCurrentMinute() but they don't seem to be
doing the job.I have tried to clearFocus() but that did not make a
difference.
I am trying to get the time on a button click. I have attached the
relevant code below , let me know if you need to see anymore.
Button next_button = (Button) findViewById(R.id.next_button);
next_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Calendar current = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
//time_picker = (TimePicker) findViewById(R.id.time);
// time_picker.clearFocus(); // this did not help
cal.set(
time_picker.getCurrentHour(),
time_picker.getCurrentMinute(),
00);
Toast.makeText(getApplicationContext(),
"set time: "+cal.getTime(),
Toast.LENGTH_LONG).show(); // this is returning the
current time
// that gets initialised
with
setAlarm(cal);
}
});
my question is : how do i get the the time form the TImePicker?
Thanks for taking the time to read this and for any help that you can give.
I am trying to get the set time form a time picker from for some reason ,
it is not happening.
I am using getCurrentHour and getCurrentMinute() but they don't seem to be
doing the job.I have tried to clearFocus() but that did not make a
difference.
I am trying to get the time on a button click. I have attached the
relevant code below , let me know if you need to see anymore.
Button next_button = (Button) findViewById(R.id.next_button);
next_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Calendar current = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
//time_picker = (TimePicker) findViewById(R.id.time);
// time_picker.clearFocus(); // this did not help
cal.set(
time_picker.getCurrentHour(),
time_picker.getCurrentMinute(),
00);
Toast.makeText(getApplicationContext(),
"set time: "+cal.getTime(),
Toast.LENGTH_LONG).show(); // this is returning the
current time
// that gets initialised
with
setAlarm(cal);
}
});
my question is : how do i get the the time form the TImePicker?
Thanks for taking the time to read this and for any help that you can give.
Integration aproximation
Integration aproximation
For $f(x)=e^x$ we have:
$F(x)=\int f(x) dx=e^x$
For $x_1=2 \text{ and } x_2=3$, we can compute:
$S_1=F(x_1) \text{ and } S_2=F(x_1)+F(x_2)$
In Mathematica we have function NIntegrate for numerical integration. For
$g(x)=e^{x^2}$ how compute $S_3=G(x_1) \text{ and } S_4=G(x_1)+G(x_2)$
using NIntegrate function?
For $f(x)=e^x$ we have:
$F(x)=\int f(x) dx=e^x$
For $x_1=2 \text{ and } x_2=3$, we can compute:
$S_1=F(x_1) \text{ and } S_2=F(x_1)+F(x_2)$
In Mathematica we have function NIntegrate for numerical integration. For
$g(x)=e^{x^2}$ how compute $S_3=G(x_1) \text{ and } S_4=G(x_1)+G(x_2)$
using NIntegrate function?
Need the last entry while using XSUM in SYNCSORT JCL
Need the last entry while using XSUM in SYNCSORT JCL
I have some data like below:
This is not the actual data, but actual data is similar to this.
Name Number code
+++++++++++++++
Albert 122234 xcc
Robert 565435 rtd
Robert 776567 iuy
Robert 452890 yyt
Stuart 776565 ter
I need to eliminate the duplicates using SYNCSORT. Now I can do this using
XSUM, but I would get the following data:
Name Number code
+++++++++++++++
Albert 122234 xcc
Robert 565435 rtd
Stuart 776565 ter
But I need:
Name Number code
+++++++++++++++
Albert 122234 xcc
Robert 452890 yyt
Stuart 776565 ter
The last set of data has the last occurance of 'Robert' in the output,
while the former set has the first occurance.
So, is there any way to achieve this using XSUM...?
I have some data like below:
This is not the actual data, but actual data is similar to this.
Name Number code
+++++++++++++++
Albert 122234 xcc
Robert 565435 rtd
Robert 776567 iuy
Robert 452890 yyt
Stuart 776565 ter
I need to eliminate the duplicates using SYNCSORT. Now I can do this using
XSUM, but I would get the following data:
Name Number code
+++++++++++++++
Albert 122234 xcc
Robert 565435 rtd
Stuart 776565 ter
But I need:
Name Number code
+++++++++++++++
Albert 122234 xcc
Robert 452890 yyt
Stuart 776565 ter
The last set of data has the last occurance of 'Robert' in the output,
while the former set has the first occurance.
So, is there any way to achieve this using XSUM...?
youtube in the latest firefox doesn't display videos in Linux Mint 15 olivia
youtube in the latest firefox doesn't display videos in Linux Mint 15 olivia
I'm running Linux mint 15 olivia, Xfce 32-bit version. I try to access
youtube videos in the latest Firefox, but the videos displays incorrectly
for some reason. I do have flash installed, but I see there is more than
one flash plugin that can be installed when I go the software manager. I
installed Google Chrome also and there youtube videos displays correctly,
I can watch the videos as normal. Why is this? What can I do to fix
firefox? I can see that I have shockwave player also installed. Please
assist.
I'm running Linux mint 15 olivia, Xfce 32-bit version. I try to access
youtube videos in the latest Firefox, but the videos displays incorrectly
for some reason. I do have flash installed, but I see there is more than
one flash plugin that can be installed when I go the software manager. I
installed Google Chrome also and there youtube videos displays correctly,
I can watch the videos as normal. Why is this? What can I do to fix
firefox? I can see that I have shockwave player also installed. Please
assist.
Thursday, 22 August 2013
Integral of summation of functions
Integral of summation of functions
a=@(x,y) exp(j*x*cos(y-z1)) + exp(j*x*cos(y-z2)) +exp(j*x*cos(y-z3))
b=abs(a)^2
c=integral2(b,0,pi,0,pi)
Above s not a proper coding. I just express the equation. I want to write
a matlab program for above task.Can anybody help me? Thanks in advance.
a=@(x,y) exp(j*x*cos(y-z1)) + exp(j*x*cos(y-z2)) +exp(j*x*cos(y-z3))
b=abs(a)^2
c=integral2(b,0,pi,0,pi)
Above s not a proper coding. I just express the equation. I want to write
a matlab program for above task.Can anybody help me? Thanks in advance.
Initialize a property in Entity Framework that already has a constructor
Initialize a property in Entity Framework that already has a constructor
Is there ANY way to initialize a property in an Entity Framework entity
that has a collection?
This is the generated code for an Entity that has a collection:
public partial class MyEntity
{
public MyEntity()
{
this.MySubEntities = new HashSet<MySubEntity>();
}
public bool IsActive {get; set;}
public virtual ICollection<MySubEntity> MySubEntities {get; set;}
}
If I need to make a new MyEntity that I want to default to IsActive =
true, it cannot be done! (Unless I edit the T4 template.)
Please tell me there is a way to default IsActive = True without editing
the generated file (or the T4).
Is there ANY way to initialize a property in an Entity Framework entity
that has a collection?
This is the generated code for an Entity that has a collection:
public partial class MyEntity
{
public MyEntity()
{
this.MySubEntities = new HashSet<MySubEntity>();
}
public bool IsActive {get; set;}
public virtual ICollection<MySubEntity> MySubEntities {get; set;}
}
If I need to make a new MyEntity that I want to default to IsActive =
true, it cannot be done! (Unless I edit the T4 template.)
Please tell me there is a way to default IsActive = True without editing
the generated file (or the T4).
how to delete duplicate rows in sql server
how to delete duplicate rows in sql server
How can i delete duplicate rows where no unique row id exists?
My table is
col1 col2 col3 col4 col5 col6 col7
john 1 1 1 1 1 1
john 1 1 1 1 1 1
sally 2 2 2 2 2 2
sally 2 2 2 2 2 2
I want to be left with the following after the duplicate removal
john 1 1 1 1 1 1
sally 1 1 1 1 1 1
Ive tried a few queries but i think they depend on a rowId as i dont get
desired result, for example
DELETE FROM table WHERE col1 IN (
SELECT id FROM table GROUP BY id HAVING ( COUNT(col1) > 1 )
)
How can i delete duplicate rows where no unique row id exists?
My table is
col1 col2 col3 col4 col5 col6 col7
john 1 1 1 1 1 1
john 1 1 1 1 1 1
sally 2 2 2 2 2 2
sally 2 2 2 2 2 2
I want to be left with the following after the duplicate removal
john 1 1 1 1 1 1
sally 1 1 1 1 1 1
Ive tried a few queries but i think they depend on a rowId as i dont get
desired result, for example
DELETE FROM table WHERE col1 IN (
SELECT id FROM table GROUP BY id HAVING ( COUNT(col1) > 1 )
)
Jump to arbitrary point on a UIBezierPath
Jump to arbitrary point on a UIBezierPath
I am developing an app that animates a motion on a UIBezierPath (made of
several curves). In some use cases I need to place an item so it will
start moving from some point on the route, and not from its beginning. E.g
put item in the middle or 2/3 point of the path. How can I calculate the
location of such point?
Thanks!
I am developing an app that animates a motion on a UIBezierPath (made of
several curves). In some use cases I need to place an item so it will
start moving from some point on the route, and not from its beginning. E.g
put item in the middle or 2/3 point of the path. How can I calculate the
location of such point?
Thanks!
how to check typing any word in span value
how to check typing any word in span value
hi my friend I want to create search box and I want when anybody typing
any word start searching and console result it.
this is my code:
<input type="text" id="search"> //search input
<ul id="all">
<li><span>Andro</span></li>
<li><span>andre</span></li>
<li><span>Marcos</span></li>
<li><span>mamaaaaa</span></li>
<li><span>louis</span></li>
</ul>
jQuery
var $all = $('#all');
$('#search').on('keyup', function() {
$all.find('li').hide();
//I want check span value with enter any key
//(point: span value should to be lowerCase)
});
please guide me how to lowerCase spans value and check lowerCase typing
any word
hi my friend I want to create search box and I want when anybody typing
any word start searching and console result it.
this is my code:
<input type="text" id="search"> //search input
<ul id="all">
<li><span>Andro</span></li>
<li><span>andre</span></li>
<li><span>Marcos</span></li>
<li><span>mamaaaaa</span></li>
<li><span>louis</span></li>
</ul>
jQuery
var $all = $('#all');
$('#search').on('keyup', function() {
$all.find('li').hide();
//I want check span value with enter any key
//(point: span value should to be lowerCase)
});
please guide me how to lowerCase spans value and check lowerCase typing
any word
Wednesday, 21 August 2013
How to have a form submit a perimeter value for a javascript function?
How to have a form submit a perimeter value for a javascript function?
I am looking to have the input of a form submit a perimeter value to a
javascript function and have the function called once the submit button is
clicked. I have limited knowledge on how to approach this so any help is
greatly appreciated. P.S. I had to take off the opening bracket to the
submit button so everything will display.
<input type="text" name="name" id="numbervalue" value="value" />
input type="submit" value="submit" onsubmit="numbervalue()">
I am looking to have the input of a form submit a perimeter value to a
javascript function and have the function called once the submit button is
clicked. I have limited knowledge on how to approach this so any help is
greatly appreciated. P.S. I had to take off the opening bracket to the
submit button so everything will display.
<input type="text" name="name" id="numbervalue" value="value" />
input type="submit" value="submit" onsubmit="numbervalue()">
Apply different scopes to the same character in a Sublime Text syntax definition file
Apply different scopes to the same character in a Sublime Text syntax
definition file
I'm trying to create a new .tmLanguage file for Sublime Text 2 that
defines special fenced code blocks for knitr and Markdown. These blocks
take this form:
```{r example_chunk, echo=true}
x <- rnorm(100)
y <- rnorm(100)
plot(y ~ x, pch=20)
```
There are two sections: (1) the parameters ({r ...}) and (2) the actual
embedded code (between the closing } and the ``` at the end). There are
four scopes that need to be applied to delineate the two sections:
punctuation.definition.parameters.begin.knitr
punctuation.definition.parameters.end.knitr
punctuation.section.embedded.begin.knitr
punctuation.section.embedded.end.knitr
Using regular expressions to peg these scopes to parts of code is easy
enough (code available here). However, two of these scopes need to be
applied to the same single character: the final } in the parameters
section, which ends the parameters and signifies the beginning of the
fenced/embedded code.
However, it appears to be impossible to assign two scopes to the same
character in a .tmLanguage file. It's not possible to end the parameters
section and begin the embedded section. The first scope defined takes
precedence, thus breaking the syntax highlighting.
Is there a way to use a .tmLanguage syntax definition to apply two
different scopes to the same character in Sublime Text? If not, is there
some way I can peg punctuation.definition.parameters.end.knitr and
punctuation.section.embedded.begin.knitr to two different somethings
instead of the single {? (Keeping in mind that I can't add additional
characters to the code block.)
definition file
I'm trying to create a new .tmLanguage file for Sublime Text 2 that
defines special fenced code blocks for knitr and Markdown. These blocks
take this form:
```{r example_chunk, echo=true}
x <- rnorm(100)
y <- rnorm(100)
plot(y ~ x, pch=20)
```
There are two sections: (1) the parameters ({r ...}) and (2) the actual
embedded code (between the closing } and the ``` at the end). There are
four scopes that need to be applied to delineate the two sections:
punctuation.definition.parameters.begin.knitr
punctuation.definition.parameters.end.knitr
punctuation.section.embedded.begin.knitr
punctuation.section.embedded.end.knitr
Using regular expressions to peg these scopes to parts of code is easy
enough (code available here). However, two of these scopes need to be
applied to the same single character: the final } in the parameters
section, which ends the parameters and signifies the beginning of the
fenced/embedded code.
However, it appears to be impossible to assign two scopes to the same
character in a .tmLanguage file. It's not possible to end the parameters
section and begin the embedded section. The first scope defined takes
precedence, thus breaking the syntax highlighting.
Is there a way to use a .tmLanguage syntax definition to apply two
different scopes to the same character in Sublime Text? If not, is there
some way I can peg punctuation.definition.parameters.end.knitr and
punctuation.section.embedded.begin.knitr to two different somethings
instead of the single {? (Keeping in mind that I can't add additional
characters to the code block.)
Disadvatages of tld other than own country
Disadvatages of tld other than own country
I live in Belgium, so most tld's around are obviously .be. Now I'd like my
site to also have a shorter version, something like Google did with goo.gl
and youtu.be, but I'd do it with a .es domain.
I wouldn't only get the .es though, I'd also get full names with .com and
.be. Now, the fanciest would be if the site was located on the .es. The
question is though, do SEO's know that the other pages redirect to the
.es? Because if you search for sites only in your country, in my case it
only seems to show .com, .be, .eu and perhaps some more.
Another thing that jumps to mind is that my site will probably be visited
most in Belgium. Does having a tld from another country impact DNS-lookup
or something, even though the site is hosted in belgium itself?
In short:
I have mysite.es, mysitefull.be and mysitefull.com, which of these would
be best to actually serve the site on, and have the others redirect to?
Does a tld from another country impact speeds of eg DNS-lookup as opposed
to a tld from your own country?
I live in Belgium, so most tld's around are obviously .be. Now I'd like my
site to also have a shorter version, something like Google did with goo.gl
and youtu.be, but I'd do it with a .es domain.
I wouldn't only get the .es though, I'd also get full names with .com and
.be. Now, the fanciest would be if the site was located on the .es. The
question is though, do SEO's know that the other pages redirect to the
.es? Because if you search for sites only in your country, in my case it
only seems to show .com, .be, .eu and perhaps some more.
Another thing that jumps to mind is that my site will probably be visited
most in Belgium. Does having a tld from another country impact DNS-lookup
or something, even though the site is hosted in belgium itself?
In short:
I have mysite.es, mysitefull.be and mysitefull.com, which of these would
be best to actually serve the site on, and have the others redirect to?
Does a tld from another country impact speeds of eg DNS-lookup as opposed
to a tld from your own country?
Trying to Consolidate using Excel - Need to Concatenate
Trying to Consolidate using Excel - Need to Concatenate
I have a mail list that I need to merge the duplicate addresses together
and concatenate the names. Example below:
Name Street_Address
--------- ----------------
JohnDoe 444 Elm Street
JaneDoe 444 Elm Street
BillyBob 456 Birch Street
BugsBunny 999 Maple Street
BabsBunny 999 Maple Street
I would like to merge the duplicates like so:
Name Street_Address
------------------ ----------------
JohnDoeJaneDoe 444 Elm Street
BillyBob 456 Birch Street
BugsBunnyBabsBunny 999 Maple Street
I've tried using the consolidate feature but you don't get the option for
concatenate. Thanks for your help!
I have a mail list that I need to merge the duplicate addresses together
and concatenate the names. Example below:
Name Street_Address
--------- ----------------
JohnDoe 444 Elm Street
JaneDoe 444 Elm Street
BillyBob 456 Birch Street
BugsBunny 999 Maple Street
BabsBunny 999 Maple Street
I would like to merge the duplicates like so:
Name Street_Address
------------------ ----------------
JohnDoeJaneDoe 444 Elm Street
BillyBob 456 Birch Street
BugsBunnyBabsBunny 999 Maple Street
I've tried using the consolidate feature but you don't get the option for
concatenate. Thanks for your help!
Synchronous UI operation
Synchronous UI operation
I am creating custom alertview in which I wish to integrate synchronous
operation. that is before dismissing first alert second one should not
show. To create this i am customizing this downloaded control. Here
UIViewController used as subclass to show an alert, we need to present to
above view controller to show alert.
Code
[alert show];
[alert show];
[alert show];
In show method I present to alert view subclass. When I consecutively call
the show method, the operation should perform synchronously. The second
alert should not pop up until the first one is dismissed.
Can you please provide the best approach to achieve this.
I am creating custom alertview in which I wish to integrate synchronous
operation. that is before dismissing first alert second one should not
show. To create this i am customizing this downloaded control. Here
UIViewController used as subclass to show an alert, we need to present to
above view controller to show alert.
Code
[alert show];
[alert show];
[alert show];
In show method I present to alert view subclass. When I consecutively call
the show method, the operation should perform synchronously. The second
alert should not pop up until the first one is dismissed.
Can you please provide the best approach to achieve this.
Interquartile Rang concept / Problem?
Interquartile Rang concept / Problem?
If a set of data consists of only the first ten positive mulitple of $5$,
what is the interquartile range of the set ?
I have tried to solve but my answer is wrong..
If a set of data consists of only the first ten positive mulitple of $5$,
what is the interquartile range of the set ?
I have tried to solve but my answer is wrong..
Confused about default string comparison option on sql
Confused about default string comparison option on sql
I am completely confused about the default string comparison method used
in SQl. Up till now I had been using UPPER() and LOWER() functions for
performing any string comparison on SQL. However got to know that by
default SQL is case insensitive and we need to change the collation while
installing SQL to make it case sensitive. However if this is the case then
what is the use of UPPER and LOWER() functions.
Can somebody please explain..
I am completely confused about the default string comparison method used
in SQl. Up till now I had been using UPPER() and LOWER() functions for
performing any string comparison on SQL. However got to know that by
default SQL is case insensitive and we need to change the collation while
installing SQL to make it case sensitive. However if this is the case then
what is the use of UPPER and LOWER() functions.
Can somebody please explain..
Tuesday, 20 August 2013
SQlServer select query with utf-8 data
SQlServer select query with utf-8 data
I want some sample select querys in sqlserver with utf-8
For Ex: select * from KADULM where UADULLID like '%மு%'
I want some sample select querys in sqlserver with utf-8
For Ex: select * from KADULM where UADULLID like '%மு%'
What is the correct way to make a POST request to a Rest api with an authentication token?
What is the correct way to make a POST request to a Rest api with an
authentication token?
I need to consume the api documented here:
[http://docs.opsview.com/doku.php?id=developer:restapi][1]
The login call returns a token successfully. However, when I try other
calls, I'm getting the following error:
failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden
This is the function I wrote to make my calls:
public function sendRequestGetResults($path, $data = [], $method = 'GET',
$headers = [], $contentType = "application/x-www-form-urlencoded")
{
return json_decode
(
file_get_contents
(
'https://' . $this->apiHost . '/rest/' . $path,
false,
stream_context_create
(
[
'http' =>
[
'header' => array_merge
(
[
"Content-type: " . $contentType
],
$headers
),
'method' => $method,
'content' => http_build_query
(
$data
)
],
]
)
)
);
}
I tried adding the login and the token returned by the login call to the
headers of the request by calling my function with the a $headers
parameter as follows, but still no luck:
[
"X-Opsview-Username: myUsername",
"X-Opsview-Token: myToken"
]
I also tried modifying the function to concatenate the string of headers
instead of using an array, but got the same result:
What might I be missing?
authentication token?
I need to consume the api documented here:
[http://docs.opsview.com/doku.php?id=developer:restapi][1]
The login call returns a token successfully. However, when I try other
calls, I'm getting the following error:
failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden
This is the function I wrote to make my calls:
public function sendRequestGetResults($path, $data = [], $method = 'GET',
$headers = [], $contentType = "application/x-www-form-urlencoded")
{
return json_decode
(
file_get_contents
(
'https://' . $this->apiHost . '/rest/' . $path,
false,
stream_context_create
(
[
'http' =>
[
'header' => array_merge
(
[
"Content-type: " . $contentType
],
$headers
),
'method' => $method,
'content' => http_build_query
(
$data
)
],
]
)
)
);
}
I tried adding the login and the token returned by the login call to the
headers of the request by calling my function with the a $headers
parameter as follows, but still no luck:
[
"X-Opsview-Username: myUsername",
"X-Opsview-Token: myToken"
]
I also tried modifying the function to concatenate the string of headers
instead of using an array, but got the same result:
What might I be missing?
Allocate memory on stack without calling constructor
Allocate memory on stack without calling constructor
I'd like to keep MyClass in the stack memory (simpler, faster) in the
following code, but avoid calling the default constructor:
#include <iostream>
class MyClass {
public:
MyClass() {
std::cout << "MyClass()" << std::endl;
}
MyClass(int a) {
std::cout << "MyClass(" << a << ")" << std::endl;
}
MyClass(const std::string& a) {
std::cout << "MyClass(\"" << a << "\")" << std::endl;
}
void doStuff() {
std::cout << "doStuff()" << std::endl;
}
};
int main(int argc, char* argv[]) {
bool something;
if (argc > 1)
something = 1;
else
something = 0;
MyClass c;
if (something)
c = MyClass(1);
else
c = MyClass("string");
c.doStuff();
return 0;
}
As far as I know, the only way to avoid calling the default constructor
would be to use a pointer, but then I would have to allocate in the heap
and deal with memory management. Is there any other way?
I'd like to keep MyClass in the stack memory (simpler, faster) in the
following code, but avoid calling the default constructor:
#include <iostream>
class MyClass {
public:
MyClass() {
std::cout << "MyClass()" << std::endl;
}
MyClass(int a) {
std::cout << "MyClass(" << a << ")" << std::endl;
}
MyClass(const std::string& a) {
std::cout << "MyClass(\"" << a << "\")" << std::endl;
}
void doStuff() {
std::cout << "doStuff()" << std::endl;
}
};
int main(int argc, char* argv[]) {
bool something;
if (argc > 1)
something = 1;
else
something = 0;
MyClass c;
if (something)
c = MyClass(1);
else
c = MyClass("string");
c.doStuff();
return 0;
}
As far as I know, the only way to avoid calling the default constructor
would be to use a pointer, but then I would have to allocate in the heap
and deal with memory management. Is there any other way?
Why can Oracle not select truthiness of a statement in the order by cluase
Why can Oracle not select truthiness of a statement in the order by cluase
If I want to order a table by one column, but extract one specified row to
the top, in MySQL, I can do something like this... (fiddle)
select * from name
order by surname != 'moon', surname
However, when I want to do this in oracle, the truthy test in the order by
clause does not work, and I end up having to do something like this...
(fiddle)
select surname from name
order by case when surname = 'moon' then 0 else 1 end, surname
What is the reason for Oracle not supporting truthy tests in the order by
clause?
(or even the select statement for that matter)
Results
(all are in alphabetical order, except moon which has floated to top)
SURNAME
moon
adane
bell
day
larkin
williams
If I want to order a table by one column, but extract one specified row to
the top, in MySQL, I can do something like this... (fiddle)
select * from name
order by surname != 'moon', surname
However, when I want to do this in oracle, the truthy test in the order by
clause does not work, and I end up having to do something like this...
(fiddle)
select surname from name
order by case when surname = 'moon' then 0 else 1 end, surname
What is the reason for Oracle not supporting truthy tests in the order by
clause?
(or even the select statement for that matter)
Results
(all are in alphabetical order, except moon which has floated to top)
SURNAME
moon
adane
bell
day
larkin
williams
Unsupported Media Type (415) Error while implementing File upload using Jersey in Mule
Unsupported Media Type (415) Error while implementing File upload using
Jersey in Mule
I am trying to implement File Upload using Jersey module in Mule.
My mule flow looks like this:
<flow name="rest-service">
<inbound-endpoint address="http://localhost:9999/testupload"/>
<jersey:resources>
<component class="com.example.test.UploadFileResource"/>
</jersey:resources>
</flow>
If I don't put @Consumes annotation in the resource method in
UploadFileResource like below, the method gets called when an HTTP Post
request is made using multipart/form-data Content-type and I get HTTP 2xx
status code:
@Path("/uploadfile")
public class UploadFileResource {
@POST
public Response uploadFile2(...) {
logger.info("Multipart Upload");
...
}
}
But when I put @Consumes annotation with MULTIPART_FORM_DATA Media Type
like below, the method does not get called and I get HTTP 415 Unsupported
Media type, even when the HTTP Post request is made using
multipart/form-data Content-type:
@Path("/uploadfile")
public class UploadFileResource {
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile2(...) {
logger.info("Multipart Upload");
...
}
}
Any idea why 415 status comes even when @Consumes Media type matches the
HTTP Post Content-type header?
Jersey in Mule
I am trying to implement File Upload using Jersey module in Mule.
My mule flow looks like this:
<flow name="rest-service">
<inbound-endpoint address="http://localhost:9999/testupload"/>
<jersey:resources>
<component class="com.example.test.UploadFileResource"/>
</jersey:resources>
</flow>
If I don't put @Consumes annotation in the resource method in
UploadFileResource like below, the method gets called when an HTTP Post
request is made using multipart/form-data Content-type and I get HTTP 2xx
status code:
@Path("/uploadfile")
public class UploadFileResource {
@POST
public Response uploadFile2(...) {
logger.info("Multipart Upload");
...
}
}
But when I put @Consumes annotation with MULTIPART_FORM_DATA Media Type
like below, the method does not get called and I get HTTP 415 Unsupported
Media type, even when the HTTP Post request is made using
multipart/form-data Content-type:
@Path("/uploadfile")
public class UploadFileResource {
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile2(...) {
logger.info("Multipart Upload");
...
}
}
Any idea why 415 status comes even when @Consumes Media type matches the
HTTP Post Content-type header?
Native function call in testcase using gwt-test-utils causes UnsatisfiedLinkError
Native function call in testcase using gwt-test-utils causes
UnsatisfiedLinkError
I am testing my gwt Composite component using gwt-test-utils 0.44.
I am using gwt-cal Calendar component. But i cant instantiate the class
beacause it throws UnstisfiedLinkError when a native function in invoked.
I have simulated the problem. Here is my code.
@GwtModule("com.testing.web.MyProject")
public class CalendarViewTest extends GwtTest{
private static native void alrt() /*-{
$wnd.alert("js");
}-*/;
@Test
public void test01(){
alrt();
}
}
This also causes UnstisfiedLinkError. How can i call the native funcion
correctly? Is there any configuration needed?
UnsatisfiedLinkError
I am testing my gwt Composite component using gwt-test-utils 0.44.
I am using gwt-cal Calendar component. But i cant instantiate the class
beacause it throws UnstisfiedLinkError when a native function in invoked.
I have simulated the problem. Here is my code.
@GwtModule("com.testing.web.MyProject")
public class CalendarViewTest extends GwtTest{
private static native void alrt() /*-{
$wnd.alert("js");
}-*/;
@Test
public void test01(){
alrt();
}
}
This also causes UnstisfiedLinkError. How can i call the native funcion
correctly? Is there any configuration needed?
Partial download nightmare in Java
Partial download nightmare in Java
Here is my complete code that I use to download files from the internet in
my Android app. The idea is to resume the download from where it left off
when the app restarts / is restored.
package com.example.simpledownloader.task;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.atomic.AtomicLong;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.Log;
import com.example.simpledownloader.sharable.NetworkOptions;
import com.example.simpledownloader.sharable.Sharable;
public class Task extends Thread {
private String url = null;
private String name = null;
private AtomicLong contentLength = null;
private AtomicLong bytesWritten = null;
private boolean isReady = true;
private String errCode = new String("OK");
//------------------------------------------------------------------------------
public Task(String name, String url, long contentLength, long
bytesWritten){
// Instantiate the variables
// The values here depend on whether the Task was created by TaskDAO
// or by clicking the download button
this.name = name;
this.url = url;
this.contentLength = new AtomicLong(contentLength);
this.bytesWritten = new AtomicLong(bytesWritten);
}
//------------------------------------------------------------------------------
@Override
public void run() {
File f = null;
RandomAccessFile rFile = null;
setReadiness(false);
Sharable.setShouldLook(false);
try {
String[] names = name.split("/");
if(names.length == 0){
// nothing
}else{
name = names[names.length-1];
}
Log.v("TASKPATH", "/sdcard/" + name);
f = new File("/sdcard/",name);
rFile = new RandomAccessFile(f, "rw");
writeToFile(rFile);
} catch (FileNotFoundException e) {
Log.v("TASK", e.getLocalizedMessage());
if(contentLength.get() == 0){ // new download will have
content length set to zero
try {
f.createNewFile(); // make a new file
writeToFile(rFile);// start downloading
}catch (IOException e1) {
errCode = e1.getMessage(); // Unable to create file;
Log.v("TASK", "FILE DELETED");
Sharable.setShouldLook(true);
return;
}
}else{
errCode = "Created file has been deleted"; // File was
previously created but now is not found.
Log.v("TASK", "FILE DELETED");
Sharable.setShouldLook(true);
return;
}
} catch (IOException e) {
errCode = e.getLocalizedMessage();
Sharable.setShouldLook(true);
Log.v("TASK", e.getLocalizedMessage());
}
}
//------------------------------------------------------------------------------
private void writeToFile(RandomAccessFile file){
NetworkInfo wifi =
Sharable.connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile =
Sharable.connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
URL u;
HttpURLConnection httpCon = null;
try {
byte[] buffer = new byte[2 * 1024]; // 2 MB buffer
long bytesWritten = 0;
if(contentLength.get() == 0){ // new file ?
u = new URL(url); // make a URL
httpCon = (HttpURLConnection) u.openConnection(); //
Get ready to make a connection via HTTP
httpCon.setDoInput(true); // this connection will
download data
httpCon.connect(); // make a connection
BufferedInputStream buf = new
BufferedInputStream(httpCon.getInputStream()); // get
a stream
contentLength.addAndGet(httpCon.getContentLength());
// set content length
while((bytesWritten = buf.read(buffer)) != -1 ){
if(Sharable.networkOption ==
NetworkOptions.WIFI_ONLY){
if(!wifi.isConnected()){ // check WiFi
connectivity
setReadiness(false);
Sharable.setShouldLook(true);
break;
}
}
Log.v("TASK", "Writing at location " +
this.bytesWritten.get());
file.write(buffer);
this.bytesWritten.addAndGet(bytesWritten);
String update = "UPDATE tasks SET byteswritten=" +
this.bytesWritten.get() +
" ,contentlength=" +
this.contentLength.get() +
" WHERE url='" + url + "'";
Sharable.db.execSQL(update); // write data to
database
Sharable.handler.post(new Runnable(){
@Override
public void run() {
Sharable.adapter.notifyDataSetChanged();
// update the display
}
});
if(isInterrupted()){
setReadiness(true);
Sharable.setShouldLook(true);
break;
}
}
}else{ // not a new file
file.seek(this.bytesWritten.get()); // seek to proper
position
u = new URL(url); // make a URL
httpCon = (HttpURLConnection) u.openConnection(); //
Get ready to make a connection via HTTP
httpCon.setDoInput(true); // this connection will
download data
httpCon.setRequestProperty("Range:",
"bytes="+this.bytesWritten.get()+"-");
httpCon.connect(); // make a connection
if(httpCon.getResponseCode() !=
HttpURLConnection.HTTP_PARTIAL){ // check if partial
download supported
errCode = "206 Not Supported";
setReadiness(false);
Sharable.setShouldLook(true);
return;
}
BufferedInputStream buf = new
BufferedInputStream(httpCon.getInputStream()); // get
a stream
while((bytesWritten = buf.read(buffer)) != -1 ){ //
start downlading
if(Sharable.networkOption ==
NetworkOptions.WIFI_ONLY){
if(!wifi.isConnected()){ // check WiFi
connectivity
setReadiness(false);
Sharable.setShouldLook(true);
if(httpCon != null){
httpCon.disconnect();
}
break;
}
}
Log.v("TASK", "Writing at location " +
this.bytesWritten.get());
file.write(buffer);
this.bytesWritten.addAndGet(bytesWritten);
String update = "UPDATE tasks SET byteswritten=" +
this.bytesWritten.get() +
" ,contentlength=" +
this.contentLength.get() +
" WHERE url='" + url + "'";
Sharable.db.execSQL(update); // write data to
database
Sharable.handler.post(new Runnable(){
@Override
public void run() {
Sharable.adapter.notifyDataSetChanged();
// update the display
}
});
if(isInterrupted()){ // check for thread interruption
setReadiness(true);
Sharable.setShouldLook(true);
break;
}
}
}
} catch (MalformedURLException e) {
errCode = e.getMessage();
Log.v("TASK", e.getLocalizedMessage());
} catch (IOException e) {
errCode = e.getLocalizedMessage();
Log.v("TASK", e.getLocalizedMessage());
}catch(Exception e){
errCode = e.getLocalizedMessage();
Log.v("TASK", e.getLocalizedMessage());
}
}
//------------------------------------------------------------------------------
public synchronized float getProgress(){
if(contentLength.get() != -1 && contentLength.get() != 0){
return (bytesWritten.get()*100)/contentLength.get();
}else{
return -1;
}
}
//------------------------------------------------------------------------------
public synchronized boolean getReadiness(){
return isReady;
}
//------------------------------------------------------------------------------
public synchronized void setReadiness(boolean ready){
isReady = ready;
}
//------------------------------------------------------------------------------
public synchronized String getStatus(){
return errCode;
}
//------------------------------------------------------------------------------
public synchronized String getTaskName(){
return name;
}
//------------------------------------------------------------------------------
@Override
public String toString(){
return name;
}
//------------------------------------------------------------------------------
}
The problem, however, is that the partial download never starts... I do
not know why. I usually end up with no activity at all or with a 206 Not
Supported error.
Other class that might interest you is the Sharable which contains
singleton instances:
Sharable.java and Scheduler.java
How do I resume partial downloads ?
Here is my complete code that I use to download files from the internet in
my Android app. The idea is to resume the download from where it left off
when the app restarts / is restored.
package com.example.simpledownloader.task;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.atomic.AtomicLong;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.Log;
import com.example.simpledownloader.sharable.NetworkOptions;
import com.example.simpledownloader.sharable.Sharable;
public class Task extends Thread {
private String url = null;
private String name = null;
private AtomicLong contentLength = null;
private AtomicLong bytesWritten = null;
private boolean isReady = true;
private String errCode = new String("OK");
//------------------------------------------------------------------------------
public Task(String name, String url, long contentLength, long
bytesWritten){
// Instantiate the variables
// The values here depend on whether the Task was created by TaskDAO
// or by clicking the download button
this.name = name;
this.url = url;
this.contentLength = new AtomicLong(contentLength);
this.bytesWritten = new AtomicLong(bytesWritten);
}
//------------------------------------------------------------------------------
@Override
public void run() {
File f = null;
RandomAccessFile rFile = null;
setReadiness(false);
Sharable.setShouldLook(false);
try {
String[] names = name.split("/");
if(names.length == 0){
// nothing
}else{
name = names[names.length-1];
}
Log.v("TASKPATH", "/sdcard/" + name);
f = new File("/sdcard/",name);
rFile = new RandomAccessFile(f, "rw");
writeToFile(rFile);
} catch (FileNotFoundException e) {
Log.v("TASK", e.getLocalizedMessage());
if(contentLength.get() == 0){ // new download will have
content length set to zero
try {
f.createNewFile(); // make a new file
writeToFile(rFile);// start downloading
}catch (IOException e1) {
errCode = e1.getMessage(); // Unable to create file;
Log.v("TASK", "FILE DELETED");
Sharable.setShouldLook(true);
return;
}
}else{
errCode = "Created file has been deleted"; // File was
previously created but now is not found.
Log.v("TASK", "FILE DELETED");
Sharable.setShouldLook(true);
return;
}
} catch (IOException e) {
errCode = e.getLocalizedMessage();
Sharable.setShouldLook(true);
Log.v("TASK", e.getLocalizedMessage());
}
}
//------------------------------------------------------------------------------
private void writeToFile(RandomAccessFile file){
NetworkInfo wifi =
Sharable.connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile =
Sharable.connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
URL u;
HttpURLConnection httpCon = null;
try {
byte[] buffer = new byte[2 * 1024]; // 2 MB buffer
long bytesWritten = 0;
if(contentLength.get() == 0){ // new file ?
u = new URL(url); // make a URL
httpCon = (HttpURLConnection) u.openConnection(); //
Get ready to make a connection via HTTP
httpCon.setDoInput(true); // this connection will
download data
httpCon.connect(); // make a connection
BufferedInputStream buf = new
BufferedInputStream(httpCon.getInputStream()); // get
a stream
contentLength.addAndGet(httpCon.getContentLength());
// set content length
while((bytesWritten = buf.read(buffer)) != -1 ){
if(Sharable.networkOption ==
NetworkOptions.WIFI_ONLY){
if(!wifi.isConnected()){ // check WiFi
connectivity
setReadiness(false);
Sharable.setShouldLook(true);
break;
}
}
Log.v("TASK", "Writing at location " +
this.bytesWritten.get());
file.write(buffer);
this.bytesWritten.addAndGet(bytesWritten);
String update = "UPDATE tasks SET byteswritten=" +
this.bytesWritten.get() +
" ,contentlength=" +
this.contentLength.get() +
" WHERE url='" + url + "'";
Sharable.db.execSQL(update); // write data to
database
Sharable.handler.post(new Runnable(){
@Override
public void run() {
Sharable.adapter.notifyDataSetChanged();
// update the display
}
});
if(isInterrupted()){
setReadiness(true);
Sharable.setShouldLook(true);
break;
}
}
}else{ // not a new file
file.seek(this.bytesWritten.get()); // seek to proper
position
u = new URL(url); // make a URL
httpCon = (HttpURLConnection) u.openConnection(); //
Get ready to make a connection via HTTP
httpCon.setDoInput(true); // this connection will
download data
httpCon.setRequestProperty("Range:",
"bytes="+this.bytesWritten.get()+"-");
httpCon.connect(); // make a connection
if(httpCon.getResponseCode() !=
HttpURLConnection.HTTP_PARTIAL){ // check if partial
download supported
errCode = "206 Not Supported";
setReadiness(false);
Sharable.setShouldLook(true);
return;
}
BufferedInputStream buf = new
BufferedInputStream(httpCon.getInputStream()); // get
a stream
while((bytesWritten = buf.read(buffer)) != -1 ){ //
start downlading
if(Sharable.networkOption ==
NetworkOptions.WIFI_ONLY){
if(!wifi.isConnected()){ // check WiFi
connectivity
setReadiness(false);
Sharable.setShouldLook(true);
if(httpCon != null){
httpCon.disconnect();
}
break;
}
}
Log.v("TASK", "Writing at location " +
this.bytesWritten.get());
file.write(buffer);
this.bytesWritten.addAndGet(bytesWritten);
String update = "UPDATE tasks SET byteswritten=" +
this.bytesWritten.get() +
" ,contentlength=" +
this.contentLength.get() +
" WHERE url='" + url + "'";
Sharable.db.execSQL(update); // write data to
database
Sharable.handler.post(new Runnable(){
@Override
public void run() {
Sharable.adapter.notifyDataSetChanged();
// update the display
}
});
if(isInterrupted()){ // check for thread interruption
setReadiness(true);
Sharable.setShouldLook(true);
break;
}
}
}
} catch (MalformedURLException e) {
errCode = e.getMessage();
Log.v("TASK", e.getLocalizedMessage());
} catch (IOException e) {
errCode = e.getLocalizedMessage();
Log.v("TASK", e.getLocalizedMessage());
}catch(Exception e){
errCode = e.getLocalizedMessage();
Log.v("TASK", e.getLocalizedMessage());
}
}
//------------------------------------------------------------------------------
public synchronized float getProgress(){
if(contentLength.get() != -1 && contentLength.get() != 0){
return (bytesWritten.get()*100)/contentLength.get();
}else{
return -1;
}
}
//------------------------------------------------------------------------------
public synchronized boolean getReadiness(){
return isReady;
}
//------------------------------------------------------------------------------
public synchronized void setReadiness(boolean ready){
isReady = ready;
}
//------------------------------------------------------------------------------
public synchronized String getStatus(){
return errCode;
}
//------------------------------------------------------------------------------
public synchronized String getTaskName(){
return name;
}
//------------------------------------------------------------------------------
@Override
public String toString(){
return name;
}
//------------------------------------------------------------------------------
}
The problem, however, is that the partial download never starts... I do
not know why. I usually end up with no activity at all or with a 206 Not
Supported error.
Other class that might interest you is the Sharable which contains
singleton instances:
Sharable.java and Scheduler.java
How do I resume partial downloads ?
Monday, 19 August 2013
how to separate a string from text in android
how to separate a string from text in android
I want to split a string from text. my text is
Text: "#FoodType:Veg#\r\n#Ratings:5.0#\r\n#Description:Short Description#"
I want like this
"#FoodType:" + veg + "#". only want veg, that is the value of foodType.
I want to split a string from text. my text is
Text: "#FoodType:Veg#\r\n#Ratings:5.0#\r\n#Description:Short Description#"
I want like this
"#FoodType:" + veg + "#". only want veg, that is the value of foodType.
How to compute, for each method, the set of exceptions that method may throw, including runtime exceptions?
How to compute, for each method, the set of exceptions that method may
throw, including runtime exceptions?
I'm trying to implement an intra-procedural analysis that computes, for
each method, the set of exceptions that method may throw, including
runtime exceptions
throw, including runtime exceptions?
I'm trying to implement an intra-procedural analysis that computes, for
each method, the set of exceptions that method may throw, including
runtime exceptions
Is there any good Jenkins plugin for Rspec report
Is there any good Jenkins plugin for Rspec report
Currently I am using HTML Publisher Plugin to just publish the HTML file
created by the RSpec HTML formatter, it doesn't look very nice.
I am aware that there is a Cucumber Reports Plugin, so wondering if there
is any similar plugin for Rspec?
Currently I am using HTML Publisher Plugin to just publish the HTML file
created by the RSpec HTML formatter, it doesn't look very nice.
I am aware that there is a Cucumber Reports Plugin, so wondering if there
is any similar plugin for Rspec?
Security concerns using web services /Ajax
Security concerns using web services /Ajax
To make a Jquery auto complete control work, a call is made to the web
service to populate the filtered drop down choices. Is this a secure way
to handle things ? How can i make these calls to web services more secure?
To make a Jquery auto complete control work, a call is made to the web
service to populate the filtered drop down choices. Is this a secure way
to handle things ? How can i make these calls to web services more secure?
File not found exception inside php class
File not found exception inside php class
Hello and thanks for your time. I have a problem with the following code:
//reads all the data from $fileName and returns it
private function readFile($fileName)
{
$location = $this->path.$fileName;
try{//try to open file
$file=fopen($location,"r");
}
catch(Exception $e){
return $e;
}
$return = "";//read file contents
while (!feof($file))
{
$return .= fgetc($file);
}
//close file and return result
fclose($file);
return $return;
}
I have this function in a class, but every time i call fopen it throws the
following exception:
Warning: readfile(messages.txt): failed to open stream: No such file or
directory in C:\xampp\htdocs\zdupp\php\textChat.php on line 85
But I checked the $location var and it is ok("../chat/1.2/messages.txt");
Also the file is there. I also tried a path starting from C:
C:/xampp/htdocs/zdupp/chat/1.2/messages.txt
But with no success. Could you please help me out?
Hello and thanks for your time. I have a problem with the following code:
//reads all the data from $fileName and returns it
private function readFile($fileName)
{
$location = $this->path.$fileName;
try{//try to open file
$file=fopen($location,"r");
}
catch(Exception $e){
return $e;
}
$return = "";//read file contents
while (!feof($file))
{
$return .= fgetc($file);
}
//close file and return result
fclose($file);
return $return;
}
I have this function in a class, but every time i call fopen it throws the
following exception:
Warning: readfile(messages.txt): failed to open stream: No such file or
directory in C:\xampp\htdocs\zdupp\php\textChat.php on line 85
But I checked the $location var and it is ok("../chat/1.2/messages.txt");
Also the file is there. I also tried a path starting from C:
C:/xampp/htdocs/zdupp/chat/1.2/messages.txt
But with no success. Could you please help me out?
Not using correctly javascript setTimeout / clearTimeout?
Not using correctly javascript setTimeout / clearTimeout?
I have problem with simple javascript and some ajax.
I have link that calls javascript function like this:
<div id="Button11" onmouseover="changeContent4()">Actions</div>
Javascript function that is called above is like this:
function changeContent4()
{
BubbleOn()
document.getElementById("text1").innerHTML='Some text here';
clearTimeout(BOffi);
var BOffi = setTimeout(BubbleOff, 20000);
}
This works, it runs BubbleOn function, places text to element text1, most
likely it empties BOffi timeout and sets new timeout 20000ms for it.
Here is BubbleOn:
function BubbleOn() {
$("#bubble").fadeIn(function() {
})
}
And here is BubbleOff:
function BubbleOff() {
$("#bubble").fadeOut(function() {
})
}
As in functions BubbleOn and BubbleOff works. They just hide or show div
named bubble which contains text1 element. When BOffi goes timeout it just
runs the BubbleOff function. This works fine. The problem is that when
BubbleOff has been run and mouse is placed immediately over link that runs
changeContent4(), It does make the bubble div visible again and places
text there again but then bubble div fades out inside a second! Not after
20000ms. After this if the mouse is placed again to run changeContent4()
everything works great. If there is about millisecond longer time than a
second between the bubble fadeout and placing the mouse over
changeContent4() launcher it works and waits 20000ms. Less than a second
and bubble is shown about second...
What can cause this? Could it be that fadeOut is still running even the
bubble is vanished from the screen and therefore it does not reset the
BOffi counter? Which could have 1 second or less time left and then runs
BubbleOff again after that magical second?
I have problem with simple javascript and some ajax.
I have link that calls javascript function like this:
<div id="Button11" onmouseover="changeContent4()">Actions</div>
Javascript function that is called above is like this:
function changeContent4()
{
BubbleOn()
document.getElementById("text1").innerHTML='Some text here';
clearTimeout(BOffi);
var BOffi = setTimeout(BubbleOff, 20000);
}
This works, it runs BubbleOn function, places text to element text1, most
likely it empties BOffi timeout and sets new timeout 20000ms for it.
Here is BubbleOn:
function BubbleOn() {
$("#bubble").fadeIn(function() {
})
}
And here is BubbleOff:
function BubbleOff() {
$("#bubble").fadeOut(function() {
})
}
As in functions BubbleOn and BubbleOff works. They just hide or show div
named bubble which contains text1 element. When BOffi goes timeout it just
runs the BubbleOff function. This works fine. The problem is that when
BubbleOff has been run and mouse is placed immediately over link that runs
changeContent4(), It does make the bubble div visible again and places
text there again but then bubble div fades out inside a second! Not after
20000ms. After this if the mouse is placed again to run changeContent4()
everything works great. If there is about millisecond longer time than a
second between the bubble fadeout and placing the mouse over
changeContent4() launcher it works and waits 20000ms. Less than a second
and bubble is shown about second...
What can cause this? Could it be that fadeOut is still running even the
bubble is vanished from the screen and therefore it does not reset the
BOffi counter? Which could have 1 second or less time left and then runs
BubbleOff again after that magical second?
Sunday, 18 August 2013
NON activity class calling an SqlLite Dtabase For android
NON activity class calling an SqlLite Dtabase For android
package com.example.beachvolley;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
public static final String DATABASE_NAME = "MyDb";
private static final String TAG = "DBAdapter";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public static final int DATABASE_VERSION = 21;
// I CREATED A TOURNAMENT TABLE public static final String
TOURNAMENT_TABLE = "Tournament";
public static final String KEY_TOURNAMENT_ID = "IdTournament";
public static final int COL__TOURNAMENT_ID = 0;
public static final String KEY_NAME_TOURNAMENT = "TournamentName";
public static final int COL_NAME_TOURNAMENT = 1;
public static final String KEY_YEAR_TOURNAMENT = "Year";
public static final int COL_YEAR_TOURNAMENT = 2;
public static final String KEY_MYTEAM_TOURNAMENT = "MyTeam";
public static final int COL_MYTEAM_TOURNAMENT = 2;
public static final String[] ALL_TOURNAMENT_KEYS = new String[] {
KEY_TOURNAMENT_ID, KEY_NAME_TOURNAMENT, KEY_YEAR_TOURNAMENT,
KEY_MYTEAM_TOURNAMENT};
private static final String TOURNAMEN_TABLE_CREATE_SQL =
"create table " + TOURNAMENT_TABLE
+ " (" + KEY_TOURNAMENT_ID + " integer primary key autoincrement, "
+ KEY_NAME_TOURNAMENT + " string not null, "
+ KEY_YEAR_TOURNAMENT + " string not null, "
+ KEY_MYTEAM_TOURNAMENT + " string not null "
+ ");";
public Cursor getAllTournamentRows() {
String where = null;
Cursor c = db.query(true, TOURNAMENT_TABLE, ALL_TOURNAMENT_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public long insertTournamentRow(String nameTournament, String
yearTournament, String teamTournament) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME_TOURNAMENT, nameTournament);
initialValues.put(KEY_YEAR_TOURNAMENT, yearTournament);
initialValues.put(KEY_MYTEAM_TOURNAMENT, teamTournament);
return db.insert(TOURNAMENT_TABLE, null, initialValues);
}
//END OF TOURNAMENT TABLE
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
//START OF MY DB HELPER
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(TOURNAMEN_TABLE_CREATE_SQL);
_db.execSQL(GAME_TABLE_CREATE_SQL);
_db.execSQL(PLAYER_TABLE_CREATE_SQL);
_db.execSQL(PLAYER_SET_CREATE_SQL);
_db.execSQL(PLAYER_MOVE_CREATE_SQL);
_db.execSQL(PLAYER_STATS_CREATE_SQL);
_db.execSQL(PLAYER_PLAYERMOVES_CREATE_SQL);
_db.execSQL(PLAYER_ROSTER_CREATE_SQL);
_db.execSQL(TOURNAMENT_PLAYER_CREATE_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int
newVersion) {
Log.w(TAG, "Upgrading application's database from version " +
oldVersion
+ " to " + newVersion + ", which will destroy all old
data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + TOURNAMENT_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + GAME_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + PLAYER_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + SET_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + MOVE_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + STATS_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + PLAYERMOVE_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + PLAYER_ROSTER_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + TOURNAMENT_PLAYER_TABLE);
// Recreate new database:
onCreate(_db);
}
}
&& // HOW Am i able to store my data INTO MY TOURNAMENT TABLE I CAN'T CALL
THE method open(); top open my database package com.example.beachvolley;
import java.util.ArrayList;
import java.util.Observable;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.provider.OpenableColumns;
public class TournamentModel extends Observable { //NOTE it does not
extend activity only observable
public String TournamentName;// = getTournamentName();
public String TournamentYear;
public String TeamRecorded;
public boolean ToggeTname = true;
public boolean ToggeTyear = true;
public boolean ToggeTteam= true;
public boolean ToggePlayerNames= true;
Player[] ListOfPlayers;
public boolean CheckIfInvalid(String TournamentName, String Year,
String teamName, String FirstName1, String LastName1,String
FirstName2, String LastName2, String FirstName3, String LastName3,
String p1, String p2, String p3 ){
ToggeTname = true;
ToggeTyear = true;
ToggeTteam= true;
if(TournamentName.equals(""))
this.ToggeTname = false;
else
this.ToggeTname = true;
if(Year.equals(""))
this.ToggeTyear = false;
else
this.ToggeTyear = true;
if(teamName.equals(""))
this.ToggeTteam = false;
else
this.ToggeTteam = true;
if(FirstName1.equals("") || LastName1.equals("") ||
FirstName2.equals("") || LastName2.equals("")||
FirstName3.equals("") || LastName3.equals("") || p1.equals("")||
p2.equals("")|| p3.equals(""))
this.ToggePlayerNames = false;
else
this.ToggePlayerNames = true;
triggerObservers();
if(this.ToggeTname && this.ToggeTyear && this.ToggeTteam &&
this.ToggePlayerNames)
return true;
else
return false;
}
public void StoreInputsForTournament(boolean tog , String
TournamentName, String Year, String teamName, ArrayList<Player>
playerList ){
if(tog == true){
//code goes here to STORE INTO THE TOURNAMENT TABLE
}
}
private void triggerObservers() {
setChanged();
notifyObservers();
}
public boolean isToggeTname() {
return ToggeTname;
}
public void setToggeTname(boolean toggeTname) {
ToggeTname = toggeTname;
}
public boolean isToggeTyear() {
return ToggeTyear;
}
public void setToggeTyear(boolean toggeTyear) {
ToggeTyear = toggeTyear;
}
public boolean isToggeTteam() {
return ToggeTteam;
}
public void setToggeTteam(boolean toggeTteam) {
ToggeTteam = toggeTteam;
}
public boolean isToggePlayerNames() {
return ToggePlayerNames;
}
public void setToggePlayerNames(boolean toggePlayerNames) {
ToggePlayerNames = toggePlayerNames;
}
public String getTournamentYear() {
return TournamentYear;
}
public void setTournamentYear(String tournamentYear) {
TournamentYear = tournamentYear;
}
public String getTeamRecorded() {
return TeamRecorded;
}
public void setTeamRecorded(String teamRecorded) {
TeamRecorded = teamRecorded;
}
public String getTournamentName() {
return TournamentName;
}
public void setTournamentName(String tournamentName) {
this.TournamentName = tournamentName;
}
}
package com.example.beachvolley;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
public static final String DATABASE_NAME = "MyDb";
private static final String TAG = "DBAdapter";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public static final int DATABASE_VERSION = 21;
// I CREATED A TOURNAMENT TABLE public static final String
TOURNAMENT_TABLE = "Tournament";
public static final String KEY_TOURNAMENT_ID = "IdTournament";
public static final int COL__TOURNAMENT_ID = 0;
public static final String KEY_NAME_TOURNAMENT = "TournamentName";
public static final int COL_NAME_TOURNAMENT = 1;
public static final String KEY_YEAR_TOURNAMENT = "Year";
public static final int COL_YEAR_TOURNAMENT = 2;
public static final String KEY_MYTEAM_TOURNAMENT = "MyTeam";
public static final int COL_MYTEAM_TOURNAMENT = 2;
public static final String[] ALL_TOURNAMENT_KEYS = new String[] {
KEY_TOURNAMENT_ID, KEY_NAME_TOURNAMENT, KEY_YEAR_TOURNAMENT,
KEY_MYTEAM_TOURNAMENT};
private static final String TOURNAMEN_TABLE_CREATE_SQL =
"create table " + TOURNAMENT_TABLE
+ " (" + KEY_TOURNAMENT_ID + " integer primary key autoincrement, "
+ KEY_NAME_TOURNAMENT + " string not null, "
+ KEY_YEAR_TOURNAMENT + " string not null, "
+ KEY_MYTEAM_TOURNAMENT + " string not null "
+ ");";
public Cursor getAllTournamentRows() {
String where = null;
Cursor c = db.query(true, TOURNAMENT_TABLE, ALL_TOURNAMENT_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public long insertTournamentRow(String nameTournament, String
yearTournament, String teamTournament) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME_TOURNAMENT, nameTournament);
initialValues.put(KEY_YEAR_TOURNAMENT, yearTournament);
initialValues.put(KEY_MYTEAM_TOURNAMENT, teamTournament);
return db.insert(TOURNAMENT_TABLE, null, initialValues);
}
//END OF TOURNAMENT TABLE
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
//START OF MY DB HELPER
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(TOURNAMEN_TABLE_CREATE_SQL);
_db.execSQL(GAME_TABLE_CREATE_SQL);
_db.execSQL(PLAYER_TABLE_CREATE_SQL);
_db.execSQL(PLAYER_SET_CREATE_SQL);
_db.execSQL(PLAYER_MOVE_CREATE_SQL);
_db.execSQL(PLAYER_STATS_CREATE_SQL);
_db.execSQL(PLAYER_PLAYERMOVES_CREATE_SQL);
_db.execSQL(PLAYER_ROSTER_CREATE_SQL);
_db.execSQL(TOURNAMENT_PLAYER_CREATE_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int
newVersion) {
Log.w(TAG, "Upgrading application's database from version " +
oldVersion
+ " to " + newVersion + ", which will destroy all old
data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + TOURNAMENT_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + GAME_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + PLAYER_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + SET_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + MOVE_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + STATS_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + PLAYERMOVE_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + PLAYER_ROSTER_TABLE);
_db.execSQL("DROP TABLE IF EXISTS " + TOURNAMENT_PLAYER_TABLE);
// Recreate new database:
onCreate(_db);
}
}
&& // HOW Am i able to store my data INTO MY TOURNAMENT TABLE I CAN'T CALL
THE method open(); top open my database package com.example.beachvolley;
import java.util.ArrayList;
import java.util.Observable;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.provider.OpenableColumns;
public class TournamentModel extends Observable { //NOTE it does not
extend activity only observable
public String TournamentName;// = getTournamentName();
public String TournamentYear;
public String TeamRecorded;
public boolean ToggeTname = true;
public boolean ToggeTyear = true;
public boolean ToggeTteam= true;
public boolean ToggePlayerNames= true;
Player[] ListOfPlayers;
public boolean CheckIfInvalid(String TournamentName, String Year,
String teamName, String FirstName1, String LastName1,String
FirstName2, String LastName2, String FirstName3, String LastName3,
String p1, String p2, String p3 ){
ToggeTname = true;
ToggeTyear = true;
ToggeTteam= true;
if(TournamentName.equals(""))
this.ToggeTname = false;
else
this.ToggeTname = true;
if(Year.equals(""))
this.ToggeTyear = false;
else
this.ToggeTyear = true;
if(teamName.equals(""))
this.ToggeTteam = false;
else
this.ToggeTteam = true;
if(FirstName1.equals("") || LastName1.equals("") ||
FirstName2.equals("") || LastName2.equals("")||
FirstName3.equals("") || LastName3.equals("") || p1.equals("")||
p2.equals("")|| p3.equals(""))
this.ToggePlayerNames = false;
else
this.ToggePlayerNames = true;
triggerObservers();
if(this.ToggeTname && this.ToggeTyear && this.ToggeTteam &&
this.ToggePlayerNames)
return true;
else
return false;
}
public void StoreInputsForTournament(boolean tog , String
TournamentName, String Year, String teamName, ArrayList<Player>
playerList ){
if(tog == true){
//code goes here to STORE INTO THE TOURNAMENT TABLE
}
}
private void triggerObservers() {
setChanged();
notifyObservers();
}
public boolean isToggeTname() {
return ToggeTname;
}
public void setToggeTname(boolean toggeTname) {
ToggeTname = toggeTname;
}
public boolean isToggeTyear() {
return ToggeTyear;
}
public void setToggeTyear(boolean toggeTyear) {
ToggeTyear = toggeTyear;
}
public boolean isToggeTteam() {
return ToggeTteam;
}
public void setToggeTteam(boolean toggeTteam) {
ToggeTteam = toggeTteam;
}
public boolean isToggePlayerNames() {
return ToggePlayerNames;
}
public void setToggePlayerNames(boolean toggePlayerNames) {
ToggePlayerNames = toggePlayerNames;
}
public String getTournamentYear() {
return TournamentYear;
}
public void setTournamentYear(String tournamentYear) {
TournamentYear = tournamentYear;
}
public String getTeamRecorded() {
return TeamRecorded;
}
public void setTeamRecorded(String teamRecorded) {
TeamRecorded = teamRecorded;
}
public String getTournamentName() {
return TournamentName;
}
public void setTournamentName(String tournamentName) {
this.TournamentName = tournamentName;
}
}
Phalcon Devtools 1.2.3: "WebtoolsController handler class cannot be loaded"
Phalcon Devtools 1.2.3: "WebtoolsController handler class cannot be loaded"
I input this:
$ phalcon create-project store --enable-webtools
I get a:
Phalcon DevTools (1.2.3)
Success: Controller "index" was successfully created.
Success: Project "store" was successfully created.
and then when i access: http://localhost/store/webtools
i get a:
"WebtoolsController handler class cannot be loaded"
What's the problem?
I input this:
$ phalcon create-project store --enable-webtools
I get a:
Phalcon DevTools (1.2.3)
Success: Controller "index" was successfully created.
Success: Project "store" was successfully created.
and then when i access: http://localhost/store/webtools
i get a:
"WebtoolsController handler class cannot be loaded"
What's the problem?
Parsing XML issue
Parsing XML issue
I have been trying to parse an XML file and all is going well except for
one thing.
this is what my XML looks like:
<portfolio>
<item>
<image url="http://www.google.com" />
<title>my first title here.</title>
<desc>my first description here...</desc>
<date>15/07/2010</date>
<skills>skills 1, skills 2, skills 3</skills>
</item>
</portfolio>
I have been parsing: title, desc, date, and skills perfectly. The only
issue I am having is parsing the image url. I am using this simple parser:
https://github.com/robertmryan/Simple-XML-Parser
Anyway this is how I am setting up the element names to parse:
parser.elementNames = @[@"image", @"title", @"desc", @"date", @"skills"];
Anyway what do I feed into the element name for the image url based upon
the XML snippet I gave above?
Thanks!
I have been trying to parse an XML file and all is going well except for
one thing.
this is what my XML looks like:
<portfolio>
<item>
<image url="http://www.google.com" />
<title>my first title here.</title>
<desc>my first description here...</desc>
<date>15/07/2010</date>
<skills>skills 1, skills 2, skills 3</skills>
</item>
</portfolio>
I have been parsing: title, desc, date, and skills perfectly. The only
issue I am having is parsing the image url. I am using this simple parser:
https://github.com/robertmryan/Simple-XML-Parser
Anyway this is how I am setting up the element names to parse:
parser.elementNames = @[@"image", @"title", @"desc", @"date", @"skills"];
Anyway what do I feed into the element name for the image url based upon
the XML snippet I gave above?
Thanks!
Inserting multiple checkboxsed into MySQL
Inserting multiple checkboxsed into MySQL
I want to create something like quiz in php and mysql. It's just for fun,
but still, I have a problem with submitting radio inputs. Example of HTML:
<input type="radio" name="news[]"
value="0"><label>Nie</label>
<input type="radio" name="news[]" value="1"><label>Tak</label>
and my SQL is as follows:
$answer1 = $_POST['news'];
$answer2 = $_POST['politics];
mysql_query('INSERT INTO quiz (id, answer1, answer2...) VALUES (null,
$answer1, $answer2...);
It alsways inserts 0, no matter what will I check. I know I cal solve this
by using foreach, but this will - I think - create multiple INSERT
statements.
I want to create something like quiz in php and mysql. It's just for fun,
but still, I have a problem with submitting radio inputs. Example of HTML:
<input type="radio" name="news[]"
value="0"><label>Nie</label>
<input type="radio" name="news[]" value="1"><label>Tak</label>
and my SQL is as follows:
$answer1 = $_POST['news'];
$answer2 = $_POST['politics];
mysql_query('INSERT INTO quiz (id, answer1, answer2...) VALUES (null,
$answer1, $answer2...);
It alsways inserts 0, no matter what will I check. I know I cal solve this
by using foreach, but this will - I think - create multiple INSERT
statements.
How can i access to a textbox in MainWindow from another form, without creating an instace of it in a WPF?
How can i access to a textbox in MainWindow from another form, without
creating an instace of it in a WPF?
private void btnConfirmInMyForm_Click(object sender, RoutedEventArgs e)
{
//for example without creating like this
MainWindow mainWin = new MainWindow();
mainWin.txtBirthDate.Text = "anything";
this.close();
}
when i try the above, content of the txtBirthDate of new instance of
MainWindow (mianWin) changes to "anything", but not in current MainWindow!
in other words as i click btnConfirmInMyForm in MyForm it opens a new
MainWindow with the txtBirthDate textBox contains "anything", which i
don't want! i only want to set the txtBirthDate from MyForm, not to create
a new MainWindow that contains this!
with best regards
creating an instace of it in a WPF?
private void btnConfirmInMyForm_Click(object sender, RoutedEventArgs e)
{
//for example without creating like this
MainWindow mainWin = new MainWindow();
mainWin.txtBirthDate.Text = "anything";
this.close();
}
when i try the above, content of the txtBirthDate of new instance of
MainWindow (mianWin) changes to "anything", but not in current MainWindow!
in other words as i click btnConfirmInMyForm in MyForm it opens a new
MainWindow with the txtBirthDate textBox contains "anything", which i
don't want! i only want to set the txtBirthDate from MyForm, not to create
a new MainWindow that contains this!
with best regards
weird issue when sorting MySQL `date` results
weird issue when sorting MySQL `date` results
I'm getting some weird results when I query on of my tables to show
upcoming birthdays (schema and query below), and then sort by date with
the upcoming dates first. The type for the dob (date of birth) field is
date with the format 0000-00-00
I'm using the below schema:
People:
+------------+-------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra
|
+------------+-------------+------+-----+-------------------+----------------+
| id | int(11) | NO | PRI | NULL |
auto_increment |
| fname | varchar(32) | NO | | NULL |
|
| lname | varchar(32) | NO | | NULL |
|
| dob | date | NO | | 0000-00-00 |
|
| license_no | varchar(24) | NO | | NULL |
|
| date_added | timestamp | NO | | CURRENT_TIMESTAMP |
|
| status | varchar(8) | NO | | Allow |
|
+------------+-------------+------+-----+-------------------+----------------+
and here's my query, as it's called from PHP:
<?php
/* This will give us upcoming dobs for the next 2 weeks */
$con = connect_db();
// grab any dobs coming up in the next week and sort them by what's
//coming up first
//if they are born on Feb. 29th, it will fall on March 1st
$query = 'select p.lname, p.fname, u.number, p.dob ' .
'from people p, units u where p.id = u.resident and ' .
'DAYOFYEAR(curdate()) <= DAYOFYEAR(DATE_ADD(dob, INTERVAL ' .
'(YEAR(NOW()) - YEAR(dob)) YEAR)) AND DAYOFYEAR(curdate()) +30 >=
' .
'dayofyear(`dob`) order by dayofyear(dob) limit 7;';
$result = mysqli_query($con, $query);
if (!empty($result)) {
while($row = mysqli_fetch_array($result)) {
$fname = $row['fname'];
$lname = $row['lname'];
$number = $row['number'];
$dob = date("m-d", strtotime($row['dob']));
if($dob == date("m-d")) {
$dob = 'Today!';
printf('%s, %s</br>Unit: %s</br>%s</br></br>',
$lname,
$fname, $number, $dob);
} else {
printf('%s, %s</br>Unit: %s</br>Date:
%s</br></br>', $lname,
$fname, $number, $dob);
}
}
}
?>
here's an example of the returned query:
Name, Name
Unit: 110
Date: 09-11
Name2, Name2
Unit: 434
Date: 09-10
As you can see, the order is wrong!
EDIT - Now I've noticed that the records in question (the two dates above)
are not ordered correctly ever in MySQL!
One of the full dates is: 1950-09-11 and the other is: 1956-09-10
I've looked through those two records and haven't found any mangled data,
so I'm pretty confused as to why this is happening
I'm getting some weird results when I query on of my tables to show
upcoming birthdays (schema and query below), and then sort by date with
the upcoming dates first. The type for the dob (date of birth) field is
date with the format 0000-00-00
I'm using the below schema:
People:
+------------+-------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra
|
+------------+-------------+------+-----+-------------------+----------------+
| id | int(11) | NO | PRI | NULL |
auto_increment |
| fname | varchar(32) | NO | | NULL |
|
| lname | varchar(32) | NO | | NULL |
|
| dob | date | NO | | 0000-00-00 |
|
| license_no | varchar(24) | NO | | NULL |
|
| date_added | timestamp | NO | | CURRENT_TIMESTAMP |
|
| status | varchar(8) | NO | | Allow |
|
+------------+-------------+------+-----+-------------------+----------------+
and here's my query, as it's called from PHP:
<?php
/* This will give us upcoming dobs for the next 2 weeks */
$con = connect_db();
// grab any dobs coming up in the next week and sort them by what's
//coming up first
//if they are born on Feb. 29th, it will fall on March 1st
$query = 'select p.lname, p.fname, u.number, p.dob ' .
'from people p, units u where p.id = u.resident and ' .
'DAYOFYEAR(curdate()) <= DAYOFYEAR(DATE_ADD(dob, INTERVAL ' .
'(YEAR(NOW()) - YEAR(dob)) YEAR)) AND DAYOFYEAR(curdate()) +30 >=
' .
'dayofyear(`dob`) order by dayofyear(dob) limit 7;';
$result = mysqli_query($con, $query);
if (!empty($result)) {
while($row = mysqli_fetch_array($result)) {
$fname = $row['fname'];
$lname = $row['lname'];
$number = $row['number'];
$dob = date("m-d", strtotime($row['dob']));
if($dob == date("m-d")) {
$dob = 'Today!';
printf('%s, %s</br>Unit: %s</br>%s</br></br>',
$lname,
$fname, $number, $dob);
} else {
printf('%s, %s</br>Unit: %s</br>Date:
%s</br></br>', $lname,
$fname, $number, $dob);
}
}
}
?>
here's an example of the returned query:
Name, Name
Unit: 110
Date: 09-11
Name2, Name2
Unit: 434
Date: 09-10
As you can see, the order is wrong!
EDIT - Now I've noticed that the records in question (the two dates above)
are not ordered correctly ever in MySQL!
One of the full dates is: 1950-09-11 and the other is: 1956-09-10
I've looked through those two records and haven't found any mangled data,
so I'm pretty confused as to why this is happening
Saturday, 17 August 2013
nodejs stdin readable event not triggered
nodejs stdin readable event not triggered
The readable event is not triggered in the process.stdin
test.js
var self = process.stdin, data ;
self.on('readable', function() {
var chunk = this.read();
if (chunk === null) {
handleArguments();
} else {
data += chunk;
}
});
self.on('end', function() {
console.log("end event",data )
});
Then when i do node test.jsand start typing the in the console, the
readable event is not triggered at all.
Please tell me how to attach readable listener to process.stdin stream.
The readable event is not triggered in the process.stdin
test.js
var self = process.stdin, data ;
self.on('readable', function() {
var chunk = this.read();
if (chunk === null) {
handleArguments();
} else {
data += chunk;
}
});
self.on('end', function() {
console.log("end event",data )
});
Then when i do node test.jsand start typing the in the console, the
readable event is not triggered at all.
Please tell me how to attach readable listener to process.stdin stream.
Java Chat - How to client can listen continuously from the server
Java Chat - How to client can listen continuously from the server
I'm working on a university project were I was asked to create a java chat
using sockets and other java features. I have managed to complete
basically the whole assignment (but the GUI part, and that's what I'm
working on now) and I'm having issues when I want the client to
continuously listen to the server, I cannot make all the clients to
receive message from the server (Like a broadcast feature). So if I want
the server to send a message to the clients who are online, they do not
get the message, so the clients are not Listening to the server all time,
and that's where I am stuck. Below my code, so do you have any idea how I
can program this or do you have any suggestion(s)?
You may ignore the comments in Spanish, those are my notes about the code
itself.
Client Classes /* * To change this template, choose Tools | Templates *
and open the template in the editor. */ package vmatesclientv2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Inet4Address;
import java.net.Socket;
import javax.swing.JOptionPane;
/**
*
* @author murillke
*/
public class Client {
private Socket client;
private ObjectOutputStream out;
private ObjectInputStream in;
private BufferedReader In;
private String serverIP;
private String nombre;
private String email;
private String MSG;
public static int user_ID;
public static int room_ID;
public static boolean admin = false;
public Client() throws IOException {
connectToServer();
startStreams();
new ListenServer(client, in, out, In).start();
}
private void connectToServer() throws IOException {
serverIP = "127.0.0.1";
System.out.println("Iniciando coneccion con el servidor");
client = new Socket(serverIP, 28001);
System.out.println("Conectado con el servidor");
}
private void startStreams() throws IOException {
out = new ObjectOutputStream(client.getOutputStream());
in = new ObjectInputStream(client.getInputStream());
In = new BufferedReader(new
InputStreamReader(client.getInputStream()));
}
// Formato de mensaje:"REGISTER_TYPE"+" "+"Name"+" "+"email"+"
"+"USER_ID"+" "+"ROOM_ID"+"MSG";
public void menu() {
// Listen listen = new Listen(socket);//PREGUNTAR AL PROFESOR COMO
HACE EL CLIENTE PARA RECIBIR LOS MENSAJES
// listen.start();
int tipo = Integer.parseInt(JOptionPane.showInputDialog("Client "
+ admin
+ "\n 1) REGISTER_REQUEST"
+ "\n 2) NEW_ROOM"
+ "\n 3) JOIN_ROOM"
+ "\n 4) SEND_MSG"
+ "\n 5) REMOVE_MATE"
+ "\n 6) FILE_TRANSFER"));
switch (tipo) {
case (1):
REGISTER_REQUEST();
menu();
break;
case (2):
NEW_ROOM();
menu();
break;
case (3):
room_ID =
Integer.parseInt(JOptionPane.showInputDialog("Room ID"));
JOIN_ROOM("Kevin", "kevin@test.com", room_ID);
break;
case (4):
SEND_MSG(JOptionPane.showInputDialog("Mensaje"));
menu();
break;
case (5):
String removeValue = JOptionPane.showInputDialog("removal
criteria (NICK/ID)");
REMOVE_MATE(removeValue);
menu();
break;
case (6):
break;
}
}
public void REGISTER_REQUEST() {
nombre = "Georgie";
email = "email@test.com";
try {
String text = "REGISTER_REQUEST" + " " + nombre + " " + email
+ " " + "null" + " " + "null" + " " + "null";
out.writeUTF(text);
out.flush();
} catch (IOException ex) {
}
}
public void NEW_ROOM() {
nombre = "Georgie";
email = "email@test.com";
try {
String text = "NEW_ROOM" + " " + nombre + " " + email + " " +
"null" + " " + "null" + " " + "null";
out.writeUTF(text);
out.flush();
admin = true;
} catch (IOException ex) {
}
}
// Formato de mensaje:"REQUEST_TYPE"+" "+"Name"+" "+"email"+"
"+"USER_ID"+" "+"ROOM_ID"+"MSG";
public void JOIN_ROOM(String Nombre, String Email, int ROOM_ID) {
try {
String text = "JOIN_ROOM" + " " + Nombre + " " + Email + " " +
"null" + " " + ROOM_ID + " " + "null";
out.writeUTF(text);
out.flush();
} catch (IOException ex) {
}
}
public void REMOVE_MATE(String removeValue) {
try {
if (admin == true) {
String text = "REMOVE_MATE" + " " + removeValue + " " +
"null" + " " + "null" + " " + room_ID + " " + "null";
out.writeUTF(text);
out.flush();
} else {
System.out.println("No puede remover usuarios");
}
} catch (IOException ex) {
}
}
public void SEND_MSG(String msg) {
System.out.println("" + room_ID);
System.out.println("Enviando mensaje");
try {
String text = "SEND_MSG" + " " + "null" + " " + "null" + " " +
user_ID + " " + room_ID + " " + msg;
System.out.println("Enviando: ***" + text + "***");
out.writeUTF(text);
out.flush();
System.out.println("Mensaje enviado");
} catch (IOException ex) {
}
}
public void FILE_TRANSFER(String msg) {
try {
String text = "FILE_TRANSFER" + " " + "null" + " " + "null" +
" " + user_ID + " " + room_ID + " " + msg;
String path = JOptionPane.showInputDialog("Ingrese el path del
archivo a enviar: ");
String userToSend = JOptionPane.showInputDialog("Ingrese
usuario al que desee enviar el archivo: ");
out.writeUTF(text);
out.flush();
} catch (IOException ex) {
}
}
}//FIN DE CLASE
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesclientv2;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author murillke
*/
public class ListenServer extends Thread {
private Socket client;
private ObjectInputStream in;
private ObjectOutputStream out;
private BufferedReader In;
// private int ID;
// private int room_ID;
// private boolean admin = false;
public ListenServer(Socket client, ObjectInputStream in,
ObjectOutputStream out, BufferedReader In) {
this.client = client;
this.in = in;
this.out = out;
this.In = In;
}
@Override
public void run() {
DataInputStream IN = null;
try {
IN = new DataInputStream(client.getInputStream());
while (true) {
String data = "";
try {
// data =in.readUTF();
data = IN.readUTF();
System.out.println("Recibido: " + data);
} catch (IOException ex) {
Logger.getLogger(ListenServer.class.getName()).log(Level.SEVERE,
null, ex);
}
String[] msg_parts = data.split(" ", 3);
String msg_type = msg_parts[0];
switch (msg_type) {
case "MSG":
System.out.println(msg_parts[0]);
System.out.println(msg_parts[1]);
break;
case "ROOM_&_ID":
System.out.println("ROOM_ID & User_ID recibido");
if (!"null".equals(msg_parts[1])) {
Client.room_ID = Integer.parseInt(msg_parts[1]);
}
Client.user_ID = Integer.parseInt(msg_parts[2]);
System.out.println(Client.room_ID);
System.out.println(Client.user_ID);
break;
case "SET_TO_ADMIN":
System.out.println("This Client is now ADMIN");
Client.admin = true;
break;
}
}
} catch (IOException ex) {
Logger.getLogger(ListenServer.class.getName()).log(Level.SEVERE,
null, ex);
} finally {
try {
IN.close();
} catch (IOException ex) {
Logger.getLogger(ListenServer.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesclientv2;
import java.io.IOException;
/**
*
* @author murillke
*/
public class VMatesClientV2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
Client client = new Client();
client.menu();
}
}
Server Classes
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesserver;
/**
*
* @author murillke
*/
public class Celda {
private clientThreadServer info;
private Celda next;
private Celda previous;
public Celda getPrevious() {
return previous;
}
public void setPrevious(Celda previous) {
this.previous = previous;
}
public Celda(clientThreadServer info) {
this.info = info;
}
public clientThreadServer getInfo() {
return info;
}
public void setInfo(clientThreadServer info) {
this.info = info;
}
public Celda getNext() {
return next;
}
public void setNext(Celda next) {
this.next = next;
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesserver;
/**
*
* @author murillke
*/
public class Lista {
public Celda cabeza;
public Lista() {
cabeza = null;
}
public void inserta(clientThreadServer client) {
if (cabeza == null) { // si la lista está vacia
cabeza = new Celda(client);
} else if (client.getId() < cabeza.getInfo().getId()) { // si
debo insertar a la izquierda de cabeza
Celda aux = new Celda(client);
aux.setNext(cabeza);
cabeza = aux;
} else if (cabeza.getNext() == null) { // si sòlo tiene uno y
debo insertar a la derecha
Celda aux = new Celda(client);
cabeza.setNext(aux);
} else { // hay màs de uno y debemos insertar en medio o al final
Celda actual = cabeza;
while (actual.getNext() != null
&& actual.getNext().getInfo().getId() < client.getId()) {
actual = actual.getNext();
}
Celda aux = new Celda(client);
aux.setNext(actual.getNext());
actual.setNext(aux);
}
}
public boolean existe(int id) {
Celda aux = cabeza;
while (aux != null && aux.getInfo().getId() < id) {
aux = aux.getNext();
}
return (aux != null && aux.getInfo().getId() == id);
}
public clientThreadServer recupera(int id) {
Celda aux = cabeza;
while (aux != null && aux.getInfo().getId() < id) {
aux = aux.getNext();
}
if (aux != null && aux.getInfo().getId() == id) {
return aux.getInfo();
} else {
return null;
}
}
// public clientThreadServer recupera() {
// Celda aux = cabeza;
// while (aux != null) {
// return aux.getInfo();
// aux = aux.getNext();
// }
//
// }
public void elimina(int id) {
Celda aux = cabeza; //se fija el auxiliar como la cabeza
if (aux.getInfo().getId() == id) { //Si id ingresado por el
usuario es igual al que esta en la lista
cabeza = aux.getNext();
}
while (aux != null && aux.getNext() != null &&
aux.getInfo().getId() != id) { //Si id ingresado por el usuario no
es igual al que esta en la lista
if (aux.getNext().getInfo().getId() == id) { //Mientras que
sea igual, asigne la variable elimina
Celda elimina; //variable tipo celda
elimina = aux; //igualar la variable tipo celda con el
auxiliar
aux = aux.getNext();
elimina.setNext(aux.getNext()); //Asignar el valor de
elimina igual al siguiente para q no se imprima.
} else {
aux = aux.getNext(); //Si no se cumple, sigue buscando...
}
}
}
public void elimina(String NICK) {
Celda aux = cabeza; //se fija el auxiliar como la cabeza
if (aux.getInfo().getNICK().equals(NICK)) { //Si id ingresado por
el usuario es igual al que esta en la lista
cabeza = aux.getNext();
}
while (aux != null && aux.getNext() != null &&
!aux.getInfo().getNICK().equals(NICK)) { //Si id ingresado por el
usuario no es igual al que esta en la lista
if (aux.getNext().getInfo().getNICK().equals(NICK)) {
//Mientras que sea igual, asigne la variable elimina
Celda elimina; //variable tipo celda
elimina = aux; //igualar la variable tipo celda con el
auxiliar
aux = aux.getNext();
elimina.setNext(aux.getNext()); //Asignar el valor de
elimina igual al siguiente para q no se imprima.
} else {
aux = aux.getNext(); //Si no se cumple, sigue buscando...
}
}
}
// public void modifica(int id, String nombre) {
// //Taller
// Celda aux = cabeza; //se fija el auxiliar como la cabeza
// while (aux != null && aux.getInfo().getId() < id) { //Si id
ingresado por el usuario es menor al que esta en la lista
// aux = aux.getNext(); //asignarle un valor a aux
// }
// if (aux != null && aux.getInfo().getId() == id) {//Si id
ingresado por el usuario es igual al que esta en la lista
// clientThreadServer cambio; //varible tipo persona
// cambio= aux.getInfo(); // se iguala la variable tipo persona
// cambio.setNombre(nombre); // se hace el cambio al nuevo nombre
// }
// }
public clientThreadServer extrae(int id) {
//Taller
Celda aux = cabeza; //se fija el auxiliar como la cabeza
if (aux.getInfo().getId() == id) { //Si id ingresado por el
usuario es igual al que esta en la lista se asigna al siguiente
cabeza = aux.getNext(); //metodo para asignar al siguiente
}
while (aux != null && aux.getNext() != null &&
aux.getInfo().getId() != id) { //Si id ingresado por el usuario no
es igual al que esta en la lista
if (aux.getNext().getInfo().getId() == id) { //Si el valor id
es igual a algun valor en la lista
Celda elimina; //variable tipo celda
elimina = aux; // varible tipo celda es igual al auxiliar
aux = aux.getNext(); // obtener el siguiente elemento de
la lista
elimina.setNext(aux.getNext()); //
} else {
aux = aux.getNext(); //De lo contrario siga buscando
}
} //Si hay elementos que coinciden, entonces se extraen y luego
con el return siguiente se devuelve a la lista
return aux.getInfo();
}
@Override
public String toString() {
String s = "Room Mates ";
Celda aux = cabeza;
while (aux != null) {
s += aux.getInfo() + ", ";
aux = aux.getNext();
}
return s;
}
public void sendMessages(String msg) {
Celda aux = cabeza;
while (aux != null) {
aux.getInfo().sendBackClient(msg);
aux = aux.getNext();
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesserver;
public class Room implements Runnable {
private int ROOM_ID = 0;//ID para ingresar al ROOM
private Lista L = new Lista();
public Room(clientThreadServer client) {
if (ROOM_ID == 0) {
ROOM_ID = generaRoomID();
}
L.inserta(client);
System.out.println(L);
}
@Override
public void run() {
while (true) {
}
}
private int generaRoomID() {
return Static.ROOM_ID = Static.ROOM_ID + (int) (Math.random() * 500);
}
@Override
public String toString() {
return "ROOM_ID=" + ROOM_ID;
}
public int getROOM_ID() {
return ROOM_ID;
}
public Lista getL() {
return L;
}
}//CLASS END
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesserver;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server {
// static final String REGISTER_REQUEST = "REGISTER_REQUEST";
// static final String NEW_ROOM = "NEW_ROOM";
// static final String JOIN_ROOM = "JOIN_ROOM";
// static final String REMOVE_MATE = "REMOVE_MATE";
// static final String FILE_TRANSFER = "FILE_TRANSFER";
// static final String MSG = "MSG";
// static int ROOM_ID = 22222;
// static int CLIENT_ID=1;
// static List<Room> Rooms;
// static clientThreadServer cliente;
private ServerSocket server;
public Server() {
try {
server = new ServerSocket(28001);
} catch (IOException ex) {
}
}
public void accept() {
while (true) {
try {
Static.cliente = new clientThreadServer(server.accept());
Static.cliente.start();
} catch (IOException ex) {
}
}
}
}
package vmatesserver;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author murillke
*/
public class Static {
static final String REGISTER_REQUEST = "REGISTER_REQUEST";
static final String NEW_ROOM = "NEW_ROOM";
static final String JOIN_ROOM = "JOIN_ROOM";
static final String REMOVE_MATE = "REMOVE_MATE";
static final String FILE_TRANSFER = "FILE_TRANSFER";
static final String MSG = "MSG";
static final String SEND_MSG = "SEND_MSG";
static int ROOM_ID = 22222;
static int CLIENT_ID=1;
static List<Room> Rooms = new ArrayList<Room>();
static List<Byte> User;
static clientThreadServer cliente;
static Lista lista;
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesserver;
/**
*
* @author murillke
*/
public class VMatesServer {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Server S = new Server();
S.accept();
}
}
package vmatesserver;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class clientThreadServer extends Thread {
private Socket socket;
private ObjectInputStream in;
private ObjectOutputStream out;
private String NICK;
private String email;
private int ID;
public clientThreadServer(final Socket socket) {
this.socket = socket;
startStreams();
}
public void sendBackClient(String msg) {
try {
System.out.println("Enviando mensaje a " + NICK + ": " + msg);
out.writeUTF(msg);
} catch (IOException ex) {
Logger.getLogger(clientThreadServer.class.getName()).log(Level.SEVERE,
null, ex);
}
}
private void startStreams() {
try {
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException ex) {
}
}
@Override
public String toString() {
return "NICK= " + NICK + ", email= " + email + ", ID= " + ID;
}
// Formato de mensaje:"REGISTER_TYPE"+" "+"Name"+" "+"email"+"
"+"USER_ID"+" "+"ROOM_ID"+"MSG";
@Override
public void run() {
while (true) {
try {
String data = in.readUTF();
String[] msg_parts = data.split(" ", 6);
String msg_type = msg_parts[0];
switch (msg_type) {
case Static.MSG:
break;
case Static.REGISTER_REQUEST:
generaClientID();
NICK = msg_parts[1];
email = msg_parts[2];
out.writeUTF("MSG Server_found");
out.flush();
System.out.println(msg_parts[1] + " has registered");
break;
case Static.NEW_ROOM:
System.out.println("New Room has been requested");
generaClientID();
NICK = msg_parts[1];
email = msg_parts[2];
Room room = new Room(this);
(new Thread(room)).start();
Static.Rooms.add(room);
out.writeUTF("ROOM_&_ID" + " " + Static.ROOM_ID +
" " + Static.CLIENT_ID);
out.flush();
for (int i = 0; i < Static.Rooms.size(); i++) {
System.out.println(Static.Rooms.get(i).getROOM_ID());
}
// out.writeUTF("ROOM_&_ID" + " " + Static.ROOM_ID
+ " " + Static.CLIENT_ID);
// out.flush();
break;
case Static.SEND_MSG:
for (int i = 0; i < Static.Rooms.size(); i++) {
System.out.println("From List " +
Static.Rooms.get(i).getROOM_ID());
System.out.println("From Client " +
Integer.parseInt(msg_parts[4]));
if (Static.Rooms.get(i).getROOM_ID() ==
Integer.parseInt(msg_parts[4])) {
System.err.println("Sala encontrada");
Static.Rooms.get(i).getL().sendMessages(msg_parts[5]);
}
}
break;
case Static.JOIN_ROOM:
for (int i = 0; i < Static.Rooms.size(); i++) {
if (Static.Rooms.get(i).getROOM_ID() ==
Integer.parseInt(msg_parts[4])) {
generaClientID();
NICK = msg_parts[1];
email = msg_parts[2];
Static.Rooms.get(i).getL().inserta(this);
out.writeUTF("ROOM_&_ID" + " " + "null" +
" " + Static.CLIENT_ID);
out.flush();
System.out.println(Static.Rooms.get(i).getL());
}
}
break;
case Static.REMOVE_MATE:
for (int i = 0; i < Static.Rooms.size(); i++) {
if (Static.Rooms.get(i).getROOM_ID() ==
Integer.parseInt(msg_parts[4])) {
Static.Rooms.get(i).getL().elimina(Integer.parseInt(msg_parts[1]));
System.out.println(Static.Rooms.get(i).getL());
}
}
break;
case Static.FILE_TRANSFER:
for (int i = 0; i < Static.Rooms.size(); i++) {
}
break;
// if (data.length() > 0) {
//// for (int i = 0; i < Server.Users.size(); i++) {
//// Server.Users.get(i).out.writeUTF(data);
//// Server.Users.get(i).out.flush();
//// }
// System.out.println(data);
}
sleep(800);
} catch (IOException ex) {
} catch (InterruptedException ex) {
}
}
}
private void generaClientID() {
Static.CLIENT_ID = Static.CLIENT_ID + 1;
ID = Static.CLIENT_ID;
}
public String getNICK() {
return NICK;
}
public void setNICK(String NICK) {
this.NICK = NICK;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
}
I'm working on a university project were I was asked to create a java chat
using sockets and other java features. I have managed to complete
basically the whole assignment (but the GUI part, and that's what I'm
working on now) and I'm having issues when I want the client to
continuously listen to the server, I cannot make all the clients to
receive message from the server (Like a broadcast feature). So if I want
the server to send a message to the clients who are online, they do not
get the message, so the clients are not Listening to the server all time,
and that's where I am stuck. Below my code, so do you have any idea how I
can program this or do you have any suggestion(s)?
You may ignore the comments in Spanish, those are my notes about the code
itself.
Client Classes /* * To change this template, choose Tools | Templates *
and open the template in the editor. */ package vmatesclientv2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Inet4Address;
import java.net.Socket;
import javax.swing.JOptionPane;
/**
*
* @author murillke
*/
public class Client {
private Socket client;
private ObjectOutputStream out;
private ObjectInputStream in;
private BufferedReader In;
private String serverIP;
private String nombre;
private String email;
private String MSG;
public static int user_ID;
public static int room_ID;
public static boolean admin = false;
public Client() throws IOException {
connectToServer();
startStreams();
new ListenServer(client, in, out, In).start();
}
private void connectToServer() throws IOException {
serverIP = "127.0.0.1";
System.out.println("Iniciando coneccion con el servidor");
client = new Socket(serverIP, 28001);
System.out.println("Conectado con el servidor");
}
private void startStreams() throws IOException {
out = new ObjectOutputStream(client.getOutputStream());
in = new ObjectInputStream(client.getInputStream());
In = new BufferedReader(new
InputStreamReader(client.getInputStream()));
}
// Formato de mensaje:"REGISTER_TYPE"+" "+"Name"+" "+"email"+"
"+"USER_ID"+" "+"ROOM_ID"+"MSG";
public void menu() {
// Listen listen = new Listen(socket);//PREGUNTAR AL PROFESOR COMO
HACE EL CLIENTE PARA RECIBIR LOS MENSAJES
// listen.start();
int tipo = Integer.parseInt(JOptionPane.showInputDialog("Client "
+ admin
+ "\n 1) REGISTER_REQUEST"
+ "\n 2) NEW_ROOM"
+ "\n 3) JOIN_ROOM"
+ "\n 4) SEND_MSG"
+ "\n 5) REMOVE_MATE"
+ "\n 6) FILE_TRANSFER"));
switch (tipo) {
case (1):
REGISTER_REQUEST();
menu();
break;
case (2):
NEW_ROOM();
menu();
break;
case (3):
room_ID =
Integer.parseInt(JOptionPane.showInputDialog("Room ID"));
JOIN_ROOM("Kevin", "kevin@test.com", room_ID);
break;
case (4):
SEND_MSG(JOptionPane.showInputDialog("Mensaje"));
menu();
break;
case (5):
String removeValue = JOptionPane.showInputDialog("removal
criteria (NICK/ID)");
REMOVE_MATE(removeValue);
menu();
break;
case (6):
break;
}
}
public void REGISTER_REQUEST() {
nombre = "Georgie";
email = "email@test.com";
try {
String text = "REGISTER_REQUEST" + " " + nombre + " " + email
+ " " + "null" + " " + "null" + " " + "null";
out.writeUTF(text);
out.flush();
} catch (IOException ex) {
}
}
public void NEW_ROOM() {
nombre = "Georgie";
email = "email@test.com";
try {
String text = "NEW_ROOM" + " " + nombre + " " + email + " " +
"null" + " " + "null" + " " + "null";
out.writeUTF(text);
out.flush();
admin = true;
} catch (IOException ex) {
}
}
// Formato de mensaje:"REQUEST_TYPE"+" "+"Name"+" "+"email"+"
"+"USER_ID"+" "+"ROOM_ID"+"MSG";
public void JOIN_ROOM(String Nombre, String Email, int ROOM_ID) {
try {
String text = "JOIN_ROOM" + " " + Nombre + " " + Email + " " +
"null" + " " + ROOM_ID + " " + "null";
out.writeUTF(text);
out.flush();
} catch (IOException ex) {
}
}
public void REMOVE_MATE(String removeValue) {
try {
if (admin == true) {
String text = "REMOVE_MATE" + " " + removeValue + " " +
"null" + " " + "null" + " " + room_ID + " " + "null";
out.writeUTF(text);
out.flush();
} else {
System.out.println("No puede remover usuarios");
}
} catch (IOException ex) {
}
}
public void SEND_MSG(String msg) {
System.out.println("" + room_ID);
System.out.println("Enviando mensaje");
try {
String text = "SEND_MSG" + " " + "null" + " " + "null" + " " +
user_ID + " " + room_ID + " " + msg;
System.out.println("Enviando: ***" + text + "***");
out.writeUTF(text);
out.flush();
System.out.println("Mensaje enviado");
} catch (IOException ex) {
}
}
public void FILE_TRANSFER(String msg) {
try {
String text = "FILE_TRANSFER" + " " + "null" + " " + "null" +
" " + user_ID + " " + room_ID + " " + msg;
String path = JOptionPane.showInputDialog("Ingrese el path del
archivo a enviar: ");
String userToSend = JOptionPane.showInputDialog("Ingrese
usuario al que desee enviar el archivo: ");
out.writeUTF(text);
out.flush();
} catch (IOException ex) {
}
}
}//FIN DE CLASE
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesclientv2;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author murillke
*/
public class ListenServer extends Thread {
private Socket client;
private ObjectInputStream in;
private ObjectOutputStream out;
private BufferedReader In;
// private int ID;
// private int room_ID;
// private boolean admin = false;
public ListenServer(Socket client, ObjectInputStream in,
ObjectOutputStream out, BufferedReader In) {
this.client = client;
this.in = in;
this.out = out;
this.In = In;
}
@Override
public void run() {
DataInputStream IN = null;
try {
IN = new DataInputStream(client.getInputStream());
while (true) {
String data = "";
try {
// data =in.readUTF();
data = IN.readUTF();
System.out.println("Recibido: " + data);
} catch (IOException ex) {
Logger.getLogger(ListenServer.class.getName()).log(Level.SEVERE,
null, ex);
}
String[] msg_parts = data.split(" ", 3);
String msg_type = msg_parts[0];
switch (msg_type) {
case "MSG":
System.out.println(msg_parts[0]);
System.out.println(msg_parts[1]);
break;
case "ROOM_&_ID":
System.out.println("ROOM_ID & User_ID recibido");
if (!"null".equals(msg_parts[1])) {
Client.room_ID = Integer.parseInt(msg_parts[1]);
}
Client.user_ID = Integer.parseInt(msg_parts[2]);
System.out.println(Client.room_ID);
System.out.println(Client.user_ID);
break;
case "SET_TO_ADMIN":
System.out.println("This Client is now ADMIN");
Client.admin = true;
break;
}
}
} catch (IOException ex) {
Logger.getLogger(ListenServer.class.getName()).log(Level.SEVERE,
null, ex);
} finally {
try {
IN.close();
} catch (IOException ex) {
Logger.getLogger(ListenServer.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesclientv2;
import java.io.IOException;
/**
*
* @author murillke
*/
public class VMatesClientV2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
Client client = new Client();
client.menu();
}
}
Server Classes
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesserver;
/**
*
* @author murillke
*/
public class Celda {
private clientThreadServer info;
private Celda next;
private Celda previous;
public Celda getPrevious() {
return previous;
}
public void setPrevious(Celda previous) {
this.previous = previous;
}
public Celda(clientThreadServer info) {
this.info = info;
}
public clientThreadServer getInfo() {
return info;
}
public void setInfo(clientThreadServer info) {
this.info = info;
}
public Celda getNext() {
return next;
}
public void setNext(Celda next) {
this.next = next;
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesserver;
/**
*
* @author murillke
*/
public class Lista {
public Celda cabeza;
public Lista() {
cabeza = null;
}
public void inserta(clientThreadServer client) {
if (cabeza == null) { // si la lista está vacia
cabeza = new Celda(client);
} else if (client.getId() < cabeza.getInfo().getId()) { // si
debo insertar a la izquierda de cabeza
Celda aux = new Celda(client);
aux.setNext(cabeza);
cabeza = aux;
} else if (cabeza.getNext() == null) { // si sòlo tiene uno y
debo insertar a la derecha
Celda aux = new Celda(client);
cabeza.setNext(aux);
} else { // hay màs de uno y debemos insertar en medio o al final
Celda actual = cabeza;
while (actual.getNext() != null
&& actual.getNext().getInfo().getId() < client.getId()) {
actual = actual.getNext();
}
Celda aux = new Celda(client);
aux.setNext(actual.getNext());
actual.setNext(aux);
}
}
public boolean existe(int id) {
Celda aux = cabeza;
while (aux != null && aux.getInfo().getId() < id) {
aux = aux.getNext();
}
return (aux != null && aux.getInfo().getId() == id);
}
public clientThreadServer recupera(int id) {
Celda aux = cabeza;
while (aux != null && aux.getInfo().getId() < id) {
aux = aux.getNext();
}
if (aux != null && aux.getInfo().getId() == id) {
return aux.getInfo();
} else {
return null;
}
}
// public clientThreadServer recupera() {
// Celda aux = cabeza;
// while (aux != null) {
// return aux.getInfo();
// aux = aux.getNext();
// }
//
// }
public void elimina(int id) {
Celda aux = cabeza; //se fija el auxiliar como la cabeza
if (aux.getInfo().getId() == id) { //Si id ingresado por el
usuario es igual al que esta en la lista
cabeza = aux.getNext();
}
while (aux != null && aux.getNext() != null &&
aux.getInfo().getId() != id) { //Si id ingresado por el usuario no
es igual al que esta en la lista
if (aux.getNext().getInfo().getId() == id) { //Mientras que
sea igual, asigne la variable elimina
Celda elimina; //variable tipo celda
elimina = aux; //igualar la variable tipo celda con el
auxiliar
aux = aux.getNext();
elimina.setNext(aux.getNext()); //Asignar el valor de
elimina igual al siguiente para q no se imprima.
} else {
aux = aux.getNext(); //Si no se cumple, sigue buscando...
}
}
}
public void elimina(String NICK) {
Celda aux = cabeza; //se fija el auxiliar como la cabeza
if (aux.getInfo().getNICK().equals(NICK)) { //Si id ingresado por
el usuario es igual al que esta en la lista
cabeza = aux.getNext();
}
while (aux != null && aux.getNext() != null &&
!aux.getInfo().getNICK().equals(NICK)) { //Si id ingresado por el
usuario no es igual al que esta en la lista
if (aux.getNext().getInfo().getNICK().equals(NICK)) {
//Mientras que sea igual, asigne la variable elimina
Celda elimina; //variable tipo celda
elimina = aux; //igualar la variable tipo celda con el
auxiliar
aux = aux.getNext();
elimina.setNext(aux.getNext()); //Asignar el valor de
elimina igual al siguiente para q no se imprima.
} else {
aux = aux.getNext(); //Si no se cumple, sigue buscando...
}
}
}
// public void modifica(int id, String nombre) {
// //Taller
// Celda aux = cabeza; //se fija el auxiliar como la cabeza
// while (aux != null && aux.getInfo().getId() < id) { //Si id
ingresado por el usuario es menor al que esta en la lista
// aux = aux.getNext(); //asignarle un valor a aux
// }
// if (aux != null && aux.getInfo().getId() == id) {//Si id
ingresado por el usuario es igual al que esta en la lista
// clientThreadServer cambio; //varible tipo persona
// cambio= aux.getInfo(); // se iguala la variable tipo persona
// cambio.setNombre(nombre); // se hace el cambio al nuevo nombre
// }
// }
public clientThreadServer extrae(int id) {
//Taller
Celda aux = cabeza; //se fija el auxiliar como la cabeza
if (aux.getInfo().getId() == id) { //Si id ingresado por el
usuario es igual al que esta en la lista se asigna al siguiente
cabeza = aux.getNext(); //metodo para asignar al siguiente
}
while (aux != null && aux.getNext() != null &&
aux.getInfo().getId() != id) { //Si id ingresado por el usuario no
es igual al que esta en la lista
if (aux.getNext().getInfo().getId() == id) { //Si el valor id
es igual a algun valor en la lista
Celda elimina; //variable tipo celda
elimina = aux; // varible tipo celda es igual al auxiliar
aux = aux.getNext(); // obtener el siguiente elemento de
la lista
elimina.setNext(aux.getNext()); //
} else {
aux = aux.getNext(); //De lo contrario siga buscando
}
} //Si hay elementos que coinciden, entonces se extraen y luego
con el return siguiente se devuelve a la lista
return aux.getInfo();
}
@Override
public String toString() {
String s = "Room Mates ";
Celda aux = cabeza;
while (aux != null) {
s += aux.getInfo() + ", ";
aux = aux.getNext();
}
return s;
}
public void sendMessages(String msg) {
Celda aux = cabeza;
while (aux != null) {
aux.getInfo().sendBackClient(msg);
aux = aux.getNext();
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesserver;
public class Room implements Runnable {
private int ROOM_ID = 0;//ID para ingresar al ROOM
private Lista L = new Lista();
public Room(clientThreadServer client) {
if (ROOM_ID == 0) {
ROOM_ID = generaRoomID();
}
L.inserta(client);
System.out.println(L);
}
@Override
public void run() {
while (true) {
}
}
private int generaRoomID() {
return Static.ROOM_ID = Static.ROOM_ID + (int) (Math.random() * 500);
}
@Override
public String toString() {
return "ROOM_ID=" + ROOM_ID;
}
public int getROOM_ID() {
return ROOM_ID;
}
public Lista getL() {
return L;
}
}//CLASS END
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesserver;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server {
// static final String REGISTER_REQUEST = "REGISTER_REQUEST";
// static final String NEW_ROOM = "NEW_ROOM";
// static final String JOIN_ROOM = "JOIN_ROOM";
// static final String REMOVE_MATE = "REMOVE_MATE";
// static final String FILE_TRANSFER = "FILE_TRANSFER";
// static final String MSG = "MSG";
// static int ROOM_ID = 22222;
// static int CLIENT_ID=1;
// static List<Room> Rooms;
// static clientThreadServer cliente;
private ServerSocket server;
public Server() {
try {
server = new ServerSocket(28001);
} catch (IOException ex) {
}
}
public void accept() {
while (true) {
try {
Static.cliente = new clientThreadServer(server.accept());
Static.cliente.start();
} catch (IOException ex) {
}
}
}
}
package vmatesserver;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author murillke
*/
public class Static {
static final String REGISTER_REQUEST = "REGISTER_REQUEST";
static final String NEW_ROOM = "NEW_ROOM";
static final String JOIN_ROOM = "JOIN_ROOM";
static final String REMOVE_MATE = "REMOVE_MATE";
static final String FILE_TRANSFER = "FILE_TRANSFER";
static final String MSG = "MSG";
static final String SEND_MSG = "SEND_MSG";
static int ROOM_ID = 22222;
static int CLIENT_ID=1;
static List<Room> Rooms = new ArrayList<Room>();
static List<Byte> User;
static clientThreadServer cliente;
static Lista lista;
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesserver;
/**
*
* @author murillke
*/
public class VMatesServer {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Server S = new Server();
S.accept();
}
}
package vmatesserver;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class clientThreadServer extends Thread {
private Socket socket;
private ObjectInputStream in;
private ObjectOutputStream out;
private String NICK;
private String email;
private int ID;
public clientThreadServer(final Socket socket) {
this.socket = socket;
startStreams();
}
public void sendBackClient(String msg) {
try {
System.out.println("Enviando mensaje a " + NICK + ": " + msg);
out.writeUTF(msg);
} catch (IOException ex) {
Logger.getLogger(clientThreadServer.class.getName()).log(Level.SEVERE,
null, ex);
}
}
private void startStreams() {
try {
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException ex) {
}
}
@Override
public String toString() {
return "NICK= " + NICK + ", email= " + email + ", ID= " + ID;
}
// Formato de mensaje:"REGISTER_TYPE"+" "+"Name"+" "+"email"+"
"+"USER_ID"+" "+"ROOM_ID"+"MSG";
@Override
public void run() {
while (true) {
try {
String data = in.readUTF();
String[] msg_parts = data.split(" ", 6);
String msg_type = msg_parts[0];
switch (msg_type) {
case Static.MSG:
break;
case Static.REGISTER_REQUEST:
generaClientID();
NICK = msg_parts[1];
email = msg_parts[2];
out.writeUTF("MSG Server_found");
out.flush();
System.out.println(msg_parts[1] + " has registered");
break;
case Static.NEW_ROOM:
System.out.println("New Room has been requested");
generaClientID();
NICK = msg_parts[1];
email = msg_parts[2];
Room room = new Room(this);
(new Thread(room)).start();
Static.Rooms.add(room);
out.writeUTF("ROOM_&_ID" + " " + Static.ROOM_ID +
" " + Static.CLIENT_ID);
out.flush();
for (int i = 0; i < Static.Rooms.size(); i++) {
System.out.println(Static.Rooms.get(i).getROOM_ID());
}
// out.writeUTF("ROOM_&_ID" + " " + Static.ROOM_ID
+ " " + Static.CLIENT_ID);
// out.flush();
break;
case Static.SEND_MSG:
for (int i = 0; i < Static.Rooms.size(); i++) {
System.out.println("From List " +
Static.Rooms.get(i).getROOM_ID());
System.out.println("From Client " +
Integer.parseInt(msg_parts[4]));
if (Static.Rooms.get(i).getROOM_ID() ==
Integer.parseInt(msg_parts[4])) {
System.err.println("Sala encontrada");
Static.Rooms.get(i).getL().sendMessages(msg_parts[5]);
}
}
break;
case Static.JOIN_ROOM:
for (int i = 0; i < Static.Rooms.size(); i++) {
if (Static.Rooms.get(i).getROOM_ID() ==
Integer.parseInt(msg_parts[4])) {
generaClientID();
NICK = msg_parts[1];
email = msg_parts[2];
Static.Rooms.get(i).getL().inserta(this);
out.writeUTF("ROOM_&_ID" + " " + "null" +
" " + Static.CLIENT_ID);
out.flush();
System.out.println(Static.Rooms.get(i).getL());
}
}
break;
case Static.REMOVE_MATE:
for (int i = 0; i < Static.Rooms.size(); i++) {
if (Static.Rooms.get(i).getROOM_ID() ==
Integer.parseInt(msg_parts[4])) {
Static.Rooms.get(i).getL().elimina(Integer.parseInt(msg_parts[1]));
System.out.println(Static.Rooms.get(i).getL());
}
}
break;
case Static.FILE_TRANSFER:
for (int i = 0; i < Static.Rooms.size(); i++) {
}
break;
// if (data.length() > 0) {
//// for (int i = 0; i < Server.Users.size(); i++) {
//// Server.Users.get(i).out.writeUTF(data);
//// Server.Users.get(i).out.flush();
//// }
// System.out.println(data);
}
sleep(800);
} catch (IOException ex) {
} catch (InterruptedException ex) {
}
}
}
private void generaClientID() {
Static.CLIENT_ID = Static.CLIENT_ID + 1;
ID = Static.CLIENT_ID;
}
public String getNICK() {
return NICK;
}
public void setNICK(String NICK) {
this.NICK = NICK;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
}
Subscribe to:
Comments (Atom)