Saturday, 31 August 2013

How can I open the running application opened by my previous login?

How can I open the running application opened by my previous login?

Now I am using a remote desktop to connect to a remote linux(ubuntu)
virtual machine.Yesterday ,I opened a applicationiKomodojCand closed my
remote desktop client when I left(the virtual machine was kept
running).Today ,I reconnect to my VM and want to reuse the Komodo I opened
yesterday,What can I do?When I directly click the Komodo tag on my
desktop,I cannot open it because there is already a Komodo process
running.So I have to manually kill the process in the terminal and then
click the Komodo tag on my desktop.I think it's not a very good way
because every time I reconnect to my VM,I have to kill the Komodo process.

2D dynamic allocation in C error when incrementing the pointer

2D dynamic allocation in C error when incrementing the pointer

I wanted to allocate a string array dynamically , the program is supposed
to ask the user for characters and collect them in the first string in the
array till letter 'q' is entered then the program starts adding the
characters to the second line and so on.
When I print the characters memory location it seems like each character
takes two memory cells instead of one though I increment it only once.
Here is the source code to my program
#include <stdio.h>
void main(){
char** txt;
char* baseAddress;
txt = (char **)malloc(5*sizeof(char*));
*txt = (char *)malloc(20*sizeof(char));
baseAddress=*txt;
while(*(*txt)!='q'){
(*txt)++;
scanf("%c",(*txt));
printf("%p\r\n",(*txt));
}
*txt='\0';
printf("%p",baseAddress);
free(baseAddress);
free(txt);
}
the output is like this
>j
>0x9e12021
>0x9e12022
>s
>0x9e12023
>0x9e12024
>
I think there may be something wrong with the pointers. How do I go about
accomplishing this? and sorry for the bad english

How do you run DaoTest

How do you run DaoTest

I really don't know anything about JUnit, and I want a quick answer. I
built and ran DAOtest using eclipse, but where are the entry points. Or
where see the execution.

How to merge videos by avconv?

How to merge videos by avconv?

I have several chunks in folder.
0001.mp4
0002.mp4
0003.mp4
...
0112.mp4
I would like to join them into full video.mp4
I tried to use
avconv -i "concat:`ls -l /root/chunk/ | awk 'BEGIN {ORS="|"} { print $9
}'`" \
-c:v copy -c:a copy /root/test/2.mp4
but I have error
concat:|0000.mp4|0001.mp4|0002.mp4|0003.mp4|0004.mp4|0005.mp4|0006.mp4|\
0007.mp4|0008.mp4|0009.mp4|0010.mp4|0011.mp4|0012.mp4|0013.mp4|0015.mp4|\
0016.mp4|0017.mp4|0018.mp4|0019.mp4|: No such file or directory
After I tried
avconv -i
"concat:/root/chunk/0000.mp4|/root/chunk/0001.mp4|/root/chunk/0002.mp4"
\
-c:v copy -c:a copy /root/test/2.mp4
but only one input file was catched to output.
How to merge all chunks from folder into full video?
I don't want to use ffmpeg or other. Avconv only.

Sql performance more columns or more tables for reporting

Sql performance more columns or more tables for reporting

Hi all first post for me!!
I have a sql database that was passed down to me that started of as an
access application. Since then its evolved alot. The previous developer
stored additional columns on a table instead of splitting the tables and
we are starting to report on this data ( over 1m rows) and performance is
starting to drag on some queries.
1 table is for company and contains name, reference, address details,
financial details, insurance etc.
I am thinking that we should split the table up and have tblcompany,
tbladdress, tblfinance etc. Since our reporting allows users to report on
whatever fields they want. i think it would be better to inner join
tbladdress if the user wants to report on address details, the same for
finance, insurance etc, also some companies may not have any finance
details so whats the point in having lots of null fields?
So my question is would it improve performance? I think design wise it is
the thing to do but wanted everyones tips, tricks and opinions.
Thanks in advanced

How ui:include in jsf work?

How ui:include in jsf work?

I am trying to make templates so I don't need to write same code for xhtml
page 2 times, but I have problem with ui:include when I have some parts of
page that need to be change depends on what action I requested.To be clear
problem is in when i need to have some actions on included page.Here is my
code so you can see what I am doing. This is template where I use include
for parts that need to be different depends on what user want to do.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<ui:composition template="/sheard/template.xhtml">
<ui:define name="body">
<rich:message/>
<ui:include src="/sheard/admin/admin_header.xhtml" />
<a4j:outputPanel id="tabela">
<h:form>
<rich:panel>
<f:facet name="header">
<h:outputText value="#{ title}" />
</f:facet>
<rich:dataTable value="#{ data}" var="model"
iterationStatusVar="it">
<rich:column style="width:50px">
<f:facet name="header">Red br.</f:facet>
<h:outputText value="#{it.index+1}" />
</rich:column>
<ui:insert name="table_body"/>
</rich:dataTable>
</rich:panel>
</h:form>
</a4j:outputPanel>
<h:form prependId="false">
<rich:popupPanel id="popup" modal="true"
width="500" moveable="true"
resizeable="false" domElementAttachment="form">
<f:facet name="header">
<h:outputText value="Pregled Korisnika" />
</f:facet>
<f:facet name="controls">
<h:outputLink value="#"
onclick="#{rich:component('popup')}.hide();
return false;">
X
</h:outputLink>
</f:facet>
<a4j:outputPanel id="popup_internal">
<ui:include src="#{ includeOption}" />
</a4j:outputPanel>
</rich:popupPanel>
</h:form>
</ui:define>
<ui:define name="footer">
<h:outputLink value="rentacar.xhtml">Glavni meni</h:outputLink>
<br />
<h:form>
<ui:insert name="footer_menu"/>
<br />
<h:commandLink value="Logout" action="#{
LogInControler.LogOut()}" />
</h:form>
</ui:define>
</ui:composition>
so you can see that I am doing include inside some popup panel, and you
can see that include depends on some parameter.Here is definition for page
that user see and from which I set include parameter.
<ui:composition template="/sheard/admin/pregled_template.xhtml">
<ui:param name="title" value="Pregled musterija" />
<ui:param name="data" value="#{ DataFetcher.fetchUsers()}" />
<ui:define name="table_body">
<rich:column style="width:150px">
<f:facet name="header">JMBG</f:facet>
<h:outputText value="#{model.JMBG}" />
</rich:column>
<rich:column style="width:150px">
<f:facet name="header">Ime</f:facet>
<h:outputText value="#{model.ime}" />
</rich:column>
<rich:column style="width:150px">
<f:facet name="header">Prezime</f:facet>
<h:outputText value="#{model.prezime}" />
</rich:column>
<rich:column style="width:250px">
<f:facet name="header">Adresa</f:facet>
<h:outputText value="#{model.adresa}" />
</rich:column>
<rich:column style="width:150px">
<a4j:commandButton value="View" render="popup_internal"
action="#{
UserController.viewCustomer(model.username)}"
oncomplete="#{rich:component('popup')}.show()">
<a4j:param value="/sheard/admin/customer/view.xhtml"
assignTo="#{ includeOption}"/>
</a4j:commandButton>
<a4j:commandButton value="Edit" render="popup_internal"
action="#{ UserController.edit(model)}"
oncomplete="#{rich:component('popup')}.show()">
<a4j:param value="/sheard/admin/customer/edit.xhtml"
assignTo="#{ includeOption}"/>
</a4j:commandButton>
<a4j:commandButton value="Delete" render="tabela"
action="#{ UserController.delete(model)}" >
</a4j:commandButton>
</rich:column>
</ui:define>
<ui:define name="footer_menu">
<h:commandLink action="#{UserController.newCustomer()}"
value="Unost musterija" />
</ui:define>
</ui:composition>
Here is page on which i have problem when I include it.
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:rich="http://richfaces.org/rich"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
template="/sheard/admin/popup_panel_template.xhtml">
<ui:param name="columnCount" value="3" />
<ui:define name="popup_panel_body">
<rich:validator>
<h:outputText value="Username:" />
<h:inputText id="username" value="#{ UserController.user.username}" />
<rich:message for="username"/>
<h:outputText value="Ime:" />
<h:inputText id="ime" value="#{ UserController.user.ime}" />
<rich:message for="ime"/>
<h:outputText value="Prezime:" />
<h:inputText id="prezime" value="#{ UserController.user.prezime}" />
<rich:message for="prezime"/>
<h:outputText value="Adresa:" />
<h:inputText id="adresa" value="#{ UserController.user.adresa}" />
<rich:message for="adresa"/>
<h:outputText value="E-mail:" />
<h:inputText id="email" value="#{ UserController.user.email}" />
<rich:message for="email"/>
<h:outputText value="Kategorije:" />
<h:selectManyCheckbox id = "kategorija"
value="#{UserController.user.kategorijaList}" >
<f:selectItem itemValue='A' />
<f:selectItem itemValue='B'/>
<f:selectItem itemValue='C'/>
<f:selectItem itemValue='D'/>
</h:selectManyCheckbox>
<rich:message for="kategorija"/>
--> --> -->
Now when I gave you all code you need I will tell you what is problem.You
see problem is with this buttons on included page if i use this ajax
button which I actually need it's simple don't work.And if I use just
simple button it trigger action in moment I include page and not on click.
I hope i was clear and you get it what I ask. :)

Get Flash video uri from webview in android

Get Flash video uri from webview in android

Recently i made a app that can download flash video from webview because
of the webview calls the onShowCustomView() but when the device run on
android 3.0 + then the webview does not call the method instead webview
calls some class to handle the video. so i want to force the webview to
use CustomView to play the video. But i have not any idea how can do this
. Please help me.

GWT: What to expect when an HTTP request fails

GWT: What to expect when an HTTP request fails

I'm sending a HTTP request with RequestBuilder.send(). I would expect to
see successful responses come back in onResponseReceived(), and errors
come back in onError(). But that's not what I'm seeing. GWT calls
onResponseReceived() regardless of success or failure.
Does anyone know what I should really expect? Do you have any information
that would help me detect and report errors better?
Here's some sample code:
builder.sendRequest(null, new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response
response) {
Header[] debugHeaders = response.getHeaders();
String debugHeaders1 = response.getHeadersAsString();
int debugStatusCode = response.getStatusCode();
String debugStatusText = response.getStatusText();
String debugText = response.getText();
handleResponse(response);
}
@Override
public void onError(Request request, Throwable exception) {
reportError();
}
});
I can force an error on my computer by disabling the Wi-Fi. In that case
onResponse() is called. getHeaders() returns an array of length 1, with
the only entry set to null. getHeadersAsString returns "". getStatusCode
returns 0. getStatusText() returns "". getText() returns "".
If this is always the case, I can look for that in my code. However, I
expect that different browsers, different errors, etc, will cause a
different result. Is there any good way to always detect an error?
(As long as there are no HTTP problems, my code works fine.)

Friday, 30 August 2013

Alphabetize a List Using orderby=

Alphabetize a List Using orderby=

I have a script that searches post titles and generates a list based on a
specific label (Freebies). However, it does not return an alphabetical
list because of the command "orderby=published" How can I get my list to
be alphabetical? I've tried "&Order=alphabet" Can someone tell me what
keywords "orderby=" uses? This will be used on Blogger and I am a neophyte
:(
Here is the script:
<script type="text/javascript">
var numposts = 100;
var standardstyling = true;
function showrecentposts(json) {
for (var i = 0; i < numposts; i++) {
var entry = json.feed.entry[i];
var posttitle = entry.title.$t;
var posturl;
if (i == json.feed.entry.length) break;
for (var k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
posturl = entry.link[k].href;
break;
}}
posttitle = posttitle.link(posturl);
if (standardstyling) document.write('<li>');
document.write(posttitle);}
if (standardstyling) document.write('</li>');
}
</script>
<ul>
<script src="http://blogname.blogspot.com/feeds/posts/default/-/Freebies?
orderby=published&amp;alt=json-in-script&amp;callback=showrecentposts&amp;max-
results=999
"></script>
</ul>

Thursday, 29 August 2013

Can't run two AnyEvent::timers in the same time?

Can't run two AnyEvent::timers in the same time?

I'm trying to build a Jobs Queue Manager that is Inotyfing a folder for
changes, when a job is inserted to the new folder it is being moved to
progress folder and if the job hasn't been successfully processed, the
program moves it to failed folder. Now, I want to add a feature that after
10 minutes that a job is in failed folder, the program will retry to do
the job again by moving the job to the new folder.
Here's my code:
use strict;
use warnings;
package QueueManager;
use AnyEvent;
use AnyEvent::Filesys::Notify;
use Const::Fast;
use DDP;
use File::Basename;
use File::Copy;
use File::Remove qw(remove);
use File::Slurp;
use File::Stat qw(:stat);
use List::Util qw(first);
use List::MoreUtils qw(natatime);
use Moo;
use MooX::Types::MooseLike::Base qw<Str Num InstanceOf ArrayRef HashRef Int>;
use Regexp::Common qw(net);
use v5.10.1;
with 'MooseX::Role::Loggable';
has notifier_interval => (
is => 'ro',
isa => Num,
default => sub {30.0},
);
has failed_interval => (
is => 'ro',
isa => Num,
default => sub{60*10},
);
has number_of_jobs_to_process => (
is => 'ro',
isa => Int,
default => sub{20},
);
has failed_timer => (
is => 'ro',
writer => 'set_failed_timer',
);
has notifier => (
is => 'ro',
isa => InstanceOf['AnyEvent::Filesys::Notify'],
writer => 'set_notifier',
);
has add_output_file => (
is => 'ro',
isa => Str,
default => sub{'.add_route.output'},
);
has del_output_file => (
is => 'ro',
isa => Str,
default => sub{'.del_route.output'},
);
has jobs_folder_path => (
is => 'ro',
isa => Str,
default => sub{'queue_manager/jobs'},
);
has job_folders => (
is => 'ro',
isa => HashRef,
lazy => 1,
builder => '_build_job_folders',
);
has jobs => (
is => 'rw',
isa => ArrayRef,
lazy => 1,
default => sub{ [] },
clearer => '_clear_jobs',
);
has queue => (
is => 'rw',
isa => ArrayRef,
lazy => 1,
default => sub{ [] },
clearer => '_clear_queue',
);
has added_jobs => (
is => 'rw',
isa => ArrayRef[HashRef],
lazy => 1,
default => sub { [] },
clearer => '_clear_added_jobs',
);
has deleted_jobs => (
is => 'rw',
isa => ArrayRef[HashRef],
lazy => 1,
default => sub { [] },
clearer => '_clear_deleted_jobs',
);
has routing_table => (
is => 'rw',
isa => ArrayRef[HashRef],
lazy => 1,
builder => '_build_routing_table',
);
has email_contact => (
is => 'ro',
isa => Str,
default => sub{'some@user.com'},
);
has '+log_to_file' => ( default => sub{1} );
has '+log_path' => ( default => sub{'queue_manager/logs'} );
has '+log_file' => ( default => sub{'queue_manager.log'} );
has '+log_to_stdout' => ( default => sub{1} );
sub _build_job_folders {
my $self = shift;
my $jobs_folder_path = $self->jobs_folder_path;
my %ret_val = (
new => "$jobs_folder_path/new",
progress => "$jobs_folder_path/progress",
failed => "$jobs_folder_path/failed",
);
return \%ret_val;
}
sub _build_routing_table {
my $self = shift;
my @ret_val;
my @routing_table = `ip route show`;
foreach my $line (@routing_table) {
# 1.1.1.1 via 2.2.2.2 dev eth0 proto baba
my ($ip_address, $next_hop) = $line =~ /^($RE{net}{IPv4}) via
($RE{net}{IPv4}) .*proto zebra\s+$/;
if (defined ($ip_address) and defined ($next_hop)) {
push @ret_val, { ip_address => $ip_address, next_hop =>
$next_hop };
}
}
return \@ret_val;
}
sub run {
my $self = shift;
my %job_folders = %{ $self->job_folders };
$self->log("Queue Manager is running...");
$self->set_failed_timer(
AnyEvent->timer(
interval => $self->failed_interval,
cb => sub {
$self->post_process_failed_jobs();
},
)
);
$self->set_notifier(
AnyEvent::Filesys::Notify->new(
dirs => [ $job_folders{'new'} ],
interval => $self->notifier_interval,
cb => sub {
my (@events) = @_;
for my $event (@events) {
if ($event->is_created and basename($event->path) !~
/^\./) {
push @{ $self->jobs }, $event->path;
}
}
my $queue_timer; $queue_timer = AE::timer
$self->notifier_interval, 0, sub {
$self->process_new_jobs();
undef $queue_timer;
};
},
)
);
}
sub process_new_jobs {
my $self = shift;
my $progress_path;
my %job_folders = %{ $self->job_folders };
my @new_jobs = @{ $self->jobs };
foreach my $new_job (@new_jobs) {
my $file_name = basename($new_job);
$progress_path = "$job_folders{'progress'}/$file_name";
move($new_job, $progress_path);
$self->enter_queue($progress_path);
}
$self->_clear_jobs;
$self->start_new_jobs();
}
sub post_process_failed_jobs {
my $self = shift;
my %job_folders = %{ $self->job_folders };
my @failed_files = read_dir($job_folders{'failed'});
if (@failed_files) {
foreach my $failed_file (@failed_files) {
my $file_stat = stat("$job_folders{'failed'}/$failed_file");
my $result = time - $file_stat->mtime;
$self->log("Modified " . int($result/60) . " mins ago");
}
}
}
sub enter_queue {
my $self = shift;
my ($job_to_process) = shift;
my $file_name = basename($job_to_process);
my $args = read_file($job_to_process);
chomp $args;
for ($job_to_process) {
when (/add/) {
my ($ip_address, $next_hop) = split(/ /, $args);
push @{ $self->added_jobs }, {
ip_address => $ip_address,
next_hop => $next_hop,
file_name => $file_name,
};
push @{ $self->queue }, "add:$ip_address:$next_hop";
}
when (/del/) {
my ($ip_address) = $args;
push @{ $self->deleted_jobs }, {
ip_address => $ip_address,
file_name => $file_name,
};
push @{ $self->queue }, "del:$ip_address";
}
}
}
sub start_new_jobs {
my $self = shift;
my $iterator = natatime $self->number_of_jobs_to_process, @{
$self->queue };
while ( my @values = $iterator->() ) {
my $arguments_line = join(' ', @values);
$self->log("Processing: $arguments_line");
}
$self->_clear_queue;
$self->jobs_post_process();
}
sub jobs_post_process {
my $self = shift;
my %job_folders = %{ $self->job_folders };
p $self->added_jobs;
foreach my $added_job ( @{ $self->added_jobs } ) {
my ($ip_address, $next_hop, $file_name) =
($added_job->{'ip_address'},
$added_job->{'next_hop'},
$added_job->{'file_name'});
my $is_in_routing_table =
$self->check_is_in_routing_table($ip_address);
if (not $is_in_routing_table) {
$self->log("FAILED job: $file_name");
move("$job_folders{'progress'}/$file_name",
"$job_folders{'failed'}/$file_name");
$self->send_email($self->add_output_file, $added_job);
}
else {
$self->log("Finished processing job: $file_name");
remove("$job_folders{'progress'}/$file_name");
}
}
$self->_clear_added_jobs;
foreach my $deleted_job ( @{ $self->deleted_jobs } ) {
my ($ip_address, $file_name) =
($deleted_job->{'ip_address'},
$deleted_job->{'file_name'});
my $is_in_routing_table =
$self->check_is_in_routing_table($ip_address);
if ($is_in_routing_table) {
$self->log("FAILED job: $file_name");
move("$job_folders{'progress'}/$file_name",
"$job_folders{'failed'}/$file_name");
$self->send_email($self->del_output_file, $deleted_job);
}
else {
$self->log("Finished processing job: $file_name");
remove("$job_folders{'progress'}/$file_name");
}
}
$self->_clear_deleted_jobs;
}
sub check_is_in_routing_table {
my $self = shift;
my ($ip_address) = shift;
$self->routing_table($self->get_routing_table);
my @addresses = @{ $self->routing_table };
my ($comparable_ip) = $ip_address =~ /($RE{net}{IPv4})\/32$/;
my $ret_val = first { $_->{'ip_address'} eq $comparable_ip } @addresses;
return $ret_val;
}
sub get_routing_table {
my $self = shift;
my @routing_table = `ip route show`;
my @ret_val;
foreach my $line (@routing_table) {
# 1.1.1.1 via 2.2.2.2 dev eth0 proto baba
my ($ip_address, $next_hop) = $line =~ /^($RE{net}{IPv4}) via
($RE{net}{IPv4}) .*proto zebra\s+$/;
if (defined ($ip_address) and defined ($next_hop)) {
push @ret_val, { ip_address => $ip_address, next_hop =>
$next_hop };
}
}
return @ret_val;
}
1;
Now, my problem is that failed_timer runs only once, when the program
starts, and that's it... What have I done wrong?

Cassandra-Cli reading TimeUUID as a date string

Cassandra-Cli reading TimeUUID as a date string

I am using composite columns in cassandra, the column key is of the form
When I am reading using cassandra-cli commands get cf_name[row_id], the
data displayed is of the form
str:9f44c000-09f4-11e3-90b8-e0a485d07184
What can I do to read this in human readable format, eg. str:2013-08-21 ?
The current display format makes it difficult to read and interpret
things.
Thanks!

.NET Compact Framework library and missing DLL

.NET Compact Framework library and missing DLL

I'm playing with a CF library for the Dolphin 6000 Scanphone
HandHeldProducts.Embedded.SwiftDecoder.SwiftDecoderAssembly.dll which
links to a SD2.dll library (ILspy screen)

While debugging the application I get the error message can't find PInvoke
DLL 'SD2.dll' I found the SD2.lib file but I don't know how to use it (if
it is possible). Does anyone know how to fix that error ?

Wednesday, 28 August 2013

Accented characters trouble in SQL

Accented characters trouble in SQL

Ok, I have a web where I consult a database (phpMyAdmin) and display some
results (it's basically a searcher). The problem comes when I display
results from this Database that have accented characters. The pages in the
web are codified in utf-8 and all the content of the web accept accented
characters except when I call this database by php. I have also put the
collation of the database, the table and the fields on it in
ut8-general-ci. I have spent a lot of time finding a solution and it never
cames up. I leave the code (in php) when calling the information in the
Database:
... some code
//We select the webs with the same keywords (coincidences).
//We order first the search in the same language. All ordered by Title.
$result = mysql_query("SELECT * FROM Webs WHERE Keywords LIKE '%$search%'
ORDER BY CASE WHEN Language='English' THEN 0 ELSE 1 END, Title", $link);
if ($row = mysql_fetch_array($result))
{
//We start the list of results
echo "<ul>";
do
{
//One list element
echo "<li>";
echo "<a
href=http://".$row["Url"].".html><b>".$row["Title"]."</b></a><br/>";
echo "<a href=http://".$row["Url"].".html>".$row["Url"]."</a><br/>";
echo "".$row["Description"]."<br/>";
echo "</li><br/>";
}
while ($row = mysql_fetch_array($result));
//We end the list of results
echo "</ul><br/>";
}
else
{
echo "<p>No register has been found !</p>";
}
?>
Please any help will be welcomed.

OpenGL FreeImage Texture Loading Error

OpenGL FreeImage Texture Loading Error

Currently, my rendering works except for the textures rendering totally
black. I am getting the error 1380, or GL_INVALID_ENUM, right after
calling glTexture2D in this segment of code. I have tried everything that
I can think of, but the error will not go away.
-Calling get error right before this block of code -Texture is in powers
of 2 (128 x 128) -Using new 24-bit photoshop .bmp
glEnable(GL_TEXTURE_2D);
FREE_IMAGE_FORMAT imageFormat = FreeImage_GetFileType(filename, 0);
FIBITMAP* targaImage =
FreeImage_ConvertTo32Bits(FreeImage_Load(imageFormat, filename));
int width = FreeImage_GetWidth(targaImage);
int height = FreeImage_GetHeight(targaImage);
int nBPP = FreeImage_GetBPP(targaImage);
if (nBPP == 32)
{
// Generate an ID for the texture.
glGenTextures(1, &m_texture);
// Bind the texture as a 2D texture.
glBindTexture(GL_TEXTURE_2D, m_texture);
// Load the image data into the texture unit.
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
GL_UNSIGNED_BYTE, (GLvoid*)FreeImage_GetBits(targaImage));
if(auto temp = glGetError())
{
// GL_INVALID_ENUM/1380 here
}
FreeImage_Unload(targaImage);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

TextView line bounds and orientation change mismatched values of bounds when landscape

TextView line bounds and orientation change mismatched values of bounds
when landscape

I have a confusing problem with my textview, after orientation change:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:text="Simple"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:background="@drawable/my_color_drawable"
android:id="@+id/text1"
android:layout_gravity="center"/><\FrameLayout>
when i start app in landscape mode the method getLineBounds(1,tmpRect)
results in:
tmpRect.top = 69
then I change my phone orientation to portrait and results are:
tmpRect.top = 76
Hovewer after changing back to landscape the results is set to
74(previosuly 69), and both results doesnt change from now on.
The results are 76 and 74 for when starting app in portrait mode.
I'm really curious why is that happening that numbers are diffrent when
started in landscape and I will appreciate any help.
Info: my activity have set android:screenOrientation="sensor"
Thanks.

Mono Linq to XML throwing SIGSEGV

Mono Linq to XML throwing SIGSEGV

I have been banging my head against the wall on this one and I'm hoping
that somebody can be kind enough give some advice about what might be
going wrong with the code below.
I've got a project that I'm developing with Mono 3.0.7 in MonoDevelop
4.0.9 on Linux and the project is targeting .NET 3.5.
I need to process an XML file so I want to use Linq to XML to make it
easier to work with the XML file. I'm not having any problems generating
the XML and writing it out to a file. However, when I try to read things
from the file, Mono is crashing with a SIGSEGV error.
For example, I'd like to try something like this:
//Load the document
XDocument indexFile = XDocument.Load(indexFilePath);
foreach (XElement acctElement in indexFile.Descendants("Account"))
{
AcctCls acct = new AcctCls(acctElement.Attribute("AcctID").Value);
AcctsList.Add(acct);
foreach (XElement regionElement in acctElement.Descendants("Region"))
{
RegionCls region = new
RegionCls(regionElement.Attribute("Region").Value);
acct.RegionsList.Add(region);
}
}
I have tried running this with the .NET Framework and it seems to run
fine. However, when I run this with Mono, I get the following error
message:
Stacktrace:
at <unknown> <0xffffffff>
...My own libraries...
at (wrapper runtime-invoke) <Module>.runtime_invoke_void_object
(object,intptr,intptr,intptr) <IL 0x00050, 0xffffffff>
Native stacktrace:
/usr/bin/mono() [0x4ae331]
/usr/bin/mono() [0x503b8b]
/usr/bin/mono() [0x4226b2]
/usr/lib/libpthread.so.0(+0xf830) [0x7f4f68629830]
/usr/bin/mono() [0x4d00d9]
/usr/bin/mono() [0x4d5049]
/usr/bin/mono() [0x4d5741]
/usr/bin/mono() [0x4d583f]
/usr/bin/mono() [0x4d67b5]
/usr/bin/mono() [0x4d75fc]
/usr/bin/mono() [0x4caeea]
/usr/bin/mono() [0x4cb03e]
=================================================================
Got a SIGSEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.
=================================================================
I even get the same error when I do something as simple as this:
IEnumerable acctsList = indexFile.Descendants("Account");
foreach(XElement acctElmnt in acctsList)
{
string test = acctElmnt.Attribute("AcctID").Value;
}
I've tried putting the XMLReader in a using statement and passing that
XMLReader to the XDocument.Load method but that doesn't help either. I
don't know if this is relevant or not, but this is happening while I'm
debugging the code and stepping through it.
I've been Googling for a few hours now and racking my brains trying
everything, but I can't figure out how to get this to work. The Mono
website says that it supports all of Linq to XML and other people on
various forums and sites that I'm reading seem to have this working fine
so I'm wondering what it is that I'm missing. Can anybody help?

Validate stored data against a form in django

Validate stored data against a form in django

Obviously when you save data through a form you can run validation through
it's clean method, but then if you wanted to re-validate that data every
time you view it can you just run the form's clean method again?
I was thinking the view would go along the lines of;
def detail(request, person_id=None):
"""
Renders an individual person
@param employer_id: The id of employer to view
@param request: HttpRequest
@return: HttpResponse
"""
person = get_object_or_404(People, pk=person_id)
validation_form = AddForm(instance=person)
is_valid = validate_person(validation_form)
return render_to_response(
'person/detail.html',
{
'is_valid': is_valid,
},
context_instance=RequestContext(request))
But what would be the 'proper' way of doing validate_person()?

Tuesday, 27 August 2013

MAIL FROM command from postfix to mdaemon caused 501 Domain must resolve, but not on putty

MAIL FROM command from postfix to mdaemon caused 501 Domain must resolve,
but not on putty

I have a strange problem with postfix. This first screenshot is captured
by tcpdump on postfix. This one gave me "501 Domain must resolve" error.
I tried to connect manually, and enter information as captured on tcpdump
on putty, but got different result. Using putty, server responds as 250,
Sender Ok
SMTP Server is MDaemon, and our mail server is Postfix
Any idea why it happened and how to solve it?
Thank you

I want to paint a image on the screen of a blackberry phone in puzzle layout using paint() method and also want to render car on that...

I want to paint a image on the screen of a blackberry phone in puzzle
layout using paint() method and also want to render car on that...

I want to paint a image on the screen of a blackberry phone in puzzle
layout using paint() method and also want to render car on that layout .it
is game called BLOCKED TRAFFIC . What should be the logic to move a car
???

jQuery text() in pure Javascript

jQuery text() in pure Javascript

jQuery text() is a good function for get text from an element because it
respects spaces and line breaks. How to replace it with cross-browser pure
javascript function?
Note: innertext and textcontent are no good solution because line breaks
and spaces (partially) are not consider.

Concept do-while-do-loop

Concept do-while-do-loop

I often need something like a do-while-do loop. In the moment I implement
this concept like this:
Instructions part 1 (for instance: read data)
while(Condition){
Instructions part 2 (save data)
Instructions part 1 (read next data)
}
I have to write part 1 twice, which is ugly. Is it possible to get rid of
the duplicate? I think of a concept like this:
do{
Instructions part 1
} while (Condition) do {
Instructions part 2
}

need help unexpected $end in php

need help unexpected $end in php

I have this error on my work
Parse error : syntax error, unexpected $end in /../messenger.php on line 304
i've checked my script a couple of times and i dont find any missing
semicolon or bracket.So if anyone can help please give me your advice.
Thanks before.
Here is my script
<?php
mysql_connect ("localhost","root","");
mysql_select_db ("aplydroidmessenger");
extract ($_REQUEST, EXTR_OVERWRITE);
if ($c=="r"){
$reg = " ";
$h = ereg_replace ("~", $reg, $h);
$n = ereg_replace ("~", $reg, $n);
if ($s == "user") {
$sql = "SELECT * FROMhe tbl_user where nick = '$k'";
$result = mysql_query ($sql);
$total = mysql_num_rows ($result);
if ($total == 0) {
$sql = "INSERT INTO tbl_user
(name,email,password,nick,status,cdate)";
$sql .= "VALUES ('$n','$e','$p','$k','offline',NOW())";
$result = mysql_query($sql) or die("gagal");
$status = 1;
$msgReg = "============================\n";
$msgReg .= " SELAMAT\n";
$msgReg .= "===========================\n";
$msgReg .= "Kamu Telah Terdaftar\n";
$msgReg .= "Nick anda adalah : $k \n";
echo $msgReg;
}
else {
echo "Nick anda telah terdaftar";
}
}
else if ($s == "room"){
$sql = "SELECT * FROM tbl_user where nick = '$k'";
$result = mysql_query($sql);
$total = mysql_num_rows($result);
if ($total == 0){
$sql = "INSERT INTO tbl_user
(name,email,password,nick,status,cdate)";
$sql .= "VALUES ('$n','$e','$p','$k','room',NOW())";
$result = mysql_query($sql) or die ("gagal");
$status = 1;
$msgReg = "SUKSES";
echo $msgReg;
}
else {
echo "Room is exist";
}
}
}
if ($c=="s"){
$sql = "SELECT * FROM tbl_user";
$sql .= "WHERE nick = '$k' AND password = '$p'";
$result = mysql_query($sql) or die ("3");
$row = mysql_num_rows($result);
if ($row > 0){
$sql = "UPDATE tbl_user set status = 'online'";
$sql .= "WHERE nick = '$k'";
$result = mysql_query($sql) or die ("2");
if ($result) {
echo "1";
}
}
else {
echo "2";
}
}
if ($c=="f"){
if ($z=="on"){
$sql = "SELECT * FROM tbl_user";
$sql .= "WHERE status='online' AND nick != '$k'";
$result = mysql_query($sql) or die ("gagal");
$spce = "_";
$con = "1";
$row = mysql_num_rows($result);
if (!$row == 0){
while ($data = mysql_fetch_array($result)){
$nama .= $data["nick"].$spce;
}
echo "$con$nama";
}
else {
echo "1";
}
}
else if ($z=="off"){
$sql = "SELECT * FROM tbl_user";
$sql .= "WHERE status='offline' AND nick != '$k'";
$result = mysql_query($sql) or die ("gagal");
$spce = "_";
$con = "0";
$row=mysql_num_rows($result);
if (!$row == 0){
while ($data = mysql_fetch_array($result)){
$nama .= $data["nick"].$spce;
}
echo "$con$nama";
}
else {
echo "0";
}
}
if ($c=="a"){
$spce = "_";
$con = "1";
$sqla = "SELECT * FROM tbl_user";
$sqla .= "WHERE nick = '$k'";
$reslt = mysql_query($sqla);
if (mysql_num_rows($reslt) > 0){
while ($data = mysql_fetch_array($reslt)){
$userid = (int) $data ["id"];
}
}
$sqlb = "SELECT * FROM tbl_room_user";
$sqlb .= "WHERE id_user = '$userid'";
$hasil = mysql_query($sqlb);
if (mysql_num_rows($hasil) > 0){
$i=1;
while ($data = mysql_fetch_array($hasil)){
$roomid[$i] = (int) $data ["id_room"];
$i++;
}
}
for ($i=1;$i <=count($roomid);$i++){
$sql_rm = "SELECT * FROM tbl_room";
$sql_rm .= "WHERE id = '$roomid[$i]'";
$resultq = mysql_query($sql_rm) or die ("gagal");
$row=mysql_num_rows($resultq);
if (!$row == 0){
while ($data = mysql_fetch_array($resultq)){
$nama .= $data["nama"].$spce;
}
}
}
echo "$con$nama";
}
if ($c=="o"){
$sql = "UPDATE tbl_user set status = 'offline'";
$sql .= "WHERE nick = '$k'";
$result = mysql_query($sql) or die ("2");
}
if ($c=="k"){
$spasi = " ";
$null = "";
$m = ereg_replace("~", $spasi, $m);
$t = ereg_replace("~", $null, $t);
if ($m != ""){
$sql .= "INSERT INTO tbl_msg(dari,ke,msg,status)";
$sql .= "VALUES ('$n','$t','$m','0')";
$result = mysql_query($sql);
}
}
if ($c=="p"){
$pisah = "_";
$batas = " : ";
if ($r == "person"){
$sql_tm = "SELECT * FROM tbl_msg";
$sql_tm .= "WHERE dari='$a'";
$sql_tm .= "AND ke='$n' AND status = '0'";
$result = mysql_query($sql_tm);
if (mysql_num_rows($result) > 0){
while ($data = mysql_fetch_array($result)){
$msg = $data["msg"];
$dari = $data["dari"];
echo "$dari$batas$msg$pisah";
}
}
$sql_rd = "UPDATE tbl_msg set status = 1";
$sql_rd .= "WHERE dari = '$a' AND ke = '$n'";
$result_rd = mysql_query($sql_rd);
}
else if ($r == "room"){
$sql_rm = "SELECT * FROM tbl_room";
$sql_rm .= "WHERE nama='$a'";
$result = mysql_query($sql_rm);
if (mysql_num_rows($result) > 0){
while ($data = mysql_fetch_array($result)){
$idroom = $data["id"];
}
}
$sql_rm = "SELECT * FROM tbl_room_user";
$sql_rm .= "WHERE id_room='$idroom'";
$result = mysql_query($sql_rm);
if (mysql_num_rows($result) > 0){
$i=1;
while ($data = mysql_fetch_array($result)){
$from[$i] = $data["id_user"];
$i++;
}
}
for ($i=1;$i <=count($from);$i++){
$sql_rm = "SELECT * FROM tbl_user";
$sql_rm .= "WHERE id='$from[$i]'";
$result = mysql_query($sql_rm);
if (mysql_num_rows($result) > 0){
while ($data = mysql_fetch_array($result)){
$name[$i] = $data["nick"];
}
}
}
for ($i=1;$i<=count($name);$i++){
$sql_tm = "SELECT * FROM tbl_msg";
$sql_tm .= "WHERE dari='$name[$i]'";
$sql_tm .= "AND ke= '$n' AND status = '0'";
$result = mysql_query($sql_tm);
if (mysql_num_rows($result) > 0){
while ($data = mysql_fetch_array($result)){
$msg = $data["msg"];
$dari = $data["dari"];
echo "$dari$batas$msg$pisah";
}
}
$sql_rd = "UPDATE tbl_msg set status = 1";
$sql_rd .= "WHERE dari = '$name[$i]' AND ke ='$n'";
$result_rd = mysql_query($sql_rd);
}
} }
?>

Java: Weird method ambiguity

Java: Weird method ambiguity

Consider the following code:
public class Converter {
public <K> MyContainer<K> pack(K key, Object[] values) {
return new MyContainer<>(key);
}
public MyContainer<IntWrapper> pack(int key, Object[] values) {
return new MyContainer<>(new IntWrapper(key));
}
public static final class MyContainer<T> {
public MyContainer(T object) { }
}
public static final class IntWrapper {
public IntWrapper(int i) { }
}
public static void main(String[] args) {
Converter converter = new Converter();
MyContainer<IntWrapper> test = converter.pack(1, new
String[]{"Test", "Test2"});
}
}
The above code compiles without problems. However, if one changes Object[]
to Object... in both pack signatures and new String[]{"Test", "Test2"} to
"Test", "Test2", the compiler complains about the call to converter.pack
being ambiguous.
Now, I can understand why it could be considered ambiguous (as int can be
autoboxed into an Integer, thus matching the conditions, or lack thereof,
of K). However, what I can't understand is why the ambiguity isn't there
if you're using Object[] instead of Object....
Can someone please explain this odd behavior?

Monday, 26 August 2013

NginX or rewrite the script with new programming language?

NginX or rewrite the script with new programming language?

Hi I have a website created using PHP, Apache, memcache. The traffic is
big and we have server high loads almost every night.
As the number of users grows, the traffic becomes bigger and bigger and we
would like to solve this issue.
we would like to hear the suggestions from the ppl who had experienced
this issue and how they were solved.
some introduced Nginx / Node.js and etc. If possible, we prefer a solution
that is faster to implement and good for the long run.
Thanks.

jquery validation of text field not firing ajax request for valid entry

jquery validation of text field not firing ajax request for valid entry

I have a text field(email) in my form which checks whether the entered
value is valid, if so then it will have to validate the same again my DB.
The problem is that when I type wrong its not displaying the error message
that I have configured under message, instead it chooses over the default
msg.
$("#myform").validate({
rules: {
email:{
required: true,
email: true,
type: "post",
remote:{
url:"myservlet?verifyEmail=checkEmail",
/* data: "verifyEmail=checkEmail", */
type: "post",
}
},
messagess:{
email:{
required: "Enter a valid email",
remote: "This user is already taken"
}
}
},
highlight: function(element){
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function(element){
element
.closest('.control-group').removeClass('error')/*
.addclass('error') */;
}
});
if(('#myform').validated())
('#myform').submit();
I tried to check the network traffic i dnt see any traffic due to this
request. The bootstrap class configured under highlight and success is
working fine. This is my first time using this plugin.

How can the temporary update directory be changed?

How can the temporary update directory be changed?

When a plugin, theme, or even WordPress itself are updated, it downloads
and saves the files (.zip, extracted files, etc.) to wp-content\upgrade.
This is not always desirable.
For example, I run a portable version of WordPress from a flash-drive, so
I don't want it using the flash-drive for temp files. I would prefer it to
put temporary files in the system's temporary directory.
I already changed the temporary (upload) directory in php.ini as so:
upload_tmp_dir = ${Temp}
This works for regular PHP scripts, and while I've seen a couple of pages
which seem to indicate that WordPress (3.0+) should use the default
(upload? download?) temporary directory, it is ignoring it and still
putting the temporary files in wp-content\upgrade.
How can this be changed?

Excel drop down values from a SQL Server source

Excel drop down values from a SQL Server source

I am trying to get a cell drop-down values in Excel from a SQL Server. I
don't want to use the method of putting all the data to another sheet and
the use data validation to control the drop down values. That always give
my a bunch of empty lines towards the end since I want to make sure I have
room for any addition in the DB.
Is there a way to retrieve the drop-down values directly from SQL Server?
Using a statement something like:
Select name from employees
Thanks for your help...

nginx + php fpm security issue?

nginx + php fpm security issue?

I am new user of nginx + php-pfm, but I am a little bit confused about
security.
For example I am running a few pools with different uid/gid as TCP
sockets. So theoritically it is possible that any local shell user can
connect to 127.0.0.1 9000 OR 9001 or any other FPM port and send php code
to execute with different uids? How to avoid that? (file sockets is not an
option)

Play framework input without label

Play framework input without label

I've just started with Play Framework and I'm looking to create input
field in scala template but without label and for some reason I'm unable
to get rid of the generated label element. Here is how my code looks like
:
@helper.inputText(form("name"), 'id -> "name", 'class ->
"ui-state-default", 'autocomplete -> "off", 'placeholder -> "Please write
name ...")
So I end up with this element along with my input (looking at browser
source code) :
<dt><label for="s2id_autogen2">name</label></dt>
Is there any way of removing it?

When the last part of expression will be returned

When the last part of expression will be returned

I have the following expression taken from jQuery native code:
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || []
I'm curios under which conditions the last part of the expression - [] -
will be assigned to the handlers variable? Here is my speculation:
1) This part is executed first ( jQuery._data( this, "events" ) || {} ).
If there are no attached events jQuery._data( this, "events" ) ===
undefined, then the empty object is returned.
2) Then this part {}[event.type] || [] is processed. If event.type is
undefined, then an array is returned and assigned to the handlers
variable. So it means that for the array to be returned it is enough that
event.type is undefined?
Am I right?

Sunday, 25 August 2013

google +1 button adds scroll bar to my site

google +1 button adds scroll bar to my site

I have had a google +1 button on my site for more then a year and it all
worked fine.
In the last couple of days this button started to create a horizontal
scroll bar on my site.
I know that beacase when I remove the button the scroll bar disappears.
Here is my site: www.kitchen-guide.co.il
Any suggestions what should I do?
Thanks!

Vector bundles on a smooth curve

Vector bundles on a smooth curve

Let $V$ be a vector bundle over smooth projective curve, then there is a
natural evaluation map $$ f: \operatorname{Hom}(\mathcal{O}, V) \otimes
\mathcal{O} \to V, $$ what is kernel and cokernel of this map?

Saturday, 24 August 2013

Rails - Query for has_many association

Rails - Query for has_many association

I have a User model that has_many tweets. In the User index action I want
to show all Users who have tweeted, but I also only want to show the
latest tweet for each User.
@user = User.where.....
Not getting anywhere with this.

Enumerating Registry Values in Go (Golang)

Enumerating Registry Values in Go (Golang)

I'm trying to enumerate over a list of values in the Windows registry
using Go, but I'm running into some trouble. I've tried two approaches:
using both the Go-provided syscall library to call into RegEnumValue, as
well as using a Windows API wrapper by lxn. In both cases, I'm having the
same issue. This is the code I'm using (which is currently using the win
library from lxn):
var root win.HKEY
rootpath, _ := syscall.UTF16PtrFromString("HARDWARE\\DEVICEMAP\\SERIALCOMM")
fmt.Println(win.RegOpenKeyEx(win.HKEY_LOCAL_MACHINE, rootpath, 0,
win.KEY_READ, &root))
var name_length uint32 = 72
var name *uint16
var key_type uint32
var lpData *byte
var lpDataLength uint32 = 72
var zero_uint uint32 = 0
fmt.Println(win.RegEnumValue(root, zero_uint, name, &name_length, nil,
&key_type, lpData, &lpDataLength))
win.RegCloseKey(root)
In this case, RegEnumValue always returns code 87, which MSDN's only
explanation is "The parameter is incorrect."
Does anyone have any ideas that can point me in the right direction for this?

Why are my Symfony/Doctrine2 entites different from my CI/D2 ones ? (Ultimately, What is the difference between Doctrine 2 and Doctrine 2...

Why are my Symfony/Doctrine2 entites different from my CI/D2 ones ?
(Ultimately, What is the difference between Doctrine 2 and Doctrine 2...

I know this seems like a very basic question but PLEASE before voting
down, read until the end.
This question came to my mind when using Codeigniter along with Doctrine 2.
I have noticed that, at least when using annotation, the synthax is
slightly different than when using Doctrine 2 with Symfony2 and I am
wondering why.
I'll provide an example:
This is a class in Symfony2 with a Many To One relation:
<?php
namespace Pondip\LakeBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* Lake
*
* @ORM\Table(name="pondip_lake")
* @ORM\Entity(repositoryClass="Pondip\LakeBundle\Entity\LakeRepository")
*/
class Lake
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var integer
* @Assert\Type(type="Pondip\LakeBundle\Entity\Venue")
*
* @ORM\ManyToOne(targetEntity="Pondip\LakeBundle\Entity\Venue")
* @ORM\JoinColumn(name="venue_id", referencedColumnName="id")
*/
private $venue;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* @var text
*
* @ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* @var integer
*
* @ORM\ManyToOne(targetEntity="Pondip\UserAccountBundle\Entity\User")
* @ORM\JoinColumn(name="created_by", referencedColumnName="id",
nullable=true)
*/
private $createdBy;
please pay attention to all the @ORM\ everywhere.
Now, when using this with codeigniter2/Doctrine2.3.0 I have Mapping errors
in my console. But, when following some tuts, I ended up removing all of
the ORM\ (and the corresponding use Doctrine\ORM\Mapping as ORM) and it
worked.
This work :
<?php
namespace Entity;
/**
* Friend Model
*
* @Entity
* @Table(name="friend")
* @author Miles Yohann Merran <hello_miles@hotmail.com>
*/
class Friend
{
/**
* @Id
* @Column(type="integer", nullable=false)
* @GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @Column(type="string", length=32, unique=true, nullable=false)
*/
protected $name;
/**
* @Column(type="text", nullable=false)
*/
protected $description;
/**
* @Column(type="string", length=64, nullable=false)
*/
protected $picture;
/**
* @Column(type="string", length=64, nullable=false)
*/
protected $genre;
/**
* @ManyToOne(targetEntity="User", inversedBy="friends")
* @JoinColumn(nullable=false)
*/
protected $user;
/**
* @var datetime $date
*
* @Column(name="date", type="datetime")
*/
protected $date;
When this doesn't work (pay attention at the ORM)
<?php
namespace Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Friend Model
*
* @Entity
* @Table(name="friend")
* @author Miles Yohann Merran <hello_miles@hotmail.com>
*/
class Friend
{
/**
* @Id
* @Column(type="integer", nullable=false)
* @GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @Column(type="string", length=32, unique=true, nullable=false)
*/
protected $name;
/**
* @Column(type="text", nullable=false)
*/
protected $description;
/**
* @Column(type="string", length=64, nullable=false)
*/
protected $picture;
/**
* @Column(type="string", length=64, nullable=false)
*/
protected $genre;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="friends")
* @ORM\JoinColumn(nullable=false)
*/
protected $user;
/**
* @var datetime $date
*
* @ORM\Column(name="date", type="datetime")
*/
protected $date;
Why ? What is the difference ?

Copy Paste from Clipboard to Excel

Copy Paste from Clipboard to Excel

I have perform the Copy paste from custom DataGrid to ExcelSheet.
In this DataGrid some CellValue contains the "\r\n" line breaks. How to
past this CellValue in single cell instead of next cell of Excel. Can you
please provide suggestion to achieve this.
Thanks in advance
Regards, Rajasekar

Error when checking result.getMeta().getCode() from Result

Error when checking result.getMeta().getCode() from Result

Keeping getting an error when trying to check the code from the meta data
from the results. Not sure why code is not working, here's a snippet of
what i'm doing. Everything up to this point works fine.
Result<VenuesSearchResult> result =
foursquareapi.venuesSearch(lat+","+lng, null, null, null, null, null,
null, null, null, null, null);
if (result.getMeta().getCode() == 200) {
Toast.makeText(getApplicationContext(), "phase 5",
Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(), "Error has occured",
Toast.LENGTH_SHORT).show();
}

ALT + SPACE to change language

ALT + SPACE to change language

Is it possible to make ALT and SPACE keys combination to change language
in windows? This combination is assigned by default to system menu.

how to pass data simultaneously to backbonejs and php on form submission?

how to pass data simultaneously to backbonejs and php on form submission?

For example: A user enters or submits names. These names are stored
locally using backbone.localStorage.js and displayed in #sidebar using
backbone.js. And, by using php, the most recently added name should be
displayed in #content. So, if user enters these two names, one after
another- foo and bar. Then in #sidebar(here the backbone does the job)
foo
bar
should be displayed and in #content (here php does the job) bar should be
displayed (as it is most recently added). when third name, boo is entered,
in #sidebar it will be
foo
bar
boo
And in #content boo will be displayed.
To achieve this I am using: backbone.js, backbone.localStorage.js, jquery.
And app.js contains model, collection and view for handling and displaying
data.
The js part works fine but not the php.
The index.php
<div id="myapp">
<div class="enter-data">
<form method="POST" action="index.php">
<input type="text" name="name" id="new-data" />
<input type="submit" value="Subscribe" name="submit" id="submit"/>
</form>
</div>
<div class="sidebar-data">
//here names are displayed which are stored locally using backbone
</div>
</div>
<div class="content">
<?php
function main() {
if(isset($_POST['name']) && !empty($_POST['name'])) {
$data =$_POST['name'];
echo $data;
}
}
main();
?>
</div>
event in app.js (view)
events: {
"click #submit": "submitClick",
},
submitClick: function(e){
if (!this.input.val()) return;
Todos.create({title: this.input.val()});
this.input.val('');
}
with the above code, data is passed to js, but not to php. Which means
names are displayed in #sidebar as shown in above example but the php part
is not working. #content is remained blank. I have also tried
events: {
"submit form": "submitForm",
},
submitForm: function(e){
if (!this.input.val()) return;
Todos.create({title: this.input.val()});
this.input.val('');
}
but same thing happens.
So, how can I pass data to php too and display the recently added name in
#content

Friday, 23 August 2013

php json_encode and decode multi-dimension array

php json_encode and decode multi-dimension array

I have a php array structure
Array
(
[car] => Array
(
[red] => 0.333
[orange] => 0.333
[blue] => 0.333
)
[truck] => Array
(
[white] => 0.333
[green] => 0.333
[blue] => 0.333
)
)
I have been using serialize to save the array to a text file, and
unserialize to get back the array form. Unfortunately, the serialized
array is getting very large, but mostly due to the float point (bug or by
design) conversion when serialized. For example, instead of 0.333, the
serialized process converts .333 into
.3333333333333333333333333333333333333333333333333. This made me want to
switch to json_encode to save the array. When compare serialize to
json_encode, the serialized file is 40MB in size vs 8MB size for
json_encode.
That is great, except when I try to json_decode the file, it is no longer
in the array form. I tried json_decode($array, true), but that does not
work either.
Any idea how to get json_encode to work for this example?
TIA
PS, my floating point number was generated by rounding off the decimals.
Another answer that I found on StackO suggested that instead of using
round($part/$sum, 3);, use sprintf('%.3f', $part/$sum); which turned the
floating point into a string. That alone cut the serialized file down from
40MB to 19MB, but it still much larger than the json_encode file size of
8MB.

How do I get a ListView to draw over its list items?

How do I get a ListView to draw over its list items?

I have extended ListView such that I can have a fast scroller. In the
onDraw method I draw a rectangle with lettering along the right edge of
the list, and if you are actively sliding your finger up and down I render
the current letter in the center of the view. The problem is the list
items render on top. Not idea. I am looking for the best way to render my
background, then my list items, then my foreground.

populating JSON to Listview

populating JSON to Listview

Trying to populate data into listview
I am using JSON Response from the server
Having the error
I have mentioned the classes



MainActivity.java
public class MainActivity extends ListActivity {
// url to make request
private static String url = "http://54.218.73.244:7002/";
// JSON Node names
private static final String TAG_CONTACTS = "restaurants";
private static final String TAG_ID = "restaurantID";
private static final String TAG_NAME = "restaurantNAME";
// contacts JSONArray
JSONArray contacts = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new
ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME }, new int[] {
R.id.name });
setListAdapter(adapter);
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!-- Name Label -->
<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold"
android:paddingTop="6dip"
android:paddingBottom="2dip" />
</LinearLayout>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(@android:id/list)
-->
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
single_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Name Label -->
<TextView android:id="@+id/name_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip"
android:textStyle="bold"
android:paddingTop="10dip"
android:paddingBottom="10dip"
android:layout_gravity="center"
android:textColor="#43bd00"/>
</LinearLayout>
Log::
08-23 17:08:14.940: E/JSON Parser(985): Error parsing data
org.json.JSONException: Value Cannot of type java.lang.String cannot be
converted to JSONObject
08-23 17:08:14.950: D/AndroidRuntime(985): Shutting down VM
08-23 17:08:14.950: W/dalvikvm(985): threadid=1: thread exiting with
uncaught exception (group=0x40015560)
08-23 17:08:14.980: E/AndroidRuntime(985): FATAL EXCEPTION: main
08-23 17:08:14.980: E/AndroidRuntime(985): java.lang.RuntimeException:
Unable to start activity
ComponentInfo{com.project.findmybuffet/com.project.findmybuffet.MainActivity}:
java.lang.NullPointerException
08-23 17:08:14.980: E/AndroidRuntime(985): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
08-23 17:08:14.980: E/AndroidRuntime(985): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-23 17:08:14.980: E/AndroidRuntime(985): at
android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-23 17:08:14.980: E/AndroidRuntime(985): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-23 17:08:14.980: E/AndroidRuntime(985): at
android.os.Handler.dispatchMessage(Handler.java:99)
08-23 17:08:14.980: E/AndroidRuntime(985): at
android.os.Looper.loop(Looper.java:123)
08-23 17:08:14.980: E/AndroidRuntime(985): at
android.app.ActivityThread.main(ActivityThread.java:3683)
08-23 17:08:14.980: E/AndroidRuntime(985): at
java.lang.reflect.Method.invokeNative(Native Method)
08-23 17:08:14.980: E/AndroidRuntime(985): at
java.lang.reflect.Method.invoke(Method.java:507)
08-23 17:08:14.980: E/AndroidRuntime(985): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-23 17:08:14.980: E/AndroidRuntime(985): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-23 17:08:14.980: E/AndroidRuntime(985): at
dalvik.system.NativeStart.main(Native Method)
08-23 17:08:14.980: E/AndroidRuntime(985): Caused by:
java.lang.NullPointerException
08-23 17:08:14.980: E/AndroidRuntime(985): at
com.project.findmybuffet.MainActivity.onCreate(MainActivity.java:53)
08-23 17:08:14.980: E/AndroidRuntime(985): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-23 17:08:14.980: E/AndroidRuntime(985): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-23 17:08:14.980: E/AndroidRuntime(985): ... 11 more
08-23 17:13:15.060: I/Process(985): Sending signal. PID: 985 SIG: 9
08-23 17:20:27.350: E/JSON Parser(1018): Error parsing data
org.json.JSONException: Value Cannot of type java.lang.String cannot be
converted to JSONObject
08-23 17:20:27.362: D/AndroidRuntime(1018): Shutting down VM
08-23 17:20:27.362: W/dalvikvm(1018): threadid=1: thread exiting with
uncaught exception (group=0x40015560)
08-23 17:20:27.390: E/AndroidRuntime(1018): FATAL EXCEPTION: main
08-23 17:20:27.390: E/AndroidRuntime(1018): java.lang.RuntimeException:
Unable to start activity
ComponentInfo{com.project.findmybuffet/com.project.findmybuffet.MainActivity}:
java.lang.NullPointerException
08-23 17:20:27.390: E/AndroidRuntime(1018): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
08-23 17:20:27.390: E/AndroidRuntime(1018): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-23 17:20:27.390: E/AndroidRuntime(1018): at
android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-23 17:20:27.390: E/AndroidRuntime(1018): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-23 17:20:27.390: E/AndroidRuntime(1018): at
android.os.Handler.dispatchMessage(Handler.java:99)
08-23 17:20:27.390: E/AndroidRuntime(1018): at
android.os.Looper.loop(Looper.java:123)
08-23 17:20:27.390: E/AndroidRuntime(1018): at
android.app.ActivityThread.main(ActivityThread.java:3683)
08-23 17:20:27.390: E/AndroidRuntime(1018): at
java.lang.reflect.Method.invokeNative(Native Method)
08-23 17:20:27.390: E/AndroidRuntime(1018): at
java.lang.reflect.Method.invoke(Method.java:507)
08-23 17:20:27.390: E/AndroidRuntime(1018): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-23 17:20:27.390: E/AndroidRuntime(1018): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-23 17:20:27.390: E/AndroidRuntime(1018): at
dalvik.system.NativeStart.main(Native Method)
08-23 17:20:27.390: E/AndroidRuntime(1018): Caused by:
java.lang.NullPointerException
08-23 17:20:27.390: E/AndroidRuntime(1018): at
com.project.findmybuffet.MainActivity.onCreate(MainActivity.java:53)
08-23 17:20:27.390: E/AndroidRuntime(1018): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-23 17:20:27.390: E/AndroidRuntime(1018): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-23 17:20:27.390: E/AndroidRuntime(1018): ... 11 more
Any ideas Thanks,

$\sin x+\dfrac{\sin 2x}{2}+\dfrac{\sin 3x}{3}+\cdots$ is positive

$\sin x+\dfrac{\sin 2x}{2}+\dfrac{\sin 3x}{3}+\cdots$ is positive

Let $0<x<\pi$. $n$ be a natural number.
How to prove
$$\sin x+\dfrac{\sin 2x}{2}+\dfrac{\sin 3x}{3}+\ldots+ \dfrac{\sin nx}{n}>0$$

Thursday, 22 August 2013

why does my LAMP stack show my image when I navigate to it w/ a URL but not when I load it w/jQuery and PHP

why does my LAMP stack show my image when I navigate to it w/ a URL but
not when I load it w/jQuery and PHP

pI have a php file at codepath/renderer/renderImage.php/code that builds
and returns a PNG image to the browser. When I navigate to that URL with
my browser, it dumps the correct image on the screen. But when I try to
load that image into a DIV with jQuery using the code below from
path/index.html .../p precodelt;!DOCTYPE htmlgt; lt;htmlgt; lt;headgt;
lt;meta charset='utf-8'/gt; .... lt;script
src=https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.jsgt;lt;/scriptgt;
lt;script src=../jquery.colorbox.jsgt;lt;/scriptgt; lt;scriptgt;
$.colorbox({width:30%, inline:true, href:#inline_content, onClosed:
function() { $(#myPic).load('./renderer/renderPicture.php');
$('#myPic').css('display','inline'); }, }); /code/pre pit fills the DIV
with strange symbols.../p pimg src=http://i.stack.imgur.com/xHL9H.png
alt=enter image description here/p pHere is a picture of the directory
structure: /p pimg src=http://i.stack.imgur.com/yIRe5.png alt=enter image
description here/p pWhy is the browser interpreting the picture
differently on these two pages? What might cause the discrepancy?/p

giving credit to google charts ina system development project

giving credit to google charts ina system development project

I used google charts for my coursework,to display reports.and i think i am
supposed to give credit for the code for them,given that they have a
creative commons license. where in the report should i do that?
and how should i show it in the citations?I am using the harvard
referncing system
https://google-developers.appspot.com/chart/interactive/docs/quick_start
I know this is kind of a weird question,but still its kind of an emergency
for me.so id appreciate a fast reply :)

why the "open" command runs under the home directory?

why the "open" command runs under the home directory?

Under Mac OSX (Mountain Lion), I have a shell script "a":
#!/bin/bash
open -a Terminal b
which run another shell script "b" using Terminal:
echo `pwd`
Something interesting is that, no matter where my running scripts are
located, the pwd command in "b" always returns the home directory.
Questions:
Why does this happen?
How to set the running environment to be the working instead home
directory (ie, return the working directory when arriving at pwd)

Makefiles. multiple rules match a target

Makefiles. multiple rules match a target

I am using the gnu make and I have the same problem reported in when
multiple pattern rules match a target. Basically two rules, a generic one,
and a more specific one, match the same target and they are both
executed!!. I would like the more specific one to be executed ONLY. The
answer given on the above thread is basically to upgrade to gnu make 3.82.
I have version 3.81 and it is the one found very commonly with many Linux
distributions.
Is there a fix for this problem that would work with gnu make version 3.81?
Thank you in advance.

Gradle distributions repository in artifactory outdated?

Gradle distributions repository in artifactory outdated?

I set up my virtual repository in artifactory to cache gradle distribution
libraries by adding a remote repository called 'gradle-distributions' as
described here. This remote repository points to this repository
As it looks like, the stated remote repository is not up to date any more
because the latest version offered is gradle-1.0-milestone-8-bin.zip.
Is there a workaround for this issue, like pointing to a different remote
repository or whatsoever?
Thanks in advance.

Jquery form won't validate to success

Jquery form won't validate to success

I'm having problem to "get pass" the validation of my form validator, it
stops and won't start to process. When it should be processed it gives me
"You need to fill out: "
What could be wrong?
Fidde her: http://jsfiddle.net/SBYQ5/
Jquery:
$("form").submit(function (e) {
e.preventDefault(); // This will prevent the form submission
var response = "";
var missing = "";
$('#submit-holder').find('input').each(function(){
if ($(this).val() == '') {
missing += $('label[for="' + this.id + '"]').html() + " | ";
empty_fields = true;
missing_fields = true;
}
else if ($(this).val() != '') {
empty_fields = false;
$('.alert').hide();
}
});
response += "* <strong>You need to fill out:</strong> " + missing;
if(!$('#user_terms').is(':checked'))
{
response += "<br>* You need to accept the terms and conditions to
continue";
}
var email = $('[name="txtEmail"]').val();
if(IsEmail(email)==false){
valid_email = false;
response += "<br><strong>* The e-mail address you've entered is
invalid</strong>";
}
response_message(response);
if(!missing_fields && valid_email !== false &&
$('#user_terms').is(":checked")) {
$('.alert').hide()
}
});
// Functions:
function IsEmail(email) {
var regex =
/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!regex.test(email)) {
return false;
}else{
return true;
}
}
function response_message(response) {
$('.alert').addClass('alert-danger');
$('.alert').fadeIn();
$('.error_message').html(response);
}

handing dataset array as dataset in matlab like as other programs(spss,r,stata)

handing dataset array as dataset in matlab like as other
programs(spss,r,stata)

i have a table that has 80 variables, 512 observations
and all values are numeric
i want to factor analysis with my table(class:dataset) as dataset.
still now, i am using this expression to do that
factoran(double(table),m)
I want to use an expression with datasetfun like this for conserving table
information.
datasetfun(@(x) factoran(x,m), table, 'datasetoutput', true)
but it is not working.
Error using factoran (line 133)
X must have more than one row (observation) and more than one column
(variable).
Error in @(x)factoran(x,3)
Error in dataset/datasetfun (line 101)
how to do?

Wednesday, 21 August 2013

Differentiable and Continuous functions on [0.1]

Differentiable and Continuous functions on [0.1]

I've been stuck on this one for a while. Comes from an analysis qual
question.
Let f be a function that is continuous on $\left[0,1\right]$ and
differentiable on $(0,1)$. Show that if $f(0)=0$ and $|f'(x)| \leq |f(x)|$
for all $x \in (0,1)$, then $f(x)=0$ for all $x \in \left[0,1\right]$.
What I've tried doing so far is see if there was anything I could do with
MVT. I didn't really see anything to do with definitions either..to which
I have a feeling I'll be playing around with them. Drawing a picture was a
little difficult with these conditions as well
Any hints/suggestions?

Multicast after service starts after boot in Android

Multicast after service starts after boot in Android

I am using Android 4.2 on an OMAP4460 processor from TI. My goal is this,
start a service right after boot that listens for SSDP queries on a
multicast socket. I can do this but when I go to create the
MulticastSocket the I get an exception. The exception is coming from the
underlying datagramSocket. Here is some code snippets:
<receiver
android:name="com.example.reciever.StartServicesAtBootReceiver"
android:enabled="true" android:exported="false"
android:label="StartServicesAtBootRemoteReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
my onRecieve() looks like this:
public void onReceive(Context context, Intent intent) {
Intent ServiceIntent = new Intent(context,
myService.class);
ComponentName serviceStarted = context
.startService(ServiceIntent);
if (serviceStarted != null)
}
And finally, the service snippet:
public int onStartCommand(Intent intent, int flags, int startId) {
try {
if (null == ssdpServer) {
ssdpServer = new UDPListenThread();
ssdpServer.start();
}
} catch (Exception e) {
e.printStackTrace();
}
public class UDPListenThread extends Thread {
protected MulticastSocket socket = null;
public UDPListenThread() throws IOException {
this("UDPListenThread");
}
public UDPListenThread(String name) throws IOException {
super(name);
}
@Override
public void run() {
Socket mySocket = new Socket();
socket = new MulticastSocket(SSDP_PORT);
// socket.setLoopbackMode(false);
socket.joinGroup(InetAddress.getByName(SSDP_ADDRESS));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
etc.
Note the Socket get allocated ok (its not used here so not sure if it is
valid or not). Also,if I try:
ConnectivityManager cm = (ConnectivityManager) getBaseContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = cm.getActiveNetworkInfo();
from the service or the reciever. activeNetwork comes back as null. Even
if I wait for activeNetwork (from the service) like this:
NetworkInfo activeNetwork = null;
while (null == activeNetwork) {
ConnectivityManager cm = (ConnectivityManager) getBaseContext()
.getApplicationContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
activeNetwork = cm.getActiveNetworkInfo();
Log.d(this.getClass().getSimpleName(), "activeNetwork "
+ activeNetwork);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
it will remain null even after I am able to pull up the browser and search
from the UI.

possibility on xss via iframe

possibility on xss via iframe

Say you have a website where you can inject iframes due to non-sanitized
input. Let's name this site the following:
http://www.vulnerable.com
Now we have a hosted page on:
http://www.page.com/page.html
`page.html` contains javascript code used to make an alert box.
Now is it possible to somehow break out of the iframe injected into
http://www.vulnerable.com and launch the javascript code on
http://www.vulnerable.com instead of it just being launched from
http://www.page.com? The typical iframe code in this case would be:
<iframe src="http://www.page.com/page.html" width="1" height="1"></iframe>
Thanks to anyone who can help.

How to animate elements move with css3 transitions after hiding some element

How to animate elements move with css3 transitions after hiding some element

Is it possible to animate elements move with css3 transitions after hiding
some element?
I found some kind of solution here (see "It works for grids, too"
section):
http://blog.stevensanderson.com/2013/03/15/animating-lists-with-css-3-transitions/
However my case is more like this: http://jsfiddle.net/CUzNx/5/
<div class="container">
<div id="item1" class="item">Test1</div>
<div id="item2" class="item">Test2</div>
<div id="item3" class="item">Test3</div>
<div id="item4" class="item">Test4</div>
<div id="item5" class="item">Test5</div>
<div id="item6" class="item">Test6</div>
<div id="item7" class="item">Test7</div>
</div>
<div style="clear:both">
<button onclick="$('#item1').fadeOut();">
Hide first
</button>
<button onclick="$('#item1').fadeIn();">
Show first
</button>
</div>
I have floating div elements and after some element is hidden, it would be
nice if other elements were animated. Is it possible?

make js loop unlimited

make js loop unlimited

I got the following script
<script type="text/javascript">
function UpdateCost() {
var sum = 0;
var gn, elem;
for (i = 0; i < 5; i++) {
gn = 'game' + i;
elem = document.getElementById(gn);
if (elem.checked == true) {
sum += Number(elem.value);
}
}
document.getElementById('totalcost').value = sum.toFixed(2);
}
</script>
<input type="checkbox" id='game0' value="10" onclick="UpdateCost()">Game
1 ( 9.99)<br>
<input type="checkbox" id='game1' value="10" onclick="UpdateCost()">Game 2
(19.99)<br>
<input type="checkbox" id='game2' value="10" onclick="UpdateCost()">Game 3
(27.50)<br>
<input type="checkbox" id='game3' value="10" onclick="UpdateCost()">Game 4
(45.65)<br>
<input type="checkbox" id='game4' value="10" onclick="UpdateCost()">Game 5
(87.20)<br>
<input type="text" id="totalcost">
Now when i add checkboxes it is no longer working. the same happens when i
delete checkboxes.
This has something to do with(I think):
for (i=0; i<5; i++)
How can i change this so that i can have only 1 checkbox or 1000 so
basically any amount i want to create.

Check if image has been loaded

Check if image has been loaded

Hello i have this code:
BitmapImage image = new BitmapImage(new Uri(contact.PreviewPhoto,
UriKind.Relative));
a.photo.Source = image;
contact.PreviewPhoto="https://files.test.lv/public/photos/h66/38B83D35-15B5-4872-8CE5-F3E50001E921.jpg";
How can i determine if image has been loaded?
Because sometimes internet connection can get lost, or the link is blank,
how to replace it in that case?

Tuesday, 20 August 2013

Why is it considered bad practice to call a method from within a constructor?

Why is it considered bad practice to call a method from within a constructor?

In Java, why is it considered bad practice to call a method from within a
constructor? Is it especially bad if the method is computationally heavy?

Not able to detect referring url on redirection

Not able to detect referring url on redirection

I have a third party url like
http://affiliates.tyroodr.com/ad/175291/CD16284/&lnkurl=http%3A//www.flipkart.com/%3Faffid%3Dtyroo%26cmpid%3Daffiliate_promo_tyroo%3Faffid%3Dtyroo%26cmpid%3Daffiliate_promo_tyroo&subid1=168&subid2=f39ce6-c5c9-4280_770460
It gets redirected to site :
http://www.flipkart.com/?affid=tyroo
I have a button on my site. When a user clicks the button the a new tab is
opened and user lands on the later url by getting redirected from former
url.
Now while landing I check for document.referrer but it returns null.
shouldn't it return the former url.