Thursday, 3 October 2013

How to remove space before and ending of text?

How to remove space before and ending of text?

For example : I have a string like that: " Text is text ".
Now i want to use Javascript to remove all space before and ending of that
string to have result :
"Text is text".
How can I that with Javascript. Thank for your help.

Wednesday, 2 October 2013

getting checked value from checkbox thats taking data from database

getting checked value from checkbox thats taking data from database

I have problem to get to the checked value in checkbox. I have first query
that is taking names of the tables in database and second query that is
taking names of the columns of that tables. Names of the columns are
displayed in a checkbox, but i have problem to take that values from the
checkbox. I know I should use $_POST['kolona'] but somehow that variable
its not recognized:
if(mysqli_connect_errno())
{
echo "Error: Greška u konekciji";
exit;
}
$sql1 = "SHOW TABLES FROM db_baza";
$result1 = mysql_query($sql1);
if (!$result1)
{
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row1 = mysql_fetch_row($result1))
{
echo "<div id='blok'
style='width:200px;height:200px;background-color:red;margin:20px;float:left;'>{$row1[0]}"."</br>";
$tablename=$row1[0];
$sql2="SELECT column_name FROM information_schema.columns WHERE
table_name = '{$tablename}'";
$result2= mysql_query($sql2);
while($row2=mysql_fetch_row($result2))
echo "<form id='forma1' action='' method='POST'><input type='checkbox'
name='kolona[]' value='{$row2[0]}' />{$row2[0]}</br>";
echo "<input type='submit' name='submit' value='{$tablename}'/></form>";
echo "</div>";
}
if(isset($_POST['submit']))
if(isset($_POST['kolona'])
echo 1;
?>
So, I am just trying to echo number one, i will need it for other stuff
but just for the example.

Why can I not pass to_lower_copy directly to transform instead of wrapping it in a lambda?

Why can I not pass to_lower_copy directly to transform instead of wrapping
it in a lambda?

I'm trying to use boost::to_lower_copy and std::transform to lower-case a
bunch of strings. As below, Variant 1, using a lamdba works; Variant 2
also works demonstrating that that's the right template-overload the
compiler picks. But the lambda is silly – all it does is forward the
single argument along to boost::to_lower_copy. But Variant 3, using the
function template directly doesn't compile, even if I instantiate it. What
am I missing?
I have clang version 3.3 (tags/RELEASE_33/rc3), using
libstdc++-4.8.1-1.fc19.i686 and boost-1.53.0-14.fc19.i686.
vector<string> strings = {"Foo", "Bar"};
vector<string> lower_cased_strings;
transform(
strings.begin(),
strings.end(),
inserter(lower_cased_strings, lower_cased_strings.end()),
// Variant 1
// [](const string &word) {
// return boost::to_lower_copy(word);
// }
// Variant 2
// [](const string &word) {
// return boost::to_lower_copy<string>(word);
// }
// Variant 3
boost::to_lower_copy<string>
);
> clang++ -std=c++11 lowercase.cxx
In file included from lowercase.cxx:3:
In file included from /usr/include/boost/algorithm/string.hpp:18:
In file included from
/usr/include/boost/algorithm/string/std_containers_traits.hpp:23:
In file included from
/usr/include/boost/algorithm/string/std/slist_traits.hpp:16:
In file included from
/usr/lib/gcc/i686-redhat-linux/4.8.1/../../../../include/c++/4.8.1/ext/slist:47:
In file included from
/usr/lib/gcc/i686-redhat-linux/4.8.1/../../../../include/c++/4.8.1/algorithm:62:
/usr/lib/gcc/i686-redhat-linux/4.8.1/../../../../include/c++/4.8.1/bits/stl_algo.h:4949:33:
error: too few arguments to function call, expected 2, have 1
*__result = __unary_op(*__first);
~~~~~~~~~~ ^
lowercase.cxx:11:5: note: in instantiation of function template
specialization
'std::transform<__gnu_cxx::__normal_iterator<std::basic_string<char> *,
std::vector<std::basic_string<char>,
std::allocator<std::basic_string<char> > > >,
std::insert_iterator<std::vector<std::basic_string<char>,
std::allocator<std::basic_string<char> > > >, std::basic_string<char>
(*)(const std::basic_string<char>
&, const std::locale &)>' requested here
transform(
^

How to find difference between two columns data?

How to find difference between two columns data?

I have a temp table with two columns of integer data i want to find the
difference between two columns in 3rd column.
#TEMP1
Present previous
59 88
75 75
45 45
77 88
09 08
#temp2
Difference
29
0
0
11
-1
Is this possible ??

working with object in C#

working with object in C#

consider the variable ob4 as shown in figure
now : how can i reach ob4[0]->[0,2]
var o=ob4[0];
double[,] p=(double[,]) o[0,0];
the line (double[,] p=(double[,]) o[0,0];) gives the following error :
Cannot apply indexing with [] to an expression of type 'object'

Tuesday, 1 October 2013

Where is disk buffer cache situated

Where is disk buffer cache situated

I have read that The buffer cache interfaces with block devices, and
caches recently used meta-data disk blocks. The Linux kernel reads file
data through the buffer cache, but keeps the data in the page cache for
reuse on future reads.
I know that page cache is situated at main memory. Whether its true with
buffer cache also?
If buffer cache is in main memory, how access is made to it. Whether any
mechanism like paging is used for accessing buffer cache?

assign list of parent class reference with list of child class object does not work C#

assign list of parent class reference with list of child class object does
not work C#

I am new to C#. I have a parent class declared:
class PmdTable
{
}
and I have a child class
class PmdSdStageCfg : PmdTable
{
Now it complains if I do like:
List<OracleObject.PmdTable> instanceList = new List<PmdSdStageCfg>();
The error says"Cannot implicityly convert type
'System.Collections.Generic.List' to 'System.Collection.Generics.List'".
Since PmdTable is the parent class. Why this does not work?

How do I enable SR-IOV for Mellanox ConnectX-3 Ubuntu 12.04.3?

How do I enable SR-IOV for Mellanox ConnectX-3 Ubuntu 12.04.3?

I have a Supermicro 2027TR-HTFRF server that I'm using as a xen server.
What I'm wanting to do is get SR-IOV operating for the Connectx-3 card so
that I can expose Infiniband to virtual machines.
Following this recipe I managed to get the I350 Ethernet to expose the VF's.
Adding /etc/modprobe.d/mlx4_core.conf containing
options max_vfs=4
Didn't create the virtual functions for the mellanox device despite the
fact that this is a valid parameter to the mlx4_core module. i.e.
The error I get is
mlx4_core: `4' invalid for parameter `max_vfs'
I also tried a value of 1 to which I got a similar error
mlx4_core: `1' invalid for parameter `max_vfs'
Output from lspci -v
06:00.0 Network controller: Mellanox Technologies MT27500 Family [ConnectX-3]
Subsystem: Mellanox Technologies Device 0051
Flags: bus master, fast devsel, latency 0, IRQ 11
Memory at df900000 (64-bit, non-prefetchable) [size=1M]
Memory at de000000 (64-bit, prefetchable) [size=8M]
Capabilities: [40] Power Management version 3
Capabilities: [48] Vital Product Data
Capabilities: [9c] MSI-X: Enable- Count=128 Masked-
Capabilities: [60] Express Endpoint, MSI 00
Capabilities: [100] Alternative Routing-ID Interpretation (ARI)
Capabilities: [148] Device Serial Number 00-25-90-ff-ff-17-57-24
Capabilities: [18c] #19
Kernel modules: mlx4_core
So it would seem that SR-IOV is not available.
I then discovered this thread: http://community.mellanox.com/thread/1073
But I'm using ubuntu 12.04.
Next I installed mstflint using apt-get.
Then I identified what type of card it is.
mstflint -d 06:00.0 q
Unfortunately mstflint crashes.
Warning: memory access to device 06:00.0 failed: Input/output error.
Warning: Fallback on IO: much slower, and unsafe if device in use.
*** buffer overflow detected ***: mstflint terminated
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(__fortify_fail+0x37)[0x7f66d91ac817]
Some of the strace output:
strace mstflint -d 06:00.0 q
...
open("/proc/bus/pci/06/00.0", O_RDWR|O_DSYNC) = 3
ioctl(3, IIOCNETDIF, 0xdf900000) = 0
mmap(NULL, 1048576, PROT_READ|PROT_WRITE, MAP_SHARED, 3, 0xdf900000) =
0x7f0e0a200000
munmap(0x7f0e0a200000, 65536) = 0
close(3) = 0
open("/dev/mem", O_RDWR|O_DSYNC) = 3
mmap(NULL, 1048576, PROT_READ|PROT_WRITE, MAP_SHARED, 3, 0xdf900000) =
0x7f0e092f2000
munmap(0x7f0e092f2000, 65536) = 0
close(3) = 0
write(2, "Warning: memory access to device"..., 136Warning: memory access
to device 06:00.0 failed: Input/output error.
Warning: Fallback on IO: much slower, and unsafe if device in use.
) = 136
open("/sys/bus/pci/devices/0000:06:00.0/config", O_RDWR|O_DSYNC) = 3
pwrite(3, "\375\374\373\372", 4, 88) = 4
pread(3, "\375\374\373\372", 4, 88) = 4
close(3) = 0
open("/dev/tty", O_RDWR|O_NOCTTY|O_NONBLOCK) = 3
writev(3, [{"*** ", 4}, {"buffer overflow detected", 24}, {" ***: ", 6},
{"mstflint", 8}, {" terminated\n", 12}], 5*** buffer overflow detected
***: mstflint terminated
) = 54
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) =
0x7f0e0a3f9000
write(3, "======= Backtrace: =========\n", 29======= Backtrace: =========
) = 29
writev(3, [{"/lib/x86_64-linux-gnu/libc.so.6", 31}, {"(", 1},
{"__fortify_fail", 14}, {"+0x", 3}, {"37", 2}, {")", 1}, {"[0x", 3},
{"7f0e094fc817", 12}, {"]\n", 2}],
9/lib/x86_64-linux-gnu/libc.so.6(__fortify_fail+0x37)[0x7f0e094fc817]
) = 69
writev(3, [{"/lib/x86_64-linux-gnu/libc.so.6", 31}, {"(", 1}, {"+0x", 3},
{"109710", 6}, {")", 1}, {"[0x", 3}, {"7f0e094fb710", 12}, {"]\n", 2}],
8/lib/x86_64-linux-gnu/libc.so.6(+0x109710)[0x7f0e094fb710]
) = 59
writev(3, [{"/lib/x86_64-linux-gnu/libc.so.6", 31}, {"(", 1}, {"+0x", 3},
{"108b79", 6}, {")", 1}, {"[0x", 3}, {"7f0e094fab79", 12}, {"]\n", 2}],
8/lib/x86_64-linux-gnu/libc.so.6(+0x108b79)[0x7f0e094fab79]
) = 59
writev(3, [{"/lib/x86_64-linux-gnu/libc.so.6", 31}, {"(", 1},
{"_IO_default_xsputn", 18}, {"+0x", 3}, {"dd", 2}, {")", 1}, {"[0x", 3},
{"7f0e0946e13d", 12}, {"]\n", 2}],
9/lib/x86_64-linux-gnu/libc.so.6(_IO_default_xsputn+0xdd)[0x7f0e0946e13d]
) = 73
writev(3, [{"/lib/x86_64-linux-gnu/libc.so.6", 31}, {"(", 1},
{"_IO_vfprintf", 12}, {"+0x", 3}, {"1ae7", 4}, {")", 1}, {"[0x", 3},
{"7f0e0943c4a7", 12}, {"]\n", 2}],
9/lib/x86_64-linux-gnu/libc.so.6(_IO_vfprintf+0x1ae7)[0x7f0e0943c4a7]
) = 69
writev(3, [{"/lib/x86_64-linux-gnu/libc.so.6", 31}, {"(", 1},
{"__vsprintf_chk", 14}, {"+0x", 3}, {"94", 2}, {")", 1}, {"[0x", 3},
{"7f0e094fac14", 12}, {"]\n", 2}],
9/lib/x86_64-linux-gnu/libc.so.6(__vsprintf_chk+0x94)[0x7f0e094fac14]
) = 69
writev(3, [{"/lib/x86_64-linux-gnu/libc.so.6", 31}, {"(", 1},
{"__sprintf_chk", 13}, {"+0x", 3}, {"7d", 2}, {")", 1}, {"[0x", 3},
{"7f0e094fab5d", 12}, {"]\n", 2}],
9/lib/x86_64-linux-gnu/libc.so.6(__sprintf_chk+0x7d)[0x7f0e094fab5d]
) = 68
writev(3, [{"mstflint", 8}, {"[0x", 3}, {"40de46", 6}, {"]\n", 2}],
4mstflint[0x40de46]
) = 19
writev(3, [{"mstflint", 8}, {"[0x", 3}, {"40ee56", 6}, {"]\n", 2}],
4mstflint[0x40ee56]
) = 19
writev(3, [{"mstflint", 8}, {"[0x", 3}, {"406475", 6}, {"]\n", 2}],
4mstflint[0x406475]
) = 19
writev(3, [{"mstflint", 8}, {"[0x", 3}, {"408d00", 6}, {"]\n", 2}],
4mstflint[0x408d00]
) = 19
writev(3, [{"/lib/x86_64-linux-gnu/libc.so.6", 31}, {"(", 1},
{"__libc_start_main", 17}, {"+0x", 3}, {"ed", 2}, {")", 1}, {"[0x", 3},
{"7f0e0941376d", 12}, {"]\n", 2}],
9/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x7f0e0941376d]
) = 72
writev(3, [{"mstflint", 8}, {"[0x", 3}, {"401af9", 6}, {"]\n", 2}],
4mstflint[0x401af9]
) = 19
write(3, "======= Memory map: ========\n", 29======= Memory map: ========
) = 29
open("/proc/self/maps", O_RDONLY) = 4
read(4, "00400000-0041a000 r-xp 00000000 "..., 1024) = 1024
write(3, "00400000-0041a000 r-xp 00000000 "..., 102400400000-0041a000 r-xp
00000000 08:01 220 /usr/bin/mstflint
00619000-0061a000 r--p 00019000 08:01 220
/usr/bin/mstflint
0061a000-0061b000 rw-p 0001a000 08:01 220
/usr/bin/mstflint
024a3000-024c4000 rw-p 00000000 00:00 0
[heap]
7f0e09302000-7f0e093f2000 rw-s df910000 00:05 1028
/dev/mem
7f0e093f2000-7f0e095a7000 r-xp 00000000 08:01 135350
/lib/x86_64-linux-gnu/libc-2.15.so
7f0e095a7000-7f0e097a6000 ---p 001b5000 08:01 135350
/lib/x86_64-linux-gnu/libc-2.15.so
7f0e097a6000-7f0e097aa000 r--p 001b4000 08:01 135350
/lib/x86_64-linux-gnu/libc-2.15.so
7f0e097aa000-7f0e097ac000 rw-p 001b8000 08:01 135350
/lib/x86_64-linux-gnu/libc-2.15.so
7f0e097ac000-7f0e097b1000 rw-p 00000000 00:00 0
7f0e097b1000-7f0e097c6000 r-xp 00000000 08:01 131116
/lib/x86_64-linux-gnu/libgcc_s.so.1) = 1024
read(4, "\n7f0e097c6000-7f0e099c5000 ---p "..., 1024) = 1024
write(3, "\n7f0e097c6000-7f0e099c5000 ---p "..., 1024
7f0e097c6000-7f0e099c5000 ---p 00015000 08:01 131116
/lib/x86_64-linux-gnu/libgcc_s.so.1
7f0e099c5000-7f0e099c6000 r--p 00014000 08:01 131116
/lib/x86_64-linux-gnu/libgcc_s.so.1
7f0e099c6000-7f0e099c7000 rw-p 00015000 08:01 131116
/lib/x86_64-linux-gnu/libgcc_s.so.1
7f0e099c7000-7f0e09ac2000 r-xp 00000000 08:01 135361
/lib/x86_64-linux-gnu/libm-2.15.so
7f0e09ac2000-7f0e09cc1000 ---p 000fb000 08:01 135361
/lib/x86_64-linux-gnu/libm-2.15.so
7f0e09cc1000-7f0e09cc2000 r--p 000fa000 08:01 135361
/lib/x86_64-linux-gnu/libm-2.15.so
7f0e09cc2000-7f0e09cc3000 rw-p 000fb000 08:01 135361
/lib/x86_64-linux-gnu/libm-2.15.so
7f0e09cc3000-7f0e09da5000 r-xp 00000000 08:01 30579
/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.16
7f0e09da5000-7f0e09fa4000 ---p 000e2000 08:01 30579
/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.16
7f0e09fa4000-7f0e09fac000 ) = 1024
read(4, "r--p 000e1000 08:01 30579 "..., 1024) = 1024
write(3, "r--p 000e1000 08:01 30579 "..., 1024r--p 000e1000 08:01
30579 /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.16
7f0e09fac000-7f0e09fae000 rw-p 000e9000 08:01 30579
/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.16
7f0e09fae000-7f0e09fc3000 rw-p 00000000 00:00 0
7f0e09fc3000-7f0e09fd9000 r-xp 00000000 08:01 131300
/lib/x86_64-linux-gnu/libz.so.1.2.3.4
7f0e09fd9000-7f0e0a1d8000 ---p 00016000 08:01 131300
/lib/x86_64-linux-gnu/libz.so.1.2.3.4
7f0e0a1d8000-7f0e0a1d9000 r--p 00015000 08:01 131300
/lib/x86_64-linux-gnu/libz.so.1.2.3.4
7f0e0a1d9000-7f0e0a1da000 rw-p 00016000 08:01 131300
/lib/x86_64-linux-gnu/libz.so.1.2.3.4
7f0e0a1da000-7f0e0a1fc000 r-xp 00000000 08:01 135367
/lib/x86_64-linux-gnu/ld-2.15.so
7f0e0a210000-7f0e0a300000 rw-s df910000 00:03 4026533088
/proc/bus/pci/06/00.0
7f0e0a300000-7f0e0a3f0000 rw-s df910000 00:0e 19851
/sys/devices/pci0000:00/0000:00:03.2/0000:06:) = 1024
read(4, "00.0/resource0\n7f0e0a3f0000-7f0e"..., 1024) = 570
write(3, "00.0/resource0\n7f0e0a3f0000-7f0e"..., 57000.0/resource0
7f0e0a3f0000-7f0e0a3f5000 rw-p 00000000 00:00 0
7f0e0a3f9000-7f0e0a3fc000 rw-p 00000000 00:00 0
7f0e0a3fc000-7f0e0a3fd000 r--p 00022000 08:01 135367
/lib/x86_64-linux-gnu/ld-2.15.so
7f0e0a3fd000-7f0e0a3ff000 rw-p 00023000 08:01 135367
/lib/x86_64-linux-gnu/ld-2.15.so
7fffdd53f000-7fffdd560000 rw-p 00000000 00:00 0
[stack]
7fffdd5ff000-7fffdd600000 r-xp 00000000 00:00 0
[vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0
[vsyscall]
) = 570
read(4, "", 1024) = 0
close(4) = 0
rt_sigprocmask(SIG_UNBLOCK, [ABRT], NULL, 8) = 0
gettid() = 4122
tgkill(4122, 4122, SIGABRT) = 0
--- SIGABRT (Aborted) @ 0 (0) ---
+++ killed by SIGABRT (core dumped) +++
Aborted (core dumped)
At this point I'm somewhat stuck.



Update: I managed to obtain a firmware update from SuperMicro which has
SR-IOV enabled.
Also I needed to set options max_vfs= to options num_vfs=. It seems the
named parameter is slightly different. This was enough to get it working
under Ubuntu.
Installing the firmware I used this method: http://www.panticz.de/mellanox
But with the addition that I had to call insmod on each module before
calling mst start. Modprobe didn't work.

what is dconf and gvfs folders?

what is dconf and gvfs folders?

I recently installed samba but now I see the following files off my home
directory that are permissioned by root. Both folders are empty. Can I
remove them? I am not sure if this is related or not to samba or whether
it is safe to nix these.
find: `./.cache/dconf': Permission denied
find: `./.gvfs': Permission denied

Monday, 30 September 2013

Pipe output of grep to a variable – apple.stackexchange.com

Pipe output of grep to a variable – apple.stackexchange.com

I need to be able to write whether the test for a grep is either TRUE or
FALSE to a variable so I can use it later For the following, if I run
defaults read com.apple.Finder | grep ...

Points and Coordinates

Points and Coordinates

If $P$ is $(1,2,-2)$, find vector $P$ (from the origin) and the angles
which vector $P$ makes with the coordinate axes $x, y,$ and $z$.

Error creating bean with name 'org.springframework.security.filterChains' Spring + Hibernate + UserDetailService

Error creating bean with name 'org.springframework.security.filterChains'
Spring + Hibernate + UserDetailService

I just started to learn Spring Security and have some trouble. I want to
configure User login on page with password and username which stored in
database during registration. I use Hibernate.
My error stack:
INFO : org.springframework.web.context.ContextLoader - Root
WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext -
Refreshing Root WebApplicationContext: startup date [Mon Sep 30 16:16:07
EDT 2013]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader -
Loading XML bean definitions from ServletContext resource
[/WEB-INF/spring/spring-context.xml]
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader -
Loading XML bean definitions from ServletContext resource
[/WEB-INF/spring/root-context.xml]
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader -
Loading XML bean definitions from ServletContext resource
[/WEB-INF/spring/security-context.xml]
INFO :
org.springframework.beans.factory.support.DefaultListableBeanFactory -
Overriding bean definition for bean 'guestBookDAOImpl': replacing [Generic
bean: class [demidov.pkg.persistence.GuestBookDAOImpl]; scope=;
abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0;
autowireCandidate=true; primary=false; factoryBeanName=null;
factoryMethodName=null; initMethodName=null; destroyMethodName=null;
defined in ServletContext resource [/WEB-INF/spring/spring-context.xml]]
with [Generic bean: class [demidov.pkg.persistence.GuestBookDAOImpl];
scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0;
autowireCandidate=true; primary=false; factoryBeanName=null;
factoryMethodName=null; initMethodName=null; destroyMethodName=null;
defined in ServletContext resource [/WEB-INF/spring/security-context.xml]]
INFO :
org.springframework.beans.factory.support.DefaultListableBeanFactory -
Pre-instantiating singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory@11dab12:
defining beans
[dataSource,sessionFactory,guestBookDAOImpl,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,org.springframework.security.filterChains,org.springframework.security.filterChainProxy,org.springframework.security.web.DefaultSecurityFilterChain#0,org.springframework.security.web.DefaultSecurityFilterChain#1,org.springframework.security.web.PortMapperImpl#0,org.springframework.security.web.PortResolverImpl#0,org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0,org.springframework.security.authentication.ProviderManager#0,org.springframework.security.web.context.HttpSessionSecurityContextRepository#0,org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy#0,org.springframework.
security.web.savedrequest.HttpSessionRequestCache#0,org.springframework.security.access.vote.AffirmativeBased#0,org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0,org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator#0,org.springframework.security.authentication.AnonymousAuthenticationProvider#0,org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint#0,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0,org.springframework.security.userDetailsServiceFactory,org.springframework.security.web.DefaultSecurityFilterChain#2,org.springframework.security.authentication.dao.DaoAuthenticationProvider#0,org.springframework.security.authentication.DefaultAuthenticationEventPublisher#0,org.springframework.security.authenticationManager];
root of factory hierarchy
WARN : org.hibernate.internal.util.xml.DTDEntityResolver - HHH000223:
Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/.
Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate
3.6 Migration Guide!
WARN : org.hibernate.internal.util.xml.DTDEntityResolver - HHH000223:
Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/.
Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate
3.6 Migration Guide!
ERROR: org.hibernate.tool.hbm2ddl.SchemaUpdate - HHH000388: Unsuccessful:
create table USER_DESC (ID bigint not null auto_increment, USER_NAME
varchar(255), USER_PASS varchar(255), USER_PRIV varchar(255) default
ROLE_USER, USER_EMALE varchar(255), USER_GENDER varchar(255), primary key
(ID))
ERROR: org.hibernate.tool.hbm2ddl.SchemaUpdate - You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near 'ROLE_USER, USER_EMALE varchar(255),
USER_GENDER varchar(255), primary key (ID))' at line 1
INFO :
org.springframework.beans.factory.support.DefaultListableBeanFactory -
Destroying singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory@11dab12:
defining beans
[dataSource,sessionFactory,guestBookDAOImpl,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,transactionManager,org.springframework.security.filterChains,org.springframework.security.filterChainProxy,org.springframework.security.web.DefaultSecurityFilterChain#0,org.springframework.security.web.DefaultSecurityFilterChain#1,org.springframework.security.web.PortMapperImpl#0,org.springframework.security.web.PortResolverImpl#0,org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0,org.springframework.security.authentication.ProviderManager#0,org.springframework.security.web.context.HttpSessionSecurityContextRepository#0,org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy#0,org.springframework.
security.web.savedrequest.HttpSessionRequestCache#0,org.springframework.security.access.vote.AffirmativeBased#0,org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0,org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator#0,org.springframework.security.authentication.AnonymousAuthenticationProvider#0,org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint#0,org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0,org.springframework.security.userDetailsServiceFactory,org.springframework.security.web.DefaultSecurityFilterChain#2,org.springframework.security.authentication.dao.DaoAuthenticationProvider#0,org.springframework.security.authentication.DefaultAuthenticationEventPublisher#0,org.springframework.security.authenticationManager];
root of factory hierarchy
ERROR: org.springframework.web.context.ContextLoader - Context
initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'org.springframework.security.filterChains': Cannot resolve
reference to bean
'org.springframework.security.web.DefaultSecurityFilterChain#2' while
setting bean property 'sourceList' with key [2]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.DefaultSecurityFilterChain#2': Cannot
resolve reference to bean
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0'
while setting constructor argument with key [10]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1387)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1128)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:610)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at
org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at
org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at
org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4701)
at
org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204)
at
org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
'org.springframework.security.web.DefaultSecurityFilterChain#2': Cannot
resolve reference to bean
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0'
while setting constructor argument with key [10]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154)
at
org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:615)
at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:148)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1045)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:949)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
... 38 more
Caused by: java.lang.IllegalArgumentException: Unsupported configuration
attributes: [hasRole('ROLE_USER')]
at
org.springframework.security.access.intercept.AbstractSecurityInterceptor.afterPropertiesSet(AbstractSecurityInterceptor.java:156)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479)
... 45 more
Sep 30, 2013 4:16:09 PM org.apache.catalina.core.StandardContext
listenerStart
SEVERE: Exception sending context initialized event to listener instance
of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name 'org.springframework.security.filterChains': Cannot resolve
reference to bean
'org.springframework.security.web.DefaultSecurityFilterChain#2' while
setting bean property 'sourceList' with key [2]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.DefaultSecurityFilterChain#2': Cannot
resolve reference to bean
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0'
while setting constructor argument with key [10]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1387)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1128)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:610)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at
org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at
org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at
org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4701)
at
org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204)
at
org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
'org.springframework.security.web.DefaultSecurityFilterChain#2': Cannot
resolve reference to bean
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0'
while setting constructor argument with key [10]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating
bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:353)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:154)
at
org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:615)
at
org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:148)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1045)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:949)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name
'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0':
Invocation of init method failed; nested exception is
java.lang.IllegalArgumentException: Unsupported configuration attributes:
[hasRole('ROLE_USER')]
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at
org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
... 38 more
Caused by: java.lang.IllegalArgumentException: Unsupported configuration
attributes: [hasRole('ROLE_USER')]
at
org.springframework.security.access.intercept.AbstractSecurityInterceptor.afterPropertiesSet(AbstractSecurityInterceptor.java:156)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479)
... 45 more
I can not get access any jsp pages after I add Spring Security.
My spring-context.xml
<security:http pattern="/guestbook" security="none" />
<security:http pattern="/regestration" security="none" />
<security:http auto-config="true">
<security:intercept-url pattern="/user/*"
access="hasRole('ROLE_USER')"/>
</security:http>
<security:authentication-manager>
<security:authentication-provider
user-service-ref="guestBookDAOImpl"/>
</security:authentication-manager>
<bean id="guestBookDAOImpl"
class="demidov.pkg.persistence.GuestBookDAOImpl"/>
My dao impl implemented with UserDetailsService from Spring Security:
@Transactional
public class GuestBookDAOImpl implements GuestBookDAOIF, UserDetailsService {
public SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@SuppressWarnings("unchecked")
@Override
public User fetchAllUsers(String userName) {
return(User)sessionFactory.getCurrentSession().createQuery("select
user from User user where user.userName=:name")
.setParameter("name",
userName)
.uniqueResult();
}
@Override
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException {
org.springframework.security.core.userdetails.User user;
Set<GrantedAuthority> userroles = new HashSet<GrantedAuthority>();
User myuser = fetchAllUsers(userName);
userroles.add(myuser);
user = new
org.springframework.security.core.userdetails.User(myuser.getUserName(),
myuser.getUserPassword(), true, true, true, true, userroles);
return user;
}
My User entity:
public class User implements Serializable, GrantedAuthority {
private static final long serialVersionUID = -1576600424405883465L;
private long userId;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
private String userPassword;
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
private String userRole;
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
private String userEmale;
public String getUserEmale() {
return userEmale;
}
public void setUserEmale(String userEmale) {
this.userEmale = userEmale;
}
private String userGender;
public String getUserGender() {
return userGender;
}
public void setUserGender(String userGender) {
this.userGender = userGender;
}
private Set<UserMessage> userMessageList = new HashSet<UserMessage>();
public Set<UserMessage> getUserMessageList() {
return userMessageList;
}
public void setUserMessageList(Set<UserMessage> userMessageList) {
this.userMessageList = userMessageList;
}
@Override
public String getAuthority() {
return getUserRole();
}
}
Hibernate mapping xml fro user entity:
<hibernate-mapping>
<class name="demidov.pkg.domain.User" table="USER_DESC">
<!-- Primary key ID will be generated depends on database
configuration -->
<id name="userId" column="ID">
<generator class="native"></generator>
</id>
<property name="userName" column="USER_NAME" unique="true" />
<property name="userPassword" column="USER_PASS"/>
<property name="userRole" >
<column name="USER_PRIV" default="ROLE_USER"/>
</property>
<property name="userEmale" column="USER_EMALE" unique="true"/>
<property name="userGender" column="USER_GENDER" />
<!-- User is owner of relationships, all changes on user will
effect UserMessage entity -->
<set name="userMessageList" inverse="true" lazy="false"
fetch="select" cascade="all">
<key>
<column name="USER_ID" not-null="true"/>
</key>
<one-to-many class="demidov.pkg.domain.UserMessage" />
</set>
</class>
</hibernate-mapping>
Please help me. I'm confused what is what: GrantedAuthority, UserDetails,
User and how they work with xml configuration of Spring Security.
Thanks.

how can i retrieve same column with two different alias?

how can i retrieve same column with two different alias?

I have one table called 'answers' with four column wherein adding answers
with positive and negative rankings and i want to retrieve answer with
different aliasing for answer with positive ranks and answer with negative
ranks. is there any way to retrieve same column with two different aliases
?
id answer rank question_id
1 Yes 1 1
2 No 2 1
3 True -2 2
4 False -1 2

Sunday, 29 September 2013

captureScreenshotOnFailure not working, broken

captureScreenshotOnFailure not working, broken

I can't get these screenshots working for the life of me:
The directories exist
The test executes (and fails) as expected
I've read everything I can find:
http://www.devinzuczek.com/2011/08/taking-a-screenshot-with-phpunit-and-selenium-rc/
PHPUnit Selenium captureScreenshotOnFailure does not work?
lots of others
Should be pretty simple, but there's no error messages, nothing. Can
anyone shed some light?
class ScreenshotTest extends PHPUnit_Extensions_Selenium2TestCase {
protected $captureScreenshotOnFailure = TRUE;
protected $screenshotPath = 'C:\\';
protected $screenshotUrl = 'http://127.0.0.1/';
protected function setUp()
{
$this->setBrowser('firefox');
$this->setBrowserUrl('http://127.0.0.1/');
}
public function testTitle()
{
$this->url('http://127.0.0.1');
$this->assertEquals('foobarbaz', $this->title());
} }

MVVM Light Portable Class Library Navigation

MVVM Light Portable Class Library Navigation

I am making a Windows Phone 8 app using the MVVM architecture and a
portable class library. I am currently using MVVM light messages to
navigate to a new page. Is there a different approach that I can use
instead of messages because I always have to put code in the code behind.

knockout "with" binding: each property to multiple controls

knockout "with" binding: each property to multiple controls

Within "with" binding div, I tried to bind 5 properties of a model to 2
different types of controls, namely textbox and label. However, only the
first property on the list is bound to two controls, the rest are only
bound to textbox:
<div data-bind="with: Object">
<input type= "text" data-bind="value: property1" /> <br />
<input type= "text" data-bind="value: property2" /> <br />
<input type= "text" data-bind="value: property3" /> <br />
<input type= "text" data-bind="value: property4" /> <br />
<input type= "text" data-bind="value: property5" /> <br />
<label data-bind="value: property1" /> <br />
<label data-bind="value: property2" /> <br />
<label data-bind="value: property3" /> <br />
<label data-bind="value: property4" /> <br />
<label data-bind="value: property5" /> <br />
</div>
Object is populated dynamically, meaning its properties are assigned
dynamically. In my view model, I have Object = ko.observable() . And once
user clicked some button, I have Object(createModel1()) executed, where
createModel1 returns a new Model1. Model1 has properties defined as
ko.observable.
I don't know whether this is not supposed to work or am I doing something
else wrong (barking at the wrong tree) Please help! Thank you!!!

SQL Select data if only data exist

SQL Select data if only data exist

I created a register form and logging form with html, and I created a
database for it, but when I insert invalid data (data that doesn't exist
in database) to the logging form, It doesn't show an error, I want an
error msg when I insert invalid data (data that doesn't exist in
database), how i do it?

Saturday, 28 September 2013

Having trouble with linked list functions

Having trouble with linked list functions

I'm having trouble using a member function of a pointer to a video object.
My code is as follows:
vlist.h:
5 #ifndef VLIST_H
6 #define VLIST_H
7
8 #include<iostream>
9 using namespace std;
10
11 #include<string>
12 #include"video.h"
13
14 class Vlist
15 {
16 public:
17 Vlist();
18 // ~Vlist();
19 void insert(Video *vid);
20 // void insert_alphabetical(Video *vid);
21 void print();
22 // void length();
23 bool lookup(string title);
24 bool remove(string title);
25 private:
26 class Node
27 {
28 public:
29 Node(Video *vid, Node *next)
30 {m_vid = vid; m_next = next;}
31 Video *m_vid;
32 Node *m_next;
33 };
34 Node *m_head;
35 };
36
37

form variables not passing to php

form variables not passing to php

I'm using php version 5.5.1 and Apache server if this information helps I
have a simple form and I'm trying to pass the form variable to php and
output the value. I am a beginner in php so please excuse me if this is
something obvious, I have tried to solve this myself with the almighty
google but wasn't successful. The html form code is as follows
<html>
<head>
<title>Form</title>
</head>
<body>
<form method="post" action="test1.php">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
Then the php to handle the form is:
<html>
<head>
<title>Form</title>
</head>
<body>
<?php
echo "<h1>Hello " . $_POST["username"] . "</h1>";
?>
</body>
</html>
The output I'm getting no matter what I type into the html form is , Hello
" . $_POST["username"] . ""; ?>
I don't know why it also outputs the ending semi colon and ending php tag
also, maybe this is evidence of what's going wrong here?
Any and all help is appreciated! Thank You.

How do I make an emualator for a certain device?

How do I make an emualator for a certain device?

So I'm trying to make a new emulator in "Virtual Devcice Manager" in
Eclipse. I want it to be the same as a certain device (same screen size,
same android version installed as it is by default on that device etc.).
The device I'm trying to "re-create" as an emulator is Sony Xperia Z. I
searched for the phone's specs and this is what I found:
Android 4.1
12.7cm (5") screen
I then tried to create a new virtual device in eclipse and I don't have
any of these options. The closest Android version that Eclipse lets you
use for Virtual device is 4.1.2 and the closest screen size is 5.1" WVGA
If I created a virtual device like this, would it be good? Would an
application that I ran on this virtual device behave the exact same way as
on actual Sony Xperia Z?

In R, how to add the fitted value column to the original dataframe?

In R, how to add the fitted value column to the original dataframe?

I got a multiple regression model. And I want to add the fitted values and
residuals to the original dataframe as a two new column, how can I achieve
that? Thanks in advance.

Friday, 27 September 2013

File Encoding Format : ANSI_134_1968 and UTF : 8 Diffrence?

File Encoding Format : ANSI_134_1968 and UTF : 8 Diffrence?

i would like to know what is diffrence between File Encoding Format :
ANSI_134_1968 and UTF : 8.
please let me know your suggection's
thank you.
tousif shaikh

Incorrect Casting

Incorrect Casting

For some reason I am getting a precision error when I try to compile my
code. The precision error comes in the return of my second method where I
am trying to calculate the circumference. What am I doing incorrectly?
public class Methods2
{
public static final double PI = 3.14;
public static double calcCirc(double x)
{
return PI*x;
}
public static int calcCirc(int x)
{
return (2*(double) x)*PI;
}
public static void main(String[]args)
{
System.out.println(calcCirc(10.2));
System.out.println(calcCirc(4));
}
}

Ajax call returns data with "/n" tags

Ajax call returns data with "/n" tags

Hey All I've been searching around for awhile and haven't much luck
finding the reasoning behind this so hopefully somebody can help me. I
don't understand why it is returning newline characters
$('#tbl tr td').click(function () {
// Here selection =" 710-610A " spaces are included
var selection = $(this).text();
alert(selection)
$.ajax({
type: "Post",
url: "/Home/Index/",
dataType: "json",
data: { grpCode: selection },
success: function (ResponseData) {},
error: function (errorResponse) {
alert('AJAX Call Failed');
}
// When passed grpCode = "\n 710-610A\n "
I dnt understand why theres so many spaces along with it
[HttpPost]
public ActionResult Index(string grpCode)
{
// do something
}
I'm thinking it has something to do with the way I'm displaying my table
in the View
<table id="tbl">
<tr>
<th>
Groups
</th>
</tr>
@foreach (var item in Model.groupCodesList.Select(m=>
m.Group_Code).Distinct())
{
<tr>
<td>
@item
</td>
</tr>
}
</table>
I am using EF Code First to retrieve Data

Precision timing using DateTime possible?

Precision timing using DateTime possible?

I would like to test the time required by certain methods and SQL queries
in my code. I've tried doing the following:
DateTime start = DateTime.Now;
//Do something
DateTime end = DateTime.Now;
TimeSpan ts = end - start;
int millis = ts.Milliseconds;
But I just don't feel that this is the right way of doing it. I often get
back a value of 1 for some methods and values like 200 for others, are
there any accurate ways to measure and record this kind of thing?

How to restrict foreign keys in Rails' update controller action?

How to restrict foreign keys in Rails' update controller action?

In my Rails app I have invoices which in turn can have many projects.
model:
class Invoice < ActiveRecord::Base
attr_accessible :project_id
end
controller:
class InvoicesController < ApplicationController
before_filter :authorized_user, :only => [ :show, :edit, :destroy ]
before_filter :authorized_project, :only => [ :create, :update ]
def create # safe
@invoice = @project.invoices.build(params[:invoice])
if @invoice.save
flash[:success] = "Invoice saved."
redirect_to edit_invoice_path(@invoice)
else
render :new
end
end
def update # not safe yet
if @invoice.update_attributes(params[:invoice])
flash[:success] = "Invoice updated."
redirect_to edit_invoice_path(@invoice)
else
render :edit
end
end
private
def authorized_user
@invoice = Invoice.find(params[:id])
redirect_to root_path unless current_user?(@invoice.user)
end
def authorized_project
@project = Project.find(params[:invoice][:project_id])
redirect_to root_path unless current_user?(@project.user)
end
end
My biggest concern is that a malicious user might, one day, create an
invoice that belongs to the project of another user.
Now thanks to the help of some people on this board I managed to come up
with a before_filter that makes sure that this won't happen when a project
is created.
The problem is I don't understand how to apply this filter to the update
action as well.
Since the update action does not make use of Rails' build function, I
simply don't know how to get my @project in there.
Can anybody help?

Resizing Bitmap to fit other Bitmap

Resizing Bitmap to fit other Bitmap

I have problem with displaying bitmaps. I have bitmap (maker) that is
loaded from resource and placed on the map and i download bitmap (avatar)
from the server with specific dimensions and I place the avatar in the
center of the marker. The result is that on one phone every thing works
fine but on other the avatar is larger then maker. What should I do?

CSS how to keep text always inline with a paragraph

CSS how to keep text always inline with a paragraph

I have a block of text with unknown width and I would like to place
another text right after it that would always stick to the last word. If
the first block is one line then setting them both to 'inline' or
'inline-block' is enough, but if the first block is more than one line,
the second block always goes to the next line.
Code:
<div id="text">sit amet, consectetur adipiscing elit. Donec facilisis eros
arcu, sed dictum lorem consequat a. Duis sodales rhoncus felis at
convallis.</div>
<div id="new">New</div>
div {
float: left;
display: inline-block;
}
http://jsfiddle.net/nmuUd/1/
'New' needs to always stick to the last word of the previous block. How
can I do this?

Thursday, 26 September 2013

PHP Pagination query not working

PHP Pagination query not working

In my controller I have the following code:
if($action=='shipping_list'){
$numrows=inquire_row(); //Get number of rows in query
$pages= new Paginator('10', 'p'); //create object
$pages->set_total($numrows);
$shipping=shipping_list(); //Goes to model
include('shipping_list.php');
}
In my model I these codes:
function shipping_list(){
global $MEMS;
global $pages;
$query = "SELECT * FROM Inventory" .$pages->get_limit()
."WHERE Yield >=320 AND (Q = 'Pass' OR Q='No Q') AND shipdate = ' '
ORDER BY Wafer ASC, RC ASC";
echo $query;
$shipping = $MEMS -> query($query);
var_dump($shipping);
return $shipping;
}
When I echo $query, I get
SELECT * FROM Inventory LIMIT 0, 20 WHERE Yield >=320 AND (Q = 'Pass' OR
Q='No Q') AND shipdate = ' ' ORDER BY Wafer ASC, RC ASC
So I know everything is right up to that point. However, when I var_dump
$shipping, I get bool(false). Why isn't my query returning the right
results?

Wednesday, 25 September 2013

Visual Studio Load Test Support for (.Net, C#, WPF , WCF, Silverlight)

Visual Studio Load Test Support for (.Net, C#, WPF , WCF, Silverlight)

I need your help to find out Visual Studio Credibility, pros and cons. Can
you please answer me following question with reference links: 1.
Reputation of tool and its results in market? 2. Which companies are
currently using Visual Studio 2010 load testing tool? 3. Reputation w.r.t
the technologies (.Net, C#, WPF , WCF, Silverlight)? 4. What is the market
share of Visual studio 2010 load testing tool?
Thank you in advance.
Regards, Atif Abbas

Thursday, 19 September 2013

c++ : the game of life?

c++ : the game of life?

i really need your help and really fast. i've been working on this project
where i am supposed to create a simulation of conway's game of life.
A cell can only be in one of two states: alive or dead. There are two
kinds of cells: ConwayCells and FredkinCells.
Live ConwayCells are denoted with an asterisk, "*", and dead cells are
denoted with a period, "." A ConwayCell has 8 neighbours, if it's an
interior cell, 5 neighbours, if it's an edge cell, and 3 neighbours, if
it's a corner cell
ConwayCells do not have the notion of age, FredkinCells do. A
FredkinCells' age is initially zero and only increments by one if the cell
is alive and stays alive. Live FredkinCells are denoted with their age, if
their age is less than 10, otherwise denoted with a plus, "+", and dead
cells are denoted with a minus, "-". A FredkinCell has 4 neighbours, if
it's an interior cell, 3 neighbours, if it's an edge cell, and 2
neighbours, if it's a corner cell.
The rules for going from one generation to the next for ConwayCells are:
a dead cell becomes a live cell, if exactly 3 neighbours are alive
a live cell becomes a dead cell, if less than 2 or more than 3 neighbours
are alive
The rules for going from one generation to the next for FredkinCells are:
a dead cell becomes a live cell, if 1 or 3 neighbours are alive
a live cell becomes a dead cell, if 0, 2, or 4 neighbours are alive
I have to create 5 classes: *Cell class(abstract) from which two are
derived ConwayCell and FredkinCell where each of these cells knows how to
print itself, whether it is alive or not and how many neighbours are
alive. *Life class(abstract) from which two others are derived :
fredkinLife and conwayLife.the subclasses should have functions that keeps
track of the grid (2d dynamic array) and generation , that plays life ,
that evolves , and that prints itself.
And a LifeFactory class that would shoose between creating a fredkinLife
or a ConwayLife.
To push Life forward one generation (evolve), traverse the grid of cells,
only notice the live cells, and for each of them, visit the neighbours and
increment their respective neighbour counts. Remember that the two kinds
of cells have different definitions of neighbour. Traverse the grid a
second time, set the next state, and zero out the neighbour count.
Remember that the two kinds of cells have different rules for the next
state.
In a main program, you will read in initial board states from an input
file and iterate through several generations of the game of life.
#include <iostream>
#include <fstream>
using namespace std;
const int _rows = 109;
const int _columns = 69;
const int maxRows = 20;
const int maxColumns = 20;
class Cell{
protected:
char cell;
int count; // nb of neighbors alive
public:
Cell( char unit = NULL , int n = 0 ){
cell = unit;
count = n;
}
int get_count(){
return count;
}
virtual bool is_live()=0;
virtual int _neighbors()=0;
virtual void print();
};
class ConwayCell : public Cell {
public:
ConwayCell( char unit = NULL , int n = 0 ){
count = n;
cell = unit;;
}
bool is_live(){
if( cell = '*' )
return true;
else if( cell = '.' )
return false;
}
int _neighbors(){
char c[_rows][_columns] = {0};
for( int i=0; i<_rows ; ++i){
for( int j=0; j<_columns ; ++j){
//if( (i == 0 && j == 0) || ( i == _rows - 1 && j ==
_columns - 1 ) || (i == 0 && j == _columns - 1 ) || (i ==
_rows && j == 0) ){
if( c[ i + 1][j] == '*')
count++;
if( c[i][j+1] == '*')
count++;
if( c[i+1][j+1] == '*')
count++;
if( c[i-1][j] == '*')
count++;
if( c[i-1][j-1] == '*')
count++;
if( c[i][j-1] == '*')
count++;
if( c[i-1][j+1] == '*')
count++;
if( c[i+1][j-1] == '*')
count++;
}
}
return count;
}
void print(){
if( ConwayCell::is_live())
cout << '*' ;
else
cout << '.' ;
}
};
class FredkinCell : public Cell {
int cellAge;
public:
FredkinCell( char unit = NULL , int n = 0 , int age = 0 ){
count = n;
cell = unit;
cellAge = age;
if(cell == '+')
cellAge = 10;
else if (cell != '-')
age = (cell - '0');
}
int get_age(){
return cellAge;
}
bool is_live(){
switch (cell){
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '+':
return true;
break;
default:
return false;
}
}
char age(){
if(!FredkinCell::is_live())
return '-';
else if(cellAge>9)
return '+';
return cellAge + '0';
}
int _neighbors(){
char c[maxRows][maxColumns];
for( int i=0; i<maxRows ; ++i){
for( int j = 0; j<maxColumns ; ++j){
if( (c[i+1][j] >= '0' && c[i+1][j] < '10') || c[i+1][j]
== '+' )
count++;
if( (c[i][j+1] >= '0' && c[i][j+1] < '10') || c[i][j+1]
== '+')
count++;
if( (c[i+1][j+1] >= '0' && c[i+1][j+1] < '10') ||
c[i+1][j+1] == '+')
count++;
if( (c[i-1][j] >= '0' && c[i-1][j] < '10') || c[i-1][j]
== '+')
count++;
if( (c[i-1][j-1] >= '0' && c[i-1][j-1] < '10') ||
c[i-1][j-1] == '+')
count++;
if( (c[i][j-1] >= '0' && c[i][j-1] < '10') || c[i][j-1]
== '+')
count++;
if( (c[i-1][j+1] >= '0' && c[i-1][j+1] < '10') ||
c[i-1][j+1] == '+')
count++;
if( (c[i+1][j-1] >= '0' && c[i+1][j-1] < '10') ||
c[i+1][j-1] == '+')
count++;
}
}
return count;
}
void print(){
for( int i=0; i < maxRows ; ++i){
for( int j=0; j< maxColumns; ++j){
if(!FredkinCell::is_live())
cout << "-" ;
else
cout << cell ;
}
}
}
};
class Life {
Cell ** c;
int generation;
int population;
public:
Life(Cell **cell = NULL, int g=0, int p=0){
cell = c;
generation = g;
population = p;
}
virtual void grid() = 0;
virtual void evolve() = 0;
virtual void play() =0;
virtual void print() =0;
};
class ConwayLife {
public:
ConwayLife(){
c = new char * [_rows];
for( int i=0; i< _rows ; ++i)
c[i] = new char[_columns];
}
void grid();
void play();
void evolve();
void print (){
for( int i=0; i< _rows; ++i){
for( int j=0; j< _columns ; ++j){
cout << c[i][j] << " ";
}
cout << endl;
}
}
~ConwayLife(){
for( int i=0; i< _rows;++i)
delete [] c[i];
delete [] c;
}
};
class FredkinLife {
public:
FredkinLife(){
c = new char * [_rows];
for( int i=0; i< _rows ; ++i)
c[i] = new char[_columns];
}
void grid();
void play();
void evolve();
void print (){
for( int i=0; i< maxRows; ++i){
for( int j=0; j< maxColumns ; ++j){
cout << c[i][j] << " ";
}
cout << endl;
}
}
~FredkinLife(){
for( int i=0; i< maxRows;++i)
delete [] c[i];
delete [] c;
}
};
basically what i am asking for is someone to check if my code is correct
and to help me implement gthe other functions in class Life (no code is
required) just detailed explanation

Yii order/search related model in bootstrap.widgets.TbGridView

Yii order/search related model in bootstrap.widgets.TbGridView

there is 3 tables article, author and university
I'm making a grid for table article. Every article belongs to one author
and every author belongs to one university. I need to show University.name
| Author.name | Article.*
At admin view
$gridWidget=$this->widget('bootstrap.widgets.TbGridView',array(
'id'=>'dados-cd-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'author_name'=>array(
'name' => 'author_name',
'value' => '$data->author->name'
),
'university_name'=>array(
'name' => 'university_name',
'value' => '$data->university->author->nome'
),
...
array(
'class'=>'bootstrap.widgets.TbButtonColumn',
),
),
));
And at article model I have
public $author_name;
public $university_name;
public function rules()
{
...
return array(
array('author.name, university.name, ... , 'safe', 'on'=>'searc
h'),
...
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->with = array( 'author','author.university' );
$criteria->compare('author.name',$this->author_name,true);
$criteria->compare('university.name',$this->university_name,true);
...
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'attributes'=>array(
'author_name'=>array(
'asc'=>'author.name',
'desc'=>'author.name DESC',
),
'university_name'=>array(
'asc'=>'university.name',
'desc'=>'university.name DESC',
),
'*',
),
),
));
}
The grid is working perfect fine. However when I try to search or order by
author_name I got a error message. I'll try to translate the error message
from portuguese but I don't know if it is like that in english: "Undefined
table:7 Error: missing entry for table author"
The funny part is that the university search and order is working just
fine. And I can't see the diference between they.
Anyone can help me?

Regex pattern for Validating phone number in C#

Regex pattern for Validating phone number in C#

I have a input string ("My phone number is 860-678 - 2345"). From the
input string I need to validate phone number using Regex and need to
replace the phone number with (xxxxxxxxxx).
I am using the below pattern but it doesn't work if the phone number
contains white Space in it.
[(]?[2-9]{1}[0-9]{2}[)-. ,]?[2-9]{1}[0-9]{2}[-. ,]?[0-9]{4}
Thanks.

Math.round is not working as i want to

Math.round is not working as i want to

Whenever a double is returned from the calculateVolume() it gets a value
for example 1.0, this need to be displayed as 1.00 (2 decimals instead of
1). It's probably quite easy but i'm not seeing what i'm doing wrong right
now. Can someone help me out and give a short explanation. Thanks a lot!
public class Block extends Shape {
private double length;
private double width;
private double height;
public Block(double length, double width, double height){
this.length = length;
this.width = width;
this.height = height;
}
@Override
public double calculateVolume(){
return Math.round((length * width * height)* 100.0) / 100.0;
}

Search through multidimentional array JavaScript

Search through multidimentional array JavaScript

I got stuck trying to retrive array items. So here is the deal. I have a
two dimentional array which has value and key so example of my data is:
[
Object { css="SS", title="Apple"},
Object { css="SS", title="Orange"},
Object { css="SS", title="Banana"}
]
I want to see if an object exists in the array above. And I have no idea
why its not working, here is my code to find the object:
jQuery.inArray("Apple", fruits["title"]); //this returns -1 why?
Any ideas how to search two dimentional array?

Network condition monitoring, in android native voip SDK

Network condition monitoring, in android native voip SDK

I have developed an android VOIP client using the native Android VOIP SDK,
I have been asked to display the status of the network during the active
phone call, e.g. The App says Expect good,bad or fair phone call in real
time while the user is talking, just like Skype or Viber.
Perhaps I could not find the solution myself because I presumed that Viber
or Skype implemented it from within their VOIP stack, While in the reality
It is just a separate software-networking function.

How to resolve a NameError in my 'rock, paper, scissors' function

How to resolve a NameError in my 'rock, paper, scissors' function

I just started programming in python 2.7.x. and had to put a programm for
rock, paper and scissors into a function. In the programm itself I asked
the user for an input and now I have to change it to just using parameters
only and using return instead of 'print'. Its a simple piece of code but I
just keep getting the NameError: name 'x' is not defined.
So I run the function into shell and then I type in: rps(rock, paper).
Some hints on how to resolve this or advice on my code would be great.
Here's the code.
def rps(player1, player2): if (player1 != 'rock' and player1 != 'scissors'
and player1 != 'paper'): return 'This is not a valid object selection'
if (player2 != 'rock' and
player2 != 'scissors' and
player2 != 'paper'):
return 'This is not a valid object selection'
if (player1 == 'rock' and
player2 == 'scissors'):
return 'Player 1 wins.'
if (player1 == 'rock' and
player2 == 'rock'):
return 'There is a tie.'
if (player1 == 'rock' and
player2 == 'paper'):
return 'Player 2 wins.'
if (player1 == 'scissors' and
player2 == 'scissors'):
return 'There is a tie.'
if (player1 == 'scissors' and
player2 == 'rock'):
return 'Player 2 wins.'
if (player1 == 'scissors' and
player2 == 'paper'):
return 'Player 1 wins.'
if (player1 == 'paper' and
player2 == 'rock'):
return 'Player 1 wins.'
if (player1 == 'paper' and
player2 == 'paper'):
return 'There is a tie.'
if (player1 == 'paper' and
player2 == 'scissors'):
return 'Player 2 wins.'

Wednesday, 18 September 2013

How to detect of tap gesture is from uiwebview or self.view?

How to detect of tap gesture is from uiwebview or self.view?

Hello everyone I have a uitapgesture on my view using the following code :
UITapGestureRecognizer *tap= [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(TAPGestureRecognizer)];
tap.numberOfTapsRequired=1;
tap.delegate = self;
[self.view addGestureRecognizer:tap];
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer
*)otherGestureRecognizer
{
return YES;
}
And I have a uiwebview as a subview in my UIview. The problem is that on
the uivewview HTML it had a onclick(); which in turn is calling the
tapgesture. Any help?

Jenkins - NUnit/MSTest Code Coverage Graph

Jenkins - NUnit/MSTest Code Coverage Graph

Is it possible to produce a graph of code coverage v time in Jenkins for
NUnit/MSTest?
I can produce a code coverage report with OpenCover and ReportGenerator. I
would prefer to be able to visualise this with a graph. The NUnit plugin
only produces of a graph of tests run or test failures over time.
On a separate note, does anyone know how to get OpenCover to set the
%ERRORLEVEL% batch variable is a test fails during code coverage
calculation?

How to programmatically display HTML5 client-side form validation error bubbles?

How to programmatically display HTML5 client-side form validation error
bubbles?

I'm trying to use HTML5 client-side validation (i.e. inside a form), but
cannot see how to display the validation error bubbles programatically.

Consider the following:
<form id="myForm">
<input type="text" id="number" min="1" max="10" step="3" required>
</form>
If there is a canonical submit button (i.e <input type="submit">), and
there are validation errors, the user-agent will halt the submit and show
UI to the user:

But, if instead of a using a submit input, the user is clicking an anchor
that executes javascript (i.e. ASP.net Webforms):
<a href='javascript:SaveChanges()'>Save Quantity</a>
<script>
function SaveChanges()
{
var form = document.getElementById('myForm');
if (form === null) return;
if (!form.checkValidity())
{
//We reach here, but no UI is displayed
return;
}
form.submit();
</script>
The issue is that while
form.checkValidity();
does check the form's validity (returning false if it's not valid), it
does not trigger the UI displays.
And now we have our question. Submitting through
<input type="submit"> works (halts and shows UI)
<button type="submit> works (halts and shows UI)
form.submit doesn't work (doesn't halt; doesn't show UI)
form.checkValidity() doesn't work (doesn't show UI)
How to programmatically display HTML5 client-side form validation error
bubbles?
jsFiddle for all of the above
See also
How to programmatically display HTML5 client-side validation error bubbles?

Is it possible to do an inline "else if"?

Is it possible to do an inline "else if"?

This is really unnecessary, but I'm curious... can you do an inline "else
if" much like you would do a standard inline if/then/else? A few minutes
of googling did not return an answer.
Example:
if (n == 1) {
alert("The variable is 1!")
} else {
alert("The variable is not 1!")
}
is the same as:
n == 1 ? alert("The variable is 1!") : alert("The variable is not 1!")
But is there a way to do this using similar syntax?
if (n == 1) {
alert("The variable is 1!")
} else if (n == 2) {
alert("The variable is 2!")
} else {
alert("The variable is not 1 or 2!")
}
I tried the following, but it did not seem to work:
n == 1 ? alert("The variable is 1!") : (n == 2 ? alert("The variable is
2!") : alert("The variable is not 1 or 2!"))

Javascript if value is in array else in next array

Javascript if value is in array else in next array

I have found a few posts on here with similar questions but not entirely
the same as what I am trying. I am currently using a simple if statement
that checks the data the user enters then checks to see if it starts with
a number of different values. I am doing this with the following:
var value = string;
var value = value.toLowerCase();
country = "NONE";
county = "NONE";
if (value.indexOf('ba1 ') == 0 || value.indexOf('ba2 ') == 0 ||
value.indexOf('ba3 ') == 0) { //CHECK AVON (MAINLAND UK) UK.AVON
country = "UK";
county = "UK.AVON";
}
I have about 20-30 different if, else statements that are basically
checking the post code entered and finding the county associated. However
some of these if statements are incredibly long so I would like to store
the values inside an array and then in the if statement simply check
value.indexOf() for each of the array values.
So in the above example I would have an array as follows for the statement:
var avon = new Array('ba1 ','ba 2','ba3 ');
then inside the indexOf() use each value
Would this be possible with minimal script or am I going to need to make a
function for this to work? I am ideally wanting to keep the array inside
the if statement instead of querying for each array value.
Edit:
just found a post on here mentioning the following JQuery:
$.inArray(value, array) am going to have a play around with this

line between textbox and lable wpf

line between textbox and lable wpf

I need to create something like this:

I was thinking to use a label and a textbox, but I don't know how to put
that line between them. All that I need is good idea how to do it. Are
there other tools to do that?

Find the best solution for read file and call web service

Find the best solution for read file and call web service

I have a text file which has about 100,000 records of identifier.
I must read all of record, each record i do request to web service and
receive the result from web service, the result i write to another file.
I'm confuse between two solution: - Read identifier file to a list of
identifier, iterate this list, call web service, .... - Read identifier
line on each line, call web service, .....
Do you think what solution will be better ? program will do faster ?
Thanks for all.

is there any alternates to merge two datasets in SAS apart from Proc Sql and Merge statement?

is there any alternates to merge two datasets in SAS apart from Proc Sql
and Merge statement?

i want to merge two datasets, but without using merge statement and Proc
sql,can i do this? is there any way to do the same

Tuesday, 17 September 2013

Python module pseudo compiler idea.

Python module pseudo compiler idea.

Say I work for a python project, in folder myfolder/
it has a library file "Mylibrary.py" and a script file "myscript.py"
and in myscript.py I imported Mylibrary.py, is there a program such that
it will replace "import Mylibrary" by my library file literally and
replace all function call "Mylibrary.myfunction" by "myfunction"? It kind
of like "compile" multiple python scripts into one. Or this would be a
terrible solution
The reason is that I want to use myscript as an executable in other
folders without having to copy multiple files or making a package.

Create a list out of the output in loop

Create a list out of the output in loop

We are tasked to print out the values in the pascal triangle in this manner
(pascal 2)
(1 2 1)
(pascal 0)
(1)
I copied the code for the binomial thereom somewhere in the internet
defined as follows:
(defun choose(n k)
(labels ((prod-enum (s e)
(do ((i s (1+ i)) (r 1 (* i r))) ((> i e) r)))
(fact (n) (prod-enum 1 n)))
(/ (prod-enum (- (1+ n) k) n) (fact k))))
Now I'm trying to create a list out of the values here in my pascal function:
(defun pascal (start end)
(do ((i start (+ i 1)))
((> i end) )
(print (choose end i) ))
)
The function produces 1 2 1 NIL if I test it with (pascal 0 2). How can I
eliminate the NIL and create the list.

What are the orgins of the terms "parse" in java?

What are the orgins of the terms "parse" in java?

In java I noticed there are methods associated with conversion of strings
and those methods sometimes use the word "parse" in the name of the
method. For example the static method,
static int parseInt(String str)
is used to convert a string into int. My question is this. Is "parse"
short for another word? Is is just a random word or did it come from
somewhere else in some other context?

Matlab remoteParallelFunction and Mex file Error

Matlab remoteParallelFunction and Mex file Error

I'm trying to validate the default local matlab parallel configuration,
but I get the following error:
Validation Details
Configuration: "local" Type: local
-------------------------------------- Stage: Find Resource
Status: Passed Description: Validation passed
Command Line Output: (none)



-------------------------------------- Stage: Distributed Job
Status: Passed Description: Validation passed
Command Line Output: (none)



-------------------------------------- Stage: Parallel Job
Status: Passed Description: Validation passed
Command Line Output: (none)



-------------------------------------- Stage: Matlabpool
Status: Failed Description: Encountered a problem while trying to run code
in the matlabpool.
Command Line Output: Starting matlabpool using the 'local' configuration
... connected to 8 labs.
Error Report: Error using ==> parallel_function at 598 Error in remote
execution of remoteParallelFunction : RUNTIME_ERROR
Debug Log: (none)



And if I actually try to run the code, I receive the following error:
??? Invalid MEX-file
'/usr/local/matlab/R2010a/toolbox/distcomp/private/dctRegisterMpiFunctions.mexa64':
/usr/local/matlab/R2010a/toolbox/distcomp/private/../../../../../bin/glnxa64/libmwmpi.so:
undefined symbol: _ZN9MathWorks6System9Condition9signalAllEv.
Error in ==> remoteParallelFunction at 51
dctRegisterMpiFunctions('mwmpi');
??? Error using ==> parallel_function at 598
Error in remote execution of remoteParallelFunction : RUNTIME_ERROR
Error in ==> InterpCorrectionPar at 53
parfor n=1:size(Image,3)
Error in ==> InterleaveDetCor at 119
FixedImage=InterpCorrectionPar(ImStack,Int,Tr,varargin{Ctrl});
Error in ==> MainCompareProgram at 25
InterleaveDetCor(FilePath,SavePath,RunCorrection,'FiltShift','Cubic','Spline','Linear','Sinc');
I'm running matlab 2010a on a gnome 2.28.2 linux "server" (really just a
computer with 400Gigs of memory and 32 processors used for intensive
computation). The code I'm running is just a few parfor loops that I've
run on my local machine before. I'm actually running the program on the
server computer locally through vcn. Can anyone please suggest what the
problem may be?

When can DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK have an effect?

When can DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK have an effect?

DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK is "supposed" to be used
before a transaction, to explicitly set the value on failure.
However, the documentation states that this is more or less the default
behavior anyway?
If a condition occurs for which no handler has been declared, the action
taken depends on the condition class:
For SQLEXCEPTION conditions, the stored program terminates at the
statement that raised the condition, as if there were an EXIT handler. If
the program was called by another stored program, the calling program
handles the condition using the handler selection rules applied to its own
handlers.
But that means COMMIT is never called, so, same effect as having no handler.
I'm not sure how to interpret that. It sounds like the "obvious" thing to
do is exit the stored program, but if a calling program has handlers
telling to do otherwise - perhaps a DECLARE EXIT HANDLER FOR SQLEXCEPTION
CONTINUE - it's not clear to me whether the inside stored program
continues or not, or what the "handler selection rules" are in general.
If this (strange to me) interpretation is the case, then that means if
hypothetically a stored program could assume it was never called by
another stored program, the handler is extraneous, but it ensures
consistent behavior

Clear data option in android application

Clear data option in android application

If we select clear data option in android program, It'll clear application
database.As I know we cannot prevent this action if we install application
database in default location.Is there any method to prevent this action by
saving application database in a hidden location which will not be able to
access by users.Please provide me any solution regarding this matter.