get value from select option jsp
I need to take the value of html select tag, I'm trying this code but it
does not work, any ideas?
<body>
<h1>Nuevo Producto</h1>
<form name ='formulario' action='nuevoProducto.jsp' method='post' >
Descripcion<input name='descripcion' type='text' size='20' required><br>
Precio<input name='precio' type='text' size='20' required><br>
Stock<input name='stock' type='text' size='20' required><br>
Categoria <select name="categoid" id="categoid">
<% for(int i=0;i<myList.size();i++){%>
<option value ="<%= myList.get(i).getId() %>" >
<%out.print(myList.get(i).getDescripcion());%></option>
<%}%>
</select><br>
Imagen<input name="imagen" text="seleccionar archivo" type="file"
size="10" accept="image/jpg" /><br>
<input type ="submit" value ='Guardar' />
<!-- <input type="submit" value="guardar">-->
</form>
Friday, 27 September 2013
How to Mask Sensitive Fields in Logs With Asterisks. C++
How to Mask Sensitive Fields in Logs With Asterisks. C++
I have a requirement to mask sensitive fields(like SSN, Address, Names)
from logs using '***' instesd of the text. The codebase is entirely C++.
It is a huge code base. I have noticed that most of the sensitive info is
printed in xml tags in the logs. I am very new to C++. I would appreciate
if someone could point me in the right direction on how to go about this.
Here is an example of how the fields are logged in the code:
AppMsg rsp(a_dictionary::a_dictionary, XML_RSP, 1);
........
log_msg(CONSOLE, " ResponseTime: %d", response_time);
rsp.add_field(OUTPUT_XML, rsp_xml);
rsp.add_field(STATUS_CODE, status_code);
rsp.add_field(STATUS_DESC, status_desc);
the the logs lookk like:
14:02:58 C--[abcInterfaceServer-1]: abc Query ResponseTime: 0
aRspXml:<?xml version="1.0" encoding="UTF-8"?>
//rsp.add_field(OUTPUT_XML, rsp_xml);
<CustomerInfo>
<sourceFlag>1</sourceFlag>
<Response>
<Data>
<LastName>aa</LastName> //these are the fieds I need
to mask
<FirstName>aaa</FirstName>
<PhoneNumber>aaaa</PhoneNumber>
<Street>aaaa</Street>
<City>aa</City>
<State>aaaa</State>
<Zip>aaa</Zip>
.....
[1] STATUS_CODE[1234] : num_inst = 1
[0] 0
[2] STATUS_DESC[12345] : num_inst = 1
[0] "SUCCESS"
Any ideas would be helpful.
I have a requirement to mask sensitive fields(like SSN, Address, Names)
from logs using '***' instesd of the text. The codebase is entirely C++.
It is a huge code base. I have noticed that most of the sensitive info is
printed in xml tags in the logs. I am very new to C++. I would appreciate
if someone could point me in the right direction on how to go about this.
Here is an example of how the fields are logged in the code:
AppMsg rsp(a_dictionary::a_dictionary, XML_RSP, 1);
........
log_msg(CONSOLE, " ResponseTime: %d", response_time);
rsp.add_field(OUTPUT_XML, rsp_xml);
rsp.add_field(STATUS_CODE, status_code);
rsp.add_field(STATUS_DESC, status_desc);
the the logs lookk like:
14:02:58 C--[abcInterfaceServer-1]: abc Query ResponseTime: 0
aRspXml:<?xml version="1.0" encoding="UTF-8"?>
//rsp.add_field(OUTPUT_XML, rsp_xml);
<CustomerInfo>
<sourceFlag>1</sourceFlag>
<Response>
<Data>
<LastName>aa</LastName> //these are the fieds I need
to mask
<FirstName>aaa</FirstName>
<PhoneNumber>aaaa</PhoneNumber>
<Street>aaaa</Street>
<City>aa</City>
<State>aaaa</State>
<Zip>aaa</Zip>
.....
[1] STATUS_CODE[1234] : num_inst = 1
[0] 0
[2] STATUS_DESC[12345] : num_inst = 1
[0] "SUCCESS"
Any ideas would be helpful.
Defining ranges in bash for loops didn't work
Defining ranges in bash for loops didn't work
I have the following for loop in bash that creates loop devices in a
chrooted directory.
for var in 0 1 2 3 .. 7
do
MAKEDEV -d ${CHROOT}/dev -x loop$var
done
This didn't work for me as after it creates loop3 it takes .. literally
and tries to create loop.. and fails. However according to this tutorial
it should have worked. I got it to work by doing the following:
for (( var=0; var<=7; var++ ))
do
MAKEDEV -d ${CHROOT}/dev -x loop$var
done
I still want to know why the for loop I tried first didn't work. Please help.
I have the following for loop in bash that creates loop devices in a
chrooted directory.
for var in 0 1 2 3 .. 7
do
MAKEDEV -d ${CHROOT}/dev -x loop$var
done
This didn't work for me as after it creates loop3 it takes .. literally
and tries to create loop.. and fails. However according to this tutorial
it should have worked. I got it to work by doing the following:
for (( var=0; var<=7; var++ ))
do
MAKEDEV -d ${CHROOT}/dev -x loop$var
done
I still want to know why the for loop I tried first didn't work. Please help.
carrierwave-video error: nil is not a symbol
carrierwave-video error: nil is not a symbol
I'm using the carrierwave-video gem to upload videos using my Rails app.
When I try to upload a video, I get the following error:
Failed to transcode with FFmpeg. Check ffmpeg install and verify video is
not corrupt or cut short. Original error: nil is not a symbol.
I believe that my ffmpeg installation was successful because if I can run
the following command successfully:
qt-faststart input.mp4 output.mp4
Looking more closely at my logs, it seems like the parameters for the
video file are correct, but I have two rollbacks when the app tries to
create a video record:
Started POST "/videos" for 127.0.0.1 at 2013-09-27 11:42:04 -0400
Processing by VideosController#create as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"5lMoFtM5Rrdu4Ra8ut8rD3jYv3FJ0cxo38QW5ATw9ZQ=",
"video"=>{"project_id"=>"4", "step_id"=>"22", "saved"=>"true",
"embed_url"=>"",
"video_path"=>#<ActionDispatch::Http::UploadedFile:0x007f84702436b8
@original_filename="2013-08-02 17.19.02.mp4", @content_type="video/mp4",
@headers="Content-Disposition: form-data; name=\"video[video_path]\";
filename=\"2013-08-02 17.19.02.mp4\"\r\nContent-Type: video/mp4\r\n",
@tempfile=#<File:/var/folders/dc/c0nfvwy96lq7p4ll94mklnmr0000gp/T/RackMultipart20130927-1871-173l2g7>>},
"button"=>""}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1
LIMIT 1
Project Load (0.3ms) SELECT "projects".* FROM "projects" WHERE
"projects"."id" = $1 LIMIT 1 [["id", "4"]]
(0.2ms) BEGIN
(0.2ms) ROLLBACK
(0.2ms) BEGIN
(0.1ms) ROLLBACK
#<ActiveModel::Errors:0x007f847058fd08 @base=#<Video id: nil, embed_url:
"", project_id: 4, step_id: 22, saved: true, created_at: nil, updated_at:
nil, thumbnail_url: nil, image_id: nil, video_path: nil>,
@messages={:video_path=>["Failed to transcode with FFmpeg. Check ffmpeg
install and verify video is not corrupt or cut short. Original error: nil
is not a symbol"]}>
Completed 406 Not Acceptable in 616ms (ActiveRecord: 1.6ms)
Has anyone had a similar problem, and if so, how did you solve it?
Video.rb:
class Video < ActiveRecord::Base
# maybe we should add a title attribute to the video?
attr_accessible :position, :project_id, :step_id, :image_id, :saved,
:embed_url, :thumbnail_url, :video_path
mount_uploader :video_path, VideoPathUploader
...
def set_success(format, opt)
self.success = true
end
end
video_path_uploader.rb
class VideoPathUploader < CarrierWave::Uploader::Base
include CarrierWave::Video
include CarrierWave::Video::Thumbnailer
process encode_video: [:mp4, callbacks: { after_transcode: :set_success } ]
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
# include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
# storage :file
storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :thumb do
process thumbnail: [{format: 'png', quality: 10, size: 158, strip:
false, logger: Rails.logger}]
def full_filename for_file
png_name for_file, version_name
end
end
version :square_thumb do
process thumbnail: [{format: 'png', quality: 10, size: 105, strip:
false, logger: Rails.logger}]
def full_filename for_file
png_name for_file, version_name
end
end
end
I'm using the carrierwave-video gem to upload videos using my Rails app.
When I try to upload a video, I get the following error:
Failed to transcode with FFmpeg. Check ffmpeg install and verify video is
not corrupt or cut short. Original error: nil is not a symbol.
I believe that my ffmpeg installation was successful because if I can run
the following command successfully:
qt-faststart input.mp4 output.mp4
Looking more closely at my logs, it seems like the parameters for the
video file are correct, but I have two rollbacks when the app tries to
create a video record:
Started POST "/videos" for 127.0.0.1 at 2013-09-27 11:42:04 -0400
Processing by VideosController#create as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"5lMoFtM5Rrdu4Ra8ut8rD3jYv3FJ0cxo38QW5ATw9ZQ=",
"video"=>{"project_id"=>"4", "step_id"=>"22", "saved"=>"true",
"embed_url"=>"",
"video_path"=>#<ActionDispatch::Http::UploadedFile:0x007f84702436b8
@original_filename="2013-08-02 17.19.02.mp4", @content_type="video/mp4",
@headers="Content-Disposition: form-data; name=\"video[video_path]\";
filename=\"2013-08-02 17.19.02.mp4\"\r\nContent-Type: video/mp4\r\n",
@tempfile=#<File:/var/folders/dc/c0nfvwy96lq7p4ll94mklnmr0000gp/T/RackMultipart20130927-1871-173l2g7>>},
"button"=>""}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1
LIMIT 1
Project Load (0.3ms) SELECT "projects".* FROM "projects" WHERE
"projects"."id" = $1 LIMIT 1 [["id", "4"]]
(0.2ms) BEGIN
(0.2ms) ROLLBACK
(0.2ms) BEGIN
(0.1ms) ROLLBACK
#<ActiveModel::Errors:0x007f847058fd08 @base=#<Video id: nil, embed_url:
"", project_id: 4, step_id: 22, saved: true, created_at: nil, updated_at:
nil, thumbnail_url: nil, image_id: nil, video_path: nil>,
@messages={:video_path=>["Failed to transcode with FFmpeg. Check ffmpeg
install and verify video is not corrupt or cut short. Original error: nil
is not a symbol"]}>
Completed 406 Not Acceptable in 616ms (ActiveRecord: 1.6ms)
Has anyone had a similar problem, and if so, how did you solve it?
Video.rb:
class Video < ActiveRecord::Base
# maybe we should add a title attribute to the video?
attr_accessible :position, :project_id, :step_id, :image_id, :saved,
:embed_url, :thumbnail_url, :video_path
mount_uploader :video_path, VideoPathUploader
...
def set_success(format, opt)
self.success = true
end
end
video_path_uploader.rb
class VideoPathUploader < CarrierWave::Uploader::Base
include CarrierWave::Video
include CarrierWave::Video::Thumbnailer
process encode_video: [:mp4, callbacks: { after_transcode: :set_success } ]
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
# include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
# storage :file
storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :thumb do
process thumbnail: [{format: 'png', quality: 10, size: 158, strip:
false, logger: Rails.logger}]
def full_filename for_file
png_name for_file, version_name
end
end
version :square_thumb do
process thumbnail: [{format: 'png', quality: 10, size: 105, strip:
false, logger: Rails.logger}]
def full_filename for_file
png_name for_file, version_name
end
end
end
Implement thread safe ctime function
Implement thread safe ctime function
ANSI C time function are not thread safe: in particular gmtime, ctime and
strftime. For what I know the only thread-safe function is time.
If I'm right in Visual Studio this function are all thread safe. I'm using
MinGW compiler (4.8.0 with dwarf-2, that one provided by Qt 5.1.0 ).
How can inplement thread safe function of gmtime_r, ctime_r and
strftime_r? Or is there a more thread-safe library for that?
I'm using C++11 as default language.
ANSI C time function are not thread safe: in particular gmtime, ctime and
strftime. For what I know the only thread-safe function is time.
If I'm right in Visual Studio this function are all thread safe. I'm using
MinGW compiler (4.8.0 with dwarf-2, that one provided by Qt 5.1.0 ).
How can inplement thread safe function of gmtime_r, ctime_r and
strftime_r? Or is there a more thread-safe library for that?
I'm using C++11 as default language.
Thursday, 26 September 2013
how to view the output of a file with .html.haml extension
how to view the output of a file with .html.haml extension
Please help me, I am working on a rails project and I've created a view
file with extension .html.haml but now when I am trying to view the output
of that file it is giving an error. Is there any other method to view the
files of such extension, I am using the way as i use to view my file with
exyension .html.erb. I've created an action in controller nd matches the
path in routes.rb. Please help me , Thanks in advance.
Please help me, I am working on a rails project and I've created a view
file with extension .html.haml but now when I am trying to view the output
of that file it is giving an error. Is there any other method to view the
files of such extension, I am using the way as i use to view my file with
exyension .html.erb. I've created an action in controller nd matches the
path in routes.rb. Please help me , Thanks in advance.
Thursday, 19 September 2013
how can I control the feed i share on my page text friend
how can I control the feed i share on my page text friend
I'm new to all this, so the terms I use might not be the exact ones... I'm
posting thru an ios application to the player's wall at certain events. If
I get it right, the post is called a 'post', a 'feed' and a 'dialog'...
seems the term 'story' also fits the category somehow. Anyway, Whatever
the application posts on players wall ia also automatically shared, so
that friends of player get notified when they browse 'home' in facebook.
That post however, the one the FRIENDS see in their accounts, is different
from what was posted on the PLAYER's wall. I'm assuming that there is some
way to control that, so that they either appear the same, or have some
text I choose. Can someone please point to what extra parameters I should
send along with the post, or what actions I should take as to accomplish
the task? I tried to include an image that clarifies the issue, but I
couldn't so I'm posting a link that will explain the problem:
http://imgur.com/0zHAJle
I'm new to all this, so the terms I use might not be the exact ones... I'm
posting thru an ios application to the player's wall at certain events. If
I get it right, the post is called a 'post', a 'feed' and a 'dialog'...
seems the term 'story' also fits the category somehow. Anyway, Whatever
the application posts on players wall ia also automatically shared, so
that friends of player get notified when they browse 'home' in facebook.
That post however, the one the FRIENDS see in their accounts, is different
from what was posted on the PLAYER's wall. I'm assuming that there is some
way to control that, so that they either appear the same, or have some
text I choose. Can someone please point to what extra parameters I should
send along with the post, or what actions I should take as to accomplish
the task? I tried to include an image that clarifies the issue, but I
couldn't so I'm posting a link that will explain the problem:
http://imgur.com/0zHAJle
How To Restore Android OpenGL Native App
How To Restore Android OpenGL Native App
I have an Android app that renders an OpenGL scene. All of the OpenGL code
is done in c++.
The problem I am having is that when I press the home button, and then
return to the app, the OpenGL calls start to return errors.
Specifically, the ES 1.1 version fails on glDrawArrays with a logcat error
<gl_draw_error_checks::550>: GL_INVALID_OPERATION
The ES 2.0 version fails on glUseProgram with a locat error of
<core_glUseProgram:1496>: GL_INVALID_VALUE.
What is the proper process for leaving / returning to an OpenGL application?
I have an Android app that renders an OpenGL scene. All of the OpenGL code
is done in c++.
The problem I am having is that when I press the home button, and then
return to the app, the OpenGL calls start to return errors.
Specifically, the ES 1.1 version fails on glDrawArrays with a logcat error
<gl_draw_error_checks::550>: GL_INVALID_OPERATION
The ES 2.0 version fails on glUseProgram with a locat error of
<core_glUseProgram:1496>: GL_INVALID_VALUE.
What is the proper process for leaving / returning to an OpenGL application?
java.lang.VerifyError: Bad type on operand stack in method com.sun.net.httpserver.spi.HttpServerProvider
java.lang.VerifyError: Bad type on operand stack in method
com.sun.net.httpserver.spi.HttpServerProvider
I have been plagued by this problem and managed to narrow it down to a
small file that fails throwing the java.lang.VerifyError when invoked from
Ant with fork set to false in the <java> task but succeeds when fork is
set to true.
The self-contained file is:
package foo;
import javax.xml.ws.Endpoint;
import javax.jws.WebService;
@WebService
class Hello {
public String sayHello() {
return "hello";
}
}
public class FooMain {
public static void main(String args[]) throws Exception {
Object implementor = new Hello();
String address = "http://localhost:9000/SoapContext/SoapPort";
Endpoint.publish(address, implementor);
}
}
When invoked with Ant and fork set to false it throws:
java.lang.VerifyError: Bad type on operand stack in method
com.sun.net.httpserver.spi.HttpServerProvider$1.run()Ljava/lang/Object; at
offset 27
When invoked with fork set to true it succeeds. The specific exception
VerifyError especially when combined with "Bad type on operand stack"
points to a compiler bug from what I've read but why should it succeed or
fail depending on the fork attribute of the <java> Ant task is beyond me.
Any thoughts? I am running Ubuntu 12.04 with the following java tools:
$ java -version
java version "1.7.0_40"
Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
Java HotSpot(TM) Server VM (build 24.0-b56, mixed mode)
$ javac -version
javac 1.7.0_40
$ ant -version
Apache Ant(TM) version 1.8.2 compiled on December 3 2011
$ ant -diagnostics | grep java.vm
java.vm.version : 23.21-b01
java.vm.vendor : Oracle Corporation
java.vm.name : Java HotSpot(TM) Server VM
java.vm.specification.name : Java Virtual Machine Specification
java.vm.specification.vendor : Oracle Corporation
java.vm.specification.version : 1.7
java.vm.info : mixed mode
com.sun.net.httpserver.spi.HttpServerProvider
I have been plagued by this problem and managed to narrow it down to a
small file that fails throwing the java.lang.VerifyError when invoked from
Ant with fork set to false in the <java> task but succeeds when fork is
set to true.
The self-contained file is:
package foo;
import javax.xml.ws.Endpoint;
import javax.jws.WebService;
@WebService
class Hello {
public String sayHello() {
return "hello";
}
}
public class FooMain {
public static void main(String args[]) throws Exception {
Object implementor = new Hello();
String address = "http://localhost:9000/SoapContext/SoapPort";
Endpoint.publish(address, implementor);
}
}
When invoked with Ant and fork set to false it throws:
java.lang.VerifyError: Bad type on operand stack in method
com.sun.net.httpserver.spi.HttpServerProvider$1.run()Ljava/lang/Object; at
offset 27
When invoked with fork set to true it succeeds. The specific exception
VerifyError especially when combined with "Bad type on operand stack"
points to a compiler bug from what I've read but why should it succeed or
fail depending on the fork attribute of the <java> Ant task is beyond me.
Any thoughts? I am running Ubuntu 12.04 with the following java tools:
$ java -version
java version "1.7.0_40"
Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
Java HotSpot(TM) Server VM (build 24.0-b56, mixed mode)
$ javac -version
javac 1.7.0_40
$ ant -version
Apache Ant(TM) version 1.8.2 compiled on December 3 2011
$ ant -diagnostics | grep java.vm
java.vm.version : 23.21-b01
java.vm.vendor : Oracle Corporation
java.vm.name : Java HotSpot(TM) Server VM
java.vm.specification.name : Java Virtual Machine Specification
java.vm.specification.vendor : Oracle Corporation
java.vm.specification.version : 1.7
java.vm.info : mixed mode
HTML Encoding and PHP
HTML Encoding and PHP
Hello im using php i need to compare data from my array and data from
readed captcha. But i got problem with html encoding. Example from my
array:
"osiemnaœcie" => 18,
and data from captcha:
osiemnaście
How can compare these data ? I already tried "html_entity_decode()" but no
results.
Hello im using php i need to compare data from my array and data from
readed captcha. But i got problem with html encoding. Example from my
array:
"osiemnaœcie" => 18,
and data from captcha:
osiemnaście
How can compare these data ? I already tried "html_entity_decode()" but no
results.
You must specify valid values for the A3, P3, and T3 parameters for a subscription button
You must specify valid values for the A3, P3, and T3 parameters for a
subscription button
I used to use the following code for Paypal dropdown subscriptions using
BMCreateButtonReq. But in the past 30-60 days it started to fail with
asking for A3, P3 and T3. I tried adding these fields as dummpy fields,
but it did not work. How can I get it back up and running?
foreach (var p in pricings)
{
var optionSelectionDetail = new OptionSelectionDetailsType()
{
OptionSelection = string.Format("{0}", p.pricing1), //
a little risky but makes paypal form look better
Price = Math.Round(p.price, 2).ToString("N"),
};
if (p.months != null && p.months > 0)
{
var installmentDetails = new List<InstallmentDetailsType>();
installmentDetails.Add(new InstallmentDetailsType()
{
BillingFrequency = (int)p.months, //
BillingFrequency doesn't work
BillingPeriod = p.months == 12 ?
BillingPeriodType.YEAR : BillingPeriodType.MONTH,
//TotalBillingCycles = 20,
// Amount = optionSelectionDetail.Price,
});
optionSelectionDetail.PaymentPeriod = installmentDetails;
}
selectionDetails.Add(optionSelectionDetail);
}
subscription button
I used to use the following code for Paypal dropdown subscriptions using
BMCreateButtonReq. But in the past 30-60 days it started to fail with
asking for A3, P3 and T3. I tried adding these fields as dummpy fields,
but it did not work. How can I get it back up and running?
foreach (var p in pricings)
{
var optionSelectionDetail = new OptionSelectionDetailsType()
{
OptionSelection = string.Format("{0}", p.pricing1), //
a little risky but makes paypal form look better
Price = Math.Round(p.price, 2).ToString("N"),
};
if (p.months != null && p.months > 0)
{
var installmentDetails = new List<InstallmentDetailsType>();
installmentDetails.Add(new InstallmentDetailsType()
{
BillingFrequency = (int)p.months, //
BillingFrequency doesn't work
BillingPeriod = p.months == 12 ?
BillingPeriodType.YEAR : BillingPeriodType.MONTH,
//TotalBillingCycles = 20,
// Amount = optionSelectionDetail.Price,
});
optionSelectionDetail.PaymentPeriod = installmentDetails;
}
selectionDetails.Add(optionSelectionDetail);
}
How to perform an action after a Random Time Delay? - Android
How to perform an action after a Random Time Delay? - Android
So I'm making an app on "I'm not telling you"... :-)
Going to the problem :
final ToggleButton passTog = (ToggleButton) findViewById(R.id.onoff);
passTog.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
init = System.currentTimeMillis();
handler.post(updater);
}
});
Up above is a normal toggle button, I previously defined a handler, using
this I'm running a Runnable named updater...(For the following: "display"
is a textview)
final Runnable updater = new Runnable() {
@Override
public void run() {
if (passTog.isChecked()) {
now = System.currentTimeMillis();
time = now - init;
display.setText(time + " ms");
handler.postDelayed(this, 30);
}
}
};
And here's the runnable... The variable time, now, init ... are time
variables.
What I'm trying to do is (right now) I'm updating the textview with the
milliseconds passed since the Toggle button is pressed (see the if
statement)
EXPLAINATION of the above code
So, activity starts, click the toggle button, init variable gets a value
of the current time... Program goes to the runnable. Now , after double
checking that the button is infact in the "on" state... the system puts
the current time in "now" ... and we have the time variable as the
subtraction of the two. And that gets updated in the textview "display"
every 30 milliseconds. In the app you can see the textview pacing as time
passes. Works great.
That's that, and what I want is...
The activity starts, you press the button.. After a random time delay* say
between 2-10 seconds.... The textview should then start getting updated.
We press a button, nothing seemingly happens, Then after that random
delay... the textview bursts up, and starts churning out the current time
starting from 1ms, that is the above runnable should run after that random
time delay.
Seeing as in the matter is completely logical and not really technical- I
need to somehow introduce a non-fixed time delay before the runnable does
it's thing.
I think we may be able to do this in the runnable itself... we already
have the "time" variable.... Why not use that in a "if" statement.... and
then reset the time variable so that it seems to start from the start.
Heavy stuff, I just can't seem to get it right.
Any idea how we can do this ?
So I'm making an app on "I'm not telling you"... :-)
Going to the problem :
final ToggleButton passTog = (ToggleButton) findViewById(R.id.onoff);
passTog.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
init = System.currentTimeMillis();
handler.post(updater);
}
});
Up above is a normal toggle button, I previously defined a handler, using
this I'm running a Runnable named updater...(For the following: "display"
is a textview)
final Runnable updater = new Runnable() {
@Override
public void run() {
if (passTog.isChecked()) {
now = System.currentTimeMillis();
time = now - init;
display.setText(time + " ms");
handler.postDelayed(this, 30);
}
}
};
And here's the runnable... The variable time, now, init ... are time
variables.
What I'm trying to do is (right now) I'm updating the textview with the
milliseconds passed since the Toggle button is pressed (see the if
statement)
EXPLAINATION of the above code
So, activity starts, click the toggle button, init variable gets a value
of the current time... Program goes to the runnable. Now , after double
checking that the button is infact in the "on" state... the system puts
the current time in "now" ... and we have the time variable as the
subtraction of the two. And that gets updated in the textview "display"
every 30 milliseconds. In the app you can see the textview pacing as time
passes. Works great.
That's that, and what I want is...
The activity starts, you press the button.. After a random time delay* say
between 2-10 seconds.... The textview should then start getting updated.
We press a button, nothing seemingly happens, Then after that random
delay... the textview bursts up, and starts churning out the current time
starting from 1ms, that is the above runnable should run after that random
time delay.
Seeing as in the matter is completely logical and not really technical- I
need to somehow introduce a non-fixed time delay before the runnable does
it's thing.
I think we may be able to do this in the runnable itself... we already
have the "time" variable.... Why not use that in a "if" statement.... and
then reset the time variable so that it seems to start from the start.
Heavy stuff, I just can't seem to get it right.
Any idea how we can do this ?
java.net.ConnectException: Connection refused: connect
java.net.ConnectException: Connection refused: connect
trying to upload file using apache file upload, but getting this error:
java.net.ConnectException: Connection refused: connect
it was working yesterday, but today it is not working
trying to upload file using apache file upload, but getting this error:
java.net.ConnectException: Connection refused: connect
it was working yesterday, but today it is not working
how to change Qtablewidget's spesific cells backround color in pyqt
how to change Qtablewidget's spesific cells backround color in pyqt
I am new in pyqt4 and i couldn't figure out how to figure out this. I have
a QtableWidget with data in it. i want to change some backround color of
tableWidget's cells. I tried self.tableWidget.item(3,
5).setBackground(QtGui.QColor(100,100,150)) and error returns like this
AttributeError: 'NoneType' object has no attribute 'setBackground'
what should i do ?
Thanks in advance.
I am new in pyqt4 and i couldn't figure out how to figure out this. I have
a QtableWidget with data in it. i want to change some backround color of
tableWidget's cells. I tried self.tableWidget.item(3,
5).setBackground(QtGui.QColor(100,100,150)) and error returns like this
AttributeError: 'NoneType' object has no attribute 'setBackground'
what should i do ?
Thanks in advance.
Wednesday, 18 September 2013
Android app with 3 categories on google play market
Android app with 3 categories on google play market
I have seen an android app that is present in 3 categories: casual,
wallpaper and widget. How can I also declare my application the same way ?
Google Developer Console only allows me to declare one category.
I have seen an android app that is present in 3 categories: casual,
wallpaper and widget. How can I also declare my application the same way ?
Google Developer Console only allows me to declare one category.
Searching a c# List containing inherited class
Searching a c# List containing inherited class
I have created the following code just as a more simplified way to display
my problem.
I haven't ran this version through a compiler so it may have typos.
I'm am looking if there is a more condense way (or even a better way) to
search a List that contains inherited classes.
public class Engine {
public String FuelType { get; set; }
}
----------------------------------------------------------------------------
public class Wheel {
public String TyreType { get; set; }
}
----------------------------------------------------------------------------
public abstract class Car {
public abstract String Make { get; }
}
public class Ford : Car {
public override String Make {
get { return "Ford"; }
}
Public Engine Engine { get; set; }
}
public class Porche : Car {
public override String Make {
get { return "Porche"; }
}
Public Wheel Wheel { get; set; }
}
----------------------------------------------------------------------------
// CarCollection as follows:
// Ford > Engine > FuelType > "Petrol"
// Ford > Engine > FuelType > "Diesel"
// Porche > Wheel > TyreType > "Dry"
List<Car> carCollection = GetCarcollection();
What I want is a reference to the ' Ford > Engine > FuelType > "Petrol" '.
(assume the collection will only contain one)
//-- Start --
List<Ford> fordCollection = carCollection.FindAll( cc => cc.Make == "Ford" )
.Cast<Ford>().ToList();
Im not able to access the fuelType in the above so I do it in a seperate
statement below.
// This 'ford' is the reference I require
Ford ford = fordCollection.Find( fc => fc.Engine.FuelType == "Petrol" );
//-- Finish --
Although this works is it possible to combine the two above statement into
one.
The Class structure is just a simple example and the design isnt fully
relevant to my real code.
I have created the following code just as a more simplified way to display
my problem.
I haven't ran this version through a compiler so it may have typos.
I'm am looking if there is a more condense way (or even a better way) to
search a List that contains inherited classes.
public class Engine {
public String FuelType { get; set; }
}
----------------------------------------------------------------------------
public class Wheel {
public String TyreType { get; set; }
}
----------------------------------------------------------------------------
public abstract class Car {
public abstract String Make { get; }
}
public class Ford : Car {
public override String Make {
get { return "Ford"; }
}
Public Engine Engine { get; set; }
}
public class Porche : Car {
public override String Make {
get { return "Porche"; }
}
Public Wheel Wheel { get; set; }
}
----------------------------------------------------------------------------
// CarCollection as follows:
// Ford > Engine > FuelType > "Petrol"
// Ford > Engine > FuelType > "Diesel"
// Porche > Wheel > TyreType > "Dry"
List<Car> carCollection = GetCarcollection();
What I want is a reference to the ' Ford > Engine > FuelType > "Petrol" '.
(assume the collection will only contain one)
//-- Start --
List<Ford> fordCollection = carCollection.FindAll( cc => cc.Make == "Ford" )
.Cast<Ford>().ToList();
Im not able to access the fuelType in the above so I do it in a seperate
statement below.
// This 'ford' is the reference I require
Ford ford = fordCollection.Find( fc => fc.Engine.FuelType == "Petrol" );
//-- Finish --
Although this works is it possible to combine the two above statement into
one.
The Class structure is just a simple example and the design isnt fully
relevant to my real code.
Strange animation on iOS 7 when using hidesBottomBarWhenPushed in app built targeting < iOS 6
Strange animation on iOS 7 when using hidesBottomBarWhenPushed in app
built targeting < iOS 6
When I build targeting iOS 5 or 6, but run an app on 7. If I have a
controller in a navigation controller that is a part of a tab bar
controller, and I do the following:
controller.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:testController animated:YES];
A strange vertical positioning animation occurs. I would instead like the
new controller (with the bottom bar hidden) to push or pop on the
navigation controller pushing the tab bar out or bringing it back and with
no vertical positioning changes.
Video of Issue: http://cl.ly/1w0g3j293m03
Open Radar Report: http://www.openradar.me/14670329
built targeting < iOS 6
When I build targeting iOS 5 or 6, but run an app on 7. If I have a
controller in a navigation controller that is a part of a tab bar
controller, and I do the following:
controller.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:testController animated:YES];
A strange vertical positioning animation occurs. I would instead like the
new controller (with the bottom bar hidden) to push or pop on the
navigation controller pushing the tab bar out or bringing it back and with
no vertical positioning changes.
Video of Issue: http://cl.ly/1w0g3j293m03
Open Radar Report: http://www.openradar.me/14670329
runtime error 3077 in ms access 2010
runtime error 3077 in ms access 2010
I have an access form called FindClientsListBox in which I am using a
listbox called lstbxClients to allow users to select which client's
information they want displayed on the form. lstbxClients is populated
with a row source property sql statement, and is not bound to data. But
the FindClientsListBox form is bound to data which, at the moment, is two
controls each bound to a field in a table called Clients. What I want is
for the values in the two controls (ClientNumber and FullName) on
FindClientsListBox form to change their values to match the client whose
name is selected in lstbxClients. But I am getting runtime error 3077 when
I select a client.
Here is how it looks when I click on one of the names in lstbxClients
(Notice that the name on right does not match the name on left, and that
an error dialog is thrown):
When I click the debug button on the error dialog, I am taken to the
following:
Can anyone show me how to get this to work?
I have an access form called FindClientsListBox in which I am using a
listbox called lstbxClients to allow users to select which client's
information they want displayed on the form. lstbxClients is populated
with a row source property sql statement, and is not bound to data. But
the FindClientsListBox form is bound to data which, at the moment, is two
controls each bound to a field in a table called Clients. What I want is
for the values in the two controls (ClientNumber and FullName) on
FindClientsListBox form to change their values to match the client whose
name is selected in lstbxClients. But I am getting runtime error 3077 when
I select a client.
Here is how it looks when I click on one of the names in lstbxClients
(Notice that the name on right does not match the name on left, and that
an error dialog is thrown):
When I click the debug button on the error dialog, I am taken to the
following:
Can anyone show me how to get this to work?
Spring Java Conversion exception
Spring Java Conversion exception
I am trying to store an EnumSet object into my neo4j db. However, I get
this exception:
org.springframework.core.convert.ConversionFailedException: Failed to
convert from type java.util.LinkedHashSet<?> to type java.util.EnumSet<?>
for value '[READ, WRITE, OPTIONAL]'; nested exception is
java.lang.IllegalArgumentException: Could not instantiate Collection type:
java.util.EnumSet
Is there some way to substitute the the EnumSet with something else? Or,
does anyone know a work around?
I've tried making the set as a HashSet, but I lose the methods that
EnumSet gives me, such as noneOf().
I am trying to store an EnumSet object into my neo4j db. However, I get
this exception:
org.springframework.core.convert.ConversionFailedException: Failed to
convert from type java.util.LinkedHashSet<?> to type java.util.EnumSet<?>
for value '[READ, WRITE, OPTIONAL]'; nested exception is
java.lang.IllegalArgumentException: Could not instantiate Collection type:
java.util.EnumSet
Is there some way to substitute the the EnumSet with something else? Or,
does anyone know a work around?
I've tried making the set as a HashSet, but I lose the methods that
EnumSet gives me, such as noneOf().
add sensor linker using android cmake
add sensor linker using android cmake
I'm developing a c++ plugin to get android sensor data.
when I compile my shared library using android-cmake toolchain I've got a
linker error :
error: undefined reference to 'ASensorManager_getInstance'
How can I add the right library (-landroid or -lsensor I guess) to the
compilation using android-cmake?
Thanks
I'm developing a c++ plugin to get android sensor data.
when I compile my shared library using android-cmake toolchain I've got a
linker error :
error: undefined reference to 'ASensorManager_getInstance'
How can I add the right library (-landroid or -lsensor I guess) to the
compilation using android-cmake?
Thanks
Apache reverse proxy for Cloud9 using ServerName
Apache reverse proxy for Cloud9 using ServerName
I am trying to setup a reverse proxy to a Cloud9 instance running locally
on my server using Apache. I have the following setup:
<VirtualHost *.80>
ProxyPreserveHost On
ProxyPass / http://localhost:3131/
ProxyPassReverse / http://localhost:3131/
ServerAdmin cloud9@mydomain.org
ServerName cloud9.mydomain.org
</VirtualHost>
I have also tried re-ordering the directives so the ServerAdmin and
ServerName came first. So far, if I hit http://cloud9.mydomain.org, I get
a browser error saying it could not connect. There is nothing logged in
Apache's access.log or error.log either. I am thinking that I am missing
some piece, but I am not sure as to what that missing piece might be yet.
I also don't know if I am looking in the right place for logs. The Cloud9
process was started, and appears to be running on the 3131 port.
I don't plan to run Cloud9 wide open. The end-game I am shooting for is to
eventually get Cloud9 hosted through SSL using some auth, maybe basic
auth, but I figured before I started adding SSL and auth into the mix, I
should probably get the basics working first.
I am trying to setup a reverse proxy to a Cloud9 instance running locally
on my server using Apache. I have the following setup:
<VirtualHost *.80>
ProxyPreserveHost On
ProxyPass / http://localhost:3131/
ProxyPassReverse / http://localhost:3131/
ServerAdmin cloud9@mydomain.org
ServerName cloud9.mydomain.org
</VirtualHost>
I have also tried re-ordering the directives so the ServerAdmin and
ServerName came first. So far, if I hit http://cloud9.mydomain.org, I get
a browser error saying it could not connect. There is nothing logged in
Apache's access.log or error.log either. I am thinking that I am missing
some piece, but I am not sure as to what that missing piece might be yet.
I also don't know if I am looking in the right place for logs. The Cloud9
process was started, and appears to be running on the 3131 port.
I don't plan to run Cloud9 wide open. The end-game I am shooting for is to
eventually get Cloud9 hosted through SSL using some auth, maybe basic
auth, but I figured before I started adding SSL and auth into the mix, I
should probably get the basics working first.
Complexity of the method
Complexity of the method
I was asked this in an interview.WHat is the complexity of this method??
static int magic(int n) {
System.out.println( count+" "+ n);
count++;
return (n < 2) ? n : magic(n - 1) + magic(n - 2);
}
I was asked this in an interview.WHat is the complexity of this method??
static int magic(int n) {
System.out.println( count+" "+ n);
count++;
return (n < 2) ? n : magic(n - 1) + magic(n - 2);
}
Tuesday, 17 September 2013
How to show/implement a ShoutBox/ mini Chat Room in my android app?
How to show/implement a ShoutBox/ mini Chat Room in my android app?
http://www.freeshoutbox.net/
I want to add a ShoutBox or like a mini Chat Room section to my app where
random people can talk with other random people.....
I stumbled across this above website, and it turned out to offer exactly
what I need.
a.freeshoutbox.net
The above is an example of the sort of ShoutBox I want to add in my app.
After creating an account as admin, you get a link (like above) and some
HTML code to add it in your own site, a blog for example.
There is absolutely no documentation whatsoever about adding this
functionality to an android app, and I speak after googling for an hour. I
think all I just need to show the web page by the given URL. when you try
to open up the above link(2nd one) in the mobile browser, it appears in
zoomed out.
Below is exactly what I want to replicate:
Click here
So I need to somehow resize it so that it appears perfectly on every
device with different resolutions and sizes etc.
I don't have a lot of experience with WebViews, and I like I said showing
the URL simple gives me a crappy looking zoomed out shoutbox.
So How do I go about accomplishing this ?
http://www.freeshoutbox.net/
I want to add a ShoutBox or like a mini Chat Room section to my app where
random people can talk with other random people.....
I stumbled across this above website, and it turned out to offer exactly
what I need.
a.freeshoutbox.net
The above is an example of the sort of ShoutBox I want to add in my app.
After creating an account as admin, you get a link (like above) and some
HTML code to add it in your own site, a blog for example.
There is absolutely no documentation whatsoever about adding this
functionality to an android app, and I speak after googling for an hour. I
think all I just need to show the web page by the given URL. when you try
to open up the above link(2nd one) in the mobile browser, it appears in
zoomed out.
Below is exactly what I want to replicate:
Click here
So I need to somehow resize it so that it appears perfectly on every
device with different resolutions and sizes etc.
I don't have a lot of experience with WebViews, and I like I said showing
the URL simple gives me a crappy looking zoomed out shoutbox.
So How do I go about accomplishing this ?
How can I swap (as in alias) command names in zsh?
How can I swap (as in alias) command names in zsh?
If I try
$ alias pwd=echo
$ alias echo=pwd
I get
$ pwd
/home/owen
$ echo hi
hi
It seems aliases are followed recursively. Perhaps if there was a way to
stop the recursion, that would work. In this example I can use builtin,
but that won't work in general, particular for -g aliases.
If I try
$ alias pwd=echo
$ alias echo=pwd
I get
$ pwd
/home/owen
$ echo hi
hi
It seems aliases are followed recursively. Perhaps if there was a way to
stop the recursion, that would work. In this example I can use builtin,
but that won't work in general, particular for -g aliases.
Ruby: can you send a socket as a parameter?
Ruby: can you send a socket as a parameter?
Can I do this?
tcpsocket = TCPSocket.open host, port
data = "xxx"
send(data, tcpsocket)
->
def send data, my_socket
my_socket.write data
end
Unfortunately I can't test.
Can I do this?
tcpsocket = TCPSocket.open host, port
data = "xxx"
send(data, tcpsocket)
->
def send data, my_socket
my_socket.write data
end
Unfortunately I can't test.
Get the changes made in a specific file at a specific commit?
Get the changes made in a specific file at a specific commit?
I know you can do git log --stat and the do a git diff (commit1)
(commit2), however, this gives me the changes in all of the files. I would
like to see the changes in only a specific file. Is this possible?
I know you can do git log --stat and the do a git diff (commit1)
(commit2), however, this gives me the changes in all of the files. I would
like to see the changes in only a specific file. Is this possible?
Calling a simple shell script from java is not working
Calling a simple shell script from java is not working
My Shell script named "hello"
#This is a shell script
echo "Hello Shell World!"
My Java Code,
Runtime.getRuntime().exec(new String[]{"./hello"});
My Java code is executed with no errors, but I do not see "Hello Shell
World!" being printed on the terminal.
I believe my script is being executed since I do not get errors like,
"hello cannot be executed, there is no such file or directory".
I am executing this on a Linux machine, Ubuntu. Thanks!
My Shell script named "hello"
#This is a shell script
echo "Hello Shell World!"
My Java Code,
Runtime.getRuntime().exec(new String[]{"./hello"});
My Java code is executed with no errors, but I do not see "Hello Shell
World!" being printed on the terminal.
I believe my script is being executed since I do not get errors like,
"hello cannot be executed, there is no such file or directory".
I am executing this on a Linux machine, Ubuntu. Thanks!
Execute an open default editor command inside vim
Execute an open default editor command inside vim
I am trying to make a habit of never leaving my gvim, not even for
executing commands in the terminal. This works fine with :!<command>.
However if this command wants to open default editor (vim) it ironically
does not work from gvim (it works from command line vim). Example:
:!git commit
error: Terminal is dumb, but EDITOR unset
Please supply the message using either -m or -F option.
I can run:
:!git commit -m "message"
But I like the vim window when I am inspecting files and write commit
messages. Is it possible to make the commit window appear in gvim as with
command line vim?
I am trying to make a habit of never leaving my gvim, not even for
executing commands in the terminal. This works fine with :!<command>.
However if this command wants to open default editor (vim) it ironically
does not work from gvim (it works from command line vim). Example:
:!git commit
error: Terminal is dumb, but EDITOR unset
Please supply the message using either -m or -F option.
I can run:
:!git commit -m "message"
But I like the vim window when I am inspecting files and write commit
messages. Is it possible to make the commit window appear in gvim as with
command line vim?
Sunday, 15 September 2013
Get values in between tags from web page
Get values in between tags from web page
I'm trying to pull two pieces of data from an external web page. There are
two tags on the page, and the data I need is within both.
How would I get the data from both tags?
I've tried a few different things, but none seem to work. Here's what I
tried last:
$dom = new DOMDocument;
$dom->loadHtmlFile('url');
$xpath = new DOMXPath($dom);
$elements = $xpath->query('b');
if ($elements->length) {
echo "found: ", $elements->item(0)->getAttribute('value');
} else {
echo "not found";
}
I'm trying to pull two pieces of data from an external web page. There are
two tags on the page, and the data I need is within both.
How would I get the data from both tags?
I've tried a few different things, but none seem to work. Here's what I
tried last:
$dom = new DOMDocument;
$dom->loadHtmlFile('url');
$xpath = new DOMXPath($dom);
$elements = $xpath->query('b');
if ($elements->length) {
echo "found: ", $elements->item(0)->getAttribute('value');
} else {
echo "not found";
}
Text effecting div alignment
Text effecting div alignment
I'm trying to get the tops of elements '.wrap1' and '.wrap2' to line up.
As is you can see in this jsfiddle that the top of 'wrap1' is a little
below '.wrap2' yet when I delete the displayed text from '.wrap2' the tops
do line up. Can any one explain why the text is lowering the top of
'.wrap1'?
<html>
<body>
<ul
style="margin:0px 0px!important;position:relative;width:100%"
class="mainList"
id="dateMainList">
<li
class="list-element"
id=""
style="width:100%">
<div
class="list-inner-wrap"
style="border:1px solid black">
<div
class="wrap1"
style="display:inline-block;background:white;border:2px
solid black;height:50px;width:50px">
<div
class="line-1"
style="display:block;text-align:center;font-size:10pt">1</div>
<div
class="line-2"
style="display:block;text-align:center;font-size:10pt">2</div>
<div
class="line-3"
style="display:block;text-align:center;font-size:10pt">3</div>
</div>
<div
class="wrap2"
style="display:inline-block;height:50px;background:green;width:200px"></div>
</div>
</li>
</ul>
</body>
I'm trying to get the tops of elements '.wrap1' and '.wrap2' to line up.
As is you can see in this jsfiddle that the top of 'wrap1' is a little
below '.wrap2' yet when I delete the displayed text from '.wrap2' the tops
do line up. Can any one explain why the text is lowering the top of
'.wrap1'?
<html>
<body>
<ul
style="margin:0px 0px!important;position:relative;width:100%"
class="mainList"
id="dateMainList">
<li
class="list-element"
id=""
style="width:100%">
<div
class="list-inner-wrap"
style="border:1px solid black">
<div
class="wrap1"
style="display:inline-block;background:white;border:2px
solid black;height:50px;width:50px">
<div
class="line-1"
style="display:block;text-align:center;font-size:10pt">1</div>
<div
class="line-2"
style="display:block;text-align:center;font-size:10pt">2</div>
<div
class="line-3"
style="display:block;text-align:center;font-size:10pt">3</div>
</div>
<div
class="wrap2"
style="display:inline-block;height:50px;background:green;width:200px"></div>
</div>
</li>
</ul>
</body>
C++ thread conversion error
C++ thread conversion error
First : I'm from Colombia so the error is in spanish. This seems the
fastest place to get an answer...
I've been trying to make a simple program that creates threads and saves
the information in a vector but when I build the code the next error
appears:
...Lanzador.cpp|19|error: no se puede convertir 'void* (Hilo::)(void)' a
'void* ()(void)' para el argumento '3' para 'int
pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)'|
I have three files: the header for Hilos that says:
#ifndef HILO_H
#define HILO_H
using namespace std;
class Hilo
{
public:
Hilo();
virtual ~Hilo();
void addHilo(int);
void* ImprimirHilo(void*);
protected:
private:
};
First : I'm from Colombia so the error is in spanish. This seems the
fastest place to get an answer...
I've been trying to make a simple program that creates threads and saves
the information in a vector but when I build the code the next error
appears:
...Lanzador.cpp|19|error: no se puede convertir 'void* (Hilo::)(void)' a
'void* ()(void)' para el argumento '3' para 'int
pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)'|
I have three files: the header for Hilos that says:
#ifndef HILO_H
#define HILO_H
using namespace std;
class Hilo
{
public:
Hilo();
virtual ~Hilo();
void addHilo(int);
void* ImprimirHilo(void*);
protected:
private:
};
Is there a more concise way to call an outside method on a map in Ruby?
Is there a more concise way to call an outside method on a map in Ruby?
Is there a more concise way of doing this?
# Given a directory containing subdirectories: foo, bar
targets = ['./foo', './bar', './free']
targets.map{ |d| Dir.exists? d }
# => [ true, true, false ]
I'd love to be able to do something similar to proc calls... it feels
cleaner:
# targets.map( Dir.exists? )
Is there a more concise way of doing this?
# Given a directory containing subdirectories: foo, bar
targets = ['./foo', './bar', './free']
targets.map{ |d| Dir.exists? d }
# => [ true, true, false ]
I'd love to be able to do something similar to proc calls... it feels
cleaner:
# targets.map( Dir.exists? )
insert a text include new line character (from Enter button) from textbox into SQL
insert a text include new line character (from Enter button) from textbox
into SQL
I've already read many questions and answers about my problem, but I
cannot get the solution.
I have a textbox in my Webform, I write the text which entered from that
textbox(from Keyboard) into SQL DB. But when I open the table in SQL DB,
the text is showing without any new line character (ex: \n) or any
replacement character.
So that, when I get that text from the SQL DB to showing on a Panel in my
Webform again, it display the text same as one in SQL DB.
How can I insert the text from Textbox into SQL and load it again into a
Panel in Webform correctly???
into SQL
I've already read many questions and answers about my problem, but I
cannot get the solution.
I have a textbox in my Webform, I write the text which entered from that
textbox(from Keyboard) into SQL DB. But when I open the table in SQL DB,
the text is showing without any new line character (ex: \n) or any
replacement character.
So that, when I get that text from the SQL DB to showing on a Panel in my
Webform again, it display the text same as one in SQL DB.
How can I insert the text from Textbox into SQL and load it again into a
Panel in Webform correctly???
Debugging PDF for error
Debugging PDF for error
I'm creating PDF files using PDFClown java library.
Sometimes, when openning these files with Adobe Acrobat Reader I get the
famous error message:
"An error exists on this page. Acrobat may not display the page correctly.
Please contact the person who created the PDF document to correct the
problem."
The error shows while reading (with Adobe) the attached file only when
scrolling down to the 8'th page, then scrolling back up to 3'td page.
Alternatively, Zooming out to 33.3% will also produce the message.
Just for the record, Foxit reader reads the file flawlessly, as well as
other PDF readers like browsers.
My questions are:
What's wrong with my file?? (file is attached)
How can I find what's wrong with it? is there a tool which tells you where
does the error lie?
Thanks!
I'm creating PDF files using PDFClown java library.
Sometimes, when openning these files with Adobe Acrobat Reader I get the
famous error message:
"An error exists on this page. Acrobat may not display the page correctly.
Please contact the person who created the PDF document to correct the
problem."
The error shows while reading (with Adobe) the attached file only when
scrolling down to the 8'th page, then scrolling back up to 3'td page.
Alternatively, Zooming out to 33.3% will also produce the message.
Just for the record, Foxit reader reads the file flawlessly, as well as
other PDF readers like browsers.
My questions are:
What's wrong with my file?? (file is attached)
How can I find what's wrong with it? is there a tool which tells you where
does the error lie?
Thanks!
configure many to many for unique notes in middle table
configure many to many for unique notes in middle table
I have two entities: Student and Prepod. Its linked as many to many.
I have so mapping:
Student:
@Entity
@Table(name="Student")
public class Student {
private Long id;
private String name;
private Long age;
private Set<Prepod> prepods = new HashSet<Prepod>();
@ManyToMany(mappedBy="students" ,fetch = FetchType.EAGER)
public Set<Prepod> getPrepods() {
return prepods;
}
public void setPrepods(Set<Prepod> prepods) {
this.prepods = prepods;
}
public Student(){
name = null;
}
public Student(Student s){
name = s.getName();
}
@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy = "increment")
@Column(name="id")
public Long getId() {
return id;
}
@Column(name="name")
public String getName(){
return name;
}
@Column(name="age")
public Long getAge(){
return age;
}
public void setId(Long i){
id = i;
}
public void setName(String s){
name = s;
}
public void setAge(Long age){
this.age = age;
}
}
Prepod:
@Entity(name = "prepod")
public class Prepod {
private Long id;
private String name;
Set<Student> students = new HashSet<Student>();
@ManyToMany(fetch = FetchType.EAGER)
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long i) {
id = i;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And I get so database schema:
Thuse in table prepod_Student can be duplicate values.
How to change my mapping for resolving this problem?
I have two entities: Student and Prepod. Its linked as many to many.
I have so mapping:
Student:
@Entity
@Table(name="Student")
public class Student {
private Long id;
private String name;
private Long age;
private Set<Prepod> prepods = new HashSet<Prepod>();
@ManyToMany(mappedBy="students" ,fetch = FetchType.EAGER)
public Set<Prepod> getPrepods() {
return prepods;
}
public void setPrepods(Set<Prepod> prepods) {
this.prepods = prepods;
}
public Student(){
name = null;
}
public Student(Student s){
name = s.getName();
}
@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy = "increment")
@Column(name="id")
public Long getId() {
return id;
}
@Column(name="name")
public String getName(){
return name;
}
@Column(name="age")
public Long getAge(){
return age;
}
public void setId(Long i){
id = i;
}
public void setName(String s){
name = s;
}
public void setAge(Long age){
this.age = age;
}
}
Prepod:
@Entity(name = "prepod")
public class Prepod {
private Long id;
private String name;
Set<Student> students = new HashSet<Student>();
@ManyToMany(fetch = FetchType.EAGER)
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long i) {
id = i;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And I get so database schema:
Thuse in table prepod_Student can be duplicate values.
How to change my mapping for resolving this problem?
java beginner programming, putting strings in char array to filter input
java beginner programming, putting strings in char array to filter input
in this code I've been trying to filter the characters in the array with a
for-loop to a second array, but am unable to. Could anyone tell me what is
exactly wrong with my code?
public class Deel1 {
public static void main(String[] args) {
String zinInvoer = getInput();
String zinUitvoer = filterZin(zinInvoer);
}
static String getInput() {
Scanner scan = new Scanner(System.in);
String zinInvoer = "";
System.out.println("Voer een zin in: ");
if (scan.hasNextLine()) {
zinInvoer = scan.nextLine().trim();
}
if (zinInvoer.equals("")) {
System.out.println("Geen invoer!");
System.exit(0);
}
return zinInvoer;
}
static String filterZin(String zinInvoer) {
String zinUitvoer = "";
char ongefilterd[] = zinInvoer.toCharArray();
String nogFilteren = new String(ongefilterd);
char a = nogFilteren.charAt(97);
for (a = 97; a <= 122; a++) {
a = a += 32;
char gefilterd[] = //second array to be printed
}
System.out.println("Gefilterd: " + zinUitvoer);
return zinInvoer;
}
}
in this code I've been trying to filter the characters in the array with a
for-loop to a second array, but am unable to. Could anyone tell me what is
exactly wrong with my code?
public class Deel1 {
public static void main(String[] args) {
String zinInvoer = getInput();
String zinUitvoer = filterZin(zinInvoer);
}
static String getInput() {
Scanner scan = new Scanner(System.in);
String zinInvoer = "";
System.out.println("Voer een zin in: ");
if (scan.hasNextLine()) {
zinInvoer = scan.nextLine().trim();
}
if (zinInvoer.equals("")) {
System.out.println("Geen invoer!");
System.exit(0);
}
return zinInvoer;
}
static String filterZin(String zinInvoer) {
String zinUitvoer = "";
char ongefilterd[] = zinInvoer.toCharArray();
String nogFilteren = new String(ongefilterd);
char a = nogFilteren.charAt(97);
for (a = 97; a <= 122; a++) {
a = a += 32;
char gefilterd[] = //second array to be printed
}
System.out.println("Gefilterd: " + zinUitvoer);
return zinInvoer;
}
}
Saturday, 14 September 2013
How to get UTC timestamp in php
How to get UTC timestamp in php
how to get UTC timestamp in php.. The below doesn't returns UTC timestamp,
it is displaying some other timestamp
<?php
date_default_timezone_set('UTC');
echo strtotime("now");
?>
i think, setting default timezone as not been effective?
how to get UTC timestamp in php.. The below doesn't returns UTC timestamp,
it is displaying some other timestamp
<?php
date_default_timezone_set('UTC');
echo strtotime("now");
?>
i think, setting default timezone as not been effective?
Open multiple links in same Iframe
Open multiple links in same Iframe
*Im trying to Open multiple links in same Iframe, as well as changing the
divsstyle.visibility(Visibility is working for me) but adding window.open
I get nothing. I have the original address in a div id="testing"
name="wordp" *
<head>
<script type="text/javascript">
function wordpaboutme() {
var showme2 = document.getElementById("testing");
showme2.style.visibility = "visible";
var changeme = document.getElementById("testing");
changeme.window.open.('http://mysite.com/main/about-me/','wordp');
}
</script>
<body>
<div id="testing" name="wordp" class="bloger" ><iframe
src="http://mysite.com/main/" frameborder="0" scrolling="no"
width="990" height="800" >
<p>Your browser does not support iframes.</p>
</iframe>
</div>
*Im trying to Open multiple links in same Iframe, as well as changing the
divsstyle.visibility(Visibility is working for me) but adding window.open
I get nothing. I have the original address in a div id="testing"
name="wordp" *
<head>
<script type="text/javascript">
function wordpaboutme() {
var showme2 = document.getElementById("testing");
showme2.style.visibility = "visible";
var changeme = document.getElementById("testing");
changeme.window.open.('http://mysite.com/main/about-me/','wordp');
}
</script>
<body>
<div id="testing" name="wordp" class="bloger" ><iframe
src="http://mysite.com/main/" frameborder="0" scrolling="no"
width="990" height="800" >
<p>Your browser does not support iframes.</p>
</iframe>
</div>
Pointer-like behaviour in Python
Pointer-like behaviour in Python
I have two modules. One is the core of the website based on web.py (let's
name it code.py), and other is an add-on module (addon.py). Using web.py,
for each page that the website server there should be class definition in
a core, like that:
class Page:
def GET(self):
variable = "Hello!"
return render.page_template(variable) #Here, it returns the rendered
template to user
def POST(self):
post_variables = web.input()
pass #Doing something with those variables, maybe, writing in a database...
Now I really need to move that class definition from code.py to addon.py.
I can refer to the class definition as a addon.Page instead of simply
Page. The Page.GET function still works well... But there's one problem
with POST. It seems like at the each call of POST function in a module
web.input() is being set as a storage object storing all the variables.
And if my class definition is being stored in addon, the core simply calls
addon.Page.POST() (I see no way to change this behaviour). The POST()
tries to get web.input... And fails, of course - web is not imported in
addon.py, and even if it was, there wouldn't be any value web.py
web-server is getting - just empty dictionary, it would be just another
instance of the module. So i don't know...
One solution would be: putting some kind of function in addon.Page.POST().
This function would go one level down, to code.py and execute web.input()
there, and return it back, to addon.py, some kind of accessing parent
module namespace (like doing import __main__ and accessing
main.web.input() (which, as I know, is discouraged) ).
Or, for example, putting some kind of C-like pointer that would be shared
between the modules, like:
* in code.py there's definition that all the calls to
code.addon.web_input() get routed to code.web.input()
* in addon.py - there's simply need to call addon.web_input to get info
from code.web.input()
What do I do in this situation? There will be multiple addons, each with
the class definition stored in this addon, and I should be able to add new
modules, connect and disconnect existing modules easily, without any need
to modify code.py. I believe this is possible in Python... Maybe web.py
source needs modifying then?
I have two modules. One is the core of the website based on web.py (let's
name it code.py), and other is an add-on module (addon.py). Using web.py,
for each page that the website server there should be class definition in
a core, like that:
class Page:
def GET(self):
variable = "Hello!"
return render.page_template(variable) #Here, it returns the rendered
template to user
def POST(self):
post_variables = web.input()
pass #Doing something with those variables, maybe, writing in a database...
Now I really need to move that class definition from code.py to addon.py.
I can refer to the class definition as a addon.Page instead of simply
Page. The Page.GET function still works well... But there's one problem
with POST. It seems like at the each call of POST function in a module
web.input() is being set as a storage object storing all the variables.
And if my class definition is being stored in addon, the core simply calls
addon.Page.POST() (I see no way to change this behaviour). The POST()
tries to get web.input... And fails, of course - web is not imported in
addon.py, and even if it was, there wouldn't be any value web.py
web-server is getting - just empty dictionary, it would be just another
instance of the module. So i don't know...
One solution would be: putting some kind of function in addon.Page.POST().
This function would go one level down, to code.py and execute web.input()
there, and return it back, to addon.py, some kind of accessing parent
module namespace (like doing import __main__ and accessing
main.web.input() (which, as I know, is discouraged) ).
Or, for example, putting some kind of C-like pointer that would be shared
between the modules, like:
* in code.py there's definition that all the calls to
code.addon.web_input() get routed to code.web.input()
* in addon.py - there's simply need to call addon.web_input to get info
from code.web.input()
What do I do in this situation? There will be multiple addons, each with
the class definition stored in this addon, and I should be able to add new
modules, connect and disconnect existing modules easily, without any need
to modify code.py. I believe this is possible in Python... Maybe web.py
source needs modifying then?
C# WinForms minimize frm.Show() when main form is minimized
C# WinForms minimize frm.Show() when main form is minimized
I have a Windows Form that is showing an overlay form:
private void ShowWait()
{
frmOverlay = new Base.frmOverlay("Please Wait...");
frmOverlay.Show(this);
}
This frmOverlay form at the same time is show it shows another form in the
middle (message form):
private void frmOverlay_Load(object sender, EventArgs e)
{
frmPleaseWait = new frmPleaseWait(_text);
frmPleaseWait.Show(this);
}
When I minimize the main form then I can still see the frmPleaseWait form,
is there a way I can minimize all when the main form is minimized?
Thanks a lot.
I have a Windows Form that is showing an overlay form:
private void ShowWait()
{
frmOverlay = new Base.frmOverlay("Please Wait...");
frmOverlay.Show(this);
}
This frmOverlay form at the same time is show it shows another form in the
middle (message form):
private void frmOverlay_Load(object sender, EventArgs e)
{
frmPleaseWait = new frmPleaseWait(_text);
frmPleaseWait.Show(this);
}
When I minimize the main form then I can still see the frmPleaseWait form,
is there a way I can minimize all when the main form is minimized?
Thanks a lot.
Copying with batch scriptfile in Windows 2008 R2
Copying with batch scriptfile in Windows 2008 R2
I have a .cmd file that i want to use in automating copying a folder from
a mapped location on a windows 2008 server to an external HDD connected to
the windows server box:
@ECHO OFF
ECHO Backup process started.
set TARGET_FOLDER=Z:\"WindowsImageBackup - Copy"
ECHO TARGET_FOLDER "%TARGET_FOLDER%"
SET DESTINATION_FOLDER=H:\SERVER_BACKUP_IMAGE
ECHO DESTINATION_FOLDER "%DESTINATION_FOLDER%"
For /f "tokens=1-4 delims=/ " %%a in ('date /t') do (set mydate=%%d%%c%%b%%a)
For /f "tokens=1-2 delims=: " %%a in ('time /t') do (set mytime=%%a%%b)
SET BACKUP_FOLDER=BACKUP_%mydate%_%mytime%
ECHO BACKUP_FOLDER "%BACKUP_FOLDER%"
SET FINAL_FOLDER=%DESTINATION_FOLDER%\%BACKUP_FOLDER%
MKDIR "%FINAL_FOLDER%"
ECHO DIRECTORY CREATED "%FINAL_FOLDER%"
ECHO Backup process started ...
XCOPY "%TARGET_FOLDER%" "%FINAL_FOLDER%" >>
"%FINAL_FOLDER%\%BACKUP_FOLDER%.log" /Y
ECHO Backup process ended successfully.
@ECHO ON
pause
After running the script, the destination folder is created and the log
file created says 0 files copied but there are files in the target folder.
This is the output:
Backup process started. TARGET_FOLDER "Z:\"WindowsImageBackup - Copy""
DESTINATION_FOLDER "H:\SERVER_BACKUP_IMAGE" BACKUP_FOLDER
"BACKUP_20131409Sat_0333" DIRECTORY CREATED
"H:\SERVER_BACKUP_IMAGE\BACKUP_20131409Sat_0333" Backup process started
... Invalid number of parameters Backup process ended successfully.
C:\Control>pause Press any key to continue . . .
The 7th line is of interest but I do not know how to go around it. What
parameters am i supposed to use?
Funny thing is that if i run this same script on my windows 7 laptop (i
have the same directory structure), it runs and copies accordingly.
Thanks for your help.
I have a .cmd file that i want to use in automating copying a folder from
a mapped location on a windows 2008 server to an external HDD connected to
the windows server box:
@ECHO OFF
ECHO Backup process started.
set TARGET_FOLDER=Z:\"WindowsImageBackup - Copy"
ECHO TARGET_FOLDER "%TARGET_FOLDER%"
SET DESTINATION_FOLDER=H:\SERVER_BACKUP_IMAGE
ECHO DESTINATION_FOLDER "%DESTINATION_FOLDER%"
For /f "tokens=1-4 delims=/ " %%a in ('date /t') do (set mydate=%%d%%c%%b%%a)
For /f "tokens=1-2 delims=: " %%a in ('time /t') do (set mytime=%%a%%b)
SET BACKUP_FOLDER=BACKUP_%mydate%_%mytime%
ECHO BACKUP_FOLDER "%BACKUP_FOLDER%"
SET FINAL_FOLDER=%DESTINATION_FOLDER%\%BACKUP_FOLDER%
MKDIR "%FINAL_FOLDER%"
ECHO DIRECTORY CREATED "%FINAL_FOLDER%"
ECHO Backup process started ...
XCOPY "%TARGET_FOLDER%" "%FINAL_FOLDER%" >>
"%FINAL_FOLDER%\%BACKUP_FOLDER%.log" /Y
ECHO Backup process ended successfully.
@ECHO ON
pause
After running the script, the destination folder is created and the log
file created says 0 files copied but there are files in the target folder.
This is the output:
Backup process started. TARGET_FOLDER "Z:\"WindowsImageBackup - Copy""
DESTINATION_FOLDER "H:\SERVER_BACKUP_IMAGE" BACKUP_FOLDER
"BACKUP_20131409Sat_0333" DIRECTORY CREATED
"H:\SERVER_BACKUP_IMAGE\BACKUP_20131409Sat_0333" Backup process started
... Invalid number of parameters Backup process ended successfully.
C:\Control>pause Press any key to continue . . .
The 7th line is of interest but I do not know how to go around it. What
parameters am i supposed to use?
Funny thing is that if i run this same script on my windows 7 laptop (i
have the same directory structure), it runs and copies accordingly.
Thanks for your help.
Joomla 2.5 Menu Image
Joomla 2.5 Menu Image
I have to create a module in joomla 2.5, which is kind of type menu that
displays the menu and when we hoover with mous in a menu it shows an image
in a place holder for that menu item. The point is how to get the menu
item id with the hover and how to display an image with that id ??
I have to create a module in joomla 2.5, which is kind of type menu that
displays the menu and when we hoover with mous in a menu it shows an image
in a place holder for that menu item. The point is how to get the menu
item id with the hover and how to display an image with that id ??
Malloc error when assigning memory to a struct
Malloc error when assigning memory to a struct
#include<stdio.h>
#include<conio.h>
struct Node{
int number;
struct Node * next;
};
struct Node * insertNodeInLinkedList(int number,struct Node * startOfList){
if(startOfList == NULL){
startOfList = (struct Node *)malloc(sizeof(struct Node));
startOfList->number = number;
startOfList->next = NULL;
}else{
struct Node * temporaryNode = startOfList;
struct Node * newNode = (struct Node *)malloc(sizeof(struct Node));
while(temporaryNode->next != NULL){
temporaryNode = temporaryNode->next;
}
newNode->number = number;
newNode->next = NULL;
temporaryNode->next = newNode;
}
return startOfList;
}
void display(struct Node * startOfList){
struct Node * temporaryNode = startOfList;
while(temporaryNode != NULL){
printf("%d",temporaryNode->number);
temporaryNode = temporaryNode->next;
}
}
int main (void){
int howManyNodes = 0;
int counter = 0;
int enteredNumber = 0;
struct Node * startOfMyList = NULL;
printf("How many nodes do you want in your linked list?");
scanf("%d",&howManyNodes);
while(counter < howManyNodes){
printf("Enter number: ");
scanf("%d",&enteredNumber);
startOfMyList =
insertNodeIntoLinkedList(enteredNumber,startOfMyList);
counter++;
}
display(startOfMyList);
getch();
return 0;
}
This is my simple program to insert and display nodes of a linked list.
However, the line:
startOfList = (struct Node *)malloc(sizeof(struct Node));
gets flagged as an error. I do not know why.
What is going wrong here ?
#include<stdio.h>
#include<conio.h>
struct Node{
int number;
struct Node * next;
};
struct Node * insertNodeInLinkedList(int number,struct Node * startOfList){
if(startOfList == NULL){
startOfList = (struct Node *)malloc(sizeof(struct Node));
startOfList->number = number;
startOfList->next = NULL;
}else{
struct Node * temporaryNode = startOfList;
struct Node * newNode = (struct Node *)malloc(sizeof(struct Node));
while(temporaryNode->next != NULL){
temporaryNode = temporaryNode->next;
}
newNode->number = number;
newNode->next = NULL;
temporaryNode->next = newNode;
}
return startOfList;
}
void display(struct Node * startOfList){
struct Node * temporaryNode = startOfList;
while(temporaryNode != NULL){
printf("%d",temporaryNode->number);
temporaryNode = temporaryNode->next;
}
}
int main (void){
int howManyNodes = 0;
int counter = 0;
int enteredNumber = 0;
struct Node * startOfMyList = NULL;
printf("How many nodes do you want in your linked list?");
scanf("%d",&howManyNodes);
while(counter < howManyNodes){
printf("Enter number: ");
scanf("%d",&enteredNumber);
startOfMyList =
insertNodeIntoLinkedList(enteredNumber,startOfMyList);
counter++;
}
display(startOfMyList);
getch();
return 0;
}
This is my simple program to insert and display nodes of a linked list.
However, the line:
startOfList = (struct Node *)malloc(sizeof(struct Node));
gets flagged as an error. I do not know why.
What is going wrong here ?
Friday, 13 September 2013
creating memory of the size of a pointer for char array inside struct
creating memory of the size of a pointer for char array inside struct
I have a program that asks to input two arguments using argv and I would
like to then using the length of argv[1] and argv[2] dynamically allocate
memory for two pointer char inside my struct the size of argv[1] and
argv[2]. Here is my code but i'm not sure if i did it correctly, can
anyone verify? Parameters passedargv1 and passedargv1 inside the function
are argv[1] and argv[2] passed from the main function. Basically i want to
make chararray1=argv[1] and chararray2=argv[2] if they were just plain
char arrays but i don't know ahead of time the size of our input so i
can't pre-initialize chararray2 and chararray2. Also i can't change what
is inside argv so i cannot have chararray1 and chararray2 just point to
them because i will need to change them later on.
struct StructInformation{
char *chararray1;
char *chararray2;
};
typedef struct StructInformation SimplifiedStruct;
SimplifiedStruct *CreateMem(char *passedargv1, char *passedargv2) {
SimplifiedStruct *ptr=(SimplifiedStruct*)malloc(sizeof(SimplifiedStruct));
ptr->chararray1=(char*)malloc(sizeof(passedargv1));
ptr->chararray2=(char*)malloc(sizeof(passedargv2));
I have a program that asks to input two arguments using argv and I would
like to then using the length of argv[1] and argv[2] dynamically allocate
memory for two pointer char inside my struct the size of argv[1] and
argv[2]. Here is my code but i'm not sure if i did it correctly, can
anyone verify? Parameters passedargv1 and passedargv1 inside the function
are argv[1] and argv[2] passed from the main function. Basically i want to
make chararray1=argv[1] and chararray2=argv[2] if they were just plain
char arrays but i don't know ahead of time the size of our input so i
can't pre-initialize chararray2 and chararray2. Also i can't change what
is inside argv so i cannot have chararray1 and chararray2 just point to
them because i will need to change them later on.
struct StructInformation{
char *chararray1;
char *chararray2;
};
typedef struct StructInformation SimplifiedStruct;
SimplifiedStruct *CreateMem(char *passedargv1, char *passedargv2) {
SimplifiedStruct *ptr=(SimplifiedStruct*)malloc(sizeof(SimplifiedStruct));
ptr->chararray1=(char*)malloc(sizeof(passedargv1));
ptr->chararray2=(char*)malloc(sizeof(passedargv2));
Photos from private groupe
Photos from private groupe
We are a cupple of people who made a secret group. A lot of pictures were
uploaded to this group and we were all taged. The pictures were not
visible in our profiles so now the group has been opend. The pictures
still don't show up in our profiles. Do we have to delete all the tags and
redo them to get the pictures on our profiles? We are talking hundres of
pictures and it would be nice if we didn't have to do that.
We are a cupple of people who made a secret group. A lot of pictures were
uploaded to this group and we were all taged. The pictures were not
visible in our profiles so now the group has been opend. The pictures
still don't show up in our profiles. Do we have to delete all the tags and
redo them to get the pictures on our profiles? We are talking hundres of
pictures and it would be nice if we didn't have to do that.
Ignoring or removing line breaks python
Ignoring or removing line breaks python
I'm sorry for the noobish question, but none of the answers I've looked at
seem to fix this. I'd like to take a multi-line string like this:
myString = """a
b
c
d
e"""
And get a result that looks like or that is at least interpreted as this:
myString = "abcde"
myString.rstrip(), myString.rstrip(\n), and myString.rstrip(\r) don't seem
to change anything when I print this little "abcde" test string. Some of
the other solutions I've read involve entering the string like this:
myString = ("a"
"b"
"c")
But this solution is impractical because I'm working with very large sets
of data. I need to be able to copy a dataset and paste it into my program,
and have python remove or ignore the line breaks.
Am I entering something in wrong? Is there an elegant solution to this?
Thanks in advance for your patience.
I'm sorry for the noobish question, but none of the answers I've looked at
seem to fix this. I'd like to take a multi-line string like this:
myString = """a
b
c
d
e"""
And get a result that looks like or that is at least interpreted as this:
myString = "abcde"
myString.rstrip(), myString.rstrip(\n), and myString.rstrip(\r) don't seem
to change anything when I print this little "abcde" test string. Some of
the other solutions I've read involve entering the string like this:
myString = ("a"
"b"
"c")
But this solution is impractical because I'm working with very large sets
of data. I need to be able to copy a dataset and paste it into my program,
and have python remove or ignore the line breaks.
Am I entering something in wrong? Is there an elegant solution to this?
Thanks in advance for your patience.
DLL syntax error
DLL syntax error
I'm trying to create a dll with multiple functions, in Visual C++ 2010,
and I keep getting a syntax error that is related to using strings, or so
it seems.
1>c:\users\new\documents\visual studio
2010\projects\getint\getint\getint.h(9): error C2061: syntax error :
identifier 'string'
The code can be seen below. I literally followed what I did last time;
although the last dll I made had 1 function and no boolean or string
values.
#include <string>
class getInt
{
public:
//NB :: static __declspec(dllexport) is need to export data from the dll!
//This declares the function for retrieving an integer value from the
user
static __declspec(dllexport) int toInt (const string &inStr);
static __declspec(dllexport) int getNum();
static __declspec(dllexport) bool isValidInt (const string& str);
};
There are several other syntax errors but I believe they are arising due
to the string being before the other functions.
I'm trying to create a dll with multiple functions, in Visual C++ 2010,
and I keep getting a syntax error that is related to using strings, or so
it seems.
1>c:\users\new\documents\visual studio
2010\projects\getint\getint\getint.h(9): error C2061: syntax error :
identifier 'string'
The code can be seen below. I literally followed what I did last time;
although the last dll I made had 1 function and no boolean or string
values.
#include <string>
class getInt
{
public:
//NB :: static __declspec(dllexport) is need to export data from the dll!
//This declares the function for retrieving an integer value from the
user
static __declspec(dllexport) int toInt (const string &inStr);
static __declspec(dllexport) int getNum();
static __declspec(dllexport) bool isValidInt (const string& str);
};
There are several other syntax errors but I believe they are arising due
to the string being before the other functions.
No Scrollbars in GWT Flextable
No Scrollbars in GWT Flextable
I am creating a flextable and adding cells in it dynamically. Flextable is
inside scrollpanel but scrollbars never come vertically. They always come
horizontally/
<g:ScrollPanel ui:field='toppanel'>
</g:ScrollPanel>
Flextable is added in this Scrollpanel dynamically as toppanel.add(stutable);
I am creating a flextable and adding cells in it dynamically. Flextable is
inside scrollpanel but scrollbars never come vertically. They always come
horizontally/
<g:ScrollPanel ui:field='toppanel'>
</g:ScrollPanel>
Flextable is added in this Scrollpanel dynamically as toppanel.add(stutable);
Thursday, 12 September 2013
continuous insert/add to xml file vb.net
continuous insert/add to xml file vb.net
<gamerecord>
<Record>
<adate></adate>
<IMEI></IMEI>
<coin></coin>
<type></type>
<gameresult></gameresult>
</Record>
</gamerecord>
this is my xml file pattern(above sample) but I can't continuous add new
node(sample below)
<gamerecord>
<Record>
<adate></adate>
<IMEI></IMEI>
<coin></coin>
<type></type>
<gameresult></gameresult>
</Record>
<Record>
<adate></adate>
<IMEI></IMEI>
<coin></coin>
<type></type>
<gameresult></gameresult>
</Record>
</gamerecord>
this is my coding(vb.net)
Dim xDoc As New XmlDocument
Dim xNode As XmlNode = xDoc.AppendChild(xDoc.CreateElement("Record"))
Dim xadate As XmlNode = xNode.AppendChild(xDoc.CreateElement("adate"))
xadate.InnerText = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")
Dim xIMEI As XmlNode = xNode.AppendChild(xDoc.CreateElement("IMEI"))
xIMEI.InnerText = value
Dim xcoin As XmlNode = xNode.AppendChild(xDoc.CreateElement("coin"))
xcoin.InnerText = value
Dim xtype As XmlNode = xNode.AppendChild(xDoc.CreateElement("type"))
xtype.InnerText = value
Dim xgameresult As XmlNode =
xNode.AppendChild(xDoc.CreateElement("gameresult"))
xgameresult.InnerText = value
xDoc.Save(aConfig.pathxml)
I try few method but the value replace my latest record, how I can
continuous adding new record?
<gamerecord>
<Record>
<adate></adate>
<IMEI></IMEI>
<coin></coin>
<type></type>
<gameresult></gameresult>
</Record>
</gamerecord>
this is my xml file pattern(above sample) but I can't continuous add new
node(sample below)
<gamerecord>
<Record>
<adate></adate>
<IMEI></IMEI>
<coin></coin>
<type></type>
<gameresult></gameresult>
</Record>
<Record>
<adate></adate>
<IMEI></IMEI>
<coin></coin>
<type></type>
<gameresult></gameresult>
</Record>
</gamerecord>
this is my coding(vb.net)
Dim xDoc As New XmlDocument
Dim xNode As XmlNode = xDoc.AppendChild(xDoc.CreateElement("Record"))
Dim xadate As XmlNode = xNode.AppendChild(xDoc.CreateElement("adate"))
xadate.InnerText = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")
Dim xIMEI As XmlNode = xNode.AppendChild(xDoc.CreateElement("IMEI"))
xIMEI.InnerText = value
Dim xcoin As XmlNode = xNode.AppendChild(xDoc.CreateElement("coin"))
xcoin.InnerText = value
Dim xtype As XmlNode = xNode.AppendChild(xDoc.CreateElement("type"))
xtype.InnerText = value
Dim xgameresult As XmlNode =
xNode.AppendChild(xDoc.CreateElement("gameresult"))
xgameresult.InnerText = value
xDoc.Save(aConfig.pathxml)
I try few method but the value replace my latest record, how I can
continuous adding new record?
Where can we get the freshest and most accurate ip to country data from RIRs?
Where can we get the freshest and most accurate ip to country data from RIRs?
We have been using various ip to country database (LITE) for years.
Recently we noticed that they are (voluntary?) getting less and less
reliable (especially for European countries).
Therefore we decided to generate our own ip to country database.
It looks like we simply need to aggregate the data of the following public
ressources:
http://stackoverflow.com/ftp://ftp.afrinic.net/pub/stats/afrinic/delegated-afrinic-latest
http://stackoverflow.com/ftp://ftp.lacnic.net/pub/stats/lacnic/delegated-lacnic-latest
http://stackoverflow.com/ftp://ftp.arin.net/pub/stats/arin/delegated-arin-extended-latest
http://stackoverflow.com/ftp://ftp.apnic.net/pub/stats/apnic/delegated-apnic-latest
http://stackoverflow.com/ftp://ftp.ripe.net/ripe/stats/delegated-ripencc-latest
http://stackoverflow.com/ftp://ftp.ripe.net/ripe/dbase/split/ripe.db.inetnum.gz
Is a database missing? Do you see some issue in the reasoning?
Please note:
We only need the country.
A1s/A2s are not needed.
We will be the user of the database (we will not resell it)
We have been using various ip to country database (LITE) for years.
Recently we noticed that they are (voluntary?) getting less and less
reliable (especially for European countries).
Therefore we decided to generate our own ip to country database.
It looks like we simply need to aggregate the data of the following public
ressources:
http://stackoverflow.com/ftp://ftp.afrinic.net/pub/stats/afrinic/delegated-afrinic-latest
http://stackoverflow.com/ftp://ftp.lacnic.net/pub/stats/lacnic/delegated-lacnic-latest
http://stackoverflow.com/ftp://ftp.arin.net/pub/stats/arin/delegated-arin-extended-latest
http://stackoverflow.com/ftp://ftp.apnic.net/pub/stats/apnic/delegated-apnic-latest
http://stackoverflow.com/ftp://ftp.ripe.net/ripe/stats/delegated-ripencc-latest
http://stackoverflow.com/ftp://ftp.ripe.net/ripe/dbase/split/ripe.db.inetnum.gz
Is a database missing? Do you see some issue in the reasoning?
Please note:
We only need the country.
A1s/A2s are not needed.
We will be the user of the database (we will not resell it)
What is the most optimal Ember.js file/directory structure?
What is the most optimal Ember.js file/directory structure?
I have a hard time deciding on the most optimal file/directory structure
for my Ember.js application.
Should I serve all my static content from a public directory like below?
index.html
public/
|- js/
|- app.js
|- lib
|- ember-x.x.x.js
|- jquery-x.x.x.js
|- css/
|- ...
|- img/
|- ...
Is there a better alternative? Is it purely a matter of opinion and taste?
Thanks in advance for your answers.
I have a hard time deciding on the most optimal file/directory structure
for my Ember.js application.
Should I serve all my static content from a public directory like below?
index.html
public/
|- js/
|- app.js
|- lib
|- ember-x.x.x.js
|- jquery-x.x.x.js
|- css/
|- ...
|- img/
|- ...
Is there a better alternative? Is it purely a matter of opinion and taste?
Thanks in advance for your answers.
reading config data from sd card in arduino
reading config data from sd card in arduino
i need to be reading some config data from an sd card to an arduino.
format will look like this.
type=10? DPSNC=xx DPSCOM=xy type=11? DPSNC=xx DPSCOM=xy
so basically the program should run a query of the different types based
on user input in char array format then pulls the corresponding
parameters.
i already managed to implement a variable file name for the database file
based on user input as well.
basically if a match is not found, it needs to read through the line until
the next "type" string is
I have very little success in implementing this. any help of sample code
will be appreciated. thanks!
i need to be reading some config data from an sd card to an arduino.
format will look like this.
type=10? DPSNC=xx DPSCOM=xy type=11? DPSNC=xx DPSCOM=xy
so basically the program should run a query of the different types based
on user input in char array format then pulls the corresponding
parameters.
i already managed to implement a variable file name for the database file
based on user input as well.
basically if a match is not found, it needs to read through the line until
the next "type" string is
I have very little success in implementing this. any help of sample code
will be appreciated. thanks!
checking if a value for a core data entity is a boolean or no
checking if a value for a core data entity is a boolean or no
I would like to check if a attribute in core data is boolean. How do I go
about it? I can check if it is date class by:
if([[dict valueForKey:key] isKindOfClass:[NSDate class]])
{
value = ([outputFormatter stringFromDate:[dict
objectForKey:key]]);
[dict setObject:value forKey:key];
}
else
{
value = [dict objectForKey:key];
}
Need this fix for an urgent delivery.Thanks in advance for any advice.
I would like to check if a attribute in core data is boolean. How do I go
about it? I can check if it is date class by:
if([[dict valueForKey:key] isKindOfClass:[NSDate class]])
{
value = ([outputFormatter stringFromDate:[dict
objectForKey:key]]);
[dict setObject:value forKey:key];
}
else
{
value = [dict objectForKey:key];
}
Need this fix for an urgent delivery.Thanks in advance for any advice.
Wednesday, 11 September 2013
How to compare datetime in SQL Server in where clause
How to compare datetime in SQL Server in where clause
I have CreatedDate as datetime column in my database table. I want to
fetch the rows where CreatedDate and current time difference is more than
1 hour
I have CreatedDate as datetime column in my database table. I want to
fetch the rows where CreatedDate and current time difference is more than
1 hour
Pie with legend
Pie with legend
I want to add legend to matlab pie instead of just putting the names close
the pie itself. That is, I want names to be displayed in a box, and the
percentage to be displayed close to the pie (as it usually is). But if I
simply add a legend, as follows, it will be not attached to the patches
information:
pieH=pie([.3,.4,.3]);
legend({'Leg1','Leg2','Leg3'},'location','EastOutside');
I've tried turning the patch annotation icon display to on, as follows,
but it didn't work:
set(get(get(pieH(1),'Annotation'),'LegendInformation'),'IconDisplayStyle','on')
set(get(get(pieH(3),'Annotation'),'LegendInformation'),'IconDisplayStyle','on')
set(get(get(pieH(5),'Annotation'),'LegendInformation'),'IconDisplayStyle','on')
I also tried passing the patched handles, as it says in the help, also
with no effect:
legend([pieH(1:2:end)],{'Leg1','Leg2','Leg3'},'location','EastOutside');
I want to add legend to matlab pie instead of just putting the names close
the pie itself. That is, I want names to be displayed in a box, and the
percentage to be displayed close to the pie (as it usually is). But if I
simply add a legend, as follows, it will be not attached to the patches
information:
pieH=pie([.3,.4,.3]);
legend({'Leg1','Leg2','Leg3'},'location','EastOutside');
I've tried turning the patch annotation icon display to on, as follows,
but it didn't work:
set(get(get(pieH(1),'Annotation'),'LegendInformation'),'IconDisplayStyle','on')
set(get(get(pieH(3),'Annotation'),'LegendInformation'),'IconDisplayStyle','on')
set(get(get(pieH(5),'Annotation'),'LegendInformation'),'IconDisplayStyle','on')
I also tried passing the patched handles, as it says in the help, also
with no effect:
legend([pieH(1:2:end)],{'Leg1','Leg2','Leg3'},'location','EastOutside');
Odd behavior when initializing an array using a class member
Odd behavior when initializing an array using a class member
I found an oddity with initialization that I'm trying to wrap my head
around. I understand that an array can be initialized to all default
values by using T[size] {}, which seems to work in most cases, but doesn't
seem to work when being initialized by a class member, as in:
class Hashtable {
int *table;
int size;
public:
Hashtable() : size { 10 }, table { new int[size]{} } {
for (int index = 0; index != size; ++index) { // size = 10
cout << table[index] << endl; // this displays an
uninitialized array??
}
}
};
If I try to initialize table with a literal, as in table { new int[10] {}
}, all the items in the array are set to default (0). Why is that?
I found an oddity with initialization that I'm trying to wrap my head
around. I understand that an array can be initialized to all default
values by using T[size] {}, which seems to work in most cases, but doesn't
seem to work when being initialized by a class member, as in:
class Hashtable {
int *table;
int size;
public:
Hashtable() : size { 10 }, table { new int[size]{} } {
for (int index = 0; index != size; ++index) { // size = 10
cout << table[index] << endl; // this displays an
uninitialized array??
}
}
};
If I try to initialize table with a literal, as in table { new int[10] {}
}, all the items in the array are set to default (0). Why is that?
WCF Router raising Exception over WS-RM packets
WCF Router raising Exception over WS-RM packets
I have a WCF Router setup where the client communicates to the target
service with WS Http bindings using reliable messaging (RMP.) When the
connection between client service to router is WS HTTP and router to
target service is WS HTTP, all works as expected. I log the SOAP packets
as they hit the router and they look like:
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
xmlns:r="http://docs.oasis-open.org/ws-rx/wsrm/200702"
xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<r:Sequence s:mustUnderstand="1">
<r:Identifier>urn:uuid:76bac170-ace3-4a9b-8a5f-eba263cbdf57</r:Identifier>
<r:MessageNumber>1</r:MessageNumber>
</r:Sequence>
<a:Action s:mustUnderstand="1">http://tempuri.org/Foo/Connect</a:Action>
<a:MessageID>urn:uuid:d76b500f-f59e-41a1-9831-cb33e2f9eb3c</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<a:To s:mustUnderstand="1">http://foobox:62435/RouterService.svc</a:To>
</s:Header>
<s:Body>
<Connect xmlns="http://tempuri.org/">
<!-- Request body removed -->
</Connect>
</s:Body>
</s:Envelope>
This returns a valid response.
The problem is when I switch to a WS HTTPS connection between the client
service and the router and keep the WS HTTP connection between the router
and the target service, it's logging the WS-RM messages:
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<a:Action
s:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequence</a:Action>
<a:MessageID>urn:uuid:96d7c674-471e-4c9d-8ba5-7a1c8ed3275b</a:MessageID>
<a:To s:mustUnderstand="1">https://foobox:44300/RouterService.svc</a:To>
</s:Header>
<s:Body>
<CreateSequence xmlns="http://schemas.xmlsoap.org/ws/2005/02/rm">
<AcksTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</AcksTo>
<Offer>
<Identifier>urn:uuid:de2129d5-58f2-4672-915f-eb3196d51bff</Identifier>
</Offer>
</CreateSequence>
</s:Body>
</s:Envelope>
And this is generating the following ActionNotSupported exception in the
client service:
The message with Action
'http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequence' cannot be
processed at the receiver, due to a ContractFilter mismatch at the
EndpointDispatcher. This may be because of either a contract mismatch
(mismatched Actions between sender and receiver) or a binding/security
mismatch between the sender and the receiver. Check that sender and
receiver have the same contract and the same binding (including security
requirements, e.g. Message, Transport, None).
This error makes sense considering that the service interface doesn't
handle CreateSequence messages but I'm not sure why switching to SSL
causes these to be explicitly sent to the target service.
What can I do to get the router to properly pass/handle the WS-RM packets?
I have a WCF Router setup where the client communicates to the target
service with WS Http bindings using reliable messaging (RMP.) When the
connection between client service to router is WS HTTP and router to
target service is WS HTTP, all works as expected. I log the SOAP packets
as they hit the router and they look like:
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
xmlns:r="http://docs.oasis-open.org/ws-rx/wsrm/200702"
xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<r:Sequence s:mustUnderstand="1">
<r:Identifier>urn:uuid:76bac170-ace3-4a9b-8a5f-eba263cbdf57</r:Identifier>
<r:MessageNumber>1</r:MessageNumber>
</r:Sequence>
<a:Action s:mustUnderstand="1">http://tempuri.org/Foo/Connect</a:Action>
<a:MessageID>urn:uuid:d76b500f-f59e-41a1-9831-cb33e2f9eb3c</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<a:To s:mustUnderstand="1">http://foobox:62435/RouterService.svc</a:To>
</s:Header>
<s:Body>
<Connect xmlns="http://tempuri.org/">
<!-- Request body removed -->
</Connect>
</s:Body>
</s:Envelope>
This returns a valid response.
The problem is when I switch to a WS HTTPS connection between the client
service and the router and keep the WS HTTP connection between the router
and the target service, it's logging the WS-RM messages:
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<a:Action
s:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequence</a:Action>
<a:MessageID>urn:uuid:96d7c674-471e-4c9d-8ba5-7a1c8ed3275b</a:MessageID>
<a:To s:mustUnderstand="1">https://foobox:44300/RouterService.svc</a:To>
</s:Header>
<s:Body>
<CreateSequence xmlns="http://schemas.xmlsoap.org/ws/2005/02/rm">
<AcksTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</AcksTo>
<Offer>
<Identifier>urn:uuid:de2129d5-58f2-4672-915f-eb3196d51bff</Identifier>
</Offer>
</CreateSequence>
</s:Body>
</s:Envelope>
And this is generating the following ActionNotSupported exception in the
client service:
The message with Action
'http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequence' cannot be
processed at the receiver, due to a ContractFilter mismatch at the
EndpointDispatcher. This may be because of either a contract mismatch
(mismatched Actions between sender and receiver) or a binding/security
mismatch between the sender and the receiver. Check that sender and
receiver have the same contract and the same binding (including security
requirements, e.g. Message, Transport, None).
This error makes sense considering that the service interface doesn't
handle CreateSequence messages but I'm not sure why switching to SSL
causes these to be explicitly sent to the target service.
What can I do to get the router to properly pass/handle the WS-RM packets?
WPF TreeView - Context Menu on TreeViewItem doesn't appear
WPF TreeView - Context Menu on TreeViewItem doesn't appear
I have a user control with a TreeView where the nodes are generated
dinamically (in fact I use the HierarchicalDataTemplate property),
depending on the structure of an input XML. If I click with the left
button on the single node, the content of that part of XML appears on a
separate user control. The single node is visualized through the property
Header of a TreeViewItem.
What I would like to add, is a logic with the right button that simply
shows a contextual menu with few commands on that single node.
I searched for some material online (as I'm quite new to WPF) and tried
first to define a context Menu...
1st solution XAML:
<TreeView x:Name="treeViewStruttura" Panel.ZIndex="1"
HorizontalAlignment="Left" VerticalContentAlignment="Top" Width="200"
Height="Auto">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<HierarchicalDataTemplate.Resources>
<Style TargetType="{x:Type TreeViewItem}">
<EventSetter Event="PreviewMouseLeftButtonDown"
Handler="OnTreeNodeMouseClick" />
<EventSetter Event="PreviewMouseRightButtonDown"
Handler="OnTreeNodeMouseRightClick"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="BorderBrush" Value="LightGray" />
</Trigger>
</Style.Triggers>
<Style.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="4"/>
<Setter Property="BorderThickness" Value="4"/>
</Style>
</Style.Resources>
</Style>
</HierarchicalDataTemplate.Resources>
<TreeViewItem Header="{Binding Text}" x:Name="treeViewItem"
HorizontalAlignment="Left" HorizontalContentAlignment="Left"
BorderThickness="2">
<TreeViewItem.ContextMenu>
<ContextMenu IsEnabled="True" IsOpen="True" >
<MenuItem Command="ModificaArticolo" />
<MenuItem x:Name="menuItemCopy" Header="Copy" Command="Copy"
Tag="0"/>
</ContextMenu>
</TreeViewItem.ContextMenu>
</TreeViewItem>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
Codebehind:
public partial class DocumentView : UserControl
{
public DocumentView()
{
InitializeComponent();
PreviewMouseRightButtonDown +=
DocumentView_PreviewMouseRightButtonDown;
}
void DocumentView_PreviewMouseRightButtonDown(object sender,
MouseButtonEventArgs e)
{
MenuClick();
}
private void MenuClick()
{
ContextMenu menu = new ContextMenu();
var copyMenuItem = new MenuItem();
copyMenuItem.Command = System.Windows.Input.ApplicationCommands.Copy;
copyMenuItem.Header = "Copy";
menu.Items.Add(copyMenuItem);
menu.Visibility = System.Windows.Visibility.Visible;
menu.IsEnabled = true;
menu.IsOpen = true;
menu.Focusable = true;
}
}
Second solution, I tried to define a Context Menu outside the XAML TreeView:
<ContextMenuService.ContextMenu>
<ContextMenu x:Name="contextMenuTreeViewItem">
<Style TargetType="{x:Type TreeViewItem}" >
</Style>
<MenuItem x:Name="menuItemCopy" Header="Copy" Command="Copy"
Tag="0"/>
</ContextMenu>
</ContextMenuService.ContextMenu>
CodeBehind:
private void MenuClick()
{
this.contextMenuTreeViewItem.IsOpen = true;
this.contextMenuTreeViewItem.IsEnabled = true;
this.menuItemCopy.IsEnabled = true;
this.contextMenuTreeViewItem.StaysOpen = true;
}
I'm sure I'm doing something wrong but I can't say what precisely...plus I
saw the use of property ContextMenu as a Setter Property...and I can't
appreciate the differences on this approach.
Thx in advance for your help.
I have a user control with a TreeView where the nodes are generated
dinamically (in fact I use the HierarchicalDataTemplate property),
depending on the structure of an input XML. If I click with the left
button on the single node, the content of that part of XML appears on a
separate user control. The single node is visualized through the property
Header of a TreeViewItem.
What I would like to add, is a logic with the right button that simply
shows a contextual menu with few commands on that single node.
I searched for some material online (as I'm quite new to WPF) and tried
first to define a context Menu...
1st solution XAML:
<TreeView x:Name="treeViewStruttura" Panel.ZIndex="1"
HorizontalAlignment="Left" VerticalContentAlignment="Top" Width="200"
Height="Auto">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<HierarchicalDataTemplate.Resources>
<Style TargetType="{x:Type TreeViewItem}">
<EventSetter Event="PreviewMouseLeftButtonDown"
Handler="OnTreeNodeMouseClick" />
<EventSetter Event="PreviewMouseRightButtonDown"
Handler="OnTreeNodeMouseRightClick"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="BorderBrush" Value="LightGray" />
</Trigger>
</Style.Triggers>
<Style.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="4"/>
<Setter Property="BorderThickness" Value="4"/>
</Style>
</Style.Resources>
</Style>
</HierarchicalDataTemplate.Resources>
<TreeViewItem Header="{Binding Text}" x:Name="treeViewItem"
HorizontalAlignment="Left" HorizontalContentAlignment="Left"
BorderThickness="2">
<TreeViewItem.ContextMenu>
<ContextMenu IsEnabled="True" IsOpen="True" >
<MenuItem Command="ModificaArticolo" />
<MenuItem x:Name="menuItemCopy" Header="Copy" Command="Copy"
Tag="0"/>
</ContextMenu>
</TreeViewItem.ContextMenu>
</TreeViewItem>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
Codebehind:
public partial class DocumentView : UserControl
{
public DocumentView()
{
InitializeComponent();
PreviewMouseRightButtonDown +=
DocumentView_PreviewMouseRightButtonDown;
}
void DocumentView_PreviewMouseRightButtonDown(object sender,
MouseButtonEventArgs e)
{
MenuClick();
}
private void MenuClick()
{
ContextMenu menu = new ContextMenu();
var copyMenuItem = new MenuItem();
copyMenuItem.Command = System.Windows.Input.ApplicationCommands.Copy;
copyMenuItem.Header = "Copy";
menu.Items.Add(copyMenuItem);
menu.Visibility = System.Windows.Visibility.Visible;
menu.IsEnabled = true;
menu.IsOpen = true;
menu.Focusable = true;
}
}
Second solution, I tried to define a Context Menu outside the XAML TreeView:
<ContextMenuService.ContextMenu>
<ContextMenu x:Name="contextMenuTreeViewItem">
<Style TargetType="{x:Type TreeViewItem}" >
</Style>
<MenuItem x:Name="menuItemCopy" Header="Copy" Command="Copy"
Tag="0"/>
</ContextMenu>
</ContextMenuService.ContextMenu>
CodeBehind:
private void MenuClick()
{
this.contextMenuTreeViewItem.IsOpen = true;
this.contextMenuTreeViewItem.IsEnabled = true;
this.menuItemCopy.IsEnabled = true;
this.contextMenuTreeViewItem.StaysOpen = true;
}
I'm sure I'm doing something wrong but I can't say what precisely...plus I
saw the use of property ContextMenu as a Setter Property...and I can't
appreciate the differences on this approach.
Thx in advance for your help.
Get the locator of the element upon which mouse is hovered/clicked
Get the locator of the element upon which mouse is hovered/clicked
I want to know a way of extracting id/locator of the element in the dom on
which mouse is hovered/clicked. I want to capture this in my code.
Ex:
Consider a web page which has a button with id=saveButton.
I will be running the deamon code at the back end.
When a user clicks the button, I want my code to capture the mouse event
which is click and locator which is @saveButton.
Please let me know how to do this. Code in jave would be helpful.
Thanks in advance.
I want to know a way of extracting id/locator of the element in the dom on
which mouse is hovered/clicked. I want to capture this in my code.
Ex:
Consider a web page which has a button with id=saveButton.
I will be running the deamon code at the back end.
When a user clicks the button, I want my code to capture the mouse event
which is click and locator which is @saveButton.
Please let me know how to do this. Code in jave would be helpful.
Thanks in advance.
Tuesday, 10 September 2013
Python: Trying to fix my insult generator
Python: Trying to fix my insult generator
So I'm trying to build an insult generator that will take lists, randomize
the inputs, and show the randomized code at the push of a button.
Right now, the code looks like...
import Tkinter
import random
section1=["list of stuff"]
section2=["list of stuff"]
section3=["list of stuff"]
class myapp(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent=parent
self.initialize()
def initialize(self):
self.grid() ##creates grid layout manager where we can place our
widgets within the window
button = Tkinter.Button(self, text=u"Generate!",
command=self.OnButtonClick)
button.grid(column=1,row=0)
self.labelVariable = Tkinter.StringVar()
label = Tkinter.Label(self, textvariable=self.labelVariable,
anchor='w', fg='white', bg='green')
label.grid(column=0,row=1, columnspan=2, sticky='EW')
self.labelVariable.set(u"Oh hi there !")
self.grid_columnconfigure(0,weight=1)
self.resizable(True,False)
self.update()
self.geometry(self.geometry())
def generator():
a= random.randint(0,int(len(section1))-1)
b= random.randint(0,int(len(section2))-1)
c= random.randint(0,int(len(section3))-1)
myText= "You are a "+ section1[a]+"
"+section2[b]+'-'+section3[c]+"! Fucker."
return myText
def OnButtonClick(self):
self.labelVariable.set(myText+"(You clicked the button !)")
self.entry.focus_set()
self.entry.selection_range(0,Tkinter.END)
if __name__=='__main__':
app= myapp(None) ##instanciates the class
app.title('Random Insult Generator') ##names the window we're creating.
app.mainloop() ##Program will loop indefinitely, awaiting input
Right now, the error it's giving is that the myText isn't defined. Have
any thoughts on how to fix it? Thanks in advance for your help!
Edit: The error message is...
Exception in Tkinter callback Traceback (most recent call last): File
"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py",
line 1470, in call return self.func(*args) File "...", line 41, in
OnButtonClick self.labelVariable.set(myText+"(You clicked the button !)")
NameError: global name 'myText' is not defined
So I'm trying to build an insult generator that will take lists, randomize
the inputs, and show the randomized code at the push of a button.
Right now, the code looks like...
import Tkinter
import random
section1=["list of stuff"]
section2=["list of stuff"]
section3=["list of stuff"]
class myapp(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent=parent
self.initialize()
def initialize(self):
self.grid() ##creates grid layout manager where we can place our
widgets within the window
button = Tkinter.Button(self, text=u"Generate!",
command=self.OnButtonClick)
button.grid(column=1,row=0)
self.labelVariable = Tkinter.StringVar()
label = Tkinter.Label(self, textvariable=self.labelVariable,
anchor='w', fg='white', bg='green')
label.grid(column=0,row=1, columnspan=2, sticky='EW')
self.labelVariable.set(u"Oh hi there !")
self.grid_columnconfigure(0,weight=1)
self.resizable(True,False)
self.update()
self.geometry(self.geometry())
def generator():
a= random.randint(0,int(len(section1))-1)
b= random.randint(0,int(len(section2))-1)
c= random.randint(0,int(len(section3))-1)
myText= "You are a "+ section1[a]+"
"+section2[b]+'-'+section3[c]+"! Fucker."
return myText
def OnButtonClick(self):
self.labelVariable.set(myText+"(You clicked the button !)")
self.entry.focus_set()
self.entry.selection_range(0,Tkinter.END)
if __name__=='__main__':
app= myapp(None) ##instanciates the class
app.title('Random Insult Generator') ##names the window we're creating.
app.mainloop() ##Program will loop indefinitely, awaiting input
Right now, the error it's giving is that the myText isn't defined. Have
any thoughts on how to fix it? Thanks in advance for your help!
Edit: The error message is...
Exception in Tkinter callback Traceback (most recent call last): File
"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py",
line 1470, in call return self.func(*args) File "...", line 41, in
OnButtonClick self.labelVariable.set(myText+"(You clicked the button !)")
NameError: global name 'myText' is not defined
Using a select clause in a case statement in TD
Using a select clause in a case statement in TD
Is it possible to somehow use a select clause in a case statement in TD
(rather than doing a join)?
I would like to do something like this:
SELECT
id
, CASE(id IN ANY (SELECT DISTINCT ID FROM PARTICIPANTS_TABLE) THEN 1
ELSE 0 end) AS participant
FROM EVERYONE_TABLE
Is it possible to somehow use a select clause in a case statement in TD
(rather than doing a join)?
I would like to do something like this:
SELECT
id
, CASE(id IN ANY (SELECT DISTINCT ID FROM PARTICIPANTS_TABLE) THEN 1
ELSE 0 end) AS participant
FROM EVERYONE_TABLE
xcode version visible from the ipa
xcode version visible from the ipa
I have few versions of Xcode installed in my mac. Lately I noticed that
some of my code compiles and does what it should when built using xcode
4.6.3. But it does not behave as expected when built using xcode 4.4.1.
Question: Is it possible to know about the xcode version from the ipa (iOS
application) itself?
Thanks and I shall really appreciate sharing your knowledge and thoughts
on this.
I have few versions of Xcode installed in my mac. Lately I noticed that
some of my code compiles and does what it should when built using xcode
4.6.3. But it does not behave as expected when built using xcode 4.4.1.
Question: Is it possible to know about the xcode version from the ipa (iOS
application) itself?
Thanks and I shall really appreciate sharing your knowledge and thoughts
on this.
Robotium test single app with two package structures
Robotium test single app with two package structures
I'm trying to setup Robotium and have a problem getting it to run with my
current package structure. I believe the trouble is because my apk's
package is com.name1.mobile but my launcher activity is
com.name2.mobile.login.LoginActivity (name1 and name2 substituted for
actual package name for anonymity).
So far the most helpful tidbit for me with Robotium setup is this
To make this work you need to know the package name and the launcher
activity name. Those can be obtained by starting the application in the
emulator and whatching the logs (adb logcat). The log shows what the
package name and the activity name are. An example of how the log message
can look like: "Starting activity: Intent { act=android.intent.action.MAIN
cat=android.intent.category.LAUNCHER? flg=0x10200000
cmp=com.example.android.notepad/.NotesList"
This is what my application logs
Starting: Intent { act=android.intent.action.MAIN
cat=[android.intent.category.LAUNCHER]
cmp=com.name1.mobile/com.name2.mobile.login.LoginActivity }
If I'm violating some android standard by having multiple package
structures I'd appreciate input on that otherwise the closest answer to
this I've been able to find is from here but it's speaking more to testing
two applications.
Is it possible to write a test case that spans over 2 applications?
No, that is not possible. In the AndroidManifest.xml you state which
target application you want to test.
Does this apply to me since I have two package structures within a single
application?
I'm trying to setup Robotium and have a problem getting it to run with my
current package structure. I believe the trouble is because my apk's
package is com.name1.mobile but my launcher activity is
com.name2.mobile.login.LoginActivity (name1 and name2 substituted for
actual package name for anonymity).
So far the most helpful tidbit for me with Robotium setup is this
To make this work you need to know the package name and the launcher
activity name. Those can be obtained by starting the application in the
emulator and whatching the logs (adb logcat). The log shows what the
package name and the activity name are. An example of how the log message
can look like: "Starting activity: Intent { act=android.intent.action.MAIN
cat=android.intent.category.LAUNCHER? flg=0x10200000
cmp=com.example.android.notepad/.NotesList"
This is what my application logs
Starting: Intent { act=android.intent.action.MAIN
cat=[android.intent.category.LAUNCHER]
cmp=com.name1.mobile/com.name2.mobile.login.LoginActivity }
If I'm violating some android standard by having multiple package
structures I'd appreciate input on that otherwise the closest answer to
this I've been able to find is from here but it's speaking more to testing
two applications.
Is it possible to write a test case that spans over 2 applications?
No, that is not possible. In the AndroidManifest.xml you state which
target application you want to test.
Does this apply to me since I have two package structures within a single
application?
How to call method which is placed in class stored in array of objects?
How to call method which is placed in class stored in array of objects?
I have class Jorney where you have several variables and some methods that
returns those variables values.
public class Jorney {
private int timeH;
public Jorney(int timeH)
{
this.timeH=timeH;
}
private int getTimeH()
{
return townFrom;
}
}
and than i have another class where i create ArrayList of objects
ArrayList<Object> myJorney = new ArrayList<Object>();
now when I add some objects to ArrayList my aim is to go through all those
'jorneys'(objects) call getTimeH() method and store its parameters in
variables.
I use iterator to go from one object to another but dunno how to call the
method.
private int totalTime()
{
Iterator<Object> i = myJorney.iterator();
int sum;
while (i.hasNext()) {
Object j = i.next();
int hour= j.getTimeH();
sum=sum+hour;
}
return sum;
I am wondering if someone could help me with that?
I have class Jorney where you have several variables and some methods that
returns those variables values.
public class Jorney {
private int timeH;
public Jorney(int timeH)
{
this.timeH=timeH;
}
private int getTimeH()
{
return townFrom;
}
}
and than i have another class where i create ArrayList of objects
ArrayList<Object> myJorney = new ArrayList<Object>();
now when I add some objects to ArrayList my aim is to go through all those
'jorneys'(objects) call getTimeH() method and store its parameters in
variables.
I use iterator to go from one object to another but dunno how to call the
method.
private int totalTime()
{
Iterator<Object> i = myJorney.iterator();
int sum;
while (i.hasNext()) {
Object j = i.next();
int hour= j.getTimeH();
sum=sum+hour;
}
return sum;
I am wondering if someone could help me with that?
How to pass argument got from ellipsis oprator to other function?
How to pass argument got from ellipsis oprator to other function?
void myPrintf(const char* format, ...) {
// some code
va_list vl;
printf(format, vl);
}
int main() {
myPrintf("%d\n", 78);
}
In this code I have tried to pass the argument from ellipsis to printf. It
compiles but prints garbage instead of 78. What is the right way of doing
it.
void myPrintf(const char* format, ...) {
// some code
va_list vl;
printf(format, vl);
}
int main() {
myPrintf("%d\n", 78);
}
In this code I have tried to pass the argument from ellipsis to printf. It
compiles but prints garbage instead of 78. What is the right way of doing
it.
setDirectoryURL is not working first time
setDirectoryURL is not working first time
Why NSOpenPanel, opens ~/Documents folder first time?
NSOpenPanel* restorePanel = [NSOpenPanel openPanel];
[restorePanel setCanCreateDirectories: YES];
[restorePanel setCanChooseDirectories:YES];
[restorePanel setCanChooseFiles:NO];
[restorePanel setAllowsMultipleSelection: NO];
[restorePanel setTitle:@"My app?"];
[restorePanel setNameFieldLabel:@"App to:"];
[restorePanel setPrompt:@"Choose"];
[restorePanel setDirectoryURL:[NSURL fileURLWithPath:ValidPath]];
NSLog(@"%@", [restorePanel directoryURL]); // ValidPath URL
If i will call
[[NSUserDefaults standardUserDefaults] setObject:restoreSaveFolder
forKey:@"NSNavLastRootDirectory"];
in awakeFromNib its working fine.
Why NSOpenPanel, opens ~/Documents folder first time?
NSOpenPanel* restorePanel = [NSOpenPanel openPanel];
[restorePanel setCanCreateDirectories: YES];
[restorePanel setCanChooseDirectories:YES];
[restorePanel setCanChooseFiles:NO];
[restorePanel setAllowsMultipleSelection: NO];
[restorePanel setTitle:@"My app?"];
[restorePanel setNameFieldLabel:@"App to:"];
[restorePanel setPrompt:@"Choose"];
[restorePanel setDirectoryURL:[NSURL fileURLWithPath:ValidPath]];
NSLog(@"%@", [restorePanel directoryURL]); // ValidPath URL
If i will call
[[NSUserDefaults standardUserDefaults] setObject:restoreSaveFolder
forKey:@"NSNavLastRootDirectory"];
in awakeFromNib its working fine.
Monday, 9 September 2013
Big O of this code
Big O of this code
I am doing the exercise of Skiena's book on algorithms and I am stuck in
this question:
I need to calculate the big O of the following algorithm:
function mystery()
r=0
for i=1 to n-1 do
for j=i+1 to n do
for k=1 to j do
r=r+1
Here, the big O of the outermost loop will be O(n-1) and the middle loop
will be O(n!). Please tell me if I am wrong here.
I am not able to calculate the big O of the innermost loop.
Can anyone please help me with this?
I am doing the exercise of Skiena's book on algorithms and I am stuck in
this question:
I need to calculate the big O of the following algorithm:
function mystery()
r=0
for i=1 to n-1 do
for j=i+1 to n do
for k=1 to j do
r=r+1
Here, the big O of the outermost loop will be O(n-1) and the middle loop
will be O(n!). Please tell me if I am wrong here.
I am not able to calculate the big O of the innermost loop.
Can anyone please help me with this?
MS SQL Server: Binary datatype for Primary Keys Vs Int?
MS SQL Server: Binary datatype for Primary Keys Vs Int?
Are there performance (or other) issues using the Binary datatype for
Primary Keys. The database has a are a large number of large tables that
are regularly joined using these keys. The indexes are clustered. I
believe that these can't be automatically incremented (as an Identity
field).
Are there performance (or other) issues using the Binary datatype for
Primary Keys. The database has a are a large number of large tables that
are regularly joined using these keys. The indexes are clustered. I
believe that these can't be automatically incremented (as an Identity
field).
Converting elements of String[] to Scanner object
Converting elements of String[] to Scanner object
I'm new to Java, and what I've been trying to do:
tempTrailerArris a String[] = {"12.0 1.1", "24.51", "34.12", "82.87 231.2
1.1 2.2"}
Each element of tempTrailerArr is converted into a Scanner object trScan.
The first double of each element in tempTrailerArr is to be stored in a
Double[] called trailerVals.
So the desired result would be for tempTrailerArr = {12.0 24.51 34.12 82.87}
However, the code below won't terminate, and I don't understand why?
for (int j=0; j<tempTrailerArr.length; j++) {
Scanner trScan = new Scanner(tempTrailerArr[j]);
switch (j) {
case 0:
case 1:
case 2:
case 3: this.trailerVals[j] = trScan.nextDouble();
break;
}
}
I'm new to Java, and what I've been trying to do:
tempTrailerArris a String[] = {"12.0 1.1", "24.51", "34.12", "82.87 231.2
1.1 2.2"}
Each element of tempTrailerArr is converted into a Scanner object trScan.
The first double of each element in tempTrailerArr is to be stored in a
Double[] called trailerVals.
So the desired result would be for tempTrailerArr = {12.0 24.51 34.12 82.87}
However, the code below won't terminate, and I don't understand why?
for (int j=0; j<tempTrailerArr.length; j++) {
Scanner trScan = new Scanner(tempTrailerArr[j]);
switch (j) {
case 0:
case 1:
case 2:
case 3: this.trailerVals[j] = trScan.nextDouble();
break;
}
}
Mule 3.3.1. Custom component to read messages from queue
Mule 3.3.1. Custom component to read messages from queue
I am trying to write a Component that reads all available messages from
queue, which I intend to be polled using a Quartz scheduler.
Here is my code.
@Override
public Object onCall(MuleEventContext muleEventContext) throws Exception {
MuleMessage[] messages = null;
MuleMessage result = muleEventContext.getMessage();
do {
if (result == null) {
break;
}
if (result instanceof MuleMessageCollection) {
MuleMessageCollection resultsCollection =
(MuleMessageCollection) result;
System.out.println("Number of messages: " +
resultsCollection.size());
messages = resultsCollection.getMessagesAsArray();
} else {
messages = new MuleMessage[1];
messages[0] = result;
}
result = muleEventContext.getMessage();
} while (result !=null);
return messages;
}
Unfortunately, it loops indefinitely on the first message. Thoughts?
I am trying to write a Component that reads all available messages from
queue, which I intend to be polled using a Quartz scheduler.
Here is my code.
@Override
public Object onCall(MuleEventContext muleEventContext) throws Exception {
MuleMessage[] messages = null;
MuleMessage result = muleEventContext.getMessage();
do {
if (result == null) {
break;
}
if (result instanceof MuleMessageCollection) {
MuleMessageCollection resultsCollection =
(MuleMessageCollection) result;
System.out.println("Number of messages: " +
resultsCollection.size());
messages = resultsCollection.getMessagesAsArray();
} else {
messages = new MuleMessage[1];
messages[0] = result;
}
result = muleEventContext.getMessage();
} while (result !=null);
return messages;
}
Unfortunately, it loops indefinitely on the first message. Thoughts?
Print array of elements into table or unordered list. jQuery or HTML
Print array of elements into table or unordered list. jQuery or HTML
I have an array of elements, I print them out using the following:
function extractResult(result){
jQuery.each(result, function(index, value) {
console.log(index, value);
});
};
It prints out to the console like this:
Mr.
Jim
00000001VKnAAL
Smith
sales
Prof.
3d000001VKkAAL
I want to print it out into a table or unordered list. Could anyone
suggest how I could go about doing this?
I'm happy to use a dynamically generated jQuery table or unordered list if
that would be best.
Cheers!
I have an array of elements, I print them out using the following:
function extractResult(result){
jQuery.each(result, function(index, value) {
console.log(index, value);
});
};
It prints out to the console like this:
Mr.
Jim
00000001VKnAAL
Smith
sales
Prof.
3d000001VKkAAL
I want to print it out into a table or unordered list. Could anyone
suggest how I could go about doing this?
I'm happy to use a dynamically generated jQuery table or unordered list if
that would be best.
Cheers!
phpCgiHandler. Exception: java.net.SocketException: Broken pipe
phpCgiHandler. Exception: java.net.SocketException: Broken pipe
I have a javascript app running on a mobile device (as a web server) that
performs several web services locally for each execution. The web services
are php codes. It works fine for small data. But, when the computation and
time grows, the client raises the POST FAILED error. I checked the PhP log
file and found phpCgiHandler. Exception: java.net.SocketException: Broken
pipe exception error.
I searched and found quiet several questions about this problem in stack
overflow, but non of them provide solution to this problem. According to
the answers, the error raise because the connection will be closed after
120 seconds and in my case the 120 second already reached so the
connection is closed before the call is finished.
In this case, can I set client/server not to close the connection? Similar
to a parameter in php.ini that we can perform some runtime setting, is
there anything we can do to avoid the connection dies after 120 seconds?
Sorry for being old question. I hope I can get solution of how to avoid it.
I have a javascript app running on a mobile device (as a web server) that
performs several web services locally for each execution. The web services
are php codes. It works fine for small data. But, when the computation and
time grows, the client raises the POST FAILED error. I checked the PhP log
file and found phpCgiHandler. Exception: java.net.SocketException: Broken
pipe exception error.
I searched and found quiet several questions about this problem in stack
overflow, but non of them provide solution to this problem. According to
the answers, the error raise because the connection will be closed after
120 seconds and in my case the 120 second already reached so the
connection is closed before the call is finished.
In this case, can I set client/server not to close the connection? Similar
to a parameter in php.ini that we can perform some runtime setting, is
there anything we can do to avoid the connection dies after 120 seconds?
Sorry for being old question. I hope I can get solution of how to avoid it.
Tomcat - FileNotFoundException
Tomcat - FileNotFoundException
I have a web application deployed on my tomcat server. My folder structure
is TOMCAT_HOME/webapps/segnalazioni_degrado/config.
The config folder contains some properties files. When I run my
application in Development Mode (Eclipse) everything works fine, but since
I deployed it on Tomcat I am getting the filenotfound exception. This is
the way I load the .properties file on the server:
[...]
Properties props = new Properties();
try {
props.load(new FileInputStream("config/DBconfig.properties"));
} catch (IOException e) {
System.out.println(e.getMessage());
}
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
[...]
Am I doing something wrong?
I have a web application deployed on my tomcat server. My folder structure
is TOMCAT_HOME/webapps/segnalazioni_degrado/config.
The config folder contains some properties files. When I run my
application in Development Mode (Eclipse) everything works fine, but since
I deployed it on Tomcat I am getting the filenotfound exception. This is
the way I load the .properties file on the server:
[...]
Properties props = new Properties();
try {
props.load(new FileInputStream("config/DBconfig.properties"));
} catch (IOException e) {
System.out.println(e.getMessage());
}
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
[...]
Am I doing something wrong?
Jquery shopping cart doesn't trigger price, subtotal and totalcost
Jquery shopping cart doesn't trigger price, subtotal and totalcost
Its my first shopping cart and I'm not sure is the right way to build it
however I got few functions that aren't working properly. The price should
render not just on change and the incremented number should trigger the
price, the subtotal and the totalcost! IF someone has any ideas to help me
fix my mistake, I'd really appreciate it. Here's the problematic demo and
script:
http://plnkr.co/edit/Y6lyX5ncW1381hpeBNxm
shoppingCart: function () {
numberIncrementer();
updateQuantity(this);
/* Set rates + misc */
var taxRate = 0.20;
var fadeTime = 300;
/* Assign actions */
$('.product-quantity input').change( function() {
updateQuantity(this);
});
$('.product-removal button').click( function() {
removeItem(this);
});
/* Recalculate cart */
function recalculateCart() {
var subtotal = 0;
/* Sum up row totals */
$('.product').each(function () {
subtotal += parseFloat($(this).children('.product-line-price').text());
});
/* Calculate totals */
var tax = subtotal * taxRate;
var total = subtotal + tax;
/* Update totals display */
$('.totals-value').fadeOut(fadeTime, function() {
$('#cart-subtotal').html(subtotal.toFixed(2));
$('#cart-tax').html(tax.toFixed(2));
$('#cart-total').html(total.toFixed(2));
if(total == 0){
$('.checkout').fadeOut(fadeTime);
}else{
$('.checkout').fadeIn(fadeTime);
}
$('.totals-value').fadeIn(fadeTime);
});
}
/* Update quantity */
function updateQuantity(quantityInput) {
/* Calculate line price */
var productRow = $(quantityInput).parent().parent();
var price = parseFloat(productRow.children('.product-price').text());
var quantity = $(quantityInput).val();
var linePrice = price * quantity;
/* Update line price display and recalc cart totals */
productRow.children('.product-line-price').each(function () {
$(this).fadeOut(fadeTime, function() {
$(this).text(linePrice.toFixed(2));
recalculateCart();
$(this).fadeIn(fadeTime);
});
});
}
/* Remove item from cart */
function removeItem(removeButton) {
/* Remove row from DOM and recalc cart total */
var productRow = $(removeButton).parent().parent();
productRow.slideUp(fadeTime, function() {
productRow.remove();
recalculateCart();
});
}
function numberIncrementer(){
$("div.product-quantity").append('<div class="inc
button">+</div><div class="dec button">-</div>');
$(".button").on("click", function() {
var $button = $(this);
var oldValue = $button.parent().find("input").val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
$button.parent().find("input").val(newVal);
});
}
}
Its my first shopping cart and I'm not sure is the right way to build it
however I got few functions that aren't working properly. The price should
render not just on change and the incremented number should trigger the
price, the subtotal and the totalcost! IF someone has any ideas to help me
fix my mistake, I'd really appreciate it. Here's the problematic demo and
script:
http://plnkr.co/edit/Y6lyX5ncW1381hpeBNxm
shoppingCart: function () {
numberIncrementer();
updateQuantity(this);
/* Set rates + misc */
var taxRate = 0.20;
var fadeTime = 300;
/* Assign actions */
$('.product-quantity input').change( function() {
updateQuantity(this);
});
$('.product-removal button').click( function() {
removeItem(this);
});
/* Recalculate cart */
function recalculateCart() {
var subtotal = 0;
/* Sum up row totals */
$('.product').each(function () {
subtotal += parseFloat($(this).children('.product-line-price').text());
});
/* Calculate totals */
var tax = subtotal * taxRate;
var total = subtotal + tax;
/* Update totals display */
$('.totals-value').fadeOut(fadeTime, function() {
$('#cart-subtotal').html(subtotal.toFixed(2));
$('#cart-tax').html(tax.toFixed(2));
$('#cart-total').html(total.toFixed(2));
if(total == 0){
$('.checkout').fadeOut(fadeTime);
}else{
$('.checkout').fadeIn(fadeTime);
}
$('.totals-value').fadeIn(fadeTime);
});
}
/* Update quantity */
function updateQuantity(quantityInput) {
/* Calculate line price */
var productRow = $(quantityInput).parent().parent();
var price = parseFloat(productRow.children('.product-price').text());
var quantity = $(quantityInput).val();
var linePrice = price * quantity;
/* Update line price display and recalc cart totals */
productRow.children('.product-line-price').each(function () {
$(this).fadeOut(fadeTime, function() {
$(this).text(linePrice.toFixed(2));
recalculateCart();
$(this).fadeIn(fadeTime);
});
});
}
/* Remove item from cart */
function removeItem(removeButton) {
/* Remove row from DOM and recalc cart total */
var productRow = $(removeButton).parent().parent();
productRow.slideUp(fadeTime, function() {
productRow.remove();
recalculateCart();
});
}
function numberIncrementer(){
$("div.product-quantity").append('<div class="inc
button">+</div><div class="dec button">-</div>');
$(".button").on("click", function() {
var $button = $(this);
var oldValue = $button.parent().find("input").val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
$button.parent().find("input").val(newVal);
});
}
}
Sunday, 8 September 2013
Select record Details and its own table count in select statements where Each record have its own table
Select record Details and its own table count in select statements where
Each record have its own table
I have a table with recordid ,record name, and an extra column with its
corresponding Table name. Each record have its own table . Now I want to
select record name , id and its corresponding table count using select
query in sql. Please help me ..
Thank You
Each record have its own table
I have a table with recordid ,record name, and an extra column with its
corresponding Table name. Each record have its own table . Now I want to
select record name , id and its corresponding table count using select
query in sql. Please help me ..
Thank You
Getting the correct spindle load call from the Okuma API
Getting the correct spindle load call from the Okuma API
I am trying to call the load for each spindle on a lathe. I have found in
the API help the calling for the axis loads and that works fine, but am
not having luck calling the correct calls for the spindle loads. Before a
I work on subsystem calls want to make the first spindle work. Below is
what I have tried.
Axis load example (works fine):
private object zaxisload()
{
return objaxis.GetAxisLoad(AxisIndex2Enum.Z_Axis);
}
Attempt for spindle loads:
private object firstspindleload()
{
return objSpindle.GetSpindleLoad;
}
I have run the a program and the axis loads return a value, but the
spindle load doesn't return any values.
I am trying to call the load for each spindle on a lathe. I have found in
the API help the calling for the axis loads and that works fine, but am
not having luck calling the correct calls for the spindle loads. Before a
I work on subsystem calls want to make the first spindle work. Below is
what I have tried.
Axis load example (works fine):
private object zaxisload()
{
return objaxis.GetAxisLoad(AxisIndex2Enum.Z_Axis);
}
Attempt for spindle loads:
private object firstspindleload()
{
return objSpindle.GetSpindleLoad;
}
I have run the a program and the axis loads return a value, but the
spindle load doesn't return any values.
Running twistd with wrong python version
Running twistd with wrong python version
Twisted is doing this
" 2013-09-08 19:09:24-0400 [-] twistd 13.1.0 (/usr/bin/python 2.6.6)
starting up.
2013-09-08 19:09:24-0400 [-] reactor class:
twisted.internet.epollreactor.EPollReactor. "
and nothing is happening, i'm sure it needs to be using 2.7. I installed
Python 2.7 I do not understand why it's not using python 2.7.
Twisted is doing this
" 2013-09-08 19:09:24-0400 [-] twistd 13.1.0 (/usr/bin/python 2.6.6)
starting up.
2013-09-08 19:09:24-0400 [-] reactor class:
twisted.internet.epollreactor.EPollReactor. "
and nothing is happening, i'm sure it needs to be using 2.7. I installed
Python 2.7 I do not understand why it's not using python 2.7.
How to get Google Maps route planner on website's iframe
How to get Google Maps route planner on website's iframe
I'm programming a new (wordpress) website and there is a "Contact" menu
item. In this menu item I got a map (code by Google Maps iframe). Now I
should have a route planner under the map. For this I got a little code:
<form name="search_route" method="get" action="http://maps.google.com/"
target="_blank">
<input name="saddr" type="text" id="saddr">
<input name="daddr" type="hidden" id="daddr" value="Empire State
Building, 350 5th Avenue, New York, NY, USA">
<input type="submit" name="Submit" value="Submit">
</form>
My problem: The code is working, but it links to maps.google.com like I
told the form. But the route should plan on the iframe I got on the page
and not open another link. Is this possible? If yes, can someone give me a
hint?
Thanks in advance
Cheers
I'm programming a new (wordpress) website and there is a "Contact" menu
item. In this menu item I got a map (code by Google Maps iframe). Now I
should have a route planner under the map. For this I got a little code:
<form name="search_route" method="get" action="http://maps.google.com/"
target="_blank">
<input name="saddr" type="text" id="saddr">
<input name="daddr" type="hidden" id="daddr" value="Empire State
Building, 350 5th Avenue, New York, NY, USA">
<input type="submit" name="Submit" value="Submit">
</form>
My problem: The code is working, but it links to maps.google.com like I
told the form. But the route should plan on the iframe I got on the page
and not open another link. Is this possible? If yes, can someone give me a
hint?
Thanks in advance
Cheers
Getting all text from DOM
Getting all text from DOM
Ok, so I have this simple HTML code
<html>
<head>
<script src="jquery.js"></script>
<script src="script.js"></script>
<title>Get all text</title>
</head>
<body>
<span>This is Thomas</span>
This is Bar
<div id="content">
This is Foo.
</div>
<span>This is Bufu</span>
</body>
</html>
And i want to get all text in a variable. So i made this javascript code.
But "This is Foo" and "This is Bar" are not shown.
var sep = '~';
$(function() {
pageTexts = getTextFromPage();
console.log(pageTexts);
});
function getTextFromPage()
{
var pageText = '';
i = 0;
j = 0;
var itr = document.createTreeWalker(
document.getElementsByTagName("body")[0],
NodeFilter.SHOW_TEXT,
null, // no filter
false
);
while(itr.nextNode())
{
if (itr.currentNode.textContent.search("\t") &&
itr.currentNode.textContent.search("\n") &&
itr.currentNode.parentNode.nodeName.toLowerCase() != 'script' &&
itr.currentNode.parentNode.nodeName.toLowerCase() != 'noscript')
{
if (i == 0)
{
pageText = itr.currentNode.textContent;
i++;
}
else
{
pageText = pageText + sep + itr.currentNode.textContent;
i++;
}
}
charNumber = pageText.length;
elemNumber = i;
}
return pageText;
}
Current result is "This is Thomas~This is Bufu". And I would like to have
"This is Thomas~This is Bar~This is Foo~This is Bufu". Can anyone tell me
what is wrong or what should I do? I will apreciate any answer that helps
me. PS. This is for a chrome-extension and i will need to get all text
from any html page even if is a very complicated page.
Ok, so I have this simple HTML code
<html>
<head>
<script src="jquery.js"></script>
<script src="script.js"></script>
<title>Get all text</title>
</head>
<body>
<span>This is Thomas</span>
This is Bar
<div id="content">
This is Foo.
</div>
<span>This is Bufu</span>
</body>
</html>
And i want to get all text in a variable. So i made this javascript code.
But "This is Foo" and "This is Bar" are not shown.
var sep = '~';
$(function() {
pageTexts = getTextFromPage();
console.log(pageTexts);
});
function getTextFromPage()
{
var pageText = '';
i = 0;
j = 0;
var itr = document.createTreeWalker(
document.getElementsByTagName("body")[0],
NodeFilter.SHOW_TEXT,
null, // no filter
false
);
while(itr.nextNode())
{
if (itr.currentNode.textContent.search("\t") &&
itr.currentNode.textContent.search("\n") &&
itr.currentNode.parentNode.nodeName.toLowerCase() != 'script' &&
itr.currentNode.parentNode.nodeName.toLowerCase() != 'noscript')
{
if (i == 0)
{
pageText = itr.currentNode.textContent;
i++;
}
else
{
pageText = pageText + sep + itr.currentNode.textContent;
i++;
}
}
charNumber = pageText.length;
elemNumber = i;
}
return pageText;
}
Current result is "This is Thomas~This is Bufu". And I would like to have
"This is Thomas~This is Bar~This is Foo~This is Bufu". Can anyone tell me
what is wrong or what should I do? I will apreciate any answer that helps
me. PS. This is for a chrome-extension and i will need to get all text
from any html page even if is a very complicated page.
After successfull login with FBSession reshowing login on opening another Fb page
After successfull login with FBSession reshowing login on opening another
Fb page
I have used FBSession for authentication to my app natively and this is
working fine, I am also getting the accesstoken.
But my problem is after that when i am loading the Client facebook page on
webView by passing the specific URl it is showing the page successfully
but its not loged in. Still i can see Join and Log in button on the top.
As i am already loged in then why to login again.
Friends give me some hint how to solve this.
Fb page
I have used FBSession for authentication to my app natively and this is
working fine, I am also getting the accesstoken.
But my problem is after that when i am loading the Client facebook page on
webView by passing the specific URl it is showing the page successfully
but its not loged in. Still i can see Join and Log in button on the top.
As i am already loged in then why to login again.
Friends give me some hint how to solve this.
C# Download Youtube Video and Convert in mp4 360p Resolution
C# Download Youtube Video and Convert in mp4 360p Resolution
In My Website We Need Download Youtube Video and Convert It Video In mp4
360p Resolution So Please Provide C#.net Code
In My Website We Need Download Youtube Video and Convert It Video In mp4
360p Resolution So Please Provide C#.net Code
Regarding Servlet and JSP
Regarding Servlet and JSP
I was practicing Servlet and JSP and got stuck with an scenario
this is my html page code.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Home</title>
</head>
<body>
<form action="Second.jsp" method="post">
<p>Name:<input type="text" name="name"/>
<p>Employee Id:<input type="text" name="empId" />
<p><input type="submit" value="Enter" />
</form>
</body>
</html>
JSP Code
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="person" class="com.Person" scope="request">
<jsp:setProperty name="person" property="name" />
</jsp:useBean>
<jsp:getProperty property="name" name="person"/>
</body>
</html>
Person.java
package com;
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My request goes directly to jsp and the form element name and bean
property name matches so no need tp set value in jsp:setProperty
However getProperty is showing null.
I was practicing Servlet and JSP and got stuck with an scenario
this is my html page code.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Home</title>
</head>
<body>
<form action="Second.jsp" method="post">
<p>Name:<input type="text" name="name"/>
<p>Employee Id:<input type="text" name="empId" />
<p><input type="submit" value="Enter" />
</form>
</body>
</html>
JSP Code
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="person" class="com.Person" scope="request">
<jsp:setProperty name="person" property="name" />
</jsp:useBean>
<jsp:getProperty property="name" name="person"/>
</body>
</html>
Person.java
package com;
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My request goes directly to jsp and the form element name and bean
property name matches so no need tp set value in jsp:setProperty
However getProperty is showing null.
Thread 1: signal SIGABRT in main.m file
Thread 1: signal SIGABRT in main.m file
Hey I need some help in Xcode. I am getting the error Thread 1: SIGABRT
and it is pointing to the main.m file. I set up the exception breakpoint
and it still stops in the main.m file.
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import "AppDelegate.h"
int main(int argc, char *argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil,
NSStringFromClass([AppDelegate class]));
}
}
That is the code that I have in my main.m file. Can someone please help me
with this error.
The full error is:
2013-09-07 23:41:05.440 save the jewel 5[86090:c07] -[game pause:]:
unrecognized selector sent to instance 0x845ece0
2013-09-07 23:41:09.460 save the jewel 5[86090:c07] *** Terminating app
due to uncaught exception 'NSInvalidArgumentException', reason: '-[game
pause:]: unrecognized selector sent to instance 0x845ece0'
*** First throw call stack:
(0x1693012 0x13a0e7e 0x171e4bd 0x1682bbc 0x168294e 0x13b4705 0x2e82c0
0x2e8258 0x3a9021 0x3a957f 0x3a86e8 0x317cef 0x317f02 0x2f5d4a 0x2e7698
0x26f5df9 0x26f5ad0 0x1608bf5 0x1608962 0x1639bb6 0x1638f44 0x1638e1b
0x26f47e3 0x26f4668 0x2e4ffc 0x23c2 0x22f5)
libc++abi.dylib: terminate called throwing an exception
Hey I need some help in Xcode. I am getting the error Thread 1: SIGABRT
and it is pointing to the main.m file. I set up the exception breakpoint
and it still stops in the main.m file.
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import "AppDelegate.h"
int main(int argc, char *argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil,
NSStringFromClass([AppDelegate class]));
}
}
That is the code that I have in my main.m file. Can someone please help me
with this error.
The full error is:
2013-09-07 23:41:05.440 save the jewel 5[86090:c07] -[game pause:]:
unrecognized selector sent to instance 0x845ece0
2013-09-07 23:41:09.460 save the jewel 5[86090:c07] *** Terminating app
due to uncaught exception 'NSInvalidArgumentException', reason: '-[game
pause:]: unrecognized selector sent to instance 0x845ece0'
*** First throw call stack:
(0x1693012 0x13a0e7e 0x171e4bd 0x1682bbc 0x168294e 0x13b4705 0x2e82c0
0x2e8258 0x3a9021 0x3a957f 0x3a86e8 0x317cef 0x317f02 0x2f5d4a 0x2e7698
0x26f5df9 0x26f5ad0 0x1608bf5 0x1608962 0x1639bb6 0x1638f44 0x1638e1b
0x26f47e3 0x26f4668 0x2e4ffc 0x23c2 0x22f5)
libc++abi.dylib: terminate called throwing an exception
Saturday, 7 September 2013
Facebook oAuth user details with MVC 4
Facebook oAuth user details with MVC 4
I am using the OAuthWebSecurity with MVC to allow users of my website to
login using Facebook's oAuth. Everything works fine, and I have a test
user authenticating fine.
My question is based on the details Facebook can provide. I am currently
returning the user details using the following...
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication();
This will give the follwing details:
UserName (email)
ProviderUserId
I also get a ExternalData object which has:
UserName
Name
Gender
Do you know if it's possible to get further data, maybe DoB, photo etc?
I am using the OAuthWebSecurity with MVC to allow users of my website to
login using Facebook's oAuth. Everything works fine, and I have a test
user authenticating fine.
My question is based on the details Facebook can provide. I am currently
returning the user details using the following...
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication();
This will give the follwing details:
UserName (email)
ProviderUserId
I also get a ExternalData object which has:
UserName
Name
Gender
Do you know if it's possible to get further data, maybe DoB, photo etc?
SetValidator for complex properties not working
SetValidator for complex properties not working
I have the following validation class for "Expense" entity:
public class ExpenseBaseValidator : AbstractValidator<Expense>
{
public ExpenseBaseValidator()
{
RuleFor(x => x.Description).NotEmpty();
RuleFor(x => x.Amount).NotNull();
RuleFor(x => x.BusinessID).NotEqual(0).WithMessage("BusinessID is
required.");
RuleFor(x =>
x.ExpenseTypeID).NotEqual(0).WithMessage("ExpenseTypeID is
required.");
RuleFor(x => x.CreatedDate).NotNull();
RuleFor(x => x.Transaction).SetValidator(new TransactionValidator());
}
}
Then I have validation class for Transaction which is a complex property
in Expense class above:
public class TransactionBaseValidator : AbstractValidator<Transaction>
{
public TransactionBaseValidator()
{
RuleFor(x =>
x.BankAccountID).NotEqual(0).WithMessage("BankAccountID is
required.");
RuleFor(x => x.EmployeeID).NotEqual(0).WithMessage("EmployeeID is
required.");
RuleFor(x => x.TransactionDate).NotNull();
RuleFor(x => x.IsWithdrawal).NotNull();
RuleFor(x => x.Amount).NotNull();
RuleFor(x => x.Description).NotEmpty();
RuleFor(x => x.PaymentMethod).NotEmpty();
RuleFor(x => x.PaymentMethod).Length(0,
50).WithMessage("PaymentMethod can not exceed 50 characters");
}
}
Now these are base classes and I call the validator using the following
child classes respectively:
public class ExpenseValidator : ExpenseBaseValidator
{
public ExpenseValidator()
: base()
{
RuleFor(x => x.Transaction)
.NotNull()
.When(x => x.IsPaid == true)
.WithMessage("An account transaction is required when the
amount is paid.");
RuleFor(x => x.DatePaid)
.NotNull()
.When(x => x.IsPaid == true)
.WithMessage("Please enter the date when the expense was paid.");
}
}
And Transaction child class:
public class TransactionValidator : TransactionBaseValidator
{
public TransactionValidator() : base()
{
}
}
And these can have extra rules for validation and the base rules are
called using the base() constructor.
And I validate the Expense object using this:
var validator = new ExpenseValidator();
var results = validator.Validate(oExpense);
Now this doesn't return the validation for the complex property
transaction which I am using in the following way:
oExpense.Transaction = new Transaction();
oExpense.Transaction.Amount = oExpense.Amount;
oExpense.Transaction.BankAccountID = ddlAccounts.SelectedItem.Value.ToInt();
oExpense.Transaction.TransactionDate = oExpense.DatePaid.Value;
oExpense.Transaction.IsWithdrawal = true;
oExpense.Transaction.Description = oExpense.Description;
oExpense.Transaction.IsDeleted = false;
// I dont set the below and it should give me validation error:
// oExpense.Transaction.EmployeeID = 10;
I don't set the EmployeeID and it should give me validation error when I
call validator for expense object as it has SetValidator() for the
Transaction property and the Transaction is also not null as I already set
new Transaction().
Any idea?
I have the following validation class for "Expense" entity:
public class ExpenseBaseValidator : AbstractValidator<Expense>
{
public ExpenseBaseValidator()
{
RuleFor(x => x.Description).NotEmpty();
RuleFor(x => x.Amount).NotNull();
RuleFor(x => x.BusinessID).NotEqual(0).WithMessage("BusinessID is
required.");
RuleFor(x =>
x.ExpenseTypeID).NotEqual(0).WithMessage("ExpenseTypeID is
required.");
RuleFor(x => x.CreatedDate).NotNull();
RuleFor(x => x.Transaction).SetValidator(new TransactionValidator());
}
}
Then I have validation class for Transaction which is a complex property
in Expense class above:
public class TransactionBaseValidator : AbstractValidator<Transaction>
{
public TransactionBaseValidator()
{
RuleFor(x =>
x.BankAccountID).NotEqual(0).WithMessage("BankAccountID is
required.");
RuleFor(x => x.EmployeeID).NotEqual(0).WithMessage("EmployeeID is
required.");
RuleFor(x => x.TransactionDate).NotNull();
RuleFor(x => x.IsWithdrawal).NotNull();
RuleFor(x => x.Amount).NotNull();
RuleFor(x => x.Description).NotEmpty();
RuleFor(x => x.PaymentMethod).NotEmpty();
RuleFor(x => x.PaymentMethod).Length(0,
50).WithMessage("PaymentMethod can not exceed 50 characters");
}
}
Now these are base classes and I call the validator using the following
child classes respectively:
public class ExpenseValidator : ExpenseBaseValidator
{
public ExpenseValidator()
: base()
{
RuleFor(x => x.Transaction)
.NotNull()
.When(x => x.IsPaid == true)
.WithMessage("An account transaction is required when the
amount is paid.");
RuleFor(x => x.DatePaid)
.NotNull()
.When(x => x.IsPaid == true)
.WithMessage("Please enter the date when the expense was paid.");
}
}
And Transaction child class:
public class TransactionValidator : TransactionBaseValidator
{
public TransactionValidator() : base()
{
}
}
And these can have extra rules for validation and the base rules are
called using the base() constructor.
And I validate the Expense object using this:
var validator = new ExpenseValidator();
var results = validator.Validate(oExpense);
Now this doesn't return the validation for the complex property
transaction which I am using in the following way:
oExpense.Transaction = new Transaction();
oExpense.Transaction.Amount = oExpense.Amount;
oExpense.Transaction.BankAccountID = ddlAccounts.SelectedItem.Value.ToInt();
oExpense.Transaction.TransactionDate = oExpense.DatePaid.Value;
oExpense.Transaction.IsWithdrawal = true;
oExpense.Transaction.Description = oExpense.Description;
oExpense.Transaction.IsDeleted = false;
// I dont set the below and it should give me validation error:
// oExpense.Transaction.EmployeeID = 10;
I don't set the EmployeeID and it should give me validation error when I
call validator for expense object as it has SetValidator() for the
Transaction property and the Transaction is also not null as I already set
new Transaction().
Any idea?
Subscribe to:
Comments (Atom)