Thursday, 3 October 2013

convert unicode to string in java

convert unicode to string in java

URL with string text
HttpGet request = new
HttpGet("http://localhost:8090/Servlet/ServletTest?to=3274&from=34875&sms=testtest");
to get value of above url parameter i used following code
while(en.hasMoreElements())
{
Object o1=en.nextElement();
to1=(String)o1;
to2=request.getParameter(to1);
Object o2=en.nextElement();
from1=(String)o2;
from2=request.getParameter(from1);
Object o3=en.nextElement();
text1=(String)o3;
text2=request.getParameter(text1);
}
Url with unicode text
HttpGet request = new
HttpGet("http://localhost:8090/Servlet/ServletTest?to=3274&from=34875&sms=0915094D092F093E00200917093E0902091709410932094000200915094B");
How to get parameter value as string from unicode value

Wednesday, 2 October 2013

JRebel caused WELD-001414 Bean name is ambiguous

JRebel caused WELD-001414 Bean name is ambiguous

We created a multi-module maven project but is currently encountering the
error in the title on deploy.
Here's the setup (those with parenthesis rebel means there is a jrebel
configuration in that project):
-MainProject: --Model (rebel) --ProjectA ---Web (rebel) ---EJB (rebel)
---Config (rebel)
The weird thing is, if I removed the rebel configuration in EJB it deploys
successfully.
The error:
Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001414 Bean
name is ambiguous. Name bayadDunningInputHistoryBean resolves to beans
[Managed Bean [class xxx.yyy.ClassBean] with qualifiers [@Any @Default
@Named], Managed Bean [class xxx.yyy.ClassBean] with qualifiers [@Any
@Default @Named]]
Base on the error, could it be that the same class is loaded twice?

JQuery Spinner unselectable after entering zero

JQuery Spinner unselectable after entering zero

I'm having a problem using the JQuery spinner widget. If I manually enter
a value of 0 into the text field (not using the arrows for the spinner,
just entering a value directly), then the spinner greys out and I can not
select it. I have to completely restart the single board microcomputer to
get it back. Any ideas what could be causing this (code below)?
$(function() {
var spinner = $( "#spinner_current" ).spinner({min: 0, max: 100,
stop: function() { dlpCurrent();} });
});
<label for="spinner_current">Illumination Power (%) </label><input
id="spinner_current" style="width:30px" name="value">

HTML-FormHandler Updating fields with the SET data type

HTML-FormHandler Updating fields with the SET data type

I have MySQL table which uses field with the SET data type, for example
`color` SET( 'red', 'green', 'blue' )
I can not find the right way to use HTML-FormHandler for this field. I
tried to use the next variant. I have create form with multiple field
has_field 'color' => ( type => 'Multiple', size => 3,
options => [ { value => 'red', label => 'Red'},
{ value => 'green', label => 'Green'},
{ value => 'blue', label => 'Blue'} ] );
But this does not work. I think because, DBIx returns string value for SET
field ('red,blue') but HTML-FormHandler needs array ref (['red', 'blue']).
Is there any proper way to use HTML-FormHandler for such fields?

Taknig Backup from one server to another server in SUSE SP1 Enterprise Server

Taknig Backup from one server to another server in SUSE SP1 Enterprise Server

I am using SUSE SP1 Enterprise Server installed in two machine (Main
Server and Database Server) within LAN. and I want to Bakcup from Main
Server in Database server. please help me.

Tuesday, 1 October 2013

pos argument to networkx.draw() not working

pos argument to networkx.draw() not working

I'm trying to generate images of subgraphs of a graph where nodes should
appear in the same locations for both graphs.
Based on the documentation for networkx.draw the "pos" argument to the
draw function accepts a dictionary which specifies the positions of the
nodes. I see several examples where people use the pos argument similar to
this pattern:
positions = networkx.spring_layout( GraphObject )
networkx.draw( GraphObject, positions )
However, when I try this I find that the positions is apparently ignored -
or at least when I draw a graph and record the position of its nodes, and
then use that dictionary as the pos argument for drawing a subgraph the
corresponding nodes are not plotted in the same locations.
Here is a simple reproducer that demonstrates the problem. I think what
this code should do is create two .png files of two graphs "g" and "h."
The nodes "c" and "d" should be in the same position in the drawing of "h"
as they are in "g" - however they are not.
#!/usr/bin/python
import matplotlib.pyplot as plt
import networkx as nx
import pylab
g = nx.Graph()
g.add_node( 'a' )
g.add_node( 'b' )
g.add_node( 'c' )
g.add_node( 'd' )
g.add_edge( 'a', 'b' )
g.add_edge( 'c', 'd' )
h = nx.Graph()
h.add_node( 'c' )
h.add_node( 'd' )
# Define the positions of a, b, c, d
positions = nx.spring_layout( g )
# Produce image of graph g with a, b, c, d and some edges.
nx.draw( g, positions )
plt.savefig( "g.png" )
# Clear the figure.
plt.clf()
# Produce image of graph h with two nodes c and d which should be in
# the same positions of those of graph g's nodes c and d.
nx.draw( h, positions )
plt.savefig( "h.png" )
Can anyone please suggest what I'm doing wrong, or how to generate images
of subgraphs where the nodes are in the same location as that of the full
graph?

Alternative PImpl Idiom - advantages vs disadvantages?

Alternative PImpl Idiom - advantages vs disadvantages?

The traditional PImpl Idiom is like this:
#include <memory>
struct Blah
{
//public interface declarations
private:
struct Impl;
std::unique_ptr<Impl> impl;
};
//in source implementation file:
struct Blah::Impl
{
//private data
};
//public interface definitions
However, for fun, I tried to use composition with private inheritance
instead:
#include <iostream>
#include <type_traits>
#include <memory>
template<typename Derived>
struct PImplMagic
{
PImplMagic()
{
static_assert(std::is_base_of<PImplMagic, Derived>::value,
"Template parameter must be deriving class");
}
//protected: //has to be public, unfortunately
struct Impl;
};
struct Test : private PImplMagic<Test>, private
std::unique_ptr<PImplMagic<Test>::Impl>
{
Test();
void f();
};
int main()
{
Test t;
t.f();
}
template<>
struct PImplMagic<Test>::Impl
{
Impl()
{
std::cout << "It works!" << std::endl;
}
int x = 7;
};
Test::Test()
: std::unique_ptr<Impl>(new Impl)
{
}
void Test::f()
{
std::cout << (*this)->x << std::endl;
}
http://ideone.com/WcxJu2
I like the way this alternate version works, however I'm curious if it has
any major drawbacks over the traditional version?

Ubuntu 13.04 shutdown problem. Got no idea what to do next

Ubuntu 13.04 shutdown problem. Got no idea what to do next

I have been using Ubuntu for two years now and had few actual problems. I
have searched this site and tried various things to no effect. I will do
my best to explain, and certainly include too much info as I have no idea
what my problem really is. Please take answers to the 'for dummies'-level
and I shall certainly do my best to understand!
So, I have this lovely acer TravelMate 5310 from around 07 that's causing
a bit of a headache. It's Vista was removed and replaced with Ubuntu 11.??
some two years ago and was updated to the 12.04 LTS at some point before
christmas. It has worked well except a problem with the network that's
solved with a plug in reciever. All was just fine until I two days ago
wanted to install the latest version, 13.04. I by accident installed
12.04LTS again and thought it won't matter. The problem with shutdown
started after this, and we have finally arrived at the point of all this.
It won't shut down. I removed the 12 and installed the 13 last night
thinking the problem might go away. It installed and updated and whent for
a restart without problems but came to a halt at the purple screen.
I performed the hard shutdown(the press button method) and restarted. It
boots up with ease and all is really well BUT it simply cannot shut down.
It now hangs on a black screen with loads of white numbers, words and
other such terminal-like things. So I push and hold shutdown to turn it
off.
I tried doing this Then tried the acpi=off in terminal but nothing works.
I have yet to try the command shutdown -h now but I now managed to hit esc
at the right time and go behind the first screen and see the next. I am
sorry that I have no pictures to show you.
The processes that seems to fail are two:
*killing all remaining processes.... [fail]
modem-manager[953] : Caught signal 15, shutting down...
then follows ok's on deactivating swanps, unmounting filesystems.
then:
*stopping remanining crypto discs... [ok]
*stopping early crypto discs... [fail]
Unmount: /run/lock: not mounted
unmount: /run/shm: not mounted
mount: / is busy
*will now halt
And that is where it hangs..
I hope you are able to understand anything. I have no idea. The formating
above is all wrong and such, I tried my best^^

Software for aiding in printing photos

Software for aiding in printing photos

I wanted to know if there is any software to print photos, which can frame
the photo and also change the size of it. I have two printers canon and
while I found the drivers and work, Ubuntu 12.04 will not let me install
the printer CD. Unable to install this SW, not only I can not print photos
as I want, but I can not run a head cleaning, aligning, or know that I
have ink level. I hope you can help me and all the SW probe recommended
software center, but they are very basic and none worked as I expected.

Monday, 30 September 2013

Notation for anti-symmetric part of a tensor – physics.stackexchange.com

Notation for anti-symmetric part of a tensor – physics.stackexchange.com

I know that $A_{[a} B_{b]} = \frac{1}{2!}(A_{a}B_{b} - A_{b}B_{a})$ But
how can write $E_{[a} F_{bc]}$ like the above? Can you provide a reference
where this notational matter is discussed?

Openconnect on Ubuntu 64-bit: Can't connect to Cisco VPN

Openconnect on Ubuntu 64-bit: Can't connect to Cisco VPN

I am trying to use OpenConnect on Ubuntu 64-bit to connect to a Cisco VPN
as an alternative to the AnyConnect software.
I am running Ubuntu Linux 64-bit 13.04.
I am not able to get the connection working. The Openconnect log output
shows the following content over and over again in a loop apparently
without end:
Connected to HTTPS on vpn.mycompany.com
GET https://vpn.mycompany.com/+CSCOE+/sdesktop/wait.html
Refreshing +CSCOE+/sdesktop/wait.html after 1 second...
SSL negotiation with vpn.mycompany.com
Connected to HTTPS on vpn.mycompany.com
GET https://vpn.mycompany.com/+CSCOE+/sdesktop/wait.html
Refreshing +CSCOE+/sdesktop/wait.html after 1 second...
SSL negotiation with vpn.mycompany.com
and so on and on.
Does anyone have any suggestions about what the solution to this problem
is? I have enabled use of the Cisco Secure Desktop Trojan in the VPN
configuration.
Any help gratefully received.

findind and replacement of value in xml

findind and replacement of value in xml

I have a query that is i have different xml which contain these below tags
<property name="abcaddress">
<value>Rt:try:yutt</value>
Now I am at the root of the project that is at /opt/app/pro1 now in side
pro1 there may be many directories which may contain different xml's in
side in some xml's there may be this tag so i need to search and replace
the tag with TEST1 , so finally after replacement it would look like ...
<property name="abcaddress">
<value>TEST</value>
please advise what will be the appropriate unix command to achieve this..!!

Change submit button image the very moment when radio button is selected in php

Change submit button image the very moment when radio button is selected
in php

This is the dynamic radio button:
echo "<input type='radio' name='q_id' value='.$ans[$i].'
id='.$i.'>$ans[$i].";
and here is the submit button:
<input type="submit" name="submit" id="submit" value="Submit"
style="border: 0; background: transparent"><img src="images/skip.png"
alt="submit_x" width="223" hspace="40" height="49"/>
I want to change the image source in the button the very moment when radio
button is clicked. New image source will be "images/next.png"
This change in image has to be done before submitting the form.

Sunday, 29 September 2013

Logisim Rock Paper Scissors

Logisim Rock Paper Scissors

I need to create a rock paper scissors game in Logisim(circuit simulator).
I do not know where to start but I know I need a selector and probably a
decoder to choose inputs 00-rock 01-paper 11-scissors
Does anyone know how to approach the problem?

dragging ckeditor toolbar in inline editing

dragging ckeditor toolbar in inline editing

As CKEditor documentation is really poor, I couldn't find an answer to
this question anywhere.
Is it possible to configure CKeditor so that toolbar would be draggable in
inline editing mode? I'd like to be able to move it around.
If so, how is it possible to set that?
Thanks!

How to plot time series in python

How to plot time series in python

I have been trying to plot a time series graph from a CSV file. I have
managed to read the file and converted the data from string to date using
strptime and stored in a []. When i tried plotting a test plot in
matplotlib with the[] containing the date information it plotted the date
as series of dots that is for a date 2012-may-31 19:00 hours i got a a
plot with a dot at 2012, 05, 19, 31, 00 at y axis for the value of x=1 and
so on. I understand that this is not the correct way of passing date
information for plotting. can someone tell me how to pass this information
correctly.

WaveMaker Training?

WaveMaker Training?

We have three developers for whom I'd like to kick-start our understanding
and familiarisation with WaveMaker. We need some rapid learning's
regarding developing some fairly sophisticated front ends.
Is there a training available (WaveMaker community seems unable to take
registrations from us so cant ask there) or perhaps a UK developer who
feels able to offer this training support?

Saturday, 28 September 2013

jQuery blur() or focusout() not firing in Internet Explorer

jQuery blur() or focusout() not firing in Internet Explorer

So i have this form and i would like to do some stuff when the inputs
loose focus. This is the code i have and it's working like a champ in
every browser except Internet Explorer.
function formstyle() {
var focus = 0;
//comentario is the ID of the input
$("#comentario").focus(function() {
//blablablabla
});
$("#comentario").blur(function() {
setTimeout(function() {
var whatFocus = document.activeElement.tagName;
if(whatFocus === "BODY")
{
focus = 0;
//bla bla bla
}
}, 2);
});
}
$(document).ready(function(){
formstyle();
});
I'm almost blowing up my mind. It's a simple piece of code and yet…
nothing… Did i miss anything?

How to reference a parent object (i.e; from root or stage)?

How to reference a parent object (i.e; from root or stage)?

I'm currently playing around with some AS3 platform gaming, and trying to
go with a cleaner object-based approach for platforms. In short, I'm
trying to detect if the player object is colliding with platform - ala:
if (!player.hitTestObject(this)) {
//player falls
}
However, the problem is in actually referencing the player object - the
player is at the following location (from the stage); manager.player -
wheras the platforms are at manager.level.foreground.
Is there any way to actually reference the player object from within the
foreground object as listed above, without passing in a constructor from
the player to each and every instance of the platform?

Checking for duplicates using jQuery and localStorage

Checking for duplicates using jQuery and localStorage

Need to check for duplicates before storing new values in localStorage.
Here's a working fiddle that does everything I need except that.
Please feel free to suggest any other ways you see that will help me
improve—still learning.
Here's part of the code that's in the fiddle:
("button#save").click(function () {
var id = $("#id").val();
if (id != "") {
var text = 'http://' + id + '.tumblr.com';
} else {
alert('empty');
return false
}
// UPDATE
var result = JSON.parse(localStorage.getItem("blog"));
if (result == null) result = [];
result.push({
id: id,
tumblr: text
});
// SAVE
localStorage.setItem("blog", JSON.stringify(result));
// APPEND
$("#faves").append('<div class="blog"><button class="del" id=' + id +
'>x</button><a target="_blank" href=' + text + '>' + imgstem + id +
imgstemclose + '</a></div>');
});
// INIT
var blog = JSON.parse(localStorage.getItem("blog"));
var stem = 'http://'
var stemclose = '.tumblr.com';
var imgstem = '<img src="http://api.tumblr.com/v2/blog/'
var imgstemclose = '.tumblr.com/avatar/48"/>'
//console.log(blog[0].id);
if (blog != null) {
for (var i = 0; i < blog.length; i++) {
var item = blog[i];
var text = 'http://' + item.id + '.tumblr.com';
$("#faves").append('<div class="blog"><button class="del" id=' +
item.id + '>x</button><a href=' + text + '>' + imgstem + item.id
+ imgstemclose + '</a></div>');
}
}
$('#faves').on('click', 'button.del', function (e) {
var id = $(e.target).attr('id');
// UPDATE
var blog = JSON.parse(localStorage.getItem("blog"));
var blog = blog.filter(function (item) {
return item.id !== id;
});
// SAVE
localStorage.setItem("blog", JSON.stringify(blog));
// REMOVE
$(e.target).parent().remove();
});

javascript Array map with apply

javascript Array map with apply

I am trying to declare and initialize an array with 0, in javascript. I
created an array and set the length like this.
var previousRow = [];
previousRow.length = 5;
Then, I did this.
console.log(previousRow);
previousRow = previousRow.map(Number.prototype.valueOf, 0);
console.log(previousRow);
and I got,
[ , , , , ]
[ , , , , ]
But, when I did
console.log(previousRow);
previousRow = Array.apply(null, previousRow).map(Number.prototype.valueOf,
0);
console.log(previousRow);
I got what I expected
[ , , , , ]
[ 0, 0, 0, 0, 0 ]
Why the first code didn't work?

Friday, 27 September 2013

Google Maps, "is null or not an object" and IE8

Google Maps, "is null or not an object" and IE8

So, i have a Google Maps map in a web site i'm creating and everything
runs great in every browser, except for… IE8. In IE8 the browser simply
stops reading the JS file when he encounters the first variable
declaration and it gives the error i mentioned in the subject. It doesn't
load the map neither any function bellow the error.
It's always in the same variable, which means that if i change the code it
will always stuck in that part.
So the code is the following:
var monteiros_xs = new google.maps.LatLng(40.562884,-7.113948);
var MY_MAPTYPE_ID = 'custom_style';
function calculateCenter() {
center = map.getCenter();
}
function initialize() {
var featureOpts = [
{
stylers: [
{ hue: '#b0d57d' },
{ visibility: 'on' },
{ gamma: 0 },
{ weight: 1 }
]
},
{
elementType: 'labels',
stylers: [
{ visibility: 'on' }
]
},
{
featureType: 'water',
stylers: [
{ color: '#f1f2f2' }
]
}
];
var mapOptions;
mapOptions = {
scrollwheel: false,
zoom: 10,
center: monteiros_xs,
disableDefaultUI: true,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, MY_MAPTYPE_ID]
},
mapTypeId: MY_MAPTYPE_ID
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var styledMapOptions = {
name: 'Granigri'
};
var rectangulo = new google.maps.Rectangle({
strokeColor: '#3c3c3c',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#1a1a1a',
fillOpacity: 0.35,
map: map,
bounds: new google.maps.LatLngBounds(new
google.maps.LatLng(40.560884,-7.119948), new
google.maps.LatLng(40.566884,-7.112948))
});
if(rectangulo !== "") {}
var customMapType = new google.maps.StyledMapType(featureOpts,
styledMapOptions);
map.mapTypes.set(MY_MAPTYPE_ID, customMapType);
google.maps.event.addDomListener(map, 'idle', function() {
calculateCenter();
});
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(center);
});
}
$(document).ready(function(){
initialize();
});
The error is always in the "google.maps" part. I've read somewhere that it
can be related with trailing commas, but 24 hours later i can't find any.
So any ideias?
Thank you in advance. :)

angular-ui bootstrap tabs reorder orderBy

angular-ui bootstrap tabs reorder orderBy

I am using angular and angular-ui-bootstrap tabs. I would live to use the
orderBy or be able to dynamically reorder the tabs.
I created this plunkr
<tab ng-repeat="tab in tabs | orderBy:disabled" heading="{{tab.title}}"
active="tab.active" disabled="tab.disabled">

asp.net client page validation not working for mobile chrome browser on iOS7, is there a workaround?

asp.net client page validation not working for mobile chrome browser on
iOS7, is there a workaround?

I have this javascript function that validates the page using asp.net 2.0
validation controls, with client-side validation enabled. I know there are
better ways of doing this but I don't have the luxury of time to rework
the validation architecture. To debug I open the site from Chrome, on my
desktop using the User Agent string from Chrome on iOS7 and the "Emulate
touch events" turned on. when I add the Page_Validators global array to
the watch list or hover over it while debugging the lines, it tells me it
is "not available". It seems like there is an issue with .Net's client
side scripts, yet I don't get an error from them at all. In safari it
works as expected and also on Android browsers.
function validatePage() {
var errorCount = 0;
if (typeof Page_Validators != 'undefined') {
Page_ClientValidate('1');
$.each(Page_Validators, function () {
//do some work...
});
if (errorCount > 0) {
//something happens here...
} else {
//something else happens here...
}
return errorCount;
}
}
Anybody know of a hot fix to make this work?

How to check that pc speaker is on or not using java

How to check that pc speaker is on or not using java

How to get hardware level detail using Java is this possible? I know how
to get PC name, Hard drive size, Ram size etc.
But how I can check that my pc speaker sound is ON or not using Java? And
How I can enable or disable speaker sound using Java? I am searching for
that but found Sound API which I don't think so provide a such function?
Anyone know that?

jQuery Cookie on slideToggle

jQuery Cookie on slideToggle

I've a navigation bar, and a hidden sub navigation bar. When I click on
Page2 the hidden bar shows up (with slideToggle). So far so good. Now the
client wants, when the sub navigation bar is shown, and he clicks on Page3
or Page1 again that the sub navigation bar stays shown until he click on
Page2 again. I know that I need cookies for this. I've tried to make it by
myself but with no effort, because this is the first time I work with JS
cookies. I'm sure somebody knows how to do this jQuery script
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.js"
type="text/javascript"></script>
<script type="text/javascript"
src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
</head>
<body>
<nav>
<ul>
<li><a href="index.html">Page1</a></li>
<li id="item"><a href="#">Page2</a></li>
<li><a href="page3.html">Page3</a></li>
</ul>
</nav>
<br /><br />
<ul id="sub-nav">
<li><a href="#">Subpage1</a></li>
<li><a href="#">Subpage2</a></li>
<li><a href="#">Subpage3</a></li>
</ul>
</body>
CSS:
<style type="text/css">
*{margin: 0; padding: 0;}
ul{list-style:none; font: 20px; float: left;}
ul li{float: left; margin-right: 20px;}
#sub-nav{font:14px; display: none;}
</style>
jQuery:
<script type="text/javascript">
$(document).ready(function(){
$('#item').click(function(){
$('#sub-nav').slideToggle('fast');
});
});
</script>

Thursday, 26 September 2013

How to get filtered data by calling webservice in Java

How to get filtered data by calling webservice in Java

I am writing a code where I call a webservice to get the data from
database and then fetch it in the grid by applying some conditions which
is working fine. But since in future the database will be huge so to call
whole data and then refining it will create performance issues. So I want
to get filter data itself from database.
Current Code: Calling webservice code:
RESTClient<AuditInfoObject, ArrayList<AuditInfoObject>> restClient = new
RESTClient<AuditInfoObject, ArrayList<AuditInfoObject>>(
new AuditInfoObject(), new
TypeToken<ArrayList<AuditInfoObject>>() {
}.getType(), CommonConstatnts.SHOW_ALL_AUDIT,
CommonConstatnts.CONTET_TYPE_JSON);
ArrayList<AuditInfoObject> auditInfoList = restClient.getResponse();
AuditInfoObject contains: userID,appID,and othe details.
Here auditinfolist contains the whole data.
Now i apply the condition to filter the data which i recieved by comparing
userId and appId and insert it in grid table.
Code:
try {
for (AuditInfoObject row : auditInfoList) {
if (app.getUserID() == row.getUserID() &&
app.getAppName().equalsIgnoreCase(row.getAppName().trim())) {
GridItem item = new GridItem(appDashBoardGrid, SWT.FILL |
SWT.NONE);
item.setText(0, row.getTimeStamp());
item.setText(1, row.getAction());
item.setText(2, row.getActionData());
item.setText(3, row.getMachineDetail());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
HERE:app.getUserID() is the current userID which i match with the recieved
data userid column i.e row.getUserID() similarly for appID also.
Now I want to call webservice in such a way that the present userID and
appId goes with webservice call match with database and I should get
filtered data before only on that basis so that I can put in grid table
because it will be fast and have good performance.

Wednesday, 25 September 2013

Duplicate values removal using Javascript

Duplicate values removal using Javascript

var arr1=["a","b","b","c","c","d"];
var arr2=["b","c",];
arr1 has duplicate values which are listed in arr2. Now I want to remove
the duplicate values from arr1 using arr2. Is it possible?

Thursday, 19 September 2013

Rewrite folder's name using htaccess

Rewrite folder's name using htaccess

I am wondering wether it's possible to use .htaccess to rewrite a folder
name. What I mean is this.
Lets say I have a url like:
www.example.org/anyname/page.php
Now I want to rewrite the url to (for example)
www.example.org/folder1/page.php
The folder1 is an existing folder on my webspace.
important: the "anyname" is not a folder rather just a name!
Ok here is a step by step plan:
User types www.site.com/anyname/login.php. The url should rewrite and not
redirect the url to www.site.com/folder1/login.php This means that
"anyname" is just a name and not a directory. All the code should just
come from folder1. Acutally "anyname" should just be an alias for folder1.
I can't just rename folder1 to "anyname". Therefore I would just rewrite
folder1 to "anyname".

Email is not sending using php

Email is not sending using php

I am using the following code for sending attachments to the email...but i
am unable to get the email..
I am able to get the message for successfully sending mail like " message
sent " but the email is not going to corresponding mail id..
I don't where i do wrong....
Here is php file ...
<?php
if(isset ($_POST["send"]))
{
$upload_name=$_FILES["upload"]["name"];
$upload_type=$_FILES["upload"]["type"];
$upload_size=$_FILES["upload"]["size"];
$upload_temp=$_FILES["upload"]["tmp_name"];
$message=$_POST["msg"];
$subject = $_POST["subject"];
$to=$_POST["to"];
if($message==""||$subject==""||$to=="")
{
echo '<font style="font-family:Verdana, Arial; font-size:11px;
color:#F3363F; font-weight:bold">Please fill all fields</font>';
}
else
{
$fp = fopen($upload_temp, "rb");
$file = fread($fp, $upload_size);
$file = chunk_split(base64_encode($file));
$num = md5(time());
//Normal headers
$headers = "From: Info Mail<Info@example.com>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; ";
$headers .= "boundary=".$num."\r\n";
$headers .= "--$num\r\n";
// This two steps to help avoid spam
$headers .= "Message-ID: <".gettimeofday()."
TheSystem@".$_SERVER['SERVER_NAME'].">\r\n";
$headers .= "X-Mailer: PHP v".phpversion()."\r\n";
// With message
$headers .= "Content-Type: text/html; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 8bit\r\n";
$headers .= "".$message."\n";
$headers .= "--".$num."\n";
// Attachment headers
$headers .= "Content-Type:".$upload_type." ";
$headers .= "name=\"".$upload_name."\"r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; ";
$headers .= "filename=\"".$upload_name."\"\r\n\n";
$headers .= "".$file."\r\n";
$headers .= "--".$num."--";
// SEND MAIL
mail($to, $subject, $message, $headers);
fclose($fp);
echo '<font style="color:#333333">Mail sent please check inbox and spam
both <br /></font>';
}
}
?>
//HTML code for form details and adding attachment..
<form id="attach" name="attach" method="post" action="<?php echo
$_SERVER["PHP_SELF"]; ?>" enctype="multipart/form-data">
//Html code for mail details
</form>
I am getting "Warning: mail() [function.mail]: Bad parameters to mail()
function, mail not sent...." and also it is showing the "Mail sent please
check inbox and spam both ".. what's the problem ?
Help me to fix this problem...

Cannot insert column NULL... but the value is not null

Cannot insert column NULL... but the value is not null

Really, this couldn't be more simple. See on the screenshot, I get the
error Cannot insert null value into column ZoneID. I don't get it because
we clearly see that ZoneID = 64.
I've never seen that before, anyone has an explanation? I've retried many
times with the same result.
(Click for bigger image)

Misplaced footer when viewed on iPad's Safari

Misplaced footer when viewed on iPad's Safari

A website that I'm currently working on works completely fine in regards
to the footer, however when viewing the website on the iPad's Safari, the
footer is misplaced quite a bit above the bottom of the page and after an
hour of trial and error I'm not getting anywhere fast. I was hoping
someone had this very issue and can perhaps aid me by explain what you did
to resolve the issue.
This is the basic markup of my HTML.
<html>
<body>
<form>
<iframe></iframe> <!-- This is where the different pages are set -->
</form>
<footer>
</footer>
</body>
</html>
Here's the CSS
html,
body {
margin:0;
padding:0;
height:100%;
}
.footer {
position:absolute;
bottom:0;
width:100%;
height:40px; /* Height of the footer */
background:#6d8085;
}
Chrome

iPad

Thanks a lot for the help!

Pig: Counting the occurence of a grouped column

Pig: Counting the occurence of a grouped column

In this raw data we have info of baseball players, the schema is
name:chararray, team:chararray, position:bag{t:(p:chararray)}, bat:map[].
Using the following script we are able to list out players and the
different positions they have played. How do we get a count of how many
players have played a particular position (for instance: how many players
were in 'Designated_hitter' position?
Pig Script and sample out is listed below. Please help me out, thanks in
advance.
--pig script
players = load 'baseball' as (name:chararray,
team:chararray,position:bag{t:(p:chararray)}, bat:map[]);
pos = foreach players generate name, flatten(position) as position;
groupbyposition = group pos by position;dump groupbyposition;
--dump groupbyposition (output of one position i.e Designated_hitter)
(Designated_hitter,{(Ken Griffey, Jr.,Designated_hitter),(Jack
Cust,Designated_hitter),(Jason Giambi,Designated_hitter),(Michael
Young,Designated_hitter),(Hank Blalock,Designated_hitter),(Hensley
Meulens,Designated_hitter),(Johnny Damon,Designated_hitter),(Ryan
Garko,Designated_hitter),(Lance Berkman,Designated_hitter),(Rocco
Baldelli,Designated_hitter),(Adam Lind,Designated_hitter),(Carlos
Guillén,Designated_hitter),(Josh Bard,Designated_hitter),(Vladimir
Guerrero,Designated_hitter),(Nick Johnson,Designated_hitter),(Willy
Aybar,Designated_hitter),(Luke Scott,Designated_hitter),(Milton
Bradley,Designated_hitter),(Jason Kubel,Designated_hitter),(Jermaine
Dye,Designated_hitter),(Wladimir Balentien,Designated_hitter),(Hideki
Matsui,Designated_hitter),(Adam Dunn,Designated_hitter),(Cliff
Floyd,Designated_hitter),(Travis Hafner,Designated_hitter),(Billy
Butler,Designated_hitter),(Matt Stairs,Designated_hitter),(Pat
Burrell,Designated_hitter),(Jorge Posada,Designated_hitter),(Jeff
Larish,Designated_hitter),(Marcus Thames,Designated_hitter),(Jim
Thome,Designated_hitter),(David Ortiz,Designated_hitter)})

Can we customize the android setting options and meta options?

Can we customize the android setting options and meta options?

I want to create an application but I want to use Setting Options in my UI
(i.e. every device has a specific user interface but i want to display
setting option and meta options in My User interface).
I have not done such type of work previously. Does anybody have an idea
how to implement this?

Hide/Show on left side using jQuery

Hide/Show on left side using jQuery

I want to hide/show a div on click. I want the div to go left to hide when
I want it to hide. I have this. But the div goes up to hide. FIDDLE
$(document).ready(function() {
$('#showmenu').click(function() {
var hidden = $('.sidebarmenu').data('hidden');
$('#showmenu').text(hidden ? 'Show Menu' : 'Hide Menu');
if(hidden){
$('.sidebarmenu').css({
position: 'absolute',
left: -200000
})
} else {
$('.sidebarmenu').css({
position: '',
left: 0
})
}
$('.sidebarmenu,.image').data("hidden", !hidden);
});
});
And this is my HTML
<button id="showmenu" type="button">Show menu</button>
<div class="sidebarmenu" style="position: absolute; left:
-200000px">
This should go left
</div>

Wednesday, 18 September 2013

Wordpress add wp_editor media button at front end

Wordpress add wp_editor media button at front end

I have used wp_editor function at front-end ,if user login as (admin,
editor, author, Contributor) but not in Subscriber , so how appear media
button when Subscriber login ,with out change Subscriber permission.

AngularJS google maps directive

AngularJS google maps directive

Hi i'm trying to develop an app using angularjs and a directive that I've
found for instantiate GMaps:
http://nlaplante.github.io/angular-google-maps/#!/usage. I follow all the
steps but I cant get to render the map! it returns no errors! HELP!!
in the HTML
<html ng-app="Maptesting">
<google-map center="center"
zoom="zoom"
markers="markers"
refresh="!isMapElementHidden"
style="height: 400px; width: 100%; display: block;">
</google-map>
<div ng-view></div>
<script type="text/javascript" src="js/angular/angular.js"></script>
<script
src="http://code.angularjs.org/1.2.0-rc.2/angular-route.min.js"></script>
<script type="text/javascript" src="js/angular-google-maps.js"></script>
<script
src="http://maps.googleapis.com/maps/api/js?sensor=false&language=en"></script>
<script src="app/map.js">
</script>
In the controller:
angular.module('Maptesting', ['google-maps'])
.controller('CtrlGMap', ['$scope', function($scope) {
$scope.center = {
latitude: 45,
longitude: -73
};
$scope.markers = [];
$scope.zoom = 8;
}])

how javascript interprets variables?

how javascript interprets variables?

How javascript interprets variables if it can be used without declaring?
Or if it is using a "var" to declare, how javascript know that this
variable is for string, boolean.. etc. Answers will be highly appreciated.
Thanks.

changing keyboard in cordova phonegap in iOS

changing keyboard in cordova phonegap in iOS

Is it possible to change the display of the keyboard in a cordova phonegap
application running on iOS? I want to experiment with leaving off certain
keys and changing its size.
I take it if this feature is locked down then maybe an alternative would
be disabling the keyboard (i could do so this way) and then writing one
from scratch .

Struts2 action method and struts.convention.result.path not working

Struts2 action method and struts.convention.result.path not working

I have problem with Struts2 action method and
struts.convention.result.path Here is my struts.xml
<struts>
<constant name="struts.action.extension" value="" />
<constant name="struts.action.excludePattern"
value="/.*\.(html|jsp),/static/.*"/>
<constant name="struts.convention.result.path"
value="/WEB-INF/pages/" />
<package name="user" namespace="/user" extends="struts-default">
<action name="login" class="loginAction" method="login">
<result name="success">login.jsp</result>
</action>
</package>
<struts>
When I run url "localhost:8080/venus/user/login". It display error "HTTP
Status 404 - /venus/user/login.jsp"
If I change login() method to execute() method, it works. Or if I change
to /WEB-INF/pages/login.jsp, it works.
Can anyone explain and teach me how use action method with result.path
config in xml? Thank you!

Use SharedPreferences in service has Nullpointerexception

Use SharedPreferences in service has Nullpointerexception

I would like to develop a program to upload file to Dropbox automatically
in background.
I find that it cannot get the Shared preference key after reboot and
return Nullpointerexception. Would you guys please help to find out the
reason and solution?
public class Upload extends Service {
private File mFile = new
File(Environment.getExternalStorageDirectory()+"test.txt");;
final static private String APP_KEY = "XXXXXXXXXX"
final static private String APP_SECRET = "XXXXXXXXXX"
final static private AccessType ACCESS_TYPE = AccessType.DROPBOX;
///////////////////////////////////////////////////////////////////////////
// End app-specific settings.
//
///////////////////////////////////////////////////////////////////////////
// You don't need to change these, leave them alone.
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
// AndroidAuthSession session = new AndroidAuthSession(appKeys,
ACCESS_TYPE);
AndroidAuthSession session = buildSession();
DropboxAPI<AndroidAuthSession> mDBApi = new
DropboxAPI<AndroidAuthSession>(session);
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int res = super.onStartCommand(intent, flags, startId);
if (mDBApi.getSession().authenticationSuccessful()){
try {
// Required to complete auth, sets the access token on
the session
mDBApi.getSession().finishAuthentication();
AccessTokenPair tokens =
mDBApi.getSession().getAccessTokenPair();
storeKeys(tokens.key, tokens.secret);
Runnable runnable = new Runnable(){
@Override
public void run() {
try {
uploadtodropbox();
stopSelf();
} catch (Exception e)
{
Log.e("Upload", "Could not Upload to
dropbox", e);
}
}
};
new Thread(runnable).start();
} catch (IllegalStateException e) {
Log.i("DbAuthLog", "Error authenticating", e);
}
}else{
mDBApi.getSession().startAuthentication(this);
try {
uploadtodropbox();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DropboxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return res;
}
private void storeKeys(String key, String secret) {
// Save the access key for later
SharedPreferences prefs =
getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, key);
edit.putString(ACCESS_SECRET_NAME, secret);
edit.commit();
}
private void uploadtodropbox() throws FileNotFoundException,
DropboxException{
FileInputStream fis = new FileInputStream(mFile);
String path = mFile.getName();
mDBApi.putFileOverwrite(path, fis, mFile.length(), new
ProgressListener(){
@Override
public long progressInterval() {
// Update the progress bar every half-second or so
return 500;
}
@Override
public void onProgress(long bytes, long total) {
publishProgress(bytes);
}
});
}
protected void publishProgress(long bytes) {
// TODO Auto-generated method stub
}
/**
* Shows keeping the access keys returned from Trusted Authenticator
in a local
* store, rather than storing user name & password, and
re-authenticating each
* time (which is not to be done, ever).
*/
private void clearKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
private String[] getKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
String key = prefs.getString(ACCESS_KEY_NAME,null);
String secret = prefs.getString(ACCESS_SECRET_NAME, null);
if (key != null && secret != null) {
String[] ret = new String[2];
ret[0] = key;
ret[1] = secret;
return ret;
} else {
return null;
}
}
AndroidAuthSession buildSession() {
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session;
String[] stored = getKeys();
if (stored != null) {
AccessTokenPair accessToken = new
AccessTokenPair(stored[0], stored[1]);
session = new AndroidAuthSession(appKeys, ACCESS_TYPE,
accessToken);
} else {
session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
}
return session;
};
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

Log base n of x

Log base n of x

I have a little problem. who knows how we can calculate the log base n (2
for example: for n=2 we had this solution:
int log(int n){
int res = 0;
while((n>>=1))
res++;
return res;
}

Overriding methods with derived type

Overriding methods with derived type

I need the following inheritance:
public class Persistent
{
public virtual Persistent Clone() { ... }
}
public class Animal : Persistent
{
public override Animal Clone() { ... }
}
This can be implemented using a generic class:
public class Persistent<T>
{
public virtual T Clone() { ... }
}
public class Animal : Persistent<Animal>
{
public override Animal Clone() { ... }
}
However inheriting further from Animal does not work:
public class Pet : Animal
{
public override Pet Clone() // return type is Animal
}
Obviously Pet should derive from Persistent<Pet> for this to work but I
need classic inheritance. Unfortunately C# supports neither multiple
inheritance nor mixins. Is there any workaround?

Delphi: Creating a TComboBox in a dynamically created form at runtime

Delphi: Creating a TComboBox in a dynamically created form at runtime

Okay, I am working in a project that was originally done in D7. And I am
doing double duty here as I am working on fixing bugs in the original code
and attempting to port it over to XE3/4. Kinda hard when the original
author used some none-open source kits for the project.
But anyways, the app is a scripting/macroing program. As part of the
custome scripting/macroing language. There is a ability to create very
simple basic forms for user input. The forms are created dynamically at
runtime based on the script/macro the script/macro author has created. I
have already fixed some bugs in the code for the creation of the forms.
But, there is one that I just can not figure out.
When creating a TComboBox for the parent form and setting the Text
property AT component creation. The text in the Text property is not
displayed.
Here is the code to create the form:
procedure CreateForm(var wFrm: TForm; sName: String);
var
iLoop, iPos, iLen: Integer;
iFormHeight, iFormWidth: Integer;
lh, hresult1, hresult2: Integer;
sWork, sWork2, sLine, CmdName: String;
lstForm, lst: TStringList;
pnl: TPanel;
begin
iFormHeight := 80;
iFormWidth := 400;
hresult1 := 0;
lst := TStringList.Create;
iLoop := lstForms.IndexOf(Trim(UpperCase(sName)));
if iLoop < 0 then
begin
AbortError('Form "' + sName + '" could not be found!');
Exit;
end;
lstForm := TStringList(lstForms.Objects[iLoop]);
for iLoop := 0 to lstForm.Count - 1 do
begin
sLine := lstForm[iLoop];
iPos := Pos('=', sLine);
iLen := Length(sLine);
if iPos = 0 then
continue;
CmdName := Uppercase(Trim(Copy(sLine, 1, iPos - 1)));
sWork2 := Trim(Copy(sLine, iPos + 1, iLen));
if CmdName = 'FORMCAPTION' then
begin
with wfrm do
begin
Caption := Trim(Copy(sLine, iPos + 1, iLen));
Name := Trim(sName);
Height := iFormHeight;
Width := iFormWidth;
Tag := 10;
BorderStyle := bsSizeable;
BorderIcons := [biSystemMenu];
Position := poDesktopCenter;
pnl := TPanel.Create(wfrm);
with pnl do
begin
Parent := wfrm;
Caption := '';
Align := alBottom;
BevelInner := bvNone;
BevelOuter := bvNone;
Height := 30;
end;
with TButton.Create(wfrm) do
begin
Parent := pnl;
Caption := '&OK';
Default := True;
ModalResult := mrOK;
Left := 235;
Top := 0;
end;
with TButton.Create(wfrm) do
begin
Parent := pnl;
Caption := '&Cancel';
Cancel := True;
ModalResult := mrCancel;
Left := 310;
Top := 0;
end;
pnl := TPanel.Create(wfrm);
with pnl do
begin
Parent := wfrm;
Caption := '';
Align := alClient;
BevelInner := bvRaised;
BevelOuter := bvNone;
BorderWidth := 5;
end;
end;
end
else
begin
lst.Clear;
StringToList(sWork2, lst, ':');
if UpperCase(lst[0]) = 'EDITBOX' then
CreateEditBox
else if UpperCase(lst[0]) = 'CHECKBOX' then
CreateCheckBox
else if UpperCase(lst[0]) = 'COMBOBOX' then
CreateComboBox
else if UpperCase(lst[0]) = 'LABEL' then
CreateLabel;
end;
end;
with wfrm do
begin
if hresult1 > 1 then
hresult2 := 5
else
hresult2 := 9;
Tag := Tag + hresult2;
Height := Height + hresult2;
end;
lst.Free;
end;
And here is the specific code to create the TComboBox, w/ TLabel, for the
form:
procedure CreateComboBox;
var
iPos: Integer;
begin
with TLabel.Create(wfrm) do
begin
Parent := pnl;
Caption := lst[1];
Left := 15;
if hresult1 > 1 then
hresult2 := 5 * hresult1
else
hresult2 := 3 * hresult1;
Top := wfrm.Tag + hresult2;
Name := 'lbl' + CmdName;
Width := 150;
WordWrap := True;
AutoSize := True;
lh := Height;
end;
hresult1 := Trunc(lh/13);
with TComboBox.Create(wfrm) do
begin
Parent := pnl;
Left := 170;
Width := 200;
if hresult1 > 1 then
hresult2 := 5 * hresult1
else
hresult2 := 3 * hresult1;
Top := wfrm.Tag + hresult2;
Style := csDropDownList;
Name := UpperCase(CmdName);
Text := 'Test Text';
sWork := lst[3];
lst.Clear;
StringToList(sWork, lst, ',');
for iPos := 0 to lst.Count - 1 do
lst[iPos] := lst[iPos];
Items.Assign(lst);
// ItemIndex := 0;
end;
wfrm.Tag := wfrm.Tag + ((hresult1 * 13)+ 13);
wfrm.Height := wfrm.Height + ((hresult1 * 13)+ 13);
TComboBox(wfrm
end;
NOTE: the above procedure is a child procedure of the CreateForm procedure.
The app uses TStringList lists to store the form definition at
script/macro runtime. Then the above code retrieves that information to
create to form when the author wants the form to be shown. And then
creates the form and places the form object into another temporary
TStringList list prior to being shown. This is done so that when the user
runs the script/macro and enters the information/settings as requested in
the form. The author may retrieve the requested information/settings from
the form before the form is destroyed.
The form is deleted (if previously created) from tmp TStringList list,
created, stored in tmp TStringList list, and shown modally with the
following code:
iPos := lstForms.IndexOf(UpperCase(sWVar2));
if iPos < 0 then
begin
AbortError('Could not find form "' + Trim(sWVar2) + '" defined!');
Exit;
end;
iPos := lstFormsTMP.IndexOf(UpperCase(sWVar2));
if iPos > -1then
begin
TForm(lstFormsTMP.Objects[iPos]).Free;
lstFormsTMP.Delete(iPos);
frm.Free;
iPos := lstFormsTMP.IndexOf(UpperCase(sWVar2));
if iPos > -1 then
begin
AbortError('Form "' + Trim(sWVar2) + '" was not removed from the
lstFormsTMP TStringList.');
Exit;
end;
end;
frm := TForm.Create(frmMain);
CreateForm(frm, sWVar2);
lstFormsTMP.AddObject(Uppercase(sWVar2), frm);
end;
iPos := lstFormsTMP.IndexOf(UpperCase(sWVar2));
if iPos < 0 then
begin
AbortError('Could not find form "' + Trim(sWVar2) + '" defined!');
Exit;
end;
hndHold := SwitchToHandle(frmMain.Handle);
try
Result := TForm(lstFormsTMP.Objects[iPos]).ShowModal = mrOK;
finally
SwitchToHandle(hndHold);
end;
With the above sets of code the form defined in the running script is
created and shown, without to many bugs/errors. But, even though I have
hardcoded the text for the TComboBox.Text property. It is not shown. Can
anyone shed some lite on why this is the case for me? All other form
components, TCheckBox, TEditBox, TLabel, are displayed without any issues,
so far. It is just the TComboBox that is causing me to scratch my head in
confusion.
NOTE: Eventually the TComboBox.Text property will be dynamically set based
on the authors setting for that property in the form component's
definition.
Thanks in advance.

Tuesday, 17 September 2013

Reversed Pub/Sub behavior in jQuery

Reversed Pub/Sub behavior in jQuery

I'm using the jQuery Tiny Pub/Sub plugin for some loose coupling. The
current behavior is the following:
Publishing foo triggers foo.bar
But publishing foo.bar doesn't triggers foo
The behavior I want is pretty much the reversed way:
Publishing foo.bar triggers foo
But publishing foo doesn't triggers foo.bar
Is there a plugin doing that or a way to get jQuery Tiny Pub/Sub working
this way?

filename contain Chinese characters can't be compiled by Jekyll

filename contain Chinese characters can't be compiled by Jekyll

This is my file name in _post directory of GitHub local.
However, I cannot use a Chinese-name in the filename, How to set/solve
this problem?
http://i.stack.imgur.com/WtKBu.png
I have no reputations. help me add these images.
http://i.stack.imgur.com/KMxmX.png

org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update

org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch
update

I am trying to insert a row into my POSTGRES database and it throws the
error below. I am using Struts2 / Hibernate. The query which is shown in
the log file is getting executed properly when i do it manually. Kindly
help.
Hibernate queries:
select nextval ('hibernate_sequence')
insert into public.fnas_master_entity_tbl
("ENTITY_STAT_COUNTRY", "ENTITY_NAME", "ENTITY_STATUS",
"ENTITY_EMAIL", "ENTITY_TYPE", "ENTITY_MAIL_NAME", "ENTITY_MAIL_ADDR",
"ENTITY_CURR_SYMBOL", "ENTITY_PHONE", "ENTITY_CREATE_DATE",
"ENTITY_CREATED_BY", "ENTITY_UID")
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Exception:
org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch
update
at
org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90)
at
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at
org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
at
org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at
org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365)
at
org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at
finassist.DAO.EntityProcessManagerDAO.add(EntityProcessManagerDAO.java:25)
at
finassist.controller.EntityProcessManager.createEntity(EntityProcessManager.java:27)
at
finassist.view.EntityManageAction.createEntity(EntityManageAction.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at
com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441)
at
com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243)
at
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165)
at
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252)
at
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
at
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
at
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
at
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
at
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
at
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
at
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
at
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488)
at
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.sql.BatchUpdateException: Batch entry 0 insert into
public.fnas_master_entity_tbl ("ENTITY_STAT_COUNTRY", "ENTITY_NAME",
"ENTITY_STATUS", "ENTITY_EMAIL", "ENTITY_TYPE", "ENTITY_MAIL_NAME",
"ENTITY_MAIL_ADDR", "ENTITY_CURR_SYMBOL", "ENTITY_PHONE",
"ENTITY_CREATE_DATE", "ENTITY_CREATED_BY", "ENTITY_UID") values ('l', 'a',
'k', 'l', 'p', 'l', 'l', 'l', '0', '2013/09/17 19:41:00', 'Karthick',
'12') was aborted. Call getNextException to see the cause.
at
org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2746)
at
org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1887)
at
org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:405)
at
org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2893)
at
org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at
org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)

Declared Boolean as False, turns up true

Declared Boolean as False, turns up true

Here's a snippet from my code...
Boolean Add;
Double Answer;
Add = false;
if (Add == true);
{
Answer = (3 + 6);
System.out.print(Answer);
}
What baffles me is that at the end of my code it keeps evaluating and
printing 3 + 6 even though the code is specifically geared to make it NOT
show up. Any help would be appreciated.

How do you use pointers to reference the address of an element in an array?

How do you use pointers to reference the address of an element in an array?

We just started going over pointers in my C/C++ class, and I'm a bit
confused at how they work. I am presented with this problem:
Assume you have declared a multi-dimensional array char ma[5][30]. What is
the address of the element "ma[0][0]"? Use two (2) different ways to
assign the address to a pointer variable, p. (Do not give a concrete
address for ma[0][0] - this will vary each time the program is run, based
on the memory allocated.)
I know how much this community frowns on providing the "answers" to a
homework problem. I don't need the answer, but hopefully someone can
explain to me how I can use a pointer to get the address of an element in
an array?

CSS dropdown menu: What is the fastest selector?

CSS dropdown menu: What is the fastest selector?

I have a multi level navigation menu on my page consisting of an unordered
list. That list has the class menu, like so:
<ul class="menu">
<li><a href="#">Category 1</a></li>
<li><a href="#">Category 2</a></li>
<li><a href="#">Category 3</a>
<ul>
<li><a href="#">Subcategory 1</a></li>
<li><a href="#">Subcategory 2</a></li>
</ul>
</li>
</ul>
The href attributes are set to # for illustration purposes.
My question is: What is the best Selector to use for that kind of menu
regarding speed?
At the moment I am using something along these lines (again, just for
illustration, there are rules missing):
.menu {
background-color: #CCC;
}
.menu li {
background-color: #FFF;
}
.menu li > ul li ul {
background-color: #333;
}
Is a class the fastest selector in that case? Or should I use something
like .navigation-container ul? Do you have any recommendations?

Sunday, 15 September 2013

Could not instantiate SAX2 parser in Java

Could not instantiate SAX2 parser in Java

I am using iTest lib for Conversion of html to pdf My code is
String File_To_Convert = inputFilename;
String url = new File(File_To_Convert).toURI().toURL().toString();
System.out.println(""+url);
String HTML_TO_PDF = outputFilename;
OutputStream os = new FileOutputStream(HTML_TO_PDF);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(os);
os.close();
It is working fine as a standalone program. But when I deployed it on my
jboss server. It gives me error like
org.xhtmlrenderer.util.XRRuntimeException: Could not instantiate any SAX 2
parser, including JDK default. The name of the class to use should have
been read from the org.xml.sax.driver System property, which is set to:
I have added this below line in run.config.bat file.
-Dorg.xml.sax.driver=org.apache.xerces.parsers.SAXParser
I am still getting the error.Any suggestions ?

Add key to unique values in the SQl database

Add key to unique values in the SQl database

My SQL data looks like this:
Col1
A
A
A
B
B
C
D
I want to add a key to only unique values. So the end result will look
like this:
Col1 Col2
A 1
A 1
A 1
B 2
B 2
C 3
D 3
How can I do this?

How to implement `viewForHeaderInSection` on iOS7 style?

How to implement `viewForHeaderInSection` on iOS7 style?

How to implement (UIView *)tableView:(UITableView *)tableView
viewForHeaderInSection:(NSInteger)section on iOS7 style like (NSString
*)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section works?
P.S. I just need to change a color of header's title of the UITableView
and save it's style.

what's the meaning of EJB view ( local view ,remote view, no-interface view)

what's the meaning of EJB view ( local view ,remote view, no-interface view)

I used to understand it means "Interface".
a local client can operate the EJB by local interface, so client can view
local interface, is this the "View" means?

parse error when authenticating facebook account to other website

parse error when authenticating facebook account to other website

this error came when i was authenticating my profile to a website through
facebook. "parse error: syntax error, unexpected $end, expecting
T_VARIABLE or T_DOLLAR_OPEN_CURLY_BRACES or T_CURLY_OPEN in
location.php(722).eval()'d code on line 1"
how do I download this php file... just to learn purpose

wound edge detection in a color image

wound edge detection in a color image

Actually, I have some wound images that I am going to specify the region
of interest (wound boundary) automatically, that is I am going to do edge
detection of the wound with Matlab. however, the available edge detection
algorithm in Matlab (e.g. Sobel) do not give me the exact boundaries of
wound. I would like to mention that my images are in JPEG format. so,
would you please kind enough and guide me how can I do it with Matlab with
many thanks Hamidreza

How To Create Multiple Picture Boxes In C# And Keep Them?

How To Create Multiple Picture Boxes In C# And Keep Them?

I Want To Create An Ability For The User In My App To Create Pictureboxs
Everytime The User Clicks On The Main Picturebox (I Want To Keep The
Pictureboxs and Give A Infinity Picturebox Creating Ability To The User)
tyvm

Saturday, 14 September 2013

HttpWebRequest simulate Firefox issue

HttpWebRequest simulate Firefox issue

Right now I use this code to simulate firefox:
var myUri = new Uri("http://www.google.com/search%3Fq%3Dyamaha");
// Create a 'HttpWebRequest' object for the specified url.
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri);
// Set the user agent as if we were a web browser
myHttpWebRequest.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1;
en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4";
var myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
var stream = myHttpWebResponse.GetResponseStream();
var reader = new StreamReader(stream);
html = reader.ReadToEnd();
// Release resources of response object.
myHttpWebResponse.Close();
But I'm sure that this is not the best implementation, because I see
different results in Firefox and in my code response.
Question:
What is the best implementation of Mozilla Firefox (so google will think
that it's not my custom request, but request of Firefox) with
HttpWebRequest or System.Windows.Forms.WebBrowser (no matter what to use,
the best way please, if it's exist ).
Thank you in advance!

CSS3 Transition different depending on search or text input?

CSS3 Transition different depending on search or text input?

First off, I went and looked at the responses generated for answers when
asking this question. Didn't find anything similar. I'm just dealing with
a weird quirk in my code pen. A result I was not expecting.
The easiest way to explain is to simply link to my code pen. Code Pen:
CSS3 Expandable Search Form
I have the same css code applied to two different types of inputs. One is
a search input and the other a text input. In order to get similar results
from each i have to modify the amount that the transition opens up to in
width on the text input and set it to 95% instead of 100%.
My goal was to have each using the same transition code with similar
transition effect. But it's not working. I would be very appreciative to
anyone who takes a look at it and may be able to help me. Thanks. BTW I am
a newbie to both stack overflow and code pen. I'm sorry if I do anything
wrong. lol I did try and look for an answer.
I tried posting code here, but I must be doing something wrong. Everything
is in code pen though.

How to get row =1,3 with trigger

How to get row =1,3 with trigger

My trigger: Hi,
I have table tbl_BetSlipEvents Id, event 202, event1 203, event2 204, event
and tbl_BetSlipSystem
In the table tbl_BetSlipEvents inserted regarding on row in the
tbl_BetSlipEvents table Id, BetSlipEventId 73, 202 74, 204
I need to find row 1 and row 3 in the first table and to insert the second
table.
my trigger:
ALTER TRIGGER BetSlipEventsTrigger ON dbo.tbl_BetSlipEvents AFTER INSERT
AS
BEGIN INSERT INTO tbl_BetSlipSystem(BetSlipEventId) SELECT Id FROM
INSERTED WHERE id =352 ; END
where id=352 works, but I need 1 row and 3 row which was inserted in the
table.
So if I inserted in the first table 3 records, I need to find 1 row was
inserted and 3 row was inserted.

Set bitmap as wallpaper

Set bitmap as wallpaper

Well my bitmap have the exact size of the device screen, so for this
example lets say 1200x780. If I set that bitmap as the wallpaper with this
code:
WallpaperManager myWallpaperManager =
WallpaperManager.getInstance(getApplicationContext());
myWallpaperManager.setBitmap(bitmap);
My wallpaper gets zoomed and the image look horrible. So my question is:
If the bitmap is the exact same size as the device screen, how could I set
it as wallpaper without it get zoomed?

Detecting overlap with UIPanGestureRecognizer

Detecting overlap with UIPanGestureRecognizer

I am using UIPanGesture recogniser on UIButtons. I want to detect when two
of them overlap in the following way:
if([(UIPanGestureRecognizer*)sender state] ==
UIGestureRecognizerStateEnded||[(UIPanGestureRecognizer*)sender state] ==
UIGestureRecognizerStateCancelled||[(UIPanGestureRecognizer*)sender state]
== UIGestureRecognizerStateFailed){
CGPoint fingerPoint;
for(id key in BluetoothDeviceDictionary) {
UIButton* btn = [BluetoothDeviceDictionary objectForKey:key];
fingerPoint = [(UIPanGestureRecognizer*)sender
locationInView:btn.superview];
}
//BLUETOOTH SHARING
if (CGRectContainsPoint(All buttons from dictionary.frame, fingerPoint)){
for the UIButton that has been overlapped do...
What is basically happening is that the user drags a UIButton on any other
UIButton on a series of UIbuttons on screen that are part of a dictionary.
When the user releases on any of them, the program has to recognise which
one of them has overlapped and the relative key from the dictionary. But I
am stuck in mud. I only can specify one button for CGRectContainsPoint and
I also don't know how to understand which one of the buttons it was and
get the key from the mutable dictionary.

How to delay instantion of a specific controller(not a route)?

How to delay instantion of a specific controller(not a route)?

I would like to have a directive which behaves as typical ng-controller,
but I want it to be called once a promise is resolved, not sooner. In HTML
this could be written like this:
<div ng-controller="myCtrl" ctrl-promise="p">
p could be any promise on parent scope. I know there is a way to delay
instantiation of a controller for a route(as answered here: Angular.js
delaying controller initialization), but I would much prefer to specify
this per controller rather than per route. I know I could use ng-if with p
as atribute, but is there other way?

Use original post meta values on WPML translation

Use original post meta values on WPML translation

I am building a WordPress plugin, and I like to integrade it with WPML.
What I like to do is the following:
I have registered a custom post type for my plugin, that using post meta,
in order to create an image gallery for each post. The post meta, is an
array with the used pictures ID's and looks like the following:
Array
(
[0] => 124
[1] => 127
[2] => 128
)
So, the question is, how can I use this post meta values when I translate
the original post to some language ?
Lets see it step by step:
The user creates the post in English language, and then adding some
pictures for this post in the post meta.
Then the user click on blue cross symbol, under the panel "Language" to
translate this post into Russians.
How the images from the original post can be placed in this new
translation by default ? Is there a way ?
Kind regards

Get the value from db and place it in view in codeigniter

Get the value from db and place it in view in codeigniter

am getting values into view when am usin the following code
echo '<pre>';print_r($result1['organization_answer_rating1']);exit;
am getting output as
Array
(
[0] => stdClass Object
(
[organization_answer_rating] => 2.7500
)
)
but when given as
<?php
//echo '<pre>';print_r($result);
//echo '<pre>';print_r($result1);?>
<table class="footable">
<thead>
<tr>
<th style="text-align:center;">Organizational Mean</th>
<th style="text-align:center;">Workgroup Mean</th>
</tr>
</thead>
<tbody>
<?php
//echo '<pre>';print_r($result1['organization_answer_rating1']);exit;
echo "<td
style='text-align:center;'><span>".$result1['organization_answer_rating1']."</span></td>";
echo "<td
style='text-align:center;'><span>".$result1['workgroup_answer_rating1']."</span></td>";
?>
</tbody>
</table>
am getting output as array what was the reason for this what was the wrong
am doing can you please say me thanks.

Friday, 13 September 2013

How to circumvent curl/curlbuild.h error?

How to circumvent curl/curlbuild.h error?

I would like to write a program that takes files from the website as
input. Searching the internet on how best to do this, I stumbled across
"cURL and libcurl" library and decided to go through its tutorial to get a
feel for it. I am using Visual Studio and found this link
http://quantcorner.wordpress.com/2012/04/08/using-libcurl-with-visual-c-2010/
that explains how to install cURL with Visual Studio. I followed the
instructions there except for the last line that says:
Now, open the curl.h file. Replace the line #include "curl/curlbuild.h"
with #include "curlbuild.h" .
I couldn't make this change since the code for the tutorial file that I
wanted to run in VS doesn't contain curl/curlbuild.h, I also had to
comment out #include <curl/curl.h> and replace it with #include <curl.h>
in order for VS to accept my code. But when I tried to run the program
#include <stdio.h>
//#include <curl/curl.h>
#include <curl.h>
#include "curlbuild.h"
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
/* example.com is redirected, so we tell libcurl to follow redirection */
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}
I got this error:
1>------ Build started: Project: cURL.c, Configuration: Debug Win32 ------
1> main.c 1>c:\libcurl\include\curl\curl.h(35): fatal error C1083: Cannot
open include file: 'curl/curlbuild.h': No such file or directory
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped
==========
So the compiler is complaining about the same error that was mentioned in
the above installation guide. What can I do to circumvent this error?

C# db connection security

C# db connection security

I have a small C# desktop application. It connects to postgres db server.
I will distribute this application to some users.
Now my question; Is someone can get my connection string (username,
password) with local port listener software or any other software?
If answer is yes, how can I prevent this?
Thank you.

Akka always timeout waiting for future

Akka always timeout waiting for future

I'm rather new to Akka and trying to figure out how to get a result from
my code, I have the following:
object MyClass extends Controller {
def createCluster(id: String, uuid: String, loc: String, size: String,
quantity: Int, name: String) = { implicit request =>
Async{
Akka.future {
.....
val system = ActorSystem("System")
val master = system.actorOf(Props[Master], name = "master")
val launch = Launch(s, d, request.user, quantity, clusterName)
//val future = master ? launch
implicit val timeout = Timeout(5 minutes)
val future = Patterns.ask(master, launch, timeout) //master ? launch
val result = Await.result(future.mapTo[ServerContainer], timeout.duration)
}
}
And my main Actor looks like:
class Master() extends Actor {
def receive = {
case Launch(server, details, user, quantity, clusterName) => {
d = details
s = Some(server)
u = Some(user)
q = Some(quantity)
cname = Some(clusterName)
hostnameActor ! Host(BIServer.NONE, Server.PDI, Database.NONE,
server.uuid.getOrElse(""), None)
}
case Host(bi,etl,db,uuid,name2) => {
instance = name2
h = Some(Host(bi,etl,db,uuid,name2))
templateActor ! TemplateOpts(s.get, d.get, instance.get)
}
case TemplateContainer(client,temp,id, server, _, _, _,_, _) => {
nodeActor ! TemplateContainer(client,temp,id, server, d.get, h, q, u,
cname)}
case NodeContainer(server, details, meta, dns, host, key) => { n =
Some(NodeContainer(server,details,meta,dns,host,q))
etlServerActor ! n.get
}
case ServerContainer(server,details) => {
sender ! ServerContainer(server, details)
}
}
But the ServerContainer is never returned to the sender and the request
always timesout after 5 minutes.
Can anyone lend any ideas as to why?

replacement for this key word inorder to pass context argument

replacement for this key word inorder to pass context argument

In the program, i am trying to pass the context of the class to the
INTENT, but View.OnClickListener() is being passed as it is enclosed in
the onClick() method. what should i write instead of "this"..??
Please help me out..
package com.calender;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class GoTo extends Activity{
Spinner sp;
EditText etyear;
Button submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.go_to);
sp = (Spinner) findViewById (R.id.spin);
etyear = (EditText) findViewById (R.id.editText1);
submit = (Button) findViewById (R.id.bsub);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent in = new Intent(this,NextCal.class);
Bundle bun = new Bundle();
bun.putString("month", sp.getSelectedItem().toString());
int y = Integer.parseInt(etyear.getText().toString());
bun.putInt("year", y);
in.putExtras(bun);
startActivity(in);
}
});
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}

menu not adding in overflow menu in sherlock action bar

menu not adding in overflow menu in sherlock action bar

While i m trying to show 3 menu in overflow menu on sherlockactionbar but
it not showing overflow icon , but when i press menu button from hardware
it shows option at bottom of screen :
I m overriding menu through this in SherlockFragmentActivity
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.activity_home, menu);
return true;
}
and in Menu xml i have also added android:showAsAction="never" property
coding for that .xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/menu_settings"
android:icon="@android:drawable/ic_menu_info_details"
android:showAsAction="never"
android:title="about"/>
<item
android:id="@+id/menu_settings2"
android:icon="@drawable/plusnew"
android:showAsAction="never"
android:title="Add"/>
<item
android:id="@+id/menu_settings3"
android:icon="@drawable/tem2"
android:showAsAction="never"
android:title="Done"/>
</menu>

Thursday, 12 September 2013

OpenGL GBuffer normals and depth buffer issues

OpenGL GBuffer normals and depth buffer issues

I finally got my GBuffer working (well not really) but now I have some
strange issues with it and i can't find out why.
When I draw the Normal texture to screen, the normals are always showing
to me (blue color always pointing to camera). I don't know how to explain
it correctly, so here are some screens:

(I think this is the problem why my lighting pass is looking pretty strange)
Here is how I create the GBuffer:
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
// generate texture object
glGenTextures(GBUFFER_NUM_TEXTURES, textures);
for (unsigned int i = 0; i < 4; i++)
{
glBindTexture(GL_TEXTURE_2D, textures[i]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA,
GL_FLOAT, 0);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i,
GL_TEXTURE_2D, textures[i], 0);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
// generate depth texture object
glGenTextures(1, &depthStencilTexture);
glBindTexture(GL_TEXTURE_2D, depthStencilTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, width, height, 0,
GL_DEPTH_COMPONENT, GL_FLOAT,NULL);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_TEXTURE_2D, depthStencilTexture, 0);
// generate output texture object
glGenTextures(1, &outputTexture);
glBindTexture(GL_TEXTURE_2D, outputTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, width, height, 0, GL_RGB,
GL_FLOAT, NULL);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT4,
GL_TEXTURE_2D, outputTexture, 0);
GLenum Status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
assert(Status == GL_FRAMEBUFFER_COMPLETE);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
Here the Geometry Pass:
glEnable(GL_DEPTH_TEST);
glDepthMask(true);
glCullFace(GL_BACK);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
GLenum DrawBuffers[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1,
GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3};
glDrawBuffers(GBUFFER_NUM_TEXTURES, DrawBuffers);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
camera.Render();
geoProgram->Use();
GLfloat mat[16];
glPushMatrix();
glTranslatef(0,0,-20);
glRotatef(rot, 1.0, 0, 0);
glGetFloatv(GL_MODELVIEW_MATRIX,mat);
glUniformMatrix4fv(worldMatrixLocation, 1, GL_FALSE, mat);
glutSolidCube(5);
glPopMatrix();
glPushMatrix();
glTranslatef(0,0,0);
glGetFloatv(GL_MODELVIEW_MATRIX,mat);
glUniformMatrix4fv(worldMatrixLocation, 1, GL_FALSE, mat);
gluSphere(sphere, 3.0, 20, 20);
glPopMatrix();
glDepthMask(false);
glDisable(GL_DEPTH_TEST);
And here the Geometry pass shader:
[Vertex]
varying vec3 normal;
varying vec4 position;
uniform mat4 worldMatrix;
void main( void )
{
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
position = worldMatrix * gl_Vertex;
normal = (worldMatrix * vec4(gl_Normal, 0.0)).xyz;
gl_TexCoord[0]=gl_MultiTexCoord0;
}
[Fragment]
varying vec3 normal;
varying vec4 position;
void main( void )
{
gl_FragData[0] = vec4(0.5, 0.5, 0.5, 1);//gl_Color;
gl_FragData[1] = position;
gl_FragData[2] = vec4(normalize(normal),0);
gl_FragData[3] = vec4(gl_TexCoord[0].st, 0, 0);
}
Sorry for the long question / code fragment, but I don't know what to do
next, I checked everything with other GBuffer implementations but couldn't
find the error.

How To Code A JVM?

How To Code A JVM?

I've recently been trying to make a programming language like Java with
good success in C but now I'm stuck on how to create something like the
JVM to run my bytecode in? I haven't been able to find anything on the
internet and I want my VM to be more efficient than Java's. Are there any
good open source VMs that run bytecode or tutorials on how to write them?

XSLT replace attributes

XSLT replace attributes

I have the following xml
<ExternalAssessmentRequest>
<ApplicationData Lender="Test">
<LiabilityList>
<RequestedLoan Identifier="New1" BaseAmount="250000"
LoanAccountFees="100" LoanAccountLMI="2000" LoanTerm="25"
LoanTermMonths="6" Product="Basic Variable" Repurposing="No"
PrimaryPurpose="OwnerOccupied" TaxDeductible="No"
InterestRate="0.075" ProductID="Product1"
PaymentType="InterestOnly" ABSCode="123">
<Applicant RelatedIdentifier="Applicant1" Percentage="0.5"/>
<Applicant RelatedIdentifier="Applicant2" Percentage="0.5"/>
<Feature Code="SupaPackage"/>
</RequestedLoan>
</LiabilityList>
</ApplicationData>
<AdditionalAssessment Lender="MegaBank">
<RequestedLoan Product="Supa Variable" ProductID="Product2"/>
</AdditionalAssessment>
</ExternalAssessmentRequest>
I need to use Xpath to create two seperate elements. One is the existing
and the other one is again the existing BUT only the elements and
attributes specified in must be replaced.
So the end result should be
<ExternalAssessmentRequest>
<ApplicationData Lender="Test">
<LiabilityList>
<RequestedLoan Identifier="New1" BaseAmount="250000"
LoanAccountFees="100" LoanAccountLMI="2000" LoanTerm="25"
LoanTermMonths="6" Product="Basic Variable" Repurposing="No"
PrimaryPurpose="OwnerOccupied" TaxDeductible="No"
InterestRate="0.075" ProductID="Product1"
PaymentType="InterestOnly" ABSCode="123">
<Applicant RelatedIdentifier="Applicant1" Percentage="0.5"/>
<Applicant RelatedIdentifier="Applicant2" Percentage="0.5"/>
<Feature Code="SupaPackage"/>
</RequestedLoan>
</LiabilityList>
</ApplicationData>
<ApplicationData Lender="MegaBank">
<LiabilityList>
<RequestedLoan Identifier="New1" BaseAmount="250000"
LoanAccountFees="100" LoanAccountLMI="2000" LoanTerm="25"
LoanTermMonths="6" Product="Supa Variable" Repurposing="No"
PrimaryPurpose="OwnerOccupied" TaxDeductible="No"
InterestRate="0.075" ProductID="Product2"
PaymentType="InterestOnly" ABSCode="123">
<Applicant RelatedIdentifier="Applicant1" Percentage="0.5"/>
<Applicant RelatedIdentifier="Applicant2" Percentage="0.5"/>
<Feature Code="SupaPackage"/>
</RequestedLoan>
</LiabilityList>
</ApplicationData>
</ExternalAssessmentRequest>
Pleaseeee help me.