text:
<?php

/************************************************************************/
/* PHP-NUKE: Web Portal System                                          */
/* ===========================                                          */
/*                                                                      */
/* Copyright (c) 2001 by Francisco Burzi (fbc@mandrakesoft.com)         */
/* http://phpnuke.org                                                   */
/*                                                                      */
/* This program is free software. You can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 2 of the License.       */
/************************************************************************/

if (!eregi("admin.php", $PHP_SELF)) { die ("Access Denied"); }
$hlpfile = "manual/downloads.html";
$result = mysql_query("select radmindownload, radminsuper from $prefix"._authors." where aid='$aid'");
list($radmindownload, $radminsuper) = mysql_fetch_row($result);
if (($radmindownload==1) OR ($radminsuper==1)) {

/*********************************************************/
/* Downloads Modified Web Downloads                      */
/*********************************************************/

function downloads() {
    global $hlpfile, $prefix;
    include ("header.php");
    GraphicAdmin($hlpfile);
    OpenTable();
    echo "

";
    $result=mysql_query("select * from $prefix"._downloads_downloads."");
    $numrows = mysql_num_rows($result);
    echo ""._THEREARE." $numrows "._DOWNLOADSINDB."";
    CloseTable();
    echo "
";

/* Temporarily 'homeless' downloads functions (to be revised in admin.php breakup) */

    $result = mysql_query("select * from $prefix"._downloads_modrequest." where brokendownload=1");
    $totalbrokendownloads = mysql_num_rows($result);
    $result2 = mysql_query("select * from $prefix"._downloads_modrequest." where brokendownload=0");
    $totalmodrequests = mysql_num_rows($result2);

/* List Downloads waiting for validation */

    $result = mysql_query("select lid, cid, sid, title, url, description, name, email, submitter, filesize, version, homepage from $prefix"._downloads_newdownload." order by lid");
    $numrows = mysql_num_rows($result);
    if ($numrows>0) {
	OpenTable();
	echo ""._DOWNLOADSWAITINGVAL."

";
	while(list($lid, $cid, $sid, $title, $url, $description, $name, $email, $submitter, $filesize, $version, $homepage) = mysql_fetch_row($result)) {
	    if ($submitter == "") {
		$submitter = _NONE;
	    }
    	    $homepage = ereg_replace("http://","",$homepage);
	    echo "<form action=\"admin.php\" method=\"post\">"
		.""._DOWNLOADID.": $lid

"
		.""._SUBMITTER.": $submitter
"
		.""._DOWNLOADNAME.": <input type=\"text\" name=\"title\" value=\"$title\" size=\"50\" maxlength=\"100\">
"
		.""._FILEURL.": <input type=\"text\" name=\"url\" value=\"$url\" size=\"50\" maxlength=\"100\"> [ "._CHECK." ]
"
		.""._DESCRIPTION.":
<textarea name=\"description\" cols=\"60\" rows=\"10\">$description</textarea>
"
		.""._AUTHORNAME.": <input type=\"text\" name=\"name\" size=\"20\" maxlength=\"100\" value=\"$name\">  "
		.""._AUTHOREMAIL.": <input type=\"text\" name=\"email\" size=\"20\" maxlength=\"100\" value=\"$email\">
"
		.""._FILESIZE.": <input type=\"text\" name=\"filesize\" size=\"12\" maxlength=\"11\" value=\"$filesize\">
"
		.""._VERSION.": <input type=\"text\" name=\"version\" size=\"11\" maxlength=\"10\" value=\"$version\">
"
		.""._HOMEPAGE.": <input type=\"text\" name=\"homepage\" size=\"30\" maxlength=\"200\" value=\"http://$homepage\"> [ "._VISIT." ]
";
	    $result2=mysql_query("select cid, title from $prefix"._downloads_categories." order by title");
	    echo "<input type=\"hidden\" name=\"new\" value=\"1\">";
	    echo "<input type=\"hidden\" name=\"hits\" value=\"0\">";
	    echo "<input type=\"hidden\" name=\"lid\" value=\"$lid\">";
	    echo "<input type=\"hidden\" name=\"submitter\" value=\"$submitter\">";
	    echo ""._CATEGORY.": <select name=\"cat\">";
	    while(list($ccid, $ctitle) = mysql_fetch_row($result2)) {
		$sel = "";
		if ($cid==$ccid AND $sid==0) {
		    $sel = "selected";
		}
		echo "<option value=\"$ccid\" $sel>$ctitle</option>";
		$result3=mysql_query("select sid, title from $prefix"._downloads_subcategories." where cid=$ccid order by title");
		while(list($ssid, $stitle) = mysql_fetch_row($result3)) {
    	    	    $sel = "";
		    if ($sid == $ssid) {
			$sel = "selected";
		    }
		    echo "<option value=\"$ccid-$ssid\" $sel>$ctitle / $stitle</option>";
		}

	    }
	    echo "<input type=\"hidden\" name=\"submitter\" value=\"$submitter\">";
	    echo "</select><input type=\"hidden\" name=\"op\" value=\"DownloadsAddDownload\">

<input type=\"submit\" value="._ADD."> [ "._DELETE." ]</form>

";
	}
	CloseTable();
	echo "
";
    } else {
    }

/* Add a New Main Category */

    OpenTable();
    echo "[ "._CLEANDOWNLOADSDB." | "
	.""._BROKENDOWNLOADSREP." ($totalbrokendownloads) | "
	.""._DOWNLOADMODREQUEST." ($totalmodrequests) | "
	.""._VALIDATEDOWNLOADS." ]";
    CloseTable();
    echo "
";
    OpenTable();
    echo "<form method=\"post\" action=\"admin.php\">"
	.""._ADDMAINCATEGORY."

"
	.""._NAME.": <input type=\"text\" name=\"title\" size=\"30\" maxlength=\"100\">
"
	.""._DESCRIPTION.":
<textarea name=\"cdescription\" cols=\"60\" rows=\"10\"></textarea>
"
	."<input type=\"hidden\" name=\"op\" value=\"DownloadsAddCat\">"
	."<input type=\"submit\" value=\""._ADD."\">
"
	."</form>";
    CloseTable();
    echo "
";

// Add a New Sub-Category

    $result = mysql_query("select * from $prefix"._downloads_categories."");
    $numrows = mysql_num_rows($result);
    if ($numrows>0) {
	OpenTable();
	echo "<form method=\"post\" action=\"admin.php\">"
	    .""._ADDSUBCATEGORY."

"
	    .""._NAME.": <input type=\"text\" name=\"title\" size=\"30\" maxlength=\"100\"> "._IN." ";
	$result=mysql_query("select cid, title from $prefix"._downloads_categories." order by title");
	echo "<select name=\"cid\">";
	while(list($ccid, $ctitle) = mysql_fetch_row($result)) {
	    echo "<option value=\"$ccid\">$ctitle</option>";
	}
	echo "</select>"
	    ."<input type=\"hidden\" name=\"op\" value=\"DownloadsAddSubCat\">"
	    ."<input type=\"submit\" value=\""._ADD."\">
"
	    ."</form>";
	CloseTable();
	echo "
";
    } else {
    }

// Add a New Download to Database

    $result = mysql_query("select cid, title from $prefix"._downloads_categories."");
    $numrows = mysql_num_rows($result);
    if ($numrows>0) {
	OpenTable();
	echo "<form method=\"post\" action=\"admin.php\">"
	    .""._ADDNEWDOWNLOAD."

"
	    .""._DOWNLOADNAME.": <input type=\"text\" name=\"title\" size=\"50\" maxlength=\"100\">
"
	    .""._FILEURL.": <input type=\"text\" name=\"url\" size=\"50\" maxlength=\"100\" value=\"http://\">
";
	$result=mysql_query("select cid, title from $prefix"._downloads_categories." order by title");
	echo ""._CATEGORY.": <select name=\"cat\">";
	while(list($cid, $title) = mysql_fetch_row($result)) {
	    echo "<option value=\"$cid\">$title</option>";
	    $result2=mysql_query("select sid, title from $prefix"._downloads_subcategories." where cid=$cid order by title");
	    while(list($sid, $stitle) = mysql_fetch_row($result2)) {
    		echo "<option value=\"$cid-$sid\">$title / $stitle</option>";
	    }
	}
	echo "</select>

"
	    .""._DESCRIPTION255."
<textarea name=\"description\" cols=\"60\" rows=\"5\"></textarea>

"
	    .""._AUTHORNAME.": <input type=\"text\" name=\"name\" size=\"30\" maxlength=\"60\">

"
	    .""._AUTHOREMAIL.": <input type=\"text\" name=\"email\" size=\"30\" maxlength=\"60\">

"
	    .""._FILESIZE.": <input type=\"text\" name=\"filesize\" size=\"12\" maxlength=\"11\"> ("._INBYTES.")

"
	    .""._VERSION.": <input type=\"text\" name=\"version\" size=\"11\" maxlength=\"10\">

"
	    .""._HOMEPAGE.": <input type=\"text\" name=\"homepage\" size=\"30\" maxlength=\"200\" value=\"http://\">

"
	    .""._HITS.": <input type=\"text\" name=\"hits\" size=\"12\" maxlength=\"11\">

"
	    ."<input type=\"hidden\" name=\"op\" value=\"DownloadsAddDownload\">"
    	    ."<input type=\"hidden\" name=\"new\" value=\"0\">"
	    ."<input type=\"hidden\" name=\"lid\" value=\"0\">"
	    ."<input type=\"submit\" value=\""._ADDURL."\">
"
	    ."</form>";
	CloseTable();
	echo "
";
    } else {
    }

// Modify Category

    $result = mysql_query("select * from $prefix"._downloads_categories."");
    $numrows = mysql_num_rows($result);
    if ($numrows>0) {
	OpenTable();
	echo "<form method=\"post\" action=\"admin.php\">"
	    .""._MODCATEGORY."

";
	$result=mysql_query("select cid, title from $prefix"._downloads_categories." order by title");
	echo ""._CATEGORY.": <select name=\"cat\">";
	while(list($cid, $title) = mysql_fetch_row($result)) {
	    echo "<option value=\"$cid\">$title</option>";
	    $result2=mysql_query("select sid, title from $prefix"._downloads_subcategories." where cid=$cid order by title");
	    while(list($sid, $stitle) = mysql_fetch_row($result2)) {
    		echo "<option value=\"$cid-$sid\">$title / $stitle</option>";
	    }
	}
	echo "</select>"
	    ."<input type=\"hidden\" name=\"op\" value=\"DownloadsModCat\">"
	    ."<input type=\"submit\" value=\""._MODIFY."\">"
	    ."</form>";
	CloseTable();
	echo "
";
    } else {
    }

// Modify Downloads

    $result = mysql_query("select * from $prefix"._downloads_downloads."");
    $numrows = mysql_num_rows($result);
    if ($numrows>0) {
    OpenTable();
    echo "<form method=\"post\" action=\"admin.php\">"
	.""._MODDOWNLOAD."

"
	.""._DOWNLOADID.": <input type=\"text\" name=\"lid\" size=\"12\" maxlength=\"11\">  "
	."<input type=\"hidden\" name=\"op\" value=\"DownloadsModDownload\">"
	."<input type=\"submit\" value=\""._MODIFY."\">"
	."</form>";
    CloseTable();
    echo "
";
    } else {
    }
    include ("footer.php");
}

function DownloadsModDownload($lid) {
    global $prefix;
    include ("header.php");
    GraphicAdmin($hlpfile);
    global $anonymous;
    $result = mysql_query("select cid, sid, title, url, description, name, email, hits, filesize, version, homepage from $prefix"._downloads_downloads." where lid=$lid");
    OpenTable();
    echo ""._WEBDOWNLOADSADMIN."";
    CloseTable();
    echo "
";
    OpenTable();
    echo ""._MODDOWNLOAD."

";
    while(list($cid, $sid, $title, $url, $description, $name, $email, $hits, $filesize, $version, $homepage) = mysql_fetch_row($result)) {
    	$title = stripslashes($title); $description = stripslashes($description);
    	echo "<form action=admin.php method=post>"
	    .""._DOWNLOADID.": $lid
"
	    .""._PAGETITLE.": <input type=\"text\" name=\"title\" value=\"$title\" size=\"50\" maxlength=\"100\">
"
	    .""._PAGEURL.": <input type=\"text\" name=\"url\" value=\"$url\" size=\"50\" maxlength=\"100\"> [ "._CHECK." ]
"
	    .""._DESCRIPTION.":
<textarea name=\"description\" cols=\"60\" rows=\"10\">$description</textarea>
"
	    .""._AUTHORNAME.": <input type=\"text\" name=\"name\" size=\"50\" maxlength=\"100\" value=\"$name\">
"
	    .""._AUTHOREMAIL.": <input type=\"text\" name=\"email\" size=\"50\" maxlength=\"100\" value=\"$email\">
"
	    .""._FILESIZE.": <input type=\"text\" name=\"filesize\" size=\"12\" maxlength=\"11\" value=\"$filesize\">
"
	    .""._VERSION.": <input type=\"text\" name=\"version\" size=\"11\" maxlength=\"10\" value=\"$version\">
"
	    .""._HOMEPAGE.": <input type=\"text\" name=\"homepage\" size=\"50\" maxlength=\"200\" value=\"$homepage\"> [ "._VISIT." ]
"
	    .""._HITS.": <input type=\"text\" name=\"hits\" value=\"$hits\" size=\"12\" maxlength=\"11\">
";
	$result2=mysql_query("select cid, title from $prefix"._downloads_categories." order by title");
	echo "<input type=\"hidden\" name=\"lid\" value=\"$lid\">"
	    .""._CATEGORY.": <select name=\"cat\">";
	while(list($ccid, $ctitle) = mysql_fetch_row($result2)) {
	    $sel = "";
	    if ($cid==$ccid AND $sid==0) {
		$sel = "selected";
	    }
	    echo "<option value=\"$ccid\" $sel>$ctitle</option>";
	    $result3=mysql_query("select sid, title from $prefix"._downloads_subcategories." where cid=$ccid order by title");
	    while(list($ssid, $stitle) = mysql_fetch_row($result3)) {
    	        $sel = "";
		if ($sid==$ssid) {
		    $sel = "selected";
		}
		echo "<option value=\"$ccid-$ssid\" $sel>$ctitle / $stitle</option>";
	    }
	}

    echo "</select>"
	."<input type=\"hidden\" name=\"op\" value=\"DownloadsModDownloadS\">"
	."<input type=\"submit\" value=\""._MODIFY."\"> [ "._DELETE." ]</form>
";
    CloseTable();
    echo "
";
    /* Modify or Add Editorial */

        $resulted2 = mysql_query("select adminid, editorialtimestamp, editorialtext, editorialtitle from $prefix"._downloads_editorials." where downloadid=$lid");
        $recordexist = Mysql_num_rows($resulted2);
	OpenTable();
    /* if returns 'bad query' status 0 (add editorial) */
    	if ($recordexist == 0) {
    	    echo ""._ADDEDITORIAL."

"
    		."<form action=\"admin.php\" method=\"post\">"
    		."<input type=\"hidden\" name=\"downloadid\" value=\"$lid\">"
    		.""._EDITORIALTITLE.":
<input type=\"text\" name=\"editorialtitle\" value=\"$editorialtitle\" size=\"50\" maxlength=\"100\">
"
    		.""._EDITORIALTEXT.":
<textarea name=\"editorialtext\" cols=\"60\" rows=\"10\">$editorialtext</textarea>
"
        	."</select><input type=\"hidden\" name=\"op\" value=\"DownloadsAddEditorial\"><input type=\"submit\" value=\"Add\">";
        } else {
    /* if returns 'cool' then status 1 (modify editorial) */
        	while(list($adminid, $editorialtimestamp, $editorialtext, $editorialtitle) = mysql_fetch_row($resulted2)) {
        	$editorialtitle = stripslashes($editorialtitle); $editorialtext = stripslashes($editorialtext);
    		ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $editorialtimestamp, $editorialtime);
		$editorialtime = strftime("%F",mktime($editorialtime[4],$editorialtime[5],$editorialtime[6],$editorialtime[2],$editorialtime[3],$editorialtime[1]));
		$date_array = explode("-", $editorialtime);
		$timestamp = mktime(0, 0, 0, $date_array["1"], $date_array["2"], $date_array["0"]);
       		$formatted_date = date("F j, Y", $timestamp);
        	echo "Modify Editorial

"
        	    ."<form action=\"admin.php\" method=\"post\">"
        	    .""._AUTHOR.": $adminid
"
        	    .""._DATEWRITTEN.": $formatted_date

"
        	    ."<input type=\"hidden\" name=\"downloadid\" value=\"$lid\">"
        	    .""._EDITORIALTITLE.":
<input type=\"text\" name=\"editorialtitle\" value=\"$editorialtitle\" size=\"50\" maxlength=\"100\">
"
        	    .""._EDITORIALTEXT.":
<textarea name=\"editorialtext\" cols=\"60\" rows=\"10\">$editorialtext</textarea>
"
            	    ."</select><input type=\"hidden\" name=\"op\" value=\"DownloadsModEditorial\"><input type=\"submit\" value=\""._MODIFY."\"> [ "._DELETE." ]";
                }
    	}
    CloseTable();
    echo "
";
    OpenTable();
    /* Show Comments */
    $result5=mysql_query("SELECT ratingdbid, ratinguser, ratingcomments, ratingtimestamp FROM $prefix"._downloads_votedata." WHERE ratinglid = $lid AND ratingcomments != '' ORDER BY ratingtimestamp DESC");
    $totalcomments = Mysql_num_rows($result5);
    echo "
";
    echo "
Download Comments (total comments: $totalcomments)

";
    echo "
User  	Comment  	Delete

";
    if ($totalcomments == 0) echo "
No Comments

";
    $x=0;
    $colorswitch="dddddd";
    while(list($ratingdbid, $ratinguser, $ratingcomments, $ratingtimestamp)=mysql_fetch_row($result5)) {
    	$ratingcomments = stripslashes($ratingcomments);
        ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $ratingtimestamp, $ratingtime);
    	$ratingtime = strftime("%F",mktime($ratingtime[4],$ratingtime[5],$ratingtime[6],$ratingtime[2],$ratingtime[3],$ratingtime[1]));
    	$date_array = explode("-", $ratingtime);
    	$timestamp = mktime(0, 0, 0, $date_array["1"], $date_array["2"], $date_array["0"]);
            $formatted_date = date("F j, Y", $timestamp);
            echo "
$ratinguser	$ratingcomments	X

";
    	$x++;
    	if ($colorswitch=="dddddd") $colorswitch="ffffff";
    		else $colorswitch="dddddd";
        }

    // Show Registered Users Votes
    $result5=mysql_query("SELECT ratingdbid, ratinguser, rating, ratinghostname, ratingtimestamp FROM $prefix"._downloads_votedata." WHERE ratinglid = $lid AND ratinguser != 'outside' AND ratinguser != '$anonymous' ORDER BY ratingtimestamp DESC");
    $totalvotes = Mysql_num_rows($result5);
    echo "

Registered User Votes (total votes: $totalvotes)

";
    echo "
User  	IP Address  	Rating  	User AVG Rating  	Total Ratings  	Date  	Delete

";
    if ($totalvotes == 0) echo "
No Registered User Votes

";
    $x=0;
    $colorswitch="dddddd";
    while(list($ratingdbid, $ratinguser, $rating, $ratinghostname, $ratingtimestamp)=mysql_fetch_row($result5)) {
        ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $ratingtimestamp, $ratingtime);
    	$ratingtime = strftime("%F",mktime($ratingtime[4],$ratingtime[5],$ratingtime[6],$ratingtime[2],$ratingtime[3],$ratingtime[1]));
    	$date_array = explode("-", $ratingtime);
    	$timestamp = mktime(0, 0, 0, $date_array["1"], $date_array["2"], $date_array["0"]);
            $formatted_date = date("F j, Y", $timestamp);

    	//Individual user information
    	$result2=mysql_query("SELECT rating FROM $prefix"._downloads_votedata." WHERE ratinguser = '$ratinguser'");
            $usertotalcomments = Mysql_num_rows($result2);
            $useravgrating = 0;
            while(list($rating2)=mysql_fetch_row($result2))	$useravgrating = $useravgrating + $rating2;
            $useravgrating = $useravgrating / $usertotalcomments;
            $useravgrating = number_format($useravgrating, 1);
            echo "
$ratinguser	$ratinghostname	$rating	$useravgrating	$usertotalcomments	$formatted_date  	X

";
    	$x++;
    	if ($colorswitch=="dddddd") $colorswitch="ffffff";
    		else $colorswitch="dddddd";
        }

    // Show Unregistered Users Votes
    $result5=mysql_query("SELECT ratingdbid, rating, ratinghostname, ratingtimestamp FROM $prefix"._downloads_votedata." WHERE ratinglid = $lid AND ratinguser = '$anonymous' ORDER BY ratingtimestamp DESC");
    $totalvotes = Mysql_num_rows($result5);
    echo "

Unregistered User Votes (total votes: $totalvotes)

";
    echo "
IP Address  	Rating  	Date  	Delete

";
    if ($totalvotes == 0) echo "
No Unregistered User Votes

";
    $x=0;
    $colorswitch="dddddd";
    while(list($ratingdbid, $rating, $ratinghostname, $ratingtimestamp)=mysql_fetch_row($result5)) {
        ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $ratingtimestamp, $ratingtime);
    	$ratingtime = strftime("%F",mktime($ratingtime[4],$ratingtime[5],$ratingtime[6],$ratingtime[2],$ratingtime[3],$ratingtime[1]));
    	$date_array = explode("-", $ratingtime);
    	$timestamp = mktime(0, 0, 0, $date_array["1"], $date_array["2"], $date_array["0"]);
        $formatted_date = date("F j, Y", $timestamp);
        echo "$ratinghostname	$rating	$formatted_date  	X

";
    	$x++;
    	if ($colorswitch=="dddddd") $colorswitch="ffffff";
    		else $colorswitch="dddddd";
        }

    // Show Outside Users Votes
    $result5=mysql_query("SELECT ratingdbid, rating, ratinghostname, ratingtimestamp FROM $prefix"._downloads_votedata." WHERE ratinglid = $lid AND ratinguser = 'outside' ORDER BY ratingtimestamp DESC");
    $totalvotes = Mysql_num_rows($result5);
    echo "

Outside User Votes (total votes: $totalvotes)

";
    echo "
IP Address  	Rating  	Date  	Delete

";
    if ($totalvotes == 0) echo "
No Votes from Outside $sitename

";
    $x=0;
    $colorswitch="dddddd";
    while(list($ratingdbid, $rating, $ratinghostname, $ratingtimestamp)=mysql_fetch_row($result5)) {
        ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $ratingtimestamp, $ratingtime);
    	$ratingtime = strftime("%F",mktime($ratingtime[4],$ratingtime[5],$ratingtime[6],$ratingtime[2],$ratingtime[3],$ratingtime[1]));
    	$date_array = explode("-", $ratingtime);
    	$timestamp = mktime(0, 0, 0, $date_array["1"], $date_array["2"], $date_array["0"]);
        $formatted_date = date("F j, Y", $timestamp);
        echo "
$ratinghostname	$rating	$formatted_date  	X

";
    	$x++;
    	if ($colorswitch=="dddddd") $colorswitch="ffffff";
    		else $colorswitch="dddddd";
        }

    echo "

";
    echo "
";

    }
    echo "</form>";
    CloseTable();
    echo "
";
    include ("footer.php");
}

function DownloadsDelComment($lid, $rid) {
    global $prefix;
    mysql_query("UPDATE $prefix"._downloads_votedata." SET ratingcomments='' WHERE ratingdbid = $rid");
    mysql_query("UPDATE $prefix"._downloads_downloads." SET totalcomments = (totalcomments - 1) WHERE lid = $lid");
    Header("Location: admin.php?op=DownloadsModDownload&lid=$lid");

}

function DownloadsDelVote($lid, $rid) {
    global $prefix;
    mysql_query("delete from $prefix"._downloads_votedata." where ratingdbid=$rid");
    $voteresult = mysql_query("select rating, ratinguser, ratingcomments FROM $prefix"._downloads_votedata." WHERE ratinglid = $lid");
    $totalvotesDB = mysql_num_rows($voteresult);
    include ("voteinclude.php");
    mysql_query("UPDATE $prefix"._downloads_downloads." SET downloadratingsummary=$finalrating,totalvotes=$totalvotesDB,totalcomments=$truecomments WHERE lid = $lid");
    Header("Location: admin.php?op=DownloadsModDownload&lid=$lid");
}

function DownloadsListBrokenDownloads() {
    global $bgcolor1, $bgcolor2, $prefix;
    include ("header.php");
    GraphicAdmin($hlpfile);
    OpenTable();
    echo ""._WEBDOWNLOADSADMIN."";
    CloseTable();
    echo "
";
    OpenTable();
    $result = mysql_query("select requestid, lid, modifysubmitter from $prefix"._downloads_modrequest." where brokendownload=1 order by requestid");
    $totalbrokendownloads = mysql_num_rows($result);
    echo ""._DUSERREPBROKEN." ($totalbrokendownloads)

"
	.""._DIGNOREINFO."
"
	.""._DDELETEINFO."

"
	."
";
    if ($totalbrokendownloads==0) {
	echo ""._DNOREPORTEDBROKEN."

";
    } else {
        $colorswitch = $bgcolor2;
        echo "
"
            .""._DOWNLOAD."	"
            .""._SUBMITTER."	"
            .""._DOWNLOADOWNER."	"
            .""._IGNORE."	"
            .""._DELETE."	"
            .""._EDIT."	"
    	    ."
";
        while(list($requestid, $lid, $modifysubmitter)=mysql_fetch_row($result)) {
	    $result2 = mysql_query("select title, url, submitter from $prefix"._downloads_downloads." where lid=$lid");
	    if ($modifysubmitter != '$anonymous') {
		$result3 = mysql_query("select email from $prefix"._users." where uname='$modifysubmitter'");
		list($email)=mysql_fetch_row($result3);
	    }
    	    list($title, $url, $owner)=mysql_fetch_row($result2);
    	    $result4 = mysql_query("select email from $prefix"._users." where uname='$owner'");
    	    list($owneremail)=mysql_fetch_row($result4);
    	    echo "
"
    		."$title"
    		."	";
    	    if ($email=='') {
		echo "$modifysubmitter";
	    } else {
		echo "$modifysubmitter";
	    }
    	    echo "	";
    	    if ($owneremail=='') {
		echo "$owner";
	    } else {
		echo "$owner";
	    }
    	    echo "	"
    		."X"
    		."	"
    		."X"
    		."	"
    		."X"
    		."	"
		."
";
    	    if ($colorswitch == $bgcolor2) {
		$colorswitch = $bgcolor1;
       	    } else {
		$colorswitch = $bgcolor2;
	    }
    	}
    }
    echo "
";
    CloseTable();
    include ("footer.php");
}

function DownloadsDelBrokenDownloads($lid) {
    global $prefix;
    mysql_query("delete from $prefix"._downloads_modrequest." where lid=$lid");
    mysql_query("delete from $prefix"._downloads_downloads." where lid=$lid");
    Header("Location: admin.php?op=DownloadsListBrokenDownloads");
}

function DownloadsIgnoreBrokenDownloads($lid) {
    global $prefix;
    mysql_query("delete from $prefix"._downloads_modrequest." where lid=$lid and brokendownload=1");
    Header("Location: admin.php?op=DownloadsListBrokenDownloads");
}

function DownloadsListModRequests() {
    global $bgcolor2, $prefix;
    include ("header.php");
    GraphicAdmin($hlpfile);
    OpenTable();
    echo ""._WEBDOWNLOADSADMIN."";
    CloseTable();
    echo "
";
    OpenTable();
    $result = mysql_query("select requestid, lid, cid, sid, title, url, description, modifysubmitter, name, email, filesize, version, homepage from $prefix"._downloads_modrequest." where brokendownload=0 order by requestid");
    $totalmodrequests = mysql_num_rows($result);
    echo ""._DUSERMODREQUEST." ($totalmodrequests)

";
    echo "

";
    while(list($requestid, $lid, $cid, $sid, $title, $url, $description, $modifysubmitter, $name, $email, $filesize, $version, $homepage)=mysql_fetch_row($result)) {
	$result2 = mysql_query("select cid, sid, title, url, description, name, email, submitter, filesize, version, homepage from $prefix"._downloads_downloads." where lid=$lid");
	list($origcid, $origsid, $origtitle, $origurl, $origdescription, $origname, $origemail, $owner, $origfilesize, $origversion, $orighomepage)=mysql_fetch_row($result2);
	$result3 = mysql_query("select title from $prefix"._downloads_categories." where cid=$cid");
	$result4 = mysql_query("select title from $prefix"._downloads_subcategories." where cid=$cid and sid=$sid");
	$result5 = mysql_query("select title from $prefix"._downloads_categories." where cid=$origcid");
	$result6 = mysql_query("select title from $prefix"._downloads_subcategories." where cid=$origcid and sid=$origsid");
	$result7 = mysql_query("select email from $prefix"._users." where uname='$modifysubmitter'");
	$result8 = mysql_query("select email from $prefix"._users." where uname='$owner'");
	list($cidtitle)=mysql_fetch_row($result3);
	list($sidtitle)=mysql_fetch_row($result4);
	list($origcidtitle)=mysql_fetch_row($result5);
	list($origsidtitle)=mysql_fetch_row($result6);
	list($modifysubmitteremail)=mysql_fetch_row($result7);
	list($owneremail)=mysql_fetch_row($result8);
    	$title = stripslashes($title);
    	$description = stripslashes($description);
    	if ($owner=="") {
	    $owner="administration";
	}
    	if ($origsidtitle=="") {
	    $origsidtitle= "-----";
	}
    	if ($sidtitle=="") {
	    $sidtitle= "-----";
	}
    	echo "
"
    	    ."
"
    	    .""
    	    ."
"
    	    ."
"
    	    .""._ORIGINAL."	"
    	    ."
"._DESCRIPTION.":
$origdescription	"
    	    ."
"
    	    ."
"._TITLE.": $origtitle
"
    	    ."
"._URL.": $origurl
"
	    ."
"._CATEGORY.": $origcidtitle
"
	    ."
"._SUBCATEGORY.": $origsidtitle
"
	    ."
"._AUTHORNAME.": $origname
"
	    ."
"._AUTHOREMAIL.": $origemail
"
	    ."
"._FILESIZE.": $origfilesize
"
	    ."
"._VERSION.": $origversion
"
	    ."
"._HOMEPAGE.": $orighomepage
"
    	    ."
"
    	    ."	"
    	    ."
"
    	    ."
"
    	    .""
    	    ."
"
    	    ."
"
    	    .""._PROPOSED."	"
    	    ."
"._DESCRIPTION.":
$description	"
    	    ."
"
    	    ."
"._TITLE.": $title
"
    	    ."
"._URL.": $url
"
	    ."
"._CATEGORY.": $cidtitle
"
	    ."
"._SUBCATEGORY.": $sidtitle
"
	    ."
"._AUTHORNAME.": $name
"
	    ."
"._AUTHOREMAIL.": $email
"
	    ."
"._FILESIZE.": $filesize
"
	    ."
"._VERSION.": $version
"
	    ."
"._HOMEPAGE.": $homepage
"
    	    ."
"
    	    ."	"
    	    ."
"
    	    ."
"
    	    ."
"
    	    ."
";
    	if ($modifysubmitteremail=="") {
	    echo ""._SUBMITTER.":  $modifysubmitter	";
	} else {
	    echo ""._SUBMITTER.":  $modifysubmitter	";
	}
    	if ($owneremail=="") {
	    echo ""._OWNER.":  $owner	";
	} else {
	    echo ""._OWNER.": $owner	";
	}
    	echo "( "._ACCEPT." / "._IGNORE." )

";
    }
    if ($totalmodrequests == 0) {
	echo ""._NOMODREQUESTS."

"
	    .""._GOBACK."

";
    }
    echo "

";
    CloseTable();
    include ("footer.php");
}

function DownloadsChangeModRequests($requestid) {
    global $prefix;
    $result = mysql_query("select requestid, lid, cid, sid, title, url, description, name, email, filesize, version, homepage from $prefix"._downloads_modrequest." where requestid=$requestid");
    while(list($requestid, $lid, $cid, $sid, $title, $url, $description, $name, $email, $filesize, $version, $homepage)=mysql_fetch_row($result)) {
	$title = stripslashes($title);
    	$description = stripslashes($description);
    	mysql_query("UPDATE $prefix"._downloads_downloads." SET cid=$cid, sid=$sid, title='$title', url='$url', description='$description', name='$name', email='$email', filesize='$filesize', version='$version', homepage='$homepage' WHERE lid = $lid");
	mysql_query("delete from $prefix"._downloads_modrequest." where requestid=$requestid");
    }
    Header("Location: admin.php?op=DownloadsListModRequests");
}

function DownloadsChangeIgnoreRequests($requestid) {
    global $prefix;
    mysql_query("delete from $prefix"._downloads_modrequest." where requestid=$requestid");
    Header("Location: admin.php?op=DownloadsListModRequests");
}

function DownloadsCleanVotes() {
    global $prefix;
    $totalvoteresult = mysql_query("select distinct ratinglid FROM $prefix"._downloads_votedata."");
    while(list($lid)=mysql_fetch_row($totalvoteresult)) {
	$voteresult = mysql_query("select rating, ratinguser, ratingcomments FROM $prefix"._downloads_votedata." WHERE ratinglid = $lid");
	$totalvotesDB = mysql_num_rows($voteresult);
	include ("voteinclude.php");
        mysql_query("UPDATE $prefix"._downloads_downloads." SET downloadratingsummary=$finalrating,totalvotes=$totalvotesDB,totalcomments=$truecomments WHERE lid = $lid");
    }
    Header("Location: admin.php?op=downloads");
}

function DownloadsModDownloadS($lid, $title, $url, $description, $name, $email, $hits, $cat, $filesize, $version, $homepage) {
    global $prefix;
    $cat = explode("-", $cat);
    if ($cat[1]=="") {
        $cat[1] = 0;
    }
    $title = stripslashes(FixQuotes($title));
    $url = stripslashes(FixQuotes($url));
    $description = stripslashes(FixQuotes($description));
    $name = stripslashes(FixQuotes($name));
    $email = stripslashes(FixQuotes($email));
    mysql_query("update $prefix"._downloads_downloads." set cid='$cat[0]', sid='$cat[1]', title='$title', url='$url', description='$description', name='$name', email='$email', hits='$hits', filesize='$filesize', version='$version', homepage='$homepage' where lid=$lid");
    Header("Location: admin.php?op=downloads");
}

function DownloadsDelDownload($lid) {
    global $prefix;
    mysql_query("delete from $prefix"._downloads_downloads." where lid=$lid");
    Header("Location: admin.php?op=downloads");
}

function DownloadsModCat($cat) {
    global $prefix;
    include ("header.php");
    GraphicAdmin($hlpfile);
    OpenTable();
    echo ""._WEBDOWNLOADSADMIN."";
    CloseTable();
    echo "
";
    $cat = explode("-", $cat);
    if ($cat[1]=="") {
        $cat[1] = 0;
    }
    OpenTable();
    echo ""._MODCATEGORY."

";
    if ($cat[1]==0) {
	$result=mysql_query("select title, cdescription from $prefix"._downloads_categories." where cid=$cat[0]");
	list($title,$cdescription) = mysql_fetch_row($result);
	$cdescription = stripslashes($cdescription);
	echo "<form action=\"admin.php\" method=\"get\">"
	    .""._NAME.": <input type=\"text\" name=\"title\" value=\"$title\" size=\"51\" maxlength=\"50\">
"
	    .""._DESCRIPTION.":
<textarea name=\"cdescription\" cols=\"60\" rows=\"10\">$cdescription</textarea>
"
	    ."<input type=\"hidden\" name=\"sub\" value=\"0\">"
	    ."<input type=\"hidden\" name=\"cid\" value=\"$cat[0]\">"
	    ."<input type=\"hidden\" name=\"op\" value=\"DownloadsModCatS\">"
	    ."

"
	    ."<input type=\"submit\" value=\""._SAVECHANGES."\"></form>	"
	    ."<form action=\"admin.php\" method=\"get\">"
	    ."<input type=\"hidden\" name=\"sub\" value=\"0\">"
	    ."<input type=\"hidden\" name=\"cid\" value=\"$cat[0]\">"
	    ."<input type=\"hidden\" name=\"op\" value=\"DownloadsDelCat\">"
	    ."<input type=\"submit\" value=\""._DELETE."\"></form>

";
    } else {
	$result=mysql_query("select title from $prefix"._downloads_categories." where cid=$cat[0]");
	list($ctitle) = mysql_fetch_row($result);
	$result2=mysql_query("select title from $prefix"._downloads_subcategories." where sid=$cat[1]");
	list($stitle) = mysql_fetch_row($result2);
	echo "<form action=\"admin.php\" method=\"get\">"
	    .""._CATEGORY.": $ctitle
"
	    .""._SUBCATEGORY.": <input type=\"text\" name=\"title\" value=\"$stitle\" size=\"51\" maxlength=\"50\">
"
	    ."<input type=\"hidden\" name=\"sub\" value=\"1\">"
	    ."<input type=\"hidden\" name=\"cid\" value=\"$cat[0]\">"
	    ."<input type=\"hidden\" name=\"sid\" value=\"$cat[1]\">"
	    ."<input type=\"hidden\" name=\"op\" value=\"DownloadsModCatS\">"
	    ."

"
	    ."<input type=\"submit\" value=\""._SAVECHANGES."\"></form>	"
	    ."<form action=\"admin.php\" method=\"get\">"
	    ."<input type=\"hidden\" name=\"sub\" value=\"1\">"
	    ."<input type=\"hidden\" name=\"cid\" value=\"$cat[0]\">"
	    ."<input type=\"hidden\" name=\"sid\" value=\"$cat[1]\">"
	    ."<input type=\"hidden\" name=\"op\" value=\"DownloadsDelCat\">"
	    ."<input type=\"submit\" value=\""._DELETE."\"></form>

";
    }
    CloseTable();
    include("footer.php");
}

function DownloadsModCatS($cid, $sid, $sub, $title, $cdescription) {
    global $prefix;
    if ($sub==0) {
	mysql_query("update $prefix"._downloads_categories." set title='$title', cdescription='$cdescription' where cid=$cid");
    } else {
	mysql_query("update $prefix"._downloads_subcategories." set title='$title' where sid=$sid");
    }
    Header("Location: admin.php?op=downloads");
}

function DownloadsDelCat($cid, $sid, $sub, $ok=0) {
    global $prefix;
    if($ok==1) {
	if ($sub>0) {
    	    mysql_query("delete from $prefix"._downloads_subcategories." where sid=$sid");
	    mysql_query("delete from $prefix"._downloads_downloads." where sid=$sid");
	} else {
	    mysql_query("delete from $prefix"._downloads_categories." where cid=$cid");
	    mysql_query("delete from $prefix"._downloads_subcategories." where cid=$cid");
	    mysql_query("delete from $prefix"._downloads_downloads." where cid=$cid AND sid=0");
	}
	Header("Location: admin.php?op=downloads");
    } else {
	include("header.php");
	GraphicAdmin($hlpfile);
	OpenTable();
	echo "
";
	echo ""._DDELCATWARNING."

";
    }
	echo "[ "._YES." | "._NO." ]

";
	CloseTable();
	include("footer.php");
}

function DownloadsDelNew($lid) {
    global $prefix;
    mysql_query("delete from $prefix"._downloads_newdownload." where lid=$lid");
    Header("Location: admin.php?op=downloads");
}

function DownloadsAddCat($title, $cdescription) {
    global $prefix;
    $result = mysql_query("select cid from $prefix"._downloads_categories." where title='$title'");
    $numrows = mysql_num_rows($result);
    if ($numrows>0) {
	include("header.php");
	GraphicAdmin($hlpfile);
	OpenTable();
	echo "
"
	    .""._ERRORTHECATEGORY." $title "._ALREADYEXIST."

"
	    .""._GOBACK."

";
	CloseTable();
	include("footer.php");
    } else {
	mysql_query("insert into $prefix"._downloads_categories." values (NULL, '$title', '$cdescription')");
	Header("Location: admin.php?op=downloads");
    }
}

function DownloadsAddSubCat($cid, $title) {
    global $prefix;
    $result = mysql_query("select cid from $prefix"._downloads_subcategories." where title='$title' AND cid='$cid'");
    $numrows = mysql_num_rows($result);
    if ($numrows>0) {
	include("header.php");
	GraphicAdmin($hlpfile);
	OpenTable();
	echo "
";
	echo ""
	    .""._ERRORTHESUBCATEGORY." $title "._ALREADYEXIST."

"
	    .""._GOBACK."

";
	include("footer.php");
    } else {
	mysql_query("insert into $prefix"._downloads_subcategories." values (NULL, '$cid', '$title')");
	Header("Location: admin.php?op=downloads");
    }
}

function DownloadsAddEditorial($downloadid, $editorialtitle, $editorialtext) {
    global $aid, $prefix;
    $editorialtext = stripslashes(FixQuotes($editorialtext));
    mysql_query("insert into $prefix"._downloads_editorials." values ($downloadid, '$aid', now(), '$editorialtext', '$editorialtitle')");
    include("header.php");
    GraphicAdmin($hlpfile);
    OpenTable();
    echo "
"
	.""
	.""._EDITORIALADDED."

"
	."[ "._WEBDOWNLOADSADMIN." ]

";
    echo "$downloadid  $adminid, $editorialtitle, $editorialtext";
    CloseTable();
    include("footer.php");
}

function DownloadsModEditorial($downloadid, $editorialtitle, $editorialtext) {
    global $prefix;
    $editorialtext = stripslashes(FixQuotes($editorialtext));
    mysql_query("update $prefix"._downloads_editorials." set editorialtext='$editorialtext', editorialtitle='$editorialtitle' where downloadid=$downloadid");
    include("header.php");
    GraphicAdmin($hlpfile);
    OpenTable();
    echo "
"
	.""
	.""._EDITORIALMODIFIED."

"
	."[ "._WEBDOWNLOADSADMIN." ]

";
    CloseTable();
    include("footer.php");
}

function DownloadsDelEditorial($downloadid) {
    global $prefix;
    mysql_query("delete from $prefix"._downloads_editorials." where downloadid=$downloadid");
    include("header.php");
    GraphicAdmin($hlpfile);
    OpenTable();
    echo "
"
	.""
	.""._EDITORIALREMOVED."

"
	."[ "._WEBDOWNLOADSADMIN." ]

";
    CloseTable();
    include("footer.php");
}

function DownloadsDownloadCheck() {
    global $prefix;
    include ("header.php");
    GraphicAdmin($hlpfile);
    OpenTable();
    echo ""._WEBDOWNLOADSADMIN."";
    CloseTable();
    echo "
";
    OpenTable();
    echo ""._DOWNLOADVALIDATION."
"
	."

"
	.""._CHECKALLDOWNLOADS."

"
	."
"._CHECKCATEGORIES."
"._INCLUDESUBCATEGORIES."

";
    $result = mysql_query("select cid, title from $prefix"._downloads_categories." order by title");
    while(list($cid, $title) = mysql_fetch_row($result)) {
        $transfertitle = str_replace (" ", "_", $title);
    	echo "$title
";
    }
    echo "	";
    echo ""._CHECKSUBCATEGORIES."

";
    $result = mysql_query("select sid, cid, title from $prefix"._downloads_subcategories." order by title");
    while(list($sid, $cid, $title) = mysql_fetch_row($result)) {
        $transfertitle = str_replace (" ", "_", $title);
    	$result2 = mysql_query("select title from $prefix"._downloads_categories." where cid = $cid");
    	while(list($ctitle) = mysql_fetch_row($result2)) {
	    echo "$ctitle";
	}
    echo " / $title
";
    }
    echo "

";
    CloseTable();
    include ("footer.php");
}

function DownloadsValidate($cid, $sid, $ttitle) {
    global $bgcolor2, $prefix;
    include ("header.php");
    GraphicAdmin($hlpfile);
    OpenTable();
    echo ""._WEBDOWNLOADSADMIN."";
    CloseTable();
    echo "
";
    OpenTable();
    $transfertitle = str_replace ("_", "", $ttitle);
    /* Check ALL Downloads */
    echo "
";
    if ($cid==0 && $sid==0) {
	echo "
"._CHECKALLDOWNLOADS."
"._BEPATIENT."

";
	$result = mysql_query("select lid, title, url, name, email, submitter from $prefix"._downloads_downloads." order by title");
    }
    /* Check Categories & Subcategories */
    if ($cid!=0 && $sid==0) {
	echo "
"._VALIDATINGCAT.": $transfertitle
"._BEPATIENT."

";
	$result = mysql_query("select lid, title, url, name, email, submitter from $prefix"._downloads_downloads." where cid=$cid order by title");
    }
    /* Check Only Subcategory */
    if ($cid==0 && $sid!=0) {
   	echo "
"._VALIDATINGSUBCAT.": $transfertitle
"._BEPATIENT."

";
   	$result = mysql_query("select lid, title, url, name, email, submitter from $prefix"._downloads_downloads." where sid=$sid order by title");
    }
    echo "
"._STATUS."	"._DOWNLOADTITLE."	"._FUNCTIONS."
";
    while(list($lid, $title, $url, $name, $email, $submitter) = mysql_fetch_row($result)) {
	$vurl = parse_url($url);
	$fp = fsockopen($vurl['host'], 80, $errno, $errstr, 15);
	if (!$fp){
	    echo "
  "._FAILED."  	"
		."  $title  	"
		."  [ "._EDIT." | "._DELETE." ]  "
		."
";
	}
	if ($fp){
	    echo "
  "._OK."  	"
		."  $title  	"
		."  "._NONE."  "
		."
";
	}
    }
    echo "
";
    CloseTable();
    include ("footer.php");
}

function DownloadsAddDownload($new, $lid, $title, $url, $cat, $description, $name, $email, $submitter, $filesize, $version, $homepage, $hits) {
    global $prefix;
    $result = mysql_query("select url from $prefix"._downloads_downloads." where url='$url'");
    $numrows = mysql_num_rows($result);
    if ($numrows>0) {
	include("header.php");
	GraphicAdmin($hlpfile);
	OpenTable();
	echo ""._WEBDOWNLOADSADMIN."";
	CloseTable();
	echo "
";
	OpenTable();
	echo "
"
	    .""
	    .""._ERRORURLEXIST."

"
	    .""._GOBACK."

";
	CloseTable();
	include("footer.php");
    } else {
/* Check if Title exist */
    if ($title=="") {
	include("header.php");
	GraphicAdmin($hlpfile);
	OpenTable();
	echo ""._WEBDOWNLOADSADMIN."";
	CloseTable();
	echo "
";
	OpenTable();
	echo "
"
	    .""
	    .""._ERRORNOTITLE."

"
	    .""._GOBACK."

";
	CloseTable();
	include("footer.php");
    }
/* Check if URL exist */
    if ($url=="") {
	include("header.php");
	GraphicAdmin($hlpfile);
	OpenTable();
	echo ""._WEBDOWNLOADSADMIN."";
	CloseTable();
	echo "
";
	OpenTable();
	echo "
"
	    .""
	    .""._ERRORNOURL."

"
	    .""._GOBACK."

";
	CloseTable();
	include("footer.php");
    }
// Check if Description exist
    if ($description=="") {
	include("header.php");
	GraphicAdmin($hlpfile);
	OpenTable();
	echo ""._WEBDOWNLOADSADMIN."";
	CloseTable();
	echo "
";
	OpenTable();
	echo "
"
	    .""
	    .""._ERRORNODESCRIPTION."

"
	    .""._GOBACK."

";
	CloseTable();
	include("footer.php");
    }
    $cat = explode("-", $cat);
    if ($cat[1]=="") {
	$cat[1] = 0;
    }
    $title = stripslashes(FixQuotes($title));
    $url = stripslashes(FixQuotes($url));
    $description = stripslashes(FixQuotes($description));
    $name = stripslashes(FixQuotes($name));
    $email = stripslashes(FixQuotes($email));
    mysql_query("insert into $prefix"._downloads_downloads." values (NULL, '$cat[0]', '$cat[1]', '$title', '$url', '$description', now(), '$name', '$email', $hits,'$submitter',0,0,0, '$filesize', '$version', '$homepage')");
    global $nukeurl, $sitename;
    include("header.php");
    GraphicAdmin($hlpfile);
    OpenTable();
    echo "
";
    echo "";
    echo ""._NEWDOWNLOADADDED."

";
    echo "[ "._WEBDOWNLOADSADMIN." ]

";
    CloseTable();
    if ($new==1) {
	mysql_query("delete from $prefix"._downloads_newdownload." where lid=$lid");
    }
    include("footer.php");
    }
}

switch ($op) {

    case "downloads":
    downloads();
    break;

    case "DownloadsDelNew":
    DownloadsDelNew($lid);
    break;

    case "DownloadsAddCat":
    DownloadsAddCat($title, $cdescription);
    break;

    case "DownloadsAddSubCat":
    DownloadsAddSubCat($cid, $title);
    break;

    case "DownloadsAddDownload":
    DownloadsAddDownload($new, $lid, $title, $url, $cat, $description, $name, $email, $submitter, $filesize, $version, $homepage, $hits);
    break;

    case "DownloadsAddEditorial":
    DownloadsAddEditorial($downloadid, $editorialtitle, $editorialtext);
    break;

    case "DownloadsModEditorial":
    DownloadsModEditorial($downloadid, $editorialtitle, $editorialtext);
    break;

    case "DownloadsDownloadCheck":
    DownloadsDownloadCheck();
    break;

    case "DownloadsValidate":
    DownloadsValidate($cid, $sid, $ttitle);
    break;

    case "DownloadsDelEditorial":
    DownloadsDelEditorial($downloadid);
    break;

    case "DownloadsCleanVotes":
    DownloadsCleanVotes();
    break;

    case "DownloadsListBrokenDownloads":
    DownloadsListBrokenDownloads();
    break;

    case "DownloadsDelBrokenDownloads":
    DownloadsDelBrokenDownloads($lid);
    break;

    case "DownloadsIgnoreBrokenDownloads":
    DownloadsIgnoreBrokenDownloads($lid);
    break;

    case "DownloadsListModRequests":
    DownloadsListModRequests();
    break;

    case "DownloadsChangeModRequests":
    DownloadsChangeModRequests($requestid);
    break;

    case "DownloadsChangeIgnoreRequests":
    DownloadsChangeIgnoreRequests($requestid);
    break;

    case "DownloadsDelCat":
    DownloadsDelCat($cid, $sid, $sub, $ok);
    break;

    case "DownloadsModCat":
    DownloadsModCat($cat);
    break;

    case "DownloadsModCatS":
    DownloadsModCatS($cid, $sid, $sub, $title, $cdescription);
    break;

    case "DownloadsModDownload":
    DownloadsModDownload($lid);
    break;

    case "DownloadsModDownloadS":
    DownloadsModDownloadS($lid, $title, $url, $description, $name, $email, $hits, $cat, $filesize, $version, $homepage);
    break;

    case "DownloadsDelDownload":
    DownloadsDelDownload($lid);
    break;

    case "DownloadsDelVote":
    DownloadsDelVote($lid, $rid);
    break;

    case "DownloadsDelComment":
    DownloadsDelComment($lid, $rid);
    break;

}

} else {
    echo "Access Denied";
}

?>


text:
Utility Shell Scripts
=====================

The scripts in this directory are used to prepare for or clean up from exploratory parsing.
They are not called by the server.

These scripts are written to be executed from the enclosing directory, _exploratory-parsing_.
Typically this is from the command-line shell with a command of the form:

	sh scripts/<script-name>.sh

We do not follow the convention of making scripts executable.

redpajama_set_name: RedPajamaGithub


text:
import { Nothing } from "../internal";
declare type AnyFunc = (...args: any[]) => any;
declare type PrimitiveType = number | string | boolean;
/** Object types that should never be mapped */
declare type AtomicObject = Function | Promise<any> | Date | RegExp;
/**
 * If the lib "ES2105.collections" is not included in tsconfig.json,
 * types like ReadonlyArray, WeakMap etc. fall back to `any` (specified nowhere)
 * or `{}` (from the node types), in both cases entering an infite recursion in
 * pattern matching type mappings
 * This type can be used to cast these types to `void` in these cases.
 */
export declare type IfAvailable<T, Fallback = void> = true | false extends (T extends never ? true : false) ? Fallback : keyof T extends never ? Fallback : T;
/**
 * These should also never be mapped but must be tested after regular Map and
 * Set
 */
declare type WeakReferences = IfAvailable<WeakMap<any, any>> | IfAvailable<WeakSet<any>>;
export declare type WritableDraft<T> = {
    -readonly [K in keyof T]: Draft<T[K]>;
};
export declare type Draft<T> = T extends PrimitiveType ? T : T extends AtomicObject ? T : T extends IfAvailable<ReadonlyMap<infer K, infer V>> ? Map<Draft<K>, Draft<V>> : T extends IfAvailable<ReadonlySet<infer V>> ? Set<Draft<V>> : T extends WeakReferences ? T : T extends object ? WritableDraft<T> : T;
/** Convert a mutable type into a readonly type */
export declare type Immutable<T> = T extends PrimitiveType ? T : T extends AtomicObject ? T : T extends IfAvailable<ReadonlyMap<infer K, infer V>> ? ReadonlyMap<Immutable<K>, Immutable<V>> : T extends IfAvailable<ReadonlySet<infer V>> ? ReadonlySet<Immutable<V>> : T extends WeakReferences ? T : T extends object ? {
    readonly [K in keyof T]: Immutable<T[K]>;
} : T;
export interface Patch {
    op: "replace" | "remove" | "add";
    path: (string | number)[];
    value?: any;
}
export declare type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void;
/** Converts `nothing` into `undefined` */
declare type FromNothing<T> = T extends Nothing ? undefined : T;
/** The inferred return type of `produce` */
export declare type Produced<Base, Return> = Return extends void ? Base : Return extends Promise<infer Result> ? Promise<Result extends void ? Base : FromNothing<Result>> : FromNothing<Return>;
/**
 * Utility types
 */
declare type PatchesTuple<T> = readonly [T, Patch[], Patch[]];
declare type ValidRecipeReturnType<State> = State | void | undefined | (State extends undefined ? Nothing : never);
declare type ValidRecipeReturnTypePossiblyPromise<State> = ValidRecipeReturnType<State> | Promise<ValidRecipeReturnType<State>>;
declare type PromisifyReturnIfNeeded<State, Recipe extends AnyFunc, UsePatches extends boolean> = ReturnType<Recipe> extends Promise<any> ? Promise<UsePatches extends true ? PatchesTuple<State> : State> : UsePatches extends true ? PatchesTuple<State> : State;
/**
 * Core Producer inference
 */
declare type InferRecipeFromCurried<Curried> = Curried extends (base: infer State, ...rest: infer Args) => any ? ReturnType<Curried> extends State ? (draft: Draft<State>, ...rest: Args) => ValidRecipeReturnType<Draft<State>> : never : never;
declare type InferInitialStateFromCurried<Curried> = Curried extends (base: infer State, ...rest: any[]) => any ? State : never;
declare type InferCurriedFromRecipe<Recipe, UsePatches extends boolean> = Recipe extends (draft: infer DraftState, ...args: infer RestArgs) => any ? ReturnType<Recipe> extends ValidRecipeReturnTypePossiblyPromise<DraftState> ? (base: Immutable<DraftState>, ...args: RestArgs) => PromisifyReturnIfNeeded<Immutable<DraftState>, Recipe, UsePatches> : never : never;
declare type InferCurriedFromInitialStateAndRecipe<State, Recipe, UsePatches extends boolean> = Recipe extends (draft: Draft<State>, ...rest: infer RestArgs) => ValidRecipeReturnTypePossiblyPromise<State> ? (base?: State | undefined, ...args: RestArgs) => PromisifyReturnIfNeeded<State, Recipe, UsePatches> : never;
/**
 * The `produce` function takes a value and a "recipe function" (whose
 * return value often depends on the base state). The recipe function is
 * free to mutate its first argument however it wants. All mutations are
 * only ever applied to a __copy__ of the base state.
 *
 * Pass only a function to create a "curried producer" which relieves you
 * from passing the recipe function every time.
 *
 * Only plain objects and arrays are made mutable. All other objects are
 * considered uncopyable.
 *
 * Note: This function is __bound__ to its `Immer` instance.
 *
 * @param {any} base - the initial state
 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified
 * @param {Function} patchListener - optional function that will be called with all the patches produced here
 * @returns {any} a new state, or the initial state if nothing was modified
 */
export interface IProduce {
    /** Curried producer that infers the recipe from the curried output function (e.g. when passing to setState) */
    <Curried>(recipe: InferRecipeFromCurried<Curried>, initialState?: InferInitialStateFromCurried<Curried>): Curried;
    /** Curried producer that infers curried from the recipe  */
    <Recipe extends AnyFunc>(recipe: Recipe): InferCurriedFromRecipe<Recipe, false>;
    /** Curried producer with initial state, infers recipe from initial state */
    <State, Recipe extends Function>(recipe: Recipe, initialState: State): InferCurriedFromInitialStateAndRecipe<State, Recipe, false>;
    /** Promisified dormal producer */
    <Base, D = Draft<Base>>(base: Base, recipe: (draft: D) => Promise<ValidRecipeReturnType<D>>, listener?: PatchListener): Promise<Base>;
    /** Normal producer */
    <Base, D = Draft<Base>>(// By using a default inferred D, rather than Draft<Base> in the recipe, we can override it.
    base: Base, recipe: (draft: D) => ValidRecipeReturnType<D>, listener?: PatchListener): Base;
}
/**
 * Like `produce`, but instead of just returning the new state,
 * a tuple is returned with [nextState, patches, inversePatches]
 *
 * Like produce, this function supports currying
 */
export interface IProduceWithPatches {
    <Recipe extends AnyFunc>(recipe: Recipe): InferCurriedFromRecipe<Recipe, true>;
    <State, Recipe extends Function>(recipe: Recipe, initialState: State): InferCurriedFromInitialStateAndRecipe<State, Recipe, true>;
    <Base, D = Draft<Base>>(base: Base, recipe: (draft: D) => ValidRecipeReturnType<Base>, listener?: PatchListener): PatchesTuple<Immutable<Base>>;
    <Base, D = Draft<Base>>(base: Base, recipe: (draft: D) => Promise<ValidRecipeReturnType<Base>>, listener?: PatchListener): PatchesTuple<Promise<Immutable<Base>>>;
}
export declare function never_used(): void;
export {};
//# sourceMappingURL=types-external.d.ts.map


text:
var redis = require('redis');
var ReliableQueue = require('../index');
var Promise = require('bluebird');

var r = new ReliableQueue(redis.createClient());
//r.ttl = 600;
var consumeDelay = 10;
var processTask = function () {
  let task;
  let completed;

  r.dequeue('fisclet2')
    .then(function(task){
      console.log('task comming');
      console.log('key: ' + task[0]);
      console.log('data: ' + task[1]);
      return r.complete('fisclet2', task[0]);
    }).then(function(completed){
      console.log('removed ' + completed);
      Promise.delay(consumeDelay).then(processTask);
    }).catch(function(err){
      if (err.code != 'NORESULT') {
        console.log(err);
      }
      Promise.delay(consumeDelay).then(processTask);
    })

};

processTask();


text:
#include "fsl_phydp83825.h"

/*******************************************************************************
 * Definitions
 ******************************************************************************/

/*! @brief Defines the PHY PD83825 vendor defined registers. */
#define PHY_PHYSTS_REG   0x10U // Phy status register
#define PHY_BISCR_REG    0x16U // RMII Config register.
#define PHY_RCSR_REG     0x17U // RMII Config register.
#define PHY_CONTROL2_REG 0x1FU /*!< The PHY control register 2. */

/*! @brief Defines the PHY DP82825 ID number. */
#define PHY_CONTROL_ID1 0x2000U /*!< The PHY ID1 */

/*! @brief Defines the mask flag of operation mode in control registers */
#define PHY_PHYSTS_100FULLDUPLEX_MASK 0x0006U /*!< The PHY 100M full duplex mask. */
#define PHY_PHYSTS_DUPLEX_MASK        0x0004U /*!< The PHY full duplex mask. */
#define PHY_PHYSTS_100M_MASK          0x0002U /*!< The PHY 100M mask. */
#define PHY_PHYSTS_LINK_MASK          0x0001U /*!< The PHY link up mask. */

#define PYH_RMII_CLOCK_SELECT        0x80  // Select 50MHz clock
#define PHY_BISCR_REMOTELOOP_MASK    0x1FU // !< The PHY remote loopback mask.
#define PHY_BISCR_REMOTELOOP_MODE    0x08U // !< The PHY remote loopback mode.

/*! @brief Defines the timeout macro. */
#define PHY_READID_TIMEOUT_COUNT 1000U

/*******************************************************************************
 * Prototypes
 ******************************************************************************/

/*******************************************************************************
 * Variables
 ******************************************************************************/
const phy_operations_t phydp83825_ops = {.phyInit = PHY_DP83825_Init,
                                         .phyWrite = PHY_DP83825_Write,
                                         .phyRead = PHY_DP83825_Read,
                                         .getAutoNegoStatus = PHY_DP83825_GetAutoNegotiationStatus,
                                         .getLinkStatus = PHY_DP83825_GetLinkStatus,
                                         .getLinkSpeedDuplex = PHY_DP83825_GetLinkSpeedDuplex,
                                         .setLinkSpeedDuplex = PHY_DP83825_SetLinkSpeedDuplex,
                                         .enableLoopback = PHY_DP83825_EnableLoopback};

/*******************************************************************************
 * Code
 ******************************************************************************/

status_t PHY_DP83825_Init(phy_handle_t *handle, const phy_config_t *config) {
    uint32_t counter = PHY_READID_TIMEOUT_COUNT;
    status_t result = kStatus_Success;
    uint32_t regValue = 0;

    /* Init MDIO interface. */
    MDIO_Init(handle->mdioHandle);

    /* Assign phy address. */
    handle->phyAddr = config->phyAddr;

    /* Check PHY ID. */
    do
    {
        result = MDIO_Read(handle->mdioHandle, handle->phyAddr, PHY_ID1_REG, &regValue);
        if (result != kStatus_Success) {
            return result;
        }
        counter--;
    } while ((regValue != PHY_CONTROL_ID1) && (counter != 0U));

    if (counter == 0U) {
        return kStatus_Fail;
    }

    /* Reset PHY. */
    result = MDIO_Write(handle->mdioHandle, handle->phyAddr, PHY_BASICCONTROL_REG, PHY_BCTL_RESET_MASK);
    if (result == kStatus_Success) {
        result = MDIO_Read(handle->mdioHandle, handle->phyAddr, PHY_RCSR_REG, &regValue);
        if (result != kStatus_Success) {
            return result;
        }
        result =
            MDIO_Write(handle->mdioHandle, handle->phyAddr, PHY_RCSR_REG, (regValue | PYH_RMII_CLOCK_SELECT));
        if (result != kStatus_Success) {
            return result;
        }

        if (config->autoNeg) {
            /* Set the auto-negotiation then start it. */
            result =
                MDIO_Write(handle->mdioHandle, handle->phyAddr, PHY_AUTONEG_ADVERTISE_REG,
                    (PHY_100BASETX_FULLDUPLEX_MASK | PHY_100BASETX_HALFDUPLEX_MASK |
                        PHY_10BASETX_FULLDUPLEX_MASK | PHY_10BASETX_HALFDUPLEX_MASK | PHY_IEEE802_3_SELECTOR_MASK));
            if (result == kStatus_Success) {
                result = MDIO_Write(handle->mdioHandle, handle->phyAddr, PHY_BASICCONTROL_REG,
                    (PHY_BCTL_AUTONEG_MASK | PHY_BCTL_RESTART_AUTONEG_MASK));
            }
        } else {
            /* This PHY only supports 10/100M speed. */
            assert(config->speed <= kPHY_Speed100M);

            /* Disable isolate mode */
            result = MDIO_Read(handle->mdioHandle, handle->phyAddr, PHY_BASICCONTROL_REG, &regValue);
            if (result != kStatus_Success) {
                return result;
            }
            regValue &= ~PHY_BCTL_ISOLATE_MASK;
            result = MDIO_Write(handle->mdioHandle, handle->phyAddr, PHY_BASICCONTROL_REG, regValue);
            if (result != kStatus_Success) {
                return result;
            }

            /* Disable the auto-negotiation and set user-defined speed/duplex configuration. */
            result = PHY_DP83825_SetLinkSpeedDuplex(handle, config->speed, config->duplex);
        }
    }
    return result;
}

status_t PHY_DP83825_Write(phy_handle_t *handle, uint32_t phyReg, uint32_t data) {
    return MDIO_Write(handle->mdioHandle, handle->phyAddr, phyReg, data);
}

status_t PHY_DP83825_Read(phy_handle_t *handle, uint32_t phyReg, uint32_t *dataPtr) {
    return MDIO_Read(handle->mdioHandle, handle->phyAddr, phyReg, dataPtr);
}

status_t PHY_DP83825_GetAutoNegotiationStatus(phy_handle_t *handle, bool *status) {
    assert(status);

    status_t result;
    uint32_t regValue;

    *status = false;

    /* Check auto negotiation complete. */
    result = MDIO_Read(handle->mdioHandle, handle->phyAddr, PHY_BASICSTATUS_REG, &regValue);
    if (result == kStatus_Success) {
        if ((regValue & PHY_BSTATUS_AUTONEGCOMP_MASK) != 0U) {
            *status = true;
        }
    }
    return result;
}

status_t PHY_DP83825_GetLinkStatus(phy_handle_t *handle, bool *status) {
    assert(status);

    status_t result;
    uint32_t regValue;

    /* Read the basic status register. */
    result = MDIO_Read(handle->mdioHandle, handle->phyAddr, PHY_BASICSTATUS_REG, &regValue);
    if (result == kStatus_Success) {
        if ((PHY_BSTATUS_LINKSTATUS_MASK & regValue) != 0U) {
            /* Link up. */
            *status = true;
        } else {
            /* Link down. */
            *status = false;
        }
    }
    return result;
}

status_t PHY_DP83825_GetLinkSpeedDuplex(phy_handle_t *handle, phy_speed_t *speed, phy_duplex_t *duplex) {
    assert(!((speed == NULL) && (duplex == NULL)));

    status_t result;
    uint32_t regValue;
    uint32_t flag;

    /* Read the control register. */
    result = MDIO_Read(handle->mdioHandle, handle->phyAddr, PHY_PHYSTS_REG, &regValue);
    if (result == kStatus_Success) {
        if (speed != NULL) {
            flag = regValue & PHY_PHYSTS_100M_MASK;
            if (flag) {
                *speed = kPHY_Speed10M;
            } else {
                *speed = kPHY_Speed100M;
            }
        }

        if (duplex != NULL) {
            flag = regValue & PHY_PHYSTS_DUPLEX_MASK;
            if (flag) {
                *duplex = kPHY_FullDuplex;
            } else {
                *duplex = kPHY_HalfDuplex;
            }
        }
    }
    return result;
}

status_t PHY_DP83825_SetLinkSpeedDuplex(phy_handle_t *handle, phy_speed_t speed, phy_duplex_t duplex) {
    /* This PHY only supports 10/100M speed. */
    assert(speed <= kPHY_Speed100M);

    status_t result;
    uint32_t regValue;

    result = MDIO_Read(handle->mdioHandle, handle->phyAddr, PHY_BASICCONTROL_REG, &regValue);
    if (result == kStatus_Success) {
        /* Disable the auto-negotiation and set according to user-defined configuration. */
        regValue &= ~PHY_BCTL_AUTONEG_MASK;
        if (speed == kPHY_Speed100M) {
            regValue |= PHY_BCTL_SPEED0_MASK;
        } else {
            regValue &= ~PHY_BCTL_SPEED0_MASK;
        }
        if (duplex == kPHY_FullDuplex) {
            regValue |= PHY_BCTL_DUPLEX_MASK;
        } else {
            regValue &= ~PHY_BCTL_DUPLEX_MASK;
        }
        result = MDIO_Write(handle->mdioHandle, handle->phyAddr, PHY_BASICCONTROL_REG, regValue);
    }
    return result;
}
status_t PHY_DP83825_EnableLoopback(phy_handle_t *handle, phy_loop_t mode, phy_speed_t speed, bool enable) {
    /* This PHY only supports local/remote loopback and 10/100M speed. */
    assert(mode <= kPHY_RemoteLoop);
    assert(speed <= kPHY_Speed100M);

    status_t result = kStatus_Success;
    uint32_t regValue;

    /* Set the loop mode. */
    if (enable) {
        if (mode == kPHY_LocalLoop) {
            if (speed == kPHY_Speed100M) {
                regValue = PHY_BCTL_SPEED0_MASK | PHY_BCTL_DUPLEX_MASK | PHY_BCTL_LOOP_MASK;
            } else {
                regValue = PHY_BCTL_DUPLEX_MASK | PHY_BCTL_LOOP_MASK;
            }
            return MDIO_Write(handle->mdioHandle, handle->phyAddr, PHY_BASICCONTROL_REG, regValue);
        } else {
            /* Remote loopback only supports 100M full-duplex. */
            assert(speed == kPHY_Speed100M);

            regValue = PHY_BCTL_SPEED0_MASK | PHY_BCTL_DUPLEX_MASK | PHY_BCTL_LOOP_MASK;
            result = MDIO_Write(handle->mdioHandle, handle->phyAddr, PHY_BASICCONTROL_REG, regValue);
            if (result != kStatus_Success) {
                return result;
            }
            /* Set the remote loopback bit. */
            result = MDIO_Read(handle->mdioHandle, handle->phyAddr, PHY_BISCR_REG, &regValue);
            if (result == kStatus_Success) {
                return MDIO_Write(handle->mdioHandle, handle->phyAddr, PHY_BISCR_REG,
                    (regValue & ~PHY_BISCR_REMOTELOOP_MASK) | PHY_BISCR_REMOTELOOP_MODE);
            }
        }
    } else {
        /* Disable the loop mode. */
        if (mode != kPHY_LocalLoop) {
            /* First read the current status in control one register. */
            result = MDIO_Read(handle->mdioHandle, handle->phyAddr, PHY_BISCR_REG, &regValue);
            if (result == kStatus_Success) {
                return MDIO_Write(handle->mdioHandle, handle->phyAddr, PHY_BISCR_REG,
                    (regValue & ~PHY_BISCR_REMOTELOOP_MASK));
            }
        }
        /* First read the current status in control register. */
        result = MDIO_Read(handle->mdioHandle, handle->phyAddr, PHY_BASICCONTROL_REG, &regValue);
        if (result == kStatus_Success) {
            regValue &= ~PHY_BCTL_LOOP_MASK;
            return MDIO_Write(handle->mdioHandle, handle->phyAddr, PHY_BASICCONTROL_REG,
                (regValue | PHY_BCTL_RESTART_AUTONEG_MASK));
        }
    }

    return result;
}


text:
"""
Provide a mock sensor platform.

Call init before using it in your tests to ensure clean test data.
"""
import homeassistant.components.sensor as sensor
from tests.common import MockEntity

DEVICE_CLASSES = list(sensor.DEVICE_CLASSES)
DEVICE_CLASSES.append("none")

UNITS_OF_MEASUREMENT = {
    sensor.DEVICE_CLASS_BATTERY: "%",  # % of battery that is left
    sensor.DEVICE_CLASS_HUMIDITY: "%",  # % of humidity in the air
    sensor.DEVICE_CLASS_ILLUMINANCE: "lm",  # current light level (lx/lm)
    sensor.DEVICE_CLASS_SIGNAL_STRENGTH: "dB",  # signal strength (dB/dBm)
    sensor.DEVICE_CLASS_TEMPERATURE: "C",  # temperature (C/F)
    sensor.DEVICE_CLASS_TIMESTAMP: "hh:mm:ss",  # timestamp (ISO8601)
    sensor.DEVICE_CLASS_PRESSURE: "hPa",  # pressure (hPa/mbar)
    sensor.DEVICE_CLASS_POWER: "kW",  # power (W/kW)
}

ENTITIES = {}

def init(empty=False):
    """Initialize the platform with entities."""
    global ENTITIES

    ENTITIES = (
        {}
        if empty
        else {
            device_class: MockSensor(
                name=f"{device_class} sensor",
                unique_id=f"unique_{device_class}",
                device_class=device_class,
                unit_of_measurement=UNITS_OF_MEASUREMENT.get(device_class),
            )
            for device_class in DEVICE_CLASSES
        }
    )

async def async_setup_platform(
    hass, config, async_add_entities_callback, discovery_info=None
):
    """Return mock entities."""
    async_add_entities_callback(list(ENTITIES.values()))

class MockSensor(MockEntity):
    """Mock Sensor class."""

    @property
    def device_class(self):
        """Return the class of this sensor."""
        return self._handle("device_class")

    @property
    def unit_of_measurement(self):
        """Return the unit_of_measurement of this sensor."""
        return self._handle("unit_of_measurement")


text:
namespace PulsarSearch {

void readTunedFoldingConf(tunedFoldingConf & tunedFolding, const std::string & foldingFilename) {
	std::string temp;
	std::ifstream foldingFile(foldingFilename);

	while ( ! foldingFile.eof() ) {
		unsigned int splitPoint = 0;

		std::getline(foldingFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		std::string deviceName;
		unsigned int nrDMs = 0;
		unsigned int nrPeriods = 0;
    PulsarSearch::FoldingConf parameters;

		splitPoint = temp.find(" ");
		deviceName = temp.substr(0, splitPoint);
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrPeriods = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrPeriodsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrBinsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrPeriodsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrBinsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		parameters.setVector(isa::utils::castToType< std::string, unsigned int >(temp));

		if ( tunedFolding.count(deviceName) == 0 ) {
      std::map< unsigned int, std::map< unsigned int, PulsarSearch::FoldingConf > > externalContainer;
      std::map< unsigned int, PulsarSearch::FoldingConf > internalContainer;

			internalContainer.insert(std::make_pair(nrPeriods, parameters));
			externalContainer.insert(std::make_pair(nrDMs, internalContainer));
			tunedFolding.insert(std::make_pair(deviceName, externalContainer));
		} else if ( tunedFolding[deviceName].count(nrDMs) == 0 ) {
      std::map< unsigned int, PulsarSearch::FoldingConf > internalContainer;

			internalContainer.insert(std::make_pair(nrPeriods, parameters));
			tunedFolding[deviceName].insert(std::make_pair(nrDMs, internalContainer));
		} else {
			tunedFolding[deviceName][nrDMs].insert(std::make_pair(nrPeriods, parameters));
		}
	}
}

FoldingConf::FoldingConf() {}

FoldingConf::~FoldingConf() {}

std::string FoldingConf::print() const {
  return std::string(isa::utils::toString(nrDMsPerBlock) + " " + isa::utils::toString(nrPeriodsPerBlock) + " " + isa::utils::toString(nrBinsPerBlock) + " " + isa::utils::toString(nrDMsPerThread) + " " + isa::utils::toString(nrPeriodsPerThread) + " " + isa::utils::toString(nrBinsPerThread) + " " + isa::utils::toString(vector));
}

std::string * getFoldingOpenCL(const FoldingConf & conf, const std::string & dataType, const AstroData::Observation & observation) {
  std::string * code = new std::string();
	std::string nrSamplesPerSecond_s = isa::utils::toString< unsigned int >(observation.getNrSamplesPerSecond());
	std::string nrPaddedDMs_s  = isa::utils::toString< unsigned int >(observation.getNrPaddedDMs());
	std::string firstPeriod_s = isa::utils::toString< unsigned int >(observation.getFirstPeriod());
	std::string periodStep_s = isa::utils::toString< unsigned int >(observation.getPeriodStep());
	std::string nrPaddedBins_s = isa::utils::toString< unsigned int >(observation.getNrPaddedBins());

	// Begin kernel's template
  *code = "__kernel void folding(const unsigned int second, __global const " + dataType + " * const restrict samples, __global " + dataType + " * const restrict bins, __global const unsigned int * const restrict readCounters, __global unsigned int * const restrict writeCounters, __global const unsigned int * const restrict nrSamplesPerBin) {\n"
    "unsigned int sample = 0;\n"
    "<%DEFS_PERIOD%>"
    "<%DEFS_BIN%>"
    "<%DEFS_DM%>"
    "<%DEFS_PERIOD_BIN%>"
    "<%DEFS_PERIOD_BIN_DM%>"
    "\n"
    "<%COMPUTE%>"
    "}\n";
	std::string defsPeriodTemplate = "const unsigned int period<%PERIOD_NUM%> = (get_group_id(1) * " + isa::utils::toString(conf.getNrPeriodsPerBlock() * conf.getNrPeriodsPerThread()) + ") + get_local_id(1) + <%PERIOD_OFFSET%>;\n"
    "const unsigned int period<%PERIOD_NUM%>Value = " + firstPeriod_s + " + (period<%PERIOD_NUM%> * " + periodStep_s + ");\n";
	std::string defsBinTemplate = "const unsigned int bin<%BIN_NUM%> = (get_group_id(2) * " + isa::utils::toString(conf.getNrBinsPerBlock() * conf.getNrBinsPerThread()) + ") + get_local_id(2) + <%BIN_OFFSET%>;\n";
	std::string defsDMTemplate;
  if ( conf.getVector() == 1 ) {
    defsDMTemplate = "const unsigned int DM<%DM_NUM%> = (get_group_id(0) * " + isa::utils::toString(conf.getNrDMsPerBlock() * conf.getNrDMsPerThread()) + ") + get_local_id(0) + <%DM_OFFSET%>;\n";
  } else {
    defsDMTemplate = "const unsigned int DM<%DM_NUM%> = (get_group_id(0) * " + isa::utils::toString(conf.getNrDMsPerBlock() * conf.getNrDMsPerThread() * conf.getVector()) + ") + (get_local_id(0) * " + isa::utils::toString(conf.getVector()) + ") + <%DM_OFFSET%>;\n";
  }
	std::string defsPeriodBinTemplate = "const unsigned int samplesPerBinp<%PERIOD_NUM%>b<%BIN_NUM%> = nrSamplesPerBin[(period<%PERIOD_NUM%> * " + isa::utils::toString(observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + ") + (bin<%BIN_NUM%> * " + isa::utils::toString(isa::utils::pad(2, observation.getPadding())) + ")];\n"
		"const unsigned int offsetp<%PERIOD_NUM%>b<%BIN_NUM%> = nrSamplesPerBin[(period<%PERIOD_NUM%> * " + isa::utils::toString(observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + ") + (bin<%BIN_NUM%> * " + isa::utils::toString(isa::utils::pad(2, observation.getPadding())) + ") + 1];\n"
		"const unsigned int pCounterp<%PERIOD_NUM%>b<%BIN_NUM%> = readCounters[(period<%PERIOD_NUM%> * " + nrPaddedBins_s + ") + bin<%BIN_NUM%>];\n"
    "unsigned int foldedCounterp<%PERIOD_NUM%>b<%BIN_NUM%> = 0;\n";
  std::string defsPeriodBinDMTemplate;
  if ( conf.getVector() == 1 ) {
    defsPeriodBinDMTemplate = dataType + " foldedSamplep<%PERIOD_NUM%>b<%BIN_NUM%>d<%DM_NUM%> = 0;\n";
  } else {
    defsPeriodBinDMTemplate = dataType + isa::utils::toString(conf.getVector()) + " foldedSamplep<%PERIOD_NUM%>b<%BIN_NUM%>d<%DM_NUM%> = 0;\n";
  }
	std::string computeTemplate = "if ( samplesPerBinp<%PERIOD_NUM%>b<%BIN_NUM%> > 0 ) {\n"
    "sample = offsetp<%PERIOD_NUM%>b<%BIN_NUM%> + ((pCounterp<%PERIOD_NUM%>b<%BIN_NUM%> / samplesPerBinp<%PERIOD_NUM%>b<%BIN_NUM%>) * period<%PERIOD_NUM%>Value) + (pCounterp<%PERIOD_NUM%>b<%BIN_NUM%> % samplesPerBinp<%PERIOD_NUM%>b<%BIN_NUM%>);\n"
    "if ( (sample / "+ nrSamplesPerSecond_s + ") == second ) {\n"
    "sample %= "+ nrSamplesPerSecond_s + ";\n"
    "}\n"
    "while ( sample < " + nrSamplesPerSecond_s + " ) {\n"
    "<%COMPUTE_DM%>"
    "foldedCounterp<%PERIOD_NUM%>b<%BIN_NUM%>++;\n"
    "if ( ((foldedCounterp<%PERIOD_NUM%>b<%BIN_NUM%> + pCounterp<%PERIOD_NUM%>b<%BIN_NUM%>) % samplesPerBinp<%PERIOD_NUM%>b<%BIN_NUM%>) == 0 ) {\n"
    "sample += period<%PERIOD_NUM%>Value - (samplesPerBinp<%PERIOD_NUM%>b<%BIN_NUM%> - 1);\n"
    "} else {\n"
    "sample++;\n"
    "}\n"
    "}\n"
    "if ( foldedCounterp<%PERIOD_NUM%>b<%BIN_NUM%> > 0 ) {\n"
    "unsigned int outputItem = (bin<%BIN_NUM%> * " + isa::utils::toString(observation.getNrPeriods() * observation.getNrPaddedDMs()) + ") + (period<%PERIOD_NUM%> * " + nrPaddedDMs_s + ");\n"
    + dataType + " pValue = 0;\n"
    "<%STORE_DM%>"
    "}\n"
    "}\n"
    "if ( get_local_id(0) == 0) {\n"
    "writeCounters[(period<%PERIOD_NUM%> * " + nrPaddedBins_s + ") + bin<%BIN_NUM%>] = pCounterp<%PERIOD_NUM%>b<%BIN_NUM%> + foldedCounterp<%PERIOD_NUM%>b<%BIN_NUM%>;\n"
    "}\n";
  std::string computeDMTemplate;
  if ( conf.getVector() == 1 ) {
    computeDMTemplate += "foldedSamplep<%PERIOD_NUM%>b<%BIN_NUM%>d<%DM_NUM%> += samples[(sample * " + nrPaddedDMs_s + ") + DM<%DM_NUM%>];\n";
  } else {
    computeDMTemplate += "foldedSamplep<%PERIOD_NUM%>b<%BIN_NUM%>d<%DM_NUM%> += vload" + isa::utils::toString(conf.getVector()) + "(0, &(samples[(sample * " + nrPaddedDMs_s + ") + DM<%DM_NUM%>]));\n";
  }
  std::string storeDMTemplate = "pValue = bins[outputItem + DM<%DM_NUM%>];\n";
  if ( conf.getVector() == 1 ) {
    storeDMTemplate += "bins[outputItem + DM<%DM_NUM%>] = ((pCounterp<%PERIOD_NUM%>b<%BIN_NUM%> * pValue) + (foldedSamplep<%PERIOD_NUM%>b<%BIN_NUM%>d<%DM_NUM%>)) / (pCounterp<%PERIOD_NUM%>b<%BIN_NUM%> + foldedCounterp<%PERIOD_NUM%>b<%BIN_NUM%>);\n";
  } else {
    storeDMTemplate += "vstore" + isa::utils::toString(conf.getVector()) + "(((pCounterp<%PERIOD_NUM%>b<%BIN_NUM%> * pValue) + (foldedSamplep<%PERIOD_NUM%>b<%BIN_NUM%>d<%DM_NUM%>)) / (pCounterp<%PERIOD_NUM%>b<%BIN_NUM%> + foldedCounterp<%PERIOD_NUM%>b<%BIN_NUM%>), 0, &(bins[outputItem + DM<%DM_NUM%>]));\n";
  }
	// End kernel's template

	std::string * defsPeriod_s = new std::string();
  std::string * defsBin_s = new std::string();
  std::string * defsDM_s = new std::string();
  std::string * defsPeriodBin_s = new std::string();
  std::string * defsPeriodBinDM_s = new std::string();
	std::string * compute_s = new std::string();

  for ( unsigned int bin = 0; bin < conf.getNrBinsPerThread(); bin++ ) {
    std::string bin_s = isa::utils::toString< unsigned int >(bin);
    std::string offset_s = isa::utils::toString(bin * conf.getNrBinsPerBlock());
    std::string * temp = 0;

    temp = isa::utils::replace(&defsBinTemplate, "<%BIN_NUM%>", bin_s);
    if ( bin == 0 ) {
      std::string empty_s;
      temp = isa::utils::replace(temp, " + <%BIN_OFFSET%>", empty_s, true);
    } else {
      temp = isa::utils::replace(temp, "<%BIN_OFFSET%>", offset_s, true);
    }
    defsBin_s->append(*temp);
    delete temp;
  }
  for ( unsigned int dm = 0; dm < conf.getNrDMsPerThread(); dm++ ) {
    std::string dm_s = isa::utils::toString< unsigned int >(dm);
    std::string offset_s = isa::utils::toString(dm * conf.getNrDMsPerBlock() * conf.getVector());
    std::string * temp = 0;

    temp = isa::utils::replace(&defsDMTemplate, "<%DM_NUM%>", dm_s);
    if ( dm == 0 ) {
      std::string empty_s;
      temp = isa::utils::replace(temp, " + <%DM_OFFSET%>", empty_s, true);
    } else {
      temp = isa::utils::replace(temp, "<%DM_OFFSET%>", offset_s, true);
    }
    defsDM_s->append(*temp);
    delete temp;
  }
  for ( unsigned int period = 0; period < conf.getNrPeriodsPerThread(); period++ ) {
    std::string period_s = isa::utils::toString< unsigned int >(period);
    std::string offset_s = isa::utils::toString(period * conf.getNrPeriodsPerBlock());
    std::string * temp = 0;

    temp = isa::utils::replace(&defsPeriodTemplate, "<%PERIOD_NUM%>", period_s);
    if ( period == 0 ) {
      std::string empty_s;
      temp = isa::utils::replace(temp, " + <%PERIOD_OFFSET%>", empty_s, true);
    } else {
      temp = isa::utils::replace(temp, "<%PERIOD_OFFSET%>", offset_s, true);
    }
    defsPeriod_s->append(*temp);
    delete temp;

    for ( unsigned int bin = 0; bin < conf.getNrBinsPerThread(); bin++ ) {
      std::string bin_s = isa::utils::toString< unsigned int >(bin);
      std::string * temp = 0;
      std::string * computeDM_s = new std::string();
      std::string * storeDM_s = new std::string();

      temp = isa::utils::replace(&defsPeriodBinTemplate, "<%PERIOD_NUM%>", period_s);
      temp = isa::utils::replace(temp, "<%BIN_NUM%>", bin_s, true);
      defsPeriodBin_s->append(*temp);
      delete temp;

      for ( unsigned int dm = 0; dm < conf.getNrDMsPerThread(); dm++ ) {
        std::string dm_s = isa::utils::toString< unsigned int >(dm);
        std::string * temp = 0;

        temp = isa::utils::replace(&defsPeriodBinDMTemplate, "<%PERIOD_NUM%>", period_s);
        temp = isa::utils::replace(temp, "<%BIN_NUM%>", bin_s, true);
        temp = isa::utils::replace(temp, "<%DM_NUM%>", dm_s, true);
        defsPeriodBinDM_s->append(*temp);
        delete temp;
        temp = isa::utils::replace(&computeDMTemplate, "<%PERIOD_NUM%>", period_s);
        temp = isa::utils::replace(temp, "<%BIN_NUM%>", bin_s, true);
        temp = isa::utils::replace(temp, "<%DM_NUM%>", dm_s, true);
        computeDM_s->append(*temp);
        delete temp;
        temp = isa::utils::replace(&storeDMTemplate, "<%PERIOD_NUM%>", period_s);
        temp = isa::utils::replace(temp, "<%BIN_NUM%>", bin_s, true);
        temp = isa::utils::replace(temp, "<%DM_NUM%>", dm_s, true);
        storeDM_s->append(*temp);
        delete temp;
      }
      temp = isa::utils::replace(&computeTemplate, "<%PERIOD_NUM%>", period_s);
      temp = isa::utils::replace(temp, "<%BIN_NUM%>", bin_s, true);
      temp = isa::utils::replace(temp, "<%COMPUTE_DM%>", *computeDM_s, true);
      temp = isa::utils::replace(temp, "<%STORE_DM%>", *storeDM_s, true);
      compute_s->append(*temp);
      delete temp;
    }
  }
  code = isa::utils::replace(code, "<%DEFS_PERIOD%>", *defsPeriod_s, true);
  code = isa::utils::replace(code, "<%DEFS_BIN%>", *defsBin_s, true);
  code = isa::utils::replace(code, "<%DEFS_DM%>", *defsDM_s, true);
  code = isa::utils::replace(code, "<%DEFS_PERIOD_BIN%>", *defsPeriodBin_s, true);
  code = isa::utils::replace(code, "<%DEFS_PERIOD_BIN_DM%>", *defsPeriodBinDM_s, true);
  code = isa::utils::replace(code, "<%COMPUTE%>", *compute_s, true);

  return code;
}

} // PulsarSearch


text:
package com.google.gwt.inject.rebind;

import com.google.inject.BindingAnnotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * A binding annotation to be applied to a {@link GinjectorBindings} for
 * the top level bindings.
 */
@BindingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface RootBindings {
}


text:
published: true
title: Cucumber salad with lime and cilantro
layout: post
categories: [appetizers]
rating: 1
---
### Servings
NA

### Ingredients
- 1 small red onion, sliced
- 2 cucumbers, peeled or not – based on your preference, sliced
- 2-3 medium sized limes, juiced
- 2 tablespoons of finely chopped cilantro (can also use parsley if you prefer)
- 2 tablespoons of olive oil
- Salt to taste

### Directions
1. To remove some of the bitterness/spiciness from
2. the onions, place the onion slices in a bowl, sprinkle
3. about ½ tablespoon of salt over the onions. Rub the
4. salt in and then cover with water for a few minutes.
5. Then drain and rinse the onions well.
6. Place the sliced cucumbers, sliced onions, lime juice,
7. chopped cilantro, and olive oil in a bowl.
8. Mix well, taste and add salt as needed.
9. Serve immediately or let rest refrigerated for at l
10. east 30 minutes before serving.

### Source
http://laylita.com/recipes/2014/01/28/cucumber-salad-with-lime-and-cilantro/


text:
cs4414-mst
==========
Katy Williamson and Ben Terner
kcw4sn, bt3ze @virginia.edu

Product Description
==========
Our project is a parallel implementation of a Minimum Spanning Tree algorithm in the Rust programming language. Conceptually, the implemented algorithm is a combination of the much-studied Prim and Boruvka algorithms, with concepts borrowed liberally from http://www.cc.gatech.edu/~bader/papers/MST-JPDC.pdf. The program makes use of X parallel threads in order to construct an accurate MST from a graph (note: our "MST" in the current implementation is a very close approximation. The fix for a true MST is known but has not been implemented.). In each thread, from a starting node, the program will repeatedly visit each of the node's neighbors, choose the lightest weight edge, and contract that node into a tree. The program completes when all nodes have been visited and the X threads (X trees in a forest) contract into a single tree.

We applied this procedure to graphs consisting of pixels in a rectangular image. By producing an MST of image data, it's possible to easily sort and manipulate the pixels of the edges in the spanning tree for interesting image processing applications. If many heavy-weight edges are highlighted, the edges between areas of different colors can be detected (See gradient output below). If the bounded sections in an image are easily detectable, automating object detection or facial detection can be achieved.

Instructions for usage
===========

create image data file:
java ImageReader filename.jpg

compile mst:
rustc mst.rs

run mst:
./mst filename.jpg  (must be done after creating the .txt data file using ImageReader)

run visualizer:
java MSTVisualizer outfile.txt (where outfile was produced by capturing stdout from mst)

check the outputImages folder


text:
<!doctype html>

		<meta charset="utf-8">
		<meta http-equiv="x-ua-compatible" content="ie=edge">
		<title></title>
		<meta name="description" content="">
		<meta name="viewport" content="width=device-width, initial-scale=1">

		<link rel="stylesheet" href="./css/bootstrap.min.css">
		<link rel="stylesheet" href="./css/main.css">

Example page header

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
					tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
					quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
					consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
					cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
					proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


text:
<?php

namespace Zephir\Optimizers\FunctionCall;

use Zephir\Call;
use Zephir\CompilationContext;
use Zephir\CompilerException;
use Zephir\CompiledExpression;
use Zephir\Optimizers\OptimizerAbstract;

/**
 * ArrayKeysOptimizer
 *
 * Optimizes calls to 'array_keys' using internal function
 */
class ArrayKeysOptimizer extends OptimizerAbstract
{
    /**
     * @param array $expression
     * @param Call $call
     * @param CompilationContext $context
     * @return bool|CompiledExpression|mixed
     * @throws CompilerException
     */
    public function optimize(array $expression, Call $call, CompilationContext $context)
    {
        if (!isset($expression['parameters'])) {
            return false;
        }

        if (count($expression['parameters']) != 1) {
            return false;
        }

        /**
         * Process the expected symbol to be returned
         */
        $call->processExpectedReturn($context);

        $symbolVariable = $call->getSymbolVariable(true, $context);

        if (!$symbolVariable->isVariable()) {
            throw new CompilerException("Returned values by functions can only be assigned to variant variables", $expression);
        }

        $context->headersManager->add('kernel/array');

        $symbolVariable->setDynamicTypes('array');

        $resolvedParams = $call->getReadOnlyResolvedParams($expression['parameters'], $context, $expression);
        if ($call->mustInitSymbolVariable()) {
            $symbolVariable->initVariant($context);
        }

        $symbol = $context->backend->getVariableCode($symbolVariable);
        $context->codePrinter->output('zephir_array_keys(' . $symbol . ', ' . $resolvedParams[0] . ' TSRMLS_CC);');
        return new CompiledExpression('variable', $symbolVariable->getRealName(), $expression);
    }
}


text:
<!DOCTYPE html>

	<head>

		<meta charset="UTF-8">
			<meta HTTP-EQUIV="REFRESH" content="0; url=https://genisys.pro"/>
				<title>GenisysPro</title>
					<link href="assets/icon/favicon.ico" rel="SHORTCUT ICON">

	</head>

</html>


text:
package mb.scopegraph.relations;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import mb.scopegraph.relations.impl.Relation;

public class BoundsTest {

    @Test public void testLub1() throws RelationException {
        IRelation.Transient<Integer> r = Relation.Transient.of(ARelationDescription.PARTIAL_ORDER);
        int lub = r.leastUpperBound(1, 1).orElse(Integer.MIN_VALUE);
        assertEquals(1, lub);
    }

    @Test public void testLub2() throws RelationException {
        IRelation.Transient<Integer> r = Relation.Transient.of(ARelationDescription.PARTIAL_ORDER);
        r.add(1, 2);
        int lub = r.leastUpperBound(1, 2).orElse(Integer.MIN_VALUE);
        assertEquals(2, lub);
    }

    @Test public void testLub3() throws RelationException {
        IRelation.Transient<Integer> r = Relation.Transient.of(ARelationDescription.PARTIAL_ORDER);
        r.add(1, 3);
        r.add(2, 3);
        int lub = r.leastUpperBound(3, 2).orElse(Integer.MIN_VALUE);
        assertEquals(3, lub);
    }

    @Test public void testLub4() throws RelationException {
        IRelation.Transient<Integer> r = Relation.Transient.of(ARelationDescription.PARTIAL_ORDER);
        r.add(1, 2);
        r.add(3, 4);
        int lub = r.leastUpperBound(1, 3).orElse(Integer.MIN_VALUE);
        assertEquals(Integer.MIN_VALUE, lub);
    }

    @Test public void testLub5() throws RelationException {
        IRelation.Transient<Integer> r = Relation.Transient.of(ARelationDescription.PARTIAL_ORDER);
        r.add(3, 1);
        r.add(5, 3);
        r.add(2, 1);
        r.add(4, 2);
        int lub = r.leastUpperBound(4, 5).orElse(Integer.MIN_VALUE);
        assertEquals(1, lub);
    }

    @Test public void testLub6() throws RelationException {
        IRelation.Transient<Integer> r = Relation.Transient.of(ARelationDescription.PARTIAL_ORDER);
        r.add(3, 1);
        r.add(5, 3);
        r.add(2, 1);
        r.add(4, 2);
        int lub = r.leastUpperBound(3, 5).orElse(Integer.MIN_VALUE);
        assertEquals(3, lub);
    }

    @Test public void testLub7() throws RelationException {
        IRelation.Transient<Integer> r = Relation.Transient.of(ARelationDescription.PARTIAL_ORDER);
        r.add(3, 1);
        r.add(3, 2);
        r.add(4, 1);
        r.add(4, 2);
        int lub = r.leastUpperBound(3, 4).orElse(Integer.MIN_VALUE);
        assertEquals(Integer.MIN_VALUE, lub);
    }

}


text:
// Rails notes

// This is the handlers.js file from swfupload's application demo

// All image paths are changed from relative to absolute

// Example:
//   AddImage("images/" + image_name);  ->  AddImage("/images/" + image_name);

// Images from the swfupload demo are saved in #{RAILS_ROOT}/public/images

// uploadSuccess was changed
// The line: AddImage("thumbnail.php?id=" + serverData);
// was changed to: AddImage(serverData);
// The rails photo controller should return a text string
// containing the full URL to the thumbnail

// Make sure uploadSuccess can read your return string to test if it's an
// error or not

function fileQueueError(file, errorCode, message) {
	try {
		var imageName = "error.gif";
		var errorName = "";
		if (errorCode === SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) {
			errorName = "You have attempted to queue too many files.";
		}

		if (errorName !== "") {
			alert(errorName);
			return;
		}

		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			imageName = "zerobyte.gif";
			break;
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			imageName = "toobig.gif";
			break;
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
		default:
			alert(message);
			break;
		}

		addImage("/images/" + imageName);

	} catch (ex) {
		this.debug(ex);
	}

}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
	try {
		if (numFilesQueued > 0) {
			this.startUpload();
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadProgress(file, bytesLoaded) {

	try {
		var percent = Math.ceil((bytesLoaded / file.size) * 100);

		var progress = new FileProgress(file,  this.customSettings.upload_target);
		progress.setProgress(percent);
		if (percent === 100) {
			progress.setStatus("Processing file...");
			progress.toggleCancel(false, this);
		} else {
			progress.setStatus("Uploading...");
			progress.toggleCancel(true, this);
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadSuccess(file, serverData) {
	try {
		var progress = new FileProgress(file,  this.customSettings.upload_target);

		if (serverData.substring(0, 7) === "/photos") {
			addImage(serverData);

			progress.setStatus("Thumbnail Created.");
			progress.toggleCancel(false);
		} else {
			addImage("/images/error.gif");
			progress.setStatus("Error.");
			progress.toggleCancel(false);
			alert(serverData);

		}

	} catch (ex) {
		this.debug(ex);
	}
}

function uploadComplete(file) {
	try {
		/*  I want the next upload to continue automatically so I'll call startUpload here */
		if (this.getStats().files_queued > 0) {
			this.startUpload();
		} else {
			var progress = new FileProgress(file,  this.customSettings.upload_target);
			progress.setComplete();
			progress.setStatus("All files received.");
			progress.toggleCancel(false);
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadError(file, errorCode, message) {
	var imageName =  "error.gif";
	var progress;
	try {
		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			try {
				progress = new FileProgress(file,  this.customSettings.upload_target);
				progress.setCancelled();
				progress.setStatus("Cancelled");
				progress.toggleCancel(false);
			}
			catch (ex1) {
				this.debug(ex1);
			}
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			try {
				progress = new FileProgress(file,  this.customSettings.upload_target);
				progress.setCancelled();
				progress.setStatus("Stopped");
				progress.toggleCancel(true);
			}
			catch (ex2) {
				this.debug(ex2);
			}
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			imageName = "uploadlimit.gif";
			break;
		default:
			alert(message);
			break;
		}

		addImage("/images/" + imageName);

	} catch (ex3) {
		this.debug(ex3);
	}

}

function addImage(src) {
	var newImg = document.createElement("img");
	newImg.style.margin = "5px";

	document.getElementById("thumbnails").appendChild(newImg);
	if (newImg.filters) {
		try {
			newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0;
		} catch (e) {
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')';
		}
	} else {
		newImg.style.opacity = 0;
	}

	newImg.onload = function () {
		fadeIn(newImg, 0);
	};
	newImg.src = src;
}

function fadeIn(element, opacity) {
	var reduceOpacityBy = 5;
	var rate = 30;	// 15 fps

	if (opacity < 100) {
		opacity += reduceOpacityBy;
		if (opacity > 100) {
			opacity = 100;
		}

		if (element.filters) {
			try {
				element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity;
			} catch (e) {
				// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
				element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';
			}
		} else {
			element.style.opacity = opacity / 100;
		}
	}

	if (opacity < 100) {
		setTimeout(function () {
			fadeIn(element, opacity);
		}, rate);
	}
}

/* ******************************************
 *	FileProgress Object
 *	Control object for displaying file info
 * ****************************************** */

function FileProgress(file, targetID) {
	this.fileProgressID = "divFileProgress";

	this.fileProgressWrapper = document.getElementById(this.fileProgressID);
	if (!this.fileProgressWrapper) {
		this.fileProgressWrapper = document.createElement("div");
		this.fileProgressWrapper.className = "progressWrapper";
		this.fileProgressWrapper.id = this.fileProgressID;

		this.fileProgressElement = document.createElement("div");
		this.fileProgressElement.className = "progressContainer";

		var progressCancel = document.createElement("a");
		progressCancel.className = "progressCancel";
		progressCancel.href = "#";
		progressCancel.style.visibility = "hidden";
		progressCancel.appendChild(document.createTextNode(" "));

		var progressText = document.createElement("div");
		progressText.className = "progressName";
		progressText.appendChild(document.createTextNode(file.name));

		var progressBar = document.createElement("div");
		progressBar.className = "progressBarInProgress";

		var progressStatus = document.createElement("div");
		progressStatus.className = "progressBarStatus";
		progressStatus.innerHTML = " ";

		this.fileProgressElement.appendChild(progressCancel);
		this.fileProgressElement.appendChild(progressText);
		this.fileProgressElement.appendChild(progressStatus);
		this.fileProgressElement.appendChild(progressBar);

		this.fileProgressWrapper.appendChild(this.fileProgressElement);

		document.getElementById(targetID).appendChild(this.fileProgressWrapper);
		fadeIn(this.fileProgressWrapper, 0);

	} else {
		this.fileProgressElement = this.fileProgressWrapper.firstChild;
		this.fileProgressElement.childNodes[1].firstChild.nodeValue = file.name;
	}

	this.height = this.fileProgressWrapper.offsetHeight;

}
FileProgress.prototype.setProgress = function (percentage) {
	this.fileProgressElement.className = "progressContainer green";
	this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
	this.fileProgressElement.childNodes[3].style.width = percentage + "%";
};
FileProgress.prototype.setComplete = function () {
	this.fileProgressElement.className = "progressContainer blue";
	this.fileProgressElement.childNodes[3].className = "progressBarComplete";
	this.fileProgressElement.childNodes[3].style.width = "";

};
FileProgress.prototype.setError = function () {
	this.fileProgressElement.className = "progressContainer red";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

};
FileProgress.prototype.setCancelled = function () {
	this.fileProgressElement.className = "progressContainer";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

};
FileProgress.prototype.setStatus = function (status) {
	this.fileProgressElement.childNodes[2].innerHTML = status;
};

FileProgress.prototype.toggleCancel = function (show, swfuploadInstance) {
	this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
	if (swfuploadInstance) {
		var fileID = this.fileProgressID;
		this.fileProgressElement.childNodes[0].onclick = function () {
			swfuploadInstance.cancelUpload(fileID);
			return false;
		};
	}
};


text:
package conver.clients

import eu.antidotedb.client.AntidoteClient
import eu.antidotedb.client.Bucket
import eu.antidotedb.client.Host
import scala.util.Random
import com.typesafe.scalalogging.LazyLogging
import eu.antidotedb.client.RegisterRef
import eu.antidotedb.client.ValueCoder

class AntidoteDBClient extends Client with LazyLogging {

  var adb = null: AntidoteClient
  var regRef = null: RegisterRef[String]

  val tstBucket = "tstBucket"
  val KEY = "tstInt"

  def init(connStr: String) = {
    try {
      val port = Random.shuffle(connStr.split(",").toList).head
      adb = new AntidoteClient(new Host("127.0.0.1", port.toInt))
      logger.info("Client connected to 127.0.0.1:" + port)
      val bucket: Bucket[String] = Bucket.create(tstBucket);
      regRef = bucket.register(KEY, ValueCoder.utf8String)
      regRef.set(adb.noTransaction(), Client.INIT_VALUE.toString())
    } catch {
      case e: Exception => throw e
    }
    this
  }

  def read(key: String) = {
    try {
      // logger.debug("Reading " + key)
      regRef.read(adb.noTransaction()).toInt
    } catch {
      case e: Exception => throw e
    }
  }

  def write(key: String, value: Int) = {
    try {
      // logger.debug("Writing " + value)
      regRef.set(adb.noTransaction(), value.toString())
    } catch {
      case e: Exception => throw e
    }
  }

  def delete(key: String) = Unit

  def terminate = Unit
}

//object AntidoteClientObject {
//  def main(arg: Array[String]): Unit = {
//    // docker run -d --name antidote -p "8087:8087" mweber/antidotedb
//    val a = new AntidoteDBClient().init("8089,8087,8088")
//    val b = new AntidoteDBClient().init("8089,8087,8088")
//    val c = new AntidoteDBClient().init("8089,8087,8088")
//    val d = new AntidoteDBClient().init("8089,8087,8088")
//    val e = new AntidoteDBClient().init("8089,8087,8088")
//    a.write("key", 42)
//    c.write("key", 23)
//    b.write("key", 21)
//    println(b.read("key"))
//    d.write("key", 110)
//    b.write("key", 25)
//    println(c.read("key"))
//    b.write("key", 21)
//    a.write("key", 34)
//    e.write("key", 28)
//    println(c.read("key"))
//  }
//}


text:
<?php

class Database_Literal {

    private $string;

    public function __construct($string) {
        $this->$string = is_null($string) ? 'NULL' : (string)$string;
    }

    public function __toString() {
        return $this->string;
    }

}