Monday, May 14, 2012

Eclipse error- Google Map View failed to instantiate

I am making project on Google map that displays 10 nearest position in map,
Today Morning, My project works fine but than after, when I lounch my eclipse it displays dialog box that "Internal Error"
"com.google.android.maps.MapView failed to instantiate"
"java.lang.StackOverflowError"



and than pressing ok on dialog box,
says me to you are recommanded to exit the workbench..
I am afraid, that it might delete or crash my project,
What to do?? plz help me someone.



I should reinstall eclipse??





Displaying only the last Overlay item

What i do is to take data from an xml file and then using a Custom ItemizedOverlay i add the items.



public CustomItemizedOverlay callme(List<Places> result){

Drawable drawable = this.getResources().getDrawable(R.drawable.ic_launcher);

latitudeE6 = result.get(i).latitude;
longitudeE6 = result.get(i).longitude;

GeoPoint point = new GeoPoint(latitudeE6a, longitudeE6a);
OverlayItem overlayitem = new OverlayItem(point, result.get(i).title, result.get(i).text);

CustomItemizedOverlay itemizedOverlay = new CustomItemizedOverlay(drawable);

itemizedOverlay.addOverlay(overlayitem);//add point

i++;

latitudeE6 =0;
longitudeE6 =0;
return itemizedOverlay;

}


While i am on the UI Thread i use a while() loop to print :



int j=0;
List<Overlay> mapOverlays = mapView.getOverlays();

while( j < 5 ) {
test1 = callme(result1);
mapOverlays.add(test1);

j++;
}

MapController mapController = mapView.getController();
mapController.setZoom(12);


Having to display only five items the loop stops while j < 5 .
The problem is that it only displays the last item from the xml data.





how do you word the query to paginate a fulltext search correctly?

I just started working on a search feature for a small site im creating for a friend, and im having a bit of trouble building the query to page the search results.



the query I've created works perfect minus pagination:



$sql = "SELECT *,

MATCH(title, desc) AGAINST('$keyword') AS score

FROM database

WHERE MATCH(title, desc) AGAINST('$keyword') AND `cat` = '$cat' ";


but then for paging, im use to doing something like:



$query = "SELECT COUNT(*) as num FROM $tableName";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages[num];


so the part where im lost is how can I combine the two? I tried:



$sql = "SELECT COUNT(*),

MATCH(title, desc) AGAINST('$keyword') AS score

FROM database

WHERE MATCH(title, desc) AGAINST('$keyword') AND `cat` = '$cat' ";


im somewhat new to programming so this is probably a stupid question but any help would be greatly appreciated





Even numbers series

I'm trying to create a program that generates a series and asks the user to enter the last number in it.
I wrote it but the output should be something similar to




The Sum= -2+4-6+8-10+12-14+16-18+20....




And my output is




-20-18-16-14-12-10-8-6-4-2




So, as you can see, I have three mistakes which are




  1. Their sequence(should start from 2 not vice versa)

  2. The signs, it should be one time - and another + but I have no clue how

  3. Writing sum once at the beginning of the series :(



Here's my code



import java.util.*;
public class Even{
public static void main (String [] args){
Scanner myScanner= new Scanner(System.in);
System.out.println("Enter last number");
int lastNumber= myScanner.nextInt();
if (lastNumber<=1)
{
System.out.print("error");
}
while(lastNumber>1){
System.out.print("-"+lastNumber);
lastNumber-=2;
}
}
}


Thanks in advance!





MySQL query for a recommendation engine

I am making a food recommendation engine.
I have two tables:




  1. Places that contain rating, cuisine, price, name etc.

  2. checkin that contain place_name, rating, userid, count etc.



Now for recommendation I need to check the previous checkin of the user and made recommendation accordingly. So my query is like



select *,factor1+factor2+factor3 as final_rating
from places
order by final_rating desc


factor1 and factor2 are working great but not factor3.



Factor 3 is I want to check the cuisines in which user has checkined most. So for a place in place table I have to check its cuisine and then look into the checkin table for the count of checkins made by a user for that particular cuisine.



NOTE: There is no cuisine column in checkin table.





How to refresh Google map.

Hi Guys this is my code.



I am able to refresh the google map on refresh button click but it is showing me the old coordinates and in some area it is show the rectangle image with cross image in it.. So guys please let me know where is the error or what modification i have to do in it.



public class GmapActivity extends MapActivity {Mapview map;Button btnrefresh;Button btnbacktolist; int chargenumber=0;



/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gmapactivity);

final Bundle bundle = this.getIntent().getExtras();
chargenumber = bundle.getInt("ChargeNumber");
int latitude = bundle.getInt("latitude");
int longitude = bundle.getInt("longitute");
CreateMap(latitude, longitude);

btnrefresh = (Button) findViewById(R.id.btnReload);
btnrefresh.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {

RefreshMap();
}
});

btnbacktolist = (Button) findViewById(R.id.btnBack);
btnbacktolist.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
BacktoScheduleList(bundle);
}
});



}

protected void BacktoScheduleList(Bundle bundle) {

ProgressDialog progressDialog = ProgressDialog.show(this, "",
"Please wait...", true);
bundle = this.getIntent().getExtras();
Bundle Newbundle = new Bundle();
Newbundle.putString("userid", bundle.getString("userid").trim());
Newbundle.putString("username", bundle.getString("username").trim());
Intent intent = new Intent(this, Ok.class);
intent.putExtras(bundle);
startActivityForResult(intent, 0);
progressDialog.dismiss();
finish();

}

private void CreateMap(int latitude, int longitude) {



map = (MapView) findViewById(R.id.mvView);
map.setBuiltInZoomControls(true);
map.setStreetView(true);
List<Overlay> mapOverlays = map.getOverlays();
Drawable drawable = this.getResources().getDrawable(
R.drawable.school_bus);
MOverlayItems itemizedOverlay = new MOverlayItems(drawable, this);
GeoPoint point = null;
point = new GeoPoint(latitude, longitude);
OverlayItem overlayitem = new OverlayItem(point, null, null);
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
MapController mapController = map.getController();
mapController.animateTo(point);
mapController.setZoom(12);

}

protected void RefreshMap() {
map.getOverlays().clear();
map.clearAnimation();
WebServiceCaller webservicecaller = new WebServiceCaller();
String result = webservicecaller.GetLatLong(chargenumber);

if (result.toString().equalsIgnoreCase("false")) {

} else {
StringTokenizer tokens = new StringTokenizer(result, ",");
int latitude = Integer.parseInt(tokens.nextToken());
int longitude = Integer.parseInt(tokens.nextToken());
ProgressDialog progressDialog = ProgressDialog.show(this, "",
"Refreshing. Please wait...", true);
CreateMap(latitude, longitude);
progressDialog.dismiss();
}
}

protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}


}





How to map column names with EF 4.3.1?

I've got problem with simple mapping (using EF 4.3.1 - code first approach)



public class Someclass
{
public virtual int ID { get; set; }
public virtual string Name { get; set; }
}


And Table someclass with int ID and varchar someclass_name.
Now what I want to do is map Name with someclass_name



 modelBuilder.Entity<Someclass>()
.Property(r => r.Name).HasColumnName("someclass_name");


But id doesn't work and exception says: "context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269)."



I've also tried doing that by:



modelBuilder.Configurations.Add(new SomeclassMap());

public class SomeclassMap : EntityTypeConfiguration<Someclass>
{
public SomeclassMap() {
// this.Property(r => r.Name).HasColumnName("someclass_name");
Map(r =>
{
Property(m => m.Name).HasColumnName("restaurant_name");
});
}
}


Can somebody tell me what am I doing wrong? THX





How to disable/enable select field using jQuery?

I would like to create an option in a form like



[] I would like to order a [selectbox with pizza] pizza


where selectbox is enabled only when checkbox is checked and disabled when not checked.



I come up with this code:



<form>
<input type="checkbox" id="pizza" name="pizza" value="yes"> <label for="pizza">
I would like to order a</label>
<select name="pizza_kind">
<option>(choose one)</option>
<option value="margaritha">Margaritha</option>
<option value="hawai">Hawai</option>
</select>
pizza.
</form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
var update_pizza = function () {
if ($("#pizza").is(":checked")) {
$("#pizza_kind").removeAttr("disabled");
}
else {
$("#pizza_kind").prop('disabled', 'disabled');
}
};

$(update_pizza);
$("#pizza").change(update_pizza);
</script>


I tried various methods how to set disabled attribute using .prop(), .attr(), and .disabled=. However, nothing happens. When applying to a <input type="checkbox"> instead of <select>, the code works perfectly.



How to disable/enable <select> using jQuery?





constant for XmlType default namespace

XmlType.namespace returns "##default" as default value.
I want use some jdk constant for "##default" String for more elegant code.
Just do not want to write something like this



if ("##default".equals(type.namespace())) {
...
}


Is there any constant in JDK?





android google maps on a webview

I have a jqueryMobile app that uses google maps api and is working properly on iOS. However, I am not able to get it running on android. I set following permissions on my manifest file. File is loaded properly but I am not able to view the map! Assuming that jqmobile code is working because works on iOS, how to enable it or which steps are required? Thank you.



<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />


my webview class looks like,



 protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);

browse4 = (WebView) findViewById(R.id.webview1);
browse4.getSettings().setJavaScriptEnabled(true);
browse4.getSettings().setUseWideViewPort(true);
browse4.getSettings().setLoadWithOverviewMode(true);
browse4.getSettings().setBuiltInZoomControls(true);
browse4.getSettings().setSupportZoom(true);

browse4.loadUrl("file:///data/data/" + PACKAGE_NAME + "/files/" + "myMap.html");

}




Add or Repalce Text in PHP

I am new In PHP.I have js file look like



   var sites = [
//Texte anime
{url:" http://carouselinfo.com/canal/", duration:9},
//Texte anime
{url:" http://carouselinfo.com/canal-2/", duration:9},
//Intro detallee
{url:"http://carouselinfo.com/index-t1.html", duration:35},
//CTA
{url:"http://carouselinfo.com/index-t2.html", duration:35},

//Football
{url:"http://carouselinfo.com/twitter-ligue/", duration:100},


//Texte anime
{url:" http://carouselinfo.com/canal-2/", duration:9},

//TrailersClub.com
{url:"http://trailersclub.com/?lang=fr", duration:480},

//Heure
{url:"http://carouselinfo.com/heure", duration:8},
//Meteo
{url:"http://carouselinfo.com/meteo", duration:12},
//Texte anime
{url:" http://carouselinfo.com/canal-cine/", duration:9},
//Cine
{url:"http://carouselinfo.com/cine/index-t1.html", duration:150},
//Texte anime
{url:" http://carouselinfo.com/canal-2/", duration:9},
//Heure
{url:"http://carouselinfo.com/heure", duration:8},
];


I want to add text after var site=[ or any line say at 4 lines using php so how can we add.Here is my code of replacing Text on any line.



$lines = array();
foreach( file('source.js') as $line ) {
if ( 'var site=[' === $line ) {
array_push($lines, 'test');
}
array_push($lines, $line);
}

file_put_contents('source.js', $lines);


This code is not working out.





MySQL timestamp not saving in GMT?

I'm using the timestamp data type in MySQL so that any timestamp saved will be converted into GMT, then back from GMT on retrieval. From the documentation, it seems like this is all automatically done for me by MySQL; all I need to do is use the timestamp data type.



However, I noticed that it doesn't seem to work. I've tested this on my local machine and server -- and it seems that it always saves the local time instead of GMT. The local machine and server are in different time zones and neither are in GMT.



Here's my test insert:



INSERT INTO `test` (`test_id`, `stamp`) VALUES (NULL, CURRENT_TIMESTAMP);


Any ideas what I'm doing wrong?





share users actions to facebook

the video sharing site viddy automatically shares what videos you watch to your facebook account. It shows up in the news feed and ticker as you can see in the image below:



How viddy share looks on facebook news feed and ticker



So I am wondering if you could tell me how I would go about setting this up for my website. It is a music site so I would like it to be the same as this except to say "john smith listened to xxxx on beatmushroom" instead of watched.



Any and all tips welcome. Thanks!



Ok I figured part of it out. I made an open graph application and put the meta info onto the website (www.beatmushroom.com). The part i have no clue about is how to then post to facebook when somebody listens to a song.





Google api for trip planning inside my app?

Currently in my app i got a MapView, couple of Geopoints in my map, and the current destination of the user via GPS.



My question is, how can i use Google's route planning API... if is there any?
So i just want to plan routes to the Geopoints from the user's destination.



Any example or tutorial for this ? I only found one but thats not in java.





How to convert Latitud and Longitud to Google GeoPoint?

How to convert Latitud and Longitud to Google GeoPoint?



My Latitud is: 47.523009954564536
My Long is : 19.01667991207027



And when i try to convert to GeoPoints with:



GeoPoint point = new GeoPoint((int)(latitude * 1e6),
(int)(longitude * 1e6));


the results are:
4.7523009E7
1.901671E7



Which is clearly wrong cause im not typing from the Gulf of Guinea (Africa)
I need values tarts with the 47 and 19 integers not 4. and 1. decimals.



I saw this kind of convertation in many pages but somehow its not good for me.
Help please !





ActionScript3: regex expression for password that checks number of characters

I'm trying to use a regex expression in AS3/Flex4.6 to check for passwords meeting the following criteria:




  1. Between 6 and 15 characters

  2. Must contain at least one lower case letter

  3. Must contain at least one upper case letter

  4. Must contain at least one number (e.g 0-9)



So far, here is what I'm using:



<mx:RegExpValidator source="{loginPwd}" property="text" 
expression="^\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*$"
valid="rh(event);" invalid="rh(event);"/>


It does everything except catch password length of 6 to 15 characters. I could use a StringValidator to do this, but I'd rather have the RegExpValidator do both (so that I don't have the situation where multiple error messages are displayed for one TextInput field, e.g. one for each validator).



I've tried the following regex expressions, but while they compile, they do not work (for example, aaAA33 doesn't pass).



expression="((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15})"
expression="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15}"
expression="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,15}^$"
expression="^.*(?=.{6,15})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$"




how to use google maps in android app

I am a new android app developer and i want to use google map in my application.When user clicks on marker it should display address for particular locations.I am usig longitude and latitude.This is my code-
`



    <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>

<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyA5wa4_VHXgAoUA9NOwlW-J-ibOuLc4Yaw&sensor=false">
</script>



<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
function initialize() {
// sample longitude and latitude
var locations = [
['Deolali', 20.022703,73.72811],
['Nasik Road', 20.02929,73.722362],
];
var map_center = new google.maps.LatLng(20.022703,73.72811);
var str='<h2>Deolali,Nasik Road,Nasik</h2>'
var myOptions = {
zoom: 10,
center: map_center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

for (i = 0; i < locations.length; i++) {
var store1 = new google.maps.LatLng(locations[i][1], locations[i][2]);

var infowindow = new google.maps.InfoWindow({
content: str
});



var marker1 = new google.maps.Marker({
position: store1,
map: map,
title:"Store 1"
});

google.maps.event.addListener(marker1, 'click', function() {
map.set_center(store1);
map.set_zoom(16);
marker1.openInfoWindowHtml('here I am');
infowindow.open(map,marker);

});
}


}
</script>

</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>


`
Please help me out.





combo box not loading option on editform using PHP array

I've got a list of records with edit links on them. When i click on the link it takes me to an edit page with the results from the database.



I can retrieve the data successfully for all the text boxes.



I'm trying to implement this via an array which fails to work.



Here is my implementation in code fragments:



        # $data is from $data=mysqli_fetch_array($result)


$product=$data['product'];
echo $product.'<br />';

#initializing array to empty
$product_list=array("Remote"=>" ","TV"=>" ","Box"=>" ");

if (array_key_exists($product,$product_list)){


$product_list["'$product'"] = 'selected="selected" ';


}

print_r($product_list);


#combo box

<select name="products">
<option value="select">Select</option>
<option value="Remote"<?php echo @$product_list["'$product'"] ?>>Remote</option>
<option value="TV" <?php echo @$product_list["'$product'"] ?>> TV</option>
<option value="Box" <?php echo @$product_list["'$product'"] ?>> Box</option>
</select>


In the page that displays all the records if i hit edit on a record that has product 'Remote' i get the following output(as per echo statements above):



Remote
Array ( [Remote] => [TV] => [Box] => ['Remote'] => selected="selected" )


The HTML form displays:



 <select name="products">                   
<option value="select">Select</option>
<option selected="selected" value="Remote">Remote</option>
<option selected="selected" value="TV"> TV</option>
<option selected="selected" value="Box"> Box</option>
</select>


In the edit page if i select a record that has product 'TV' i get the following output:



 TV
Array ( [Remote] => [TV] => [Box] => ['TV'] => selected="selected" )


HTML output is same as above. And it always sets the option to the last product which is 'Box'.



Can somebody please advise on how i can fix this? thanks!





Simple PHP chat quirk

I've been working on a quick and simple jQuery/PHP chat to put in my website for the visitors to communicate. I've extimated peaks of 200 simultaneous website users (connected users) with at most 10-20 people actually chatting.



Here's the quirk:



As I experienced already twice (thought it seems to be rather an unlikely event more than something happening after you perform something specific) the chat happens to load multiple messages which have already been red and display them.



Trying to keep the chat system as simple as possibile I came up with this code:






HTML CODE:



<div class="chat">

<ul class="chat">

<li class="chat" >

<h5 class="chat">Date</h5>
<h6 class="chat">Time</h6>
<h4 class="chat">User</h4>
<br/>
<q class="chat">Message</q>

</li>

</ul>

<input class="chat" placeholder="write something..."/>

</div>


As you can see I put a placeholder li element for the jQuery to take and use as a snippet to create new li elements with the actual messages and prepend them inside the ul element.






jQuery CODE:



Sending messages:



$(document).ready(function(){

chatSnippet = $('ul.chat').html(); // here chatSnippet is a global variable
$('ul.chat').html('');

$('input.chat').change(function(event){// Send your message

message = $(this).attr('value');

// first thing I perform an asynchronous POST to the receiving php script

$.post(

'php/chatRec.php',

{

user : currentUser,
message: message,

}

);

// meanwhile I add a new li element to the chat html with the content just submitted


date.setTime(event.timeStamp);

hours = ''+date.getHours();

if(hours.length < 2) hours = '0'+hours;

minutes = ''+date.getMinutes();

if(minutes.length < 2) minutes = '0'+minutes;

day = ''+date.getDate();

if(day.length < 2) day = '0'+day;

newChatMessage = chatSnippet.replace('Date', ''+day+' '+months[date.getMonth()]);
// here months is an array with the months names (in italian)
newChatMessage = newChatMessage.replace('Time', ''+hours+':'+minutes);

newChatMessage = newChatMessage.replace('User', connectedUser);

newChatMessage = newChatMessage.replace('Message', message);

$mess = $(newChatMessage);

$mess.hide().prependTo('ul.chat').fadeIn(500);

$(this).attr('value','');

});

refreshChat(''); // this function retrives new messages from the DB

// Here I perform a void refreshChat call so I'll get all the messages in the DB regardless from the currentUser (at page refresh)

});


Receiving messages:



// This code is placed outside (before) the .ready function

function refreshChat(user){// Receiving messages

$.post(

'php/chatInv.php',

{

user : user,
token: lastMessage // this variable contains the token of the last red message

},

function(data){

receivedMessages = jQuery.parseJSON(data);

for(message in receivedMessages){

message = receivedMessages[message].Message;

date = receivedMessages[message].Day.split('-');
time = receivedMessages[message].Time.split(':');

newChatMessage = chatSnippet.replace('Date', ''+date[2]+' '+months[parseInt(date[1])-1]);

newChatMessage = newChatMessage.replace('Time', ''+time[0]+':'+time[1]);

newChatMessage = newChatMessage.replace('User', receivedMessages[message].Sender);

newChatMessage = newChatMessage.replace('Message', message);

$mess = $(newChatMessage);

$mess.hide().prependTo('ul.chat').fadeIn(500);

lastMessage = receivedMessages[messages].token;

}

nextRefresh = setTimeout("refreshChat('"+currentUser+"')",2000);

// When I'm done I set a timeout of 2 secs and then perform another refresh

}

);

}





PHP CODE:



Receive a new message (I think the issue is in here):



    mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("chat") or die(mysql_error());

$characters = array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');

$token = $characters[rand(0,61)].$characters[rand(0,61)].$characters[rand(0,61)].$characters[rand(0,61)].$characters[rand(0,61)];

$all_Msgs = mysql_query("SELECT * FROM Messages ORDER BY ID");

$prev_Msg = array('ID' => 1 , 'Sender' => $_POST['user'], 'Message' => $_POST['message'], 'Day' => date("Y-m-d"), 'Time' => date("H:i:s"), 'token' => $token);

while($Msg = mysql_fetch_array($all_Msgs)){

$update_success = mysql_query("UPDATE Messages SET Sender='".$prev_Msg['Sender']."', Message='".$prev_Msg['Message']."', Day='".$prev_Msg['Day']."', Time='".$prev_Msg['Time']."', token = '".$prev_Msg['token']."' WHERE ID=".$Msg['ID']);

$prev_Msg = $Msg;

}


Basically what I do here is receive the new post message, generate a token and an array element (which is itself an array) containing the new entered datas, done this I perform a seuqence of UPDATE statements on a fixed size SQL table overriding the new datas on the first record and then overriding each record with the previous one (so that the last record will be finally lost).



Sending messages:



    mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("chat") or die(mysql_error());

$receiver = $_POST['user'];
$token = $_POST['token'];

$all_Msgs = mysql_query("SELECT * FROM Messages ORDER BY ID");

$newMessages = array();

while($Msg = mysql_fetch_array($all_Msgs)){

if($Msg['token'] == $token) break;

if($Msg['Sender'] != $receiver) array_unshift($newMessages,$Msg);

}

echo json_encode($newMessages);


So I send the client the JSON encode of an array of all the records in the DB inserted after the last known message and whose author was not the querying client.






My suspects:



I came to the conclusion that when the message reception (server side) is being performed there is a time span when each message is taken from the DB, if a refresh is being performed in the meanwhile the message is not found and if that message was the one we were looking for as the last red message then the server will just select all the messages in the table and send them back.



The result is you see a bunch of messages you already red without your messages in between (cuz they were added to the view client side and the server script doesn't send you back your own messages)



Stated that:




  • I don't care if the messages aren't exactly in the actual insertion order: let's say A and B are chatting, the actual real messages order is BAB, but A may se the order ABB for his view is immediatly updated at input time (this helps me keep a 'fast-realtime' feel)

  • I don't care if some message is lost (like if it falls over the fixed DB table edge before someone can read it)

  • At this time I don't care much about actual efficency, speed and optimization

  • I know I should probalby handle the message insertion differently adding the new record and then updating the IDs only and delete the last record out. But if possible I'd like to keep this UPDATE-only fashion.



do you think my interpretation of the problem is right?
If not: what would then be the cause? / how can I fix that?
If yes: how can I fix that easily?



If the actual fix is rather complex: how actually likely to happen would be this quirk in a 10-20 users chat?



Thanks





SQL Query for Student mark functionality

Got this as an interview question from Amazon to test basic SQL skills and I kind of flopped it. Consider the following tables:



Student - Stid, Stname, Details
Subject - Subid, Subname
Marks - Stid, Subid, mark


Write a query to print the list of names of students who have scored the maximum mark in each subject.



The wrong answer which I gave was:



select A.Stname from A as Student, B as 
(select Stid, Subid, max(mark) from Marks groupby mark) where A.Stid = B.Stid


I was thinking you can have a table B in which you can get the top marks alone and match it with the names in the student table A. But turns out my "groupby" is wrong.



One more variation of the question which I felt was can be asked is that, if there is more than one student having the highest mark in a subject, even their names should be included.



Can you please help solve these queries. They seem to be simple, but I am not able to get a hang of it.



Thanks!





android - out of memory exception when creating bitmap

I am getting the following error after creating bitmap second time around:



04-17 18:28:09.310: ERROR/AndroidRuntime(3458): java.lang.OutOfMemoryError: bitmap size exceeds VM budget

this._profileBitmap = Bitmap.createBitmap(_profileBitmap, xCoor, yCoor, width, height);


From log:



04-17 18:27:57.500: INFO/CameraCropView(3458): Original Photo Size: W 1536 x H 2048   
04-17 18:28:06.170: INFO/CameraCropView(3458): xCoor: 291
04-17 18:28:06.170: INFO/CameraCropView(3458): yCoor: 430
04-17 18:28:06.170: INFO/CameraCropView(3458): Width: 952
04-17 18:28:06.170: INFO/CameraCropView(3458): Height: 952


Since the image is huge I get the error. But the interesting thing is the error does not happen the first time, only when I take the picture the second time, which makes me believe this profileBitmap is NOT destroyed. How do I clean this up?





Why after rotating UIImageView size is getting changed?

I'm new in using transformations. And still confusted how they are working.



What I'm trying to do, is to rotate my UIImageView with given angle. But after rotating, it's changing the size of image, getting smaller. I'm also doing scaling for ImageView so it won't be upside down.How to rotate and keep the size, that was given in CGRectMake, when ImageView was allocated ?



    UIImageView *myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x,y,width,height)];        

myImageView.contentMode = UIViewContentModeScaleAspectFit;

[myImageView setImage:[UIImage imageNamed:@"image.png"]];

myImageView.layer.anchorPoint = CGPointMake(0.5,0.5);

CGAffineTransform newTransform;

myImageView.transform = CGAffineTransformMakeScale(1,-1);

newTransform = CGAffineTransformRotate(newTransform, 30*M_PI/180);

[self.window addSubview:myImageView];


Thanks a lot!





String was not recognized as a valid DateTime

I know such questions are in ton in SO but my situation seems little weird to me.



I have a textbox with a calendar extender control on my aspx page



Default format is "d" in extenders date format property.
When I choose my date say 15th May 2012 from the calendar,it gives me 5/15/2012, which is fine.



Since its a string and my db field is oftype datetime, so I am using



Convert.ToDateTime(TextBox.Text);   // TextBox.Text = 5/15/2012


But it throws the exception,
string was not recognized as valid datetime.



I then Change the code and used DateTime.Parse() but the issue remains. Then i tried to reformat the date something like this,



Convert.ToDateTime(string.Format("0:MM-dd-yyyy",TextBox.Text)).Date



but still its throwing exceptions..



Please help me.





GeoCoder AsyncTask doesn't update TextView in background

Scenario:



So what I have done so far is Created an AsyncTask to handle my GeoCoder that updates every 3 min (for testing purposes). Then I set up a TimerTask that shows a toast message with the users current Address every 4 minutes. (TimerTasks not included in code)



So heres the problem:



When I am in my app, everything is fine, however when my app is running in the background, the Toast messages stay stuck at whatever address the app was last set at before I exited my app. I know for sure that the AsyncTask does run in the background (Checked LogCats) and it seems like everything is running in the background fine, I just cant display the current address on my Toast.



All thoughts and inputs will be appreciated!



Here is my code:



 public class statuspage extends MapActivity {

LocationManager locationManager;
MapView mapView;
Criteria criteria;
Location location;
Geocoder gc;
Address address;

String bestProvider;
String LOCATION_SERVICE = "location";
String addressString = "Searching for Nearest Address";
StringBuilder sb;

private MapController mapController;
private MyLocationOverlay myLocation;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.statuspage);

// Get Mapping Controllers etc //
mapView = (MapView) findViewById(R.id.mapView);
mapController = mapView.getController();
mapController.setZoom(17);
mapView.setBuiltInZoomControls(true);

// Add the MyLocationOverlay //
myLocation = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocation);
myLocation.enableCompass();
myLocation.enableMyLocation();

// Animates the map to GPS Position //
myLocation.runOnFirstFix(new Runnable() {
@Override
public void run() {
mapController.animateTo(myLocation.getMyLocation());

}
});
}

@Override
protected boolean isRouteDisplayed() {

// Location Manager Intiation
locationManager = (LocationManager) statuspage.this
.getSystemService(LOCATION_SERVICE);
criteria = new Criteria();

// More accurate, GPS fix.
criteria.setAccuracy(Criteria.ACCURACY_FINE); // More accurate, GPS fix.
bestProvider = locationManager.getBestProvider(criteria, true);

location = locationManager.getLastKnownLocation(bestProvider);
updateWithNewLocation(location);

locationManager.requestLocationUpdates(bestProvider, 60000, 10,
locationListener); // 1800000 = 30 Min

return false;
}

class GeoCoder extends AsyncTask<Void, Void, Void> {

String lat = "Acquiring";
String lng = "Acquiring";

@Override
protected Void doInBackground(Void... params) {
if (location != null) {

/**
* double latitude = myLocation.getMyLocation().getLatitudeE6();
* double longitude =
* myLocation.getMyLocation().getLongitudeE6();
*/

double latitude = location.getLatitude();
double longitude = location.getLongitude();

lat = "" + latitude;
lng = "" + longitude;

// gc = new Geocoder(statuspage.this, Locale.getDefault());
Geocoder gc = new Geocoder(getApplicationContext(),
Locale.getDefault());
try {

List<Address> addresses = gc.getFromLocation(latitude,
longitude, 1);

sb = new StringBuilder();
if (addresses != null && addresses.size() > 0) {
address = addresses.get(0);

int noOfMaxAddressLine = address
.getMaxAddressLineIndex();
if (noOfMaxAddressLine > 0) {
for (int i = 0; i < address
.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append(
"\n");
}
addressString = sb.toString();

}
}
} catch (Exception e) {

addressString = "Sorry, we are trying to find information about this location";
}

}
return null;
}


@Override
protected void onPostExecute(Void result) {
TextView scrollview = (TextView) findViewById(R.id.scrollview);

// Latitude and Longitude TextView
TextView etlongitude = (TextView) findViewById(R.id.etlongitude);
TextView etlatitude = (TextView) findViewById(R.id.etlatitude);

// TextView to display GeoCoder Address
scrollview.setGravity(Gravity.CENTER);
scrollview.setText("Your location:" + "\n"
+ "(Accurate to 500 meters)" + "\n" + (addressString));

Log.d("Address", (addressString));

// Latitude and Longitude TextView Display Coordinates //
etlongitude.setText(lng);
etlatitude.setText(lat);

// Log.d("GeoCoder", "In-Task");

return;
}




DefaultBufferMaxRows is not changing in ssis

Can any one tell,what is the reason the DefaultBufferMaxRows is automaticaly changing to 10000 when i run the package through BIDS.My package contains only one source,lookup,destination tasks.total 100000 records i want to insert into destination table by doing lookup to same destination table(non matched record).total 5 columns are passing,all are the type of int.
Actually i have increased the DefaultBufferMaxRows to 50000 before running the package and all other settings are default.What is the reason?





PHP date_create function, converting UTC time to different timezone using the timezone abbrev

instead of converting it to America/New_York time this produced a UTC time that i have stored in my database, why is this, why didnt it convert the time? it is stored in db as 2012-05-13 07:30:47



$placename=America/New_York

$date = date_create($list['stamp'], timezone_open($placename));
echo date_format($date, 'F d g:i a');




adjust and set avialable zoom between two ponts which having route in android maps

I am displaying route between two points on the map. But here I want to adjust that two points on the display as applying zoom based on the locations.
like the image....enter image description here



can anyone help me on this. thanks...





In Objective-C, we can put the instance variables in the @implementation section?

I have always put the instance variables in the interface .h file, but just saw some code doing this:



@implementation Fraction  {
int numerator;
int denominator;
}


which is to move the instance variables to the implementation side. It works too, but since when can we do it (or can we always do it with Objective-C), and I suppose it is better because what instance variables we use is not really part of an interface.





Puppet: install Rubygem-package on a machine without Rubygems preinstalled

On a clean Debian system - without Rubygems installed - I want to install a Rubygem package with Puppet. So the package has "gem" as package Provider.



This is my manifest so far (I kept it simple):



# test.pp
Package { ensure => 'installed' }

package {
'rubygems' :
name => 'rubygems',
}

package {
'libldap-ruby1.8' :
name => 'libldap-ruby1.8',
}

package { 'libldap2-dev' :
name => 'libldap2-dev',
}

package { 'libsasl2-dev' :
name => 'libsasl2-dev',
}

package { 'libsasl2-modules-ldap' :
name => 'libsasl2-modules-ldap',
}

# My Rubygem, with Provider type 'gem'
package {
'ruby-ldap' :
name => 'ruby-ldap',
provider => 'gem',
}

Package [ 'rubygems' ] -> Package [ 'ruby-ldap' ]
Package [ 'libldap2-dev' ] -> Package [ 'ruby-ldap' ]
Package [ 'libsasl2-modules-ldap' ] -> Package [ 'ruby-ldap' ]


When I test this manifest (with puppet apply --noop test.pp), I'm getting the following output:



err: /Stage[main]//Package[ruby-ldap]: Provider gem is not functional on this host


I digged through the net and found some informations about Puppet+Rubygems (for example this) but none of these helped me to solve my problem as none provided a real solution with some code.



I also tried using classes and stages (doing the rubygem install in a stage before the gem install) but I always got the Provider gem-error (but maybe I just used the stages in a wrong way).



Can anyone provide me a working manifest which installs rubygems and any rubygem on a system without Rubygems, or at least the final hints how to get there?





In which condition the onDraw method of View to be called repeatedly in Android?

I implement a view by myself, the onDraw method of the view is called repeatedly. This will cause a serious performance problem. The code is so complex that I can't paste here. Anyone can tell me some possible reasons? I haven't touch the view by my finger.