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?