Android - after loading URL with webview can i change background color
I have a webview and im loading an external HTML form a site. I try to
change the background color using javascript function:
function changeBGC(color){
document.bgColor = color;
}
and that does not work. but if i load locally then im able to change the
background color. Is there some kind of security inhibiting me from
changing a web page i load into the webview externally ?
Saturday, 31 August 2013
How do I use wildcards with php and mysql prepared statements?
How do I use wildcards with php and mysql prepared statements?
I have followed examples from other people on here who also had the same
problem but I can't get it to work. I just changed my code to use prepared
statements for safety and before the change I would get results from the
query using a certain string for $prof and now that same string won't
return any results. the query is empty every time. I don't receive any
errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$tempProf = $_POST["professor"];
$tempProfArray = explode("=",$tempProf);
$prof = $tempProfArray[1];
$postString = '';
$con=mysqli_connect("localhost","root",".......","......");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(empty($prof)) {echo "notFound";}
else
{
$stmt = $con->prepare("SELECT * FROM professors WHERE name LIKE ?");
$prof = '%' . $prof . '%';
$stmt->bind_param('i', $prof);
$stmt->execute();
$profTemp = $stmt->get_result();
while ($profResult = $profTemp->fetch_assoc())
{
$postString .= $profResult['id'];
$postString .= ".";
$postString .= $profResult['name'];
$postString .= "!";
}
if(!empty($postString))
{
echo $postString;
}
else
{
echo "notFound";
}
}
?>
I have followed examples from other people on here who also had the same
problem but I can't get it to work. I just changed my code to use prepared
statements for safety and before the change I would get results from the
query using a certain string for $prof and now that same string won't
return any results. the query is empty every time. I don't receive any
errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$tempProf = $_POST["professor"];
$tempProfArray = explode("=",$tempProf);
$prof = $tempProfArray[1];
$postString = '';
$con=mysqli_connect("localhost","root",".......","......");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(empty($prof)) {echo "notFound";}
else
{
$stmt = $con->prepare("SELECT * FROM professors WHERE name LIKE ?");
$prof = '%' . $prof . '%';
$stmt->bind_param('i', $prof);
$stmt->execute();
$profTemp = $stmt->get_result();
while ($profResult = $profTemp->fetch_assoc())
{
$postString .= $profResult['id'];
$postString .= ".";
$postString .= $profResult['name'];
$postString .= "!";
}
if(!empty($postString))
{
echo $postString;
}
else
{
echo "notFound";
}
}
?>
Open map location from Apple maps in my mapping app
Open map location from Apple maps in my mapping app
I'm developing an iOS mapping app. I would like to open a location from
the built-in maps app into my app. Ideally, my app would show up in the
Maps location sharing sheet along with Mail, Twitter, and Facebook. Is
this possible?
The best I've come up with is configuring my app as a routing app so that
Maps can send a routing request to my app, and using the destination as
the point being shared. There are a few problems with that, though. First,
my app doesn't do routing, so that's misleading to the user. Second, in my
opinion, there are too many steps for the user to get to the routing
options screen. Lastly, Apple might not approve an app that advertises
itself to the system as being a routing provider but doesn't actually do
any routing.
I've searched around quite a bit, but I haven't seen this question asked,
and I haven't found anything in Apple's documentation. Any suggestions?
I'm developing an iOS mapping app. I would like to open a location from
the built-in maps app into my app. Ideally, my app would show up in the
Maps location sharing sheet along with Mail, Twitter, and Facebook. Is
this possible?
The best I've come up with is configuring my app as a routing app so that
Maps can send a routing request to my app, and using the destination as
the point being shared. There are a few problems with that, though. First,
my app doesn't do routing, so that's misleading to the user. Second, in my
opinion, there are too many steps for the user to get to the routing
options screen. Lastly, Apple might not approve an app that advertises
itself to the system as being a routing provider but doesn't actually do
any routing.
I've searched around quite a bit, but I haven't seen this question asked,
and I haven't found anything in Apple's documentation. Any suggestions?
HTML sandbox CSS not working?
HTML sandbox CSS not working?
I was making an HTML sandbox at
this place: http://jsfiddle.net/Jtanm/
and for some reason the CSS entering textarea does not work. Please tell
me why this is.
I think it is a jQuery problem.
I was making an HTML sandbox at
this place: http://jsfiddle.net/Jtanm/
and for some reason the CSS entering textarea does not work. Please tell
me why this is.
I think it is a jQuery problem.
Watching property changes on Dart polymer-element
Watching property changes on Dart polymer-element
Is there a way to watch property changes on Dart polymer-element as
described in Change watchers section? I tried adding void
myattributeChanged(String oldValue) method but it does not get called.
Is there a way to watch property changes on Dart polymer-element as
described in Change watchers section? I tried adding void
myattributeChanged(String oldValue) method but it does not get called.
How to convert date for the first timezone to the second?
How to convert date for the first timezone to the second?
There is the following info:
date ("2013-08-30 07:05:25")
timezone ("Europe/Moscow")
My app gets this info from some server, and I need to convert this
date/time to current user's timezone. I know that I should use DateFormat
and TimeZone APIs, but I don't understand how. Please, give me a piece of
advice or some code. Thanks.
There is the following info:
date ("2013-08-30 07:05:25")
timezone ("Europe/Moscow")
My app gets this info from some server, and I need to convert this
date/time to current user's timezone. I know that I should use DateFormat
and TimeZone APIs, but I don't understand how. Please, give me a piece of
advice or some code. Thanks.
i want to now about mapreduce in mongodb codeigniter
i want to now about mapreduce in mongodb codeigniter
here am basically performing group by operation
table:sale_announcement_history fields:history_timestamp,logged by,
sale_annoucement_id --- want to know max timestamp and distinct logged by
of a particular sale_id
function test_map_reduce(){
$map = new MongoCode('
function(){
var total = 0;
var maxx = 0;
var unique = 0;
for (sum in this.sale_announcement_id) {
$total += this.sale_announcement_id[sum];
}
for (max in this.history_timestamp) {
maxx = this.history_timestamp[max];
}
for (distinct in this.logged_by) {
unique = this.logged_by[distinct];
}
emit(this.sale_announcement_id,{total:total,max:maxx,unique:unique});
}
');
$reduce = new MongoCode('
function(key, values){
var result = {total: 0, max: 0, unique: 0};
values.forEach(function(v) {
result.total = v.total;
result.max = v.max;
result.unique = v.unique;
});
return result;
}
');
$result = $this->mongo_db->command(array(
'mapreduce'=>"sale_announcement_history", // <= 'mtb'
'road' 'minivelo'
'map'=>$map,
'reduce'=>$reduce,
//'query'=>array(),
'out'=> 'test_res1'));
echo'<pre>';
print_r($result);
}
here am basically performing group by operation
table:sale_announcement_history fields:history_timestamp,logged by,
sale_annoucement_id --- want to know max timestamp and distinct logged by
of a particular sale_id
function test_map_reduce(){
$map = new MongoCode('
function(){
var total = 0;
var maxx = 0;
var unique = 0;
for (sum in this.sale_announcement_id) {
$total += this.sale_announcement_id[sum];
}
for (max in this.history_timestamp) {
maxx = this.history_timestamp[max];
}
for (distinct in this.logged_by) {
unique = this.logged_by[distinct];
}
emit(this.sale_announcement_id,{total:total,max:maxx,unique:unique});
}
');
$reduce = new MongoCode('
function(key, values){
var result = {total: 0, max: 0, unique: 0};
values.forEach(function(v) {
result.total = v.total;
result.max = v.max;
result.unique = v.unique;
});
return result;
}
');
$result = $this->mongo_db->command(array(
'mapreduce'=>"sale_announcement_history", // <= 'mtb'
'road' 'minivelo'
'map'=>$map,
'reduce'=>$reduce,
//'query'=>array(),
'out'=> 'test_res1'));
echo'<pre>';
print_r($result);
}
What would be the best way to implement a custom range filter using Solr?
What would be the best way to implement a custom range filter using Solr?
What would be the best way to implement a custom range filter using Solr?
I.e. I want to show a filter "Harddrive" (for PC's), which can have a
value in the range from 32GB to 2TB. I want these values to be added to
the query to Solr as a range-facet.
What will be the solr query?
What would be the best way to implement a custom range filter using Solr?
I.e. I want to show a filter "Harddrive" (for PC's), which can have a
value in the range from 32GB to 2TB. I want these values to be added to
the query to Solr as a range-facet.
What will be the solr query?
Friday, 30 August 2013
Match regular expression
Match regular expression
i m new in regular expression, this is my code i want to match create
regular expression which match my string (Presently Working) from
mcName[i].value.i m passing a string "Presently Working in Microsoft" but
its not getting true condition.after condition true i want to fetch next
word which is Microsoft.any one check my regular expression where i going
to mistake.
for (int i = 0; i <= mcName.Count; i++)
{
if ((Regex.IsMatch(mcName[i].Value,
"(^.*\\.[p|P][r][e][s][e][n][t][l][y](
)[w|W][o][r][i][k][n][g])$")))
{
strName = mcName[i + 1].Value.Trim();
}
//return strName
}
i m new in regular expression, this is my code i want to match create
regular expression which match my string (Presently Working) from
mcName[i].value.i m passing a string "Presently Working in Microsoft" but
its not getting true condition.after condition true i want to fetch next
word which is Microsoft.any one check my regular expression where i going
to mistake.
for (int i = 0; i <= mcName.Count; i++)
{
if ((Regex.IsMatch(mcName[i].Value,
"(^.*\\.[p|P][r][e][s][e][n][t][l][y](
)[w|W][o][r][i][k][n][g])$")))
{
strName = mcName[i + 1].Value.Trim();
}
//return strName
}
Thursday, 29 August 2013
JAXB or SAX parsing
JAXB or SAX parsing
some one have any solution for this?
I am trying to parse the following XML to read the values using Java
beans. it doesnt matter which parsing technique it is.
XML Here:
<DocumentInfo>
<Document>
<class> xyz</class>
<uid> xyz</uid>
<Pass>
xyz
</pass>
<credit />
<DocClass>xyz </DocClass>
<Properties>
<Property>
<Name>name</Name>
<Value>value</Value>
</Property>
<Property>
<Name>name</Name>
<Value>value</Value>
</Property>
<Property>
<Name>name</Name>
<Value>value</Value>
</Property>
</Properties>
<Content>
<Data>abc</Data>
<Type>txt</Type>
</Content>
</Document>
</DocumentInfo>
Thanks in advance.
some one have any solution for this?
I am trying to parse the following XML to read the values using Java
beans. it doesnt matter which parsing technique it is.
XML Here:
<DocumentInfo>
<Document>
<class> xyz</class>
<uid> xyz</uid>
<Pass>
xyz
</pass>
<credit />
<DocClass>xyz </DocClass>
<Properties>
<Property>
<Name>name</Name>
<Value>value</Value>
</Property>
<Property>
<Name>name</Name>
<Value>value</Value>
</Property>
<Property>
<Name>name</Name>
<Value>value</Value>
</Property>
</Properties>
<Content>
<Data>abc</Data>
<Type>txt</Type>
</Content>
</Document>
</DocumentInfo>
Thanks in advance.
Angularjs: Set form to dirty on model change [Advanced]
Angularjs: Set form to dirty on model change [Advanced]
I'm having a peculiar case on my hands. I'm using the number-polyfill for
input[type="number"] in my Angular app. Now, the problem with that is that
it's doesn't take into accound Angularjs's way of handling things.
Like, if I increment/decrement the input value programatically, the
ngModel associated with the input does not get the updated value.
I've resolved that by writing a custom directive, and passing the model
into the pollyfill
angular.module('appModule').
directive('type', ['$parse', '$timeout', function($parse, $timeout) {
restrict: 'A',
require: '?ngModel',
link: function($scope, iElement, iAttrs, ngModel) {
...
if iAttrs.type is 'number'
iElement.inputNumber(ngModel) // <-- THIS LINE
...
}
}
In the polyfill code, I've modified this:
increment = function(elem) {
...
if (model != null) {
model.$setViewValue(newVal);
}
...
}
which works perfectly. Now, the problem is that even after updating the
model's value, the associated form does not become dirty. In my code, it's
not possible to pass the form as an argument into this polyfill.
I tried using model.$dirty = true, but that's not working.
Any other way?
I'm having a peculiar case on my hands. I'm using the number-polyfill for
input[type="number"] in my Angular app. Now, the problem with that is that
it's doesn't take into accound Angularjs's way of handling things.
Like, if I increment/decrement the input value programatically, the
ngModel associated with the input does not get the updated value.
I've resolved that by writing a custom directive, and passing the model
into the pollyfill
angular.module('appModule').
directive('type', ['$parse', '$timeout', function($parse, $timeout) {
restrict: 'A',
require: '?ngModel',
link: function($scope, iElement, iAttrs, ngModel) {
...
if iAttrs.type is 'number'
iElement.inputNumber(ngModel) // <-- THIS LINE
...
}
}
In the polyfill code, I've modified this:
increment = function(elem) {
...
if (model != null) {
model.$setViewValue(newVal);
}
...
}
which works perfectly. Now, the problem is that even after updating the
model's value, the associated form does not become dirty. In my code, it's
not possible to pass the form as an argument into this polyfill.
I tried using model.$dirty = true, but that's not working.
Any other way?
StringBuilder + link
StringBuilder + link
I have this code
public string DeletedMessage(int id) {
StringBuilder query= new StringBuilder();
query.AppendLine("test");
query.AppendLine("");
query.AppendLine("test - "+"http://test.com/test/"+id);
return query.ToString();
}
And this link comes to as a string and not a link, How can i add link to
StringBuilder line ?
I have this code
public string DeletedMessage(int id) {
StringBuilder query= new StringBuilder();
query.AppendLine("test");
query.AppendLine("");
query.AppendLine("test - "+"http://test.com/test/"+id);
return query.ToString();
}
And this link comes to as a string and not a link, How can i add link to
StringBuilder line ?
Wednesday, 28 August 2013
MVC Ajax Post Requirements
MVC Ajax Post Requirements
Does the ActionResult Method in the Controller require the attribute
[HttpPost] to successfully respond to an ajax post from JQuery?
$.ajax({
url: "~/../../User/AssignPermission",
type: "POST",
data: $.postify({ "p_permId": optionSelectedPerm.value, "p_UserId":
iUserId }),
cache: false,
success: function () {
alert("Success");
},
error: function () {
alert("FAIL");
}
});
Controller::
[HttpPost]
public ActionResult AssignPermission(int p_permId, int p_Userid)
{
blah blah blah dance with the provided Id's
persist new permission for user to Disk
return RedirectToAction("UserPermissions", "User", new {
uzrEditId = p_Userid });
}
I was successful getting back into the controller with a GET ( including
the data values as parameters) but this isnt allowing me to update the
View so I want to try a redirect but this will need a POST. Of course it
was a different ActionResult in the controller which danced with View
Model lists.. That should be pointless since UserPermissions", "User" does
that all in the beginning
function SwapPermission(optionSelectedPerm) {
$.ajax({
url: '~/../../User/AssignPermission',
data: $.postify({ "p_permId": optionSelectedPerm.value
}),
type: 'GET',
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function () {
},
fail: function () {
alert("There was a problem saving the Permission
assignment");
}
});
}
Does the ActionResult Method in the Controller require the attribute
[HttpPost] to successfully respond to an ajax post from JQuery?
$.ajax({
url: "~/../../User/AssignPermission",
type: "POST",
data: $.postify({ "p_permId": optionSelectedPerm.value, "p_UserId":
iUserId }),
cache: false,
success: function () {
alert("Success");
},
error: function () {
alert("FAIL");
}
});
Controller::
[HttpPost]
public ActionResult AssignPermission(int p_permId, int p_Userid)
{
blah blah blah dance with the provided Id's
persist new permission for user to Disk
return RedirectToAction("UserPermissions", "User", new {
uzrEditId = p_Userid });
}
I was successful getting back into the controller with a GET ( including
the data values as parameters) but this isnt allowing me to update the
View so I want to try a redirect but this will need a POST. Of course it
was a different ActionResult in the controller which danced with View
Model lists.. That should be pointless since UserPermissions", "User" does
that all in the beginning
function SwapPermission(optionSelectedPerm) {
$.ajax({
url: '~/../../User/AssignPermission',
data: $.postify({ "p_permId": optionSelectedPerm.value
}),
type: 'GET',
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function () {
},
fail: function () {
alert("There was a problem saving the Permission
assignment");
}
});
}
django template read JSON field in {{ jsonObject }}
django template read JSON field in {{ jsonObject }}
I need to get one field in my JSON string which comes from
django-rest-framework. E.g. {{ myJsonString.pk }}
{% for obj in cols %}
obj={{obj|pprint}} <br><br><br> {# It prints the string in JSON
format, it comes from from django-rest-framework #}
obj.pk ={{ obj.pk }} {# Needed field in JSON string! #}
<div class="widget" id="my-id-{{ obj.pk }}">
</div> {# END class="widget" #}
{% endfor %}
Is it possible? Or I have to create a template filter similar to
http://eugene-yeo.me/2012/09/9/convert-queryset-json-template-filter/
Thanks,
D
I need to get one field in my JSON string which comes from
django-rest-framework. E.g. {{ myJsonString.pk }}
{% for obj in cols %}
obj={{obj|pprint}} <br><br><br> {# It prints the string in JSON
format, it comes from from django-rest-framework #}
obj.pk ={{ obj.pk }} {# Needed field in JSON string! #}
<div class="widget" id="my-id-{{ obj.pk }}">
</div> {# END class="widget" #}
{% endfor %}
Is it possible? Or I have to create a template filter similar to
http://eugene-yeo.me/2012/09/9/convert-queryset-json-template-filter/
Thanks,
D
Tuesday, 27 August 2013
[OpenGL3.2]Error in glTexSubImage2D with GL_TEXTURE_CUBE_MAP as target and height and width are not same
[OpenGL3.2]Error in glTexSubImage2D with GL_TEXTURE_CUBE_MAP as target and
height and width are not same
I am using glTexSubImage2D with GL_TEXTURE_CUBE_MAP as target. It is
giving me GL_INVALID_VALUE on my driver if height and width are not same .
I am not sure of this type of driver behavior.As far as i know, it is not
mentioned in glTexSubImage2D man page on Khronos.org. Does anyone faced
this?
height and width are not same
I am using glTexSubImage2D with GL_TEXTURE_CUBE_MAP as target. It is
giving me GL_INVALID_VALUE on my driver if height and width are not same .
I am not sure of this type of driver behavior.As far as i know, it is not
mentioned in glTexSubImage2D man page on Khronos.org. Does anyone faced
this?
Why Oracle ascii function return >255 code?
Why Oracle ascii function return >255 code?
When using Oracle ascii function:
select ascii('A') from dual;
It return 65 is right.
But,when i using:
select ascii('ü') from dual;
The return is 55004.The ascii can represent>255???
How to explain?
Help!!!!
When using Oracle ascii function:
select ascii('A') from dual;
It return 65 is right.
But,when i using:
select ascii('ü') from dual;
The return is 55004.The ascii can represent>255???
How to explain?
Help!!!!
Is there a way to follow redirects with command line cURL
Is there a way to follow redirects with command line cURL
I know that in a php script:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
will follow redirects. Is there a way to follow redirects with command
line cURL?
I know that in a php script:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
will follow redirects. Is there a way to follow redirects with command
line cURL?
Likedin sharing urls / not parsing open graph
Likedin sharing urls / not parsing open graph
The Linkedin documentation can be found here
As it says, it needs:
og:title
og:description
og:image
og:url
Here is an example of my wordpress blog source code that for simplicity I
use Jetpack plug-in:
<!-- Jetpack Open Graph Tags -->
<meta property="og:type" content="article" />
<meta property="og:title" content="Starbucks Netherlands Intel" />
<meta property="og:url"
content="http://lorentzos.com/starbucks-netherlands-intel/" />
<meta property="og:description" content="Today I had some free time at
work. I wanted to play more with Foursquare APIs. So the question:
"What is the correlation of the Starbucks Chain in the
Netherlands?". Methodology: I found all the p..." />
<meta property="og:site_name" content="Dionysis Lorentzos" />
<meta property="og:image"
content="http://lorentzos.com/wp-content/uploads/2013/08/starbucks-intel-nl-238x300.png"
/>
I Facebook it works great, or you can see the meta data here. However
LinkedIn is more stubborn and doesn't really parse the data even the If
you're unable to set Open Graph tags within the page that's being shared,
LinkedIn will attempt to fetch the content automatically by determining
the title, description, thumbnail image, etc.
I know that I don't have the og:image:width tag but Linkedin doesn't even
parse title, description or url. Any ideas to debug it?
The Linkedin documentation can be found here
As it says, it needs:
og:title
og:description
og:image
og:url
Here is an example of my wordpress blog source code that for simplicity I
use Jetpack plug-in:
<!-- Jetpack Open Graph Tags -->
<meta property="og:type" content="article" />
<meta property="og:title" content="Starbucks Netherlands Intel" />
<meta property="og:url"
content="http://lorentzos.com/starbucks-netherlands-intel/" />
<meta property="og:description" content="Today I had some free time at
work. I wanted to play more with Foursquare APIs. So the question:
"What is the correlation of the Starbucks Chain in the
Netherlands?". Methodology: I found all the p..." />
<meta property="og:site_name" content="Dionysis Lorentzos" />
<meta property="og:image"
content="http://lorentzos.com/wp-content/uploads/2013/08/starbucks-intel-nl-238x300.png"
/>
I Facebook it works great, or you can see the meta data here. However
LinkedIn is more stubborn and doesn't really parse the data even the If
you're unable to set Open Graph tags within the page that's being shared,
LinkedIn will attempt to fetch the content automatically by determining
the title, description, thumbnail image, etc.
I know that I don't have the og:image:width tag but Linkedin doesn't even
parse title, description or url. Any ideas to debug it?
assume UTC from front end
assume UTC from front end
I can define how ASP.NET MVC performs the model binding for DateTime
values via entries like this:
in the web.config file. Is there a way to define that everything that
comes from the front end is always UTC? Thanks.
Christian
I can define how ASP.NET MVC performs the model binding for DateTime
values via entries like this:
in the web.config file. Is there a way to define that everything that
comes from the front end is always UTC? Thanks.
Christian
How to catch PL/SQL errors from a pipelined function called from Java
How to catch PL/SQL errors from a pipelined function called from Java
In our Oracle(11g)-based application, we are making heavy use of pipelined
functions. Now it turns out that error reporting from such functions is
difficult, as shown in the (cut-down) example below. The procedure exists
to be called from Java, and it shall receive errors occurring anywhere
during the PL/SQL execution.
ORACLE part:
set serveroutput on
create table dummy (id NUMBER);
create or replace package mytest
as
type t_rec is record (id integer);
type t_tab is table of t_rec;
type t_ref_cur IS REF CURSOR RETURN t_rec;
function foo
return t_tab pipelined;
procedure bar( p_ref_cur out t_ref_cur);
end mytest;
/
show errors
create or replace package body mytest
as
function foo
return t_tab pipelined
is
v_cur SYS_REFCURSOR;
v_sql varchar2(2000);
v_rec t_rec;
begin
v_sql := 'select wrong_column from DUMMY';
open v_cur for v_sql;
loop
fetch v_cur into v_rec;
exit when v_cur%notfound;
pipe row (v_rec);
end loop;
exception
when no_data_needed then
null;
when others then
dbms_output.put_line(SQLCODE||' '||sqlerrm );
raise no_data_found;
end foo;
procedure bar( p_ref_cur out t_ref_cur)
is
begin
open p_ref_cur for select * from table(foo);
end bar;
end mytest;
/
show errors
-- call procedure bar() from pl/sql
set serveroutput on
declare v_ref_cur mytest.t_ref_cur;
v_rec mytest.t_rec;
begin
mytest.bar(v_ref_cur);
loop
fetch v_ref_cur into v_rec;
exit when v_ref_cur%notfound;
dbms_output.put_line(v_rec.id);
end loop;
end;
/
show errors
Running the above function results in the exception being shown:
ORA-00904: "WRONG_COLUMN": invalid column name
Java part:
package test1;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import oracle.jdbc.OracleTypes;
public class start {
public static void main(String[] args)
{
try
{
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@...", "…",
"…");
CallableStatement stmt = con.prepareCall("BEGIN mytest.bar(?);
END;");
stmt.registerOutParameter(1, OracleTypes.CURSOR);
stmt.executeQuery();
ResultSet rs = (ResultSet)stmt.getObject(1);
while (rs.next())
{
System.out.println(rs.getInt(1));
}
stmt.close();
con.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
Exception will be not catched. ResultSet is empty.
Is this the expected behavior? Do we do something wrong? Does a workaround
exist?
In our Oracle(11g)-based application, we are making heavy use of pipelined
functions. Now it turns out that error reporting from such functions is
difficult, as shown in the (cut-down) example below. The procedure exists
to be called from Java, and it shall receive errors occurring anywhere
during the PL/SQL execution.
ORACLE part:
set serveroutput on
create table dummy (id NUMBER);
create or replace package mytest
as
type t_rec is record (id integer);
type t_tab is table of t_rec;
type t_ref_cur IS REF CURSOR RETURN t_rec;
function foo
return t_tab pipelined;
procedure bar( p_ref_cur out t_ref_cur);
end mytest;
/
show errors
create or replace package body mytest
as
function foo
return t_tab pipelined
is
v_cur SYS_REFCURSOR;
v_sql varchar2(2000);
v_rec t_rec;
begin
v_sql := 'select wrong_column from DUMMY';
open v_cur for v_sql;
loop
fetch v_cur into v_rec;
exit when v_cur%notfound;
pipe row (v_rec);
end loop;
exception
when no_data_needed then
null;
when others then
dbms_output.put_line(SQLCODE||' '||sqlerrm );
raise no_data_found;
end foo;
procedure bar( p_ref_cur out t_ref_cur)
is
begin
open p_ref_cur for select * from table(foo);
end bar;
end mytest;
/
show errors
-- call procedure bar() from pl/sql
set serveroutput on
declare v_ref_cur mytest.t_ref_cur;
v_rec mytest.t_rec;
begin
mytest.bar(v_ref_cur);
loop
fetch v_ref_cur into v_rec;
exit when v_ref_cur%notfound;
dbms_output.put_line(v_rec.id);
end loop;
end;
/
show errors
Running the above function results in the exception being shown:
ORA-00904: "WRONG_COLUMN": invalid column name
Java part:
package test1;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import oracle.jdbc.OracleTypes;
public class start {
public static void main(String[] args)
{
try
{
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@...", "…",
"…");
CallableStatement stmt = con.prepareCall("BEGIN mytest.bar(?);
END;");
stmt.registerOutParameter(1, OracleTypes.CURSOR);
stmt.executeQuery();
ResultSet rs = (ResultSet)stmt.getObject(1);
while (rs.next())
{
System.out.println(rs.getInt(1));
}
stmt.close();
con.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
Exception will be not catched. ResultSet is empty.
Is this the expected behavior? Do we do something wrong? Does a workaround
exist?
How to add css for active item of a list in Sencha touch 2.2.1
How to add css for active item of a list in Sencha touch 2.2.1
I am using list in sencha touch 2.2.1. And I have to add css only on
active item of that list. I try following:
listItems.getActiveItem().addCls('gigaspace');
But it add that 'gigaspace' class to whole list and not to active item.
So, how can I add css for active item of a list.
I am using list in sencha touch 2.2.1. And I have to add css only on
active item of that list. I try following:
listItems.getActiveItem().addCls('gigaspace');
But it add that 'gigaspace' class to whole list and not to active item.
So, how can I add css for active item of a list.
Monday, 26 August 2013
Merge two array
Merge two array
I have two arrays
Array
(
[rows] => Array
(
[0] => Array
(
[color] => 0
)
[1] => Array
(
[color] => 1
)
)
)
and
Array
(
[rows] => Array
(
[0] => Array
(
[kaka] => 0
)
[1] => Array
(
[kaka] => 1
)
)
)
i want to merge that array, so the output is
Array
(
[rows] => Array
(
[0] => Array
(
[color] => 0,
[kaka] => 0
)
[1] => Array
(
[color] => 1,
[kaka] => 0
)
)
)
can anyone help me?
I have two arrays
Array
(
[rows] => Array
(
[0] => Array
(
[color] => 0
)
[1] => Array
(
[color] => 1
)
)
)
and
Array
(
[rows] => Array
(
[0] => Array
(
[kaka] => 0
)
[1] => Array
(
[kaka] => 1
)
)
)
i want to merge that array, so the output is
Array
(
[rows] => Array
(
[0] => Array
(
[color] => 0,
[kaka] => 0
)
[1] => Array
(
[color] => 1,
[kaka] => 0
)
)
)
can anyone help me?
Inverted Axis Panning Direction with 2 Range Axes in JFreeChart?
Inverted Axis Panning Direction with 2 Range Axes in JFreeChart?
I have a chart with 2 range axes. I have the datasets mapped properly to
the two axes, but when I pan the chart, they move in opposite directions
(one goes up, one goes down)? Is there a way to invert the pan direction
while maintain the order of the axis labels? I want negative values on top
of both axes, and positive on the bottom; I just need the movements
synced.
It's not obvious to me if the pan direction is setable in any way
(although I could see this being desirable).
I asked this on the official JFreechart Forum, but haven't had any luck
with replies yet.
I have a chart with 2 range axes. I have the datasets mapped properly to
the two axes, but when I pan the chart, they move in opposite directions
(one goes up, one goes down)? Is there a way to invert the pan direction
while maintain the order of the axis labels? I want negative values on top
of both axes, and positive on the bottom; I just need the movements
synced.
It's not obvious to me if the pan direction is setable in any way
(although I could see this being desirable).
I asked this on the official JFreechart Forum, but haven't had any luck
with replies yet.
error while casting a synchronized LinkedList
error while casting a synchronized LinkedList
I have a simple code:
private List<String> requests = Collections.synchronizedList(new
LinkedList<String>());
and
synchronized (requests) {
((LinkedList<String>)requests).addLast(message);
}
at runtime I get this error:
FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:2144)
at android.view.View.performClick(View.java:2485)
at android.view.View$PerformClick.run(View.java:9080)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at android.view.View$1.onClick(View.java:2139)
... 11 more
Caused by: java.lang.ClassCastException:
java.util.Collections$SynchronizedList
at
com.countryst.nabard.turnbased.client.networking.ClientNetworking.login(ClientNetworking.java:72)
at
com.countryst.nabard.turnbased.client.MainActivity.loginToServer(MainActivity.java:87)
at
com.countryst.nabard.turnbased.client.MainActivity.onButtonClicked(MainActivity.java:217)
... 14 more
This is part of an android program, I have similar code in my plain java
code and works fine.
I have a simple code:
private List<String> requests = Collections.synchronizedList(new
LinkedList<String>());
and
synchronized (requests) {
((LinkedList<String>)requests).addLast(message);
}
at runtime I get this error:
FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:2144)
at android.view.View.performClick(View.java:2485)
at android.view.View$PerformClick.run(View.java:9080)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at android.view.View$1.onClick(View.java:2139)
... 11 more
Caused by: java.lang.ClassCastException:
java.util.Collections$SynchronizedList
at
com.countryst.nabard.turnbased.client.networking.ClientNetworking.login(ClientNetworking.java:72)
at
com.countryst.nabard.turnbased.client.MainActivity.loginToServer(MainActivity.java:87)
at
com.countryst.nabard.turnbased.client.MainActivity.onButtonClicked(MainActivity.java:217)
... 14 more
This is part of an android program, I have similar code in my plain java
code and works fine.
TreeSet and compareTo() method. Single sort or multiple sorts
TreeSet and compareTo() method. Single sort or multiple sorts
Im currently working on a program, where im using a TreeSet to store
unique keys. I'm using a TreeSet, because I want them sorted.
As of now, I have been making a TreeSet object, and added the strings
one-at-a-time, when needed.
TreeSet set = new TreeSet();
set.add("How");
set.add("Are");
set.add("You");
Supposedly, the TreeSet uses the compareTo method in the Compareable
interface, to sort the strings. That would mean that the TreeSet would
have to do a sort each time I add a String to it.
Now my question is this: Would it be more efficient to create a HashSet
and then create the TreeSet after all strings are added to the HashSet?
TreeSet<String> treeSet = new TreeSet<String>(set);
My thoughts are going about whether the TreeSet would only need to do a
single sort that way.
Thanks in advance
Im currently working on a program, where im using a TreeSet to store
unique keys. I'm using a TreeSet, because I want them sorted.
As of now, I have been making a TreeSet object, and added the strings
one-at-a-time, when needed.
TreeSet set = new TreeSet();
set.add("How");
set.add("Are");
set.add("You");
Supposedly, the TreeSet uses the compareTo method in the Compareable
interface, to sort the strings. That would mean that the TreeSet would
have to do a sort each time I add a String to it.
Now my question is this: Would it be more efficient to create a HashSet
and then create the TreeSet after all strings are added to the HashSet?
TreeSet<String> treeSet = new TreeSet<String>(set);
My thoughts are going about whether the TreeSet would only need to do a
single sort that way.
Thanks in advance
create a json string in perl
create a json string in perl
I am trying to create a json string in perl that outputs something like this:
{"d":{"success":false, "error":"key is required"}}
I have figured out how to do it without the "d" using this example:
my %rec_hash = ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
my $json = encode_json \%rec_hash;
print "$json\n";
but not sure what I'm suppose to do with the extra level
I am trying to create a json string in perl that outputs something like this:
{"d":{"success":false, "error":"key is required"}}
I have figured out how to do it without the "d" using this example:
my %rec_hash = ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
my $json = encode_json \%rec_hash;
print "$json\n";
but not sure what I'm suppose to do with the extra level
how to specify a ontrol file in dh_gencontrol
how to specify a ontrol file in dh_gencontrol
i am novice in debian packaging. i want to create a specific debian
control file from a template file. so in rules file i put this option to
specify my new control file: dh_gencontrol -- "-cdebian/control_new"
this file contains all information about binary to build! but i have
always this error :
dh_gencontrol -- "-cdebian/control_new" dh_gencontrol: No packages to build.
cause it checks debian/control!!
cat control_new:
Source: xxx-xxx
Section: bb/web
Priority: optional
Maintainer: joujou joujou
Standards-Version: 3.8.2
Package: do-xxx-xxx
Architecture: all
Description: my description
cat control:
Source: xxx-xxx
Section: bb/web
Priority: optional
Maintainer: joujou joujou
Standards-Version: 3.8.2
what shall i do?
Thanks in advance
i am novice in debian packaging. i want to create a specific debian
control file from a template file. so in rules file i put this option to
specify my new control file: dh_gencontrol -- "-cdebian/control_new"
this file contains all information about binary to build! but i have
always this error :
dh_gencontrol -- "-cdebian/control_new" dh_gencontrol: No packages to build.
cause it checks debian/control!!
cat control_new:
Source: xxx-xxx
Section: bb/web
Priority: optional
Maintainer: joujou joujou
Standards-Version: 3.8.2
Package: do-xxx-xxx
Architecture: all
Description: my description
cat control:
Source: xxx-xxx
Section: bb/web
Priority: optional
Maintainer: joujou joujou
Standards-Version: 3.8.2
what shall i do?
Thanks in advance
import content of a xls file into several xml files
import content of a xls file into several xml files
I have an .xlsx file with the next format:
I need to create files:
/A/value.xml
/B/value.xml
/C/value.xml
/D/value.xml
with the content respectively:
/A/value.xml:
<root name =''1"> a </root>
<root name =''2"> aa </root>
<root name =''3"> aaa </root>
<root name =''4"> aaaa </root>
/B/value.xml:
<root name =''1"> b </root>
<root name =''2"> bb </root>
<root name =''3"> bbb </root>
<root name =''4"> bbbb </root>
and so on...
How to do it?
Thanks in advance.
I have an .xlsx file with the next format:
I need to create files:
/A/value.xml
/B/value.xml
/C/value.xml
/D/value.xml
with the content respectively:
/A/value.xml:
<root name =''1"> a </root>
<root name =''2"> aa </root>
<root name =''3"> aaa </root>
<root name =''4"> aaaa </root>
/B/value.xml:
<root name =''1"> b </root>
<root name =''2"> bb </root>
<root name =''3"> bbb </root>
<root name =''4"> bbbb </root>
and so on...
How to do it?
Thanks in advance.
Remove unvanted clicks in generated sound in AS3
Remove unvanted clicks in generated sound in AS3
I am having the following problem when generating sound wave in Flash.
This is the generator part :
const SAMPLING_RATE:int = 44100;
const TWO_PI:Number = 2 * Math.PI;
const TWO_PI_OVER_SR:Number = TWO_PI / SAMPLING_RATE;
const SAMPLE_SIZE:int = 8192 / 4;
function generateSine(fq:Number):ByteArray
{
var bytes:ByteArray = new ByteArray();
var sample:Number;
var amp:Number = 1;
for (var i:int=0; i<SAMPLE_SIZE; i++)
{
sample = amp* Math.sin(i * TWO_PI_OVER_SR * fq );
bytes.writeFloat(sample);
}
bytes.position = 0;
return bytes;
}
and this is the playback part:
function playbackSampleHandler(event:SampleDataEvent):void
{
var sample:Number;
for (var i:int = 0; i < SAMPLE_SIZE && soundData.bytesAvailable; i++)
{
sample = soundData.readFloat();
event.data.writeFloat(sample);
event.data.writeFloat(sample);
}
}
function onClickPlay(e:MouseEvent)
{
soundData= new ByteArray();
soundData.writeBytes(generateSine(440),0,generateSine(440).length);
soundData.position = 0;
morphedSound.addEventListener(SampleDataEvent.SAMPLE_DATA,
playbackSampleHandler);
soundChannel = morphedSound.play();
}
Quick explanation: I basically write values for the sine function into the
ByteArray and than playback handler reads that array and plays back the
sound. I write only one 8192/4 sample buffer.
Problem: My problem is that when you do this there are annoying clicks on
the end of sound, which are the artifacts of sine wave being cut on a
value other than 0. So my question is how can I avoid this?
Bonus: I would also like to know how can I generate for example exactly
100 ms of sine wave when buffers in Flash are so strict i.e. from 2048 to
8192 ?
Links: If it helps my code is based on this tutorial
http://www.bit-101.com/blog/?p=2669 and my own explorations.
I am having the following problem when generating sound wave in Flash.
This is the generator part :
const SAMPLING_RATE:int = 44100;
const TWO_PI:Number = 2 * Math.PI;
const TWO_PI_OVER_SR:Number = TWO_PI / SAMPLING_RATE;
const SAMPLE_SIZE:int = 8192 / 4;
function generateSine(fq:Number):ByteArray
{
var bytes:ByteArray = new ByteArray();
var sample:Number;
var amp:Number = 1;
for (var i:int=0; i<SAMPLE_SIZE; i++)
{
sample = amp* Math.sin(i * TWO_PI_OVER_SR * fq );
bytes.writeFloat(sample);
}
bytes.position = 0;
return bytes;
}
and this is the playback part:
function playbackSampleHandler(event:SampleDataEvent):void
{
var sample:Number;
for (var i:int = 0; i < SAMPLE_SIZE && soundData.bytesAvailable; i++)
{
sample = soundData.readFloat();
event.data.writeFloat(sample);
event.data.writeFloat(sample);
}
}
function onClickPlay(e:MouseEvent)
{
soundData= new ByteArray();
soundData.writeBytes(generateSine(440),0,generateSine(440).length);
soundData.position = 0;
morphedSound.addEventListener(SampleDataEvent.SAMPLE_DATA,
playbackSampleHandler);
soundChannel = morphedSound.play();
}
Quick explanation: I basically write values for the sine function into the
ByteArray and than playback handler reads that array and plays back the
sound. I write only one 8192/4 sample buffer.
Problem: My problem is that when you do this there are annoying clicks on
the end of sound, which are the artifacts of sine wave being cut on a
value other than 0. So my question is how can I avoid this?
Bonus: I would also like to know how can I generate for example exactly
100 ms of sine wave when buffers in Flash are so strict i.e. from 2048 to
8192 ?
Links: If it helps my code is based on this tutorial
http://www.bit-101.com/blog/?p=2669 and my own explorations.
Sunday, 25 August 2013
Proximity Alert Sample Code
Proximity Alert Sample Code
How to use the proximity alert to notify user when they are close to their
destinations?
Can someone please give me a link with sample code, since Ive never worked
with an app like this.
I need a solution asap
Thanks in advance
How to use the proximity alert to notify user when they are close to their
destinations?
Can someone please give me a link with sample code, since Ive never worked
with an app like this.
I need a solution asap
Thanks in advance
Python list slicing efficiency
Python list slicing efficiency
In the following code:
def listSum(alist):
"""Get sum of numbers in a list recursively."""
sum = 0
if len(alist) == 1:
return alist[0]
else:
return alist[0] + listSum(alist[1:])
return sum
is a new list created every time when I do listSum(alist[1:])?
If yes, is this the recommended way or can I do something more efficient?
(Not for the specific function -this serves as an example-, but rather
when I want to process a specific part of a list in general.)
In the following code:
def listSum(alist):
"""Get sum of numbers in a list recursively."""
sum = 0
if len(alist) == 1:
return alist[0]
else:
return alist[0] + listSum(alist[1:])
return sum
is a new list created every time when I do listSum(alist[1:])?
If yes, is this the recommended way or can I do something more efficient?
(Not for the specific function -this serves as an example-, but rather
when I want to process a specific part of a list in general.)
Using the value of an XML element in XSLT transform
Using the value of an XML element in XSLT transform
I have an XML file like this:
<Root>
<Sensor xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<position_x>2170</position_x>
<position_y>1830</position_y>
<module_number>10</module_number>
<disabled>false</disabled>
<sequence_number>0</sequence_number>
<id_number>0</id_number>
<channel_number>10</channel_number>
</Sensor>
</Root>
And I have an XSL file like this:
<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
version='1.0'>
<xsl:template match='/'>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<xsl:for-each select="Root/Sensor">
<g transform="translate(position_x,position_y)" id="S">
<text x="118" y="20" font-family="sans-serif" font-size="18px"
font-weight="bold" fill="black"><xsl:value-of
select="Root/Sensor/sequence_number" /></text>
<rect x="12" y="32" width="8" height="18" fill="#FFFFFF"
stroke="black" stroke-width="1" />
<text x="23" y="97" font-family="sans-serif" font-size="16px"
fill="black"><xsl:value-of select="Root/Sensor/id_number"
/></text>
<text x="23" y="117" font-family="sans-serif" font-size="16px"
fill="black"><xsl:value-of select="Root/Sensor/channel_number"
/></text>
<text x="142" y="80" font-family="sans-serif" font-size="20px"
font-weight="bold" fill="black">S<xsl:value-of
select="Root/Sensor/module_number" /></text>
</g>
</xsl:for-each>
</svg>
</xsl:template>
</xsl:stylesheet>
The problem is I want the value of position_x (2170) and position_y
(1830), in my transform. But I can't work out how to put them there. It
seems I'm not able to put
<xsl:value-of select="Root/Sensor/position_x" />
into the transform.
Is there a way to achieve this or am I going about this the wrong way?
EDIT:
If I try to have the line:
<g transform="translate(<xsl:value-of select="position_x"/>,<xsl:value-of
select="position_y" />)" id="S">
I get the error: '<', hexadecimal value 0x3C, is illegal in XML attribute
values.
I have an XML file like this:
<Root>
<Sensor xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<position_x>2170</position_x>
<position_y>1830</position_y>
<module_number>10</module_number>
<disabled>false</disabled>
<sequence_number>0</sequence_number>
<id_number>0</id_number>
<channel_number>10</channel_number>
</Sensor>
</Root>
And I have an XSL file like this:
<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
version='1.0'>
<xsl:template match='/'>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<xsl:for-each select="Root/Sensor">
<g transform="translate(position_x,position_y)" id="S">
<text x="118" y="20" font-family="sans-serif" font-size="18px"
font-weight="bold" fill="black"><xsl:value-of
select="Root/Sensor/sequence_number" /></text>
<rect x="12" y="32" width="8" height="18" fill="#FFFFFF"
stroke="black" stroke-width="1" />
<text x="23" y="97" font-family="sans-serif" font-size="16px"
fill="black"><xsl:value-of select="Root/Sensor/id_number"
/></text>
<text x="23" y="117" font-family="sans-serif" font-size="16px"
fill="black"><xsl:value-of select="Root/Sensor/channel_number"
/></text>
<text x="142" y="80" font-family="sans-serif" font-size="20px"
font-weight="bold" fill="black">S<xsl:value-of
select="Root/Sensor/module_number" /></text>
</g>
</xsl:for-each>
</svg>
</xsl:template>
</xsl:stylesheet>
The problem is I want the value of position_x (2170) and position_y
(1830), in my transform. But I can't work out how to put them there. It
seems I'm not able to put
<xsl:value-of select="Root/Sensor/position_x" />
into the transform.
Is there a way to achieve this or am I going about this the wrong way?
EDIT:
If I try to have the line:
<g transform="translate(<xsl:value-of select="position_x"/>,<xsl:value-of
select="position_y" />)" id="S">
I get the error: '<', hexadecimal value 0x3C, is illegal in XML attribute
values.
How to make the client perform a http post with php?
How to make the client perform a http post with php?
I'm building some efficiency tools for a crappy website. This website uses
http-posts for some of it's navigation. What I need is that when a user
runs a script on an url (redirect.php), I want the client to post to an
url on an external site, with some variables.
I know I could do this with javascript, creating a form and posting to it,
but I would prefer doing it with php if possible. It needs to be the
client that get's forwarded, because they are authenticated with the
website that I'm sending them to.
I'm building some efficiency tools for a crappy website. This website uses
http-posts for some of it's navigation. What I need is that when a user
runs a script on an url (redirect.php), I want the client to post to an
url on an external site, with some variables.
I know I could do this with javascript, creating a form and posting to it,
but I would prefer doing it with php if possible. It needs to be the
client that get's forwarded, because they are authenticated with the
website that I'm sending them to.
Examples of Law of Iterated Expectations
Examples of Law of Iterated Expectations
There is an urn which contains 3 marbles (2 black and 1 white). The person
who gets to pick the white marble gets to win $1000 whereas the individual
who picks the black marble walks away with nothing. The marbles that are
taken out are not replaced. Assuming that there are only 2 individuals,
how to show, using LIE that it does not matter whether you are the first
or second to pick the marble? Thanks
There is an urn which contains 3 marbles (2 black and 1 white). The person
who gets to pick the white marble gets to win $1000 whereas the individual
who picks the black marble walks away with nothing. The marbles that are
taken out are not replaced. Assuming that there are only 2 individuals,
how to show, using LIE that it does not matter whether you are the first
or second to pick the marble? Thanks
Saturday, 24 August 2013
My rails s and other commands dont work anymore
My rails s and other commands dont work anymore
i am new to rails . i have rcently installed the mysql2 gem with the
following command
gem install mysql2 –version=0.2.7 — –with-mysql-lib="c:\xampp\mysql\lib"
–with-mysql->include="c:\xampp\mysql\include"
i am using xampp on windows with rails version 3 .... the gem was actually
installed but none of the generate commands work im getting the following
errors
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/mysql2-0.3.13/lib/mysql2.rb
:8:in require': 126: The specified module could not be found. -
C:/RailsInsta
ller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/mysql2-0.3.13/lib/mysql2/mysql2.so
(Load Error) from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/mysql2-0.3.13/
lib/mysql2.rb:8:in' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/
lib/bundler/runtime.rb:72:in require' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/
lib/bundler/runtime.rb:72:inblock (2 levels) in require' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/
lib/bundler/runtime.rb:70:in each' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/
lib/bundler/runtime.rb:70:inblock in require' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/
lib/bundler/runtime.rb:59:in each' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/
lib/bundler/runtime.rb:59:inrequire' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/
lib/bundler.rb:132:in require' from
C:/Sites/depot4/config/application.rb:7:in' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-3.2.1
3/lib/rails/commands.rb:24:in require' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-3.2.1
v3/lib/rails/commands.rb:24:in' from script/rails:6:in require' v from
script/rails:6:in'
i am new to rails . i have rcently installed the mysql2 gem with the
following command
gem install mysql2 –version=0.2.7 — –with-mysql-lib="c:\xampp\mysql\lib"
–with-mysql->include="c:\xampp\mysql\include"
i am using xampp on windows with rails version 3 .... the gem was actually
installed but none of the generate commands work im getting the following
errors
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/mysql2-0.3.13/lib/mysql2.rb
:8:in require': 126: The specified module could not be found. -
C:/RailsInsta
ller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/mysql2-0.3.13/lib/mysql2/mysql2.so
(Load Error) from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/mysql2-0.3.13/
lib/mysql2.rb:8:in' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/
lib/bundler/runtime.rb:72:in require' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/
lib/bundler/runtime.rb:72:inblock (2 levels) in require' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/
lib/bundler/runtime.rb:70:in each' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/
lib/bundler/runtime.rb:70:inblock in require' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/
lib/bundler/runtime.rb:59:in each' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/
lib/bundler/runtime.rb:59:inrequire' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/
lib/bundler.rb:132:in require' from
C:/Sites/depot4/config/application.rb:7:in' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-3.2.1
3/lib/rails/commands.rb:24:in require' from
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-3.2.1
v3/lib/rails/commands.rb:24:in' from script/rails:6:in require' v from
script/rails:6:in'
Retrieving count of a core data relation
Retrieving count of a core data relation
I searched high and low but I couldn't find exactly what I was looking
for. My question is similar to this, but slightly different:
Core Data - Count of Related Records
Let's say I have a Car entity which has a one to many relation with a
Person entity. This means that the car could have multiple people driving
it, but each person drives only one car.
I want to be able to execute only one predicate wherein I could achieve
the following:
All cars which are 'red'.
Return only the 'Year' and 'Color' attributes of the matching car.
Return a count of how many people are driving this car (i.e the size of
the NSSet of People inside each resulting Car).
Is it possible to do all this with one query?
I know how to do this with multiple queries. I would just use
setPropertiesToFetch and use a filtered predicate to achieve 1 and 2
above. I would then perform another count query (countForFetchRequest) on
the Persons entity for every car to find how many Person(s) drive each
car.
The key is the 3rd requirement above. I want to do everything in one
predicate and I don't want to bring all of the Person entity objects into
memory (performance) on the initial query. Furthermore it hurts to call
another countForFetchRequest query for each car.
What's the best way to do this?
Thanks!
I searched high and low but I couldn't find exactly what I was looking
for. My question is similar to this, but slightly different:
Core Data - Count of Related Records
Let's say I have a Car entity which has a one to many relation with a
Person entity. This means that the car could have multiple people driving
it, but each person drives only one car.
I want to be able to execute only one predicate wherein I could achieve
the following:
All cars which are 'red'.
Return only the 'Year' and 'Color' attributes of the matching car.
Return a count of how many people are driving this car (i.e the size of
the NSSet of People inside each resulting Car).
Is it possible to do all this with one query?
I know how to do this with multiple queries. I would just use
setPropertiesToFetch and use a filtered predicate to achieve 1 and 2
above. I would then perform another count query (countForFetchRequest) on
the Persons entity for every car to find how many Person(s) drive each
car.
The key is the 3rd requirement above. I want to do everything in one
predicate and I don't want to bring all of the Person entity objects into
memory (performance) on the initial query. Furthermore it hurts to call
another countForFetchRequest query for each car.
What's the best way to do this?
Thanks!
zend server ce: Reset username
zend server ce: Reset username
I installed zend server on Ubuntu 12.04. I went to localhost:10082 to view
the console. I set a user name and password and then I was logged into the
console. The next day I tried logging in, but I must have forgotten the
user name.
How can I reset the user name?
I tried:
(1) Uninstall with apt-get purge `dpkg -l | grep zend | awk '{print $2}'`
(2) Reinstall, but the console does not ask me to set a user name and
password.
I also tried resetting my password because I thought the username was correct
(1) /usr/local/zend/bin/php /usr/local/zend/bin/gui_passwd.php <your new
password>
But still no luck.
How Can I remove everything and restart all over so I can reset the user
name?
I installed zend server on Ubuntu 12.04. I went to localhost:10082 to view
the console. I set a user name and password and then I was logged into the
console. The next day I tried logging in, but I must have forgotten the
user name.
How can I reset the user name?
I tried:
(1) Uninstall with apt-get purge `dpkg -l | grep zend | awk '{print $2}'`
(2) Reinstall, but the console does not ask me to set a user name and
password.
I also tried resetting my password because I thought the username was correct
(1) /usr/local/zend/bin/php /usr/local/zend/bin/gui_passwd.php <your new
password>
But still no luck.
How Can I remove everything and restart all over so I can reset the user
name?
Show link when all input fields filled
Show link when all input fields filled
I trying to use jquery to check a form with dynamically created formfields
to assure that all input fields have been filled prior to submission. I
would like to hide submit link until all the fields are filled. This is
what I have so far.
$( 'form#form_id' ).change(function(e) {
$(":input").each(function() {
if($(this).val() === ""){
$("#showlink").hide();
}else{
$("#showlink").show();
}
});
});
<div id="showlink">
<a href="#" id="submitBtnId" onclick="addDuctClickHandler();"
data-icon="check" data-role="button" data-inline="true"
data-theme="b">Submit Final Test</a>
</div>
Am I missing something here?
I trying to use jquery to check a form with dynamically created formfields
to assure that all input fields have been filled prior to submission. I
would like to hide submit link until all the fields are filled. This is
what I have so far.
$( 'form#form_id' ).change(function(e) {
$(":input").each(function() {
if($(this).val() === ""){
$("#showlink").hide();
}else{
$("#showlink").show();
}
});
});
<div id="showlink">
<a href="#" id="submitBtnId" onclick="addDuctClickHandler();"
data-icon="check" data-role="button" data-inline="true"
data-theme="b">Submit Final Test</a>
</div>
Am I missing something here?
do_shortcode doesnt extract WORKING shortcode
do_shortcode doesnt extract WORKING shortcode
I've got strange problem. I'm making page via Ajax and I need Form plugin
there. It uses shortcodes and it work well in default templates (twenty
thirteen), but it's not installed.
Array ( [embed] => __return_false
[wp_caption] => img_caption_shortcode
[caption] => img_caption_shortcode
[gallery] => gallery_shortcode
[audio] => wp_audio_shortcode
[video] => wp_video_shortcode )
it's list of installed shortcodes and [Form] isnt there, but it works via
the_post(); My Ajax script looks like this:
echo "<div id=\"aside\">";
$post = get_page_by_title('right');
$code = "Form";
echo extracted_shortcode();
echo $post->post_content;
echo "</div>";
function extracted_shortcode() looks like this:
global $post, $code;
$pattern = get_shortcode_regex();
preg_match("/".$pattern."/s", $post->post_content, $matches);
if (is_array($matches) && $matches[2] == $code) {
$shortcode = $matches[0];
echo do_shortcode($shortcode);
Can someone tell me where is problem? I'm doing this second day and
shortcode from gallery plugin at one of mine sites works well since 2
months.
I've got strange problem. I'm making page via Ajax and I need Form plugin
there. It uses shortcodes and it work well in default templates (twenty
thirteen), but it's not installed.
Array ( [embed] => __return_false
[wp_caption] => img_caption_shortcode
[caption] => img_caption_shortcode
[gallery] => gallery_shortcode
[audio] => wp_audio_shortcode
[video] => wp_video_shortcode )
it's list of installed shortcodes and [Form] isnt there, but it works via
the_post(); My Ajax script looks like this:
echo "<div id=\"aside\">";
$post = get_page_by_title('right');
$code = "Form";
echo extracted_shortcode();
echo $post->post_content;
echo "</div>";
function extracted_shortcode() looks like this:
global $post, $code;
$pattern = get_shortcode_regex();
preg_match("/".$pattern."/s", $post->post_content, $matches);
if (is_array($matches) && $matches[2] == $code) {
$shortcode = $matches[0];
echo do_shortcode($shortcode);
Can someone tell me where is problem? I'm doing this second day and
shortcode from gallery plugin at one of mine sites works well since 2
months.
Blank Nodes with edges in xdot file
Blank Nodes with edges in xdot file
I'm trying to show the control flow graph, but the problem that it always
shows it by blank nodes with edges which doesn't explain anything. What's
the problem?
I'm trying to show the control flow graph, but the problem that it always
shows it by blank nodes with edges which doesn't explain anything. What's
the problem?
ubuntu-12.04.2-desktop-amd64 on a toshiba C850-F22R wireless not working?
ubuntu-12.04.2-desktop-amd64 on a toshiba C850-F22R wireless not working?
I have installed ubuntu-12.04.2-desktop-amd64 on a toshiba C850-F22R. When
it connects via wireless, it works for about a minute than the wireless
stops working. The wireless connection still seem to be on according to
the wireless icon in the top right of the screen. no browser wants to load
any page. nothing wants to load from the internet. Would someone please
help me? Please!!! Kind Regards, William
I have installed ubuntu-12.04.2-desktop-amd64 on a toshiba C850-F22R. When
it connects via wireless, it works for about a minute than the wireless
stops working. The wireless connection still seem to be on according to
the wireless icon in the top right of the screen. no browser wants to load
any page. nothing wants to load from the internet. Would someone please
help me? Please!!! Kind Regards, William
set cornerRadius of class using UIButton appearanceWhenContainedIn
set cornerRadius of class using UIButton appearanceWhenContainedIn
so far I have changed image of all the button which are in my class by
using following code
[[UIButton appearanceWhenContainedIn:[FirstPadViewController class],
nil] setBackgroundImage:img forState:UIControlStateNormal];
as I dont want to create outlet thats why I have used this way so how can
I set cornerRadius using UIButton appearanceWhenContainedIn
any help will really decrease amount of code I will write thank you
so far I have changed image of all the button which are in my class by
using following code
[[UIButton appearanceWhenContainedIn:[FirstPadViewController class],
nil] setBackgroundImage:img forState:UIControlStateNormal];
as I dont want to create outlet thats why I have used this way so how can
I set cornerRadius using UIButton appearanceWhenContainedIn
any help will really decrease amount of code I will write thank you
Friday, 23 August 2013
Closing keyboard after button click (breaks if no EditText is focused on)
Closing keyboard after button click (breaks if no EditText is focused on)
I put this on my button listener:
InputMethodManager inputManager
=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
It works perfectly for when the keyboard is up: it closes the keyboard and
then continues its execution. The problem is that when no EditText was
ever pressed (none of them are highlighted/focused on), it breaks and the
app "stops working".
I guess it would be nice if I could check if an EditText had ever been
pressed.
I put this on my button listener:
InputMethodManager inputManager
=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
It works perfectly for when the keyboard is up: it closes the keyboard and
then continues its execution. The problem is that when no EditText was
ever pressed (none of them are highlighted/focused on), it breaks and the
app "stops working".
I guess it would be nice if I could check if an EditText had ever been
pressed.
Windows Communication Foundation Callbacks
Windows Communication Foundation Callbacks
I have a WCF callback server.The server invokes callbacks on registered
clients every 2 seconds. After few hours, the communication channel on the
client gets aborted and the client stops receiving callbacks. No exception
is thrown on the server side. If I restart the client without restarting
the server; all is well and the client starts to receive callbacks again.
I am not sure what is causing the callback channel on the client side to
abort. Note that no exception is thrown on the server side. Simply
restarting the client solves the problem and the client starts receiving
callbacks again, I am not sure as to why the callback channel on the
client side is getting aborted in the first place after a few hours. Any
suggestions will be most helpful. Thanks.
I have a WCF callback server.The server invokes callbacks on registered
clients every 2 seconds. After few hours, the communication channel on the
client gets aborted and the client stops receiving callbacks. No exception
is thrown on the server side. If I restart the client without restarting
the server; all is well and the client starts to receive callbacks again.
I am not sure what is causing the callback channel on the client side to
abort. Note that no exception is thrown on the server side. Simply
restarting the client solves the problem and the client starts receiving
callbacks again, I am not sure as to why the callback channel on the
client side is getting aborted in the first place after a few hours. Any
suggestions will be most helpful. Thanks.
php Frontend Scala/Play backend SOA - who has done it?
php Frontend Scala/Play backend SOA - who has done it?
I am thinking of a large scale application that uses php in frontend and
scala in backend - communicating over rest. php would run on nginx. I feel
more comfortable with php (and javascript) in the frontend because it is
easier to find frontend-devs for this stack.
Do people have real life experiences with that setup?
I am thinking of a large scale application that uses php in frontend and
scala in backend - communicating over rest. php would run on nginx. I feel
more comfortable with php (and javascript) in the frontend because it is
easier to find frontend-devs for this stack.
Do people have real life experiences with that setup?
Constructor in Constructor
Constructor in Constructor
is there some way how I can this do in C#? I can not use this(int,int) in
C# code. Can you write me some similar code which will be in C# and will
do the same things? Thank you! :)
public class JavaApplication2
{
public static class SomeClass
{
private int x;
private int y;
public SomeClass () { this(90,90); }
public SomeClass(int x, int y) { this.x = x; this.y = y; }
public void ShowMeValues ()
{
System.out.print(this.x);
System.out.print(this.y);
}
}
public static void main(String[] args)
{
SomeClass myclass = new SomeClass ();
myclass.ShowMeValues();
}
}
is there some way how I can this do in C#? I can not use this(int,int) in
C# code. Can you write me some similar code which will be in C# and will
do the same things? Thank you! :)
public class JavaApplication2
{
public static class SomeClass
{
private int x;
private int y;
public SomeClass () { this(90,90); }
public SomeClass(int x, int y) { this.x = x; this.y = y; }
public void ShowMeValues ()
{
System.out.print(this.x);
System.out.print(this.y);
}
}
public static void main(String[] args)
{
SomeClass myclass = new SomeClass ();
myclass.ShowMeValues();
}
}
Invoking immediate save for Shield UI ASP.NET Chart
Invoking immediate save for Shield UI ASP.NET Chart
I am using Shield UI ASP.NET Charts to show registered (and logged in)
users informations regarding their accounts. I went through the
documentation, but can't find a solution to the following thing: is it
possible to invoke an immediate save once the user clicks on the export
icon? I am enabling the save so:
<ExportOptions AllowExportToImage="true" AllowPrint="false" />
Are there any edditional parameters to be set?
I am using Shield UI ASP.NET Charts to show registered (and logged in)
users informations regarding their accounts. I went through the
documentation, but can't find a solution to the following thing: is it
possible to invoke an immediate save once the user clicks on the export
icon? I am enabling the save so:
<ExportOptions AllowExportToImage="true" AllowPrint="false" />
Are there any edditional parameters to be set?
Another nonlinear ODE of second order.
Another nonlinear ODE of second order.
I have problems finding out whether this initial value problem has an
explicit form solution or if it is possible to grind out a term-by-term
representation of this solution using power series expansions.
\begin{equation}f^{\prime\prime}(x)-\frac{f(x)-a}{b}f^{\prime}(x)^2=0,\quad
x\in(0,1),\qquad f(1/2)=a,\,f^{\prime}(1/2)=\sqrt{2\pi b}.\end{equation}
where $a\in\mathbb{R}$ and $b>0$ are constants.
I have tried the following: Find a solution for the easier problem,
\begin{equation}f^{\prime\prime}(x)-\frac{f(x)-a}{b}f^{\prime}(x)=0,\quad
x\in(0,1),\qquad f(1/2)=a,\,f^{\prime}(1/2)=\sqrt{2\pi b}.\end{equation}
where $a\in\mathbb{R}$ and $b>0$ are constants. Now, solve the original
system with the $f^{\prime}(x)^2$ replacing the easier $f^{\prime}(x)$.
However, I can't make sense of substituting the squared term into my
calculations...
Any help or hint is greatly appreciated.
I have problems finding out whether this initial value problem has an
explicit form solution or if it is possible to grind out a term-by-term
representation of this solution using power series expansions.
\begin{equation}f^{\prime\prime}(x)-\frac{f(x)-a}{b}f^{\prime}(x)^2=0,\quad
x\in(0,1),\qquad f(1/2)=a,\,f^{\prime}(1/2)=\sqrt{2\pi b}.\end{equation}
where $a\in\mathbb{R}$ and $b>0$ are constants.
I have tried the following: Find a solution for the easier problem,
\begin{equation}f^{\prime\prime}(x)-\frac{f(x)-a}{b}f^{\prime}(x)=0,\quad
x\in(0,1),\qquad f(1/2)=a,\,f^{\prime}(1/2)=\sqrt{2\pi b}.\end{equation}
where $a\in\mathbb{R}$ and $b>0$ are constants. Now, solve the original
system with the $f^{\prime}(x)^2$ replacing the easier $f^{\prime}(x)$.
However, I can't make sense of substituting the squared term into my
calculations...
Any help or hint is greatly appreciated.
Thursday, 22 August 2013
Printing out a binary tree with increased leading white spaces per level
Printing out a binary tree with increased leading white spaces per level
Lets say I have the tree a binary tree
0
1 2
3 4 5 6
7 8
At the moment I am printing them out traversing my tree in java (recursively)
private static void preorderTraverseTree(BinaryTree<Integer> tree,
Position<Integer> root) {
if (root != null) {
if (tree.hasLeft(root)) {
if(External(tree, tree.left(root))){
printQ(tree.left(root), true);
}
//if it not an external node, External(tree, Pos<Integer>)
else if(!External(tree, tree.left(root))){
//System.out.println(counter(3) + )
printR(tree.left(root), true);
//System.out.println("external");
}
preorderTraverseTree(tree, tree.left(root));
}
}
}
This is one part of the recursive the other part is the same but just for
the right roots rather than the left.
My printQ and R are as follow
private static void printQ(Position<Integer> result, boolean yes) {
if (yes) {
System.out.println("Y->Q" + result.element() + ":");
} else {
System.out.println("N->Q" + result.element() + ":");
}
}
private static void printR(Position<Integer> result, boolean yes) {
if (yes) {
System.out.println("Y->R" + result.element());
} else {
System.out.println("N->R" + result.element());
}
}
This just prints out the element at the node of which has been given in
and a statement true or false for Y and N to appear.
This prints out the following
Q0:
Y->Q1:
Y->Q3:
Y->R7
N->R8
N->R4
N->Q2:
Y->R5
N->R6 (R denotes an external node)
However my question is how can I get it to have leading white spaces to
denote the children for each node? Like so,
Q0:
Y->Q1:
Y->Q3:
Y->R7
N->R8
N->R4
N->Q3:
Y->R2
N->R8
Basically 3 white spaces per level, so 0 for the first, 6 for the second 9
for third and so on. Apart from Q0 which is the root of the tree, I wanted
this to have no white spaces.
EDIT: The children from the original ROOT are 1 and 2, so these should
have the same amount of whitespace before them
Things I have tried so far
Firstly I implemented a counter that counted 3 extra white spaces per
recursion, however I soon found that to be silly since it just printed
them all like a staircase.
I tried setting a boolean flag and making it add white space beforehand
dependent on whether the flag was true or false. Had no luck there
either...
Does anyone have an idea of how I could go about adding this in?
Cheers in advance,
Jim
PS: Post for any clarifications below
Lets say I have the tree a binary tree
0
1 2
3 4 5 6
7 8
At the moment I am printing them out traversing my tree in java (recursively)
private static void preorderTraverseTree(BinaryTree<Integer> tree,
Position<Integer> root) {
if (root != null) {
if (tree.hasLeft(root)) {
if(External(tree, tree.left(root))){
printQ(tree.left(root), true);
}
//if it not an external node, External(tree, Pos<Integer>)
else if(!External(tree, tree.left(root))){
//System.out.println(counter(3) + )
printR(tree.left(root), true);
//System.out.println("external");
}
preorderTraverseTree(tree, tree.left(root));
}
}
}
This is one part of the recursive the other part is the same but just for
the right roots rather than the left.
My printQ and R are as follow
private static void printQ(Position<Integer> result, boolean yes) {
if (yes) {
System.out.println("Y->Q" + result.element() + ":");
} else {
System.out.println("N->Q" + result.element() + ":");
}
}
private static void printR(Position<Integer> result, boolean yes) {
if (yes) {
System.out.println("Y->R" + result.element());
} else {
System.out.println("N->R" + result.element());
}
}
This just prints out the element at the node of which has been given in
and a statement true or false for Y and N to appear.
This prints out the following
Q0:
Y->Q1:
Y->Q3:
Y->R7
N->R8
N->R4
N->Q2:
Y->R5
N->R6 (R denotes an external node)
However my question is how can I get it to have leading white spaces to
denote the children for each node? Like so,
Q0:
Y->Q1:
Y->Q3:
Y->R7
N->R8
N->R4
N->Q3:
Y->R2
N->R8
Basically 3 white spaces per level, so 0 for the first, 6 for the second 9
for third and so on. Apart from Q0 which is the root of the tree, I wanted
this to have no white spaces.
EDIT: The children from the original ROOT are 1 and 2, so these should
have the same amount of whitespace before them
Things I have tried so far
Firstly I implemented a counter that counted 3 extra white spaces per
recursion, however I soon found that to be silly since it just printed
them all like a staircase.
I tried setting a boolean flag and making it add white space beforehand
dependent on whether the flag was true or false. Had no luck there
either...
Does anyone have an idea of how I could go about adding this in?
Cheers in advance,
Jim
PS: Post for any clarifications below
Regarding simple inheritance in C#
Regarding simple inheritance in C#
I have a question regarding simple inheritance in C#.
Here is the code:
class Mammal
{
int age { get; set; }
public Mammal(int age)
{
this.age = age;
}
}
class Dog : Mammal
{
string breed { get; set; }
public Dog(int age, string breed)
: base(age)
{
this.breed = breed;
}
}
class Program
{
static void Main(string[] args)
{
Dog joe = new Dog(8, "Labrador");
Console.WriteLine("Joe is {0} years old dog of breed {1}", joe.age,
joe.breed); // gives error
}
}
This gives error since it cannot access the age and breed parameters. So I
make age and breed public in Mammal and Dog class respectively. This makes
the program to run fine.
But my question is shouldn't ideally the parameters be made private or
non-public and only accessed through public methods? If that's the case,
then how can I access the non-public parameters in Program class?
Thanks
I have a question regarding simple inheritance in C#.
Here is the code:
class Mammal
{
int age { get; set; }
public Mammal(int age)
{
this.age = age;
}
}
class Dog : Mammal
{
string breed { get; set; }
public Dog(int age, string breed)
: base(age)
{
this.breed = breed;
}
}
class Program
{
static void Main(string[] args)
{
Dog joe = new Dog(8, "Labrador");
Console.WriteLine("Joe is {0} years old dog of breed {1}", joe.age,
joe.breed); // gives error
}
}
This gives error since it cannot access the age and breed parameters. So I
make age and breed public in Mammal and Dog class respectively. This makes
the program to run fine.
But my question is shouldn't ideally the parameters be made private or
non-public and only accessed through public methods? If that's the case,
then how can I access the non-public parameters in Program class?
Thanks
Trouble Creating an IOS App Tutorial
Trouble Creating an IOS App Tutorial
I'm having trouble creating an IOS App Tutorial. The quick little
explanation of the app with pictures and 1 sentence explanations. I'm sure
other people have had to make one of these before. How did you do it?
thanks,
Scott
I'm having trouble creating an IOS App Tutorial. The quick little
explanation of the app with pictures and 1 sentence explanations. I'm sure
other people have had to make one of these before. How did you do it?
thanks,
Scott
Only getting Length of string for converting list to datatable
Only getting Length of string for converting list to datatable
I'm writing a program in C# VS 2012 WinForms and found this block of code
on StackOverflow to transfer a list to a datatable.
public static DataTable ToDataTable(List<String> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(String));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name,
Nullable.GetUnderlyingType(prop.PropertyType) ??
prop.PropertyType);
foreach (string item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
I was wondering if there was a way to return the actual string itself and
not just the length of the string. If anyone can point me in the right
direction that would be much appreciated. Thanks.
I'm writing a program in C# VS 2012 WinForms and found this block of code
on StackOverflow to transfer a list to a datatable.
public static DataTable ToDataTable(List<String> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(String));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name,
Nullable.GetUnderlyingType(prop.PropertyType) ??
prop.PropertyType);
foreach (string item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
I was wondering if there was a way to return the actual string itself and
not just the length of the string. If anyone can point me in the right
direction that would be much appreciated. Thanks.
Is it a good idea SEO-wize to nest sections inside articles?
Is it a good idea SEO-wize to nest sections inside articles?
I'm wondering which is the best way to go about grouping inside my site
pages.
I'm using wordpress, by default it puts every page contents inside an tag.
In my "Services" page, I have different ones. I'm wondering whether it
would be a good idea to group them in section tags so the structure would
be:
<article>
<h1>services</h1>
<section>service 1</section>
<section>service 2</section>
<section>service 2</section>
</article>
Would this be good for SEO, or should I use a different structure?
I'm wondering which is the best way to go about grouping inside my site
pages.
I'm using wordpress, by default it puts every page contents inside an tag.
In my "Services" page, I have different ones. I'm wondering whether it
would be a good idea to group them in section tags so the structure would
be:
<article>
<h1>services</h1>
<section>service 1</section>
<section>service 2</section>
<section>service 2</section>
</article>
Would this be good for SEO, or should I use a different structure?
OpenWrt: LuCI: how to implement limited user access
OpenWrt: LuCI: how to implement limited user access
Goal: two users root and user. Root can access everything via
web-interface, but user should see only some parts of the menus.
One option would be to pass "sysauth" option to every module in question.
That is not very practical, because the user would see every menu entry
and would get login page for every menu he is not allowed to.
My idea is to figure out who is logged on and then do nothing in the
index() function of each restricted module. So far I couldn't find such a
function in LuCI API (http://luci.subsignal.org/api/luci/), that would
return a current logged user.
I know how to add additional users in OpenWrt/LuCI
(https://forum.openwrt.org/viewtopic.php?pid=163013#p163013). But it is
only a part of the solution.
Any idea, how to achieve my goal?
Goal: two users root and user. Root can access everything via
web-interface, but user should see only some parts of the menus.
One option would be to pass "sysauth" option to every module in question.
That is not very practical, because the user would see every menu entry
and would get login page for every menu he is not allowed to.
My idea is to figure out who is logged on and then do nothing in the
index() function of each restricted module. So far I couldn't find such a
function in LuCI API (http://luci.subsignal.org/api/luci/), that would
return a current logged user.
I know how to add additional users in OpenWrt/LuCI
(https://forum.openwrt.org/viewtopic.php?pid=163013#p163013). But it is
only a part of the solution.
Any idea, how to achieve my goal?
Wednesday, 21 August 2013
How to use kendo ui local storage as back end for my hybrid app
How to use kendo ui local storage as back end for my hybrid app
I am new to Kendo UI Mobile. Now I'm trying to save some data into local
storage but I don't know how to do. Please help me to fix this issue.
Thanks in advance.
I am new to Kendo UI Mobile. Now I'm trying to save some data into local
storage but I don't know how to do. Please help me to fix this issue.
Thanks in advance.
Data is not deleted properly after running of Spec
Data is not deleted properly after running of Spec
In my RSpec file, I have used FactoryGirl to create objects that I have
used in my RSpec file. In my RSpec file I have used three objects A, B and
C where C is dependent on B and B is dependent on A. Here in RSpec file I
have written two test cases: one for testing index method of my controller
and another for update method. So I have created the objects which I have
used to test those two methods, as follows:
before(:each) do
@A = FactoryGirl.create(:A)
@B = FactoryGirl.create(:B)
@C = FactoryGirl.create(:C)
end
And here I am using test environment of Rails, so I am using corresponding
test database which I have already. So to clean the database after
running, I have written the following code:
after(:each) do
C.all.destroy
B.all.destroy
A.all.destroy
end
But the problem is that after running the spec, while I am checking the
tables corresponding to them I find that data is not deleted. Here I have
used DataMapper in my models. So can please anyone help me to fix this
problem i.e. to clean those tables after each run of spec. Thank you.
In my RSpec file, I have used FactoryGirl to create objects that I have
used in my RSpec file. In my RSpec file I have used three objects A, B and
C where C is dependent on B and B is dependent on A. Here in RSpec file I
have written two test cases: one for testing index method of my controller
and another for update method. So I have created the objects which I have
used to test those two methods, as follows:
before(:each) do
@A = FactoryGirl.create(:A)
@B = FactoryGirl.create(:B)
@C = FactoryGirl.create(:C)
end
And here I am using test environment of Rails, so I am using corresponding
test database which I have already. So to clean the database after
running, I have written the following code:
after(:each) do
C.all.destroy
B.all.destroy
A.all.destroy
end
But the problem is that after running the spec, while I am checking the
tables corresponding to them I find that data is not deleted. Here I have
used DataMapper in my models. So can please anyone help me to fix this
problem i.e. to clean those tables after each run of spec. Thank you.
Why do GIL alternatives have an impact on performance?
Why do GIL alternatives have an impact on performance?
Coming from Java the whole Global Interpreter Lock (GIL) in Ruby and
Python is kind of startling. I have read a bit into the problem and found
in the Python documentation the following excerpt:
Can't we get rid of the Global Interpreter Lock?
The global interpreter lock (GIL) is often seen as a hindrance to Python's
deployment on high-end multiprocessor server machines, because a
multi-threaded Python program effectively only uses one CPU, due to the
insistence that (almost) all Python code can only run while the GIL is
held.
Back in the days of Python 1.5, Greg Stein actually implemented a
comprehensive patch set (the "free threading" patches) that removed the
GIL and replaced it with fine-grained locking. Unfortunately, even on
Windows (where locks are very efficient) this ran ordinary Python code
about twice as slow as the interpreter using the GIL. On Linux the
performance loss was even worse because pthread locks aren't as efficient.
What I did not found is the explanation behind the performance impact. I
have tried to find out what the technical reasons are, but could not find
any good discussion that nails it down.
Similar in Ruby, here I could find even less information. Are the reasons
the same?
Coming from Java the whole Global Interpreter Lock (GIL) in Ruby and
Python is kind of startling. I have read a bit into the problem and found
in the Python documentation the following excerpt:
Can't we get rid of the Global Interpreter Lock?
The global interpreter lock (GIL) is often seen as a hindrance to Python's
deployment on high-end multiprocessor server machines, because a
multi-threaded Python program effectively only uses one CPU, due to the
insistence that (almost) all Python code can only run while the GIL is
held.
Back in the days of Python 1.5, Greg Stein actually implemented a
comprehensive patch set (the "free threading" patches) that removed the
GIL and replaced it with fine-grained locking. Unfortunately, even on
Windows (where locks are very efficient) this ran ordinary Python code
about twice as slow as the interpreter using the GIL. On Linux the
performance loss was even worse because pthread locks aren't as efficient.
What I did not found is the explanation behind the performance impact. I
have tried to find out what the technical reasons are, but could not find
any good discussion that nails it down.
Similar in Ruby, here I could find even less information. Are the reasons
the same?
Editing grid row data on bind
Editing grid row data on bind
Is it possible to edit each line on a grid as it is binding? I'd like to
sum a series of records and have it display on one line. I'm setting it up
as a multi-sourced table with an inner and outer join. RouteVersion is the
main table with InventDim/InnerJoin and SalesLine/OuterJoin.
My ultimate goal is to Display a line for each Route per site and the
RemainSalesPhysical sum for that Route on each site. Each route is tied
one to one with an Item.
I've tried this through table methods, but since I can't access the
current grid line's fields I don't know the specific route, or site, or
item (depending on what table the method is in).
Maybe I'm going about this the wrong way, does anyone have any suggestions
for me that can put me on the right path?
Is it possible to edit each line on a grid as it is binding? I'd like to
sum a series of records and have it display on one line. I'm setting it up
as a multi-sourced table with an inner and outer join. RouteVersion is the
main table with InventDim/InnerJoin and SalesLine/OuterJoin.
My ultimate goal is to Display a line for each Route per site and the
RemainSalesPhysical sum for that Route on each site. Each route is tied
one to one with an Item.
I've tried this through table methods, but since I can't access the
current grid line's fields I don't know the specific route, or site, or
item (depending on what table the method is in).
Maybe I'm going about this the wrong way, does anyone have any suggestions
for me that can put me on the right path?
where i can see Atletico Madrid vs Barcelona Live Online Streaming
where i can see Atletico Madrid vs Barcelona Live Online Streaming
Watch Live Streaming Link
Both teams are coming into the Spanish Super Cup final after great
victories at the start of the Primera, Barcelona coming from a 7:0 victory
at home against Levante, while Atletico Madrid made a great victory over
Sevilla winning them on the road with a 3:1 result. Second match will be
played at Barcelona venue seven days from now.
Atletico continued good tradition against Sevilla, as they didn't lost
against them in last eight matches and confirmed that tradition with a 3:1
victory on the road last weekend, with scoring two goals in 79th and 92nd
minute of the match. Without their star player Falcao, Atletico made a
right step into new season, while they will try to get advantage of the
positive start and try to hurt Barcelona in the Spanish Super Cup. Last
season they managed to take the third position in the championship, while
they defeated Real Madrid in the Cup's final after overtime, meanwhile
they proved to be the best defensive team in the country. Midfielder
Thiago returns after suspension in the team, while the hosts have no
injury or suspension problems in front of this game.
Watch Live Streaming Link
Watch Live Streaming Link
Both teams are coming into the Spanish Super Cup final after great
victories at the start of the Primera, Barcelona coming from a 7:0 victory
at home against Levante, while Atletico Madrid made a great victory over
Sevilla winning them on the road with a 3:1 result. Second match will be
played at Barcelona venue seven days from now.
Atletico continued good tradition against Sevilla, as they didn't lost
against them in last eight matches and confirmed that tradition with a 3:1
victory on the road last weekend, with scoring two goals in 79th and 92nd
minute of the match. Without their star player Falcao, Atletico made a
right step into new season, while they will try to get advantage of the
positive start and try to hurt Barcelona in the Spanish Super Cup. Last
season they managed to take the third position in the championship, while
they defeated Real Madrid in the Cup's final after overtime, meanwhile
they proved to be the best defensive team in the country. Midfielder
Thiago returns after suspension in the team, while the hosts have no
injury or suspension problems in front of this game.
Watch Live Streaming Link
Ensuring initialization methods complete before member variable is accessed
Ensuring initialization methods complete before member variable is accessed
Is there a way of ensure that a set of methods operating on a volatile
static member variable via one thread will be done and over with before
other threads access this member variable? I am trying something like
this, but I am not sure if it would work.
public class MyClass {
private static final Object lock = new Object();
public static volatile MyObj mo; //assume null will be checked before
access
public static void initialize(Object something) {
if (mo == null) {
synchronized(lock) {
mo = new MyObj(something);
mo.doInit();
mo.doMoreInit();
}
}
}
}
Is there a way of ensure that a set of methods operating on a volatile
static member variable via one thread will be done and over with before
other threads access this member variable? I am trying something like
this, but I am not sure if it would work.
public class MyClass {
private static final Object lock = new Object();
public static volatile MyObj mo; //assume null will be checked before
access
public static void initialize(Object something) {
if (mo == null) {
synchronized(lock) {
mo = new MyObj(something);
mo.doInit();
mo.doMoreInit();
}
}
}
}
How to pass JQ Grid hidden table data to controller while deleting
How to pass JQ Grid hidden table data to controller while deleting
I am new to JQ grid i just started exploring it. I tried with the below
stuff's and I was stuck while deleting the records. I have hided the
application ID column and if I press delete button in navGrid I need to
pass AppID as the parameter to Controller. I tried but I am getting null
value. I logged the postdata in that i am getting value for id(id=10)
only. Instead of id i need to pass the AppID. Any help would be
appreciated.
View Page:
<div id="JqGridExampleContainer">
<table id="ApplicationDetailsTable">
</table>
<div id="JQGridPaging"></div>
</div>
Script:
function showJQGrid() {
$("#ApplicationDetailsTable").jqGrid({
width: 800,
height: '100%',
url: '@Url.Action("AppListDetails", "JQGridHome")',
datatype: 'json',
mtype: "GET",
colNames: ["Application ID", "TenantId", "Application Name",
"Actions","Inbuild Actions"],
colModel: [
{ name: 'AppId', index: 'AppId', hidden: true },
{ name: 'TenantId', index: 'TenantId', resizable: true, align:
'center', title: false, sortable: true, searchoptions: { sopt:
['eq', 'ne', 'le', 'lt', 'gt', 'ge'] }, searchtype: "number"
},
{ name: 'AppName', index: 'AppName', sortable: true },
{ name: 'Actions', sortable: false, search: false, fixed:
true,align:'center',
formatter: function () {
return "<img src='../../Images/edit-icon.png'
alt='Edit' id='editID'
style='margin-left:12px;height:18px;width:18px;cursor:pointer;'
/><img src='../../Images/Trash-can-icon.png'
alt='Edit'
id='deleteID'style='margin-left:12px;height:18px;width:18px;cursor:pointer;'
onclick='deleteApplication()' />";
}
},
{ name: 'myac', width: 80, fixed: true, resizable: false,
sortable: false, search: false, resize: false, formatter:
'actions',
formatoptions: { keys: true}
},
],
rowNum: 10,
rowList: [5, 10, 20, 30],
pager: '#JQGridPaging',
viewrecords: true,
caption: "Application List Details",
sortname: "TenantId",
sortorder: "asc",
altRows: true,
altclass: 'jqgaltrow',
hoverrows: true,
loadonce: true,
gridview: false,
rownumWidth: 40,
rownumbers: true,
multiSort: true,
hidegrid: true,
toppager: false,
pgbuttons: true,
jsonReader: {
root: 'AllApplicationList',
},
shrinkToFit: true,
emptyrecords: "No records to view",
loadtext:'Loading Data please wait ...'
});
jQuery("#ApplicationDetailsTable").jqGrid('filterToolbar', {
searchOperators: false,searchOnEnter: false, });
$("#ApplicationDetailsTable").jqGrid('navGrid', '#JQGridPaging',
{
refresh: false, add: false, edit: false, del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete",
deltitle: "Delete Application",
refreshtext: "Refresh",
position: 'left'
},
{},
{},
{
mtype: "POST",
reloadAfterSubmit: true,
url: '@Url.Action("DeleteApplicationDetails",
"JQGridHome")',
resize: false,
closeOnEscape: true,
drag: false,
ajaxDelOptions: { contentType: 'application/json;
charset=utf-8' },
serializeDelData: function (postdata) {
alert(postdata);
console.log(postdata);
return JSON.stringify({ AppId: postdata.id });
}
},
{ sopt: ['eq', 'cn', 'lt', 'le', 'bw', 'bn', 'in'],
closeOnEscape: true, multipleSearch: true, overlay: true,
width: 460, closeAfterSearch: true }
);
}
$(document).ready(function () {
showJQGrid();
});
JSON Response From Server Side:
{"AllApplicationList":[{"AppId":1004,"TenantId":1,"AppName":"Sensiple IT
Help Desk"}, {"AppId":2000,"TenantId":1,"AppName":"HR Help Desk"},
{"AppId":3000,"TenantId":1,"AppName":"Admin Desk"},
{"AppId":4000,"TenantId":1,"AppName":"Transport Facility"},
{"AppId":5000,"TenantId":2,"AppName":"Security Services"},
{"AppId":6000,"TenantId":5,"AppName":"Premises"},{"AppId":6001,"TenantId":8,"AppName":"Head
Office"},{"AppId":6002,"TenantId":14,"AppName":"Ticket Incident"},
{"AppId":6003,"TenantId":14,"AppName":"Food Service"},
{"AppId":6005,"TenantId":14,"AppName":"Cleaning Service"}]}
Image:
I am new to JQ grid i just started exploring it. I tried with the below
stuff's and I was stuck while deleting the records. I have hided the
application ID column and if I press delete button in navGrid I need to
pass AppID as the parameter to Controller. I tried but I am getting null
value. I logged the postdata in that i am getting value for id(id=10)
only. Instead of id i need to pass the AppID. Any help would be
appreciated.
View Page:
<div id="JqGridExampleContainer">
<table id="ApplicationDetailsTable">
</table>
<div id="JQGridPaging"></div>
</div>
Script:
function showJQGrid() {
$("#ApplicationDetailsTable").jqGrid({
width: 800,
height: '100%',
url: '@Url.Action("AppListDetails", "JQGridHome")',
datatype: 'json',
mtype: "GET",
colNames: ["Application ID", "TenantId", "Application Name",
"Actions","Inbuild Actions"],
colModel: [
{ name: 'AppId', index: 'AppId', hidden: true },
{ name: 'TenantId', index: 'TenantId', resizable: true, align:
'center', title: false, sortable: true, searchoptions: { sopt:
['eq', 'ne', 'le', 'lt', 'gt', 'ge'] }, searchtype: "number"
},
{ name: 'AppName', index: 'AppName', sortable: true },
{ name: 'Actions', sortable: false, search: false, fixed:
true,align:'center',
formatter: function () {
return "<img src='../../Images/edit-icon.png'
alt='Edit' id='editID'
style='margin-left:12px;height:18px;width:18px;cursor:pointer;'
/><img src='../../Images/Trash-can-icon.png'
alt='Edit'
id='deleteID'style='margin-left:12px;height:18px;width:18px;cursor:pointer;'
onclick='deleteApplication()' />";
}
},
{ name: 'myac', width: 80, fixed: true, resizable: false,
sortable: false, search: false, resize: false, formatter:
'actions',
formatoptions: { keys: true}
},
],
rowNum: 10,
rowList: [5, 10, 20, 30],
pager: '#JQGridPaging',
viewrecords: true,
caption: "Application List Details",
sortname: "TenantId",
sortorder: "asc",
altRows: true,
altclass: 'jqgaltrow',
hoverrows: true,
loadonce: true,
gridview: false,
rownumWidth: 40,
rownumbers: true,
multiSort: true,
hidegrid: true,
toppager: false,
pgbuttons: true,
jsonReader: {
root: 'AllApplicationList',
},
shrinkToFit: true,
emptyrecords: "No records to view",
loadtext:'Loading Data please wait ...'
});
jQuery("#ApplicationDetailsTable").jqGrid('filterToolbar', {
searchOperators: false,searchOnEnter: false, });
$("#ApplicationDetailsTable").jqGrid('navGrid', '#JQGridPaging',
{
refresh: false, add: false, edit: false, del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete",
deltitle: "Delete Application",
refreshtext: "Refresh",
position: 'left'
},
{},
{},
{
mtype: "POST",
reloadAfterSubmit: true,
url: '@Url.Action("DeleteApplicationDetails",
"JQGridHome")',
resize: false,
closeOnEscape: true,
drag: false,
ajaxDelOptions: { contentType: 'application/json;
charset=utf-8' },
serializeDelData: function (postdata) {
alert(postdata);
console.log(postdata);
return JSON.stringify({ AppId: postdata.id });
}
},
{ sopt: ['eq', 'cn', 'lt', 'le', 'bw', 'bn', 'in'],
closeOnEscape: true, multipleSearch: true, overlay: true,
width: 460, closeAfterSearch: true }
);
}
$(document).ready(function () {
showJQGrid();
});
JSON Response From Server Side:
{"AllApplicationList":[{"AppId":1004,"TenantId":1,"AppName":"Sensiple IT
Help Desk"}, {"AppId":2000,"TenantId":1,"AppName":"HR Help Desk"},
{"AppId":3000,"TenantId":1,"AppName":"Admin Desk"},
{"AppId":4000,"TenantId":1,"AppName":"Transport Facility"},
{"AppId":5000,"TenantId":2,"AppName":"Security Services"},
{"AppId":6000,"TenantId":5,"AppName":"Premises"},{"AppId":6001,"TenantId":8,"AppName":"Head
Office"},{"AppId":6002,"TenantId":14,"AppName":"Ticket Incident"},
{"AppId":6003,"TenantId":14,"AppName":"Food Service"},
{"AppId":6005,"TenantId":14,"AppName":"Cleaning Service"}]}
Image:
Tuesday, 20 August 2013
Esper last inserted Event
Esper last inserted Event
Is there a way to get the last inserted event in esper core prior to rule
completion?
Configuration cepConfig = new Configuration();
cepConfig.getEngineDefaults().getMetricsReporting().
setEnableMetricsReporting(true);
cepConfig.addEventType("Stream", Stream.class.getName());
EPServiceProvider cep =
EPServiceProviderManager.getProvider("myCEPEngine", cepConfig);
EPRuntime cepRT = cep.getEPRuntime();
EPAdministrator cepAdm = cep.getEPAdministrator();
EPStatement cepStatement = cepAdm.createEPL("select * from
Stream.win:length(100)") ;
cepStatement.addListener(new CEPListener());
Now for event insertion i am using this sample code
for (int i = 0; i < 500; i++) {
GenerateRandomStream(cepRT);
//Here I want get the last inserted event
}
Any help will be appreciated.
Is there a way to get the last inserted event in esper core prior to rule
completion?
Configuration cepConfig = new Configuration();
cepConfig.getEngineDefaults().getMetricsReporting().
setEnableMetricsReporting(true);
cepConfig.addEventType("Stream", Stream.class.getName());
EPServiceProvider cep =
EPServiceProviderManager.getProvider("myCEPEngine", cepConfig);
EPRuntime cepRT = cep.getEPRuntime();
EPAdministrator cepAdm = cep.getEPAdministrator();
EPStatement cepStatement = cepAdm.createEPL("select * from
Stream.win:length(100)") ;
cepStatement.addListener(new CEPListener());
Now for event insertion i am using this sample code
for (int i = 0; i < 500; i++) {
GenerateRandomStream(cepRT);
//Here I want get the last inserted event
}
Any help will be appreciated.
Split string to the right of delimiter
Split string to the right of delimiter
I am trying to obtain the string to the right of the delimiter "|" and
anything to the left can be ignored.
I tried the following, but it gives me the values to the left
Dim s As String = "John Smith | 09F2"
Console.WriteLine(s.Substring(0, s.IndexOf("|")))
Console.WriteLine(s.Split(CChar("|"))(0))
Console.ReadKey()
Result is: John Smith. I want the 09F2 value.
I also tried the following lines of code:
Dim strEmployeeInfo As String = cmbSelectEmployee.Text
Dim employeeID = Microsoft.VisualBasic.Right(strEmployeeInfo,
strEmployeeInfo.IndexOf("|"))
But the result of that is Smith | 09F2. Again I only need the 09F2
I am trying to obtain the string to the right of the delimiter "|" and
anything to the left can be ignored.
I tried the following, but it gives me the values to the left
Dim s As String = "John Smith | 09F2"
Console.WriteLine(s.Substring(0, s.IndexOf("|")))
Console.WriteLine(s.Split(CChar("|"))(0))
Console.ReadKey()
Result is: John Smith. I want the 09F2 value.
I also tried the following lines of code:
Dim strEmployeeInfo As String = cmbSelectEmployee.Text
Dim employeeID = Microsoft.VisualBasic.Right(strEmployeeInfo,
strEmployeeInfo.IndexOf("|"))
But the result of that is Smith | 09F2. Again I only need the 09F2
How to parse commandline parameter that occur multiple times
How to parse commandline parameter that occur multiple times
how to parse commandline parameter for that defintion:
myjar [-hv] [[--exclude PATTERN]...] dir
It should be possible to put multiple --exclude PATTERN and define exactly
one dir.
At the end it should match to this config class:
static class CliConfig {
public boolean verbose;
public List<String> filter;
public String dir;
}
This are some valid examples:
myjar -v --exclude *.jpg --exclude *.jpeg /tmp
myjar /tmp
myjar -h
I had a look to apache-commons-cli, jcommander and args4j but I couldn't
make it running for the --exclude PATTERN. They have this "multi variable"
options just for the last parameter. Or i overread it.
I'm free in choosing any library.
P.S.: This is similar to the linux program: ncdu
how to parse commandline parameter for that defintion:
myjar [-hv] [[--exclude PATTERN]...] dir
It should be possible to put multiple --exclude PATTERN and define exactly
one dir.
At the end it should match to this config class:
static class CliConfig {
public boolean verbose;
public List<String> filter;
public String dir;
}
This are some valid examples:
myjar -v --exclude *.jpg --exclude *.jpeg /tmp
myjar /tmp
myjar -h
I had a look to apache-commons-cli, jcommander and args4j but I couldn't
make it running for the --exclude PATTERN. They have this "multi variable"
options just for the last parameter. Or i overread it.
I'm free in choosing any library.
P.S.: This is similar to the linux program: ncdu
Macbook Pro boots successfully when using hard drive in USB enclosure but doesn't boot when connected internally
Macbook Pro boots successfully when using hard drive in USB enclosure but
doesn't boot when connected internally
Apologies for the long question. I will keep it as simple as I can.
Last week my Macbook Pro (13-inch, Mid 2010) started to act strange.
It started when I tried to open Skype and received an error complaining
that the program could not start because Skype could not read (or lock,
unfortunately I can't remember) it's skype.plist file.
I restarted my Macbook hoping that would fix the problem (and I hadn't
restarted in a while so I figured it was overdue).
My Macbook restarted and played the startup chime but then hung at the
grey startup screen with the spinning wheel. I thought nothing of it and
did a hard shutdown but no matter how many times I did, the Macbook never
advanced past the grey startup screen.
I tried to boot using Safe and Verbose mode and got the following error in
both cases:
BootCacheControl : Unable to open /var/db/BootCache.playlist: 22 invalid
argument
I googled the error and tried various solutions with no luck.
The Macbook would boot to the built-in Mountain Lion recovery partition.
At this point I decided to backup my data so I could mess with the hard
drive a bit more without fear of losing any data. I booted in to the
recovery partition and cloned my hard drive onto another using a USB
enclosure. It seemed to work OK and I verified all of my files were on the
backup hard drive by plugging it into another Macbook.
After cloning my hard drive I verified and repaired the disk and disk
permissions using the disk utility in the recovery partition but that had
no effect.
At this point I decided to reinstall Mountain Lion. I tried numerous times
to reinstall it with the hard drive inside the Macbook (both using the
recovery partition and a bootable Mountain Lion SD card) but couldn't get
it to install. Eventually I got it to install, but only when the hard
drive was placed in a USB enclosure. I knew this probably indicated a
bigger underlying problem but decided to go ahead anyway.
I installed Mountain Lion successfully but now it will not boot with the
hard drive connected inside the Macbook, only when it is used in my USB
enclosure. When the hard drive is placed in my USB enclosure it boots to
Mountain Lion without any problem.
With the hard drive inside the Macbook:
If the Macbook is booted as standard, it hangs on the grey startup screen
with spinning wheel
If it is booted in verbose mode, it seems to boot successfully (shows no
errors when the white text show up) and then hangs on a black screen with
a solid white cursor in the top left corner (I can type at this point but
it does nothing, it doesn't appear to be a terminal window)
If it is booted in safe mode, the progress bar appears, progresses to the
end and then hangs on the grey startup screen with spinning wheel
I noticed a lot of suggestions on the internet to replace the hard drive
cable to the motherboard. I did and it had no effect.
I've tried using another hard drive running a brand new install of
Mountain Lion and that behaves exactly the same (boots fine using a USB
enclosure but doesn't boot when connected internally).
I've booked an appointment at the Apple store but figured it was worth
posting the question anyway, in case anybody has a similar issue in the
future (hopefully I'll be able to post the answer, if nobody else does,
after a visit to the Genius bar).
Any suggestions?
Thanks for reading.
doesn't boot when connected internally
Apologies for the long question. I will keep it as simple as I can.
Last week my Macbook Pro (13-inch, Mid 2010) started to act strange.
It started when I tried to open Skype and received an error complaining
that the program could not start because Skype could not read (or lock,
unfortunately I can't remember) it's skype.plist file.
I restarted my Macbook hoping that would fix the problem (and I hadn't
restarted in a while so I figured it was overdue).
My Macbook restarted and played the startup chime but then hung at the
grey startup screen with the spinning wheel. I thought nothing of it and
did a hard shutdown but no matter how many times I did, the Macbook never
advanced past the grey startup screen.
I tried to boot using Safe and Verbose mode and got the following error in
both cases:
BootCacheControl : Unable to open /var/db/BootCache.playlist: 22 invalid
argument
I googled the error and tried various solutions with no luck.
The Macbook would boot to the built-in Mountain Lion recovery partition.
At this point I decided to backup my data so I could mess with the hard
drive a bit more without fear of losing any data. I booted in to the
recovery partition and cloned my hard drive onto another using a USB
enclosure. It seemed to work OK and I verified all of my files were on the
backup hard drive by plugging it into another Macbook.
After cloning my hard drive I verified and repaired the disk and disk
permissions using the disk utility in the recovery partition but that had
no effect.
At this point I decided to reinstall Mountain Lion. I tried numerous times
to reinstall it with the hard drive inside the Macbook (both using the
recovery partition and a bootable Mountain Lion SD card) but couldn't get
it to install. Eventually I got it to install, but only when the hard
drive was placed in a USB enclosure. I knew this probably indicated a
bigger underlying problem but decided to go ahead anyway.
I installed Mountain Lion successfully but now it will not boot with the
hard drive connected inside the Macbook, only when it is used in my USB
enclosure. When the hard drive is placed in my USB enclosure it boots to
Mountain Lion without any problem.
With the hard drive inside the Macbook:
If the Macbook is booted as standard, it hangs on the grey startup screen
with spinning wheel
If it is booted in verbose mode, it seems to boot successfully (shows no
errors when the white text show up) and then hangs on a black screen with
a solid white cursor in the top left corner (I can type at this point but
it does nothing, it doesn't appear to be a terminal window)
If it is booted in safe mode, the progress bar appears, progresses to the
end and then hangs on the grey startup screen with spinning wheel
I noticed a lot of suggestions on the internet to replace the hard drive
cable to the motherboard. I did and it had no effect.
I've tried using another hard drive running a brand new install of
Mountain Lion and that behaves exactly the same (boots fine using a USB
enclosure but doesn't boot when connected internally).
I've booked an appointment at the Apple store but figured it was worth
posting the question anyway, in case anybody has a similar issue in the
future (hopefully I'll be able to post the answer, if nobody else does,
after a visit to the Genius bar).
Any suggestions?
Thanks for reading.
This programs takes a long time to close after the 'return;' on main()
This programs takes a long time to close after the 'return;' on main()
This is the code I am dealing with:
#include <iostream>
#include <map>
using namespace std;
static unsigned long collatzLength(unsigned long n) {
static std::map<unsigned long,int> collatzMap;
int mapResult = collatzMap[n];
if (mapResult != 0) return mapResult;
if (n == 1) {
return 1;
} else {
collatzMap[n] = 1 + collatzLength(n%2==0?n/2:3*n+1);
return collatzMap[n];
}
}
int main() {
int maxIndex = 1;
unsigned int max = 1;
for (int i=1; i<1000000; i++) {
//cout<<i<<endl;
unsigned long count = collatzLength(i);
if (count > max) {
maxIndex = i;
max = count;
}
}
cout<<maxIndex<<endl;
getchar();
cout<<"Returning..."<<endl;
return maxIndex;
}
When I compile and run this program (using Visual Studio 2012 and Release
build settings) it takes like 10 seconds (on my computer) to close after
the program prints "Returning..."
Why is that?
Note: I am aware that this program is bad written and that i probably
shouldn't be using 'static' on the collatzLength nor using a cache for
that function, but I am not interesting on how to make this code better, I
am just interesting about why does it take so much to close.
This is the code I am dealing with:
#include <iostream>
#include <map>
using namespace std;
static unsigned long collatzLength(unsigned long n) {
static std::map<unsigned long,int> collatzMap;
int mapResult = collatzMap[n];
if (mapResult != 0) return mapResult;
if (n == 1) {
return 1;
} else {
collatzMap[n] = 1 + collatzLength(n%2==0?n/2:3*n+1);
return collatzMap[n];
}
}
int main() {
int maxIndex = 1;
unsigned int max = 1;
for (int i=1; i<1000000; i++) {
//cout<<i<<endl;
unsigned long count = collatzLength(i);
if (count > max) {
maxIndex = i;
max = count;
}
}
cout<<maxIndex<<endl;
getchar();
cout<<"Returning..."<<endl;
return maxIndex;
}
When I compile and run this program (using Visual Studio 2012 and Release
build settings) it takes like 10 seconds (on my computer) to close after
the program prints "Returning..."
Why is that?
Note: I am aware that this program is bad written and that i probably
shouldn't be using 'static' on the collatzLength nor using a cache for
that function, but I am not interesting on how to make this code better, I
am just interesting about why does it take so much to close.
Using binary component for calling a dll
Using binary component for calling a dll
I have a c++ dll that want it to be called from other c++ dll using binary
component . i also want to call the resulted dll from a javascript code .
can anybody tell me how to do this ?
I have a c++ dll that want it to be called from other c++ dll using binary
component . i also want to call the resulted dll from a javascript code .
can anybody tell me how to do this ?
Search function mixed with json and php (sql)
Search function mixed with json and php (sql)
I write a search system, this system has 4 pages/steps, on the first 3
pages are only checkboxes to find, my problem is, i create this checkboxes
per json, and i can read only names. To convert this data for checkboxes i
use:
<?php
$jsonData = json_decode($string5, true);
foreach ($jsonData as $item) :
?>
<label><input type="checkbox" name="<?php echo $item['name'] ?>" value=""
/><?php echo $item['name'] ?></label><br />
<?php
endforeach;
?>
My questions are: How can i get values from checkboxes on the page/step 4
dynamicly? How can i from this json data create a sql query for search
results?
I write a search system, this system has 4 pages/steps, on the first 3
pages are only checkboxes to find, my problem is, i create this checkboxes
per json, and i can read only names. To convert this data for checkboxes i
use:
<?php
$jsonData = json_decode($string5, true);
foreach ($jsonData as $item) :
?>
<label><input type="checkbox" name="<?php echo $item['name'] ?>" value=""
/><?php echo $item['name'] ?></label><br />
<?php
endforeach;
?>
My questions are: How can i get values from checkboxes on the page/step 4
dynamicly? How can i from this json data create a sql query for search
results?
Monday, 19 August 2013
Replace NA values by row means in especifc rows and columns
Replace NA values by row means in especifc rows and columns
Equals this post (Replace NA values by row means), but in a especific rows
and columns. Thanks
Equals this post (Replace NA values by row means), but in a especific rows
and columns. Thanks
Cannot update by clearcase in Eclipse or Clearcase Remote Client
Cannot update by clearcase in Eclipse or Clearcase Remote Client
I work under a cloud environment, so all the configurations is same to
others.
Where's problem?
I work under a cloud environment, so all the configurations is same to
others.
Where's problem?
Cakephp generated javascript throws error onclick
Cakephp generated javascript throws error onclick
I have a group of tests in my system. It is possible for a test to be
paused. On the index page of my test controller, I use the following code
to display the tests.
<table>
<tr><th>ID</th><th>Name</th><th>Updated</th><th>Actions</th></tr>
<?php foreach ($tests as $test): ?>
<tr>
<td>
<?php echo $test['Test']['id']; ?>
</td>
<td class="actions">
<?php
$status = ($test['Test']['is_paused'] == 1) ? 'Un-pause' :
'Pause';
echo $this->Form->postLink($status,
array('controller'=>'tests', 'action' => 'pause',
$test['Test']['id'], 'admin' => 1), array('confirm'=>'Are you
sure?') );
?>
<?php
echo $this->Html->link('Edit', array('controller'=>'tests',
'action' => 'edit', 'admin'=>1, $test['Test']['id']));
?>
<?php
echo $this->Form->postLink('Delete',
array('controller'=>'tests', 'action' => 'delete',
$test['Test']['id'], 'admin'=>1), array('confirm'=>'Are you
sure?') );
?>
</td>
</tr>
<?php endforeach; ?>
</table>
This generates a list of tests and provides some action functions for each
one using postlink from the cakephp form helper. The one that is causing
problems is the pause button. Sometime when clicked it throws the
following error.
Uncaught TypeError: Object #<HTMLCollection> has no method 'submit'
I'm not super up on my JS and since the JS for this is automatically
built, I'm not sure how to fix this. The pause button will do nothing when
this issue occurs and I'm not even sure where to start debugging this.
Thank you to anyone who helps.
I have a group of tests in my system. It is possible for a test to be
paused. On the index page of my test controller, I use the following code
to display the tests.
<table>
<tr><th>ID</th><th>Name</th><th>Updated</th><th>Actions</th></tr>
<?php foreach ($tests as $test): ?>
<tr>
<td>
<?php echo $test['Test']['id']; ?>
</td>
<td class="actions">
<?php
$status = ($test['Test']['is_paused'] == 1) ? 'Un-pause' :
'Pause';
echo $this->Form->postLink($status,
array('controller'=>'tests', 'action' => 'pause',
$test['Test']['id'], 'admin' => 1), array('confirm'=>'Are you
sure?') );
?>
<?php
echo $this->Html->link('Edit', array('controller'=>'tests',
'action' => 'edit', 'admin'=>1, $test['Test']['id']));
?>
<?php
echo $this->Form->postLink('Delete',
array('controller'=>'tests', 'action' => 'delete',
$test['Test']['id'], 'admin'=>1), array('confirm'=>'Are you
sure?') );
?>
</td>
</tr>
<?php endforeach; ?>
</table>
This generates a list of tests and provides some action functions for each
one using postlink from the cakephp form helper. The one that is causing
problems is the pause button. Sometime when clicked it throws the
following error.
Uncaught TypeError: Object #<HTMLCollection> has no method 'submit'
I'm not super up on my JS and since the JS for this is automatically
built, I'm not sure how to fix this. The pause button will do nothing when
this issue occurs and I'm not even sure where to start debugging this.
Thank you to anyone who helps.
Adding a text and progress icon to navigation bar
Adding a text and progress icon to navigation bar
I would like to add a status to the navigation bar. for example, in
Whatsapp, when user changes alert settings, It display "updating" text and
progress icon on the navigation bar, as shown in below image. How do i do
that?
I would like to add a status to the navigation bar. for example, in
Whatsapp, when user changes alert settings, It display "updating" text and
progress icon on the navigation bar, as shown in below image. How do i do
that?
AS3 Mouse down not working
AS3 Mouse down not working
I have a button that has been added to the stage. When it is created, it
moves into the visible area of the stage, and calls an activate function,
which adds an event listener to it that looks for mouse down. For some
reason, however, this does not work. Any ideas as to why? I've tried
adding a listener to the object via the one that created it, but that
doesn't work either.
package menus {
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.*;
public class MenuPlayButton extends MovieClip {
private var _stageWidth, _stageHeight:int;
private var comeInTimer:Timer;
private var buttonSpeed:Number;
public function MenuPlayButton(stageWidth:int, stageHeight:int) {
_stageWidth = stageWidth;
_stageHeight = stageHeight;
alpha = 1;
rescaleMe();
repositionMe();
comeIntoMenu();
}
private function rescaleMe():void {
var oldWidth = this.width;
var oldHeight = this.height;
this.height = _stageHeight/10;
this.width = (this.height * oldWidth) / oldHeight;
}
private function repositionMe():void {
this.x = 0 - this.width;
this.y = _stageHeight * 0.56;
}
private function comeIntoMenu():void {
//Sets button's original speed
buttonSpeed = _stageHeight / 40;
//Adds timer that moves in the button
comeInTimer = new Timer(10,0);
comeInTimer.addEventListener(TimerEvent.TIMER, comeInTimerListener);
comeInTimer.start();
}
private function comeInTimerListener(e:TimerEvent):void {
if(x < 0) {
x += buttonSpeed;
buttonSpeed *= 0.93;
} else {
x = 0;
activate();
}
}
private function activate():void {
//Kills off timer
comeInTimer.removeEventListener(TimerEvent.TIMER,
comeInTimerListener);
comeInTimer.stop();
comeInTimer = null;
this.addEventListener(MouseEvent.MOUSE_DOWN, clicked);
trace("Button should be activated"); //This gets traced
}
function clicked(e:MouseEvent) {
trace("Button pressed");
}
}
}
I have a button that has been added to the stage. When it is created, it
moves into the visible area of the stage, and calls an activate function,
which adds an event listener to it that looks for mouse down. For some
reason, however, this does not work. Any ideas as to why? I've tried
adding a listener to the object via the one that created it, but that
doesn't work either.
package menus {
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.*;
public class MenuPlayButton extends MovieClip {
private var _stageWidth, _stageHeight:int;
private var comeInTimer:Timer;
private var buttonSpeed:Number;
public function MenuPlayButton(stageWidth:int, stageHeight:int) {
_stageWidth = stageWidth;
_stageHeight = stageHeight;
alpha = 1;
rescaleMe();
repositionMe();
comeIntoMenu();
}
private function rescaleMe():void {
var oldWidth = this.width;
var oldHeight = this.height;
this.height = _stageHeight/10;
this.width = (this.height * oldWidth) / oldHeight;
}
private function repositionMe():void {
this.x = 0 - this.width;
this.y = _stageHeight * 0.56;
}
private function comeIntoMenu():void {
//Sets button's original speed
buttonSpeed = _stageHeight / 40;
//Adds timer that moves in the button
comeInTimer = new Timer(10,0);
comeInTimer.addEventListener(TimerEvent.TIMER, comeInTimerListener);
comeInTimer.start();
}
private function comeInTimerListener(e:TimerEvent):void {
if(x < 0) {
x += buttonSpeed;
buttonSpeed *= 0.93;
} else {
x = 0;
activate();
}
}
private function activate():void {
//Kills off timer
comeInTimer.removeEventListener(TimerEvent.TIMER,
comeInTimerListener);
comeInTimer.stop();
comeInTimer = null;
this.addEventListener(MouseEvent.MOUSE_DOWN, clicked);
trace("Button should be activated"); //This gets traced
}
function clicked(e:MouseEvent) {
trace("Button pressed");
}
}
}
Sunday, 18 August 2013
change strore procedure from Sybase to sql server
change strore procedure from Sybase to sql server
How can i change this Store Procedure for Sql Server. I try but i have not
success can you please help me . I am not understanding what is going in
this SP and what i will write in SQL SERVER 2008 .
if exists (select * from sys.systable where table_name = 'ATSROUTES')
begin
drop table ATSROUTES;
end
create table comet.ATSROUTES(
zip varchar(255) null,
route varchar(255) null,
drivernum varchar(255) null,
altserviceid varchar(255) null,
localorldrvnum varchar(255) null,
pickupzone varchar (255) null,
distcenter varchar (255) null,
altdispid varchar (255) null,
id integer null
);
load into table dbo.ATSROUTES from 'C:\Routes\ATS_Routes.csv' format ascii;
//load into table comet.ATSROUTES from 'C:\ATS_Routes.csv' format ascii;
if exists(select * from sys.sysprocedure where proc_name = 'updateroute')
begin
drop procedure updateroute;
end
CREATE PROCEDURE comet.updateroute ( /* parameter, ... */ )
/* RESULT ( column_name, ... ) */
BEGIN
declare @route varchar(255);
declare @zip varchar(255);
declare @routeid varchar(255);
declare @distcenter varchar(255);
declare @altdispid varchar(255);
declare ERR_NOTFOUND exception for sqlstate value '02000';
DECLARE priceinfo dynamic scroll CURSOR FOR SELECT zip, route from atsroutes;
OPEN priceinfo with hold;
lp: LOOP
FETCH next priceinfo INTO @zip,@route;
if(sqlstate = ERR_NOTFOUND) then begin
leave lp
end
if (@route is not null and @route <> '')
begin
if not exists (select * from routenames where routename = @ROUTE) begin
call COMET.GETNEWRECID2('ROUTENAMES','ROUTEID','ROUTENAMES',@ROUTEID);
insert into routenames (routeid,routename) values (@routeid,@ROUTE);
end
end
end loop;
close priceinfo;
END;
call updateroute;
drop procedure comet.updateroute;
update atsroutes set id = (select routeid from routenames where routename
= route);
update atsroutes set drivernum = trim(drivernum);
update atsroutes set altserviceid = trim(altserviceid);
update atsroutes set pickupzone = trim(pickupzone);
update atsroutes set distcenter = trim(distcenter);
update atsroutes set altdispid = trim(altdispid);
update atsroutes set drivernum = (case when (length(drivernum) = 3) then
'0'+drivernum else drivernum end),
//ikeadrivernum = (case when (length(ikeadrivernum) = 3) then
'0'+ikeadrivernum else ikeadrivernum end),
localorldrvnum = (case when (length(localorldrvnum) = 3) then
'0'+localorldrvnum else localorldrvnum end)
Thanks for your comments
How can i change this Store Procedure for Sql Server. I try but i have not
success can you please help me . I am not understanding what is going in
this SP and what i will write in SQL SERVER 2008 .
if exists (select * from sys.systable where table_name = 'ATSROUTES')
begin
drop table ATSROUTES;
end
create table comet.ATSROUTES(
zip varchar(255) null,
route varchar(255) null,
drivernum varchar(255) null,
altserviceid varchar(255) null,
localorldrvnum varchar(255) null,
pickupzone varchar (255) null,
distcenter varchar (255) null,
altdispid varchar (255) null,
id integer null
);
load into table dbo.ATSROUTES from 'C:\Routes\ATS_Routes.csv' format ascii;
//load into table comet.ATSROUTES from 'C:\ATS_Routes.csv' format ascii;
if exists(select * from sys.sysprocedure where proc_name = 'updateroute')
begin
drop procedure updateroute;
end
CREATE PROCEDURE comet.updateroute ( /* parameter, ... */ )
/* RESULT ( column_name, ... ) */
BEGIN
declare @route varchar(255);
declare @zip varchar(255);
declare @routeid varchar(255);
declare @distcenter varchar(255);
declare @altdispid varchar(255);
declare ERR_NOTFOUND exception for sqlstate value '02000';
DECLARE priceinfo dynamic scroll CURSOR FOR SELECT zip, route from atsroutes;
OPEN priceinfo with hold;
lp: LOOP
FETCH next priceinfo INTO @zip,@route;
if(sqlstate = ERR_NOTFOUND) then begin
leave lp
end
if (@route is not null and @route <> '')
begin
if not exists (select * from routenames where routename = @ROUTE) begin
call COMET.GETNEWRECID2('ROUTENAMES','ROUTEID','ROUTENAMES',@ROUTEID);
insert into routenames (routeid,routename) values (@routeid,@ROUTE);
end
end
end loop;
close priceinfo;
END;
call updateroute;
drop procedure comet.updateroute;
update atsroutes set id = (select routeid from routenames where routename
= route);
update atsroutes set drivernum = trim(drivernum);
update atsroutes set altserviceid = trim(altserviceid);
update atsroutes set pickupzone = trim(pickupzone);
update atsroutes set distcenter = trim(distcenter);
update atsroutes set altdispid = trim(altdispid);
update atsroutes set drivernum = (case when (length(drivernum) = 3) then
'0'+drivernum else drivernum end),
//ikeadrivernum = (case when (length(ikeadrivernum) = 3) then
'0'+ikeadrivernum else ikeadrivernum end),
localorldrvnum = (case when (length(localorldrvnum) = 3) then
'0'+localorldrvnum else localorldrvnum end)
Thanks for your comments
How do I get google play back to sys app without being able to access any apps on google play?
How do I get google play back to sys app without being able to access any
apps on google play?
After rooting my galaxy s, I deleted google play. I have now downloaded it
but I cannot get it back to sys app and it forcecloses every time I try to
open it. I can't download anything from google play to help me solve the
issue. Please help! Thank you!
apps on google play?
After rooting my galaxy s, I deleted google play. I have now downloaded it
but I cannot get it back to sys app and it forcecloses every time I try to
open it. I can't download anything from google play to help me solve the
issue. Please help! Thank you!
Arquillian Embedded Glassfish Certificate Expired
Arquillian Embedded Glassfish Certificate Expired
On Aug 14th, the gtecybertrust5ca certifcate used by Glassfish expired
causing my Arquillian tests that use an embedded Glassfish server to all
fail. I have verified I am using the latest JDK, 1.7.0_25-b17, and my
Maven libs are current.
This problem is similar to this one: Certificate has expired" in log by
starting Glassfish 3.1.2 except, I am using the Embedded version of
Glassfish via Maven, Arquillian and SureFire to run unit and integration
tests.
I have tried instructing Maven to use a local keystore, the one that comes
with the JRE, in an effort to keep the expired cert from being used.
Unfortunately, this didn't help either. Using the Maven debug flag, I can
see that the JDK is forked with the addition arguments.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<argLine>-Djavax.net.ssl.trustStore=C:\Java\jdk1.7.0_25\jre\lib\security\cacerts.jks
-Djavax.net.ssl.trustStorePassword=changeit</argLine>
<classpathDependencyExcludes>
<!-- exclude code absent api -->
<classpathDependencyExclude>javax:javaee-api</classpathDependencyExclude>
<classpathDependencyExclude>javax:javaee-web-api</classpathDependencyExclude>
</classpathDependencyExcludes>
</configuration>
</plugin>
<!-- Configure the Embedded GlassFish Maven plugin -->
<plugin>
<groupId>org.glassfish.embedded</groupId>
<artifactId>maven-embedded-glassfish-plugin</artifactId>
<version>4.0</version>
<configuration>
<app>${project.build.directory}/${project.build.finalName}.war</app>
<port>7070</port>
<containerType>web</containerType>
</configuration>
</plugin>
I have also tried downloading the actual Glassfish server, exporting its
certificates gtecybertrust5ca and gtecybertrustglobalca from the keystore
at glassfish4\glassfish\domains\domain1\config\cacerts.jks and then
imported them into my JRE keystore marking them as trusted. This also
didn't work:
keytool -exportcert -keystore cacerts.jks -alias gtecybertrustglobalca
-file gtecybertrustglobalca.crt keytool -exportcert -keystore cacerts.jks
-alias gtecybertrust5ca -file gtecybertrust5ca.crt
keytool -importcert -keystore
C:\Java\jdk1.7.0_25\jre\lib\security\cacerts.jks -alias gtecybertrust5ca
-file gtecybertrust5ca.crt keytool -importcert -keystore
C:\Java\jdk1.7.0_25\jre\lib\security\cacerts.jks -alias
gtecybertrustglobalca -file gtecybertrustglobalca.crt
I would really appreciate some help. Thanks.
On Aug 14th, the gtecybertrust5ca certifcate used by Glassfish expired
causing my Arquillian tests that use an embedded Glassfish server to all
fail. I have verified I am using the latest JDK, 1.7.0_25-b17, and my
Maven libs are current.
This problem is similar to this one: Certificate has expired" in log by
starting Glassfish 3.1.2 except, I am using the Embedded version of
Glassfish via Maven, Arquillian and SureFire to run unit and integration
tests.
I have tried instructing Maven to use a local keystore, the one that comes
with the JRE, in an effort to keep the expired cert from being used.
Unfortunately, this didn't help either. Using the Maven debug flag, I can
see that the JDK is forked with the addition arguments.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<argLine>-Djavax.net.ssl.trustStore=C:\Java\jdk1.7.0_25\jre\lib\security\cacerts.jks
-Djavax.net.ssl.trustStorePassword=changeit</argLine>
<classpathDependencyExcludes>
<!-- exclude code absent api -->
<classpathDependencyExclude>javax:javaee-api</classpathDependencyExclude>
<classpathDependencyExclude>javax:javaee-web-api</classpathDependencyExclude>
</classpathDependencyExcludes>
</configuration>
</plugin>
<!-- Configure the Embedded GlassFish Maven plugin -->
<plugin>
<groupId>org.glassfish.embedded</groupId>
<artifactId>maven-embedded-glassfish-plugin</artifactId>
<version>4.0</version>
<configuration>
<app>${project.build.directory}/${project.build.finalName}.war</app>
<port>7070</port>
<containerType>web</containerType>
</configuration>
</plugin>
I have also tried downloading the actual Glassfish server, exporting its
certificates gtecybertrust5ca and gtecybertrustglobalca from the keystore
at glassfish4\glassfish\domains\domain1\config\cacerts.jks and then
imported them into my JRE keystore marking them as trusted. This also
didn't work:
keytool -exportcert -keystore cacerts.jks -alias gtecybertrustglobalca
-file gtecybertrustglobalca.crt keytool -exportcert -keystore cacerts.jks
-alias gtecybertrust5ca -file gtecybertrust5ca.crt
keytool -importcert -keystore
C:\Java\jdk1.7.0_25\jre\lib\security\cacerts.jks -alias gtecybertrust5ca
-file gtecybertrust5ca.crt keytool -importcert -keystore
C:\Java\jdk1.7.0_25\jre\lib\security\cacerts.jks -alias
gtecybertrustglobalca -file gtecybertrustglobalca.crt
I would really appreciate some help. Thanks.
How to move an image from one point to another?
How to move an image from one point to another?
i would like to press a button and an Image move from the bottom to the
top of the screen and thats it.
How do I achieve this.
I haven't tried anything yet.
i would like to press a button and an Image move from the bottom to the
top of the screen and thats it.
How do I achieve this.
I haven't tried anything yet.
Underscore Arrow (_ => ...) What Is This?
Underscore Arrow (_ => ...) What Is This?
Reading through C# in a Nutshell I noticed this bit of code that I've
never came across:
_uiSyncContent.Post(_ => txtMessage.Text += "Test");
What is that underscore followed by an arrow? I've seen Lambda expressions
written in a similar way but nothing with an underscore.
Reading through C# in a Nutshell I noticed this bit of code that I've
never came across:
_uiSyncContent.Post(_ => txtMessage.Text += "Test");
What is that underscore followed by an arrow? I've seen Lambda expressions
written in a similar way but nothing with an underscore.
How the spring container starts and ways to load the spring container
How the spring container starts and ways to load the spring container
Hi Guys..
I want to know how actually the spring container gets loaded on server..
and in how many ways can that be done and exactly how the server comes to
know that it has to start the spring container. I tried to google it but
no luck...
Thanks in advance for your time and help...
Hi Guys..
I want to know how actually the spring container gets loaded on server..
and in how many ways can that be done and exactly how the server comes to
know that it has to start the spring container. I tried to google it but
no luck...
Thanks in advance for your time and help...
Laptop connects to wrong wireless network
Laptop connects to wrong wireless network
I mostly have two wireless networks in range NP_LNK (low signal strength,
OPEN, owned by my nieghbour) and MY_LINK(Strong signal strength ,
Protected by a KEY, Owned by me)
and My laptop always connects to NP_LINK automatically. I have tried
deleting this network and changing settings but it appears again on next
boot.
Is there a way to permanently hide/ disable this network ?
I mostly have two wireless networks in range NP_LNK (low signal strength,
OPEN, owned by my nieghbour) and MY_LINK(Strong signal strength ,
Protected by a KEY, Owned by me)
and My laptop always connects to NP_LINK automatically. I have tried
deleting this network and changing settings but it appears again on next
boot.
Is there a way to permanently hide/ disable this network ?
Saturday, 17 August 2013
How do I submit POST for cURL in Lithium
How do I submit POST for cURL in Lithium
I'm trying to create a custom Auth adapter for a legacy API. Let's call
the adapter TR42. Right now, I'm debugging TR42::check() so I'm using
hardcoded values:
<?php
class TR42 extends \lithium\core\Object {
public function __construct(array $config = []) {
$defaults = [
'scheme' => 'http',
'host' => 'localhost/tr42/mock_api_authenticate.php',
'action' => 'authLookup',
'fields' => ['username', 'password'],
'method' => 'POST'
];
parent::__construct($config + $defaults);
}
public function check($credentials, array $options = []) {
$postConfig = [
/**
* Should I be using 'body' or 'query' to submit POST fields?
*/
'body' => [
'username' => 'housni',
'password' => sha1('legacyHashedPassword'),
'action' => 'authLookup'
],
'query' => 'username=housni&password=' .
sha1('legacyHashedPassword') . '&action=authLookup',
];
$request = new Request($postConfig + $this->_config);
$stream = new Curl($this->_config);
$stream->open();
$stream->write($request);
$response = $stream->read();
$stream->close();
echo '<pre>' . print_r($response, true) . '</pre>';
die();
}
}
?>
The file http://localhost/tr42/mock_api_authenticate.php looks like this:
<?php
echo '<h1>This request is: ' . $_SERVER['REQUEST_METHOD'] . '</h1>';
if (!empty($_POST)) {
echo '<h1>YAY</h1>';
} else {
echo '<h1>NAY</h1>';
}
echo '<pre>' . print_r($_POST, true) . '</pre>';
?>
Since my cURL code submits a POST request, I'd expect my $_POST to be
populated in mock_api_authenticate.php but that's not happening because
the output from TR42::check()'s print_r() is:
HTTP/1.1 200 OK
Date: Sun, 18 Aug 2013 04:46:34 GMT
Server: Apache/2.2.14 (Ubuntu)
X-Powered-By: PHP/5.4.17-1~lucid+1
Vary: Accept-Encoding
Content-Length: 63
Connection: close
Content-Type: text/html
This request is: POST
NAY
Array
(
)
It's saying the request is POST but the POST array (the last empty array)
is empty.
What am I doing wrong?
Thanks for reading :)
I'm trying to create a custom Auth adapter for a legacy API. Let's call
the adapter TR42. Right now, I'm debugging TR42::check() so I'm using
hardcoded values:
<?php
class TR42 extends \lithium\core\Object {
public function __construct(array $config = []) {
$defaults = [
'scheme' => 'http',
'host' => 'localhost/tr42/mock_api_authenticate.php',
'action' => 'authLookup',
'fields' => ['username', 'password'],
'method' => 'POST'
];
parent::__construct($config + $defaults);
}
public function check($credentials, array $options = []) {
$postConfig = [
/**
* Should I be using 'body' or 'query' to submit POST fields?
*/
'body' => [
'username' => 'housni',
'password' => sha1('legacyHashedPassword'),
'action' => 'authLookup'
],
'query' => 'username=housni&password=' .
sha1('legacyHashedPassword') . '&action=authLookup',
];
$request = new Request($postConfig + $this->_config);
$stream = new Curl($this->_config);
$stream->open();
$stream->write($request);
$response = $stream->read();
$stream->close();
echo '<pre>' . print_r($response, true) . '</pre>';
die();
}
}
?>
The file http://localhost/tr42/mock_api_authenticate.php looks like this:
<?php
echo '<h1>This request is: ' . $_SERVER['REQUEST_METHOD'] . '</h1>';
if (!empty($_POST)) {
echo '<h1>YAY</h1>';
} else {
echo '<h1>NAY</h1>';
}
echo '<pre>' . print_r($_POST, true) . '</pre>';
?>
Since my cURL code submits a POST request, I'd expect my $_POST to be
populated in mock_api_authenticate.php but that's not happening because
the output from TR42::check()'s print_r() is:
HTTP/1.1 200 OK
Date: Sun, 18 Aug 2013 04:46:34 GMT
Server: Apache/2.2.14 (Ubuntu)
X-Powered-By: PHP/5.4.17-1~lucid+1
Vary: Accept-Encoding
Content-Length: 63
Connection: close
Content-Type: text/html
This request is: POST
NAY
Array
(
)
It's saying the request is POST but the POST array (the last empty array)
is empty.
What am I doing wrong?
Thanks for reading :)
ZoneMinder compiling error: "missing binary operator before token "(""
ZoneMinder compiling error: "missing binary operator before token "(""
When installing ZoneMinder 1.25.0 in CentOS 6.4 (64-bit) the following
error pops up when executing make:
zm_ffmpeg_camera.cpp:105:44: error: missing binary operator before token "("
Full log in this pastebin.
(I'll be answering my own question to help future users).
When installing ZoneMinder 1.25.0 in CentOS 6.4 (64-bit) the following
error pops up when executing make:
zm_ffmpeg_camera.cpp:105:44: error: missing binary operator before token "("
Full log in this pastebin.
(I'll be answering my own question to help future users).
Adding Multiple Enums to JComboBox
Adding Multiple Enums to JComboBox
I want to add different Enums to a single JComboBox. Here is how the code
looks like. Type contains 3 different type of Enums(Colors, Shapes,
Dimensions).
final JComboBox typeJComboBox = new JComboBox(Type.Colors.values());
for(Type.Shapes shape: Type.Shapes.values()) {
typeJComboBox .addItem(shape);
}
for(Type.Dimensions dimension : Type.Dimensions.values()) {
typeJComboBox .addItem(dimension );
}
What generic type do I use? When using eclipse, there is a yellow squiggly
line under JComboBox and when you hover your mouse over it, it says "Infer
Generic Type Arguments...".
I want to add different Enums to a single JComboBox. Here is how the code
looks like. Type contains 3 different type of Enums(Colors, Shapes,
Dimensions).
final JComboBox typeJComboBox = new JComboBox(Type.Colors.values());
for(Type.Shapes shape: Type.Shapes.values()) {
typeJComboBox .addItem(shape);
}
for(Type.Dimensions dimension : Type.Dimensions.values()) {
typeJComboBox .addItem(dimension );
}
What generic type do I use? When using eclipse, there is a yellow squiggly
line under JComboBox and when you hover your mouse over it, it says "Infer
Generic Type Arguments...".
Moving all files in a folder to a new child directory
Moving all files in a folder to a new child directory
In Powershell, how can I move all files in a folder to a new child directory?
I've tried mv c:\foo\* c:\foo\bar\, but all my files disappear and I get
an extension-less 'bar' file. I've also tried making the directory first
and then doing the move, but I get a The process cannot access the file
because it is being used by another process error, presumably because it
is then trying to move the 'bar' folder to itself.
In Powershell, how can I move all files in a folder to a new child directory?
I've tried mv c:\foo\* c:\foo\bar\, but all my files disappear and I get
an extension-less 'bar' file. I've also tried making the directory first
and then doing the move, but I get a The process cannot access the file
because it is being used by another process error, presumably because it
is then trying to move the 'bar' folder to itself.
Launch Photoswipe gallery by simple link
Launch Photoswipe gallery by simple link
I use the photoswipe plugin:
(function(window, PhotoSwipe){
document.addEventListener('DOMContentLoaded', function() {
var options = {
preventHide: true,
getImageSource: function(obj) {
return obj.url;
},
getImageCaption: function(obj) {
return obj.caption;
}
},
instance = PhotoSwipe.attach([
{ url: 'http://www.site.com/img/8896/ico5.jpg', caption:
'Image 001' },
{ url: 'http://www.site.com/img/8897/ico5.jpg', caption:
'Image 002' },
{ url: 'http://www.site.com/img/8898/ico5.jpg', caption:
'Image 003' },
{ url: 'http://www.site.com/img/8899/ico5.jpg', caption:
'Image 004' },
{ url: 'http://www.site.com/img/9000/ico5.jpg', caption:
'Image 005' },
{ url: 'http://www.site.com/img/9001/ico5.jpg', caption:
'Image 006' }
], options);
instance.show(0);
}, false);
}(window, window.Code.PhotoSwipe));
I would like launch the gallery from a simple url in my page like this:
<a href="#" id="photo">
<img src="/img/ico_photo1.png" border="0" /><br>
Gallery
</a>
But I don't know how do it; can you help me?
I use the photoswipe plugin:
(function(window, PhotoSwipe){
document.addEventListener('DOMContentLoaded', function() {
var options = {
preventHide: true,
getImageSource: function(obj) {
return obj.url;
},
getImageCaption: function(obj) {
return obj.caption;
}
},
instance = PhotoSwipe.attach([
{ url: 'http://www.site.com/img/8896/ico5.jpg', caption:
'Image 001' },
{ url: 'http://www.site.com/img/8897/ico5.jpg', caption:
'Image 002' },
{ url: 'http://www.site.com/img/8898/ico5.jpg', caption:
'Image 003' },
{ url: 'http://www.site.com/img/8899/ico5.jpg', caption:
'Image 004' },
{ url: 'http://www.site.com/img/9000/ico5.jpg', caption:
'Image 005' },
{ url: 'http://www.site.com/img/9001/ico5.jpg', caption:
'Image 006' }
], options);
instance.show(0);
}, false);
}(window, window.Code.PhotoSwipe));
I would like launch the gallery from a simple url in my page like this:
<a href="#" id="photo">
<img src="/img/ico_photo1.png" border="0" /><br>
Gallery
</a>
But I don't know how do it; can you help me?
Cache synchronization
Cache synchronization
I'm working on a thread safe cache implementation.
Could you please tell me if I make too much synchronization here:
private static final Map<String, Object> cache = new HashMap<String,
Object>();
public static Object getCached(String key) {
Object cached = cache.get(key);
if (cached == null) {
synchronized (cache) {
cached = cache.get(src);
if (cached == null) {
cached = createObject();
cache.put(src, cached);
}
}
}
return cached;
}
I'm working on a thread safe cache implementation.
Could you please tell me if I make too much synchronization here:
private static final Map<String, Object> cache = new HashMap<String,
Object>();
public static Object getCached(String key) {
Object cached = cache.get(key);
if (cached == null) {
synchronized (cache) {
cached = cache.get(src);
if (cached == null) {
cached = createObject();
cache.put(src, cached);
}
}
}
return cached;
}
Linux boot drive refusing to reset
Linux boot drive refusing to reset
I used one of my USB sticks to create a live ubuntu disk intending to
clear it later, well I plugged it in to Linux Mint 15 today only to find
that I can not delete any of the files on it.
Is there a way to delete those files? Or is it just stuck forever? I also
tried putting it on windows only it was even worse there only allowing me
to see only 2.19 mbs of the total 16 gig drive. I was hoping that deleting
that would fix it once I got back to linux, it however did not.
Thanks for answering! I really need help on this one.
I used one of my USB sticks to create a live ubuntu disk intending to
clear it later, well I plugged it in to Linux Mint 15 today only to find
that I can not delete any of the files on it.
Is there a way to delete those files? Or is it just stuck forever? I also
tried putting it on windows only it was even worse there only allowing me
to see only 2.19 mbs of the total 16 gig drive. I was hoping that deleting
that would fix it once I got back to linux, it however did not.
Thanks for answering! I really need help on this one.
Thursday, 8 August 2013
What determines what resolutions a laptop is willing to output over VGA?
What determines what resolutions a laptop is willing to output over VGA?
I'm responsible for several conference rooms and have setup 1080p
projectors and I provide both HDMI and VGA connectivity. HDMI for
DisplayPort and Mini-DisplayPort, and VGA as a fallback, universal option.
Contrary to what I expected, people seem to have much more trouble with
the HDMI than VGA, so VGA gets used a lot more than you'd think (even as
most workstation laptops made in the last 3-4 years have DisplayPort or
Mini-DisplayPort...). Also to my surprise, VGA outputs over 1080p on a
50ft cable run with very minimal degradation on certain laptops - other
laptops just don't offer 1080p as a resolution choice and top out at
1600x1200 or something else. Specific example: a ThinkPad W530 will do
1080p, a W520 won't, over VGA.
What determines what resolutions a laptop is willing to output over VGA?
I'm thinking this will come down to either a video driver that says it
supports only certain resolutions for output, or limitations of the RAMDAC
(which wouldn't be in play, at least DAC wise, on a digital output, but
WOULD on VGA, an analog output).
The basic reason for the question is that I noticed, say, a ThinkPad W520
with 1080p built in display, will output 1080p fine over DisplayPort to a
1080p projector, but will cap out at 1600x1200 (practically the same pixel
count, just a little shy) on VGA. Now, this wouldn't be surprising at all
except SOME laptops have no issue outputting 1080p over VGA, even with
lower native resolutions.
Why do I care? Well if there's some way I could enable it... for
situations where my users end up using VGA anyway, it's preferable for
display mirroring if they can output their laptop's native resolution,
which, you guessed it, is very often 1080p on 15" models.
DISCLAIMER: This is primarily a curiosity, I'm not claiming 1080p over VGA
is ideal by any means, but hey, if it works. I've seen HDMI start
artifacting more over same-length, same gauge cabling (up to 50' run in
certain rooms). If you think this is better suited to SuperUser, please
move it, but this is framed from an IT standpoint of something that
affects a real pool of users in a multiple conference room, 50+ deployed
laptop scenario.
I'm responsible for several conference rooms and have setup 1080p
projectors and I provide both HDMI and VGA connectivity. HDMI for
DisplayPort and Mini-DisplayPort, and VGA as a fallback, universal option.
Contrary to what I expected, people seem to have much more trouble with
the HDMI than VGA, so VGA gets used a lot more than you'd think (even as
most workstation laptops made in the last 3-4 years have DisplayPort or
Mini-DisplayPort...). Also to my surprise, VGA outputs over 1080p on a
50ft cable run with very minimal degradation on certain laptops - other
laptops just don't offer 1080p as a resolution choice and top out at
1600x1200 or something else. Specific example: a ThinkPad W530 will do
1080p, a W520 won't, over VGA.
What determines what resolutions a laptop is willing to output over VGA?
I'm thinking this will come down to either a video driver that says it
supports only certain resolutions for output, or limitations of the RAMDAC
(which wouldn't be in play, at least DAC wise, on a digital output, but
WOULD on VGA, an analog output).
The basic reason for the question is that I noticed, say, a ThinkPad W520
with 1080p built in display, will output 1080p fine over DisplayPort to a
1080p projector, but will cap out at 1600x1200 (practically the same pixel
count, just a little shy) on VGA. Now, this wouldn't be surprising at all
except SOME laptops have no issue outputting 1080p over VGA, even with
lower native resolutions.
Why do I care? Well if there's some way I could enable it... for
situations where my users end up using VGA anyway, it's preferable for
display mirroring if they can output their laptop's native resolution,
which, you guessed it, is very often 1080p on 15" models.
DISCLAIMER: This is primarily a curiosity, I'm not claiming 1080p over VGA
is ideal by any means, but hey, if it works. I've seen HDMI start
artifacting more over same-length, same gauge cabling (up to 50' run in
certain rooms). If you think this is better suited to SuperUser, please
move it, but this is framed from an IT standpoint of something that
affects a real pool of users in a multiple conference room, 50+ deployed
laptop scenario.
Subscribe to:
Comments (Atom)