Monday, 30 September 2013

No internet on VIrtual Machines and external (physical) network is unreachable from VM's

No internet on VIrtual Machines and external (physical) network is
unreachable from VM's

I have installed openstack (packstack) on centos 6.4 with neutron. The
openstack is installed on single virtual machine using vmware.
First i have created external network using following command
quantum net-create public --router:external=True
Then i added my external network subnet (ip pool not used in external
network)
Then i created router
Then i set my router gateway to external network
I created security group to allow ssh and icmp.
On second step i created private network with dhcp enabled
Then created router interface and attach it to my private network
On third step i launched the instance with private network
On fourth step i generated floating ip of external network and associates
it to instance
Problem Statement:
Virtual machines are getting IP's (private network) from dhcp and
communicating with each other but there is No internet on VM's
VM's cannot ping any external network device.
I am using Centos 6.4. Ip route shows
192.168.186.0/24 dev eth1 proto kernel scope link src 192.168.186.166
metric 1
192.168.122.0/24 dev virbr0 proto kernel scope link src 192.168.122.1
10.16.48.0/22 dev br-ex proto kernel scope link src 10.16.51.208
169.254.0.0/16 dev eth0 scope link metric 1002
169.254.0.0/16 dev br-ex scope link metric 1017
default via 10.16.48.1 dev br-ex
Where 10.16.48.0/22 is my external network on eth0 (for internet)
10.16.186.0/24 is my anoother interface on eth1
quantum agent-list shows ----+-------+----------------+
| id | agent_type | host | alive | admin_state_up |
+--------------------------------------+--------------------+-----------------------+-------+----------------+
| 4c709a4c-bf0c-4e03-a0f5-2d938fee7ae1 | L3 agent | localhost.localdomain
| :-) | True |
| 960a7806-dc4d-4ab1-99b0-a79dbc31600f | Open vSwitch agent |
localhost.localdomain | :-) | True |
| d9f545e2-4a6c-43f4-8037-b807cbe27fc5 | DHCP agent |
localhost.localdomain | :-) | True |
+--------------------------------------+--------------------+-----------------------+-------+----------------+

No wifi Ubuntu 12.04 Toshiba satellite P775-S7100

No wifi Ubuntu 12.04 Toshiba satellite P775-S7100

Does anyone know how to get WiFi working on my Toshiba satellite P775-S7100?
My Ethernet works fine, just no WiFi, which works fine on my windows
partition.

is vertex shader needed with compatibility context

is vertex shader needed with compatibility context

If i use opengl 3.2+ with compatibility context and have a fragment
shader, is it necessary to have a vertex shader? I would like to know if
per vertex lighting calculation and other per vertex calculations can be
done by the fixed function pipeline and i can just use the fragment
shader.
Also what implications would this have for per-vertex attribute binding
locations?
thanks

Best way to define Constants in Objective-C

Best way to define Constants in Objective-C

I am defining constants with proper naming convention in objective-C but
after having some search on internet, I found three different naming
conventions for defining the constants. Those of given below.
NSString *const kModel_userID;
NSString *const k_model_user_id;
NSString *const kUserId;
Please check these and help me out which is the best way convention for
constants in objective-C. Please give me valid reason if you like any
convention. Also If you have any other convention please share that too.
Thanks

Sunday, 29 September 2013

Best way of obtaining a key when a value is known in a map

Best way of obtaining a key when a value is known in a map

Suppose I have a map as such
std::map<std::string,in> mp;
mp["KeyA"] = 1;
mp["KeyB"] = 2;
mp["KeyD"] = 3;
mp["KeyF"] = 4;
Now I need to obtain the key when I have a value known for instance if I
have 1 I want to obtain KeyA. My only thought is that I will need to
iterate through the whole map and once I find a value then return the key
as such. For example the psudocode explains my approach.
for(std::map<std::string,in>::iterator it = mp.begin();i<mp.end;++i)
{
if(it->second == somevalue)
{
return it->first;
}
}
I wanted to know if there was a quicker or a better way to accomplish this

Set TimeZone on Windows Azure Virtual Machines(IaaS)

Set TimeZone on Windows Azure Virtual Machines(IaaS)

We are planning to host our web application Windows Azure Virtual
Machines(IaaS). The application was developed to work in Central European
time zone(CET). Will there be any problem if we change the time zone on
Azure VMs from UTC to CET?
For example if there is any auto-disaster-recovery / restart / any other
maintenance operation on any virtual machine, will we have to explicitly
log-in and set the time-zone as per our preference or will time-zone
setting be preserved ?
Changing time-zone is not recommended for Web Roles and Worker
roles(Platform as a Service) as per this article "Manage TimeZone for
Applications on Windows Azure" as it can introduce instability. Can there
be a similar issue with multiple Azure virtual machines in the same
availability set?
Eventually we will upgrade application to use TimeZone API but would like
to change time-zone on virtual machines to quickly move our application to
Azure.

.htaccess rewrite with a default language specified

.htaccess rewrite with a default language specified

I'm trying to make an .htaccess rewrite on the webpage.
Only these two language are available [en, it] and [en] is the default one.
Here's a list of examples to be more clear and detailed:
http://website.com -> http://website.com/en
http://website.com/en -> http://website.com/en
http://website.com/it -> http://website.com/it
http://website.com/de -> http://website.com/en
Is it possible to do?

java.util.InputMismatchException in java

java.util.InputMismatchException in java

Referring to this line of code
marks.add(new StudentMarks(scan.next(), scan.next(), scan.nextDouble(),
scan.nextDouble(), scan.nextDouble(), scan.nextDouble()));
I'm not sure how to fix it, it is while looping and reading from a text
file with 2 strings then 4 doubles separated by commas, and there is 10
lines to loop through
any help would be much appreciated.

Saturday, 28 September 2013

Ruby SimpleCov missing one return line

Ruby SimpleCov missing one return line

This is my class which returns the multiplication of parameters
class NetAssetValue
def calculate_net_asset_value(number_of_shares, price)
number_of_shares * price
end
end
And this is my Test
require 'net_asset_value'
require 'test/unit'
class NetAssetValueTest < Test::Unit::TestCase
def setup
@asset = NetAssetValue.new
end
def test_calculate_net_asset_value_for_a_symbol
assert_equal(100, @asset.calculate_net_asset_value(20,5))
end
end
I am using SimpleCov 0.7.1. The coverage report says the one line in the
method is not covered though it is being covered.
It says the coverage is 66.67% and the line
number_of_shares * price
is not covered But when I debug in RubyMine and place a breakpoint on that
line it is being hit.
Need Help on this. Thank you.

Specifying query format in Entity Framework with System.Data.SQLite

Specifying query format in Entity Framework with System.Data.SQLite

I have an Entity Framwework 4.0 Model running against an SQLite database
to which I connect via System.Data.SQLite. I have one field in the
database which is typed "Date", and formatted as yyyy-MM-dd. (As we know,
SQLite has no internal Date or DateTime type).
The Entity Framework wizard happily translated that Date type to DateTime.
When running queries against this date field, I was surprised to find out
no results came.
Suppose a table "MyTable":
Create Table MyTable
(
Id Integer Not Null Primary Key,
ADate Date Not Null
);
With System.Data.SQLite and LINQ:
var date = new DateTime(2013, 1, 1);
context.MyTables.AddObject(new MyTable { Id = 0, ADate = date });
context.SaveChanges();
context.MyTables.Where(r => r.ADate == date).Count; // -> returns 0
Looking further with ToTraceQuery, I found out that the query became:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[ADate] AS [ADate]
FROM [TestDate] AS [Extent1]
WHERE [Extent1].[ADate] = @p__linq__0
With testing, I discovered that the mapped variable p__linq__0 was
transformed to a fixed format of 'yyyy-MM-dd hh:mm:ss', so that asking for
DateTime(2013,1,1) meant the query was looking for '2013-01-01 00:00:00'
when all that was to be found was '2013-01-01'.
If the folks who make 'System.Data.SQLite' had been nice about this,
they'd have used the built in SQLite functions and done the comparison
like:
WHERE datetime([Extent1].[ADate]) = datetime(@p__linq__0)
or
WHERE date([Extent1].[ADate]) = date(@p__linq__0)
for just the date type. And indeed in System.Data.SQLite's
SqlGenerator.cs, we find this formatting for all DateTime types:
((System.DateTime)e.Value).ToString("yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture), false /* IsUnicode */)
All this to say, is there a way to specify the format for this where
clause in this context?
Notes: SQLite is what I'm stuck with, and the recorded format of
'yyyy-MM-dd' cannot be changed as other software relies on it.

Cannot find any files

Cannot find any files

I'm just starting out with C. In my program the user enters a file name
and then I check if the file exists.
Here's the code so far:
printf("Enter the file name:\n");
char filename[50];
fgets(filename, 50, stdin);
printf("You have entered %s\n", filename);
if( access(filename, F_OK ) == -1 )
{
printf("File not found/access denied.\n");
}
In the same directory as the program itself I got a file named "steps".
However whenever I enter steps or ./steps or even ~/steps I get the file
not found error message.
What's the issue here?
By the way I'm on Linux (Ubuntu). Also, I know for certain that I have
access to the file - so it's not a matter of permissions.

How to integrate Facebook Login with your website

How to integrate Facebook Login with your website

I want to provide the option to login through facebook on my website where
the user can go and login through facebook itself instead of registering
himself on my website and then logging in?

Friday, 27 September 2013

How do I iterate through this sqlalchemy query?

How do I iterate through this sqlalchemy query?

Relative newbie to python and even newer to sqlalchemy. I have the following:
Without a subquery, when I join 2 tables without a subquery each row
returned is essentially 2 objects:
query = DBSession.query(Table1,Table2).outerjoin(Table2,Table1.id==Table2.id)
for row in query:
# returns (<myproject.models.Table1 object at
0x3ad2e50>,<myproject.models.Table2 object at 0x3ad2e50>)
With a subquery, the behavior changes: subquery =
DBSession.query(Table1).order_by(Table1.d.desc()).subquery() query =
DBSession.query(subquery,Table2).outerjoin(Table2,subquery.c.id==Table2.id).group_by(subquery.c.id)
for row in query:
# hoping for 2 objects (<myproject.models.Table1 object at
0x3ad2e50>,<myproject.models.Table2 object at 0x3ad2e50>)
# receiving (1,'Dave Thomas',10001,<myproject.models.Table1 object at
0x3ad2e50>)
How can I get 2 objects for my subquery above? The columns of Table1 may
change someday and thus I don't know what position will be at in the
tuple.
thanks!

Google Play: Does Beta Tester See Alpha Updates?

Google Play: Does Beta Tester See Alpha Updates?

I know how the process works for Alpha testing an app in Google Play and
here is my scenario:
Alpha builds are linked to community A. Beta builds are linked to
community B.
A person (P) happens to be in both groups.
If I release alpha build one today, a build build tomorrow, and another
alpha build the next day, will person P see the latest alpha build, or
will they be stuck with the latest beta?

JsonConvert unexpected behavior when serialising Dictionary

JsonConvert unexpected behavior when serialising Dictionary

Hell all! I have a Dictionary<string,Dictionary<CustomClass,string>> that
i want to serialise. The result I expect is something like:
{
"key1":{
{
"CustomClassProperty1":"val1",
"CustomClassProperty2":"val2",
"CustomClassProperty3":"val3"
}:"Final STR",
{
"CustomClassProperty1":"val10",
"CustomClassProperty2":"val2",
"CustomClassProperty3":"val35"
}:"Final STR4",
{
"CustomClassProperty1":"val100",
"CustomClassProperty2":"val25",
"CustomClassProperty3":"val300"
}:"Final STR8"
},
"key2":{
{
"CustomClassProperty1":"val4",
"CustomClassProperty2":"val5",
"CustomClassProperty3":"val6"
}:"Final STR 2"
},
"key3":{
{
"CustomClassProperty1":"val1",
"CustomClassProperty2":"val7",
"CustomClassProperty3":"val5"
}:"Final STR 3",
{
"CustomClassProperty1":"val10",
"CustomClassProperty2":"val2",
"CustomClassProperty3":"val35"
}:"Final STR0",
{
"CustomClassProperty1":"val100",
"CustomClassProperty2":"val25",
"CustomClassProperty3":"val300"
}:"Final STR10"
}
}
But instead i'm getting
{
"key1":{
"MyProjectNamespace.CustomClass":"Final STR",
"MyProjectNamespace.CustomClass":"Final STR4"
},
"key2":{
"MyProjectNamespace.CustomClass":"Final STR 2"
},
"key3":{
"MyProjectNamespace.CustomClass":"Final STR 3"
}
}
Can anyone tell me how to make it right? I dont want the
"namespace.classname" but the properties... I`m using Newtonsoft.Json
btw... tks a lot!

jQuery add class to current li and remove prev li

jQuery add class to current li and remove prev li

I found this jQuery add class to current li and remove prev li when click
inside li a, but it doesn't work for me. The situation is that the code
<ul>
<li class="current"><a href="#">menu item</a></li>
<li><a href="#aba">menu item</a></li>
<li><a href="#abb">menu item</a></li>
<li><a href="#abc">menu item</a></li>
<li><a href="#abd">menu item</a></li>
</ul>
is in a header.jsp file. Other jsp pages include this header.jsp. After I
added the jQuery as the link said, the class is added temporarily, and
then it is like refreshed and the page goes back to its initial state
which is the first li has the class current. Any idea?

Is this a correct way to use polymorphism

Is this a correct way to use polymorphism

I have a couple of classes in my system
//this was not made an Interface for some WCF reasons
public abstract class BaseTransmission
{
protected internal abstract string Transmit();
//other common properties go here
}
And a few child classes like
public class EmailTransmission : BaseTransmission
{
//This property is added separately by each child class
public EmailMetadata Metadata { get; set; }
protected internal override string Transmit()
{
//verify email address or throw
if (!Metadata.VerifyMetadata())
{
throw new Exception();
}
}
}
Elsewhere, I have created a method with signature
Transmit(BaseTransmission transmission). I am calling this method from
another part of my code like this:
TransService svc = new TransService();
EmailTransmission emailTrans = new EmailTransmission(); // this inherits
from BaseTransmission
svc.Transmit(emailTrans);
This solves my purpose. But usually when I see examples of polymorphism, I
always see that the reference type is base class type and it points to an
instance of child class type. So usually in typical examples of
polymorphism
EmailTransmission emailTrans = new EmailTransmission();
will usually be
BaseTransmission emailTrans = new EmailTransmission();
I cannot do this because EmailTransmission EmailMetadata is different from
lets say FaxMetadata. So if I declare the reference to be of
BaseTranmission type and point it to an instance of EmailTranmission type,
I lose access to the EmailMetadata property of the EmailTransmission.
I want to know whether what I am doing above is a misuse of polymorphism
and whether it 'breaks' polymorphism in some way. And if it is abusing
polymorphism, whats the right way to do this.

How to get data from two databases via FastReport

How to get data from two databases via FastReport

I have created a report using FastReport Designer (Delphi 2010). I have
one TfrxIBXQuery (Query1) connected with main database -
Base1(frxIBXComponents.DefaultDatabase:=Base1). It works fine, I can get
data using Query1+MasterData band. The problem arises when I'm trying to
get data from another database in the same report. In Designer I drop new
frxIBXDatabase (Base2), set the necessary properties. Add new TfrxIBXQuery
(Query2) and connect it with Base2. But I can't get any data from Query2
becouse it does not see Base2.
Could you give me some advice on how to solve this problem?

mysql result not displaying based on my query

mysql result not displaying based on my query

I have a table called add_project. Here you can view the table structure
of add_project
And the another table called assign_project Here you can view the table
structure of assign_project
Now the table add_project : Here on this table admin add the new projects.
The admin user_id is 1 so it is all common. project_status_id is the
completation of that project(0=new,1=working,3=completed).
Now the table assign_project : Here on this table the admin assigns the
project to different users.
Now what i want id to find is how many completed projects each user has
done. As you can see on the assign_table project_id(1,4)is completed by
the user_id=5.
So my query is how do i get that value.
Below is the query i have written
Select * FROM asign_project, add_project
WHERE asign_project.project_id = add_project.project_id
AND project_status_id='3'
AND user_id='5'
But it is showing
#1052 - Column 'user_id' in where clause is ambiguous
Waiting for your reply.

Thursday, 26 September 2013

CQL- Combining two fields in SELECT statement

CQL- Combining two fields in SELECT statement

In my cassandra (columnfamily)table I have a field "message1" and a field
"message2". I would like to select all records where message1 + space +
message2 is a certain value.
How can I concat or merge two fields(message1+message) into one in
select statement as in mysql
select message1 + ' ' + message2 as WholeMessage from MessageTable
where message1 + ' ' + message2 like '%MyWholeMessageString%'

Wednesday, 25 September 2013

How to make a redirect with .htaccess?

How to make a redirect with .htaccess?

All that i want to know is it possible to do with .htaccess some tricks
(redirectings)
site.org/member/$var > site.org/member/?id=$var like this.
The point is just add the ?id (string constant) before $var.
It's gonna be something like
RewriteEngine On
RewriteRule (or RewriteMatch)... ...
Cheers.

Thursday, 19 September 2013

EF Inserting/Updating navigational properties vs assigning Id's performance?

EF Inserting/Updating navigational properties vs assigning Id's performance?

Let's assume we have a model/database tables like below (not well laid out
but fits my question). Let's also assume one movie has always only one
director and one producer.
Genre
Id
Name
SubGenre
Id
Name
GenreId
Genre (navigational property)
Director
Id
Name
List<Movie> (navigational property)
Producer
Id
Name
List<Movie> (navigational property)
Actors
Id
Name
List<Movie> (there is many-many table in db) (navigational property)
Movie
Id
Name
SubGenreId
DirectorId
ProducerId
List<Actor> (navigational property)
Director (navigational property)
Producer (navigational property)
SubGenre (navigational property)
MovieActors (table)
MovieId
ActorId
Now, let's assume, we are already in the data layer (so there will be not
be major change-tracking on objects except for the id's). We have the data
in the movie object that needs to be persisted. If it exists, it needs to
be updated, if not inserted.
Movie object (movieDTO) that's sent to DataLayer.
MovieName
GenreName
SubGenreName
DirectorName
ProducerName
List ActorNames
Let's also assume there are millions of Directors/Producers/Actors/Movies
(basically huge amounts of data in each table) and the names of
directors/producers/actors/movie are unique for simplicity purpose. So the
logic would be, if the SubGenre exists use that, otherwise create SubGenre
record. Similarly look for if Genre exists, use that otherwise create it.
Likewise for the director, producer and actors.
Finally, the questions are
Which of these would be faster and why? (or) Are they same even while
taking millions of records into consideration?
Is it likely to change between Sql Server and Oracle? (With oracle, I am
using Devart as the provider)
Approach 1:
using (MovieDBContext context = new MovieDBContext())
{
Movie movie;
movie = context.Movies.Where(a => a.Name ==
movieDTO.MovieName).SingleOrDefault();
if (movie == null)
movie = new Movie() { Name = movieDTO.MovieName };
var subGenre = context.SubGenres.Where(a => a.Name ==
movieDTO.SubGenreName).SingleOrDefault();
if (subGenre == null)
{
movie.SubGenre = new SubGenre() { Name =
movieDTO.SubGenreName };
// Check if Genre exists.
var genre = context.Genres.Where(a => a.Name ==
movieDTO.GenreName).SingleOrDefault();
if (genre == null)
{
movie.SubGenre.Genre = new Genre() { Name =
movieDTO.GenreName };
}
else
{
movie.SubGenre.Genre = genre;
}
}
else
movie.SubGenre = subGenre;
var director = context.Directors.Where(a => a.Name ==
movieDTO.DirectorName).SingleOrDefault();
if (director == null)
movie.Director = new Director() { Name =
movieDTO.DirectorName };
else
movie.Director = director;
var producer = context.Producers.Where(a => a.Name ==
movieDTO.ProducerName).SingleOrDefault();
if (producer == null)
movie.Producer = new Producer() { Name =
movieDTO.ProducerName };
else
movie.Producer = producer;
// I am skipping the logic of deleting all the actors if the
movie is existing.
foreach (var name in movieDTO.Actors)
{
var actor = context.Actors.Where(a => a.Name ==
name).SingleOrDefault();
if (actor == null)
movie.Actors.Add(new Actor() { Name = name });
else
movie.Actors.Add(actor);
}
// Finally save changes. All the non-existing entities are
added at once.
// EF is keeping track if the entity exists or not.
context.SaveChanges();
}
Approach 2:
using (MovieDBContext context = new MovieDBContext())
{
var genre = context.Genres.Where(a => a.Name ==
movieDTO.GenreName).SingleOrDefault();
if (genre == null)
{
genre = new Genre() { Name = movieDTO.GenreName };
context.Genres.Add(genre); // genre.Id is populated with
the new id.
context.SaveChanges();
}
var subGenre = context.SubGenre.Where(a => a.Name ==
movieDTO.SubGenreName).SingleOrDefault();
if (subGenre == null)
{
subGenre = new SubGenre() { Name = movieDTO.SubGenreName };
context.SubGenres.Add(subGenre); // subGenre.Id is
populated with the new id.
context.SaveChanges();
}
var director = context.Directors.Where(a => a.Name ==
movieDTO.DirectorName).SingleOrDefault();
if (director == null)
{
director = new Director() { Name = movieDTO.DirectorName };
context.Directors.Add(director); // director.Id is
populated with the new id.
context.SaveChanges();
}
var producer = context.Producers.Where(a => a.Name ==
movieDTO.ProducerName).SingleOrDefault();
if (producer == null)
{
producer = new Producer() { Name = movieDTO.ProducerName };
context.Producers.Add(producer); // director.Id is
populated with the new id.
context.SaveChanges();
}
// Similarly for actors, add them if they don't exist.
foreach (var name in movieDTO.Actors)
{
var actor = new Actor() { Name = movieDTO.name };
context.Actors.Add(actor);
context.SaveChanges();
}
// Lastly movie.
Movie movie = context.Movies.Where(a => a.Name ==
movieDTO.MovieName).SingleOrDefault();
if (movie == null)
{
movie = new Movie() { Name = movieDTO.MovieName };
}
// This works for update as well.
// The id's are added/updated instead of actual entities.
movie.DirectorId = director.Id;
movie.SubGenreId = subGenre.Id;
movie.ProducerId = producer.Id;
// I am skipping the logic of deleting all the actors if the
movie is existing.
foreach (var name in movieDTO.Actors)
{
var actor = context.Actors.Where(a => a.Name ==
name).SingleOrDefault(); // Actors always exist now
because we added them above.
movie.Actors.Add(actor);
}
// Finally save changes. Here only Movie object is saved as
all other objects are saved earlier.
context.SaveChanges();
}

JS Validate - valid input & loagin bar while remote

JS Validate - valid input & loagin bar while remote

I'm making a simple javascript form with validation. I've already planned
my sintax and everything but I need help with two things:
I've templating my JS to output the error, but how can I change the
inputbox color to "green" for example if the input is OK by validation?
My templating error until now:
$.validator.setDefaults(
{
showErrors: function(map, list)
{
this.currentElements.parents('label:first,
.controls:first').find('.error').remove();
this.currentElements.parents('.control-group:first').removeClass('error');
$.each(list, function(index, error)
{
var ee = $(error.element);
var eep = ee.parents('label:first').length ?
ee.parents('label:first') : ee.parents('.controls:first');
ee.parents('.control-group:first').addClass('error');
eep.find('.error').remove();
eep.append('<p class="error help-block"><span class="help-block
error">' + error.message + '</span></p>');
});
//refreshScrollers();
}
});
Can you help me inserting the function to change the color if it's OK? I
just can't figure it out.
Other thing is about showing a "loading" image while javascript is remotly
checking if the user / email exists. I have everything ready and work, but
I can't and don't know how to show a loading image while it checks (
before give error result ), neither tells the result is OK ( only in those
fields ). My remote function:
$(function()
{
// validate signup form on keyup and submit
$("#registerform").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 3,
remote:{
url: "inc/core/check_user.php",
type: "post",
data: {
username: function(){
return $( "#username" ).val();
}
}
}
},
password: {
required: true,
minlength: 5
},
confpassword: {
required: true,
minlength: 5,
equalTo: "#password"
},
scode: {
required: true,
minlength: 4,
maxlength: 6,
digits: true
},
scodeconf: {
required: true,
minlength: 4,
maxlength: 6,
digits: true,
equalTo: "#scode"
},
email: {
required: true,
email: true,
remote:{
url: "inc/core/check_email.php",
type: "post",
data: {
email: function(){
return $( "#email" ).val();
}
}
}
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required",
address: "required",
zipcode: "required",
city: "required",
state: "required",
country: "required",
data: "required",
age: "required"
},
messages: {
firstname: $lang['register_jquery_pnome'],
lastname: $lang['register_jquery_unome'],
username: {
required: $lang['register_jquery_username'],
minlength: $lang['register_jquery_username_min'],
remote: $lang['register_jquery_username_registado'],
},
password: {
required: $lang['register_jquery_password'],
minlength: $lang['register_jquery_password_min']
},
confpassword: {
required: $lang['register_jquery_password'],
minlength: $lang['register_jquery_password_min'],
equalTo: $lang['register_jquery_password_equalto']
},
email:{
required: $lang['register_jquery_email_valido'],
remote: $lang['register_jquery_email_registado']
},
agree: $lang['register_jquery_tos'],
address: $lang['register_jquery_morada'],
zipcode: $lang['register_jquery_zipcode'],
city: $lang['register_jquery_city'],
state: $lang['register_jquery_state'],
country: $lang['register_jquery_pais'],
data: $lang['register_jquery_data'],
age: $lang['register_jquery_age'],
scode: {
required: $lang['register_jquery_codigoseguranca'],
minlength: $lang['register_jquery_codigoseguranca_min'],
maxlenght: $lang['register_jquery_codigoseguranca_max'],
digits: $lang['register_jquery_codigoseguranca_digits']
},
scodeconf: {
required: $lang['register_jquery_codigoseguranca'],
minlength: $lang['register_jquery_codigoseguranca_min'],
maxlenght: $lang['register_jquery_codigoseguranca_max'],
digits: $lang['register_jquery_codigoseguranca_digits'],
equalTo: $lang['register_jquery_codigoseguranca_equalto']
},
}
});
});
Could someone help me with those two things? Thanks in advance!

ROOT libraries in Eclipse

ROOT libraries in Eclipse

I am getting started with eclipse and I want to include ROOT libraries to
C++ project. I am completly newbie so I have no idea what I should do.
I found that question: add library to eclipse C++ project (ROOT) and
followed this advices, but it doesn't work. I don't understand what means
'add root-config --libsto linker miscellanoeus'.
I have a simple program:
============================================================================
// Name : StaticParam.cpp
//============================================================================
#include <iostream>
#include <TH1.h>
#include <TCanvas.h>
int main(void) {
TH1F* hist = new TH1F("hist","hist",100,100,200);
for(int i=0;i<1000;++i) {
hist->Fill(i)
}
TCanvas *c = new TCanvas();
hist->Draw();
return 0;
}
and makefile:
clean:
rm StaticParam.o stat.exe
hello.exe: StaticParam.o
g++ -g -o stat StaticParam.o
main.o:
g++ -c StaticParam.cpp
g++ -o stat StaticParam.o
Could you give me some advices how could I link the root libraries to
eclipse and change makefile to run this example?
Thanks a lot, Roma

jQuery dialog box opens on click, but autoOpen not working

jQuery dialog box opens on click, but autoOpen not working

I have a site here...
When you arrive at the site...
autoOpen: true, is working, but it's not loading the ajax request
(jquery-ajax.html).
But, if you click the button at the top-left, that says "Compliance &
Ethics", then the ajax request goes through and opens the dialog.
What am I doing wrong, that it doesn't autoOpen properly?
$(function() {
$("#dialog").dialog({
autoOpen: true,
modal: true,
width: 750,
height: 'auto',
show: 'fade',
hide: 'fade',
position: {my: "center top", at:"center top", of: window },
buttons: {
"Dismiss": function() {
$(this).dialog("close");
}
}
});
Here's what calls the ajax request on click...
<script type="text/javascript">
jQuery('#dialog').load('jquery-ajax.html').dialog('open');
</script>

Memory leak in c++ native code dll

Memory leak in c++ native code dll

I have a window service written in c# end point and inside it calls c++
native code dll.
I want a tool which can detect memory leak in native code dll.
Code base is very big That's why I required a good tool.
Thanks

java.net.ConnectionExcepcion: failed to conect to / 10.38.11.xx

java.net.ConnectionExcepcion: failed to conect to / 10.38.11.xx

I´m trying to connect andriod application with a server that I created.
The server is running in Eclipse and I run the app in my device from
Eclipse.
In my device, I have this error: java.net.ConnectionExcepcion: failed to
conect to / 10.38.11.xx (port:5541): connect failed: EHOSTUNREACH (No
route to host)
Both, the server and the device are connected at the same WIFI and the
WIFI is running under proxy.
The app code is:
package com.example.localcli;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;
import android.app.Activity;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity implements LocationListener {
private static final String[] A = { "n/d", "preciso", "impreciso" };
private static final String[] P = { "n/d", "bajo", "medio","alto" };
private static final String[] E = { "fuera de servicio",
"temporalmente no
disponible ","disponible"
};
private LocationManager manejador;
private TextView salida;
private String proveedor;
private String dato_localizacion;
Socket sk;
BufferedReader entrada;
PrintWriter out;
String ip = "10.38.11.73";
int puerto = 5541;
boolean conectado;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
salida = (TextView) findViewById(R.id.TextView01);
manejador = (LocationManager) getSystemService(LOCATION_SERVICE);
log("Proveedores de localización: \n ");
Conectar();
muestraProveedores();
Criteria criteria = new Criteria();
proveedor = manejador.getBestProvider(criteria, true);
log("Mejor proveedor: " + proveedor + "\n");
log("Comenzamos con la última localización conocida:");
Location localizacion = manejador.getLastKnownLocation(proveedor);
muestraLocaliz(localizacion);
Desconectar();
}
// Métodos del ciclo de vida de la actividad
@Override protected void onResume() {
super.onResume();
// Activamos notificaciones de localización
manejador.requestLocationUpdates(proveedor, 10000, 1, this);
}
@Override protected void onPause() {
super.onPause();
// Desactivamos notificaciones para ahorrar batería
manejador.removeUpdates(this);
}
//Métodos de la interfaz LocationListener
public void onLocationChanged(Location location) {
log("Nueva localización: ");
muestraLocaliz(location);
}
public void onProviderDisabled(String proveedor) {
log("Proveedor deshabilitado: " + proveedor + "\n");
}
public void onProviderEnabled(String proveedor) {
log("Proveedor habilitado: " + proveedor + "\n");
}
public void onStatusChanged(String proveedor, int estado,
Bundle extras) {
log("Cambia estado proveedor: " + proveedor + ", estado="
+ E[Math.max(0,estado)] + ", extras=" + extras +"\n");
}
//Métodos para mostrar información
private void log(String cadena) {
salida.append(cadena + "\n");
}
private void muestraLocaliz(Location localizacion) {
if (localizacion == null)
log("Localización desconocida\n");
else
log(localizacion.toString() + "\n");
}
private void muestraProveedores() {
List<String> proveedores = manejador.getAllProviders();
for (String proveedor : proveedores) {
dato_localizacion = stringProveedor(proveedor);
enviarDato(dato_localizacion);
log(dato_localizacion);
}
enviarDato("#FIN#");
}
// private void muestraProveedor(String proveedor) {
// log(stringProveedor(proveedor));
//}
private String stringProveedor(String proveedor) {
LocationProvider info = manejador.getProvider(proveedor);
String datos_muestra;
datos_muestra = ("LocationProvider[ "+"\n getName=" + info.getName()+
", \n isProviderEnabled=" +
manejador.isProviderEnabled(proveedor)+
", \n getAccuracy=" + A[Math.max(0, info.getAccuracy())]+
", \n getPowerRequirement=" +
P[Math.max(0,
info.getPowerRequirement())]+
", \n hasMonetaryCost=" + info.hasMonetaryCost()+
", \n requiresCell=" + info.requiresCell()+
", \n requiresNetwork=" + info.requiresNetwork()+
", \n requiresSatellite=" + info.requiresSatellite()+
", \n supportsAltitude=" + info.supportsAltitude()+
", \n supportsBearing=" + info.supportsBearing()+
", \n supportsSpeed=" + info.supportsSpeed()+" ]\n");
return datos_muestra;
}
public void Conectar() {
try {
//Creamos el socket
sk = new Socket (ip,puerto);
//Comprobamos que ha conectado correctamente
if (sk.isConnected() == true) {
//Inicializamos el buffer de entrada
entrada = new BufferedReader(
new InputStreamReader(sk.getInputStream()));
//Inicializamos el buffer de salida
out = new PrintWriter(
new OutputStreamWriter(sk.getOutputStream()),true);
//Indicamos que esta conectado
conectado = true;
//Recibimos mensaje
recibirDatos();
} else {
//Indicamos que no esta conectado
conectado = false;
}
} catch (Exception e) {
//Si hubo algun error mostramos error
log(" !!! ERROR !!! "+ e.toString());
Log.e("Error connect()", "" + e);
conectado = false;
}
}
public void Desconectar(){
try{
sk.close();
}
catch (Exception e) {}
}
public void recibirDatos() {
try{
//Datos de entrada
String dato_entrada = entrada.readLine();
//Mientras que el dato que nos envia el servidor sea distinto del
//comando #FIN# (que nos indica que no hay mas datos a recibir),
//mostramos el dato leido y leemos el siguiente
log("recibiendo ... ");
while (!(dato_entrada.equals("#FIN#"))) {
log(dato_entrada);
dato_entrada = entrada.readLine();
}
//Al salir del bucle es que ha terminado la transmision de datos
//log("Recibidos todos los datos");
}
catch (Exception e) {
log("Error al recibir los datos del servidor "+ e.toString());
}
}
public void enviarDato(String datos_out) {
if(conectado) {
try {
//Enviar dato
out.println(datos_out);
//Indicamos el fin de la emision con el comando #FIN#
// out.println("#FIN#");
}
catch (Exception e) {
log("Error al enviar los datos " + e.toString());
}
}
}
}
Thanks you in advance for your help and I´m sorry if my English is not
well understood.

Wednesday, 18 September 2013

https://play.google.com/apps/testing/ 404. That’s an error. The requested URL was not found on this server. That’s all we know

https://play.google.com/apps/testing/ 404. That's an error. The requested
URL was not found on this server. That's all we know

I am maintaining multiple apk support in Google Play Store. For testing ,
I published 2 apks in beta and then I was provided a URL to install apk on
my device but When i am trying download it showing error like.
404. That's an error. The requested URL was not found on this server.
That's all we know.
The apk was published 14 hours ago in market.
Please help me on this

2 Count in 1 sql

2 Count in 1 sql

ProductTable
ProductID ProductDesc
401 Hotdog
402 Ham
403 Bacon
OrderTable
OrderID OrderPayment NumOrder OrderDate
5001 Cash 3 9-15-2013
5002 Credit 2 9-16-2013
5003 Credit 2 9-17-2013
5004 Cash 3 9-18-2013
OrderDetailsTable
OrderDetailsID OrderID ProductID
70001 5001 401 -
70002 5001 401 -
70003 5001 403 -
70004 5002 401
70005 5002 402
70006 5003 402
70007 5003 403
70008 5004 403 -
70009 5004 402 -
70010 5004 401 -
How I will count the ProductID on how many it was order by cash on each
date and then get the total count of each product?
Sample Output
ProductID ProductDesc CountOnCash OrderDate
401 Hotdog 2 9-15-2013
401 Hotdog 1 9-18-2013
401 Hotdog 3 ---------
402 Ham 1 9-18-2013
402 Ham 1 ---------
403 Bacon 1 9-15-2013
403 Bacon 1 9-18-2013
403 Bacon 2 ---------
Select p.ProductID, p.ProductDesc, count(p.ProductId) as NumOrder,
o.OrderDate
from Product p
inner join OrderDetails od on p.productid = od.productid
inner join Order o on o.orderid = od.orderid
where orderpayment = 'cash'
Group by p.ProductID, p.ProductDesc, o.OrderDate

getting text to push up or down depending on what text is below it

getting text to push up or down depending on what text is below it

If I have a series of text in a top to bottom list like, actor, title,
about...
about can be massive or small. If cast is below about how can I always
keep cast just below about no matter how much text is in cast?
JSFIDDLE
#detail_center{position: absolute; height: 615px;left: 369px;top:
155px;width: 751px;}
#detail_center .title{position: absolute; top: 84px; left: 266px;
font-size: 26px; color: black;}
#detail_center .runtime{position: absolute; top: 130px; left: 266px;
font-size: 16px; color: black;}
#detail_center .icon-detail-bar{}
#detail_center .rating{position: absolute; top: 130px; left: 340px;
font-size: 16px; color: black;}
#detail_center .synopsis{position: absolute; top: 160px; left: 266px;
font-size: 16px; color: black;}
#detail_center .cast{position: absolute; top: 220px; left: 266px;
font-size: 16px; color: black;}
#detail_center .lang{position: absolute; top: 290px; left: 266px;
font-size: 16px; color: black;}
HTML
<div id="detail_center">
<div class="title">Some awesome movie title</div>
<div class="runtime">116 mins |</div>
<div class="rating">PG-13</div>
<div class="synopsis"> about stuff and stuff stuff and stufff and stuff
stuff and stutuff and stuff stuff and stuff stuff and stuff stuff and
stuff stuff and stuff</div>
<div class="cast">CAST:</div>
<div class="lang">LANGUAGES:</div>
</div>

Install custom tool using VSIX without running devenv /setup

Install custom tool using VSIX without running devenv /setup

I have created a custom tool within a Visual Studio 2012 "Package" project
and am distributing it via a .vsix file. Everything works great but the
custom tool is not registered unless I run "devenv.exe /setup". Is there
any way around this? I was under the impression (and it seems to be
confirmed by the EF team) that this only needed to be done when installing
using an MSI.

Is there a way to automate this in excel?

Is there a way to automate this in excel?

Below is example of what I am trying to achieve but it is very complex logic.
here is logic.
If Column A for a given UniqueID column C is Yes then get the Maximum
datestamp. if it it has no then list all of them.
so here is better explanation
if for all UniqueID = 100 if any of column C = Yes then we will only have
1 data for 100. if there isn't YES record in column C for UniqueID =100
then list of UserID.
please look at example below and see the output on right. Thanks

Rails 4: passing multiple arguments to partial

Rails 4: passing multiple arguments to partial

I'm able to pass a single argument from a view to a partial, but for some
reason when I add a second it is undefined (nil class).
Here's how I call the partial in the view:
<%= render 'project_form', locals: {project: @project, form_method:
'patch'} %>
Here's the top of the partial (_project_form.html.erb):
<%= logger.debug( @form_method ) %>
This prints "true" in the view, and logs nothing (a blank line) in the log.
Why isn't it receiving the second argument? I can debug @project and it's
the class I expect.

Dynamic page on python without frameworks

Dynamic page on python without frameworks

Tell me please how i can make dynamic page with python 3.3 + cgi + apache
+ mysql without any frameworks?
For my little task i need to handle GET request like a:
/index.py?what=data&from=data
After this, connect to mysql and getting data for dynamic page generation.
Maybe i should use something like that?
os.getenv("QUERY_STRING")
Please help me or tell me where i can find some useful information about
this. Thanks

PHP custom session handler not working?

PHP custom session handler not working?

I am in the process of building a database-driven website which needs to
include user authentication. If I use standard file-based session
management, all works as expected but if I try to use a custom session
handler (so that sessions are saved in the database), the only things that
seem to get stored are the ID and the timestamp.
Anything saved in a $_SESSION variable is nuked (although interestingly
this only occurs if I use header(Location: ...) to redirect to another
page upon successful login.
This is my session handler class file:
// include class files
require_once('database.php');
require_once('database-functions.php');
// set up session handler class
class Session {
private $session_login = null;
private $session_db = null;
public function __construct() {
// connect to database
$this -> session_login = new Database;
$this -> session_db = new SimplifiedDB;
$session_db_info = $this -> session_login -> getLogin();
$this -> session_db -> dbConnect(
$session_db_info['host'],
$session_db_info['user'],
$session_db_info['pass'],
$session_db_info['database']);
}
// open
public function open($save_path, $session_name) {
return true;
}
// close
public function close() {
return true;
}
// read
public function read($id) {
$get_data = $this -> session_db -> dbGetVariable('session',
'data', array('id' => $id));
if(empty($get_data)) {
return '';
} else {
return $get_data['data'];
}
}
// write
public function write($id, $data) {
$access = time();
$get_data = $this -> session_db -> dbGetVariable('session', 'id',
array('id' => $id));
if(empty($get_data)) {
// no ID, insert a record
$write_query = $this -> session_db -> dbInsert('session', array(
'id' => $id,
'data' => $data,
'access' => $access));
return true;
} else {
// ID exists, update it
$write_query = $this -> session_db -> dbUpdate('session', array(
'id' => $id,
'data' => $data,
'access' => $access));
return true;
}
return false;
}
// destroy (destroys a session)
public function destroy($sessionId) {
$destroy_query = $this -> session_db -> dbDelete('session',
array('id' => $sessionId));
return true;
}
// garbage collector (randomly deletes old sessions)
public function gc($lifetime) {
$the_time = time();
$sql = "DELETE FROM 'session' WHERE 'access' + $lifetime <
$this_time";
$gc_query = $this -> session_db -> dbExecuteQuery($sql);
return true;
}
}
I am using a SimplifiedDB class (database-functions.php) to connect to the
MySQL database using PDO, and the database.php file is another class which
contains my database credentials.
I've spent many hours on this problem and for the life of me cannot figure
out where I am going wrong. I have a header.php file which I include as
the first line of every PHP file, contents are as follows:
require_once('sessions.php');
$user_session = new Session();
session_set_save_handler(
array($user_session, 'open'),
array($user_session, 'close'),
array($user_session, 'read'),
array($user_session, 'write'),
array($user_session, 'destroy'),
array($user_session, 'gc'));
register_shutdown_function('session_write_close');
session_start();
I did originally have that stuff in the Session constructor in my session
handler class, but I put it in a separate class in the end (probably out
of desperation). My web host says that there are no server issues with
regards to session management, and I also have this problem on my
localhost webserver so it's definitely something wrong in the code.
I should also point out that I've done some other checks such as making
sure my header.php file is located on the first line of each PHP file, and
I use exit() after all redirects, as follows:
$_SESSION['test'] = 'testval';
header("Location: /index.php");
exit();
(using a full URL in the header line above makes no difference by the way,
I still have disappearing session variables).
Thanks for taking the time to read this, hopefully someone might be able
to point anything out that I have missed? :)

Tuesday, 17 September 2013

-[__NSArrayM insertObject:atIndex:]: object cannot be nil

-[__NSArrayM insertObject:atIndex:]: object cannot be nil

I am getting error object cannot be nil. I am using web service, when I
parse it using loop it crashed and send output -[__NSArrayM
insertObject:atIndex:]: object cannot be nil as error, because I have null
value on blank value in NSMutableArray which I am trying to parse. I tried
to fix with (1) if([Array containsObject:[NSNull null]]) (2) if([Array
objectAtIndex:0 (3) if([Array objectAtIndex:counter] == 0. methods.
My code is,
if([[[node childAtIndex:counter] name] isEqualToString:@"Phone"]){
if([phoneno containsObject:[NSNull null]]){
phone.text = @"-";
}
else{
NSString *str = [[node childAtIndex:counter]
stringValue];
[phoneno addObject:str];
NSString *myString = [phoneno
componentsJoinedByString:@","];
[phone setText:myString];
phone.text = [NSString stringWithFormat:@"%@",myString];
}
}
Here, phoneno is NSMutableArray
What am I doing wrong?

Including directories with gcc is not linking correctly

Including directories with gcc is not linking correctly

So I have a subdirectory with several files and need to link with it.
Inside the .c files I have an include that looks somewhat like:
#include "subdirectory/header.h"
this header file includes functions such as lex() that I am using and my
output on compiling is:
cc -IlexicalAnalyzer -Wall -c -o parser.o parser.c
cc -IlexicalAnalyzer -Wall -c -o recognizer.o recognizer.c
g++ -IlexicalAnalyzer -Wall parser.o recognizer.o -o recognizer
parser.o: In function `advance':
parser.c:(.text+0x36): undefined reference to `lex'
recognizer.o: In function `recognizer':
recognizer.c:(.text+0xd): undefined reference to `newLexer'
collect2: error: ld returned 1 exit status
make: * [recognizer] Error 1
What am I doing wrong?

Backload and jquery File Uploader - Do not display uploaded files properly

Backload and jquery File Uploader - Do not display uploaded files properly

I'm using MVC 4 and Backload file uploader with jquery client side
scripting. I used nuget to get the Demo package which downloads the
controller and view as a starting point.
My problem is on my local server and my online server, after I upload
files the application does not accurately display all the files uploaded.
Often it get's stuck displaying just 4 or 5 files and ignores the rest.
Even if I delete one of the files being displayed and refresh the page it
still shows the same 4 or 5 images. I have verified that the files are
being uploaded and/or deleted by the application. I tried clearing the
cache by hitting cntl F5 but to no avail.
Can anyone point me in the right direction to correct this problem. Below
is the view and controller that comes from the demo downloaded from NuGet.
CONTROLLER:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Spotless_Interiors.Controllers
{
[Authorize]
public class BackloadDemoController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
VIEW:
@{
ViewBag.Title = "File Upload";
}
@section topScripts {
@Styles.Render("~/Content/themes/base/css")
@Styles.Render("~/Content/css")
<!-- We use Backloads. bundeling feature to register only those client
side javascript and style files of the jQuery File Upload Plugin
that are needed -->
@Styles.Render("~/bundles/fileupload/bootstrap/BasicPlusUI/css")
<!-- Bootstrap CSS fixes for IE6 -->
<!--[if lt IE 7]><link rel="stylesheet"
href="/Content/FileUpload/css/bootstrap/bootstrap-ie6.debug.css"><![endif]-->
<!--[if lt IE 9]><script
src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<!--[if IE]><meta http-equiv="X-UA-Compatible"
content="IE=edge,chrome=1"><![endif]-->
}
@section scripts {
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")
<!-- We use Backloads. bundeling feature to register only those client
side javascript and style files of the jQuery File Upload Plugin that
are needed -->
@Scripts.Render("~/bundles/fileupload/bootstrap/BasicPlusUI/js")
<!-- Initialize the jQuery File Upload Plugin -->
<script src="~/Scripts/FileUpload/backload.demo.js"></script>
}
<div>
<!-- The file upload form used as target for the file upload
widget -->
<form id="fileupload" action="/Backload/UploadHandler"
method="POST" enctype="multipart/form-data">
<!-- Redirect browsers with JavaScript disabled to the origin
page -->
<noscript><input type="hidden" name="redirect"
value="/"></noscript>
<!-- The fileupload-buttonbar contains buttons to add/delete
files and start/cancel the upload -->
<div class="row fileupload-buttonbar">
<div class="span7">
<!-- The fileinput-button span is used to style the
file input field as button -->
<span class="btn btn-success fileinput-button">
<i class="icon-plus icon-white"></i>
<span>Add files...</span>
<input type="file" name="files[]" multiple>
</span>
<button type="submit" class="btn btn-primary start">
<i class="icon-upload icon-white"></i>
<span>Start upload</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="icon-ban-circle icon-white"></i>
<span>Cancel upload</span>
</button>
<button type="button" class="btn btn-danger delete">
<i class="icon-trash icon-white"></i>
<span>Delete</span>
</button>
<input type="checkbox" class="toggle">
<!-- The loading indicator is shown during file
processing -->
<span class="fileupload-loading"></span>
</div>
<!-- The global progress information -->
<div class="span5 fileupload-progress fade">
<!-- The global progress bar -->
<div class="progress progress-success progress-striped
active" role="progressbar" aria-valuemin="0"
aria-valuemax="100">
<div class="bar" style="width:0%;"></div>
</div>
<!-- The extended global progress information -->
<div class="progress-extended">&nbsp;</div>
</div>
</div>
<!-- The table listing the files available for upload/download
-->
<table role="presentation" class="table table-striped"><tbody
class="files" data-toggle="modal-gallery"
data-target="#modal-gallery"></tbody></table>
</form>
<!-- The template to display files available for upload -->
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-upload fade">
<td>
<span class="preview"></span>
</td>
<td>
<p class="name">{%=file.name%}</p>
{% if (file.error) { %}
<div><span class="label
label-important">Error</span>
{%=file.error%}</div>
{% } %}
</td>
<td>
<p class="size">{%=o.formatFileSize(file.size)%}</p>
{% if (!o.files.error) { %}
<div class="progress progress-success
progress-striped active" role="progressbar"
aria-valuemin="0" aria-valuemax="100"
aria-valuenow="0"><div class="bar"
style="width:0%;"></div></div>
{% } %}
</td>
<td>
{% if (!o.files.error && !i && !o.options.autoUpload)
{ %}
<button class="btn btn-primary start">
<i class="icon-upload icon-white"></i>
<span>Start</span>
</button>
{% } %}
{% if (!i) { %}
<button class="btn btn-warning cancel">
<i class="icon-ban-circle icon-white"></i>
<span>Cancel</span>
</button>
{% } %}
</td>
</tr>
{% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-download fade">
<td>
<span class="preview">
{% if (file.thumbnail_url) { %}
<a href="{%=file.url%}" title="{%=file.name%}"
data-gallery="gallery"
download="{%=file.name%}"><img
src="{%=file.thumbnail_url%}"></a>
{% } %}
</span>
</td>
<td>
<p class="name">
<a href="{%=file.url%}" title="{%=file.name%}"
data-gallery="{%=file.thumbnail_url&&'gallery'%}"
download="{%=file.name%}">{%=file.name%}</a>
</p>
{% if (file.error) { %}
<div><span class="label
label-important">Error</span>
{%=file.error%}</div>
{% } %}
</td>
<td>
<span
class="size">{%=o.formatFileSize(file.size)%}</span>
</td>
<td>
<button class="btn btn-danger delete"
data-type="{%=file.delete_type%}"
data-url="{%=file.delete_url%}"{% if
(file.delete_with_credentials) { %}
data-xhr-fields='{"withCredentials":true}'{% } %}>
<i class="icon-trash icon-white"></i>
<span>Delete</span>
</button>
<input type="checkbox" name="delete" value="1"
class="toggle">
</td>
</tr>
{% } %}
</script>
</div>

Add Value to Variable in Lua?

Add Value to Variable in Lua?

In most languages, I can easily do some mathematical function (add,
subtract, etc...) to a variable's current value in a short form like foo
+=1. Is there something similar in Lua?

Joining same table on itself

Joining same table on itself

One of my table stores the UserAgent from the user's browser along with
the corresponding UID associated with it, with some other data. This
occurs every time a user logs in. So they will have many entries per user.
I am trying to query this table to find some unique users based on
qualities.
For example, I am trying to find only users that have used IE6 and no
other browsers. The closest I can get so far is through this method:
select distinct (U.UID) from TABLE1 tb1
inner join TABLE1 tb2 on tb1.UID = tb2.UID
where tb1.UserAgent like '%MSIE 6.%'
and tb2.UserAgent like '%MSIE 6.%'
This seems to return users whom have used IE6 and any other browser as
well. I am trying to find basically the opposite of this. Users that have
used IE6 and IE6 only. I also tried the one below but didn't quite work
either because a good chunk of this users had other entries with non IE6
browsers.
select distinct (U.UID) from TABLE1 tb1
inner join TABLE1 tb2 on tb1.UID = tb2.UID
where tb1.UserAgent like '%MSIE 6.%'
and tb2.UserAgent not like '%MSIE 6.%'
I think I am on the right track but could be way off here.
TIA!

Python (sympy) string to php issues

Python (sympy) string to php issues

I have a weird situation. I am calling a python program from my webpage
(written in PHP). It normally works fine, but I when I add
import sympy
I get problems (this is one line is the only difference).
Basically, when I run the program from the terminal (with 'import sympy')
it works just fine (prints 6 strings), but when I call the program from my
php file it returns an empty array (instead of an array with 6 strings
like it should). The two commands are
terminal:
python MyProgram.py arg1
from php:
$command='python MyProgram.py arg1';
exec($command, $output);
Any ideas? Thanks in advance!

Sunday, 15 September 2013

Dotnet Highchart in MVC

Dotnet Highchart in MVC

Now I am working on a Asp.net MVC4 application, I would like to display
graphs which represents some calculations from the database using LINQ
queries and highcharts.
I can display the graph in my application but without any filter In my
action method I have the following code:
public ActionResult Index()
{
//XAxis : Categories
var item = (from o in frh.Dates
orderby o.Date1
select o.mois).ToArray();
int lenght = item.Count();
string[] data = new string[lenght];
object[] data2 = new object[lenght];
double?[] last = new double?[lenght];
// liste des mois -- string
for (int i = 0; i < lenght; i++)
{
data[i] = item[i].ToString();
}
var items = (from x in frh.productivites
where x.Activité == ***Parameter from view ???***
select new { x.delta_, x.tempstot_, x.mois });
var j = 0;
foreach (var a in data)
{
var sumd = items.Where(c => c.mois == a).Select(c =>
c.delta_).Sum();
var sumt = items.Where(c => c.mois == a).Select(c =>
c.tempstot_).Sum();
var prod = sumd / sumt;
last[j] = prod;
j++;
sumd = 0;
sumt = 0;
prod = 0;
}
data2 = last.Cast<object>().ToArray();
DotNet.Highcharts.Highcharts chart = new
DotNet.Highcharts.Highcharts("chart")
.SetXAxis(new XAxis
{
Categories = data
})
.SetYAxis(new YAxis
{
PlotLines = new[]
{
new YAxisPlotLines
{
Value = 0,
Width = 1,
Color =
ColorTranslator.FromHtml("#808080")
}
}
})
.SetTitle(new Title
{
X = -20
})
.SetSubtitle(new Subtitle
{
X = -20
})
.SetSeries(new Series
{
Data = new Data(data2)
});
return View(chart);
}
I need to pass some fields from view to controller so that I can filter
the json request
how can i do that?? Thank you in advance!

V4L2 timeperframe weird behaviours

V4L2 timeperframe weird behaviours

I'm currently building a capture software using the V4L2 API. The thing
is, when I fetch a frame I'm experimenting weird timing behaviours.
Basically, I set up the timeperframe capability according to the specs of
my webcam :
echo% v4l2-ctl --list-formats-ext
ioctl: VIDIOC_ENUM_FMT
Index : 0
Type : Video Capture
Pixel Format: 'YUYV'
Name : YUV 4:2:2 (YUYV)
Size: Discrete 640x480
Interval: Discrete 0.033s (30.000 fps)
Interval: Discrete 0.050s (20.000 fps)
Interval: Discrete 0.067s (15.000 fps)
Interval: Discrete 0.100s (10.000 fps)
Interval: Discrete 0.133s (7.500 fps)
Interval: Discrete 0.200s (5.000 fps)
Here I choose to capture YUYV 640x480 frames at 30 fps, so I set the
timeperframe capability :
FAIL_ON_NEGATIVE(ioctl(fd, VIDIOC_G_PARM, &setfps))
if (!(setfps.parm.capture.capability & V4L2_CAP_TIMEPERFRAME))
errx(1, "%s does not support frame rate settings", device);
BZERO_STRUCT(setfps)
setfps.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
setfps.parm.capture.timeperframe.numerator = 1;
setfps.parm.capture.timeperframe.denominator = 30;
FAIL_ON_NEGATIVE(ioctl(fd, VIDIOC_S_PARM, &setfps))
I also check that the driver didn't change the numerator/denominator.
I request a frame :
FAIL_ON_NEGATIVE(select(fd + 1, &fds, NULL, NULL, NULL))
FAIL_ON_NEGATIVE(ioctl(fd, VIDIOC_DQBUF, &buf))
Surprisingly, at this point I found that the average delta time between
frames is 160 ms using the V4L2 timestamp field.
I did the same using another webcam and here I got my 30 fps at first but
then it stabilized at 133ms (2/15):
33 | 33 | 34 | 33 | 34 | 33 | 34 | 33 | 42 | 41 | 42 | 42 | 41 | 42 | 50 |
50 | 50 | 50 | 50 | 75 | 75 | 100 | 100 | 125 | 125 | 134 | 132 | 134 |
133 | 134 | 133 | 133 | 134 | 133 | 133 | 134 | 133 | 134
Using ffmpeg I have the same issue (160ms) :
ffmpeg -f video4linux2 -vcodec rawvideo -pix_fmt yuyv422 -s 640x480 -r 30
-i /dev/video0 out.yuv
frame= 109 fps=6.3 q=0.0 Lsize= 65400kB time=00:00:03.63
bitrate=147456.0kbits/s
What's going on ? Am I doing something wrong ?

add / remove field dynamically in php mysql without javascipt

add / remove field dynamically in php mysql without javascipt

I am working on student database. Each Applicant can apply for upto three
programs. I want to include add / remove program option on my php form
without using javascript. Is it possible to do it wihout javascipt? please
help!!!

Adding new calendars to iOS

Adding new calendars to iOS

iOS provides a set of calendars, that can be used in an application.
Here's the list of their ids:
NSString * const NSGregorianCalendar;
NSString * const NSBuddhistCalendar;
NSString * const NSChineseCalendar;
NSString * const NSHebrewCalendar;
NSString * const NSIslamicCalendar;
NSString * const NSIslamicCivilCalendar;
NSString * const NSJapaneseCalendar;
NSString * const NSRepublicOfChinaCalendar;
NSString * const NSPersianCalendar;
NSString * const NSIndianCalendar;
NSString * const NSISO8601Calendar;
What if I want to add more calendars. Let's say French Republican one
(http://en.m.wikipedia.org/wiki/French_Republican_Calendar)?
I perfectly understand that I can use formula to convert dates, but is
there a way to create own calendar to use just like the standard one, for
example:
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.calendar = [[NSCalendar alloc]
initWithCalendarIdentifier:@"french_republican"]];

Tab encoding not working in W2008 server

Tab encoding not working in W2008 server

I have a GET request like this:
https://server/Api/multitester%20digital%20sinometer%20m%203900%09%20-%09050301-011660-001112/productdetail
It works fine locally on my Window 8 machine but on the server I always
get "Bad Request - Invalid URL". The request on the server is not even
reaching the code in the controller.
If I remove %09 then it works in both places. My internal logic deals
properly with special escape characters.
Any light on what would be going on?
FYI: I can't quite control what the product name can be in the case of tabs.
Thanks!

String matching library with finite state machine

String matching library with finite state machine

I am looking for a library (free software) that can generate the state
machine needed for string matching. I am mainly referring to finite state
automation based search. There also a nice visual example in the wikipedia
link.
What I want to achieve in the first phase is a finite state machine for a
single pattern search, and after that to extend it to multiple pattern
search. Ideas are welcomed.
Thanks,
Iulian

Indent text in xml serialization of string property?

Indent text in xml serialization of string property?

I have a string property which will contain text with newlines. This text
has some of the properties of HTML text in that whitespace is disregarded.
If I serialize this type using XML serialization, the newlines are
serialized properly, but the indentation is "wrong". I want the
serialization process to indent the lines to keep the formatting of the
XML, since those whitespace characters will be disregarded later anyway.
Here's an example LINQPad program:
void Main()
{
var d = new Dummy();
d.Text = @"Line 1
Line 2
Line 3";
var serializer = new XmlSerializer(typeof(Dummy));
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
using (var writer = new StringWriter())
{
serializer.Serialize(writer, d, ns);
writer.ToString().Dump();
}
}
[XmlType("dummy")]
public class Dummy
{
[XmlElement("text")]
public string Text
{
get;
set;
}
}
Actual output:
<?xml version="1.0" encoding="utf-16"?>
<dummy>
<text>Line 1
Line 2
Line 3</text>
</dummy>
Desired output:
<?xml version="1.0" encoding="utf-16"?>
<dummy>
<text>
Line 1
Line 2
Line 3
</text>
</dummy>
Is this possible? If so, how? I'd rather not do the hackish way of just
adding the whitespace in myself.
The reason for this is that this XML will be viewed and edited by people,
so I'd like for the initial output to be better formatted for them out of
the box.

Saturday, 14 September 2013

Check if file existing or not in c

Check if file existing or not in c

unsigned char IsFilePathCorrect(char* prgchDirPath)
{
WIN32_FIND_DATA FindFileData;
HANDLE handle;
int found=0;
//1. prgchDirPath is char pointer. But expected is LPCWSTR.
//How to change this?
//2. prgchDirPath is a directory path. File is not existed.
//But I want to make sure if directory/path exists or not.
//Can the API below helps me? if yes, how?
handle = FindFirstFile(prgchDirPath, &FindFileData);
if(handle != INVALID_HANDLE_VALUE)
found = 1;
if(found)
{
FindClose(handle);
}
return found;
}
I want to check if directory path is existed or not. Please provide one
sample code. Thank you.

Unknown table in field list (MySQL in vb.net)

Unknown table in field list (MySQL in vb.net)

I use MySql.Data.MySqlClient.MySqlCommand and MySqlConnection
Public fillGridCmdTxt As String = "SELECT tblItems.part_num AS Part#,
tblCategory.category_description AS Category, " _
& " tblItems.item_name AS 'Item Name', tblItems.item_desc AS
Description, " _
& "tblItems.item_qty AS Qty, tblUnit.unit_name AS Unit,
tblItems.item_price AS 'Selling Price(Php)' " _
& "FROM tblUnit INNER JOIN tblItems ON tblUnit.unit_id =
tblItems.unit_id INNER JOIN tblCategory " _
& "ON tblItems.category_id = tblCategory.category_id "
and when i use executeNonQuery on MySqlCommand, it gives me an error... It
says that "Unkown table '*tblItems in field list*" even the table is
really existing on my database... a little help please?

ADO.net Adding columns to entity outside DB

ADO.net Adding columns to entity outside DB

I had a hard time to come up with a title for this :)
I've got a WCF service hooked up to a SQL-server database. I retrieve data
from the DB using ADO.NET.
On some simple operations I just retrieve from the DB and then send back a
json representation of the EntityObjects i just fetched which works fine.
However now I'm doing a more complex fetch with a procedure. The data
retrieval works fine but the procdure itself returns more columns than the
actual EntityObject (Table) has. Take this for an example:
create table Person
{
Name,
BirthDate
}
// Retrieve Persons from DB with procedure that also calculates each
persons actual age!
public List<EntityObject> getPersons()
{
var personList = new List<EntityObject>();
var dataSet = dbContext.ExceuteProcedure("GET_PERSONS_WITH_AGE",
parameters);
var dataTable = dataSet.Tables["result"];
foreach (DataRow row in dataTable.Rows)
{
personList.Add( new PersonEntity
{
Name = (String)row["Name"],
BirthDate = (DateTime)row["BirthDate"],
// Here i want the actual age calculation result, but since
the DB-table Person does'nt have this column,
// I can't set it.
}
}
return personList;
}
Do I need to create a CustomPersonClass for this which has this extra
variable? Or can I somehow force another column into Table Person in my
ADO.NET object?
Please consider that I'm novice about ADO.NET, if you see other code
faults in my example (regarding methods of retrival as well) please let me
know.

Twitter Bootstrap 3: Small Offset/Margin

Twitter Bootstrap 3: Small Offset/Margin

I'm using twitter bootstrap 3. What I want is a margin between two divs
which is smaller than the grid size (so col-md-offset-* does not work for
this).
<div id="content-row" class="row">
<div class="col-md-offset-2 col-md-2 content">
some content
</div>
<div id="content" class="col-md-offset-1 col-md-5 content">
some other content
</div>
</div>
I was wondering, what's the twitter-bootstrap way to achieve this? Surely,
one could just define margins but that would break the row/column layout
of twitter bootstrap, so I'm feeling that there must be a better solution.

Java - ProcessBuilder

Java - ProcessBuilder

I'm trying to figure out how to use the ProcessBuilder to create for each
new request coming in. I don't have a clue how to do this. I've read
something about forking or spawning a process. Does someone can give me a
clue on how to do this?

Hi Guys,how to remove duplicate from this array

Hi Guys,how to remove duplicate from this array

would you please help me on this? I have a code like this, I have to sort
it and then remove duplicate. I've already sorted it but problem removing
duplicates. would you please complete code below for me?
import java.util.*;
public class NoDuplicate {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(54);
list.add(12);
list.add(62);
list.add(54);
list.add(12);
list.add(43);
list.add(62);
Collections.sort(list);
removeDuplicate(list);
for (int i = 0; i < list.size(); i++)
System.out.println(list.get(i));
}
**private static ArrayList<Integer> removeDuplicate(ArrayList<Integer>
list)
{
}
}**
anyone can help me write this removeDuplicate method? thanks

Java: Linear Regression -- What's wrong with my code?

Java: Linear Regression -- What's wrong with my code?

This is not Homework. I am planning to implement linear regression in
mapreduce and to get started, I am trying to implement in the regular way.
The below mentioned is the code. When I try to run I am getting the cost
function value as zero and goes to negative infinity. I am debugging since
4 hours -- Please advice where I am going wrong.
I tried to declare variables outside the main method (within class) so
both main and GradientDescent methods can use them but I am getting
errors. Appreciate your help in this
public class LinearRegression{
public static double GradientDescent(int thetaparam){
int i=0,j=0;
double[] y = new double [10];
double[][] mat = {{1,1,1,1,1,1,1,1,1,1},{5,6,7,1,8,11,2,3,13,5}};
double[] price = {7,7,6,3,1,3,5,7,4,8};
double[] theta = new double[2];
int m = mat[0].length;
for(i=0;i<mat[0].length;i++){
for(j=0;j<theta.length;j++)
y[i] = y[i] + (mat[j][i]*theta[j]);
y[i] = (y[i] - price[i])*mat[thetaparam][j];
}
double a=0;
for(i=0;i<mat[0].length;i++)
a += y[i];
return a;
}
public static void main(String args[]){
int j=0,i=0;
double[][] mat = {{1,1,1,1,1,1,1,1,1,1},{5,6,7,1,8,11,2,3,13,5}};
double[] price = {7,7,6,3,1,3,5,7,4,8};
double[] theta = {0.0,0.0};
int m = mat[0].length;
double alpha = 0.01;
double[] y = new double [10];
for(int z=0;z<=20;z++){
theta[0] -= (alpha/m)*GradientDescent(0);
theta[1] -= (alpha/m)*GradientDescent(1);
for(i=0;i<mat[0].length;i++){
for(j=0;j<theta.length;j++)
y[i] = y[i] + (mat[j][i]*theta[j]);
y[i] = ((y[i] - price[i])*(y[i] - price[i]));
//y1[i] = y[i]*y[i];
}
double a=0;
for(i=0;i<mat[0].length;i++)
a += y[i];
System.out.println("Value of Costfunction at "+z+" iteration is
"+(1/(2*m)*a));
}
for(j=0;j<theta.length;j++)
System.out.println(theta[j]);
}
}

h2m_domain and p2m_domain in xen source code. what is the full form

h2m_domain and p2m_domain in xen source code. what is the full form

What is the meaning of h2m and p2m domain in xen?
What does it denote ?
what is p to m, domain and h to m domain, is it a conversion or something
else?

Friday, 13 September 2013

how can i count multiple occurence of multiple fields in a column corresponding to another attribute?

how can i count multiple occurence of multiple fields in a column
corresponding to another attribute?

I am new to MySQL.
I am having a table having fields as (NAME FRUIT TIME)
NAME FRUIT TIME
AJAY MANGO 10:10 SACHIN APPLE 12:00 RAJ MANGO 10:00 AJAY MANGO 12:00 AJAY
MANGO 11:00 AJAY APPLE 12:00 RAJ BANANA 12:00 AJAY BANANA 12:00 SACHIN
BANANA 2:00 SACHIN MANGO 12:00 RAJ MANGO 12:00 SACHIN APPLE 12:00 AJAY
APPLE 12:00 AJAY APPLE 12:00
NOW I want TO GET OUTPUT FROM THE ABOVE TABLE AS
NAME MANGOCOUNT APPLECOUNT BANANACOUNT AJAY 3 3 1 RAJ 2 0 1 SACHIN 1 2 1
I TRIED FOR UNION AS
'SELECT NAME, COUNT(*) AS MANGOCOUNT FROM FRUIT_EAT WHERE FRUIT='MANGO'
GROUP BY NAME UNION ALL SELECT NAME, COUNT(*) AS APPLECOUNT FROM FRUIT_EAT
WHERE FRUIT='APPLE' GROUP BY NAME UNION ALL SELECT NAME, COUNT(*) FROM
FRUIT_EAT WHERE FRUIT='BANANA' GROUP BY NAME;'
i am getting result as
NAME MANGOCOUNT AJAY 3 RAJ 2 SACHIN 1 AJAY 3 RAJ 0 SACHIN 2 AJAY 1 RAJ 1
SACHIN 1
I am not understanding my mistake if you please help me out??

convert an integer number in a date to the month name using python

convert an integer number in a date to the month name using python

I do have this string '2013-07-01' and I want to convert it to July 1, 2013
How to do that using python?
Thanks!

how to determine which points are in view when scrolling a c# chart

how to determine which points are in view when scrolling a c# chart

I have a c# DataVisualization chart with scrolling enabled. Is there a way
to determine which points (X value) are in view when the user scrolls the
chart? It's a simple fastline plot. Thanks in advance.

Boost HTTP server issue

Boost HTTP server issue

I'm starting to use Boost, so may be I'm messing something up.
I'm trying to set up http server with boost (ASIO). I've taken the code
from docs:
http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/examples/cpp03_examples.html
(HTTP Server, the first one)
The only difference from the example is I'm running server by my own
method "run" and starting io_service in background thread, like in the
docs:
http://www.boost.org/doc/libs/1_54_0/doc/html/boost_asio/reference/io_service.html
boost::asio::io_service::work work(io_service_);
(Also I'm stopping io_service from my run method too.)
When I'm starting this modified server everything seems to be OK, run
method is working fine. But then I'm trying to get a doc from the server
the request hangs and control flow never comes to "request_handle" method.
Am I missing something?

'!' does not exclude file in .gitignore

'!' does not exclude file in .gitignore

my .gitignore file:
.DS_Store
temp
!temp/script.txt
However when I do git status it doesn't display the temp/ directory to
indicate that the script.txt is not in the staged. It only displays the
.gitignore file:
# Changes not staged for commit:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: .gitignore
I'm just learning git. Any idea where i'm going wrong?

Thursday, 12 September 2013

Creating a Appwarp chatroom and issues in a Android game

Creating a Appwarp chatroom and issues in a Android game

(I will add the Q sign so that its more easier to look directly at what i
wanna ask ;) Also, i should mention that i'm kind of new to customising
APIs, have done some programming tho so you can post references :) )
I was creating an android app (actually a game) with customised Cocos2d
and I was planning to add in a chat feature. kind of like a counter-strike
where other players can send short IM to each other (I think the clash of
clan's clan chat comes closest to what i want to make, you can get an idea
from that)
I was trying to use AppWarp API to do this, but am finding it hard to do
so. I liked appwarp because it handles server management on its own. I
don't wanna get into implementing a XMPP/Smack customised code where
scalability becomes an issue later on, because i dont know server
management at all! (although i would love the freedom it gives me). Did i
mention that its a two man team? Me and a friend :).
In my game in I need one global room (a static room) and an another
special-group room (this will be dynamic, since its only created if the
user selects to create the room).
But the problem with creating a dynamic group room in Appwarp is that it
doesnt stay alive (remain persistent) after all the users in it have
disconnected. According to the current implementation in the API, the
dynamic group gets deleted if the last member logs out.
Q1) Is there a way for me to create a persistent/static room from client
side? Q2) and if that isnt possible is there some way i can make the
dynamic rooms persistent? Basically i'm asking anyone who has experience
with Appwarp, If it requires some tweaking with the code can you please
point me out in the right direction?, or is it not possible at all?
Q3) Also, i wanted to implement a chat history feature on the chat rooms.
Is that already available via Appwarp API? or would I have to write a
listener, so that each time a room receives a message it maintains a
history file? Again this is only possible if the user can re-connect to
the room.. Please guide me for this too.
Also,supposing i have to drop Appwarp idea (Gulp!) Q4) Can you please
point me in the right direction to create a group-based chat with a
similar api that can be integrated with an android app with cocos2D.
If anyone can post the answer to these, i will appreciate it :)
Thanks in advance!

Jframe background image

Jframe background image

I am creating a GUI, albeit a simple one, and I want to have a background
image (2048 X 2048) fill up the whole window and a square to the left top
corner where the occasional 64 X 64 image can be loaded. Thanks in advance
to anyone who helps out :) Edit: I already know how to make the JFrame a
set size, its the image loading I need help with.

How can I center two floated elements within a container?

How can I center two floated elements within a container?

This is driving me crazy. I am relatively new to this stuff so trying to
figure this one out for the past hour. I'll be really thankful if someone
can help me with this.
I have the following code:
<div class="middle_box">
<div class="box left">
Some large text
</div>
<div class="box right">
Some large text as well
</div>
</div>
CSS:
.middle_box {
height: 260px;
margin: 0 auto;
width: 960px;
}
.box {
float: left;
font-size: 21px;
margin-right: 50px;
margin-top: 25px;
padding-top: 25px;
width: 390px;
}
As you can tell the width of the container is 960px. Now, I want to center
the two .box elements within the 960px container and that's where I am
lost.
What did I try?
I tried using margin: 0px auto; and I tried faking it by adding
margin-left on both sides but it just didn't work. How can I achieve this?