Thursday, April 12, 2012

Removing an Item From a Priority Queue Based on a Linked List

I'm attempting to create a PriorityQueue class in Java implemented via a Linked List. In the queue, objects with different priorities will be added to the end of the list in no particular order, so that adding an element would be O(1) and removing an element with the highest priority would be O(n). However, I'm having difficulty writing the remove method. I've created a "removeHighestPriorityNode" method in my Linked List class, but I am stuck. This is what I have thus far:



public void removeHighestPriorityNode()
{
if(head == null)
{
throw new NoSuchElementException();
}
else if (head.next != null)
{
Node<E> previous = head;
Node<E> current = head.next;
Node<E> highestPriority = head;

while(current != null)
{
if (current.priority > previous.priority)
{
highestPriority = current;
}

previous = current;
current = current.next;
}
}
else
{
clear(); //Clears the list
}
}


Finding the node with the highest priority is no problem, but finding a way to switch the pointer (next) from the node before the one with the highest priority to the one after is what I'm having trouble with. Also, this is my first time posting on this site, so if I am being to vague in any way, please let me know. Any help would be greatly appreciated! Thanks.





Java Program read input from a text file and modify it accordingly

I am trying to create a java file that takes in a .txt file and produces another file according to the input.



More information would be the .txt file looks like this.



url = http://184.154.145.114:8013/wlraac name = wlr samplerate = 44100 channels =2 format = S16le~
url = http://newstalk.fmstreams.com:8080 name = newstalk samplerate = 22050 channels = 1 format = S16le


so far all i have is the program allows me to go select a file and when i do select the file it displays what the text file contains



the program needs to this
create the another file with this information with the following modificiations
if the samplerate is not 44100 it changes it to 44100
and if the channels are not one it changes them to 1
then it gets rid of the following parts completely url = name = and so forth
Is this possible and if so any help would be appreciated



Thanking You





Exploding text form lines into an array

I have a script that pulls in the Google Pagerank for inputted URLs.



I have tried editing the script so that instead of only being able to put 3 urls in you can paste a list of URL's in.



Unfortuantly when I past some URL's in it just puts them next to each other and doesn't display the Pagerank.



If you want to test it and see you can find it here: http://php-playground.co.cc/testdir/pagerank.php



(people have been reporting a virus on the URL but its only because its a co.cc domain, do not click if you are worried :)



Here is the code:



<?php
//If the form was submitted
if(isset($_GET['url[]'])){
//Put every new line as a new entry in the array
$url = explode("\n",trim($_POST["url[]"]));
}

echo "$url";
?>
<?php
function fetch_google_page_rank($url) {
$url = strstr($url,"http://")? $url:"http://".$url;
$fp = fsockopen("toolbarqueries.google.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET /tbr?client=navclient- auto&ch=".CheckHash(HashURL($url))."&features=Rank&q=info:".$url."&num=100&filter=0 HTTP/1.1\r\n";
$out .= "Host: toolbarqueries.google.com\r\n";
$out .= "User-Agent: Mozilla/4.0 (compatible; GoogleToolbar 2.0.114-big; Windows XP 5.1)\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);

while (!feof($fp)) {
$data = fgets($fp, 128);
$pos = strpos($data, "Rank_");
if($pos === false){} else{
$pagerank = substr($data, $pos + 9);
}
}
fclose($fp);
return (int)$pagerank;
}
}

function StrToNum($Str, $Check, $Magic) {
$Int32Unit = 4294967296; // 2^32
$length = strlen($Str);
for ($i = 0; $i < $length; $i++) {
$Check *= $Magic;
if ($Check >= $Int32Unit) {
$Check = ($Check - $Int32Unit * (int) ($Check / $Int32Unit));
$Check = ($Check < -2147483648)? ($Check + $Int32Unit) : $Check;
}
$Check += ord($Str{$i});
}
return $Check;
}

function HashURL($String) {
$Check1 = StrToNum($String, 0x1505, 0x21);
$Check2 = StrToNum($String, 0, 0x1003F);
$Check1 >>= 2;
$Check1 = (($Check1 >> 4) & 0x3FFFFC0 ) | ($Check1 & 0x3F);
$Check1 = (($Check1 >> 4) & 0x3FFC00 ) | ($Check1 & 0x3FF);
$Check1 = (($Check1 >> 4) & 0x3C000 ) | ($Check1 & 0x3FFF);
$T1 = (((($Check1 & 0x3C0) << 4) | ($Check1 & 0x3C)) << 2 ) | ($Check2 & 0xF0F );
$T2 = (((($Check1 & 0xFFFFC000) << 4) | ($Check1 & 0x3C00)) << 0xA) | ($Check2 & 0xF0F0000 );
return ($T1 | $T2);
}

function CheckHash($Hashnum) {
$CheckByte = 0;
$Flag = 0;
$HashStr = sprintf('%u', $Hashnum) ;
$length = strlen($HashStr);
for ($i = $length - 1; $i >= 0; $i --) {
$Re = $HashStr{$i};
if (1 === ($Flag % 2)) {
$Re += $Re;
$Re = (int)($Re / 10) + ($Re % 10);
}
$CheckByte += $Re;
$Flag ++;
}
$CheckByte %= 10;
if (0!== $CheckByte) {
$CheckByte = 10 - $CheckByte;
if (1 === ($Flag % 2) ) {
if (1 === ($CheckByte % 2)) {
$CheckByte += 9;
}
$CheckByte >>= 1;
}
}
return '7'.$CheckByte.$HashStr;
}
// Google PR Finder END



?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>GET Google PR</title>

<style type="text/css">
<!--
body,td,th {
font-family: Verdana, Geneva, sans-serif;
font-size: 11px;
color: #333;
}
body {
margin-left: 20px;
margin-top: 20px;
}
pre{ font-size:15px;}
-->
</style></head>
<body>

<h2>Google PR</h2>
<p>Enter your URLs </p>
<form action="" method="POST">
<p>
<textarea name="url[]" rows="10" cols="50"></textarea>
<!--<input name="url[]" type="text" id="url[]" value="http://" size="80" /><br />
<input name="url[]" type="text" id="url[]" value="http://" size="80" /><br />
<input name="url[]" type="text" id="url[]" value="http://" size="80" /><br />-->
</p>
<p><input name="findpr" type="submit" value="Find Google PageRank" />
<br />
<br />
</p>
</form>
<table>
<pre>
<?php
if(isset($_POST['findpr']))
{
foreach($_POST['url'] as $key => $url)
{
if( $_POST['url'][$key]!="http://")
echo "<td><b>PR:</td><td>" . fetch_google_page_rank($_POST['url'][$key]) . " </td><td></b>&raquo;</td><td>" . $_POST['url'][$key]."</td></tr><br />";
}
}
?>
</pre>
</table>
</body>
</html>




Remove excessive whitespace in user input field

In my controller method for handling a (potentially hostile) user input field I have the following code:



string tmptext = comment.Replace(System.Environment.NewLine, "{break was here}"); //marks line breaks for later re-insertion
tmptext = Encoder.HtmlEncode(tmptext);
//other sanitizing goes in here
tmptext = tmptext.Replace("{break was here}", "<br />");

var regex = new Regex("(<br /><br />)\\1+");
tmptext = regex.Replace(tmptext, "$1");


My goal is to preserve line breaks for typical non-malicious use and display user input in safe, htmlencoded strings. I take the user input, parse it for newline characters and place a delimiter at the line breaks. I perform the HTML encoding and reinsert the breaks. (i will likely change this to reinserting paragraphs as p tags instead of br, but for now i'm using br)



Now actually inserting real html breaks opens me up to a subtle vulnerability: the enter key. The regex.replace code is there to strip out a malicious user just standing on the enter key and filling the page with crap.



This is a fix for big crap floods of just white but still leaves me open to abuse like entering one character, two line breaks, one character, two line breaks all down the page.



My question is for a method of determining that this is abusive and failing it on validation. I'm scared that there might not be a simple procedural method to do it and instead will need heuristic techniques or bayesian filters. Hopefully, someone has an easier, better way.



PS: I can do the described abuse in the editor window here, it appears in the preview box at least, I'm not going to check if it will make it on to the site.





iphone. making UITextView but won't make it visible

@interface SomeViewController : UIViewController <UITextViewDelegate>

@property (retain, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic, retain) UIImage *image;

@property (nonatomic, retain) IBOutlet UITextView *textView;


I need textview(editable) in my view controller.



so I set protocol , then textView to delegate my file's owner, done.



and also, IB to the file's owner, too. (I don't know, is it unnecessary?)



And my .m file.... viewDidLoad..



_textView = [[UITextView alloc]init];
[_textView setFrame:CGRectMake(8, 110, 304, 82)];
[_textView setFont:[UIFont boldSystemFontOfSize:12]];
_textView.editable = YES;
//[textView setText:@"hdgffgsfgsfgds"];// if uncommented, this actually visible...

[self.view insertSubview:_textView atIndex:2];


So far, it's working. But I want these methods to run...



- (void)textViewDidChange:(UITextView *)textView
{


if([_textView.text length] == 0)
{
_textView.text = @"Foobar placeholder";
_textView.textColor = [UIColor lightGrayColor];
_textView.tag = 0;
}
}


But after build, my textview is still empty.



What did I wrong?





unix - breakdown of how many lines with number of character occurrences

Is there an inbuilt command to do this or has anyone had any luck with a script that does it?



I am looking to get counts of how many lines had how many occurrences of a specfic character. (sorted descending by the number of occurrences)



For example, with this sample file:



gkdjpgfdpgdp
fdkj
pgdppp
ppp
gfjkl


Suggested input (for the 'p' character)



bash/perl some_script_name "p" samplefile



Desired output:



occs     count
4 1
3 2
0 2




UIImage or UIImageView with paging and zoom on click

I have a UIView in which I get certain information about a user, wthin a bunch of textfields and a bunch of photos of him, if available.



No Im a bit limited here, so I must have a UIImage or UIImageView on my View (only the first half of my view, to display this images.



Up to now I have a array of this images in the background and as soon as the user swipe over the UIImageView, the image shows the next.
But it's ugly, becuase there is no real paging (you know, see the second image in pieces while you swipe, at the moment its only a UIMageView.Image = xxx and its ugly) and no zooming (zoom on click).



Any idea to solve this?





How to create a vector of integers with structure()?

I don't seem to be able to produce a vector of integers using structure().



> x <- structure(c(1,2), class='integer', mode='integer', storage.mode='integer')
> paste(class(x), mode(x), storage.mode(x), is.integer(x))
[1] "integer numeric double FALSE"


Compare with a true vector of integers:



> y <- as.integer(c(1,2))
> paste(class(y), mode(y), storage.mode(y), is.integer(y))
[1] "integer numeric integer TRUE"


Any idea?





Difference between GStreamer 0.10 Library Reference Manual and GStreamer 0.10 Core Reference Manual

I am just going through the gstreamer documentation.I couldnt understand the difference between the GStreamer 0.10 Library Reference Manual and GStreamer 0.10 Core Reference Manual.Most of the fuinction calls like gst_X_funtion_name cab be interpreted from the GStreamer 0.10 Core Reference by checking the Gst_X documentation.But why GStreamer 0.10 Library Reference Manual is used and where it is used.
Plz elaborate.
Rgds
Softy





What things should I consider when I get an intermittent exception in Visual Basic .net (debugging in Visual Studio Express 2010)?

I'm testing my Visual Basic .net application by running it in Visual Studio express.



Sometimes it runs OK, but other times I get an exception (details below, if useful). I'm not sure why I get the exception as the particular part of the application that I am testing re-uses code that works OK for other features.



What should I check, what would give me a hint as to the root cause.



Things I tried so far are:




  • Rewriting some of the code to be more robust. The outcome of this was that this approach was getting out of control - I was correcting everything. I made changes such asing alternative libraries (e.g. replacing CInt with convertTo etc). Some lazy declarations, but it occurred to me that there was no problem with these with the code before my changes. And every change I seemed to solve uncovered yet another problem, another different exception

  • So I thought something must be fundamentally wrong with my installation, and a search found discussion group posts from people experiencing something similar. The suggested remedy would be to re-install the .net framework. So I did that and the problems still occured.



Any thoughts on approach to get to the root of the problem? I'm not asking for a solution but some fresh ideas would be very welcome.



Update:



I've added in the following code to get more detail (+1 thanks @Meta-Knight)



        Dim exceptionMessage As String = ex.Message
Console.WriteLine("Message: \n" & exceptionMessage)
Dim exceptionTargetSite As String = ex.TargetSite.ToString
Console.WriteLine("Inner: \n" & ex.TargetSite.ToString)
Dim exceptionSource As String = ex.Source
Console.WriteLine("Source\n:" & exceptionSource)
' put the stack trace into a variable
' (this helps debugging - put a break point after this is assigned
' to see the contents)
Dim stackTrace As String = ex.StackTrace.ToString()
Console.WriteLine("Stack trace\n:" & stackTrace)


More details about exception



Error - Exception Message
"Arithmetic operation resulted in an overflow."



Exception Target Site:
"Int32 ToInteger(System.String)"



Exception Source:
"Microsoft.VisualBasic"




at Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String Value) at MyCo_3rd-Party-Industrial-Printing-System.Customer_EanUpc_serialNumberGeneratorAssembly.btnPrint_Click(Object sender, EventArgs e) in C:\labelprint\MyCo 3rd-Party-Industrial-Printing-System v2\MyCo 3rd-Party-Industrial-Printing-System\PrintForms\Customer_EanUpc_serialNumberGeneratorAssembly.vb:line 271 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.PerformClick() at System.Windows.Forms.Form.ProcessDialogKey(Keys keyData) at System.Windows.Forms.Control.ProcessDialogKey(Keys keyData) at System.Windows.Forms.Control.PreProcessMessage(Message& msg) at System.Windows.Forms.Control.PreProcessControlMessageInternal(Control target, Message& msg) at System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg) at System.Windows.Forms.Application.ThreadContext.System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FPreTranslateMessage(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.RunDialog(Form form) at System.Windows.Forms.Form.ShowDialog(IWin32Window owner) at System.Windows.Forms.Form.ShowDialog() at MyCo_3rd-Party-Industrial-Printing-System.utlForm.openNewModalForm(String form) in C:\labelprint\MyCo 3rd-Party-Industrial-Printing-System v2\MyCo 3rd-Party-Industrial-Printing-System\Utilities\utlForm.vb:line 128






not able to submit in-app purchase products to apple

I have just created an iPhone application and submitted it to Apple store. The application have been approved by apple and is available in Apple store. The application uses in-app purchase. I had tested the in-app purchase using test user account. Now I want to submit the in-app purchase products for review. The status of these products is ready to submit in itunesConnect. When I open up these products, I can see the button Submit for Review but it is grayed out i.e, it is disabled. Now how will I submit the in-app purchase.



I have downloaded the application from apple store but when I open it, it crashes probably because the in-app purchase haven't been submitted as yet. Can someone please help me? I am kind of stuck and afraid someone might give a negative review to my app because of this. Someone please help me.



Thanks
Pankaj





Dynamically control location tracking (registering / unregistering location broadcast receiver). How?

I want to dynamically control location tracking (registering / unregistering location broadcast receiver). This is how I am planning to do it. I have two questions :




  1. What are the mistakes in the implementation below because all this concept is still very theoretical to me as I am very new to android/java dev. Still building concepts!


  2. How do I pass some EXTRA_INFO from my location library class to the location receiver.




IMPLEMENTATION:



I have a library class LocationLibrary.java which consists of two methods. They do as the name suggest. The location tracking should start when I call startTracking(). Plz note the extraInfo that needs to be passed to myLocationReceiver. The tracking should stop when stopTracking() is called.



Code snippet:



public class LocationLibraray
{
private static BroadcastReceiver myLocationReceiver;

public LocationLibraray(Context context)
{
this.ctx = context;
myLocationReceiver = new MyLocationReceiver();
}

public void startTracking(Context context, String extraInfo)
{
IntentFilter filter = new IntentFilter();
filter.addAction("com.app.android.tracker.LOCATION_READY");
context.registerReceiver(myLocationReceiver, filter);

// NEED TO PASS extraInfo to myLocationReceiver for some processing, but HOW?
}

public void stopTracking(Context context)
{
context.unregisterReceiver(locationReceiver);
}


}



MyLocationReceiver.java



public class MyLocationReceiver extends BroadcastReceiver  {

public void onReceive(final Context context, Intent intent) {
if ((intent.getAction() != null) &&
(intent.getAction().equals("com.app.android.tracker.LOCATION_READY")))
{
//GET THAT EXTRA INFO FROM LocationLibrary class and process it here
}
}
}


Please help me out. Thnx!





Facing in Android Video searching application

I could not understand the the fifth part of the "Android Full Application Tutorial" series
that where I declare the code in the package of android project, I am new to developing the software and wand to complete code for the part of the series tatorials



 ...
Intent intent =
new Intent(MovieSearchAppActivity.this, MoviesListActivity.class);
intent.putExtra("movies", result);
startActivity(intent);
...

...
public class Movie implements Serializable
...
public class Person implements Serializable
...
public class Image implements Serializable
...

...
<activity android:name=".MoviesListActivity" />
...




jquery effect works in jfiddle but not online - help please

Still trying to solve this after many hours. The script works in jfiddle: http://jsfiddle.net/uCcYw/3/ ,apply flash effect to parent of add_item (simplecart_shelfitem), but not online: http://www.diysoakwells.com.au/test.html. Its the same code copied and pasted, i dont get it !! PLease help : )





How to recursively append cells?

I have an Excel sheet that looks like this:



ID        PARENTID        VALUE                  RESOLVED VALUE (how to generate this?)
=======================================================================================
0 0 /root /root
1 0 /one /root/one
2 1 /two /root/two
3 1 /three /root/three
4 3 /child-one-of-three /root/three/child-one-of-three
5 3 /child-two-of-three /root/three/child-two-of-three


Each row has an ID and a PARENTID. I want to generate the content of the last column, RESOLVED VALUE by resursively append the VALUE of each row.



How can I do this in Excel?





How do I get my selected gridview rows into a javascript variable?

I use ASP.NET C# MVC3 with razor templates and I want to know the following:



I have a devexpress gridview in which I can select rows.
When selected I want to pass them into a javascript variable. How do I do this?
And what if I have selected multiple rows at the same time, can I get them in an array or something?



Regards,



Marco





"Client-Side Authentication Example" on Chrome for OS X does not work (error=unknown_user)

Original Post:



I am trying to use the "Client-side Authentication with the Javascript SDK" on Chrome for OS X (17.0.963.83). The code is copied directly from the Facebook example (with the YOUR_APP_ID updated):



<!DOCTYPE html>
<html>
<head>
<title>Facebook Client-side Authentication Example</title>
</head>
<body>
<div id="fb-root"></div>
<script>
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));

// Init the SDK upon load
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : '//'+window.location.hostname+'/channel', // Path to your Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});

// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
FB.api('/me', function(me){
if (me.name) {
document.getElementById('auth-displayname').innerHTML = me.name;
}
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});

// respond to clicks on the login and logout links
document.getElementById('auth-loginlink').addEventListener('click', function(){
FB.login();
});
document.getElementById('auth-logoutlink').addEventListener('click', function(){
FB.logout();
});
}
</script>

<h1>Facebook Client-side Authentication Example</h1>
<div id="auth-status">
<div id="auth-loggedout">
<a href="#" id="auth-loginlink">Login</a>
</div>
<div id="auth-loggedin" style="display:none">
Hi, <span id="auth-displayname"></span>
(<a href="#" id="auth-logoutlink">logout</a>)
</div>
</div>

</body>
</html>


When I click on "Login", the Facebook pop-up window appears. I click on "Log In with Facebook", the pop-up disappears, and the "auth-loggedin" div appears along with my name and the logout link. However, when I refresh the page, the page loses its Facebook authorization status and returns to the logged-out state.



The expected behavior would be for the page to remain in the logged-in state.



Using the console, I noticed that the fbsr cookie appears temporarily, and disappears once the page is refreshed. In addition, the following error is caught in the console:




Unsafe JavaScript attempt to access frame with URL https://s-static.ak.fbcdn.net/connect/xd_proxy.php#cb=f16adb7b1c&origin=http%3A%2F%2F[BASE DOMAIN]%2Ff22295b918&relation=opener&transport=postmessage&frame=f3e8d40458&access_token=[ACCESS TOKEN]&expires_in=4221&signed_request=[SIGNED REQUEST]&base_domain=[BASE DOMAIN] from frame with URL [MY CODE URL]#. Domains, protocols and ports must match.




I made sure that the channel file was available and am unable to reproduce this error in Firefox or Safari on OS X or on IE, Firefox, or Chrome on Windows. Any ideas? I can work around this using server-side authentication but prefer to use client-side, if possible.



1st EDIT: Further testing



So I now think that the "Unsafe JavaScript" error is a red herring. I am using the channel file, but it is not being hit either in Firefox or Chrome.



Looking at the network traffic on Firefox vs Chrome, when the page first loads, and assuming I'm logged into Facebook on both browsers, I see the following requests being processed:



Firefox




  • [facebook url]/dialog/oauth?api_key=[app_id]&app_id=[app_id]&channel_url=https%3A%2F%2Fs-static.ak.fbcdn.net%2Fconnect%2Fxd_proxy.php%23cb%3Df24509714bbf8d%26origin%3Dhttp%253A%252F%252F[base_domain]%252Ff193ade24ab412%26relation%3Dparent.parent%26transport%3Dpostmessage&client_id=[app_id]&display=none&domain=[base_domain]&locale=en_US&origin=1&redirect_uri=https%3A%2F%2Fs-static.ak.fbcdn.net%2Fconnect%2Fxd_proxy.php%23cb%3Df2b6c8dce7b8936%26origin%3Dhttp%253A%252F%252F[base_domain]%252Ff193ade24ab412%26relation%3Dparent%26transport%3Dpostmessage%26frame%3Df22112636bf762a&response_type=token%2Csigned_request%2Ccode&sdk=joey


  • [ssl facebook url]/dialog/oauth?api_key=[app_id]&app_id=[app_id]&channel_url=https%3A%2F%2Fs-static.ak.fbcdn.net%2Fconnect%2Fxd_proxy.php%23cb%3Df24509714bbf8d%26origin%3Dhttp%253A%252F%252F[base_domain]%252Ff193ade24ab412%26relation%3Dparent.parent%26transport%3Dpostmessage&client_id=[app_id]&display=none&domain=[base_domain]&locale=en_US&origin=1&redirect_uri=https%3A%2F%2Fs-static.ak.fbcdn.net%2Fconnect%2Fxd_proxy.php%23cb%3Df2b6c8dce7b8936%26origin%3Dhttp%253A%252F%252F[base_domain]%252Ff193ade24ab412%26relation%3Dparent%26transport%3Dpostmessage%26frame%3Df22112636bf762a&response_type=token%2Csigned_request%2Ccode&sdk=joey


  • [ssl fbcdn url] /connect/xd_proxy.php#cb=f2b6c8dce7b8936&origin=http%3A%2F%2F[base_domain]%2Ff193ade24ab412&relation=parent&transport=postmessage&frame=f22112636bf762a&code=2.AQBMIMy0rSFAnqaA.3600.1332514800.1-5322361%7CU-RUi4ON2SbzfzzDT03CTeT-DgQ&signed_request=[signed_request]&access_token=[access_token]&expires_in=4302&base_domain=[base_domain]&https=1




Chrome




  • [facebook url] /dialog/oauth?api_key=[app_id]&app_id=[app_id]&channel_url=https%3A%2F%2Fs-static.ak.fbcdn.net%2Fconnect%2Fxd_proxy.php%23cb%3Df1b2a93294%26origin%3Dhttp%253A%252F%252F[base_domain]%252Ffdca87bc8%26relation%3Dparent.parent%26transport%3Dpostmessage&client_id=[app_id]&display=none&domain=[base_domain]&locale=en_US&origin=1&redirect_uri=https%3A%2F%2Fs-static.ak.fbcdn.net%2Fconnect%2Fxd_proxy.php%23cb%3Df14d4dd364%26origin%3Dhttp%253A%252F%252F[base_domain]%252Ffdca87bc8%26relation%3Dparent%26transport%3Dpostmessage%26frame%3Df230336ee8&response_type=token%2Csigned_request%2Ccode&sdk=joey


  • [ssl fbcdn url] /connect/xd_proxy.php#cb=f14d4dd364&origin=http%3A%2F%2F[base_domain]%2Ffdca87bc8&relation=parent&transport=postmessage&frame=f230336ee8&error=unknown_user




I imagine this is because Chrome does not have the fbsr cookie set; which is a long way of leading me back to my original question. Why isn't Chrome setting the fbsr cookie (and, does it have something to do with the "Unsafe JavaScript attempt to access frame with URL" since that is sending the signed_request value in the hash?)



After all that, I'm going with bug. Unless anybody has a better idea!





setting Title for navigation bar in xcode

I have created a navigation controller programmatically,



        //Creating AddViewController Object
addViewController *addView = [[addViewController alloc]init];
UINavigationController *addViewControl = [[UINavigationController alloc]init];

[addViewControl.view addSubview:addView.view];

[self presentModalViewController:addViewControl animated:YES];


But when i add self.title = @"Title" in addViewController class. it is not displaying.



i tried with the following,



self.navigationItem.title = @"Title";

self.navigationController.navigationBar.topItem.title = @"Title";


But it's not displaying Title.



I think it is possible to do with setting a label. but the above one is direct method.



Any Idea..





JavaScript events handling

I've made this wonderful plugin: https://github.com/suprMax/Zepto-onPress



Which works perfectly besides one little detail. When I get callback function I need to store it alongside with my real event handler so I can detach it when someone tries to remove event handler and provide me the original callback. So basically I need to be able to store multiple key-value pairs per element where the key supposed to be a function and value is a function too. And I tried to do just that, but right now the script makes



(function(){}).toString() 


internally. Which is not a beast idea since I can remove wrong event handlers because



(function(){}).toString() === (function(){}).toString()


I suppose there is a better way to do just that. Any suggestions are very welcome.





convert a flat list to list of list in python

Normally, you want to go the other way around, like here. I was wondering how you can convert a flat list to a list of list, quasy reshaping array in python



In numpy you could do something like:



>>> a=numpy.aranage(9)
>>> a.reshape(3,3)
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])


I was wondering how you do the opposite, and my usual solution is something like:



>>> list
['a', 'b', 'c', 'd', 'e', 'f']
>>> newList = []
for i in range(0,len(diffe2),2):
... newList.append(diffe2[i], diffe2[i+1])
>>> newList
[['a', 'b'], ['c', 'd'], ['e', 'f']]


is there a more "Pythonic" way to do it?





ShowDialog in Closing-Event

If the user closes the Application a Save-File-Message have to be shown (to be sure that he wants to discard the changes of edited files).



to implement this, i have a menuitem with a command-binding (without key-gesture):



private void Command_Exit(object sender, ExecutedRoutedEventArgs e)
{
Application.Current.Shutdown();
}


the mainwindow has a closing-event. in this event i check if there unsaved files. if yes, the savedialog has to be opened (to choose, which files have to be saved):



private void Window_Closing(object sender, CancelEventArgs e)
{
if (sdl.Count() > 0)
{
SaveDialog sd = new SaveDialog();
IEnumerable<Doc> close = sd.ShowDialog(this);
if (close == null)
e.Cancel = true;
else
foreach (Doc document in close)
document.Save();
}

}


in this ShowDialog-Method (implemented in my SaveDialog-Class) i call



bool? ret = ShowDialog();
if (!ret.HasValue)
return null;
if (!ret.Value)
return null;


The problem is:



If i use the Alt+F4-Shortcut to close the Application (default-behaviour of the mainwindow) it works and i get the savedialog if there are unsaved files. but if i close the application by executing the Command_Exit-Method, the Method-Call



bool? ret = ShowDialog(); 


returns null and the dialog does not appear.



If i assign the Alt+F4 KeyGesture to the CommandBinding, the problem is switched: Executing Command_Exit works well but Alt+F4 Shortcut not.



What is the reason that the ShowDialog()-Method works not in both cases and how to fix it?





Javascript - Hidden maths answer.

The script below generates random numbers, and calculates the answer.



The next thing is that I want to have the answer HIDDEN and place a text area there. Then you have to input an answer and when the answer is correct, it should make the answer green.



I know it is possible, but I've searched on the internet for it without success, so I'm creating a question instead.



Here's the script:



<div id="breuken"></div>

$(function () {
var number = document.getElementById("breuken");
var i = 0;
for (i = 1; i <= 10; i++) {
var sRandom = Math.floor(Math.random() * 10);
var fRandom = Math.floor(sRandom + Math.random() * (10 - sRandom));
var calc = Math.abs(fRandom - sRandom);
number.innerHTML += "" + fRandom + " - " + sRandom + " = " + calc + "<br />";
}
number.innerHTML;
});




Mono for Android LVL and

Has anyone created a C# implementation of the Android LVL and the Downloader Library yet? Or the Play Expansion Library?



If not then I could start on it, as there has been some questions about this and I would like to use Google's new 4GB expansion of the APK size, as well as the LVL in my apps.



PS: I didn't quite know where to ask this.





Changing android emulator's IMSI number results with networks connection

For a test requirement, I modified the IMSI number in emulator.exe via a hex text editor,replaced a new IMSI number instead of original '310260000000000'. I ran the emulator again and resulted in no network connection any more. Any one who knows the problem and a way to resolve it pls give me a reply, thanks.





MySQL How do you import a .sql file using jdbc?

Scenerio



I had a blank database I created in mysql



mysql> create database Frog;
mysql> exit


I'm trying to use java jdbc driver to import the tables from a sql file



frog.sql file



DROP TABLE IF EXISTS `Frog`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Frog` (
`Frog_ID` int(11) NOT NULL AUTO_INCREMENT,
`Frog_NAME` varchar(255) DEFAULT NULL,
PRIMARY KEY (`Frog_ID`),
UNIQUE KEY `DEV_NAME` (`Frog_NAME`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;


java code



 public static void setUpTables()
{
try
{

ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c",
"mysql -u root Frog < ./Frog.sql");
Process pr = builder.start();


Problem: How do I go about this? Processbuilder ? Or some other type of jdbc api that I havent discovered yet?



Desired results: Be able to call java method to populate a database from a sql file



on the same lines as doing this but with java:



username$ mysql -uroot Frog < location/Frog.sql




override haystack build_page() function

I'm using django-haystack and want to override build_page() function. here is a url of build_page(). I want to replace the default django paginator with django-paginator. thanks alot :-)



def build_page(self):
"""
Paginates the results appropriately.

In case someone does not want to use Django's built-in pagination, it
should be a simple matter to override this method to do what they would
like.
"""


I've written messy code. Will you please help me? thanks



class MyView(SearchView):
def build_page(self):
build_page = super(MyView, self).build_page()
page = self.results
return page




Iterate through each item in accordion block with Selenium & Python

I've got an accordion block which I'd like to click each item & take a screenshot. Each item shares a class so I thought a for loop would work but I can't get it to select the items.



HTML Structure:



<div class="accordionContainer">
<div class="accordion">
<h3>Click This</h3>
<div class="accordionContent" style="display:none">
</div>
<div>
<div class="accordion">
<h3>Click This</h3>
<div class="accordionContent" style="display:none">
</div>
<div>
</div>


Python:



detailsAccordion = browser.find_elements_by_class_name('accordion')
index = 1
for option in detailsAccordion:
option.click()
try:
element = ui.WebDriverWait(ff, 10).until(lambda driver : driver.find_element_by_xpath("//div[@class='accordion'][" + str(index) + "]/div[@class='accordionContent']").text != "" )
except:
print "Can't do it"
browser.quit()
index = index + 1
n = nextNumber(n)
browser.save_screenshot('{0}\{1}.png'.format(imagesPath, n))
option.click()


This is causing a timeout with the following error. I've looked at this error & people have had trouble with internet options/proxy settings - I don't have a proxy so no sure why this has started;



 [exec] Can't do it
[exec] Traceback (most recent call last):
[exec] File "viewEmployeeUseCase.py", line 82, in <module>
[exec] ff.save_screenshot('{0}\{1}.png'.format(imagesPath, n))
[exec] File "C:\Python26\lib\site-packages\selenium-2.20.0-py2.6.egg\selenium\webdriver\firefox\webdriver.py", line 75, in save_screenshot
[exec] png = RemoteWebDriver.execute(self, Command.SCREENSHOT)['value']

[exec] File "C:\Python26\lib\site-packages\selenium-2.20.0-py2.6.egg\selenium\webdriver\remote\webdriver.py", line 151, in execute
[exec] response = self.command_executor.execute(driver_command, params)

[exec] File "C:\Python26\lib\site-packages\selenium-2.20.0-py2.6.egg\selenium\webdriver\remote\remote_connection.py", line 280, in execute
[exec] return self._request(url, method=command_info[0], data=data)
[exec] File "C:\Python26\lib\site-packages\selenium-2.20.0-py2.6.egg\selenium\webdriver\remote\remote_connection.py", line 321, in _request
[exec] response = opener.open(request)
[exec] File "C:\Python26\lib\urllib2.py", line 391, in open
[exec] response = self._open(req, data)
[exec] File "C:\Python26\lib\urllib2.py", line 409, in _open
[exec] '_open', req)
[exec] File "C:\Python26\lib\urllib2.py", line 369, in _call_chain
[exec] result = func(*args)
[exec] File "C:\Python26\lib\urllib2.py", line 1170, in http_open
[exec] return self.do_open(httplib.HTTPConnection, req)
[exec] File "C:\Python26\lib\urllib2.py", line 1145, in do_open
[exec] raise URLError(err)
[exec] urllib2.URLError: <urlopen error [Errno 10061] No connection could be made because the target machine actively refused it>


Making things simple & not waiting for content to populate works fine & does all I want it to with the following;



for option in detailsAccordion:
#print option
option.click()
WebDriverWait(ff, 2)
n = nextNumber(n)
ff.save_screenshot('{0}\{1}.png'.format(imagesPath, n))
option.click()




Mouse drag in Alternativa3d 8?

So I see a couple good working examples of using the mouse to drag an object in Alternativa3d:



http://wonderfl.net/c/hrsq/read

http://www.thetechlabs.com/3d/dragging-3d-objects-in-flex-3-using-alternativa3d-and-actionscript-3/



but they are for previous versions of the engine, and they contain code that is now deprecated, with no straightforward forward-translation, if you will. Please help!





Facebook API re-showing user profile

Suppose a user gives my site permission to access their profile data.



Is it ok then if my site stores this data and then re-show it for view to other users on my site?



Note, my site would be explicit to the original user that this will occur.





App prints "ljava.lang.string;@40585b18" rather than array value

I have this printed "ljava.lang.string;@40585b18" instead of a vlaue from the string array called answers.



At the moment i am not picky really as to what is pritned out. Just get the app to display something meaningfull from the array will be a good place to start right now.



The following two lines of code is what currently prints:



TextView quesAns4 = (TextView) findViewById(R.id.answer3);



quesAns4.setText("4) " + answers) ;



package ks3.mathsapp.project;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MathsMultiplicationActivity extends Activity {

TextView quesnum;
TextView ques;
TextView ans1;
TextView ans2;
TextView ans3;
TextView ans4;


int qno = 0;
int right_answers = 0;
int wrong_answers = 0;
int rnd1;
int rnd2;

String [] questions = {"How much mph does the F-Duct add to the car?",
"What car part is considered the biggest performance variable?",
"What car part is designed to speed up air flow at the car rear?",
"In seconds, how long does it take for a F1 car to stop when travelling at 300km/h?",
"How many litres of air does an F1 car consume per second?",
"What car part can heavily influence oversteer and understeer?",
"A third of the cars downforce can come from what?",
"Around how much race fuel would be consumed per 100km?","The first high nose cone was introduced when?",
"An increase in what, has led to the length of exhaust pipes being shortened drastically?"};

String [] [] answers = {{"3","5","8","9"},
{"Tyres","Front Wing","F-Duct","Engine"},
{"Diffuser","Suspension","Tyres","Exhaust"},
{"4","6","8","10"},
{"650","10","75","450"},
{"Suspension","Tyres","Cockpit","Chassis"},
{"Rear Wing","Nose Cone","Chassis","Engine"},
{"75 Litres","100 Litres","50 Litres","25 Litres"},
{"1990","1989","1993","1992"},
{"Engine RPM","Nose Cone Lengths","Tyre Size","Number of Races"}};

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

// Importing all assets like buttons, text fields
quesnum = (TextView) findViewById(R.id.questionNum);
ques = (TextView) findViewById(R.id.question);
ans1 = (TextView) findViewById(R.id.answer1);
ans2 = (TextView) findViewById(R.id.answer2);
ans3 = (TextView) findViewById(R.id.answer3);
ans4 = (TextView) findViewById(R.id.answer4);

TextView quesAns1 = (TextView) findViewById(R.id.answer1);
quesAns1.setText("1) " + answers) ;
TextView quesAns2 = (TextView) findViewById(R.id.answer2);
quesAns2.setText("2) " + answers) ;
TextView quesAns3 = (TextView) findViewById(R.id.answer3);
quesAns3.setText("3) " + answers) ;
TextView quesAns4 = (TextView) findViewById(R.id.answer3);
quesAns4.setText("4) " + answers) ;
}
}