Check option for view
I am confused with how check option works on a view.
I crated a simple table
CREATE TABLE [dbo].[Test]( [Country] nvarchar NULL ) ON [PRIMARY]
And populate it with England, USA, Australia
I create a view as follows
CREATE VIEW dbo.TestView AS
Select country from dbo.Test where country = N'USA' WITH CHECK OPTION GO
I then do
Insert into dbo.TestView (country) Values(N'Canada');
which fails as expected.
I then do
Update dbo.TestView Set country = N'ddsffd'
It does not fail?
I get no rows when I do
select * from dbo.TestView
Saturday, 31 August 2013
IList Property stays null even when member is instantiated
IList Property stays null even when member is instantiated
I am having trouble using an IList property which always seems to return
null, even though the member is is getting is instantiated:
private List<ModelRootEntity> _validTargets = new
List<ModelRootEntity>();
public IList<IModelRootEntity> ValidTargets
{
get
{
return _validTargets as IList<IModelRootEntity>;
}
protected internal set
{
if (value == null)
_validTargets.Clear();
else
_validTargets = value as List<ModelRootEntity>;
}
}
ModelRootEntity implements IModelRootEntity. I watched both values during
debugging, whilst the member shows a positive count, the property stays
null.
I also tried raising an exception within the property getter to throw if
the counts of _validTargets and _validTargets as List<ModelRootEntity> are
different, but it never threw.
Found question [Dictionary properties are always null despite dictionaries
being instantiated, which seems similar, however in my case this seems to
happen regardless of serialization.
Any ideas?
I am having trouble using an IList property which always seems to return
null, even though the member is is getting is instantiated:
private List<ModelRootEntity> _validTargets = new
List<ModelRootEntity>();
public IList<IModelRootEntity> ValidTargets
{
get
{
return _validTargets as IList<IModelRootEntity>;
}
protected internal set
{
if (value == null)
_validTargets.Clear();
else
_validTargets = value as List<ModelRootEntity>;
}
}
ModelRootEntity implements IModelRootEntity. I watched both values during
debugging, whilst the member shows a positive count, the property stays
null.
I also tried raising an exception within the property getter to throw if
the counts of _validTargets and _validTargets as List<ModelRootEntity> are
different, but it never threw.
Found question [Dictionary properties are always null despite dictionaries
being instantiated, which seems similar, however in my case this seems to
happen regardless of serialization.
Any ideas?
imagepolygon - Generate strange output
imagepolygon - Generate strange output
When try to run this code, a strange output happen.
<?php
// cria uma imagem em branco
$image = imagecreate(400, 300);
// prenche a cor do fundo
$bg = imagecolorallocate($image, 0, 0, 0);
// escolhe uma cor para o poligono
$col_poly = imagecolorallocate($image, 255, 255, 255);
// desenha o poligono
imagepolygon($image,
array (
0, 0,
100, 200,
300, 200
),
3,
$col_poly);
// envia a imagem
header("Content-type: image/png");
imagepng($image);
?>
The output is:
Warning: Cannot modify header information - headers already sent by
(output started at /var/www/drawimage/index.php:2) in
/var/www/drawimage/index.php on line 23
what should be the picture looks like this:
‰PNG
IHDR,×ywPLTEÿÿÿ¥ÙŸÝ1IDAThí•;Ü0D5ë¡ÀÇ™C±¡à#è(lt;åÌýùivWeX»+'Púa§8ÑYxä7üä'lt;ò-ÒÈKhdþÅ#3¦Ä#EÓwy²È?ñÈû‡ŒðÊÈôb'0}á'yMH#ïÏáò~V™yû¥òV™ç:g\Ö+Nlt;8dmE*³¬2qšXeâñGDamp;ú¿ÌŠÊ„÷©ÌŠÊ¬¥He¶ï
ÙFŸSf¾p¶iá"ÙN™ý‚Ù;QÊì§L\œ21{‚'í¹ð¥LØ"2;B)³W¢"9¾Bä|F™¹xA9f…Qæ@eÎëMlt;pälD(sŒ2q1ÊÄê
D÷Â#„2áxÊœ¡ÌYPæú'kìqeæfáæš\™Á•¹/7ñH@'»¬ÌàÊÄs+••¹VÀÊ„k+s#°2wX™ìD²¡G•™Õ¥™lNPe2Uamp;¿ÚÄ#Cò6
29‚*ï%ªLì¬H¶^xTamp;dkP™•ÉËÊýBŠ'Ç"™»›nŠ)Á")L™òb)»@Ê"¦LÌ7˜2ÑØuÅnáH™Pì
eJR¦¬)Sµ©Qf6·jªA"©D™úZ©›ÊÔ¢L,·2ÑÙ+'j¿ð L¨ö25(S"iº&lsqauo;&lsqauo;4ãî+Ó
¾2Í„øÊ4¯L{©‰G‚‡´=\eZÄWamp;Ö¾2 â+#ÍÉÂ#®2¡9q•iW™¶†«ŒÒ\DvOñ"QæÃSFA
/code/pre
pwhat is happening?/p
When try to run this code, a strange output happen.
<?php
// cria uma imagem em branco
$image = imagecreate(400, 300);
// prenche a cor do fundo
$bg = imagecolorallocate($image, 0, 0, 0);
// escolhe uma cor para o poligono
$col_poly = imagecolorallocate($image, 255, 255, 255);
// desenha o poligono
imagepolygon($image,
array (
0, 0,
100, 200,
300, 200
),
3,
$col_poly);
// envia a imagem
header("Content-type: image/png");
imagepng($image);
?>
The output is:
Warning: Cannot modify header information - headers already sent by
(output started at /var/www/drawimage/index.php:2) in
/var/www/drawimage/index.php on line 23
what should be the picture looks like this:
‰PNG
IHDR,×ywPLTEÿÿÿ¥ÙŸÝ1IDAThí•;Ü0D5ë¡ÀÇ™C±¡à#è(lt;åÌýùivWeX»+'Púa§8ÑYxä7üä'lt;ò-ÒÈKhdþÅ#3¦Ä#EÓwy²È?ñÈû‡ŒðÊÈôb'0}á'yMH#ïÏáò~V™yû¥òV™ç:g\Ö+Nlt;8dmE*³¬2qšXeâñGDamp;ú¿ÌŠÊ„÷©ÌŠÊ¬¥He¶ï
ÙFŸSf¾p¶iá"ÙN™ý‚Ù;QÊì§L\œ21{‚'í¹ð¥LØ"2;B)³W¢"9¾Bä|F™¹xA9f…Qæ@eÎëMlt;pälD(sŒ2q1ÊÄê
D÷Â#„2áxÊœ¡ÌYPæú'kìqeæfáæš\™Á•¹/7ñH@'»¬ÌàÊÄs+••¹VÀÊ„k+s#°2wX™ìD²¡G•™Õ¥™lNPe2Uamp;¿ÚÄ#Cò6
29‚*ï%ªLì¬H¶^xTamp;dkP™•ÉËÊýBŠ'Ç"™»›nŠ)Á")L™òb)»@Ê"¦LÌ7˜2ÑØuÅnáH™Pì
eJR¦¬)Sµ©Qf6·jªA"©D™úZ©›ÊÔ¢L,·2ÑÙ+'j¿ð L¨ö25(S"iº&lsqauo;&lsqauo;4ãî+Ó
¾2Í„øÊ4¯L{©‰G‚‡´=\eZÄWamp;Ö¾2 â+#ÍÉÂ#®2¡9q•iW™¶†«ŒÒ\DvOñ"QæÃSFA
/code/pre
pwhat is happening?/p
Grab information from a php script and display on a winform
Grab information from a php script and display on a winform
I have a php script that returns a list of file directories held at the
root of a remote server that I need to display in my winform application.
For example if I put the link in my browser it returns something like the
following:
511157.jpg|Koala.jpg|VIDEO0031.3gp|Test_Folder.folder
However, I have never accessed a php script through a C# application
before and nor have I displayed the information it may hold.
Is there a best practice for being able to connect and grab the
information via a php script? Could someone please point me in the right
direction to achieve what I would like to achieve.
I have a php script that returns a list of file directories held at the
root of a remote server that I need to display in my winform application.
For example if I put the link in my browser it returns something like the
following:
511157.jpg|Koala.jpg|VIDEO0031.3gp|Test_Folder.folder
However, I have never accessed a php script through a C# application
before and nor have I displayed the information it may hold.
Is there a best practice for being able to connect and grab the
information via a php script? Could someone please point me in the right
direction to achieve what I would like to achieve.
add a class to all day-divs when loading calendar
add a class to all day-divs when loading calendar
i need to add the class 'modalbox' to all div's representing a day. With
that class I want to trigger a pop-up form.
Where or how do $( ".fc-day").addClass("modalbox");
PS I am just a snippet guy trying and putting all kind of things together...
Thx in advance
i need to add the class 'modalbox' to all div's representing a day. With
that class I want to trigger a pop-up form.
Where or how do $( ".fc-day").addClass("modalbox");
PS I am just a snippet guy trying and putting all kind of things together...
Thx in advance
error compiling a simple libpcap example
error compiling a simple libpcap example
I am trying to compile a simple libpcap example,
#include<stdio.h>
#include<pcap.h>
int main(int argc, char *argv[])
{
char *dev;
char errbuf[PCAP_ERRBUF_SIZE];
struct bpf_program fp ;
char filter_exp[] = "port 23";
bpf_u_int32 mask;
bpf_u_int32 net;
dev = pcap_lookupdev(errbuf);
if (dev ==NULL) {
fprintf(stderr, "couldn't find default device: %s\n", errbuf);
return(2);
}
printf ("Device: %s\n", dev);
//LOOKUP NETMASK and IP
if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1){
fprintf(stderr, "can't get netmask for device %s\n", dev);
net =0;
mask =0;
}
printf("lookup\n");
pcap_t *handle;
printf("handle defined\n");
handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
printf("opened\n");
if (handle = NULL) {
fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
return(2);
}
printf("pcap_open\n");
if ((pcap_compile(handle, &fp, filter_exp, 1, net)) == -1) {
printf("compile error block entered\n");
fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp,
pcap_geterr(handle));
return(2);
}
printf("compiled\n");
if(pcap_setfilter(handle, &fp) == -1){
fprintf(stderr, "couldn't install filter %s: %s\n", filter_exp,
pcap_geterr(handle));
return(2);
}
printf("after filter\n");
return(0);
}
It compiles without error, but when I try to run it, I'm getting
segmentation fault message or if I try to run it with root permission, I
don't get the message but the program stops after printing
Device: eth0
lookup
handle defined
opened
pcap_open
Can you please help me with this, I'm confused as to why this error
happens. Thanks in advance.
I am trying to compile a simple libpcap example,
#include<stdio.h>
#include<pcap.h>
int main(int argc, char *argv[])
{
char *dev;
char errbuf[PCAP_ERRBUF_SIZE];
struct bpf_program fp ;
char filter_exp[] = "port 23";
bpf_u_int32 mask;
bpf_u_int32 net;
dev = pcap_lookupdev(errbuf);
if (dev ==NULL) {
fprintf(stderr, "couldn't find default device: %s\n", errbuf);
return(2);
}
printf ("Device: %s\n", dev);
//LOOKUP NETMASK and IP
if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1){
fprintf(stderr, "can't get netmask for device %s\n", dev);
net =0;
mask =0;
}
printf("lookup\n");
pcap_t *handle;
printf("handle defined\n");
handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
printf("opened\n");
if (handle = NULL) {
fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
return(2);
}
printf("pcap_open\n");
if ((pcap_compile(handle, &fp, filter_exp, 1, net)) == -1) {
printf("compile error block entered\n");
fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp,
pcap_geterr(handle));
return(2);
}
printf("compiled\n");
if(pcap_setfilter(handle, &fp) == -1){
fprintf(stderr, "couldn't install filter %s: %s\n", filter_exp,
pcap_geterr(handle));
return(2);
}
printf("after filter\n");
return(0);
}
It compiles without error, but when I try to run it, I'm getting
segmentation fault message or if I try to run it with root permission, I
don't get the message but the program stops after printing
Device: eth0
lookup
handle defined
opened
pcap_open
Can you please help me with this, I'm confused as to why this error
happens. Thanks in advance.
Text effect in jquery
Text effect in jquery
I created the notification bar with the text effect everything seems ok
but when i add the text effect like moving from left to right in that it
seems work when in first time and after that it looks like this way see
the FIDDLE
jQuery('.text').animate({
'right': '300px'
}, 'slow', 'linear').animate({
'left': '300px'
}, 'slow', 'linear').animate({
'left': '0',
'right': '0',
});
For the second time when i click expand it appears from center to right
when i refreshing the page itself it appear properly for the first time.
Is there is a way to show the message as from left to right to center
whenever i open the bar.
Thanks in Advance.
I created the notification bar with the text effect everything seems ok
but when i add the text effect like moving from left to right in that it
seems work when in first time and after that it looks like this way see
the FIDDLE
jQuery('.text').animate({
'right': '300px'
}, 'slow', 'linear').animate({
'left': '300px'
}, 'slow', 'linear').animate({
'left': '0',
'right': '0',
});
For the second time when i click expand it appears from center to right
when i refreshing the page itself it appear properly for the first time.
Is there is a way to show the message as from left to right to center
whenever i open the bar.
Thanks in Advance.
Using LIKE CONCAT with wildcard
Using LIKE CONCAT with wildcard
I'm using the standard LAMP environment. I've taken an example directly
from mysql.com website and adapted it to my table structure.
$sql = 'SELECT cat_name
FROM cats
WHERE cat_name LIKE concat('%', 'Artist', '%') ';
But this does not work... the screen is just blank and even "view source"
in the browser is blank
My issue is that, even though all of the examples I've found on
StackOverflow and other forums use single quotes ('%') it only works if I
use double quotes like this ("%").
I'm using the standard LAMP environment. I've taken an example directly
from mysql.com website and adapted it to my table structure.
$sql = 'SELECT cat_name
FROM cats
WHERE cat_name LIKE concat('%', 'Artist', '%') ';
But this does not work... the screen is just blank and even "view source"
in the browser is blank
My issue is that, even though all of the examples I've found on
StackOverflow and other forums use single quotes ('%') it only works if I
use double quotes like this ("%").
Friday, 30 August 2013
Is JSF is a framework or an API?
Is JSF is a framework or an API?
Some say JSF is a framework. Others say it's an API. What is it?
Some say JSF is a framework. Others say it's an API. What is it?
Thursday, 29 August 2013
How to auto Update Views based on Changes Made to Model?
How to auto Update Views based on Changes Made to Model?
For example, when adding a new controller and specifying a template (mvc
controller with read/write actions and views using entity framework) and a
Model Class, MVC does the magic and creates a view that corresponds to
every action in the controller, the views might include a form and data
details.
Next, I update the model class with a new property: public string Location
{ get; set; }
Then update the database accordingly.
Now I would like this change to be reflected in the controller's views as
well; for example, a new Location label and textbox in the Create
view...etc
Is this possible, or does it have to be done manually? This could be a lot
of work if a lot of changes to be made to the Model.
For example, when adding a new controller and specifying a template (mvc
controller with read/write actions and views using entity framework) and a
Model Class, MVC does the magic and creates a view that corresponds to
every action in the controller, the views might include a form and data
details.
Next, I update the model class with a new property: public string Location
{ get; set; }
Then update the database accordingly.
Now I would like this change to be reflected in the controller's views as
well; for example, a new Location label and textbox in the Create
view...etc
Is this possible, or does it have to be done manually? This could be a lot
of work if a lot of changes to be made to the Model.
Wednesday, 28 August 2013
Volume mounts, but windows can access raw file system
Volume mounts, but windows can access raw file system
Truecrypt accepts my password and mounts the drive, but when I go to
access it, it tells me it's an invalid drive. Tried to use testdisk, but
it wouldn't work due to it being a raw drive. I would love to get this
data back, any help would be greatly appreciated.
Truecrypt accepts my password and mounts the drive, but when I go to
access it, it tells me it's an invalid drive. Tried to use testdisk, but
it wouldn't work due to it being a raw drive. I would love to get this
data back, any help would be greatly appreciated.
c++ variable declaration syntax
c++ variable declaration syntax
When I take something as simple as this:
char text1 = "hello world";
MessageBox(NULL, text1, NULL, NULL);
I get those Errors:
Error 1 error C2440: 'initializing' : cannot convert from 'const char
[12]' to 'char'
Error 2 error C2664: 'MessageBoxW' : cannot convert parameter 2 from
'char' to 'LPCWSTR'
When I take something as simple as this:
char text1 = "hello world";
MessageBox(NULL, text1, NULL, NULL);
I get those Errors:
Error 1 error C2440: 'initializing' : cannot convert from 'const char
[12]' to 'char'
Error 2 error C2664: 'MessageBoxW' : cannot convert parameter 2 from
'char' to 'LPCWSTR'
Can't make exercise from Jason Hickey's "Introduction to Objective Caml" book
Can't make exercise from Jason Hickey's "Introduction to Objective Caml" book
I'm trying to solve this exercise:
Suppose you have a function on integers f : int -> int that is mono-
tonically increasing over some range of arguments from 0 up to n. That is,
f i < f (i + 1) for any 0 ¡Ü i < n. In addition f 0 < 0 and f n > 0. Write
a function search f n that finds the smallest argument i where f i ¡Ý 0.
Now i wrote this
let search f n =
let min = f 0 in
let rec searchin i =
if i >= n then min
else
if f min > f i then min = i
searchin i+1;;
But it crashes with error:
Error: Parse error: "in" expected after [binding] (in [expr])
What wrong? And my implementation is correct?
I'm trying to solve this exercise:
Suppose you have a function on integers f : int -> int that is mono-
tonically increasing over some range of arguments from 0 up to n. That is,
f i < f (i + 1) for any 0 ¡Ü i < n. In addition f 0 < 0 and f n > 0. Write
a function search f n that finds the smallest argument i where f i ¡Ý 0.
Now i wrote this
let search f n =
let min = f 0 in
let rec searchin i =
if i >= n then min
else
if f min > f i then min = i
searchin i+1;;
But it crashes with error:
Error: Parse error: "in" expected after [binding] (in [expr])
What wrong? And my implementation is correct?
Can Windows Azure Mobile Services provide access to native mobile device functions?
Can Windows Azure Mobile Services provide access to native mobile device
functions?
I have a few project requirements for hybrid mobile apps. And in the quest
of best thing I came across the Windows Mobile services. But my concern is
whether it is providing any API for accessing native device function such
as the camera or accelerometer along with Push Notifications.
I appreciate if any one can reply to my question as soon as possible.
functions?
I have a few project requirements for hybrid mobile apps. And in the quest
of best thing I came across the Windows Mobile services. But my concern is
whether it is providing any API for accessing native device function such
as the camera or accelerometer along with Push Notifications.
I appreciate if any one can reply to my question as soon as possible.
Issue with an embedded Youtube video whereas it works on Youtube.com
Issue with an embedded Youtube video whereas it works on Youtube.com
I can t load this embedded video www.youtube.com/embed/xj37CsYnAU0 whereas
it works on youtube.com
http://www.youtube.com/watch?feature=player_embedded&v=xj37CsYnAU0 . In
the API, noembed=false, perm_private=false, access_control => everything
is alright... so I dont understand why I can t see this video. (I am in
australia but it shouldnt be a pb, and this is a match from France ligue
1)
I can t load this embedded video www.youtube.com/embed/xj37CsYnAU0 whereas
it works on youtube.com
http://www.youtube.com/watch?feature=player_embedded&v=xj37CsYnAU0 . In
the API, noembed=false, perm_private=false, access_control => everything
is alright... so I dont understand why I can t see this video. (I am in
australia but it shouldnt be a pb, and this is a match from France ligue
1)
Tuesday, 27 August 2013
Searching files by matching filename pattern and concatenating contents of the files
Searching files by matching filename pattern and concatenating contents of
the files
I have 10 folders which contain files of the formated like so
"xaaNP_len_0.fa"
or
"xaaP_len_0.fa"
the "xaa" part is unique to the folder it is in. the folders are named
[xaa, xab....xaj]
I want to concatenate all the files that match a specific pattern together.
For example I would like to concatenate all the
P_len_*.fa
where * is an integer from 0 to 100. This should not include the case
where the "P" has an "N" to the left.
Next I want to concatenate all the
NP_len_*.fa
files together in the same manner across all 10 directories.
the files
I have 10 folders which contain files of the formated like so
"xaaNP_len_0.fa"
or
"xaaP_len_0.fa"
the "xaa" part is unique to the folder it is in. the folders are named
[xaa, xab....xaj]
I want to concatenate all the files that match a specific pattern together.
For example I would like to concatenate all the
P_len_*.fa
where * is an integer from 0 to 100. This should not include the case
where the "P" has an "N" to the left.
Next I want to concatenate all the
NP_len_*.fa
files together in the same manner across all 10 directories.
Excel: find indices of value in list then return largest index value from other column
Excel: find indices of value in list then return largest index value from
other column
I have a small excel spreadsheet with 2 columns. One with values, the
other with dates. Eg.
A B
1 1/1/11
2 1/4/12
3 3/3/13
1 12/4/12
3 2/2/11
I want to
search a value in column A (that value may occur multiple times) and get
the row indices where it occurs.
get the largest (MAX) date from column B associated with the value that i
searched for in column A using the search indices.
E.g., I search for 1 and get back 12/4/12.
Ideally i would like to perform steps 1 and 2 in a single command. Help?
thank you!
other column
I have a small excel spreadsheet with 2 columns. One with values, the
other with dates. Eg.
A B
1 1/1/11
2 1/4/12
3 3/3/13
1 12/4/12
3 2/2/11
I want to
search a value in column A (that value may occur multiple times) and get
the row indices where it occurs.
get the largest (MAX) date from column B associated with the value that i
searched for in column A using the search indices.
E.g., I search for 1 and get back 12/4/12.
Ideally i would like to perform steps 1 and 2 in a single command. Help?
thank you!
SVG not rendering in IE
SVG not rendering in IE
I have a .svg logo on my website, http://www.dailydoog.com, and it renders
correctly in every browser except for Internet Explorer. Even newer
versions of IE (9+) that have built-in SVG support won't render the logo.
I'm using the following markup
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
but it doesn't seem to be having any impact. Am I just missing something
really simple here?
I have a .svg logo on my website, http://www.dailydoog.com, and it renders
correctly in every browser except for Internet Explorer. Even newer
versions of IE (9+) that have built-in SVG support won't render the logo.
I'm using the following markup
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
but it doesn't seem to be having any impact. Am I just missing something
really simple here?
asp.net error: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
asp.net error: Cannot implicitly convert type 'object' to 'string'. An
explicit conversion exists (are you missing a cast?)
I want to retrieve data from a table in sql server called hotel using
select WHERE statement and I get the above error. Can anyone help?
SqlConnection cnn = new
SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ToString());
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT RoomsAvailable FROM Hotel WHERE HotelName = '" +
this.DropDownList1.Text + "'";
cmd.Connection = cnn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "Hotel");
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataRow dsRow = null;
foreach (DataRow dsRow_loopVariable in ds.Tables["Hotel"].Rows)
{
dsRow = dsRow_loopVariable;
//This line is where the error comes in.
this.txtHotel.Text = (dsRow["RoomsAvailable"]);
}
explicit conversion exists (are you missing a cast?)
I want to retrieve data from a table in sql server called hotel using
select WHERE statement and I get the above error. Can anyone help?
SqlConnection cnn = new
SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ToString());
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT RoomsAvailable FROM Hotel WHERE HotelName = '" +
this.DropDownList1.Text + "'";
cmd.Connection = cnn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, "Hotel");
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataRow dsRow = null;
foreach (DataRow dsRow_loopVariable in ds.Tables["Hotel"].Rows)
{
dsRow = dsRow_loopVariable;
//This line is where the error comes in.
this.txtHotel.Text = (dsRow["RoomsAvailable"]);
}
Selecting XML Data from SQL query - No values returned
Selecting XML Data from SQL query - No values returned
Xml Column returns no rows.
Below created a table type and xml value inserted into that table. After
executing the below mentioned two queries no value is returned.
Xml data is a valid data.
DECLARE @Test TABLE (Id INT IDENTITY (1,1), XMLDATA XML)
INSERT INTO @test
SELECT '
<TXLife xmlns="http://ACORD.org/Standards/Life/2"
xmlns:tx="http://ACORD.org/Standards/Life/2" Version="2.20.00">
<TXLifeRequest PrimaryObjectID="Holding_1">
<CorrelationGUID>4b30545a-158b-441a-a37a-0b259f757059</CorrelationGUID>
</TXLifeRequest>
</TXLife>'
SELECT
Id
, XMLDATA.query('//CorrelationGUID') AS 'TransType'
, XMLDATA
FROM @test
SELECT C.value('./CorrelationGUID[1]', 'varchar(50)') AS 'TransType'
FROM @test
CROSS APPLY XMLDATA.nodes('/TXLife/TXLifeRequest') n (C)
Xml Column returns no rows.
Below created a table type and xml value inserted into that table. After
executing the below mentioned two queries no value is returned.
Xml data is a valid data.
DECLARE @Test TABLE (Id INT IDENTITY (1,1), XMLDATA XML)
INSERT INTO @test
SELECT '
<TXLife xmlns="http://ACORD.org/Standards/Life/2"
xmlns:tx="http://ACORD.org/Standards/Life/2" Version="2.20.00">
<TXLifeRequest PrimaryObjectID="Holding_1">
<CorrelationGUID>4b30545a-158b-441a-a37a-0b259f757059</CorrelationGUID>
</TXLifeRequest>
</TXLife>'
SELECT
Id
, XMLDATA.query('//CorrelationGUID') AS 'TransType'
, XMLDATA
FROM @test
SELECT C.value('./CorrelationGUID[1]', 'varchar(50)') AS 'TransType'
FROM @test
CROSS APPLY XMLDATA.nodes('/TXLife/TXLifeRequest') n (C)
Php Update mysql
Php Update mysql
Hello i've actually a table to update throught php/html and have no clue
why I got the error "Error" (which is my mysql_query die) I've tried if
every variable in my code were send in my update.php and everything was
here. So the problem come from my update.php code.
Here is my updating code:
<?php
include('config.inc.php');
$idn=$_POST["idn"];
$nom=$_POST['nom'];
$prenom=$_POST["prenom"];
$payss=$_POST["pays"];
$req="UPDATE membres SET prenom = '$prenom' , "
." pays = '$payss' "
." nom = '$nom' , "
." where id = $idn ";
$res=mysql_query($req) or die ("error updating!");
?>
Thanks for your answers !
Hello i've actually a table to update throught php/html and have no clue
why I got the error "Error" (which is my mysql_query die) I've tried if
every variable in my code were send in my update.php and everything was
here. So the problem come from my update.php code.
Here is my updating code:
<?php
include('config.inc.php');
$idn=$_POST["idn"];
$nom=$_POST['nom'];
$prenom=$_POST["prenom"];
$payss=$_POST["pays"];
$req="UPDATE membres SET prenom = '$prenom' , "
." pays = '$payss' "
." nom = '$nom' , "
." where id = $idn ";
$res=mysql_query($req) or die ("error updating!");
?>
Thanks for your answers !
Monday, 26 August 2013
What is the best way to escape HTML on ExtJS application generally?
What is the best way to escape HTML on ExtJS application generally?
I am developing a web application using ExtJS to build GUI and communicate
with server via RESTful web-service (the returned data is formatted as
JSON objects).
Now I am having problems when processing with data which contains HTML
tags, Javascript codes inside; because when I set those values to Ext
forms, labels, input fields, they are affected by those syntaxes.
I used this function to load data from model object to form:
form.loadRecord(model);
I have found a solution to escape HTML and JS: using
field.setValue(Ext.util.Format.htmlDecode(data));
but I think that is not a good solution for whole application, because the
developers must do so much things: review all input fields, labels, and
put that snippet to them. And after all, that is not a beautiful way to
build a fast, robust and maintainable application.
So, could you please help me solution so that it can be modified at one
place, and affects to the rest. Can I override the setValue/ setLabel of
AbstractComponent? Or should I encode the data before rendering them? And
how to decode those data? (P/S: I uses Grails framework on the
server-side) Thank you so much.
I am developing a web application using ExtJS to build GUI and communicate
with server via RESTful web-service (the returned data is formatted as
JSON objects).
Now I am having problems when processing with data which contains HTML
tags, Javascript codes inside; because when I set those values to Ext
forms, labels, input fields, they are affected by those syntaxes.
I used this function to load data from model object to form:
form.loadRecord(model);
I have found a solution to escape HTML and JS: using
field.setValue(Ext.util.Format.htmlDecode(data));
but I think that is not a good solution for whole application, because the
developers must do so much things: review all input fields, labels, and
put that snippet to them. And after all, that is not a beautiful way to
build a fast, robust and maintainable application.
So, could you please help me solution so that it can be modified at one
place, and affects to the rest. Can I override the setValue/ setLabel of
AbstractComponent? Or should I encode the data before rendering them? And
how to decode those data? (P/S: I uses Grails framework on the
server-side) Thank you so much.
Insert into table but unsure of foreign key
Insert into table but unsure of foreign key
Table Order
oid payerName address
1 james 1 brown
2 smith 2 smith
Table order_item
oid type price
1 AN94 3000
2 AK47 1000
order_item as a foreign from Order.
oid is an auto increment in Order Table but in order_item table it is
not(dont know if thats is the right way to do it)
I have an insert statement which inserts into both tables at the same
time. I was wonder if it the right to make order_item oid an auto
increment as well? because the is not other way I can make it copy the oid
from order table.
What is the best approach to this small issue.
Table Order
oid payerName address
1 james 1 brown
2 smith 2 smith
Table order_item
oid type price
1 AN94 3000
2 AK47 1000
order_item as a foreign from Order.
oid is an auto increment in Order Table but in order_item table it is
not(dont know if thats is the right way to do it)
I have an insert statement which inserts into both tables at the same
time. I was wonder if it the right to make order_item oid an auto
increment as well? because the is not other way I can make it copy the oid
from order table.
What is the best approach to this small issue.
why is this django regex wont work?
why is this django regex wont work?
I have this regex in my urls.py for my blog app and I'd like to know why
is it not working.
url(r'^/tag/(?P<tag_text>\w+)/$', views.tag, name='tag'),
and I have defined this in the blog's views.py
def tag(request,tag_text):
and this in the application's urls.py
url(r'^blog/', include('blog.urls')),
I have tried localhost/blog/tag/sport but I still get: The current URL,
blog/tag/sport, didn't match any of these. Am I doing something wrong?
I have this regex in my urls.py for my blog app and I'd like to know why
is it not working.
url(r'^/tag/(?P<tag_text>\w+)/$', views.tag, name='tag'),
and I have defined this in the blog's views.py
def tag(request,tag_text):
and this in the application's urls.py
url(r'^blog/', include('blog.urls')),
I have tried localhost/blog/tag/sport but I still get: The current URL,
blog/tag/sport, didn't match any of these. Am I doing something wrong?
Jquery Datatables and MVC Form Post
Jquery Datatables and MVC Form Post
I have a table (list of items) within a form that allows the user to do
some action on each row (ex: delete an item). When the user clicks submit,
all the rows (data and action) are sent to the controller. Works great.
Now I want to add some datatables filter functionality to the table. I get
it to work just fine on the View but when I click Submit, all it sends is
a null value instead of the row data. My understanding is that datatables
modifies the page/DOM and somehow I need to get it back onto the page
before the submit fires. I saw some suggestions to use the datatables API
function fnGetHiddenNodes() but I wasn't sure how to do this on my page.
Any help would be greatly appreciated.
Code
@model IEnumerable<Admin.Models.MemberFeedback>
@{
ViewBag.Title = "Member Feedback";
}
@Scripts.Render("~/bundles/datatables")
@using (Html.BeginForm("MemberFeedback", "Admin", FormMethod.Post, new
{ @id = "processmemberfeedback" }))
{
<table class="dynamicTable table table-striped table-bordered
table-primary" id="feedbackemails">
<thead>
<tr>
<th>Date</th>
<th>From</th>
<th>Feedback</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@Html.EditorForModel()
</tbody>
</table>
<br />
<input type="submit" value="Submit" id="submit1" class="btn
btn-inverse"/>
}
</div>
<script>
/* Table initialisation */
var oJobListingsTable = $('#feedbackemails').dataTable({
"sPaginationType": "bootstrap",
"bLengthChange": false,
"bFilter": false,
"oLanguage": {
"sEmptyTable": "No records found.",
"sLengthMenu": "Rows: _MENU_",
"sSearch": "Filter: "
},
"iDisplayLength": 10,
});
</script>
How do I get a jquery datatables form to post back correctly to the
Controller (and not send a null value)?
I have a table (list of items) within a form that allows the user to do
some action on each row (ex: delete an item). When the user clicks submit,
all the rows (data and action) are sent to the controller. Works great.
Now I want to add some datatables filter functionality to the table. I get
it to work just fine on the View but when I click Submit, all it sends is
a null value instead of the row data. My understanding is that datatables
modifies the page/DOM and somehow I need to get it back onto the page
before the submit fires. I saw some suggestions to use the datatables API
function fnGetHiddenNodes() but I wasn't sure how to do this on my page.
Any help would be greatly appreciated.
Code
@model IEnumerable<Admin.Models.MemberFeedback>
@{
ViewBag.Title = "Member Feedback";
}
@Scripts.Render("~/bundles/datatables")
@using (Html.BeginForm("MemberFeedback", "Admin", FormMethod.Post, new
{ @id = "processmemberfeedback" }))
{
<table class="dynamicTable table table-striped table-bordered
table-primary" id="feedbackemails">
<thead>
<tr>
<th>Date</th>
<th>From</th>
<th>Feedback</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@Html.EditorForModel()
</tbody>
</table>
<br />
<input type="submit" value="Submit" id="submit1" class="btn
btn-inverse"/>
}
</div>
<script>
/* Table initialisation */
var oJobListingsTable = $('#feedbackemails').dataTable({
"sPaginationType": "bootstrap",
"bLengthChange": false,
"bFilter": false,
"oLanguage": {
"sEmptyTable": "No records found.",
"sLengthMenu": "Rows: _MENU_",
"sSearch": "Filter: "
},
"iDisplayLength": 10,
});
</script>
How do I get a jquery datatables form to post back correctly to the
Controller (and not send a null value)?
Delete content of input field jQuery
Delete content of input field jQuery
I know others have asked about this. And I have tried the solutions that
others have recommended, but it doesn't seem to work.
Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type='text/javascript'>
$('input:text').focus(
function(){
$(this).val('');
});
</script>
</head>
<body>
<form>
<input type="text" value="Text">
</form>
</body>
</html>
I know others have asked about this. And I have tried the solutions that
others have recommended, but it doesn't seem to work.
Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type='text/javascript'>
$('input:text').focus(
function(){
$(this).val('');
});
</script>
</head>
<body>
<form>
<input type="text" value="Text">
</form>
</body>
</html>
Oracle Connect by prior... start with - running query on all children
Oracle Connect by prior... start with - running query on all children
Short version of question: is there any way to have the "Connect
prior..... start with" statement in Oracle to start with the first "child"
in the table and then run the query for all the remaining children as
well? I know how to use the statement for 1 child and get its ancestry,
but I need the code to run for lots of different children in the table.
Long version:
Let's suppose I have this code which returns a Component and Component's
Color from table of components and the Component's parent and that is
classified as a "Sample" and its color where component's parent ID is the
ID of the parent for the component.
Components table:
Component Component_ID Component_Parent_ID
Component_Color Table:
Component Component_Color
SELECT Component,
FROM Components
INNER JOIN Component_Color ON (Components.Component =
Component_Color.Component)
WHERE Component_Label = 'Sample'
connect by prior Component_Header.Component_Parent_ID =
Component_Header.Component_ID
start with Component.Component_ID = "2000";
Table Component has a lot of different components and I want the query to
return not only the component with ID 2000 and its "sample" parent, but do
this for all the children in the table "Components".
I can see how this can be done with a loop, but I cannot find what type of
loop I can use for Oracle. Sorry, just starting.
Thank you!
Short version of question: is there any way to have the "Connect
prior..... start with" statement in Oracle to start with the first "child"
in the table and then run the query for all the remaining children as
well? I know how to use the statement for 1 child and get its ancestry,
but I need the code to run for lots of different children in the table.
Long version:
Let's suppose I have this code which returns a Component and Component's
Color from table of components and the Component's parent and that is
classified as a "Sample" and its color where component's parent ID is the
ID of the parent for the component.
Components table:
Component Component_ID Component_Parent_ID
Component_Color Table:
Component Component_Color
SELECT Component,
FROM Components
INNER JOIN Component_Color ON (Components.Component =
Component_Color.Component)
WHERE Component_Label = 'Sample'
connect by prior Component_Header.Component_Parent_ID =
Component_Header.Component_ID
start with Component.Component_ID = "2000";
Table Component has a lot of different components and I want the query to
return not only the component with ID 2000 and its "sample" parent, but do
this for all the children in the table "Components".
I can see how this can be done with a loop, but I cannot find what type of
loop I can use for Oracle. Sorry, just starting.
Thank you!
Retrieve dynamicaly the columns of a records
Retrieve dynamicaly the columns of a records
my sql statement is built dynamicaly. I have something like
strSql := 'select name, tel, adress, activity_id as filtre_1, country_id
as filtre_2, ... from ... where ...'
I can have 1 to n filter, and filter_1 can be activity_id as country_id,
the order in not important.
How can I retrieve the values of filter_1, filter_2 as I don't know how
many the request send back?
Normaly to retrieve the values, I do :
FOR rowResult IN EXECUTE strSql LOOP name := rowResult.name tel :=
rowResult.tel adress := rowResult.adress filtre_1 := rowResult.filtre_1
filtre_2 := rowResult.filtre_2 END LOOP;
As this cannot be done, I like to do something like
FOR rowResult IN EXECUTE strSql LOOP name := rowResult.name tel :=
rowResult.tel adress := rowResult.adress filtre_1 := rowResult("filtre_1")
filtre_2 := rowResult("filtre_2") END LOOP;
but rowResult(stringfield) do not exist.
Is somebody have an idea?
Thanks
my sql statement is built dynamicaly. I have something like
strSql := 'select name, tel, adress, activity_id as filtre_1, country_id
as filtre_2, ... from ... where ...'
I can have 1 to n filter, and filter_1 can be activity_id as country_id,
the order in not important.
How can I retrieve the values of filter_1, filter_2 as I don't know how
many the request send back?
Normaly to retrieve the values, I do :
FOR rowResult IN EXECUTE strSql LOOP name := rowResult.name tel :=
rowResult.tel adress := rowResult.adress filtre_1 := rowResult.filtre_1
filtre_2 := rowResult.filtre_2 END LOOP;
As this cannot be done, I like to do something like
FOR rowResult IN EXECUTE strSql LOOP name := rowResult.name tel :=
rowResult.tel adress := rowResult.adress filtre_1 := rowResult("filtre_1")
filtre_2 := rowResult("filtre_2") END LOOP;
but rowResult(stringfield) do not exist.
Is somebody have an idea?
Thanks
Sunday, 25 August 2013
How can I get the partition UUID of a disk in .NET
How can I get the partition UUID of a disk in .NET
I need to be able to get the partition/filesystem UUID of a partition,
similar to how you can with VOL in WinDOS and ls -l /dev/disks/by-partuuid
in *nix, but with C# code. What's the best way to do this?
For reference, I need to be able to get the UUID from either the current
directory, or the "closest" mount upwards.
EDIT: My bad, should've said this up front: it needs to run on Mono.
I need to be able to get the partition/filesystem UUID of a partition,
similar to how you can with VOL in WinDOS and ls -l /dev/disks/by-partuuid
in *nix, but with C# code. What's the best way to do this?
For reference, I need to be able to get the UUID from either the current
directory, or the "closest" mount upwards.
EDIT: My bad, should've said this up front: it needs to run on Mono.
[ Homework Help ] Open Question : If a runner runs the first leg in 52 seconds plus or minus 2 seconds=?iso-8859-1?Q?=2C_write_an_equation_to_find_the...?=
[ Homework Help ] Open Question : "If a runner runs the first leg in 52
seconds plus or minus 2 seconds, write an equation to find the...
I don't want the answer. I just want to know how to do the problem, I've
been stuck on it for a while.
seconds plus or minus 2 seconds, write an equation to find the...
I don't want the answer. I just want to know how to do the problem, I've
been stuck on it for a while.
[ Other - Beauty & Style ] Open Question : Tan wont go away?Help?
[ Other - Beauty & Style ] Open Question : Tan wont go away?Help?
Hey im a pale asian male but due to the hot summer here my hands,face and
neck are tan now. I personally find pale attractive on me so im trying to
remove the tan by exfoliating scrub by lo'real and also use lemon to
lighten my tan but it isnt going away. I dont go out in the sun and even
if I do I put my sun block on... any ideas? How long will it take?
Hey im a pale asian male but due to the hot summer here my hands,face and
neck are tan now. I personally find pale attractive on me so im trying to
remove the tan by exfoliating scrub by lo'real and also use lemon to
lighten my tan but it isnt going away. I dont go out in the sun and even
if I do I put my sun block on... any ideas? How long will it take?
Saturday, 24 August 2013
mojarra vs myfaces. SessionScoped bean loose its parameters values
mojarra vs myfaces. SessionScoped bean loose its parameters values
Here is my simple example:
Index.xhtml in root:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Title</title>
</h:head>
<h:body>
<h:form>
<h:inputText value="#{index.variable}"></h:inputText>
<h:commandButton action="#{index.submit()}"
type="submit"></h:commandButton>
</h:form>
</h:body>
</html>
Its ManagedBean:
import java.io.IOException;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
@ManagedBean
@ViewScoped
public class Index implements Serializable {
@ManagedProperty("#{sessionBean}")
private SessionBean sessionBean; /*getter&setter*/
private String variable; /*getter&setter*/
public void submit() {
sessionBean.setAsd(variable);
ExternalContext context =
FacesContext.getCurrentInstance().getExternalContext();
try {
context.redirect("next");
} catch (IOException ex) {
}
}
}
/next/index.xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Check variable</title>
</h:head>
<h:body>
#{sessionBean.asd}
</h:body>
</html>
SessionBean.java:
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class SessionBean implements Serializable {
private String asd;
public String getAsd() {
return asd;
}
public void setAsd(String asd) {
this.asd = asd;
}
}
If I use mojarra implementation everything works as expected: after form
submitting, user gets redirected to root/ and see the value that was
printed in the form of index.xhtml.
But if I use myfaces, asd becomes null right after existing form gets
submitted. SessionScoped bean acts like RequestScoped
Why?
here is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<listener>
<listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
<!--listener-class>com.sun.faces.config.ConfigureListener</listener-class-->
</listener>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Server: Apache Tomcat 7.0.34
UPDATE: it works if we change the ViewScoped annotation of Index.java bean
to RequestScoped or SessionScoped. But why?
Here is my simple example:
Index.xhtml in root:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Title</title>
</h:head>
<h:body>
<h:form>
<h:inputText value="#{index.variable}"></h:inputText>
<h:commandButton action="#{index.submit()}"
type="submit"></h:commandButton>
</h:form>
</h:body>
</html>
Its ManagedBean:
import java.io.IOException;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
@ManagedBean
@ViewScoped
public class Index implements Serializable {
@ManagedProperty("#{sessionBean}")
private SessionBean sessionBean; /*getter&setter*/
private String variable; /*getter&setter*/
public void submit() {
sessionBean.setAsd(variable);
ExternalContext context =
FacesContext.getCurrentInstance().getExternalContext();
try {
context.redirect("next");
} catch (IOException ex) {
}
}
}
/next/index.xhtml:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Check variable</title>
</h:head>
<h:body>
#{sessionBean.asd}
</h:body>
</html>
SessionBean.java:
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class SessionBean implements Serializable {
private String asd;
public String getAsd() {
return asd;
}
public void setAsd(String asd) {
this.asd = asd;
}
}
If I use mojarra implementation everything works as expected: after form
submitting, user gets redirected to root/ and see the value that was
printed in the form of index.xhtml.
But if I use myfaces, asd becomes null right after existing form gets
submitted. SessionScoped bean acts like RequestScoped
Why?
here is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<listener>
<listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
<!--listener-class>com.sun.faces.config.ConfigureListener</listener-class-->
</listener>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Server: Apache Tomcat 7.0.34
UPDATE: it works if we change the ViewScoped annotation of Index.java bean
to RequestScoped or SessionScoped. But why?
What's the common way to embed the query parameters in the original URL in a HTTP request URL?
What's the common way to embed the query parameters in the original URL in
a HTTP request URL?
What is the usual way to embed the query parameters in the original URL in
the http request URL, e.g.
http://www.portal.mywebsite.com/res_a/res_b?orig=http://myorigin.com/test1/test2?q1=v1&q2=v2
How to pass the query parameters q1=v1&q2=v2 that are meant to be in the
original url to this new url request?
a HTTP request URL?
What is the usual way to embed the query parameters in the original URL in
the http request URL, e.g.
http://www.portal.mywebsite.com/res_a/res_b?orig=http://myorigin.com/test1/test2?q1=v1&q2=v2
How to pass the query parameters q1=v1&q2=v2 that are meant to be in the
original url to this new url request?
Get calling arguments for getter in javascript
Get calling arguments for getter in javascript
Given a javascript object like this:
var myThing = {};
Object.defineProperty(myThing, 'gen', {
'get' : function() {
// access caller name here, so I can return cool/neat stuff
}
});
I want to be able to get children of myThing.gen, but know what is being
asked for in the getter.
for example:
var coolThing = myThing.gen.oh.cool;
var neatThing = myThing.gen.oh.neat;
I want the "oh.cool" or "oh.neat" part in getter, so I can make decisions
based on this, and return something specific to it. I am ok with solution
not working in IE, or old browsers, as it is primarily for node.
without actually solving the problem of dynamically discovering the
caller, I can do this:
var myThing = {};
Object.defineProperty(myThing, 'gen', {
'get' : function() {
return {
'oh':{
'cool':'super-cool',
'neat':'pretty neat'
}
};
}
});
Is there a way to do this dynamically?
Given a javascript object like this:
var myThing = {};
Object.defineProperty(myThing, 'gen', {
'get' : function() {
// access caller name here, so I can return cool/neat stuff
}
});
I want to be able to get children of myThing.gen, but know what is being
asked for in the getter.
for example:
var coolThing = myThing.gen.oh.cool;
var neatThing = myThing.gen.oh.neat;
I want the "oh.cool" or "oh.neat" part in getter, so I can make decisions
based on this, and return something specific to it. I am ok with solution
not working in IE, or old browsers, as it is primarily for node.
without actually solving the problem of dynamically discovering the
caller, I can do this:
var myThing = {};
Object.defineProperty(myThing, 'gen', {
'get' : function() {
return {
'oh':{
'cool':'super-cool',
'neat':'pretty neat'
}
};
}
});
Is there a way to do this dynamically?
Password in Batch File
Password in Batch File
I Want to add Password in Batch actually. problem. is not setting.
password problem. is to set limit in password
for ex: I want set password to my batch file that should not be less than
5 digits and should not exceed 10 digits
DcodeX
I Want to add Password in Batch actually. problem. is not setting.
password problem. is to set limit in password
for ex: I want set password to my batch file that should not be less than
5 digits and should not exceed 10 digits
DcodeX
Driving the Options of a Given Package from Another Package or Class in LaTeX3/expl3
Driving the Options of a Given Package from Another Package or Class in
LaTeX3/expl3
I'm afraid I still don't get how I'm supposed to handle the communication
of options among packages in a LaTeX3/expl3 context. Let us say I have a
package pkg1 where I define an option opt_pkg1 that is set in the
document, but which is actually used just to drive the options
(opt1_pkg2,opt2_pkg2...) with which another package pkg2 is loaded from
the first (pkg1). What's a correct way to do this by using l3keys?
LaTeX3/expl3
I'm afraid I still don't get how I'm supposed to handle the communication
of options among packages in a LaTeX3/expl3 context. Let us say I have a
package pkg1 where I define an option opt_pkg1 that is set in the
document, but which is actually used just to drive the options
(opt1_pkg2,opt2_pkg2...) with which another package pkg2 is loaded from
the first (pkg1). What's a correct way to do this by using l3keys?
Sort Twitter tweet id string as a number on MongoDB
Sort Twitter tweet id string as a number on MongoDB
I want to store tweets on MongoDB and then find/order them by id, Twitter
API provide two IDs types for a tweet, one as a number type and the other
a string type because JavaScript (mongo/node) can only have 53 bit
integers and Twitter IDs use more than that.
If I store the IDs as numbers the ID get rounded and lost BUT I can sort
and find the IDs with a criteria as "greater than" and "less than".
If I sotre the IDs as strings the ID number get stored as it should BUT I
can't find (select) ids with a criteria of "less than" or "greater than"
and sorting is a mess because it is sorting the "field" as a string, so
"10" shows before "3" because it has "1" at the beginning.
I need to store this IDs and I want to be able to select them with a
criteria as "less/greater/equal/than" and sort them by that "field" as
numbers...
How can I achieve this?
Thanks a lot!
I want to store tweets on MongoDB and then find/order them by id, Twitter
API provide two IDs types for a tweet, one as a number type and the other
a string type because JavaScript (mongo/node) can only have 53 bit
integers and Twitter IDs use more than that.
If I store the IDs as numbers the ID get rounded and lost BUT I can sort
and find the IDs with a criteria as "greater than" and "less than".
If I sotre the IDs as strings the ID number get stored as it should BUT I
can't find (select) ids with a criteria of "less than" or "greater than"
and sorting is a mess because it is sorting the "field" as a string, so
"10" shows before "3" because it has "1" at the beginning.
I need to store this IDs and I want to be able to select them with a
criteria as "less/greater/equal/than" and sort them by that "field" as
numbers...
How can I achieve this?
Thanks a lot!
i want to show and hide the given options on specific selections in the same form in C#
i want to show and hide the given options on specific selections in the
same form in C#
I am working on and quiz application in C# and I have a query.
I have design form but I want to show and hide the given options on
specific selections on the same form, how can I do that?
Following images explain my words I can not upload here because I am new.
http://bayfiles.net/file/VbpL/9DvsMw/Untitled.jpg
same form in C#
I am working on and quiz application in C# and I have a query.
I have design form but I want to show and hide the given options on
specific selections on the same form, how can I do that?
Following images explain my words I can not upload here because I am new.
http://bayfiles.net/file/VbpL/9DvsMw/Untitled.jpg
Friday, 23 August 2013
Jquery - Dynamic sliding Div
Jquery - Dynamic sliding Div
I'm new to jQuery, so any help is appreciated.
I am "sort of" trying to reproduce this:
http://tympanus.net/Tutorials/HoverSlideEffect/
However, I want to use DIV tags with web content in them vs images.
I also don't want the box to slide when the mouse is over. I only want to
trigger the change when a button is clicked.
I sorta tried to mess with this code, but it's a little complex for me at
my current state. I wrote my own code that is sort of working, but here's
my problem:
If I open the page and choose the first button, everything is fine.
Because I basically have the div sliding out and another one sliding back
in its place; however, if I went form button 1 to button 2, it doesn't
work. I'm not sure how to make the div tags "generic" so no matter what
content is in the current box, the new content will replace it.
I understand "this" but not sure how to apply it. I did code school, but
that only gave me a basic understanding.
Thanks for any help in advance.
I'm new to jQuery, so any help is appreciated.
I am "sort of" trying to reproduce this:
http://tympanus.net/Tutorials/HoverSlideEffect/
However, I want to use DIV tags with web content in them vs images.
I also don't want the box to slide when the mouse is over. I only want to
trigger the change when a button is clicked.
I sorta tried to mess with this code, but it's a little complex for me at
my current state. I wrote my own code that is sort of working, but here's
my problem:
If I open the page and choose the first button, everything is fine.
Because I basically have the div sliding out and another one sliding back
in its place; however, if I went form button 1 to button 2, it doesn't
work. I'm not sure how to make the div tags "generic" so no matter what
content is in the current box, the new content will replace it.
I understand "this" but not sure how to apply it. I did code school, but
that only gave me a basic understanding.
Thanks for any help in advance.
How sum grouped in Cuda
How sum grouped in Cuda
I would like to know what techniques I could apply to add some dimensions
of an array and save to a new Vet lower as in the following example:
A -> [1,2], [3,4], [5,6]
B -> [3], [7], [11]
figure: http://snag.gy/83Qwl.jpg
I would like to know what techniques I could apply to add some dimensions
of an array and save to a new Vet lower as in the following example:
A -> [1,2], [3,4], [5,6]
B -> [3], [7], [11]
figure: http://snag.gy/83Qwl.jpg
Newly created NSManagedObject returns temporary objectID even after save
Newly created NSManagedObject returns temporary objectID even after save
Very simple situation. Not sure why it's causing an issue.
I have a view that creates a new NSManagedObject in a child
NSManagedObjectContext. When the user presses "done", it saves the child
context, then it saves the parent context, then it posts a notification
with the newly created object's objectID. In the main view controller, I
respond to the notification and try to get the newly created object with
existingObjectWithID:error:.
Problem is this fails because the objectID is temporary (I get a "Cocoa
error 133000"). The saves to the two contexts are flawless: when I reload
the app, I can see the entries I created. But at the time I need to get a
reference to the new object, it fails.
Why does it give me a temporary object ID after I've already saved it?
Note: I have tried using obtainPermanentIDsForObjects:error:, which works,
but the permanent ID still fails when I try to use it to obtain the
object.
Here's some code:
-(IBAction)done:(id)sender
{
if ([editorDoneNotification isEqualToString:kNOTIFICATION_OBJECTADDED]) {
// save the temporary moc
NSError* e;
if (![self.tempContext save:&e]) { // this is always a successful
save
NSLog(@"Failed to save temporary managed object context: %@",
[e localizedDescription]);
[[[UIAlertView alloc] initWithTitle:@"Database Error"
message:@"Failed to add object."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
}
}
NSError* e;
if (![[[AMDataModel sharedDataModel] mainContext] save:&e]) { // this
is also successful
NSLog(@"Failed to save main managed object context: %@", [e
localizedDescription]);
[[[UIAlertView alloc] initWithTitle:@"Database Error"
message:@"Failed to edit object."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
}
else
[[NSNotificationCenter defaultCenter]
postNotificationName:editorDoneNotification
object:[self.editingObject objectID]];
[self.navigationController dismissViewControllerAnimated:YES
completion:nil];
}
And this is how I respond to the notifications:
-(void)objectAdded:(NSNotification*)notification
{
if (self.popoverController && [self.popoverController
isPopoverVisible]) {
[self.popoverController dismissPopoverAnimated:YES];
}
NSManagedObjectID* newObjectID =
(NSManagedObjectID*)(notification.object);
NSError* error;
AMObject* object = (AMObject*)[[[AMDataModel sharedDataModel]
mainContext] existingObjectWithID:newObjectID error:&error]; // this
is where the cocoa error 133000 happens
if (error != nil) {
NSLog(@"ERROR: Could not load new object in main managed object
context.");
}
GMSMarker* m = [[GMSMarker alloc] init];
m.position = CLLocationCoordinate2DMake(object.latitudeValue,
object.longitudeValue);
m.userData = object;
m.map = self.mapView;
[self.markers addObject:m];
}
-(void)objectEdited:(NSNotification *)notification
{
NSManagedObjectID* editedObjectID =
(NSManagedObjectID*)notification.object;
NSError* error = nil;
AMObject* object = (AMObject*)[[[AMDataModel sharedDataModel]
mainContext] existingObjectWithID:editedObjectID error:&error];
if (error != nil) {
NSLog(@"Error could not load edited object in main managed object
context");
}
//update the UI based on edit
if ([self.popoverController isPopoverVisible]) {
[self.popoverController dismissPopoverAnimated:YES];
self.popoverController = nil;
}
}
Very simple situation. Not sure why it's causing an issue.
I have a view that creates a new NSManagedObject in a child
NSManagedObjectContext. When the user presses "done", it saves the child
context, then it saves the parent context, then it posts a notification
with the newly created object's objectID. In the main view controller, I
respond to the notification and try to get the newly created object with
existingObjectWithID:error:.
Problem is this fails because the objectID is temporary (I get a "Cocoa
error 133000"). The saves to the two contexts are flawless: when I reload
the app, I can see the entries I created. But at the time I need to get a
reference to the new object, it fails.
Why does it give me a temporary object ID after I've already saved it?
Note: I have tried using obtainPermanentIDsForObjects:error:, which works,
but the permanent ID still fails when I try to use it to obtain the
object.
Here's some code:
-(IBAction)done:(id)sender
{
if ([editorDoneNotification isEqualToString:kNOTIFICATION_OBJECTADDED]) {
// save the temporary moc
NSError* e;
if (![self.tempContext save:&e]) { // this is always a successful
save
NSLog(@"Failed to save temporary managed object context: %@",
[e localizedDescription]);
[[[UIAlertView alloc] initWithTitle:@"Database Error"
message:@"Failed to add object."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
}
}
NSError* e;
if (![[[AMDataModel sharedDataModel] mainContext] save:&e]) { // this
is also successful
NSLog(@"Failed to save main managed object context: %@", [e
localizedDescription]);
[[[UIAlertView alloc] initWithTitle:@"Database Error"
message:@"Failed to edit object."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
}
else
[[NSNotificationCenter defaultCenter]
postNotificationName:editorDoneNotification
object:[self.editingObject objectID]];
[self.navigationController dismissViewControllerAnimated:YES
completion:nil];
}
And this is how I respond to the notifications:
-(void)objectAdded:(NSNotification*)notification
{
if (self.popoverController && [self.popoverController
isPopoverVisible]) {
[self.popoverController dismissPopoverAnimated:YES];
}
NSManagedObjectID* newObjectID =
(NSManagedObjectID*)(notification.object);
NSError* error;
AMObject* object = (AMObject*)[[[AMDataModel sharedDataModel]
mainContext] existingObjectWithID:newObjectID error:&error]; // this
is where the cocoa error 133000 happens
if (error != nil) {
NSLog(@"ERROR: Could not load new object in main managed object
context.");
}
GMSMarker* m = [[GMSMarker alloc] init];
m.position = CLLocationCoordinate2DMake(object.latitudeValue,
object.longitudeValue);
m.userData = object;
m.map = self.mapView;
[self.markers addObject:m];
}
-(void)objectEdited:(NSNotification *)notification
{
NSManagedObjectID* editedObjectID =
(NSManagedObjectID*)notification.object;
NSError* error = nil;
AMObject* object = (AMObject*)[[[AMDataModel sharedDataModel]
mainContext] existingObjectWithID:editedObjectID error:&error];
if (error != nil) {
NSLog(@"Error could not load edited object in main managed object
context");
}
//update the UI based on edit
if ([self.popoverController isPopoverVisible]) {
[self.popoverController dismissPopoverAnimated:YES];
self.popoverController = nil;
}
}
Enable/Disable debug code dynamically
Enable/Disable debug code dynamically
I'm writing a decent sized JavaScript animation library, that I would like
to include debugging code in. I could easily do a check :
if(myLib.debugger){
console.warn('warning message');
}
However if this runs a couple thousand times a second, it would eventually
cause performance issues. Add in a few more checks throughout the code and
the effect will be even more noticeable.
What I'm wondering is if it would be possible to check onload if the
debugger should be enabled, and if so... turn something like this:
//debugger if(!this.name) console.warn('No name provided');
into:
if(!this.name) console.warn('No name provided');
Leaving the code commented if its not enabled, and uncommenting it if it
is, thus removing any possible performance issues. Could this be done
somehow with a regular expression on the entire script if loaded in
through ajax? I'm trying to avoid the need for 2 versions of the same
code, lib.dbug.js and a lib.js.
Cross browser compatibility is not of great importance for this (I'm
really only worried about new browsers), I see it as nice to have item. If
its possible however, it would be a great thing to have.
Any insight would be greatly appreciated.
I'm writing a decent sized JavaScript animation library, that I would like
to include debugging code in. I could easily do a check :
if(myLib.debugger){
console.warn('warning message');
}
However if this runs a couple thousand times a second, it would eventually
cause performance issues. Add in a few more checks throughout the code and
the effect will be even more noticeable.
What I'm wondering is if it would be possible to check onload if the
debugger should be enabled, and if so... turn something like this:
//debugger if(!this.name) console.warn('No name provided');
into:
if(!this.name) console.warn('No name provided');
Leaving the code commented if its not enabled, and uncommenting it if it
is, thus removing any possible performance issues. Could this be done
somehow with a regular expression on the entire script if loaded in
through ajax? I'm trying to avoid the need for 2 versions of the same
code, lib.dbug.js and a lib.js.
Cross browser compatibility is not of great importance for this (I'm
really only worried about new browsers), I see it as nice to have item. If
its possible however, it would be a great thing to have.
Any insight would be greatly appreciated.
Select first letter of input value and change it's color via CSS
Select first letter of input value and change it's color via CSS
Is there a way to select the text input values first letter and change its
color via CSS in the stylesheet? so for example, I have
<input type="text" name="address" value="* Property Address :" />
I would like to select only the first letter of the value property (*) and
change it to red color with CSS. Is that actualy possible to do with css ?
Is there a way to select the text input values first letter and change its
color via CSS in the stylesheet? so for example, I have
<input type="text" name="address" value="* Property Address :" />
I would like to select only the first letter of the value property (*) and
change it to red color with CSS. Is that actualy possible to do with css ?
Thursday, 22 August 2013
How to turn on autoredirect on 302
How to turn on autoredirect on 302
I have this code:
class CustomWebclient: WebClient
{
[System.Security.SecuritySafeCritical]
public CustomWebclient(): base()
{
}
public CookieContainer cookieContainer = new CookieContainer();
protected override WebRequest GetWebRequest(Uri myAddress)
{
WebRequest request = base.GetWebRequest(myAddress);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = cookieContainer;
(request as HttpWebRequest).AllowAutoRedirect = true;
}
return request;
}
}
When i load page example.com, i get:
HTTP/1.1 302
location: http://www.example.com/example/
But my CustomWebclient doesnt follow redirect. Why? What to do to fix it?
I have this code:
class CustomWebclient: WebClient
{
[System.Security.SecuritySafeCritical]
public CustomWebclient(): base()
{
}
public CookieContainer cookieContainer = new CookieContainer();
protected override WebRequest GetWebRequest(Uri myAddress)
{
WebRequest request = base.GetWebRequest(myAddress);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = cookieContainer;
(request as HttpWebRequest).AllowAutoRedirect = true;
}
return request;
}
}
When i load page example.com, i get:
HTTP/1.1 302
location: http://www.example.com/example/
But my CustomWebclient doesnt follow redirect. Why? What to do to fix it?
Tracking down the cause of a Postfix "Recipient address rejected: Access denied" error
Tracking down the cause of a Postfix "Recipient address rejected: Access
denied" error
We're having a situation where inbound emails from a specific company to
legitimate recipients are bouncing with "Recipient address rejected:
Access denied":
Aug 23 09:15:27 extranet postfix/smtpd[20228]: NOQUEUE: reject: RCPT from
sender.com[8.9.10.11]: 554 5.7.1 <user@example.com>: Recipient address
rejected: Access denied; from=<user@sender.com> to=<user@example.com>
proto=ESMTP helo=<mg01d1.sender.com>
postconf -n
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
allow_percent_hack = no
allow_untrusted_routing = yes
append_dot_mydomain = no
biff = no
bounce_queue_lifetime = 24h
broken_sasl_auth_clients = yes
config_directory = /etc/postfix
content_filter = smtp-amavis:[127.0.0.1]:10024
delay_warning_time = 4h
disable_vrfy_command = yes
html_directory = /usr/share/doc/postfix/html
inet_interfaces = all
mailbox_size_limit = 0
maximal_queue_lifetime = 24h
mydestination = mail.example.com, extranet.example.com, localhost
myhostname = mail.example.com
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
myorigin = /etc/mailname
readme_directory = /usr/share/doc/postfix
recipient_delimiter = +
relay_domains = $mydestination
relayhost =
smtp_tls_session_cache_database = btree:/var/lib/postfix/smtp_scache
smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
smtpd_data_restrictions = reject_unauth_pipelining, permit
smtpd_helo_required = yes
smtpd_recipient_restrictions = reject_non_fqdn_recipient,
permit_mynetworks, reject_unauth_destination, check_recipient_access
hash:/etc/postfix/access, reject_non_fqdn_sender, check_sender_access
hash:/etc/postfix/sender_access, reject_non_fqdn_hostname,
reject_invalid_hostname, check_helo_access hash:/etc/postfix/helo_access,
reject_rbl_client zen.spamhaus.org, reject_rbl_client bl.spamcop.net,
permit
smtpd_sasl_auth_enable = no
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous
smtpd_sasl_type = dovecot
smtpd_tls_auth_only = yes
smtpd_tls_cert_file = /etc/ssl/certs/mail.example.com.2013.chain.pem
smtpd_tls_key_file = /etc/ssl/private/example.2013.key
smtpd_tls_session_cache_database = btree:/var/lib/postfix/smtpd_scache
smtpd_use_tls = no
virtual_alias_domains = example.co.uk, example.co
virtual_alias_maps = hash:/etc/postfix/virtual,
ldap:/etc/postfix/ldap_virtual_alias_maps.cf,
ldap:/etc/postfix/ldap_virtual_groups.cf
virtual_mailbox_domains = ldap:/etc/postfix/ldap_virtual_domains.cf
virtual_mailbox_maps = ldap:/etc/postfix/ldap_virtual_mailbox_maps.cf
virtual_transport = dovecot
Now, we only use smtpd_recipient_restrictions because we're pretty
particular about the order of client, helo, recipient restrictions being
applied. But, by my (obviously limited) understanding, the only directive
in there that should be generating that error is the
check_recipient_access hash:/etc/postfix/access directive, but that file
is only used to block some commonly spammed addresses at one of our
virtual alias domains:
postmaster@example.com.au REJECT Recipient address rejected. This domain
name is only an alias. Please email postmaster @ the primary domain or the
mail server hostname.
abuse@example.com.au REJECT Recipient address rejected. This domain
name is only an alias. Please email abuse @ the primary domain or the mail
server hostname.
support@example.com.au REJECT Recipient address rejected. This domain
name is only an alias. Please email support @ the primary domain or the
mail server hostname.
All of the other directives seem to be correctly fulfilled, or I would at
least be expecting a different error, like Helo command rejected, User
unknown in virtual mailbox table, Service unavailable; Client host
[2.3.4.5] blocked using zen.spamhaus.org, etc.
Where should I be looking next to see why I'm getting "Recipient address
rejected: Access denied"? Would any of those other directives in
smtpd_recipient_restrictions issue that error in the case of failure?
denied" error
We're having a situation where inbound emails from a specific company to
legitimate recipients are bouncing with "Recipient address rejected:
Access denied":
Aug 23 09:15:27 extranet postfix/smtpd[20228]: NOQUEUE: reject: RCPT from
sender.com[8.9.10.11]: 554 5.7.1 <user@example.com>: Recipient address
rejected: Access denied; from=<user@sender.com> to=<user@example.com>
proto=ESMTP helo=<mg01d1.sender.com>
postconf -n
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
allow_percent_hack = no
allow_untrusted_routing = yes
append_dot_mydomain = no
biff = no
bounce_queue_lifetime = 24h
broken_sasl_auth_clients = yes
config_directory = /etc/postfix
content_filter = smtp-amavis:[127.0.0.1]:10024
delay_warning_time = 4h
disable_vrfy_command = yes
html_directory = /usr/share/doc/postfix/html
inet_interfaces = all
mailbox_size_limit = 0
maximal_queue_lifetime = 24h
mydestination = mail.example.com, extranet.example.com, localhost
myhostname = mail.example.com
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
myorigin = /etc/mailname
readme_directory = /usr/share/doc/postfix
recipient_delimiter = +
relay_domains = $mydestination
relayhost =
smtp_tls_session_cache_database = btree:/var/lib/postfix/smtp_scache
smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
smtpd_data_restrictions = reject_unauth_pipelining, permit
smtpd_helo_required = yes
smtpd_recipient_restrictions = reject_non_fqdn_recipient,
permit_mynetworks, reject_unauth_destination, check_recipient_access
hash:/etc/postfix/access, reject_non_fqdn_sender, check_sender_access
hash:/etc/postfix/sender_access, reject_non_fqdn_hostname,
reject_invalid_hostname, check_helo_access hash:/etc/postfix/helo_access,
reject_rbl_client zen.spamhaus.org, reject_rbl_client bl.spamcop.net,
permit
smtpd_sasl_auth_enable = no
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous
smtpd_sasl_type = dovecot
smtpd_tls_auth_only = yes
smtpd_tls_cert_file = /etc/ssl/certs/mail.example.com.2013.chain.pem
smtpd_tls_key_file = /etc/ssl/private/example.2013.key
smtpd_tls_session_cache_database = btree:/var/lib/postfix/smtpd_scache
smtpd_use_tls = no
virtual_alias_domains = example.co.uk, example.co
virtual_alias_maps = hash:/etc/postfix/virtual,
ldap:/etc/postfix/ldap_virtual_alias_maps.cf,
ldap:/etc/postfix/ldap_virtual_groups.cf
virtual_mailbox_domains = ldap:/etc/postfix/ldap_virtual_domains.cf
virtual_mailbox_maps = ldap:/etc/postfix/ldap_virtual_mailbox_maps.cf
virtual_transport = dovecot
Now, we only use smtpd_recipient_restrictions because we're pretty
particular about the order of client, helo, recipient restrictions being
applied. But, by my (obviously limited) understanding, the only directive
in there that should be generating that error is the
check_recipient_access hash:/etc/postfix/access directive, but that file
is only used to block some commonly spammed addresses at one of our
virtual alias domains:
postmaster@example.com.au REJECT Recipient address rejected. This domain
name is only an alias. Please email postmaster @ the primary domain or the
mail server hostname.
abuse@example.com.au REJECT Recipient address rejected. This domain
name is only an alias. Please email abuse @ the primary domain or the mail
server hostname.
support@example.com.au REJECT Recipient address rejected. This domain
name is only an alias. Please email support @ the primary domain or the
mail server hostname.
All of the other directives seem to be correctly fulfilled, or I would at
least be expecting a different error, like Helo command rejected, User
unknown in virtual mailbox table, Service unavailable; Client host
[2.3.4.5] blocked using zen.spamhaus.org, etc.
Where should I be looking next to see why I'm getting "Recipient address
rejected: Access denied"? Would any of those other directives in
smtpd_recipient_restrictions issue that error in the case of failure?
Difference between cutting lines with 10dd and d9 in vim?
Difference between cutting lines with 10dd and d9 in vim?
If I understand correctly both commands cut 10 lines and allow you to
paste them anywhere.
Are they both the same as (n-1)dd and dn+enter where n is the number of
lines to be cut?
If I understand correctly both commands cut 10 lines and allow you to
paste them anywhere.
Are they both the same as (n-1)dd and dn+enter where n is the number of
lines to be cut?
Column-Width and Image Wrapping in Firefox
Column-Width and Image Wrapping in Firefox
Using the CSS3 column-width property in Firefox seems to not work as
expected. When an image that is taller than it's container exists, the
image does not wrap onto a new column as expected:
Example in JSFiddle
<div id="container">
<img src="http://placehold.it/300x600" alt="" />
</div>
and
#container {
border: 1px solid #000;
width: 1200px;
height: 300px;
-moz-column-width: 300px;
-webkit-column-width: 300px;
}
One would expect two columns with the top half on the left followed by the
bottom half of the image. This works as expected on Chrome, however with
Firefox, it seems to simply overflow. Is there an additional CSS style
that needs to be applied in this case, or is this something that is
broken/not implemented in Firefox?
Using the CSS3 column-width property in Firefox seems to not work as
expected. When an image that is taller than it's container exists, the
image does not wrap onto a new column as expected:
Example in JSFiddle
<div id="container">
<img src="http://placehold.it/300x600" alt="" />
</div>
and
#container {
border: 1px solid #000;
width: 1200px;
height: 300px;
-moz-column-width: 300px;
-webkit-column-width: 300px;
}
One would expect two columns with the top half on the left followed by the
bottom half of the image. This works as expected on Chrome, however with
Firefox, it seems to simply overflow. Is there an additional CSS style
that needs to be applied in this case, or is this something that is
broken/not implemented in Firefox?
Windows 2k8 R2 - What is the UserDN belongs to 1 OU that inside the other OU?
Windows 2k8 R2 - What is the UserDN belongs to 1 OU that inside the other OU?
I would like to know what is the UserDN (User Distinquished Name) for a
user belongs to 1 OU, but that OU also belongs to the other OU.
UserDN for the first OU: "CN=George Luong,OU=People,DC=quang,DC=com"
Look at the picture to see what I want to know!
I would like to know what is the UserDN (User Distinquished Name) for a
user belongs to 1 OU, but that OU also belongs to the other OU.
UserDN for the first OU: "CN=George Luong,OU=People,DC=quang,DC=com"
Look at the picture to see what I want to know!
How to use non-capturing parenthesis to capture a word or nothing at all?
How to use non-capturing parenthesis to capture a word or nothing at all?
I am looking to use two variations of the same step I'm my ATDD test using
cucumber-jvm
Then order passes quantity limits
and
Then order passes limits
This will read better with different scenarios. I have tried various
variations of the following:
@Then(value = "^order passes (?: | quantity )limits$")
public void verifyCreditPassed(){
//Assert stuff
}
Can anyone help?
Thanks
I am looking to use two variations of the same step I'm my ATDD test using
cucumber-jvm
Then order passes quantity limits
and
Then order passes limits
This will read better with different scenarios. I have tried various
variations of the following:
@Then(value = "^order passes (?: | quantity )limits$")
public void verifyCreditPassed(){
//Assert stuff
}
Can anyone help?
Thanks
Google APIs Explorer Timeout while fetching in Development Server with appengine 1.8.3 SDK
Google APIs Explorer "Timeout while fetching" in Development Server with
appengine 1.8.3 SDK
Im creating a project in google app engine. While testing the project in
development server I have encountered these error.
{
"error" : {
"message" : "Timeout while fetching:
http://127.0.0.1:8888/_ah/spi/com.xxx.XXXEndpoint.method",
"code" : 404,
"errors" : [ {
"domain" : "global",
"reason" : "notFound",
"message" : "Timeout while fetching:
http://127.0.0.1:8888/_ah/spi/com.xxx.XXXEndpoint.method"
} ]
}
}
I dont know if these error are related to Fail to load endpoint class
Note i already apply fix in
https://code.google.com/p/googleappengine/issues/detail?id=9824 but its
not also working.
appengine 1.8.3 SDK
Im creating a project in google app engine. While testing the project in
development server I have encountered these error.
{
"error" : {
"message" : "Timeout while fetching:
http://127.0.0.1:8888/_ah/spi/com.xxx.XXXEndpoint.method",
"code" : 404,
"errors" : [ {
"domain" : "global",
"reason" : "notFound",
"message" : "Timeout while fetching:
http://127.0.0.1:8888/_ah/spi/com.xxx.XXXEndpoint.method"
} ]
}
}
I dont know if these error are related to Fail to load endpoint class
Note i already apply fix in
https://code.google.com/p/googleappengine/issues/detail?id=9824 but its
not also working.
Wednesday, 21 August 2013
DynamicJasper - grouped column seems not grouping
DynamicJasper - grouped column seems not grouping
I am currently developing a report using DynamicJasper. This is the first
time I'm going to use this. I'm following several tutorial but I can't get
my head around this problem. I have a column state which is grouped. This
column can only have two values - state1 and state2. Basically, what I'm
expecting is something like
state1
branch productline columnItem columnCode
branch productline columnItem columnCode
branch productline columnItem columnCode
branch productline columnItem columnCode
branch productline columnItem columnCode
state2
branch productline columnItem columnCode
branch productline columnItem columnCode
branch productline columnItem columnCode
branch productline columnItem columnCode
branch productline columnItem columnCode
But currently, what I'm having is
state1
branch productline columnItem columnCode
state2
branch productline columnItem columnCode
state1
branch productline columnItem columnCode
state2
branch productline columnItem columnCode
...
Its like they are never grouped at all.
Here is my runnable code :
GroupTest.java
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;
import ar.com.fdvs.dj.core.DynamicJasperHelper;
import ar.com.fdvs.dj.core.layout.ClassicLayoutManager;
import ar.com.fdvs.dj.domain.DynamicReport;
import ar.com.fdvs.dj.domain.Style;
import ar.com.fdvs.dj.domain.builders.ColumnBuilder;
import ar.com.fdvs.dj.domain.builders.DynamicReportBuilder;
import ar.com.fdvs.dj.domain.builders.GroupBuilder;
import ar.com.fdvs.dj.domain.constants.GroupLayout;
import ar.com.fdvs.dj.domain.constants.VerticalAlign;
import ar.com.fdvs.dj.domain.entities.DJGroup;
import ar.com.fdvs.dj.domain.entities.columns.AbstractColumn;
import ar.com.fdvs.dj.domain.entities.columns.PropertyColumn;
public class GroupTest{
public DynamicReport buildReport() throws Exception {
DynamicReportBuilder drb = new DynamicReportBuilder();
Integer margin = new Integer(20);
drb.setTitle("November 2006 sales report")
.setSubtitle("This is a sample report")
.setDetailHeight(new Integer(15)).setLeftMargin(margin)
.setRightMargin(margin).setTopMargin(margin).setBottomMargin(margin)
.setPrintBackgroundOnOddRows(true);
AbstractColumn columnState = ColumnBuilder.getNew()
.setColumnProperty("state", String.class.getName())
.setTitle("State")
.setWidth(new Integer(85))
.build();
AbstractColumn columnBranch = ColumnBuilder.getNew()
.setColumnProperty("branch", String.class.getName())
.setTitle("Branch")
.setWidth(new Integer(85))
.build();
AbstractColumn columnaProductLine = ColumnBuilder.getNew()
.setColumnProperty("productLine", String.class.getName())
.setTitle("Product Line")
.setWidth(new Integer(85))
.build();
AbstractColumn columnaItem = ColumnBuilder.getNew()
.setColumnProperty("item", String.class.getName()).setTitle(
"Item").setWidth(new Integer(85))
.build();
AbstractColumn columnCode = ColumnBuilder.getNew()
.setColumnProperty("id", Long.class.getName())
.setTitle("ID")
.setWidth(new Integer(40))
.build();
AbstractColumn columnaQuantity = ColumnBuilder.getNew()
.setColumnProperty("quantity", Long.class.getName())
.setTitle("Quantity")
.setWidth(new Integer(25))
.build();
AbstractColumn columnAmount = ColumnBuilder.getNew()
.setColumnProperty("amount", Float.class.getName())
.setTitle("Amount")
.setWidth(new Integer(100))
.setPattern("$ 0.00")
.build();
Style groupLabelStyle = new Style("groupLabel");
groupLabelStyle.setVerticalAlign(VerticalAlign.BOTTOM);
GroupBuilder gb1 = new GroupBuilder();
DJGroup g1 = gb1.setCriteriaColumn((PropertyColumn) columnState)
.setGroupLayout(GroupLayout.VALUE_IN_HEADER)
.build();
drb.addColumn(columnState);
drb.addColumn(columnBranch);
drb.addColumn(columnaProductLine);
drb.addColumn(columnaItem);
drb.addColumn(columnCode);
drb.addColumn(columnaQuantity);
drb.addColumn(columnAmount);
drb.addGroup(g1);
drb.setUseFullPageWidth(true);
DynamicReport dr = drb.build();
return dr;
}
public static void main(String[] args) throws Exception {
GroupTest test = new GroupTest();
DynamicReport dr = test.buildReport();
JRDataSource ds = new
JRBeanCollectionDataSource(TheBean.getDummyBeans());
JasperPrint jp = DynamicJasperHelper.generateJasperPrint(dr, new
ClassicLayoutManager(), ds);
JasperViewer.viewReport(jp);
}
}
TheBean.java
import java.util.ArrayList;
import java.util.List;
public class TheBean{
private String state;
private String branch;
private String productLine;
private String item;
private Long id;
private Long quantity;
private Float amount;
public TheBean(String state, String branch, String productLine,
String item, Long id, Long quantity, Float amount) {
this.state = state;
this.branch = branch;
this.productLine = productLine;
this.item = item;
this.id = id;
this.quantity = quantity;
this.amount = amount;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getProductLine() {
return productLine;
}
public void setProductLine(String productLine) {
this.productLine = productLine;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public Float getAmount() {
return amount;
}
public void setAmount(Float amount) {
this.amount = amount;
}
public static List getDummyBeans(){
List theBeans = new ArrayList();
for(int i = 0; i < 10; i++){
String s = "";
if(i % 2 == 0)
s = "state1";
else
s = "state2";
TheBean bean = new TheBean(s, "branch", "productLine", "item",
new Long(10L), new Long(10L), new Float(10));
theBeans.add(bean);
}
return theBeans;
}
}
I am currently developing a report using DynamicJasper. This is the first
time I'm going to use this. I'm following several tutorial but I can't get
my head around this problem. I have a column state which is grouped. This
column can only have two values - state1 and state2. Basically, what I'm
expecting is something like
state1
branch productline columnItem columnCode
branch productline columnItem columnCode
branch productline columnItem columnCode
branch productline columnItem columnCode
branch productline columnItem columnCode
state2
branch productline columnItem columnCode
branch productline columnItem columnCode
branch productline columnItem columnCode
branch productline columnItem columnCode
branch productline columnItem columnCode
But currently, what I'm having is
state1
branch productline columnItem columnCode
state2
branch productline columnItem columnCode
state1
branch productline columnItem columnCode
state2
branch productline columnItem columnCode
...
Its like they are never grouped at all.
Here is my runnable code :
GroupTest.java
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;
import ar.com.fdvs.dj.core.DynamicJasperHelper;
import ar.com.fdvs.dj.core.layout.ClassicLayoutManager;
import ar.com.fdvs.dj.domain.DynamicReport;
import ar.com.fdvs.dj.domain.Style;
import ar.com.fdvs.dj.domain.builders.ColumnBuilder;
import ar.com.fdvs.dj.domain.builders.DynamicReportBuilder;
import ar.com.fdvs.dj.domain.builders.GroupBuilder;
import ar.com.fdvs.dj.domain.constants.GroupLayout;
import ar.com.fdvs.dj.domain.constants.VerticalAlign;
import ar.com.fdvs.dj.domain.entities.DJGroup;
import ar.com.fdvs.dj.domain.entities.columns.AbstractColumn;
import ar.com.fdvs.dj.domain.entities.columns.PropertyColumn;
public class GroupTest{
public DynamicReport buildReport() throws Exception {
DynamicReportBuilder drb = new DynamicReportBuilder();
Integer margin = new Integer(20);
drb.setTitle("November 2006 sales report")
.setSubtitle("This is a sample report")
.setDetailHeight(new Integer(15)).setLeftMargin(margin)
.setRightMargin(margin).setTopMargin(margin).setBottomMargin(margin)
.setPrintBackgroundOnOddRows(true);
AbstractColumn columnState = ColumnBuilder.getNew()
.setColumnProperty("state", String.class.getName())
.setTitle("State")
.setWidth(new Integer(85))
.build();
AbstractColumn columnBranch = ColumnBuilder.getNew()
.setColumnProperty("branch", String.class.getName())
.setTitle("Branch")
.setWidth(new Integer(85))
.build();
AbstractColumn columnaProductLine = ColumnBuilder.getNew()
.setColumnProperty("productLine", String.class.getName())
.setTitle("Product Line")
.setWidth(new Integer(85))
.build();
AbstractColumn columnaItem = ColumnBuilder.getNew()
.setColumnProperty("item", String.class.getName()).setTitle(
"Item").setWidth(new Integer(85))
.build();
AbstractColumn columnCode = ColumnBuilder.getNew()
.setColumnProperty("id", Long.class.getName())
.setTitle("ID")
.setWidth(new Integer(40))
.build();
AbstractColumn columnaQuantity = ColumnBuilder.getNew()
.setColumnProperty("quantity", Long.class.getName())
.setTitle("Quantity")
.setWidth(new Integer(25))
.build();
AbstractColumn columnAmount = ColumnBuilder.getNew()
.setColumnProperty("amount", Float.class.getName())
.setTitle("Amount")
.setWidth(new Integer(100))
.setPattern("$ 0.00")
.build();
Style groupLabelStyle = new Style("groupLabel");
groupLabelStyle.setVerticalAlign(VerticalAlign.BOTTOM);
GroupBuilder gb1 = new GroupBuilder();
DJGroup g1 = gb1.setCriteriaColumn((PropertyColumn) columnState)
.setGroupLayout(GroupLayout.VALUE_IN_HEADER)
.build();
drb.addColumn(columnState);
drb.addColumn(columnBranch);
drb.addColumn(columnaProductLine);
drb.addColumn(columnaItem);
drb.addColumn(columnCode);
drb.addColumn(columnaQuantity);
drb.addColumn(columnAmount);
drb.addGroup(g1);
drb.setUseFullPageWidth(true);
DynamicReport dr = drb.build();
return dr;
}
public static void main(String[] args) throws Exception {
GroupTest test = new GroupTest();
DynamicReport dr = test.buildReport();
JRDataSource ds = new
JRBeanCollectionDataSource(TheBean.getDummyBeans());
JasperPrint jp = DynamicJasperHelper.generateJasperPrint(dr, new
ClassicLayoutManager(), ds);
JasperViewer.viewReport(jp);
}
}
TheBean.java
import java.util.ArrayList;
import java.util.List;
public class TheBean{
private String state;
private String branch;
private String productLine;
private String item;
private Long id;
private Long quantity;
private Float amount;
public TheBean(String state, String branch, String productLine,
String item, Long id, Long quantity, Float amount) {
this.state = state;
this.branch = branch;
this.productLine = productLine;
this.item = item;
this.id = id;
this.quantity = quantity;
this.amount = amount;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getProductLine() {
return productLine;
}
public void setProductLine(String productLine) {
this.productLine = productLine;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public Float getAmount() {
return amount;
}
public void setAmount(Float amount) {
this.amount = amount;
}
public static List getDummyBeans(){
List theBeans = new ArrayList();
for(int i = 0; i < 10; i++){
String s = "";
if(i % 2 == 0)
s = "state1";
else
s = "state2";
TheBean bean = new TheBean(s, "branch", "productLine", "item",
new Long(10L), new Long(10L), new Float(10));
theBeans.add(bean);
}
return theBeans;
}
}
File fails to save when filename is modified
File fails to save when filename is modified
I have a button that opens a save dialog window with default extension
filters set, but when the user does not provide a file name extension on
the file name, it should add the extension automatically. The problem is
that when this happens the file will not save (or fail to save) but does
not throw any exception. The file save successfully pop-up shows up
telling the user that the file has been saved successfully but no file was
found in the directory. Here's my code:
private void
saveRecordsButtonActionPerformed(java.awt.event.ActionEvent evt)
{
if(evt.getSource() == this.saveRecordsButton)
{
String recordName = JOptionPane.showInputDialog(this, "Please
type in the name of the record you are about to export: ",
"Input Notice", JOptionPane.INFORMATION_MESSAGE);
if(recordName == null || recordName.equals(""))
{
JOptionPane.showMessageDialog(this, "You must type in the
name of the record in order to save!", "Input Error!",
JOptionPane.ERROR_MESSAGE);
return;
}
int returnVal = this.fileChooser.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
//ObjectOutput oos = null;
try
{
File file = this.fileChooser.getSelectedFile();
String recordDate =
this.viewByDateCB.getSelectedItem().toString();
XMLTableProducer xmlTableProducer = new
XMLTableProducer(this.cbtm, "Cash Book Table",
recordName, recordDate, new Date());
if(!file.getName().contains("."))
{
FileNameExtensionFilter filter =
(FileNameExtensionFilter)this.fileChooser.getFileFilter();
file = new
File(file.getName()+(filter.getExtensions())[0]);
System.out.println(file.getName()); //This
actually prints out the exact file name with
extension the way I want
}
// if file doesnt exists, then create it
if(!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
out.print(xmlTableProducer.getDynamicText());
out.close();
bw.close();
JOptionPane.showMessageDialog(this, "File Saved
Successfully!", "Saved",
JOptionPane.INFORMATION_MESSAGE);
}
catch(IOException xcp)
{
xcp.printStackTrace(System.err);
}
}
}
}
I have a button that opens a save dialog window with default extension
filters set, but when the user does not provide a file name extension on
the file name, it should add the extension automatically. The problem is
that when this happens the file will not save (or fail to save) but does
not throw any exception. The file save successfully pop-up shows up
telling the user that the file has been saved successfully but no file was
found in the directory. Here's my code:
private void
saveRecordsButtonActionPerformed(java.awt.event.ActionEvent evt)
{
if(evt.getSource() == this.saveRecordsButton)
{
String recordName = JOptionPane.showInputDialog(this, "Please
type in the name of the record you are about to export: ",
"Input Notice", JOptionPane.INFORMATION_MESSAGE);
if(recordName == null || recordName.equals(""))
{
JOptionPane.showMessageDialog(this, "You must type in the
name of the record in order to save!", "Input Error!",
JOptionPane.ERROR_MESSAGE);
return;
}
int returnVal = this.fileChooser.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
//ObjectOutput oos = null;
try
{
File file = this.fileChooser.getSelectedFile();
String recordDate =
this.viewByDateCB.getSelectedItem().toString();
XMLTableProducer xmlTableProducer = new
XMLTableProducer(this.cbtm, "Cash Book Table",
recordName, recordDate, new Date());
if(!file.getName().contains("."))
{
FileNameExtensionFilter filter =
(FileNameExtensionFilter)this.fileChooser.getFileFilter();
file = new
File(file.getName()+(filter.getExtensions())[0]);
System.out.println(file.getName()); //This
actually prints out the exact file name with
extension the way I want
}
// if file doesnt exists, then create it
if(!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
out.print(xmlTableProducer.getDynamicText());
out.close();
bw.close();
JOptionPane.showMessageDialog(this, "File Saved
Successfully!", "Saved",
JOptionPane.INFORMATION_MESSAGE);
}
catch(IOException xcp)
{
xcp.printStackTrace(System.err);
}
}
}
}
skip first element using .append()
skip first element using .append()
I'm trying to skip the first I'm loading up with .append() I'm not sure
how to do it.
here is the code I'm using.
$.each(get_images, function(i,img){
$('#container ul').append('<li><img src="'+img+'"/></li>');
});
I'm trying to skip the first I'm loading up with .append() I'm not sure
how to do it.
here is the code I'm using.
$.each(get_images, function(i,img){
$('#container ul').append('<li><img src="'+img+'"/></li>');
});
Android 4.2 changes to Android 3.0 under Project in Eclipse
Android 4.2 changes to Android 3.0 under Project in Eclipse
Yesterday when I imported my App it showed Android 4.2 But when I loaded
my app it shows Android 3.0. Now my application is having an issue with
the manifest. Any idea why?
Yesterday when I imported my App it showed Android 4.2 But when I loaded
my app it shows Android 3.0. Now my application is having an issue with
the manifest. Any idea why?
Use Selenium to press tab and then write with java
Use Selenium to press tab and then write with java
I want selenium to press "TAB" for me and then write something in the
focused field, now I know that I can use
sendKeys(Keys.TAB)
But as I understand it That require a locator behind it, I want to test
the tab order of my page and to do so, I want to be able to focus on my
first element only, then tab my way through the page like this:
--THE ELEMENTS IN THE TAB ORDER THEY ARE SUPOSED TO BE--
String[] elementArray = {"firstname","lastname", "phone", "email"};
for(int x = 0; x < 4; x = x+1)
{
WebElement theElement = driver.findElement(By.id(elementArray[x]));
if (x == 0) {driver.theElement.sendKeys(x)}
else{driver.(TheCurrentlyFocusedElement).sendKeys(x)}
String elementval = theElement.getAttribute("value");
assertEquals(x, elementval);
(TheCurrentlyFocusedElement).sendKeys(Keys.TAB);
}
So the question is, is there a method I can use that allows me to use the
currently focused element as a locator? ie:
driver.focusedElement().sendKeys(Keys.TAB); ?
I want selenium to press "TAB" for me and then write something in the
focused field, now I know that I can use
sendKeys(Keys.TAB)
But as I understand it That require a locator behind it, I want to test
the tab order of my page and to do so, I want to be able to focus on my
first element only, then tab my way through the page like this:
--THE ELEMENTS IN THE TAB ORDER THEY ARE SUPOSED TO BE--
String[] elementArray = {"firstname","lastname", "phone", "email"};
for(int x = 0; x < 4; x = x+1)
{
WebElement theElement = driver.findElement(By.id(elementArray[x]));
if (x == 0) {driver.theElement.sendKeys(x)}
else{driver.(TheCurrentlyFocusedElement).sendKeys(x)}
String elementval = theElement.getAttribute("value");
assertEquals(x, elementval);
(TheCurrentlyFocusedElement).sendKeys(Keys.TAB);
}
So the question is, is there a method I can use that allows me to use the
currently focused element as a locator? ie:
driver.focusedElement().sendKeys(Keys.TAB); ?
Tuesday, 20 August 2013
Allow someone else edit an album on Google+
Allow someone else edit an album on Google+
Is it possible to allow someone else to edit photos within a specific
Google+ album? Like adding a legend or a location for the photo(s)?
Is it possible to allow someone else to edit photos within a specific
Google+ album? Like adding a legend or a location for the photo(s)?
Maximum of a trigonometric Polynomial
Maximum of a trigonometric Polynomial
Given $$x+y+z=\pi$$ $$3\sin(x)+4\sin(y)+18 \sin(z)=A$$ QuestionFfind
maximum of $A$.
I spend so many time on this question.
answer is $ 35\sqrt{7} /4$, but why?
Given $$x+y+z=\pi$$ $$3\sin(x)+4\sin(y)+18 \sin(z)=A$$ QuestionFfind
maximum of $A$.
I spend so many time on this question.
answer is $ 35\sqrt{7} /4$, but why?
show tweets in a listview in twitter4j
show tweets in a listview in twitter4j
I have been playing around with twitter4j and Android and so far so good.
However I am having problems figuring out how to display the tweets
properly on a list View. Here is my code so far, based on the code example
given on the Twitter4j website:
public class MainActivity extends Activity {
//ListView with the tweets
private ListView timelineListView;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
//Adapter
ArrayAdapter<twitter4j.Status> tweetAdapter ;
//List
List<Status> rawStatuses;
//Other stuff
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_main);
//Login methods, checking that there is an Internet connection, etc...
When a button is
//pressed, an Asynctask is called and it retrieves the tweets:
class updateTimeline extends AsyncTask <Void, Void, Void>{
protected void onPreExecute(Void thing){
}
protected Void doInBackground(Void... arg0) {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token =
mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret =
mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token,
access_token_secret);
Twitter twitter = new
TwitterFactory(builder.build()).getInstance(accessToken);
User user = twitter.verifyCredentials();
rawStatuses = twitter.getHomeTimeline();
System.out.println("Showing @" + user.getScreenName() + "'s
home timeline.");
for (twitter4j.Status status : rawStatuses) {
System.out.println("@" + status.getUser().getScreenName()
+ " - " + status.getText());
}
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to get timeline: " + te.getMessage());
//System.exit(-1);
}
return null;
}
protected void onPostExecute(Void result) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Timeline updated", Toast.LENGTH_SHORT)
.show();
tweetAdapter = new
ArrayAdapter<twitter4j.Status>(MainActivity.this,
android.R.layout.simple_list_item_1, rawStatuses);
timelineListView.setAdapter(tweetAdapter);
}
});
}
It retrieves the last 20 tweets or so just fine. But my problems comes
fromt he final part, where I bind the list rawStatuses to the adapter and
the listView, because it basically prints ALL the information on screen:
Ok, not all that information is useful or ever needed, but it is there.
And I don't know how to display in the listView only the Twitter handle
and the tweet, for example (i.e. extract that information from the list
rawStatuses properly). I thought about having a List with the most useful
information (something like: List <User, Tweet, ID, Time> ), but it seems
to me cumbersome and a very poor solution.
My question is: How can or should manage all that information that a tweet
contains (an many tweets) so I can display what I want and still have the
rest? The closest answer I have found is this answer, but the link given
doesn't work anymore.
I hope I have explained myself. Thanks in advance.
I have been playing around with twitter4j and Android and so far so good.
However I am having problems figuring out how to display the tweets
properly on a list View. Here is my code so far, based on the code example
given on the Twitter4j website:
public class MainActivity extends Activity {
//ListView with the tweets
private ListView timelineListView;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
//Adapter
ArrayAdapter<twitter4j.Status> tweetAdapter ;
//List
List<Status> rawStatuses;
//Other stuff
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_main);
//Login methods, checking that there is an Internet connection, etc...
When a button is
//pressed, an Asynctask is called and it retrieves the tweets:
class updateTimeline extends AsyncTask <Void, Void, Void>{
protected void onPreExecute(Void thing){
}
protected Void doInBackground(Void... arg0) {
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token =
mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret =
mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token,
access_token_secret);
Twitter twitter = new
TwitterFactory(builder.build()).getInstance(accessToken);
User user = twitter.verifyCredentials();
rawStatuses = twitter.getHomeTimeline();
System.out.println("Showing @" + user.getScreenName() + "'s
home timeline.");
for (twitter4j.Status status : rawStatuses) {
System.out.println("@" + status.getUser().getScreenName()
+ " - " + status.getText());
}
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to get timeline: " + te.getMessage());
//System.exit(-1);
}
return null;
}
protected void onPostExecute(Void result) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Timeline updated", Toast.LENGTH_SHORT)
.show();
tweetAdapter = new
ArrayAdapter<twitter4j.Status>(MainActivity.this,
android.R.layout.simple_list_item_1, rawStatuses);
timelineListView.setAdapter(tweetAdapter);
}
});
}
It retrieves the last 20 tweets or so just fine. But my problems comes
fromt he final part, where I bind the list rawStatuses to the adapter and
the listView, because it basically prints ALL the information on screen:
Ok, not all that information is useful or ever needed, but it is there.
And I don't know how to display in the listView only the Twitter handle
and the tweet, for example (i.e. extract that information from the list
rawStatuses properly). I thought about having a List with the most useful
information (something like: List <User, Tweet, ID, Time> ), but it seems
to me cumbersome and a very poor solution.
My question is: How can or should manage all that information that a tweet
contains (an many tweets) so I can display what I want and still have the
rest? The closest answer I have found is this answer, but the link given
doesn't work anymore.
I hope I have explained myself. Thanks in advance.
Multiple boxplots using ggplot
Multiple boxplots using ggplot
I have a dataframe that looks like the one attached, with 6 columns and
1000 rows (tab separated). The column headings (0,30,60,120,240 and 360)
are a time series (with 0 representing 0 mins, 30 meaning 30 mins and so
on). I'd like to create 6 boxplots corresponding to the columns using
ggplot2 in a single plot, keeping in mind that they need to be spaced
based on the time difference. It seems I would need to melt the columns,
but cant figure out a way to do so. Any help would be much appreciated.
0 30 60 120 240 360
1 1 NA NA NA 1 1
2 NA NA NA NA NA NA
3 NA NA 1 1 1 1
4 0.5 0.21 0.15 1 0.38 0.8
5 0.63 1 0.86 0.85 0.94 0.91
I have a dataframe that looks like the one attached, with 6 columns and
1000 rows (tab separated). The column headings (0,30,60,120,240 and 360)
are a time series (with 0 representing 0 mins, 30 meaning 30 mins and so
on). I'd like to create 6 boxplots corresponding to the columns using
ggplot2 in a single plot, keeping in mind that they need to be spaced
based on the time difference. It seems I would need to melt the columns,
but cant figure out a way to do so. Any help would be much appreciated.
0 30 60 120 240 360
1 1 NA NA NA 1 1
2 NA NA NA NA NA NA
3 NA NA 1 1 1 1
4 0.5 0.21 0.15 1 0.38 0.8
5 0.63 1 0.86 0.85 0.94 0.91
Created new user and can't select database - MySQL PHP
Created new user and can't select database - MySQL PHP
Problem - Created new user with 'minimal' permissions and when I plug in
the account info I get the error 'No Database Selected'
In MySQL Workbench I can connect to the database and select data. But not
through PHP.
Permissions - SELECT, INSERT, UPDATE, CREATE TEMPORARY TABLES, LOCK TABLES
$db_select = mysql_select_db('DBNAME',$conn);
if($db_select){
$sql = "SELECT * FROM TABLE1 LIMIT 1";
if ($result = mysql_query($sql)) {
$row = mysql_fetch_assoc($result);
}
else print mysql_error();
}
Problem - Created new user with 'minimal' permissions and when I plug in
the account info I get the error 'No Database Selected'
In MySQL Workbench I can connect to the database and select data. But not
through PHP.
Permissions - SELECT, INSERT, UPDATE, CREATE TEMPORARY TABLES, LOCK TABLES
$db_select = mysql_select_db('DBNAME',$conn);
if($db_select){
$sql = "SELECT * FROM TABLE1 LIMIT 1";
if ($result = mysql_query($sql)) {
$row = mysql_fetch_assoc($result);
}
else print mysql_error();
}
HtmlAgilityPack works in WP8 but not WP7?
HtmlAgilityPack works in WP8 but not WP7?
I have used HTMLAgilityPack in a Windows Phone application. I want the
application to be available both for Windows Phone 8, but lower versions
of windows as well.
My syntax in the callback method of LoadAsync() is like this:
HtmlDocument doc = e.Document;
var collection = (from data in doc.DocumentNode.Descendants()
where data.name=="a" && data.InnerText.Contains(myString)
select new
{ Link = data.Attributes["href"].Value }).First();
Now, this code runs perfectly in Windows 8 emulator, but in older versions
(such as in the emulator 7.1) I get a nullreference exception. It is
really weird, as the same thing, works in WP8, but in 7.1 it just crashes.
I tested it on a friend's phone, running 7.8, and it didn't crash, yet it
didn't display the results as the WP8 emulator does.
I have read about incompatibility from WP7.1 to WP8, but not vice versa. I
have however, included the XPath.dll from the silverlight 4.0 folder in my
references.
Any clue? Is it possible that is due to my LINQ statement?
I have used HTMLAgilityPack in a Windows Phone application. I want the
application to be available both for Windows Phone 8, but lower versions
of windows as well.
My syntax in the callback method of LoadAsync() is like this:
HtmlDocument doc = e.Document;
var collection = (from data in doc.DocumentNode.Descendants()
where data.name=="a" && data.InnerText.Contains(myString)
select new
{ Link = data.Attributes["href"].Value }).First();
Now, this code runs perfectly in Windows 8 emulator, but in older versions
(such as in the emulator 7.1) I get a nullreference exception. It is
really weird, as the same thing, works in WP8, but in 7.1 it just crashes.
I tested it on a friend's phone, running 7.8, and it didn't crash, yet it
didn't display the results as the WP8 emulator does.
I have read about incompatibility from WP7.1 to WP8, but not vice versa. I
have however, included the XPath.dll from the silverlight 4.0 folder in my
references.
Any clue? Is it possible that is due to my LINQ statement?
Adding item id's to the js if statement
Adding item id's to the js if statement
I want to add some more item Id's to the follow if statement -
if(engine.currentMap[toY] &&
engine.currentMap[toY][toX] &&
engine.currentMap[toY][toX].item > 1)
{
engine.keyboard.canInput = true;
}
Where it says engine.currentMap[toY][toX].item > 1) I want to also add
numerical Id's so it would be like .item > 1 || 45 || 78 || 45 || 23. If
that kinda make scenes.
I want to add some more item Id's to the follow if statement -
if(engine.currentMap[toY] &&
engine.currentMap[toY][toX] &&
engine.currentMap[toY][toX].item > 1)
{
engine.keyboard.canInput = true;
}
Where it says engine.currentMap[toY][toX].item > 1) I want to also add
numerical Id's so it would be like .item > 1 || 45 || 78 || 45 || 23. If
that kinda make scenes.
Monday, 19 August 2013
compile 32bit program on ubuntu 64bit (libjvm.so problems)
compile 32bit program on ubuntu 64bit (libjvm.so problems)
Here is downloadable source code:
http://cfile237.uf.daum.net/attach/247819495212DF1C07B9EB
well, first, my ubuntu is 64bit 12.04LTS. and, I installed both 64 and
32bit version of latest jdk 1.7.0_25.
I tried to compile the source code above using 32 bit library of jdk
version on my 64bit Ubuntu, it shows a following error:
/usr/lib/jvm/jdk1.7.0_25_x86/jre/lib/i386/server/libjvm.so: could not read
symbols: File in wrong format
collect2: ld returned 1 exit status
However, if I try to compile those source code using 64 bit library of jdk
version, it compiles fine and run very well.
My problem is, as you know, how would I make it compile and run well using
32 bit version of jdk library on 64bit Ubuntu platform?
AH, before I compile, I always typed following commands on Terminal,
for 32 bit compile
export PATH=$PATH:/usr/lib/jvm/jdk1.7.0_25_x86/bin
export JAVA_HOME=/usr/lib/jvm/jdk1.7.0_25_x86
export LD_LIBRARY_PATH=$JAVA_HOME/jre/lib/i386:$JAVA_HOME/jre/lib/i386/server
for 64 bit compile
export PATH=$PATH:/usr/lib/jvm/jdk1.7.0_25_x64/bin
export JAVA_HOME=/usr/lib/jvm/jdk1.7.0_25_x64
export
LD_LIBRARY_PATH=$JAVA_HOME/jre/lib/amd64:$JAVA_HOME/jre/lib/amd64/server
Here is downloadable source code:
http://cfile237.uf.daum.net/attach/247819495212DF1C07B9EB
well, first, my ubuntu is 64bit 12.04LTS. and, I installed both 64 and
32bit version of latest jdk 1.7.0_25.
I tried to compile the source code above using 32 bit library of jdk
version on my 64bit Ubuntu, it shows a following error:
/usr/lib/jvm/jdk1.7.0_25_x86/jre/lib/i386/server/libjvm.so: could not read
symbols: File in wrong format
collect2: ld returned 1 exit status
However, if I try to compile those source code using 64 bit library of jdk
version, it compiles fine and run very well.
My problem is, as you know, how would I make it compile and run well using
32 bit version of jdk library on 64bit Ubuntu platform?
AH, before I compile, I always typed following commands on Terminal,
for 32 bit compile
export PATH=$PATH:/usr/lib/jvm/jdk1.7.0_25_x86/bin
export JAVA_HOME=/usr/lib/jvm/jdk1.7.0_25_x86
export LD_LIBRARY_PATH=$JAVA_HOME/jre/lib/i386:$JAVA_HOME/jre/lib/i386/server
for 64 bit compile
export PATH=$PATH:/usr/lib/jvm/jdk1.7.0_25_x64/bin
export JAVA_HOME=/usr/lib/jvm/jdk1.7.0_25_x64
export
LD_LIBRARY_PATH=$JAVA_HOME/jre/lib/amd64:$JAVA_HOME/jre/lib/amd64/server
What are the steps to create an Ubuntu Live CD with the Server version?
What are the steps to create an Ubuntu Live CD with the Server version?
I used the 'Startup Disk Creator' with the 12.04 LTS iso to create a
bootable USB. This worked just fine, but when it started up it gave me a
menu to:
Install Ubuntu Server
Multiple server install with MAAS
Check disc for defects
Test memory
Boot from first hard disk
Rescue a broken system
What do I have to do to get it to boot directly into a login prompt?
I used the 'Startup Disk Creator' with the 12.04 LTS iso to create a
bootable USB. This worked just fine, but when it started up it gave me a
menu to:
Install Ubuntu Server
Multiple server install with MAAS
Check disc for defects
Test memory
Boot from first hard disk
Rescue a broken system
What do I have to do to get it to boot directly into a login prompt?
github error: insufficient permission for adding an object to repository database
github error: insufficient permission for adding an object to repository
database
I used to be able to do, from my App folder:
git add .
git commit -m "commit details"
git push
and the latest version of my app on my local machine would be backed up on
in my master repo, on github.
Now, when I get as far as just the git add . command, I get:
mycompaq@ubuntu:~/myapp$ git add .
error: insufficient permission for adding an object to repository database
.git/objects
error: app/views/reviews/update.js.erb: failed to insert into database
error: unable to index file app/views/reviews/update.js.erb
fatal: updating files failed
mycompaq@ubuntu:~/myapp$
I read in a message on Stackoverflow the way to overcome a similar problem
was with:
chown -R user:user /project/directory
But seeing as I got in a whole load of trouble in the first place by
running commands I wasn't sure about, I want to know if this is the
command for me. What does it do? Can it be undone?
What should the exact syntax be, if the user is 'Christophe', and the
folder where my Rails app is stored is called 'myapp'. I mean should it be
chown -R user:christophe /myapp/app/views/reviews/update.js.erb
Sorry for all the questions.
database
I used to be able to do, from my App folder:
git add .
git commit -m "commit details"
git push
and the latest version of my app on my local machine would be backed up on
in my master repo, on github.
Now, when I get as far as just the git add . command, I get:
mycompaq@ubuntu:~/myapp$ git add .
error: insufficient permission for adding an object to repository database
.git/objects
error: app/views/reviews/update.js.erb: failed to insert into database
error: unable to index file app/views/reviews/update.js.erb
fatal: updating files failed
mycompaq@ubuntu:~/myapp$
I read in a message on Stackoverflow the way to overcome a similar problem
was with:
chown -R user:user /project/directory
But seeing as I got in a whole load of trouble in the first place by
running commands I wasn't sure about, I want to know if this is the
command for me. What does it do? Can it be undone?
What should the exact syntax be, if the user is 'Christophe', and the
folder where my Rails app is stored is called 'myapp'. I mean should it be
chown -R user:christophe /myapp/app/views/reviews/update.js.erb
Sorry for all the questions.
javax.jcr.RepositoryException: This session has been closed. (Wicket, Brix, Multithreading)
javax.jcr.RepositoryException: This session has been closed. (Wicket,
Brix, Multithreading)
I have a very large project in which I am performing parallel processing
of large files (5mb) which are stored as nodes within brix repositry. The
load nodes as input stream, but the problem is that if I launch loading at
the same time something is closing my session and I get:
javax.jcr.RepositoryException: This session has been closed.
The project is very big and I cant really trace whats causing the session
to close.. I tried checking if its alive and reobtaining or wrapping dead
node into BrixNodeModel but it doesn't help.. The strange thing is that if
I launch threads with very small delay (0,5s for instance) its all fine
and they can run parallel, but If I launch them at the same time its all
going wrong...
Brix, Multithreading)
I have a very large project in which I am performing parallel processing
of large files (5mb) which are stored as nodes within brix repositry. The
load nodes as input stream, but the problem is that if I launch loading at
the same time something is closing my session and I get:
javax.jcr.RepositoryException: This session has been closed.
The project is very big and I cant really trace whats causing the session
to close.. I tried checking if its alive and reobtaining or wrapping dead
node into BrixNodeModel but it doesn't help.. The strange thing is that if
I launch threads with very small delay (0,5s for instance) its all fine
and they can run parallel, but If I launch them at the same time its all
going wrong...
Hibernate @Valid and Spring MVC
Hibernate @Valid and Spring MVC
Before asking here, I googled and search here a lot, find a usefull
content, but I could not solve my problem.
I´m studing the use of Spring MVC and Hibernate with i18n support. My
problem is related when the form needs to be validated, below is the code
I generated.
Bean User
@Entity(name="users")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty
private String firstName;
private String lastName;
}
UserController
@Secured("ROLE_USER")
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String doSave(@ModelAttribute("formUsuario") @Valid
br.com.rodrigoferra.domain.User user, BindingResult results, Model model)
{
UserValidator userValidator = new UserValidator();
userValidator.validate(user, results);
if(results.hasErrors()) {
return "users/edit";
}
user = userService.create(user);
return "redirect:/users/";
}
UserValidator
public class UserValidator implements Validator {
@Autowired private MessageSource messageSource;
protected static Logger logger = Logger.getLogger("controller");
public boolean supports(Class<?> clazz) {
return User.class.equals(clazz);
}
public void validate(Object target, Errors errors) {
logger.info("Entrou em validate");
User user = (User) target;
if (user.getFirstName() == null) {
errors.rejectValue("firstName", "NotEmpty.user.firstName");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName",
"NotEmpty.user.firstName");
}
}
The location where messages.properties is located: Finally, the
applicationContext.xml
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames"
value="classpath:/resources/i18n/messages,
classpath:/resources/i18n/errors" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean name="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource">
<ref bean="messageSource" />
</property>
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.FixedLocaleResolver">
<property name="defaultLocale" value="pt_BR" />
</bean>
The error reported when the method is executed:
GRAVE: Servlet.service() for servlet [spring] in context with path
[/simpla-spring-version] threw exception [Request processing failed;
nested exception is org.apache.tiles.request.render.CannotRenderException:
ServletException including path '/WEB-INF/layouts/simpleLayout.jsp'.] with
root cause
org.springframework.context.NoSuchMessageException: No message found under
code 'NotEmpty.user.firstName' for locale 'pt_BR'.
Well, I´m getting crazy with it, already changed the location, tryed a lot
of samples founded over the web and spring forum... I appreciate any help.
Sorry for my bad english.
Before asking here, I googled and search here a lot, find a usefull
content, but I could not solve my problem.
I´m studing the use of Spring MVC and Hibernate with i18n support. My
problem is related when the form needs to be validated, below is the code
I generated.
Bean User
@Entity(name="users")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty
private String firstName;
private String lastName;
}
UserController
@Secured("ROLE_USER")
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String doSave(@ModelAttribute("formUsuario") @Valid
br.com.rodrigoferra.domain.User user, BindingResult results, Model model)
{
UserValidator userValidator = new UserValidator();
userValidator.validate(user, results);
if(results.hasErrors()) {
return "users/edit";
}
user = userService.create(user);
return "redirect:/users/";
}
UserValidator
public class UserValidator implements Validator {
@Autowired private MessageSource messageSource;
protected static Logger logger = Logger.getLogger("controller");
public boolean supports(Class<?> clazz) {
return User.class.equals(clazz);
}
public void validate(Object target, Errors errors) {
logger.info("Entrou em validate");
User user = (User) target;
if (user.getFirstName() == null) {
errors.rejectValue("firstName", "NotEmpty.user.firstName");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName",
"NotEmpty.user.firstName");
}
}
The location where messages.properties is located: Finally, the
applicationContext.xml
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames"
value="classpath:/resources/i18n/messages,
classpath:/resources/i18n/errors" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean name="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource">
<ref bean="messageSource" />
</property>
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.FixedLocaleResolver">
<property name="defaultLocale" value="pt_BR" />
</bean>
The error reported when the method is executed:
GRAVE: Servlet.service() for servlet [spring] in context with path
[/simpla-spring-version] threw exception [Request processing failed;
nested exception is org.apache.tiles.request.render.CannotRenderException:
ServletException including path '/WEB-INF/layouts/simpleLayout.jsp'.] with
root cause
org.springframework.context.NoSuchMessageException: No message found under
code 'NotEmpty.user.firstName' for locale 'pt_BR'.
Well, I´m getting crazy with it, already changed the location, tryed a lot
of samples founded over the web and spring forum... I appreciate any help.
Sorry for my bad english.
Sunday, 18 August 2013
Authenticating WEB API and knockout Js view model
Authenticating WEB API and knockout Js view model
I am trying to create secured MVC4 web API project. In this application
knockout Js will access API service directly. I need authentication on
his. I am confused how to apply authentication only on web api. I can't
use MVC authentication because other projects also share same API
services. Any one please suggest a good solution using knockout js and web
api. I tried Thinktecture.IdentityModel but I am not able to use knockout
Js in it. this project is in .net 4.0. Thanks in advance
I am trying to create secured MVC4 web API project. In this application
knockout Js will access API service directly. I need authentication on
his. I am confused how to apply authentication only on web api. I can't
use MVC authentication because other projects also share same API
services. Any one please suggest a good solution using knockout js and web
api. I tried Thinktecture.IdentityModel but I am not able to use knockout
Js in it. this project is in .net 4.0. Thanks in advance
How to do a hidden html visable with a javascript function?
How to do a hidden html visable with a javascript function?
I'm trying to do a hidden HTML visable, by running a Javascript function.
This is the hidden div I want to get visable with a javascript function:
<div id="Signup" class="modal hide fade LoginSignup" tabindex="-1"
role="dialog" aria-labelledby="myModalLabel2" aria-hidden="true">
Some content*
</div>
Right now I'm using this button to show the hidden div content:
<li>
<a href="#Signup" role="button" data-toggle="modal" class="btn
btn-success">Sign Up</a>
</li>
Is this the best way to do it? Or is it an other way to get a designable
pop up window?
I'm trying to do a hidden HTML visable, by running a Javascript function.
This is the hidden div I want to get visable with a javascript function:
<div id="Signup" class="modal hide fade LoginSignup" tabindex="-1"
role="dialog" aria-labelledby="myModalLabel2" aria-hidden="true">
Some content*
</div>
Right now I'm using this button to show the hidden div content:
<li>
<a href="#Signup" role="button" data-toggle="modal" class="btn
btn-success">Sign Up</a>
</li>
Is this the best way to do it? Or is it an other way to get a designable
pop up window?
New to PowerShell. Unfamiliar with scripts [migrated]
New to PowerShell. Unfamiliar with scripts [migrated]
I found several answers on this site about renaming files in Powershell so
I'm sorry if this is a repeat. I've spent a good 5 hours on google and
various websites trying to figure this out. I really did try to explain
well.I am not a programmer just someone that is meticulous about their
filing. I have 14,000 picture sorted into files by year and month but
taken with multiple cameras and I want the file name to reflect the date
taken. For example October 16, 1998 pictures are in a folder called 1998
subfolder 10 October subfolder 19981016. I want the all the pictures to be
named 19981016_0001 19981016_0002 etc. I tried multiple suggestions but it
hasn't worked. Probably due to my lack of programmer knowledge haha. Could
someone help me out and give me dummy instructions? I can get to the point
where it list the folder I want to change but I'm unable to actually
change it. All of my pictures are .jpg. I tried to attach a screenshot of
what I did but unfortunately I can't since I'm too new here. Thanks in
advance!
I created a temp file of copies in case I messed it up. I started by
typing cd "C:\Documents and Settings\Brooke LastName\Desktop\Temp" then
after successfully getting my file to load I used a formula I found on
this forum.
ls *jpg | Foreach {$i=1} {Rename-Item _ -NewName
("$($.19981016){0:00000000#} .jpg" -f $i++) -whatif}
The error I got said
Unexpected token ' .19981016' in expression or statement.
At line:1 char:12 + $.19981016 <<<<
The error repeated several times
I found several formulas on the web but most created files that would
number with parenthesis for example vacation (1).jpg I want a four digit
counter after an underscore at the end of my date. ie 19981016_0001
I found several answers on this site about renaming files in Powershell so
I'm sorry if this is a repeat. I've spent a good 5 hours on google and
various websites trying to figure this out. I really did try to explain
well.I am not a programmer just someone that is meticulous about their
filing. I have 14,000 picture sorted into files by year and month but
taken with multiple cameras and I want the file name to reflect the date
taken. For example October 16, 1998 pictures are in a folder called 1998
subfolder 10 October subfolder 19981016. I want the all the pictures to be
named 19981016_0001 19981016_0002 etc. I tried multiple suggestions but it
hasn't worked. Probably due to my lack of programmer knowledge haha. Could
someone help me out and give me dummy instructions? I can get to the point
where it list the folder I want to change but I'm unable to actually
change it. All of my pictures are .jpg. I tried to attach a screenshot of
what I did but unfortunately I can't since I'm too new here. Thanks in
advance!
I created a temp file of copies in case I messed it up. I started by
typing cd "C:\Documents and Settings\Brooke LastName\Desktop\Temp" then
after successfully getting my file to load I used a formula I found on
this forum.
ls *jpg | Foreach {$i=1} {Rename-Item _ -NewName
("$($.19981016){0:00000000#} .jpg" -f $i++) -whatif}
The error I got said
Unexpected token ' .19981016' in expression or statement.
At line:1 char:12 + $.19981016 <<<<
The error repeated several times
I found several formulas on the web but most created files that would
number with parenthesis for example vacation (1).jpg I want a four digit
counter after an underscore at the end of my date. ie 19981016_0001
NoMethodError in Posts#show error in section 6.4 of RailsGuides
NoMethodError in Posts#show error in section 6.4 of RailsGuides
I am trying to follow the RailsGuides,
http://edgeguides.rubyonrails.org/getting_started.html
Now, in section 6.4 where I am supposed to be able to add comments in my
blog site, I am encountering this error:
NoMethodError in Posts#show Showing
C:/Sites/blog/app/views/posts/show.html.erb where line #12 raised:
undefined method `comments' for #
below is the snippet in my show.html.erb
<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
<p>
<%= f.label :commenter %><br>
<%= f.text_field :commenter %>
Below is the snippet for my comments controller:
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
redirect_to post_path(@post)
end
private
def comment_params
params.require(:comment).permit(:commenter, :body)
end
end
Please help me thanks.
-aguds
I am trying to follow the RailsGuides,
http://edgeguides.rubyonrails.org/getting_started.html
Now, in section 6.4 where I am supposed to be able to add comments in my
blog site, I am encountering this error:
NoMethodError in Posts#show Showing
C:/Sites/blog/app/views/posts/show.html.erb where line #12 raised:
undefined method `comments' for #
below is the snippet in my show.html.erb
<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
<p>
<%= f.label :commenter %><br>
<%= f.text_field :commenter %>
Below is the snippet for my comments controller:
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
redirect_to post_path(@post)
end
private
def comment_params
params.require(:comment).permit(:commenter, :body)
end
end
Please help me thanks.
-aguds
how to compiler compile if statement
how to compiler compile if statement
main()
{
int k = 5;
if(++k <5 && k++/5 || ++k<=8); // how to compiler compile this statement
print f("%d",k);
}
// Here answer is 7 but why ?
main()
{
int k = 5;
if(++k <5 && k++/5 || ++k<=8); // how to compiler compile this statement
print f("%d",k);
}
// Here answer is 7 but why ?
What is the online URL of todo list manager app Astrid?
What is the online URL of todo list manager app Astrid?
I often use both of the versions, web & Android app, to manage my todo lists.
But since Yahoo acquired Astrid, I cannot have the web version work any more.
What is wrong with the web? Where can I manipulate my todo(s) via a web
browser?
I often use both of the versions, web & Android app, to manage my todo lists.
But since Yahoo acquired Astrid, I cannot have the web version work any more.
What is wrong with the web? Where can I manipulate my todo(s) via a web
browser?
Edit SendInput's wParam and lParam
Edit SendInput's wParam and lParam
I need to simulate keyboard press on C#, so im using SendInput function
from InputSimulator DLL (http://inputsimulator.codeplex.com/). Checking
keypressing through spy++, I saw that there is difference between real
keyboard press and sendinput.
Real keyboard press:
WM_KEYDOWN nVirtKey:VK_DOWN cRepeat:1 ScanCode:50 fExtended:1 fAltDown:0
fRepeat:0 fUp:0 wParam: 00000028 lParam: 01500001 WM_KEYUP
nVirtKey:VK_DOWN cRepeat:1 ScanCode:50 fExtended:1 fAltDown:0 fRepeat:0
fUp:1 wParam: 00000028 lParam: C1500001
SendInput:
WM_KEYDOWN nVirtKey:VK_DOWN cRepeat:1 ScanCode:50 fExtended:0 fAltDown:0
fRepeat:0 fUp:0 wParam: 00000028 lParam: 00500001 WM_KEYUP
nVirtKey:VK_DOWN cRepeat:1 ScanCode:50 fExtended:0 fAltDown:0 fRepeat:0
fUp:1 wParam: 00000028 lParam: C0500001
As you can see, there are different wParam and lParam.
This is KeyDown function, i can edit some parameters, but i dont know,
what parameter will changes wParam and lParam:
public static void SimulateKeyDown(VirtualKeyCode keyCode, ushort
Scan, uint Flags, uint Time, IntPtr ExtraInfo)
{
INPUT down = new INPUT();
down.Type = 1;
down.Data.Keyboard = new KEYBDINPUT();
down.Data.Keyboard.Vk = (ushort) keyCode;
down.Data.Keyboard.Scan = Scan;//0
down.Data.Keyboard.Flags = Flags;//0
down.Data.Keyboard.Time = Time;//0
down.Data.Keyboard.ExtraInfo = ExtraInfo;//IntPtr.Zero
INPUT[] inputList = new INPUT[] { down };
if (SendInput(1, inputList, Marshal.SizeOf(typeof(INPUT))) == 0)
{
throw new Exception(string.Format("The key down simulation for
{0} was not successful.", keyCode));
}
}
I need to simulate keyboard press on C#, so im using SendInput function
from InputSimulator DLL (http://inputsimulator.codeplex.com/). Checking
keypressing through spy++, I saw that there is difference between real
keyboard press and sendinput.
Real keyboard press:
WM_KEYDOWN nVirtKey:VK_DOWN cRepeat:1 ScanCode:50 fExtended:1 fAltDown:0
fRepeat:0 fUp:0 wParam: 00000028 lParam: 01500001 WM_KEYUP
nVirtKey:VK_DOWN cRepeat:1 ScanCode:50 fExtended:1 fAltDown:0 fRepeat:0
fUp:1 wParam: 00000028 lParam: C1500001
SendInput:
WM_KEYDOWN nVirtKey:VK_DOWN cRepeat:1 ScanCode:50 fExtended:0 fAltDown:0
fRepeat:0 fUp:0 wParam: 00000028 lParam: 00500001 WM_KEYUP
nVirtKey:VK_DOWN cRepeat:1 ScanCode:50 fExtended:0 fAltDown:0 fRepeat:0
fUp:1 wParam: 00000028 lParam: C0500001
As you can see, there are different wParam and lParam.
This is KeyDown function, i can edit some parameters, but i dont know,
what parameter will changes wParam and lParam:
public static void SimulateKeyDown(VirtualKeyCode keyCode, ushort
Scan, uint Flags, uint Time, IntPtr ExtraInfo)
{
INPUT down = new INPUT();
down.Type = 1;
down.Data.Keyboard = new KEYBDINPUT();
down.Data.Keyboard.Vk = (ushort) keyCode;
down.Data.Keyboard.Scan = Scan;//0
down.Data.Keyboard.Flags = Flags;//0
down.Data.Keyboard.Time = Time;//0
down.Data.Keyboard.ExtraInfo = ExtraInfo;//IntPtr.Zero
INPUT[] inputList = new INPUT[] { down };
if (SendInput(1, inputList, Marshal.SizeOf(typeof(INPUT))) == 0)
{
throw new Exception(string.Format("The key down simulation for
{0} was not successful.", keyCode));
}
}
Saturday, 17 August 2013
checkbox value 0 or 1
checkbox value 0 or 1
In many cases, I have checkboxes as below
<input type="checkbox" name="custom7" value="1" id="custom7"
checked="checked"> <label for="custom7">Email me more info?</label>
Now when the checkbox is checked the value should be 1 as in value=1 . If
the checkbox is unchecked, I want the value to be zero as in value=0. How
can I do this?
In many cases, I have checkboxes as below
<input type="checkbox" name="custom7" value="1" id="custom7"
checked="checked"> <label for="custom7">Email me more info?</label>
Now when the checkbox is checked the value should be 1 as in value=1 . If
the checkbox is unchecked, I want the value to be zero as in value=0. How
can I do this?
How do I achieve this effect to my nav bar?
How do I achieve this effect to my nav bar?
I am working on a website and i want to get my site's nav bar to something
like this on a mobile phone http://imgur.com/a/cJiLO
I am working on a website and i want to get my site's nav bar to something
like this on a mobile phone http://imgur.com/a/cJiLO
THREE.js issue with intersecting objects
THREE.js issue with intersecting objects
I'm having an issue detecting object intersections with THREE.js. My
objects are being extruded from a 2D geometry like such:
var geoShape = new THREE.Shape(vertexes);
var geometry = new THREE.ExtrudeGeometry(geoShape, { bevelEnabled: false,
amount: 3 });
var mesh = THREE.SceneUtils.createMultiMaterialObject(geometry,
[new THREE.MeshLambertMaterial({ color: '#493D26' })]
);
scene.add(mesh);
I am then trying to detect intersection like this:
container.mousedown(function (e) {
event.preventDefault();
var vector = new THREE.Vector3((e.clientX / window.innerWidth) * 2 -
1, -(e.clientY / window.innerHeight) * 2 + 1, 0.5);
projector.unprojectVector(vector, camera);
var raycaster = new THREE.Raycaster(camera.position,
vector.sub(camera.position).normalize());
var intersects = raycaster.intersectObjects(scene.children);
console.log(intersects);
});
Everytime, my intersects array is empty. If I add a sphere to the scene, I
get intersections, but only if I am zoomed in to z < 18. Any suggestions?
I'm having an issue detecting object intersections with THREE.js. My
objects are being extruded from a 2D geometry like such:
var geoShape = new THREE.Shape(vertexes);
var geometry = new THREE.ExtrudeGeometry(geoShape, { bevelEnabled: false,
amount: 3 });
var mesh = THREE.SceneUtils.createMultiMaterialObject(geometry,
[new THREE.MeshLambertMaterial({ color: '#493D26' })]
);
scene.add(mesh);
I am then trying to detect intersection like this:
container.mousedown(function (e) {
event.preventDefault();
var vector = new THREE.Vector3((e.clientX / window.innerWidth) * 2 -
1, -(e.clientY / window.innerHeight) * 2 + 1, 0.5);
projector.unprojectVector(vector, camera);
var raycaster = new THREE.Raycaster(camera.position,
vector.sub(camera.position).normalize());
var intersects = raycaster.intersectObjects(scene.children);
console.log(intersects);
});
Everytime, my intersects array is empty. If I add a sphere to the scene, I
get intersections, but only if I am zoomed in to z < 18. Any suggestions?
Avoid table view didSelectRowIndexPath action while main thread is blocked
Avoid table view didSelectRowIndexPath action while main thread is blocked
I have a problem. In my app action sheet with picker opens when table's
row tapped. My problem is that action sheet dose not opens while main
thread is blocked but touch event are added in run loop therefore,
whenever main thread gets a change it completes all touches action as a
result action sheet opens according to the number of times we tapped on
table row. But I want this only once.
How to fix this problem???
I have a problem. In my app action sheet with picker opens when table's
row tapped. My problem is that action sheet dose not opens while main
thread is blocked but touch event are added in run loop therefore,
whenever main thread gets a change it completes all touches action as a
result action sheet opens according to the number of times we tapped on
table row. But I want this only once.
How to fix this problem???
Best software process tool
Best software process tool
I am software developer, who is currently making some side project, and
thinking of hiring some freelancers to help, and speed things up. (I am
server side dev, and doing everything on the front, will take considerable
time, not talking about learning spin).
In every company, that I worked, they had a different list of documents
required, but it all came down to using Word and Visio.
Since now there are so many online tools, that tend to make life easier, I
wonder, If there is a better way to build, maintain and collaborate on
your project documentation, so this would be clearer to you, and people
you work with?
I am software developer, who is currently making some side project, and
thinking of hiring some freelancers to help, and speed things up. (I am
server side dev, and doing everything on the front, will take considerable
time, not talking about learning spin).
In every company, that I worked, they had a different list of documents
required, but it all came down to using Word and Visio.
Since now there are so many online tools, that tend to make life easier, I
wonder, If there is a better way to build, maintain and collaborate on
your project documentation, so this would be clearer to you, and people
you work with?
Is it possible to formalize (higher) category theory as a one-sorted theory, just like we did with set theory?
Is it possible to formalize (higher) category theory as a one-sorted
theory, just like we did with set theory?
Set theory is typically formalized as a one-sorted theory without urelements.
Is it possible to do the same with category theory or higher category
theory, formalizing the whole affair as a theory with only one type of
object?
I know that this runs counter to what some feel is the philosophical
spirit of category theory, but I'm still curious if it's possible anyway,
just as an interesting logical puzzle.
It seems tricky to me at first glance. A "category" has a "set" of
"objects" and another set of "morphisms." That's already four sorts of
thing - category, set, object, morphism.
However, it's possible to identify an "object" with the identity morphism
on that object. So, you could perhaps use this idea to bring you down to
only three sorts of thing - category, set, and morphism.
Alternatively, you could say that "object" and "morphism" are both types
of the more fundamental n-morphism, and arrive at a three-sorted theory of
categories, sets, and n-morphisms.
You could also try to formalize a "set" as a discrete category, and bring
you down to only two sorts of thing - category and (n-)morphism.
If you go with n-morphisms, maybe you could try to identify every
n-morphism with the (n+1)-identity morphism on it, and see if that
simplifies things somehow.
The above are some ideas that I had; I'm not even sure if they'd work. But
assuming they do, that still leaves you with only two things - categories
and morphisms - and I'm not sure if it's possible to go one step further
and get it down to one thing. Thoughts?
theory, just like we did with set theory?
Set theory is typically formalized as a one-sorted theory without urelements.
Is it possible to do the same with category theory or higher category
theory, formalizing the whole affair as a theory with only one type of
object?
I know that this runs counter to what some feel is the philosophical
spirit of category theory, but I'm still curious if it's possible anyway,
just as an interesting logical puzzle.
It seems tricky to me at first glance. A "category" has a "set" of
"objects" and another set of "morphisms." That's already four sorts of
thing - category, set, object, morphism.
However, it's possible to identify an "object" with the identity morphism
on that object. So, you could perhaps use this idea to bring you down to
only three sorts of thing - category, set, and morphism.
Alternatively, you could say that "object" and "morphism" are both types
of the more fundamental n-morphism, and arrive at a three-sorted theory of
categories, sets, and n-morphisms.
You could also try to formalize a "set" as a discrete category, and bring
you down to only two sorts of thing - category and (n-)morphism.
If you go with n-morphisms, maybe you could try to identify every
n-morphism with the (n+1)-identity morphism on it, and see if that
simplifies things somehow.
The above are some ideas that I had; I'm not even sure if they'd work. But
assuming they do, that still leaves you with only two things - categories
and morphisms - and I'm not sure if it's possible to go one step further
and get it down to one thing. Thoughts?
JS: Add commas to a string
JS: Add commas to a string
I'm trying to add commas to a string and show that into label through
following function :
HTML :
<input type="text" onkeyup="addCommas(this.value);" /> <br /><br />
<label id="result">Result: </label>
JS
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
var result = x1 + x2;
document.getElementById('result').value = result;
}
JsFiddle
But won't show the result into label.
What am i doing wrong?
I'm trying to add commas to a string and show that into label through
following function :
HTML :
<input type="text" onkeyup="addCommas(this.value);" /> <br /><br />
<label id="result">Result: </label>
JS
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
var result = x1 + x2;
document.getElementById('result').value = result;
}
JsFiddle
But won't show the result into label.
What am i doing wrong?
Friday, 16 August 2013
How to disable scrolling in OSMdroid
How to disable scrolling in OSMdroid
I use OSMdroid of the version 3.0.10 in my project. And I want to disable
scrolling on MapView. I tried:
setFocusable(false)
setEnabled(false)
setClickable(false)
methods of MapView with no results. Is there any way to disable scrolling
the map?
Thank in advance.
I use OSMdroid of the version 3.0.10 in my project. And I want to disable
scrolling on MapView. I tried:
setFocusable(false)
setEnabled(false)
setClickable(false)
methods of MapView with no results. Is there any way to disable scrolling
the map?
Thank in advance.
Saturday, 10 August 2013
Multiple buttons on JList. Need to be able to handle click on one of them
Multiple buttons on JList. Need to be able to handle click on one of them
I have a JList. A class extending DefaultListCellRenderer for the JList In
this extending class there is a panel with buttons on it.
How do I handle the clicks for these buttons. They do not seem to get
clicked when I try that.
I have a JList. A class extending DefaultListCellRenderer for the JList In
this extending class there is a panel with buttons on it.
How do I handle the clicks for these buttons. They do not seem to get
clicked when I try that.
using method inside asyntask in android
using method inside asyntask in android
i have created one simple login application which takes user name and
password from sqlserver..it works fine...
i want during login process one progeress bar should be displayed using
asyntask... but i am unaware to use parameters in asyntask...if some one
plzz tell me how to put my method in doInbackground of asyntask and what
param should i use....
my code is;.....
public void save(){
initilize();
ResultSet rs = null;
String mylog=id.getText().toString();
String mypass=pass.getText().toString();
try{
Statement statement=connect.createStatement();
rs=statement.executeQuery("LOGIN '"+mylog+"', '"+mypass+"'");
}catch(Exception e){
e.printStackTrace();
}
if(mylog.equals("")||mypass.equals("")){
Toast.makeText(getApplicationContext(), "empty fields",
Toast.LENGTH_SHORT).show();
} else
try {
if(rs.next()){
Intent i=new Intent(getApplicationContext(),Act2.class);
startActivity(i);
}
else if(rs.next()==false){
Toast.makeText(getApplicationContext(), "incorrect login",
Toast.LENGTH_SHORT).show();
id.setText("");
pass.setText("");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if it is possible that same method save() be kept inside doInbackground()
of asyntask...
i have created one simple login application which takes user name and
password from sqlserver..it works fine...
i want during login process one progeress bar should be displayed using
asyntask... but i am unaware to use parameters in asyntask...if some one
plzz tell me how to put my method in doInbackground of asyntask and what
param should i use....
my code is;.....
public void save(){
initilize();
ResultSet rs = null;
String mylog=id.getText().toString();
String mypass=pass.getText().toString();
try{
Statement statement=connect.createStatement();
rs=statement.executeQuery("LOGIN '"+mylog+"', '"+mypass+"'");
}catch(Exception e){
e.printStackTrace();
}
if(mylog.equals("")||mypass.equals("")){
Toast.makeText(getApplicationContext(), "empty fields",
Toast.LENGTH_SHORT).show();
} else
try {
if(rs.next()){
Intent i=new Intent(getApplicationContext(),Act2.class);
startActivity(i);
}
else if(rs.next()==false){
Toast.makeText(getApplicationContext(), "incorrect login",
Toast.LENGTH_SHORT).show();
id.setText("");
pass.setText("");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if it is possible that same method save() be kept inside doInbackground()
of asyntask...
Friday, 9 August 2013
How to retrieve and display image base on URL and Product-ID?
How to retrieve and display image base on URL and Product-ID?
I have:
A table called Product that stored product information: PID, PName.
A table called PImage that stored the image URL of the product-ID :
ImageID, ImagePID, ImageURL.
Question: I have a form that display all products. How can i loop through
the product list, retrieve and display the image from PImage table where
the ImagePID = PID?
I have:
A table called Product that stored product information: PID, PName.
A table called PImage that stored the image URL of the product-ID :
ImageID, ImagePID, ImageURL.
Question: I have a form that display all products. How can i loop through
the product list, retrieve and display the image from PImage table where
the ImagePID = PID?
Subscribe to:
Comments (Atom)