Thursday, 3 October 2013

Why can a matrix 'protect' itself and how can I implement real restrictions to custom classes?

Why can a matrix 'protect' itself and how can I implement real
restrictions to custom classes?

I have been trying to get my ahead around validity of objects. I have read
Hadley's advanced programming and get what he says about he says about
aiming at your feet (with a gun):
"R doesn't protect you from yourself: you can easily shoot yourself in the
foot, but if
you don't aim the gun at your foot and pull the trigger, you won't have a
problem"
So this holds for S3. Looking for a more rigorous implementation I looked
into S4. The man page to setValidity brought up the following:
setClass("track",
representation(x="numeric", y = "numeric"))
t1 <- new("track", x=1:10, y=sort(stats::rnorm(10)))
## A valid "track" object has the same number of x, y values
validTrackObject <- function(object) {
if(length(object@x) == length(object@y)) TRUE
else paste("Unequal x,y lengths: ", length(object@x), ", ",
length(object@y), sep="")
}
## assign the function as the validity method for the class
setValidity("track", validTrackObject)
## t1 should be a valid "track" object
validObject(t1)
## Now we do something bad
t2 <- t1
t2@x <- 1:20
## This should generate an error
## Not run: try(validObject(t2))
Bottom line: If I do not add validObject to the initializer or constructor
there's little I can do. Also this post from Martin Morgan and
bioconductor's Seth Falcon was interesting, still though I could always
t2@x <- 1:1111.
I guess there's not much I can do about this? Though the matrix class for
example makes me wonder if there's an option.
a <- matrix(c(1:12),3,4)
cbind(a,"somechar")
# or similarily
a[1,1] <- "b"
Obviously all elements of a matrix have to be of the same class. So that's
why once a character is added all elements are coerced to the common
denominator, which is class character.
So my question is: How is this possible? In which way is the matrix class
defined, that it can protect the restriction "some class for all elements"
by any means? And is there a way to implement such a restriction to a
custom class, too?
E.g.: class of class 'customlist' that has to be a named list and names
being restricted to only be two chars long.

Wednesday, 2 October 2013

importing 20k details in php using csv

importing 20k details in php using csv

I'm trying to insert a csv file with at least 20k lines, and it prompts my
browser to kill it self, I guess its taking up a lot of memory and its
processing it really slow, I'm also doing this for export and still the
same problem it takes too much time that the browser wanna kill it self.
Do you have any suggestions on how am I supposed to make it easier and
faster?
here are my codes:
Import:
if($_POST) {
$error = 0;
$tmpName = $_SESSION["csv_file"];
$fileExtension = $_SESSION["csv_ext"];
$fieldset = explode(",", trim($_REQUEST["csv_listfields"], ","));
unset($_SESSION["csv_file"]); unset($_SESSION["csv_ext"]);
if($tmpName){
if($fileExtension == 'csv'){
$fp = fopen($tmpName, 'r');
$fr = fread($fp, filesize($tmpName));
$line = explode("\n", $fr);
$field_pairs = array();
$csvpos=array();
$csvpos=$_POST['csv_pos'];
$getCsvPos=array();
$ifNotempty=0;
for($i=0;$i<count($csvpos);$i++){
if($csvpos[$i]!=-1){
$getCsvPos[$ifNotempty] = $csvpos[$i];
$ifNotempty++;
}
}
$fldcolumns = $line[0];
$fldcolumns = array_map("trim_field", explode(",",
$fldcolumns));
$forIndexValue=0;
foreach($fieldset as $fld){
$f = explode("=", $fld);
list($dbcol, $colcsv) = explode("=",$fld);
$field_pairs[$dbcol] = $getCsvPos[$forIndexValue] ;
$forIndexValue++;
}
$csvfile = fopen($tmpName, 'r');
$ctr = 0;
$total_uploaded = 0;
while (($datax = fgetcsv($csvfile, 1000, ",")) !== FALSE) {
$insert_crm = array();
$row_hascrm_assigned = false;
if($ctr != 0){
$ins_tbl = array();
$has_val = false;
foreach($field_pairs as $field => $colkey){
if( $datax[$colkey] != '' ) $has_val = true;
if($field != 'crm_group'){
if($field == 'password'){
$ins_tbl[$field] =
(strlen($datax[$colkey]) != 64) ?
hash("sha256", $datax[$colkey]) :
$datax[$colkey];
}elseif($field == 'birthdate' || $field ==
'dateIN'){
if($field=="dateIN"){
if($datax[$colkey] == ""){
$date = date("Y-m-d");
}else{
$date = $datax[$colkey];
}
$ins_tbl[$field] = $date;
}
}elseif($field == 'email'){
$ins_tbl[$field] =
strtolower($datax[$colkey]);
}else{
$ins_tbl[$field] =
mysql_real_escape_string($datax[$colkey]);
}
if($field != "dateIN"){
$ins_tbl["dateIN"] = date("Y-m-d");
}
if($field == "birthdate"){
$ins_tbl[$field] = $datax[$colkey];
}
}else{
foreach( explode(";",
$datax[count($fldcolumns) - 1]) as $cg ){
$cg = ($cg == "")?$datax[$colkey]:$cg;
$cg = htmlentities($cg);
$crm_sql = mysql_query("SELECT crm_gid
FROM tbl_crm_groups WHERE
crm_group_name = '".trim($cg,
"'")."'");
if(mysql_num_rows($crm_sql) < 1){
mysql_query("INSERT INTO
tbl_crm_groups (crm_group_name,
crm_date_created, custom) VALUES
('".$cg."', '".date('Y/m/d
H:i:s')."', 1)") or
die("</br>Error Message:
".mysql_error());
$crm_gid = mysql_insert_id();
}else{
$crm_gid = ($cg != "" &&
mysql_num_rows($crm_sql) > 0) ?
mysql_result($crm_sql, 0) : 1;
}
if(mysql_num_rows(mysql_query("SELECT
* FROM tbl_crm_members WHERE
crm_groupid = {$crm_gid} AND crm_uid =
{$crm_uid}")) < 1){
if(!in_array("INSERT INTO
tbl_crm_members(crm_groupid,
crm_uid, datejoined)
VALUES('{$crm_gid}',
'[give_me_uid]',
'".date("Y-m-d")."')",
$insert_crm))
$insert_crm[] = "INSERT INTO
tbl_crm_members(crm_groupid,
crm_uid, datejoined)
VALUES('{$crm_gid}',
'[give_me_uid]',
'".date("Y-m-d")."')";
}
}
}
}
if($has_val){
if(mysql_query("INSERT INTO tbl_members
(".implode(',',array_keys($ins_tbl)).") VALUES
(\"".implode('","',$ins_tbl)."\")")){
$last_member_inserted = mysql_insert_id();
$total_uploaded++;
if(count($insert_crm) > 0){
foreach($insert_crm as $ic){
mysql_query(
str_replace("[give_me_uid]",
$last_member_inserted, $ic) );
}
}else{
mysql_query( "INSERT INTO
tbl_crm_members(crm_groupid, crm_uid,
datejoined) VALUES('1',
".mysql_insert_id().",
'".date("Y-m-d")."')" );
}
}
}
}
$ctr++;
}
fclose($fp);
echo "<div style='color: green; margin: 10px;'>STATUS:
".$total_uploaded." record(s) successfully imported.
<br/>This page will reload in a couple of seconds.</div>";
}else{
exit("Not a valid csv file uploaded.");
}
unlink($tmpName);
echo "<script
type='text/javascript'>setTimeout(function(){parent.location.reload(true);},
2000);</script>";
}else{
exit("File uploaded improperly.");
}
}
Export:
if(IS_AJAX){
$output = array();
$sql_getcustomers = $_POST['val'];
/* CREATE CSV FILE FOR DOWNLOAD */
$filename2 = "csv/leads_".date("M-d-Y",time()).".csv";
$fp2 = fopen($filename2, 'w') or die("can't open file");
$sql2 = $sql_getcustomers;
$res2 = mysql_query($sql2);
// fetch a row and write the column names out to the file
$row2 = mysql_fetch_assoc($res2);
$line = "";
$comma = "";
if($row2){
foreach($row2 as $name => $value) {
$line .= $comma . '"' . str_replace('"', '""', $name)
. '"';
$comma = ",";
}
$line .= ",crm_group";
$line .= "\n";
fwrite($fp2, $line);
// remove the result pointer back to the start
mysql_data_seek($res2, 0);
// and loop through the actual data
while($row2 = mysql_fetch_assoc($res2)) {
$line = "";
$comma = "";
foreach($row2 as $index => $value) {
$line .= $comma . '"' . str_replace('"', '""',
utf8_decode($value)) . '"';
$comma = ",";
}
//** GET THE CRM GROUPS
$sql_get_group = "SELECT a.crm_group_name, b.* FROM
tbl_crm_members b JOIN tbl_crm_groups a ON (a.crm_gid
= b.crm_groupid) WHERE crm_uid = ".$row2["uid"];
$sql_get_groups = mysql_query($sql_get_group);
$res_get_groups = "";
while($sgg = mysql_fetch_object($sql_get_groups))
$res_get_groups .= $sgg->crm_group_name.";";
$line .= ",".trim($res_get_groups, ";");
$line .= "\n";
fwrite($fp2, $line);
}
fclose($fp2);
$output['data'] = 1;
$output['file'] = $filename2;
}else{
$output['data'] = 0;
}
}else{
$output['data'] = 0;
}

Xcode - Use multiple SDKs on XCode 5

Xcode - Use multiple SDKs on XCode 5

I have a project which requires iOS 6.1 SDK and I have upgraded to XCode5
and dont see iOS 6.1 SDK in Build Settings -> Base SDKs. I have earlier
SDK saved separately and tried copy-pasting it in
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs
Directory. But it doesn't show up in Build settings -> Base SDKS. How can
I use multiple SDKs in Xcode 5?

Nginx+Tornado static files aren't being handled by nginx, why?

Nginx+Tornado static files aren't being handled by nginx, why?

I'm trying to set up Tornado server behind nginx proxy, here're the
relevant bits of the configuration:
server {
listen 80;
server_name localhost;
location html/ {
root /srv/www/intj.com/html;
index login.html;
if ($query_string) {
expires max;
}
}
location = /favicon.ico {
rewrite (.*) /html/favicon.ico;
}
location = /robots.txt {
rewrite (.*) /html/robots.txt;
}
location / {
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_pass http://localhost:8888;
}
}
I can get to my Python server through nginx, but when I request a static
pages, such as, say login.html, which is located in
/srv/www/intj.com/html/login.html, instead of loading the static file, the
request is forwarded to Tornado, which doesn't know what to make of it.
What did I do wrong?

Tuesday, 1 October 2013

IndexController newly added method give 404 error

IndexController newly added method give 404 error

I am new to the zf so I guess this is a basic level problem for you guys.I
have a zf1 project and I am studying the code.In my IndexController all
the old methods are working except my new method,It gives me a 404
error.Do i need to specify the method names anywhere? or what can I do for
this error ?
my controller path -
application/modules/default/controllers/IndexController.php
my newly added method that is not work in IndexController.php
public function mytestAction() { }
Old method that is work in IndexController.php
public function termsconditionsAction() { }
views path - application/modules/default/views/index/mytest.phtml

Web client works on GlassFish 4, but not on GlassFish 3

Web client works on GlassFish 4, but not on GlassFish 3

I'm developing some enterprise web site using Java EE 6 technology. My
collegue was assigned working on web client and he develops it on his PC
using JSF 2.1 and GlassFish 4.0. When I tried running that web client on
my PC, which at first had GlassFish 3.1 instaled, it didn't work. Not a
single line of xhtml code was rendered on my web browser.
Later on, I installed GlassFish 4 and deployed application on it and look
at miracle - it worked! So basicaly, my question is simple: Why does that
happend? Why can't I run web client on older version of GlassFish server?
P.S. No error or warning is recorded on server's log when I try to run it
on GlassFish 3.1.

Should graduate applicants follow instructions by department NOT to contact potential advisors=?iso-8859-1?Q?=3F_=96_academia.stackexchange.com?=

Should graduate applicants follow instructions by department NOT to
contact potential advisors? – academia.stackexchange.com

I am applying for doctoral programs in biostatistics and have read
multiple places to attempt to set up contact with a potential advisor
before applying. What if the department website specifically …

Closed form of the limit of a sequence (weighted average)

Closed form of the limit of a sequence (weighted average)

I have a sequence, which can actually be seen as Riemann-Stieltjes
integration with a binomial distribution. $\rho \in (0,1)$.
$$ S_N
:=‡"_{n=0}^{N}ƒÏ^{N-n}(1-ƒÏ)^{n}\binom{N}{n}\left(\frac{n}{N}\right)^\theta
$$
Using convexity/concavity of $(n/N)^\theta$ I can show the sequence
declines/increases with N. The sequence is also bounded between 0 and 1. I
wonder if there is a closed form limit of this sequence.
I appreciate any thoughts on this.

Monday, 30 September 2013

Troubles with Nexus 4 Ubuntu touch - Ubuntu 13.10 connection

Troubles with Nexus 4 Ubuntu touch - Ubuntu 13.10 connection

Each time I trying to copy anything to my Nexus 4 U Touch folders I
receiving the following error
Error while copying "IMG_20130723_220008.jpg".
There was an error copying the file into
mtp://[usb:001,004]/Nexus%204/Pictures.
Show more details
libmtp error: Could not send object info.
Any ideas how to fix this?

Is it possible to install Microsoft Office without a CD?

Is it possible to install Microsoft Office without a CD?

I have been a Windows user since... well... always. Now I decided to try
Linux Ubuntu, and found out it looks way much better.
The problem is, I am a student and constantly need Microsoft
Word/Excel/Powerpoint, and LibreOffice just isn't the same thing. When I
have to update something on Excel, when I open the same archive on Windows
some formatation of it is changed. That's why I would like to install
Microsoft Windows.
I do not have the installation CD. However, I already have the Microsoft
Office installed on Windows. I have tried the convenient methods to
install it through PlayOnLinux, but I keep stuck on this part
http://i.stack.imgur.com/2GPmT.png
From:Can Wine support Office 2007?
My question is: Can I install it through the archives it created on
Windows when it was there installed or would I really need the CD for that
and, therefore, not being able to install? Would I be able to borrow a CD
from someone?
Thank you.

Null bytes when using xlwt to make valid excel file

Null bytes when using xlwt to make valid excel file

I'm using Python 2.7 and attempting to automate downloading an excel file
from a website using the mechanize library. I used CharDet to discover the
original encoding for the file, which is "iso-8859-2". In order to
properly separate the data into columns based on the data read by
mechanize, I have an intermediary step storing the data to a text file.
fileobj = open("data.txt", 'wb')
fileobj.write(response.read())
fileobj.close()
To create the Excel file, I am using the xlwt module.
book = xlwt.Workbook(encoding = "utf-8")
sheet = book.add_sheet('sheet1')
After this, I read through the text file and attempt to decode the text
and encode it into utf-8 form with
for line in fileobj:
line = line.decode("iso-8859-2").encode("utf-8", "ignore")
The problem is that attempting to iterate over the file using Python's csv
default reader reports an error that there are null bytes. Placing the
encoded text in a .txt file shows there are no null bytes in the lines
themselves, so I am not sure where the problem is coming from.

Php "" and 0 return same value

Php "" and 0 return same value

$page_now=array_search($id, $user_id);
if($page_now==""){return TURE;}
else{return FALSE}//include [0]index
I have an array_search, if it can't find the match it will return "",
However I have problem on [0] index
if the search index return 0 which is 1st one from array.
if statement $page_now=="" & $page_now==0 both are return TURE
Try this
$var=0;
if($var!=""){echo "have value in var";}else{echo "no value in var";}
I want it return have value even it is 0

Sunday, 29 September 2013

R language: Maximize function subject to another function

R language: Maximize function subject to another function

I am interested to know how can I maximize a function f(x) = x/y subject
to x + y = 100 using R. I know a couple of packages like optim or optimize
that helps to do it but it requires a vector of values for the parameters
to be optimized over. I would like to know if I could do it without the
use of the values.
Any advice or help would be appreciated.
Thanks !!

SQL Truncate Error when Inserting UUID

SQL Truncate Error when Inserting UUID

I'm building a database driven PHP application that uses UUID's to store
each row of data. The application currently generates the UUID's using the
following query:
SELECT UUID()
which generates an output similar to 84058227-294c-11e3-916a-7a7919b2b2bc.
Many online sources suggest that UUID's be stored in BINARY(16) to improve
overall application performance. But when I attempt to insert the UUID
into the database, I receive the following error:
Warning: #1265 Data truncated for column 'x' at row x
I realize that this error occurred because the UUID was too large for the
column to store, and that this issue can be easily fixed by simply
increasing the amount of characters the column may store (ex: BINARY(20)),
but I fear that doing so may reduce the application's performance in the
future.
Considering that so many online sources suggest using BINARY(16) to store
UUID's, I'm assuming that I have made a mistake.
Could someone please point me in the right direction?
For extra information, here is the code I'm using (in PHP) to insert data
into the database:
//PDO Query
$this->query(
INSERT INTO users
(
user_id, //the UUID is stored in this column
taxonomy_id,
user_email,
user_password,
user_salt,
user_activation_key,
user_is_administrator
)
VALUES(?,?,?,?,?,?,?)
',
array(
$this->uuid(), //method that generates UUID
$taxonomy_id,
$user_email,
$user_password,
$user_salt,
$user_activation_key,
$user_is_administrator
)
)
);
and the method that generates each UUID:
public function uuid()
{
$uuid = $this->query("SELECT UUID() AS uuid");
return $uuid[0]['uuid'];
}

simple scrolling images in android in an single activity

simple scrolling images in android in an single activity

How to obtain the below functionality in android?
Images are coming from an external url. How to attain simple scrolling ?
For Placing the buttons i have an idea
But for Scrollable images below, how to obtain this functionality. Which
concept should i need to apply?

Saturday, 28 September 2013

android:Asynchronous downloads list of images from ftp Servicer

android:Asynchronous downloads list of images from ftp Servicer

I'm looking for a java library that works on the android that can
Asynchronous download and display images from an FTP server. Does anyone
know of such a library. I've found lots of client apps, but no stand alone
libraries.

Adding columns to a data table

Adding columns to a data table

I have a data.frame (or a matrix or any other tabular data structure
object for that matter):
df = data.frame(field1 = c(1,1,1),field2 = c(2,2,2),field3 = c(3,3,3))
And I want to copy part of its columns - given in the vector below:
fields = c("field1","field2")
to a new data.table that already has 1 or more columns:
dt = data.table(fieldX = c("x","x","x"))
I'm looking for something more efficient (and elegant) than:
for(f in 1:length(fields))
{
dt[,fields[f]] = df[,fields[f]]
}

ABAddressBookCreateWithOptions causes crash (unrecognized selector)

ABAddressBookCreateWithOptions causes crash (unrecognized selector)

In my iPad app (XCode 5, ios7, ARC, Storyboards), I'm trying to read the
Address book and get all of the entries. This is my code that I copied
from SO (why re-invent the wheel?). Unfortunataly, it doesn't work!
- (IBAction)importClientData:(UIButton *)sender {
NSMutableArray *allContacts = [[NSMutableArray alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
for(int i = 0;i<ABAddressBookGetPersonCount(addressBook);i++)
{
NSMutableDictionary *aPersonDict = [[NSMutableDictionary alloc] init];
ABRecordRef ref = CFArrayGetValueAtIndex(people, i);
NSString *fullName = (__bridge NSString *)
ABRecordCopyCompositeName(ref);
if (fullName) {
[aPersonDict setObject:fullName forKey:@"fullName"];
// collect phone numbers
NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
ABMultiValueRef phones = ABRecordCopyValue(ref,
kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++) {
NSString *phoneNumber = (__bridge NSString *)
ABMultiValueCopyValueAtIndex(phones, j);
[phoneNumbers addObject:phoneNumber];
}
[aPersonDict setObject:phoneNumbers forKey:@"phoneNumbers"];
// collect emails - key "emails" will contain an array of email
addresses
ABMultiValueRef emails = ABRecordCopyValue(ref,
kABPersonEmailProperty);
NSMutableArray *emailAddresses = [[NSMutableArray alloc] init];
for(CFIndex idx = 0; idx < ABMultiValueGetCount(emails); idx++) {
NSString *email = (__bridge NSString
*)ABMultiValueCopyValueAtIndex(emails, idx);
[emailAddresses addObject:email];
}
[aPersonDict setObject:emailAddresses forKey:@"emails"];
// if you want to collect any other info that's stored in the
address book, it follows the same pattern.
// you just need the right kABPerson.... property.
[allContacts addObject:aPersonDict];
}
else {
// Note: I have a few entries in my phone that don't have a name set
// Example one could have just an email address in their address
book.
}
}
}
No matter what code I use (I have tried several variations of the above
code) they all crash on the same call (-ABAddressBookCreateWithOptions).
Since I copied the same code from multiple examples, I would expect at
least this line to work. It's not! Why?

Error while uploading app into Windows App Store - "native API api-ms-win-core-interlocked-l1-2-0.dll:InterlockedIncrement()" in Windows...

Error while uploading app into Windows App Store - "native API
api-ms-win-core-interlocked-l1-2-0.dll:InterlockedIncrement()" in
Windows...

I am trying to upload app into Windows Appstore and stuck at the following
errors. I am using Sqlite and SQliteWinRTPhone in my app. What could be
the problem. How to resolve this?
1028: The native API
api-ms-win-core-interlocked-l1-2-0.dll:InterlockedIncrement() isn't
allowed in assembly SQLiteWinRTPhone.dll. Update it and then try again.
1028: The native API
api-ms-win-core-interlocked-l1-2-0.dll:InterlockedCompareExchange() isn't
allowed in assembly sqlite3.dll. Update it and then try again.
1028: The native API
api-ms-win-core-interlocked-l1-2-0.dll:InterlockedCompareExchange() isn't
allowed in assembly SQLiteWinRTPhone.dll. Update it and then try again.

Friday, 27 September 2013

Ubuntu pjsip python compilation

Ubuntu pjsip python compilation

Following instructions for compiling python and PjSIP
http://trac.pjsip.org/repos/wiki/Python_SIP/Build_Install When doing last
step: make
I get
/home/<user>/Downloads/pjproject-2.1.0/pjsip/lib/libpjsua-x86_64-unknown-linux-gnu.a:
could not read symbols: Bad value
collect2: ld returned 1 exit status
error: command 'gcc' failed with exit status 1
make: *** [all] Error 1
I tried recompile with: ./configure CFLAGS='-fPIC'
or use user.make
export CFLAGS += -O2 -fPIC
#export LDFLAGS +=
But same issue
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 12.04.2 LTS
Release: 12.04
Codename: precise

If not true, prompt again until is true

If not true, prompt again until is true

This is so easy, but I am drawing a blank right now (long day). I simply
need this part of the code to reprompt for a file name if the one entered
is not valid or is bad.
cout << "Please enter a file name:" << endl;
string filename;
string line;
cin >> filename;
ifstream in_file;
in_file.open(filename.c_str());
if (in_file.good())
{
getline (in_file, line);
cout << line << endl;
in_file.close();
}

Hiding an element in a

Hiding an element in a

I need your help
If
document.getElementById("file").children[1].style.display = "none" //Save
Hides the Save item, then
document.getElementById("edit").children[1].style.display = "none" //Add new
does not work properly and does not hide my edit menu item.
<div id="menuwrapper">
<div id="menu" style="width: 1001px; height: 20px">
<ul>
<li><a href="#nogo"><div id="div_rssims_file">File</div></a>
<ul id="file">
<li><a onclick="window.print()"><div
id="div_rssims_file_print">Print</div></a></li>
<li id="li_rssims_file_save"><a onclick="rssims_save()"><div
id="div_rssims_file_save">Save</div></a></li>
<li><a onclick="rssims_save();window.close()"><div
id="div_rssims_file_save_exit">Save & Exit</div></a></li>
<li><a onclick="window.close()"><div
id="div_rssims_file_exit">Exit</div></a></li>
</ul>
</li>
<li>
<a href="#nogo"><div id="div_rssims_edit">Edit</div></a>
<ul id="edit">
<li><a href="#nogo" onclick="rssims_addnew()"><div
id="div_rssims_edit_addnew">Add new</div></a></li>
<li><a href="#nogo" onclick="sims_delete()"><div
id="delete">Delete</div></a></li>
<li><a href="#nogo" onclick="sims_reset()"><div id="clear">Clear
Form</div></a></li>
</ul>
</li>
<li><a href="#nogo"><div id="div_rssims_view">View</div></a>
<ul>
<li><a href="#nogo"><div id="goto_first">&gt;&gt; Go to
First</div></a></li>
<li><a href="#nogo"><div id="goto_next">&gt;Go to Next</div></a></li>
<li><a href="#nogo"><div id="goto_prev">Go to Previous&gt;</div></a></li>
<li><a href="#nogo"><div id="goto_last">Go to Last&gt;&gt;</div></a></li>
</ul>
</li>
<li><a href="#nogo"><div id="div_rssims_reports">Reports</div></a>
<ul>
<li><a href="#nogo"><div id="export_excel">Export to Excel
Table</div></a></li>
<li><a href="#nogo" onclick="sims_compile_htmltable()"><div
id="export_html">Export to HTML Table</div></a></li>
<li><a href="#nogo" onclick="sims_compile_htmllist()"><div
id="export_list">Export to HTML List</div></a></li>
<li><a href="#nogo" onclick="sims_compile_contactcard()"><div
id="export_contact">Export as Contact Card</div></a></li>
</ul>
</li>
<li><a style="cursor: pointer;" onclick="sims_logoff()"><div
id="div_rssims_logoff">Logoff</div></a></li>
</ul>
</div>
</div>

break; inside a try block

break; inside a try block

As far as I am concerned after an exception is thrown the code that
follows is not executed in the try block so my question is - will it be a
good habit doing something like:
do{
// read input
try{
// code that throws exception
break;
}
catch (SomeException e){
// do some stuff here
}
}
while (true);
I wont to force the user to input until the input is valid and doesn't
throw an exception, is there a more elegant way to do it in case this is a
bad habit?

Composition of objects vs functions: Should I use one method interfaces or delegates?

Composition of objects vs functions: Should I use one method interfaces or
delegates?

C# is a multi paradigm language. With nesting interfaces and classes one
can get a composition of objects. This way a certain problem can be broken
down to a number of simple ones giving each component its own piece of the
puzzle to solve. The same trick can be done in a slightly different
manner, one can make a composition of functions each of which is
responsible of solving its own little task while all combined and
interconnected they give the answer to the main problem.
Following SOLID principles I found myself in a situation where 95% of my
interfaces carry just one method named do-something and the name of the
interface is something-doer. The class that implements such interfaces is
DI'ed with the a few components required to fulfill whatever that method
is supposed to do. Such approach is basically making a closure over a
function by hands. If so, why wouldn't I just go with delegates that do it
naturally and for free (no typing necessary)? If I go all the way
converting single method interfaces to delegates I will eliminate 95% of
them from my code making it look like written in functional language. But
this seems like a right thing to do unless there is some bold reason to
stick with interfaces. Is there?

How to get the DeleteParameter value in to the Code behind?

How to get the DeleteParameter value in to the Code behind?

I have a ListView that enables deleting, I also use SQLDatasource as
DataSource of the ListView, I have these 2 tables:
News table that contains news_id, title, etc.. and
Feedback table that contains feedback_id, comment, news_id(FK), etc...
I can delete a record that doesn't have comments but I get this error when
I try to delete a News that has a comments, the comments is from the table
'Feedback' that has a foreign key 'news_id' from the table 'News', I know
that to resolve this is I need to delete the records from the Feedback
table first. How can I achieve it? I'm thinking of using OnItemDeleting
Event in ListView and execute a query:
DELETE FROM Feedback WHERE news_id = @news_id
and then it can proceed to execute the DeleteCommand in the SQLDataSource
that is:
DeleteCommand="DELETE FROM [News] WHERE [news_id] = @news_id"
but then I got this error:
Must declare the scalar variable "@news_id".
this is my DeleteParameter:
<DeleteParameters>
<asp:Parameter Name="news_id" Type="Int32" />
</DeleteParameters>
how can i get the news_id from the DeleteParameter? any answer is
appreciated, thanks.

AngularJS: how to implement records per page using angularjs

AngularJS: how to implement records per page using angularjs

I need the following format "records per page" at the end of a table
Per page: 10 25 50
can any body help me! I am new to angularjs

Thursday, 26 September 2013

How to set reminder in iOS for a particular time and show it after 2 min interval again and again(five times) after that time

How to set reminder in iOS for a particular time and show it after 2 min
interval again and again(five times) after that time

I have value like
createdate = "2013-09-24 04:29:30";
I have to set a reminder on this time .I am using local notification to
set the reminder but i am not sure how to remove it after it occurs and
also how to invoke it again after two minutes of the reminder time.
Thanks in advance.

Wednesday, 25 September 2013

Passing error message for unauthorised user in the fancy box

Passing error message for unauthorised user in the fancy box

i have used this controller code: public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->Session->write('group_id', $this->Auth->user("group_id"));
$this->Session->write('username', $this->Auth->user("username"));
$this->Session->write('user_id', $this->Auth->user("user_id"));
//return $this->redirect($this->Auth->redirect());
if ( $this->Auth->user() && $this->Auth->user('group_id') == 1 )
{
//$this->Auth->allowedActions =
array($canAccess[0]['Acl']['action']);
$this->redirect('../users/admin_index');
}
else if ( $this->Auth->user() && $this->Auth->user('group_id')
== 2 ){
//$this->Auth->allowedActions =
array($canAccess[1]['Acl']['action']);
$this->redirect('../portal');
}
} else {
$this->Session->setFlash('username and password is invalid');
//$this->redirect($this->Auth->loginAction);
}
}
}
in my view i created an element and echoed it in the page i want it to
appear.i am getting the exact fancy box when clicked upon the content and
if my login is successful then it is redirecting to the correct page but
if the credentials are wrong it is taking me to my element page and
showing me invalid user name and password .but what exactly i want is that
this error message should appear in my fancy box only .

Thursday, 19 September 2013

Using loops to compute factorial numbers, Java

Using loops to compute factorial numbers, Java

I'm trying to compute the value of 7 factorial and display the answer, but
when I tried to look up a way to do this I kept finding code that was
written so that a number first had to be put in from the user and then it
would factor whatever number the user put in. But I already know what
number I need, obviously, so the code is going to be different and I'm
having trouble figuring out how to do this.
I tried this at first
public class Ch4_Lab_7
{
public static void main(String[] args)
{
int factorial = 7;
while (factorial <= 7)
{
if (factorial > 0)
System.out.println(factorial*facto…
factorial--;
}
}
}
But all it does is display 7*7, then 6*6, then 5*5, and so on, and this
isn't what I'm trying to do. Does anyone know how to do it correctly?

Configure Sublime Text 3 GIT Path

Configure Sublime Text 3 GIT Path

I keep getting an "Executable '['git']' was not found in PATH. Current
PATH" error message when trying GIT STATUS in Sublime Text 3. I have the
SublimeGit plugin installed.
I have the following in my Package Settings > Settings - User
"git_executables": {
"git": ["/usr/local/bin/git"],
"git_flow": ["/usr/local/bin/git", "flow"],
"legit": ["legit"]
}
I have read https://docs.sublimegit.net/quickstart.html, but it does not
go through windows paths.
Any help would be appreciated.

Can xtext propose styled string in template proposals?

Can xtext propose styled string in template proposals?

Can xtext propose styled string in template proposals? Normal
createCompletionProposal could have that but I didn't find any API
returning StryledString in ITemplateProposalProvider hierarchy.

Change Shopify-Logo of Admin-LogIn-Box

Change Shopify-Logo of Admin-LogIn-Box

Does anybody know how to change the default-shopify-logo, which appears at
the top of the log-in-box before getting to the admin-area?
Cheers, Tobi

How to find value of an attribute in a sub child node of an XML?

How to find value of an attribute in a sub child node of an XML?

I have a XML which has the following structure:
<Results>
<TestResultAggregation testName="MyOrder">
<Counters error="0" failed="1" timeout="0" aborted="0" inconclusive="0"/>
<InnerResults>
<UnitTestResult testName="TestMethod3" outcome="Failed">
<Output>
<ErrorInfo>
<Message>Assert.Fail failed. </Message>
<StackTrace>
at Random.UnitTest1.TestMethod3()
</StackTrace>
</ErrorInfo>
</Output>
</UnitTestResult>
<UnitTestResult testName="TestMethod2" outcome="Passed">
<Output>
</Output>
</UnitTestResult>
</InnerResults>
</TestResultAggregation>
When the result of 'outcome' attribute in 'UnitTestResult' is 'failed', I
have to display the value of 'ErrorInfo' and 'StackTrace' nodes too. The
catch here is that the above schema is not fixed. For eg,
<Results>
<UnitTestResult testName="TestMethod3" outcome="Failed">
<Output>
<ErrorInfo>
<Message>Assert.Fail failed. </Message>
<StackTrace>
at Random.UnitTest1.TestMethod3()
</StackTrace>
</ErrorInfo>
</Output>
</UnitTestResult>
<UnitTestResult testName="TestMethod2" outcome="Passed">
<Output>
</Output>
</UnitTestResult>
The above schema can also be generated dynamically.
How to write a code for the above requirement in C#??

Replacing special chars in a string with a single unique char

Replacing special chars in a string with a single unique char

I have a string like so:
string inputStr = "Name*&^%LastName*#@";
The following Regex will replace all the special chars with a '-'
Regex rgx = new Regex("[^a-zA-Z0-9 - _]");
someStr = rgx.Replace(someStr, "-");
That produces an output something like: Name---LastName---
How do I replace '---' with a single '-' so the output looks like this:
Name-LastName
So the question is how do I replace all the special chars with a single '-'?
Regards.

Wednesday, 18 September 2013

Apply Column Filtering in Gridview in asp.net

Apply Column Filtering in Gridview in asp.net

I have a gridview which is populated at runtime with a table with unknow
number of columns which are not known before hand.
I want to apply column filtering on all columns with Drop Down List.
How can I achieve it. Using Jquery, Linq or simple C sharp Coding.
Any help be highly appreciated
Thanks

Beginner Java Program to repeat user phrase

Beginner Java Program to repeat user phrase

My first post, so be gentle.
I am in an Intro to Programming class. We are covering loops after doing
the variables, classes, getters/setters, and constructors. I understand
how loops work. However, My confusion is in the directions. I have the
bare bones set up, but the instructions confuse me as I am trying to
figure out putting a method within another (if I understand correctly).
The directions are as follows:
UML Class Diagram: Learning Outcomes: „h Declare a class that is intended
to be instantiated „h Declare a method to provide a functionality „h
Create an instance of the class you declared „h Access the method using
the dot operator „h Increase your familiarity with UML class diagrams „h
Review the use of Scanner „h Create a project called LabParrot „h Add 2
files to the project: Parrot.java and ParrotTest.java „h In Parrot.java do
the following: „X Create a public class called Parrot „X Inside the class
create a public method called speak. The method speak has one String
parameter named word and no return value (i.e. return type void) The
method header looks like this: public void speak(String word) „X The
parrot repeats anything he is told. We implement this behavior by printing
the word passed as an argument. „h In ParrotTest.java create the main
method Inside the main method do the following: „X Create an instance of
Scanner named input „X Create an instance of Parrot named myParrot You
create a new instance by calling the default constructor like this: Parrot
myParrot = new Parrot(); „X Read in a text (i.e. use Scanner to let the
user choose what s/he would like to say to the parrot); make sure to
prompt the user before you read in the text Create a String variable
called text to temporarily store the input read „X Call the method speak
of the instance myParrot and pass the variable text as argument NOTE: the
variable name passed does not have to match the parameter name The method
call looks like this: myParrot.speak(text); Sample Output1: What would you
like to say to the parrot? hi hi Sample Output2: What would you like to
say to the parrot? how are you? how are you?
My code so far is this:
import java.util.Scanner;
public class LabParrot {
//begin method public void static void(String [] args) {
//set up variables
char String = word;
Scanner input = new Scanner(System.in);
//Obtain user input
System.out.println("What would you like to say to the parrot?");
word = input.nextLn();
}
}
Did I put everything in the correct place so far? Sorry if this seems
silly. I don't have too many similar examples to this assignment to figure
it out.

JoGL not drawing within a loop

JoGL not drawing within a loop

I have working on an OBJ model loader in JoGL for a few days, and can
obtain the vertices in the array draw: draw[face][vertex][x,y,z,or w] I
have tried several ways to render this array (i.e. VBO's) but none have
worked so far. I decided to attempt to render the face within a loop,
however, when I run the program nothing is rendered. Here is my code:
for(int i = 0; i < draw.length; i++){
gl.glBegin(GL.GL_TRIANGLE_STRIP);
//start drawing
for(int i2=0;i2<draw[i].length;i2++){
float[] xyzw = new float[4];
//grab all the vertex values
for(int i3=0; i3<draw[i][i2].length;i3++){
xyzw[i3]=draw[i][i2][i3];
}
gl.glColor3f(1.0f, 0.0f, 0.0f); // Set the current
drawing color to red
gl.glVertex3f(xyzw[0], xyzw[1], xyzw[2]);
}
gl.glEnd();
}
The peculiar thing is if I do this:
for(int i = 0; i < draw.length; i++){
gl.glBegin(GL.GL_TRIANGLE_STRIP);
//start drawing
for(int i2=0;i2<draw[i].length;i2++){
float[] xyzw = new float[4];
//grab all the vertex values
for(int i3=0; i3<draw[i][i2].length;i3++){
xyzw[i3]=draw[i][i2][i3];
}
gl.glColor3f(1.0f, 0.0f, 0.0f); // Set the current
drawing color to red
gl.glVertex3f(xyzw[0], xyzw[1], xyzw[2]);
gl.glVertex3f(0.0f, 0.0f, 0.0f); // Top
gl.glColor3f(0.0f, 1.0f, 0.0f); // Set the current
drawing color to green
gl.glVertex3f(1.0f, 0.0f, 1.0f); // Bottom Left
gl.glColor3f(0.0f, 0.0f, 1.0f); // Set the current
drawing color to blue
gl.glVertex3f(0.0f, 0.0f, 1.0f); // Bottom Right
}
gl.glEnd();
}
then I get a contorted shape, however without those extraneous vertices
nothing is rendered.

How to set a String ViewModel property on ReadioButton Check usin WPF?

How to set a String ViewModel property on ReadioButton Check usin WPF?

I am new to WPF and here I am trying to set a simple string property of my
viewModel when a particular radio button is checked on my window.
class ViewModel
{
string LanguageSettings
}
XAML looks like following:
<RadioButton Name="OptionEnglish" GroupName="LanguageOptions"
IsChecked="{Binding LanguageSettings}" Content="English"
HorizontalAlignment="Right" Width="760" />
<RadioButton Name="OptionChinese" GroupName="LanguageOptions"
IsChecked="{Binding LanguageSettings}" Content="Chinese" />
All I want here is that when English is selected I want Language Settings
to be set as English and same for Chinese. Is there any simple way to do
it? I also looked into some IValueConverter examples. Do I really need to
do that? is there any straightforward way to set that property?

How to run testng.xml from Command Prompt using org.testng.TestNG

How to run testng.xml from Command Prompt using org.testng.TestNG

I am trying to run testng.xml from command prompt. This is the command I'm
running:
C:\Users\sathmakur>java -cp
C:\Users\sathmakur.m2\repository\org\testng\testng\ 6.3.1\testng-6.3.1.jar
org.testng.TestNG test.xml
I get the following error: Exception in thread "main"
java.lang.NoClassDefFoundError: com/beust/jcommander/ ParameterException
at java.lang.Class.getDeclaredMethods0(Native Method) at
java.lang.Class.privateGetDeclaredMethods(Unknown Source) at
java.lang.Class.getMethod0(Unknown Source) at
java.lang.Class.getMethod(Unknown Source) at
sun.launcher.LauncherHelper.getMainMethod(Unknown Source) at
sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source) Caused by:
java.lang.ClassNotFoundException: com.beust.jcommander.ParameterExcep tion
at java.net.URLClassLoader$1.run(Unknown Source) at
java.net.URLClassLoader$1.run(Unknown Source) at
java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader.findClass(Unknown Source) at
java.lang.ClassLoader.loadClass(Unknown Source) at
sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at
java.lang.ClassLoader.loadClass(Unknown Source) ... 6 more
I'm new at using TestNG and Command Prompt. It would be a great help if
someone could shed some light.

jQuery increasing and decreasing div height based on scroll positioning

jQuery increasing and decreasing div height based on scroll positioning

jQuery increasing and decreasing div height based on scroll positioning.
Was wondering if any of you know of any way to do this in a good way.
Let's say i have a div with and id of "scroll-element" And when i scroll
down the page, let's say down like 500px it starts to increase to about
200px when scrolling down and decreasing to 0px when i scroll back up. I
tried a few methods but none have worked so far.

Math library against own library in C#

Math library against own library in C#

So we tried developing a math class in C# and we did. Comparing results
with the original math class for System.Math shows that we are always late
a little or a lot (trig methods particularly).
But the wonder comes when we are using basic methods like Absolut value
which does not contain loads of code apart from
if(value < 0) return -value;
else return value;
and still we are far behind.
I cannot make this abs method any smaller, using the ternary operator will
not help either I guess.
Is it because the System.Math would be written in C? Would it go faster if
we write it in native language, though it seems it won't change much I
read. Finally, could a dll work faster than a class and if so why and if
not ...well why too?
Thanks already.

FaceBook chat integration in my web based application[C#]

FaceBook chat integration in my web based application[C#]

Hi could anyone help me in integrating facebook chat box in my web based
application.
Is it possible to implemnt chat box in my website.

Tuesday, 17 September 2013

how change a boolean 30 days late of update_at in rails

how change a boolean 30 days late of update_at in rails

i have a list of records in Rails, and this records have a boolean field
to make it public or private. I what to change to private every public
record with update_at >= 30 days ago. And every record get the 30 days,
change automatic to boolean private.
But i don't know when to start. Advices, links and tips are welcome. Thank
you!

UDP with android

UDP with android

why UDP Android just once send [Please Help]
name class MainActivity
public class MainActivity extends Activity implements
android.view.View.OnClickListener { public static final String SERVERIP =
"192.168.5.255"; public static final int SERVERPORT = 4444; public
TextView text1; public EditText input; public Button btn; public boolean
start; public Handler Handler; static boolean isFinish = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1 = (TextView) findViewById(R.id.textView1);
input = (EditText) findViewById(R.id.editText1);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(this);
start = false;
new Thread(new Server()).start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
new Thread(new Client()).start();
Handler = new Handler() {
@Override
public void handleMessage(Message msg) {
String text = (String) msg.obj;
text1.append(text);
}
};
}
this class Client
@SuppressLint("NewApi")
public class Client implements Runnable {
@Override
public void run() {
while (start == false) {
}
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
updatetrack("Client: Start connecting\n");
DatagramSocket socket = new DatagramSocket();
byte[] buf;
if (!input.getText().toString().isEmpty()) {
buf = input.getText().toString().getBytes();
} else {
buf = ("Default message").getBytes();
}
DatagramPacket packet = new DatagramPacket(buf, buf.length,
serverAddr, SERVERPORT);
updatetrack("Client: Sending '" + new String(buf) + "'\n");
socket.send(packet);
updatetrack("Client: Message sent\n");
updatetrack("Client: Succeed!\n");
} catch (Exception e) {
updatetrack("Client: Error!\n");
}
}
}
this class Client
public class Server implements Runnable {
@Override
public void run() {
while (start = false) {
try {
InetAddress serverAddress = InetAddress.getByName(SERVERIP);
updatetrack("nServer: Start connectingn");
DatagramSocket socket = new DatagramSocket(SERVERPORT,
serverAddress);
byte[] buffer = new byte[17];
DatagramPacket packet = new DatagramPacket(buffer,
buffer.length);
updatetrack("Server: Receivingn");
socket.receive(packet);
updatetrack("Server: Message received:"
+ new String(packet.getData()) + "'n");
updatetrack("Server : Succed!n");
} catch (Exception e) {
updatetrack("Server: Error!n" + e.getMessage());
}
}
}
}
public void updatetrack(String s) {
Message msg = new Message();
String textTochange = s;
msg.obj = textTochange;
Handler.sendMessage(msg);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.button1)
start = true;
}
}
help me please ? why just once send message Thanks before

How does this curl command differ from my php code?

How does this curl command differ from my php code?

I am simply trying to duplicate this curl command in PHP:
curl -X POST -H 'Content-Type: application/xml' -u username:password
https://api.company.com/api/path
This is the PHP code I am using:
$ch = curl_init("https://api.company.com/api/path");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/xml"));
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch); // $response is null
$info = curl_getinfo($ch); // $info['http_code'] is 400
While my shell command is successful and I get data back from the server,
this PHP code fails -- the server returns a 400 error. As far as I know,
the PHP code and the shell command are effectively identical, so what's
the difference I am missing?

Monitor bandwidth of a process

Monitor bandwidth of a process

How can i monitor network statistics of my application? Similar to what
Resource Monitor does.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa372266(v=vs.85).aspx

My wpf application can save a notepad file on the fixed path i provided in app.config as a key but i want it to be saved on the desktop of...

My wpf application can save a notepad file on the fixed path i provided in
app.config as a key but i want it to be saved on the desktop of...

private void WriteToFile(TextRange textRange)
{
using (StreamWriter oWriter = new
StreamWriter(ConfigurationManager.AppSettings["folderpath"],
true))
{
oWriter.WriteLine(DateTime.Now.ToString());
oWriter.WriteLine("*****************************************************************************");
oWriter.WriteLine(textRange.Text);
oWriter.WriteLine("*****************************************************************************");
oWriter.WriteLine("*****************************************************************************");
oWriter.Write("$");
}
MessageBox.Show(folderpath);
}
the folderpath in the code is a key in app.config with
value="C:\Users\MyPC\Desktop\textfile.txt"
if i delete the key and initialize a string in the code, it shows an error
of Value cannot be null. Please help!

Sunday, 15 September 2013

Unfocus on all JTextFields

Unfocus on all JTextFields

How do i change the focus to be on a different JTextField? Currently when
my application loads, it is picking (what appears to be) a random
JTextField to set focus to!
I've tried
text.setFocusable(true);
text.requestFocusInWindow();
text.requestFocus(true);
text.requestFocus();
but no luck here. I've also tried How to UnFocus a JTextField but i
haven't had any luck with this working either.
The reason why I would like to not focus on the JTextFields is to avoid
the hints from not appearing when the application first loads. See image:
As you can see from the image, there is no hint on one of the JTextFields...
Any ideas? Thanks in advance..

Regular Expression to limit consecutive capitalization

Regular Expression to limit consecutive capitalization

I need to validate an input so that no "individual" word within the
textbox can contain more than 3 consecutive capital letters. The following
doesn't seem to be working:
[A-Z]{3,}
This is a VB application.
Thank you very much.

Rotating camera around an off center sprite

Rotating camera around an off center sprite

I am making a 2d top down game. When the user moves their mouse I want the
sprite to basically point to the mouse. I was able to get that part
working if the sprite is in the center of the screen it works fine.
My problem is I want the sprite to be in the lower fourth of the screen
So what I have tried is setting the camera to the players position
rotating it and then moving it back to having the player at 1/4 of the way
up the screen but in that he case he just orbits the center of the camera
instead of the camera rotating around him.

This is my code so far that I have worked out.
mouseX = Gdx.input.getX();
mouseY = Gdx.input.getY();
Vector3 mouse = new Vector3(mouseX, mouseY, 0);
Main.cam.unproject(mouse);
Vector3 pos = new Vector3(currx, curry, 0);
pos.sub(mouse);
vec.set(pos.x, pos.y);
angle = vec.angle();
Main.cam.position.set(currx, curry, 0f);
float camAngle = -getCameraCurrentXYAngle(Main.cam)+180;
e.setRotations(angle);
setPosition(currx, curry);
Main.cam.rotate((camAngle - angle)+180);
s_.setRotation(angle);
Main.cam.position.set(currx, curry+(Main.VIEWPORT_HEIGHT/4), 0f);



public float getCameraCurrentXYAngle(OrthographicCamera cam){
return (float)Math.atan2(cam.up.x,
cam.up.y)*MathUtils.radiansToDegrees;
}

Xcode 5 doesn't let me export unsigned cocoa application

Xcode 5 doesn't let me export unsigned cocoa application

When I try to export a cocoa application in XCode 5 GM (which probably
isn't anymore under NDA, if it is it will be off tomorrow) doesn't give me
the option to export an unsigned application as it did in xcode 4.6 < When
I pick up an archive and select export as application as shown here:

In the next screen I have no chances to save it as an unsigned
application, as I did before.
Xcode 5:

Xcode 4:

Any Idea on why? is this a bug?
Thanks

ajax page navigation not working after htaccess rewrite

ajax page navigation not working after htaccess rewrite

i use .htaccess to rewrite my url from
/list.php?pat=free&mainCol=maincate&subCol=shoes
to
/maincate/shoes
after rewrite, the ajax next page button is not working anymore. it should
load list_pull.php from same folder as list.php
$.post("list_pull.php",{
pageCurrent:pageClick,
pullSubCol:$("#pullSubCol").val()});
and the htaccess is like this
RewriteRule ^([^/.]+)/([^/.]+)$ /list.php?pat=free&mainCol=$1&subCol=$2 [L]
i tried use full path http://www.mydomain.com/list_pull.php - not working
i tried creating a folder "maincate" and put listpull.php inside, still
not working.
dont know if my question is clear enough, been trying to figure it out for
2 days now, still no luck.
thanks in advance for help!!

jQuery UI Resize with table and colspans

jQuery UI Resize with table and colspans

I need to implement jQuery UI Resize effect to a table. My table has
colspans and with equal to 100%. This the main problem. Without that
everything simply works fine. What can I do to correct this behaviour?
<table style="width: 100%">
<tr>
<th colspan="3">Table</th>
</tr>
<tr>
<th>26/12</th>
<th>27/12</th>
<th>28/12</th>
</tr>
<tr>
<td>123</td>
<td>123</td>
<td>123</td>
</tr>
</table>
$(function () {
$('table th').resizable({
handles: 'e',
minWidth: 18
});
});
Demo: http://jsfiddle.net/Helid/JvELx/

toCharArray() removing zeros from a string

toCharArray() removing zeros from a string

I have the following (hex) string: 612b048b4e15540d31f5eaa955bea2a0
(StringBuffer sbt), which I convert to char array and iterate through it
like that:
for (char c : sbt.toString().toCharArray()){
//...
}
and do some replacements.
The problem is that I'm losing the 0 characters inside the string - how do
I avoid it?

Saturday, 14 September 2013

What's the standard way of implementing an automaton with not-transitions?

What's the standard way of implementing an automaton with not-transitions?

The naive implementation of a FA would have the node look like:
struct Node {
string label;
Node*[char] trans;
}
But what if one of your transitions is "![a]" (anything but the char 'a').
And your alphabet is too huge to store all possible chars that are not
'a'. Do you see what I mean?

Why doesn't this produce ambiguous implicit error?

Why doesn't this produce ambiguous implicit error?

I expected this code to fail with "error: ambiguous implicit values",
however it does in fact compile and run:
object AmbiguousImplicitsShouldntCompile extends App {
class A {def x = 1}
class B extends A { override def x = 2}
def f(implicit i: A) = i.x
implicit val a = new A
implicit val b = new B
println(f) // prints 2
}
Is this a bug in scala? Or is this correct behavior? I tried reading the
Scala Language Specification for anything relevant, but the parts on
implicit parameter resolution and overloading resolution are quite dense.

How do I convert the html of a website popup into a mobile compatible site?

How do I convert the html of a website popup into a mobile compatible site?

I've got a popup what appears on my website with the following code, it
uses the async-twitter library to connect/authorize with twitter.
How can I turn the following code into a mobile compatible site so it does
the following:
1) Works with Safari on iOS (Apple Devices)
2) Is centered on mobile devices instead of being off center...
<!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">
<head>
<script
src="http://platform.twitter.com/anywhere.js?id=[twitter-apikey]&v=1"
type="text/javascript"></script>
<!--STYLE-->
<style type="text/css">
body {background-color: #10661A; font-family:Arial, Helvetica, sans-serif;}
#logo {background-image:url(\'img/logo.png\'); width: 770px; height:
104px; }
#content { background-color:#FFF; width: 770px; hddeight: 334px; }
.connect { width: 249px; height:49px; display:block;
background:transparent url(\'img/button.png\') center top no-repeat; }
.connect:hover { background-image: url(\'img/buttonhover.png\'); }
.title { color: #1c1c1c; padding-top: 20px; padding-left: 20px;
margin-bottom: 20px; font-weight: bold; margin-top: 0px; }
.tweet { padding: 7px 100px; font-size:13px; line-height:19px;
margin-left: 20px; margin-right: 20px; text-align:left; color: #343434;
background-color: #eeeeee; border: 1px solid #e0e0e0; }
.link { font-style:italic; font-size:13px; line-height:19px; color:
#197da4; }
.link2 { font-size:11px; text-decoration:underline; line-height:19px;
color: #c2eeff; }
.account { font-weight: bold; font-size:14px; line-height:19px; margin: 0
20px 10px 20px; padding-top: 7px; padding-bottom: 7px; text-align:center;
color: #3e3e3e; background-color: #eeeeee; border: 1px solid #e0e0e0; }
.button { background-image:url(\'img/button.png\');
background-repeat:no-repeat; color:#FFF; font-size:16px;
text-decoration:none; padding: 5px 33px 5px 33px; font-weight: bold;
width: 284px; }
.ads { font-size:11px; text-align:center; color:#FFF; margin-top: 25px; }
.p1 { font-size: 13px; color: #7f7f7f; text-align:center; margin: 0px;
padding-top: 10px; line-height: 18px; }
.line-separator{height:1px; border-bottom:1px solid #c8dbe3; width: 730px;
margin-left: 20px; margin-top: 10px; }
</style>
<!--END STYLE-->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>[title]</title>
</head>
<body>
<script type="text/javascript">
twttr.anywhere(function (T) {
T("#tweet").linkifyUsers();
T("#account").linkifyUsers();
T.hovercards();
});
</script>
<div id="logo"></div>
<div id="content">
<p class="p1">Stuff here... Stuff here... Stuff here... Stuff
here... </p>
<p class="p1">Stuff here... Stuff here... Stuff here... Stuff
here...</p>
<div class="line-separator"></div>
<p class="title">Stuff here... Stuff here... Stuff here... Stuff
here... </p>
<center><a href="[twitter-authorization-url]" class="connect"
title="Click to authorize with twitter"></a></a></center>
</div>
<p class="ads">Copyright &copy; 2013 <a href="http://website.com/"
class="link2">website</a>. All Rights Reserved.</<p>
</body>
</html>
I would greatly appreciate any help possible.
Thanks in advance - Hyflex

Want to show the domain with full page url without shoing the forwarded domain

Want to show the domain with full page url without shoing the forwarded
domain

I'm forwarding a domain to another using IFRAME. so what ever the link is
it shows only the domain, not the path. Is it possible to show the path in
this case?? I only want to hide the domain on which the site is hosted and
want to show the domain which I'm forwarding.
ex: newdomain.com forwarding to olddomain.com now its showing
newdomain.com all time. But I want to show the path of the page after
newdomain.com in url

Kendo grid group header customize to show the value and more

Kendo grid group header customize to show the value and more

I have a Kendo grid that is groupable. The initial display needs to show
all data items with no groupings displayed, i.e no 'group' and
'groupHeaderTemplate' are defined.
The grid contains a column (Suspension) where the value displayed is a
translated dataitem value, i.e. if value > 10, display '*'.
When the user drags the Suspension column header cell to group, how can
you customize the group header to show the value that it is grouping on
plus the display 'value', i.e. 10-* ?

calling a function in python got nothing instead

calling a function in python got nothing instead

I got a code like this.
....
class SocketWatcher(Thread):
....
def run(self):
....
TicketCounter.increment() # I try to get this function
...
....
class TicketCounter(Thread):
....
def increment(self):
...
when I run the program I got this error.
TypeError: unbound method increment() must be called with TicketCounter
instance as first argument (got nothing instead)
i there any way that I can call the increment() function from
TicketCounter Class to the SocketWatcher Class? or Does my calling is
wrong...

Performing Analytics over Cassandra DB

Performing Analytics over Cassandra DB

I am working for a small concern and very new to apache cassandra.
Studying about cassandra and performing some small analytics like sum
function on cassandra DB for creating reports. For the same, Hive and
Accunu can be choices.
Datastax Enterprise provides the solution for Apache Cassandra and Hive
Integration. Is Datastax Enterprise is the only solution for such
integration. Is there any way to resolve the hive and cassandra
integration. If so, Can I get the links or documents regarding the same.
Is that possible to work the same with the windows platform.
Is any other solution to perform analytics on cassandra DB?
Thanks in advance .

what is wrong with these cookies

what is wrong with these cookies

<?php
include "some.php";//that s for mysql_connect
session_start();
$uid=$_REQUEST['uid'];
//main blocking
if(isset($_COOKIE['mainblocking'])){echo '1';}else{echo '2';}
....
everytime it throws 2;i set the cookie with that php file
<?php
setcookie("mainblocking", "1", time()+3600) or die("yeah"); ?>
can anybody tell me what s wrong with this code and what is the lack of my
knowledge by the way interesting thing is it throws 1 in that one
<?php
if(isset($_COOKIE['mainblocking'])){echo '1';}else{echo 2;} ?>
somebody help me plzzzz :))//im running out of my mind

Friday, 13 September 2013

Pass URL as parameter in silex controller

Pass URL as parameter in silex controller

I want to pass a url as parameter to a controller as like below:
$api->get('/getfile/{fileurl}', function(Request $request, $fileurl){
//do something
}
Here {fileurl} can be a valid http url. However, the above mapping isn't
working and resulting 404(may be because of the slashes in the {fileurl}
part?) . How to solve it to accept the $url in $fileurl variable?

how can we handle serial no for multipule users in sql table

how can we handle serial no for multipule users in sql table

how can manage the serial no for multiple users to enter records.net at
same time in one table in SQL-SERVER. now for single user i read the last
serial no and show it text box. its working.if 2 user insert a record at
same time serial no duplication error coming.whats a solution.

Creating new instance of esri map

Creating new instance of esri map

I have an esri arc gis map. I create my map div, load that data to the map
via an ajax call. On a hyper link the jquery dialog is opened and the map
and data is loaded in there. Works great until I close and open a new
link. The same map appears and nothing changes.
V is the line number passed in from the hyper link. On each click of a new
hyper link V is changing but the map data isnt. In my dialog on the close
event i reloaded the whole page while this worked it was inefficient. The
best solution i've seen is using the map.destroy method but any time I put
that in the code it destroys the map before it even opens. Let me know if
you need anything else.
Thanks
Here is the code:
function loadData(v)
{
var varId = v;
var regType = 1;//MSA
var d =
{
varId: varId,
regionType: regType,
};
$("#loading").show();
$.ajax({
type: "GET",
url: WebRoot + "ws/GIS.asmx/CensusData",
data: d,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
fipsData = data.d;
openBox(v, d);
init(varId);
initUI();
addFeatureLayers();
$("#loading").hide();
} //ends success function
}); //ends ajax call
}; //ends message

OOP and Persistence

OOP and Persistence

In the spirit of ask don't tell and never let an object get into an
invalid state oop design, I'm wondering how persistence would be handled
in a dynamic environment.
For a contrived example, imagine you need to write a POS application for
an airline. You can only sell seats that are available. Seats are grouped
such that plane -> sections -> rows -> seats. If a section is unavailable
then all rows and therefore seats in that section are also unavailable.
And obviously if a row in unavailable then all seats in the row are also
not available.
Now the environment is highly dynamic in that maintenance personnel may be
making sections, rows, or seats available/unavailable frequently. Further,
imagine it's somewhat expensive to build the airplane object graph.
However without constructing the entire graph for each sale attempt I
don't see how you can keep business rules out of the persistence layer,
which in my mind is an absolute must.
Is oop just not a viable choice for this kind of problem?

User input first and last name , print out intisials java eclipse

User input first and last name , print out intisials java eclipse

So , im having a piece of trouble here , tried with tutorials to fix it
but nothing really helped me out saw something about printout string 0,1
etc but didnt work eather.
What the program does atm : Asks user for first/last name and prints it
out first +last name
what i want it to do is print out the intisials of the users first and
last name, any ideas how to fix this? Please help , Thanks in advance!
My code looks like this atm
package com.example.sträng.main;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
String firstName,
lastName;
//Create scanner to obtain user input
Scanner scanner1 = new Scanner( System.in );
//obtain user input
System.out.print("Enter your first name: ");
firstName = scanner1.nextLine();
System.out.print("Enter your last name: ");
lastName = scanner1.nextLine();
//output information
System.out.print("Your first name is " + firstName + " and your
last name is "+ lastName);
}
}

Thursday, 12 September 2013

Can not download sources with Intellij Idea community 12.1.4 and maven 3.0.5

Can not download sources with Intellij Idea community 12.1.4 and maven 3.0.5

I click "download sources and documentation" in Intellij Idea Community
Edition 12.1.4 and get error that sources can not be downloaded. But when
I try:
mvn dependency:sources
All sources are downloaded.
What is the problem?
P.S. I have checked that Idea use the same maven that use in console.
There are not any "off line" mode buttons triggered in Idea.

How to caculate the absolute value for an array in python?

How to caculate the absolute value for an array in python?

How to caculate the absolute value for an array in python?
for example: a = [5,-2,-6,5]
I want to know the max of abs(a), and the answer should be 6. Thank you!

JSF + Primefaces + CRUD: Running a custom query

JSF + Primefaces + CRUD: Running a custom query

OOTB I've got two database tables. They have several columns mostly of
varchar types, each have an int id column as the primary key. I'm using
Netbeans and JPA and have a pretty cool PrimeFaces generic app that I've
altered to use the auto generated Entity.java, Controller.java and
Facade.java pages. However, I'm PrimeFaces and JPA... I would like to
write a "new" query and run it. I've spent hours googling and testing
different ways with zero success. I simply want to know the easiest way to
either add a new query to the Entity's NamedQueries list for example:
Here's the first table called t_units as it's formal name in mysql.
@Named("tUnits")
@Entity
@Table(name = "t_units")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "TUnits.findAll", query = "SELECT t FROM TUnits t"),
@NamedQuery(name = "TUnits.findById", query = "SELECT t FROM TUnits t
WHERE t.id = :id"),
@NamedQuery(name = "TUnits.findByMake", query = "SELECT t FROM TUnits
t WHERE t.make = :make"),
@NamedQuery(name = "TUnits.findByModel", query = "SELECT t FROM TUnits
t WHERE t.model = :model"),
@NamedQuery(name = "TUnits.findByYear", query = "SELECT t FROM TUnits
t WHERE t.year = :year"),
@NamedQuery(name = "TUnits.findByFuelType", query = "SELECT t FROM
TUnits t WHERE t.fuelType = :fuelType"),
@NamedQuery(name = "TUnits.findByOrigPurchaseDate", query = "SELECT t
FROM TUnits t WHERE t.origPurchaseDate = :origPurchaseDate"),
@NamedQuery(name = "TUnits.findByOwner", query = "SELECT t FROM TUnits
t WHERE t.owner = :owner"),
@NamedQuery(name = "TUnits.findByOperator", query = "SELECT t FROM
TUnits t WHERE t.operator = :operator"),
@NamedQuery(name = "TUnits.findByDecommFlag", query = "SELECT t FROM
TUnits t WHERE t.decommFlag = :decommFlag"),
@NamedQuery(name = "TUnits.findByPoNum", query = "SELECT t FROM TUnits
t WHERE t.poNum = :poNum"),
@NamedQuery(name = "TUnits.findByServiceNum", query = "SELECT t FROM
TUnits t WHERE t.serviceNum = :serviceNum"),
@NamedQuery(name = "TUnits.findByOrigPurchasePrice", query = "SELECT t
FROM TUnits t WHERE t.origPurchasePrice = :origPurchasePrice"),
@NamedQuery(name = "TUnits.myNewQuery", query = "select t from TUnits
t where t.decommFlag = 'false'")})
public class TUnits implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Size(max = 255)
@Column(name = "make")
private String make;
@Size(max = 255)
@Column(name = "model")
private String model;
@Size(max = 255)
@Column(name = "year")
private String year;
@Size(max = 255)
@Column(name = "fuel_type")
private String fuelType;
@Basic(optional = false)
@NotNull
@Column(name = "orig_purchase_date")
@Temporal(TemporalType.DATE)
private Date origPurchaseDate;
@Size(max = 255)
@Column(name = "owner")
private String owner;
@Size(max = 255)
@Column(name = "operator")
private String operator;
@Basic(optional = false)
@NotNull
@Column(name = "decomm_flag")
private boolean decommFlag;
@Size(max = 255)
@Column(name = "po_num")
private String poNum;
@Size(max = 255)
@Column(name = "service_num")
private String serviceNum;
// @Max(value=?) @Min(value=?)//if you know range of your decimal
fields consider using these annotations to enforce field validation
@Basic(optional = false)
@NotNull
@Column(name = "orig_purchase_price")
private BigDecimal origPurchasePrice;
public TUnits() {
}
public TUnits(Integer id) {
this.id = id;
}
public TUnits(Integer id, Date origPurchaseDate, boolean decommFlag,
BigDecimal origPurchasePrice) {
this.id = id;
this.origPurchaseDate = origPurchaseDate;
this.decommFlag = decommFlag;
this.origPurchasePrice = origPurchasePrice;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getFuelType() {
return fuelType;
}
public void setFuelType(String fuelType) {
this.fuelType = fuelType;
}
public Date getOrigPurchaseDate() {
return origPurchaseDate;
}
public void setOrigPurchaseDate(Date origPurchaseDate) {
this.origPurchaseDate = origPurchaseDate;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public boolean getDecommFlag() {
return decommFlag;
}
public void setDecommFlag(boolean decommFlag) {
this.decommFlag = decommFlag;
}
public String getPoNum() {
return poNum;
}
public void setPoNum(String poNum) {
this.poNum = poNum;
}
public String getServiceNum() {
return serviceNum;
}
public void setServiceNum(String serviceNum) {
this.serviceNum = serviceNum;
}
public BigDecimal getOrigPurchasePrice() {
return origPurchasePrice;
}
public void setOrigPurchasePrice(BigDecimal origPurchasePrice) {
this.origPurchasePrice = origPurchasePrice;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id
fields are not set
if (!(object instanceof TUnits)) {
return false;
}
TUnits other = (TUnits) object;
if ((this.id == null && other.id != null) || (this.id != null &&
!this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entities.TUnits[ id=" + id + " ]";
}
}
The last line "TUnits.myNewQuery" is the query I added that I'd like to
run and display in a new PrimeFaces Datatable. Im not 100% sure it will
even run.
Here's the TUnitsController.java Class. AGAIN, these were autogen classes
by NetBeans. I have made a few basic changes to get the current tables
populating just like the auto gen List pages do...
@Named("tUnitsController")
@RequestScoped
public class TUnitsController implements Serializable {
EntityManager em;
private TUnits current;
private DataModel items = null;
@EJB
private controllers.TUnitsFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public TUnitsController() {
}
public TUnits getSelected() {
if (current == null) {
current = new TUnits();
selectedItemIndex = -1;
}
return current;
}
private TUnitsFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
@Override
public int getItemsCount() {
return getFacade().count();
}
@Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new
int[]{getPageFirstItem(), getPageFirstItem() +
getPageSize()}));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (TUnits) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() +
getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new TUnits();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("TUnitsCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e,
ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (TUnits) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() +
getItems().getRowIndex();
return "Edit";
}
public String prepareEditt() {
current = (TUnits) getItems().getRowData();
System.out.println("Current: " + current);
updatee();
//selectedItemIndex = pagination.getPageFirstItem() +
getItems().getRowIndex();
return "viewUnitDetails";
}
public String updatee() {
try {
System.out.println("updatee");
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("TUnitsUpdated"));
//FacesMessage msg = new FacesMessage("Unit Edited");
//FacesContext.getCurrentInstance().addMessage(null, msg);
return "viewUnitDetails";
} catch (Exception e) {
JsfUtil.addErrorMessage(e,
ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public void onCancel(RowEditEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Cancelled",""));
}
public String update() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("TUnitsUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e,
ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (TUnits) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() +
getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("TUnitsDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e,
ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getFacade().count();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getFacade().findRange(new int[]{selectedItemIndex,
selectedItemIndex + 1}).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
Here is my xhtml page viewTireInventory.xhtml. This web page simply uses a
template and displays one primefaces datatable.
<?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:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="./resources/css/default.css" rel="stylesheet"
type="text/css" />
<link href="./resources/css/cssLayout.css" rel="stylesheet"
type="text/css" />
</h:head>
<body>
<ui:composition template="./WEB-INF/templates/template.xhtml">
<ui:define name="content">
<!-- Datatable goes here -->
<h:form id="form">
<p:growl id="messages" showDetail="true" life="1100"/>
<h:panelGroup
rendered="#{tUnitsController.items.rowCount > 0}">
<h:outputText
value="#{tUnitsController.pagination.pageFirstItem
+ 1}..#{tUnitsController.pagination.pageLastItem +
1}/#{tUnitsController.pagination.itemsCount}"/>&nbsp;
<h:commandLink
action="#{tUnitsController.previous}"
value="#{bundle.Previous}
#{tUnitsController.pagination.pageSize}"
rendered="#{tUnitsController.pagination.hasPreviousPage}"/>&nbsp;
<h:commandLink action="#{tUnitsController.next}"
value="#{bundle.Next}
#{tUnitsController.pagination.pageSize}"
rendered="#{tUnitsController.pagination.hasNextPage}"/>&nbsp;
<p:dataTable var="item"
value="#{tUnitsController.items}" id="items"
editable="true" resizableColumns="true"
paginator="false" rows="20" sortMode="multiple">
<f:facet name="header">
View All Units
</f:facet>
<p:ajax event="rowEdit"
listener="#{tUnitsController.prepareEditt}"
update=":form:messages" />
<p:ajax event="rowEditCancel"
listener="#{tUnitsController.onCancel}"
update=":form:messages" />
<p:column headerText="Unit ID"
sortBy="#{item.id}" style="font-size: 12px">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{item.id}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{item.id}" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Make"
sortBy="#{item.make}" style="font-size: 12px">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{item.make}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{item.make}" />
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Model"
sortBy="#{item.model}" style="font-size:
12px">
<p:cellEditor>
<f:facet name="output">
<h:outputText
value="#{item.model}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{item.model}"
label="Model"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Year"
sortBy="#{item.year}" style="font-size: 12px">
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{item.year}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{item.year}"
label="Year"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Purchase Price"
style="font-size: 12px">
<p:cellEditor>
<f:facet name="output">
<h:outputText
value="#{item.origPurchasePrice}"
/>
</f:facet>
<f:facet name="input">
<p:inputText
value="#{item.origPurchasePrice}"
label="Purchase Price"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Fuel Type"
style="font-size: 12px">
<p:cellEditor>
<f:facet name="output">
<h:outputText
value="#{item.fuelType}" />
</f:facet>
<f:facet name="input">
<p:inputText
value="#{item.fuelType}"
label="Fuel Type"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Owner" style="font-size:
12px">
<p:cellEditor>
<f:facet name="output">
<h:outputText
value="#{item.owner}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{item.owner}"
label="Owner"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Operator"
style="font-size: 12px">
<p:cellEditor>
<f:facet name="output">
<h:outputText
value="#{item.operator}" />
</f:facet>
<f:facet name="input">
<p:inputText
value="#{item.operator}"
label="Operator"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Out of Stock"
style="font-size: 12px">
<p:cellEditor>
<f:facet name="output">
<h:outputText
value="#{item.decommFlag}" />
</f:facet>
<f:facet name="input">
<p:inputText
value="#{item.decommFlag}"
label="Remove From Stock"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="PO #" style="font-size:
12px">
<p:cellEditor>
<f:facet name="output">
<h:outputText
value="#{item.poNum}" />
</f:facet>
<f:facet name="input">
<p:inputText value="#{item.poNum}"
label="PO #"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Service #"
style="font-size: 12px">
<p:cellEditor>
<f:facet name="output">
<h:outputText
value="#{item.serviceNum}" />
</f:facet>
<f:facet name="input">
<p:inputText
value="#{item.serviceNum}"
label="Service #"/>
</f:facet>
</p:cellEditor>
</p:column>
<p:column headerText="Edit &amp; Tires"
style="width: 6%; font-size: 12px">
<p:rowEditor/>
<p:commandLink id="viewInv" value="Tires"/>
</p:column>
</p:dataTable>
</h:panelGroup>
</h:form>
<!-- End of Datatable -->
</ui:define>
</ui:composition>
</body>
</html>
So how do I get my custom query to populate this data table? Currently,
using the default "items" from TUnitsController WILL populate this table,
but I have found it EXTREMELY frustrating to try and customize anything
with JPA or Jquery. The CRUD auto generated pages are really complicated
and restricting.