• 0

[PHP/MySQL] $15 Contest for the most complex code


Question

Ok, so the rules are simple. Just post the most complex php/mysql code (within reason don't post some mysql string that takes up 500 pages) that takes up of a maximum of 2 pages of code (printed). It doesn't even have to be yours (as long as you have a right to post it). Just post it and explain what it does. The winner will be chosen by me and I'll paypal them $15. Contest ends Friday. Have fun! :)

btw: I'm doing this for a learning experience more than anything. I want to see really complex pieces of work so I can see where I'm at with my coding as far as queries go. Just to fill you in as you're probably wondering why on earth I decided to do this lol.

25 answers to this question

Recommended Posts

  • 0
<?php

class Blog {

	public $id;
	public $userId;
	public $title;
	public $body;
	public $views;
	public $comments;
	public $voteCount;
	public $voteAverage;
	public $voteTotal;
	public $voteUserIds;
	public $created;
	public $updated;
	public $autoLoad;

	function __construct($id, $userId, $title, $body=NULL, $views=NULL, $comments=NULL, $voteCount=NULL, $voteAverage=NULL, $voteTotal=NULL, $voteUserIds=NULL, $created=NULL, $updated=NULL, $autoLoad=array()) {
		$this->id 			= $id;
		$this->userId		= $userId;
		$this->title 		= stripslashes($title);
		$this->body 		= stripslashes($body);
		$this->views		= $views;
		$this->comments		= $comments;
		$this->voteCount 	= $voteCount;
		$this->voteAverage	= $voteAverage;
		$this->voteTotal	= $voteTotal;
		$this->voteUserIds	= $voteUserIds;
		$this->created 		= $created;
		$this->updated		= $updated;
		$this->autoLoad		= $autoLoad;
		$this->AutoLoad($this->autoLoad);
	}


	public function AutoLoad($autoLoad) {

		if(is_array($autoLoad)) {
			foreach($autoLoad as $load):
				switch($load):
					case 'comments' :
						$this->LoadComments();
					break;
					case 'tags' :
						$this->LoadTags();
					break;
				endswitch;
			endforeach;
		} else if ($autoLoad === true) {
			$this->LoadComments();
			$this->LoadTags();
		}
	}


	public static function Load($id, $autoLoad=array()) {

		try {
			$db = Database::GetInstance();
			$result = $db->query("SELECT * FROM Blog WHERE id = ".$id);

				if($result && $result->num_rows > 0) {
					$q = $result->fetch_object();
						if($Object = new self($q->id, $q->user_id, $q->title, $q->body, $q->views, $q->comments, $q->vote_count, $q->vote_average, $q->vote_total, $q->vote_user_ids, $q->created, $q->updated, $autoLoad)) {
							return $Object;
						}
					} else {
						throw new ApplicationException('Could not load blogId '.$id);
					}

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}
	}


	public function LoadComments() {
		$this->Comments = Comment_Blog::LoadByBlogId($this->id);
	}


	public function LoadTags() {
		$this->Tags = Tag_Blog::LoadTagsByBlogId($this->id);
	}



	public function AddView() {

		try {
			$db = Database::GetInstance();
			$result = $db->query("UPDATE Blog SET views = views + 1 WHERE id = ".$this->id);

				if(!$result) {
					return false;
				} else if ($db->affected_rows >= 0) {
					return true;
				} else {
					return false;

				}

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}		
	}


	public function HasVoted($userId) {
		$items = explode(',', $this->voteUserIds);
		return in_array($userId, $items) ? true : false;
	}

	public function TagsToString() {

			if(!empty($this->Tags)):
				$result = NULL;
					foreach($this->Tags as $tag):
						$result .= ', '.$tag->title;
					endforeach;
				return substr($result, 2);
			endif;
		return false;
	}


	public function Vote($rating) {
	global $User;

		try {
			$db = Database::GetInstance();

			if($User->id == $this->userId) {//my blog, cant vote
				return false;
			} else if ($this->HasVoted($User->id) == true) {//already voted
				return false;
			}

			$this->voteUserIds = $this->voteUserIds.",".$User->id;

			if($this->voteCount > 1) {
				$this->voteTotal 	= $this->voteTotal + $rating;
				$this->voteCount 	= $this->voteCount + 1;
				$this->voteAverage 	=  $this->voteTotal / $this->voteCount + 1;
			} else {
				$this->voteAverage = $rating;
			}

			$result = $db->query("UPDATE Blog SET vote_count = vote_count + 1, vote_average = '".$this->voteAverage."', vote_user_ids = '".$this->voteUserIds."', vote_total = vote_total + $rating WHERE id = ".$this->id);

				if(!$result) {
					return false;
				} else if ($db->affected_rows >= 0) {
					return true;
				} else {
					return false;

				}

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}		
	}


	public function AddComment($blogId) {

		try {
			$db = Database::GetInstance();
			$result = $db->query("UPDATE Blog SET comments = comments + 1 WHERE id = ".$blogId);

				if(!$result) {
					return false;
				} else if ($db->affected_rows >= 0) {
					return true;
				} else {
					return false;

				}

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}		
	}


	public function RemoveComment($blogId) {

		try {
			$db = Database::GetInstance();
			$result = $db->query("UPDATE Blog SET comments = comments - 1 WHERE id = ".$blogId);

				if(!$result) {
					return false;
				} else if ($db->affected_rows >= 0) {
					return true;
				} else {
					return false;

				}

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}		
	}


	public function Save() {

		try {
			$db = Database::GetInstance();
			$result = $db->query("UPDATE Blog SET title = ".$db->safe($this->title).", body = ".$db->safe($this->body).", updated = ".time()." WHERE id = ".$this->id);

				if(!$result) {
					return false;
				} else if ($db->affected_rows >= 0) {
					return true;
				} else {
					return false;
				}

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}		
	}


	public static function LoadAllByType($from, $to, $type=NULL, $extra=NULL, $count=0, $autoLoad=array()) {
	global $User;

		try {
			$db = Database::GetInstance();

			if($type == 'by_user') {
				$arg = " AND b.user_id = $extra ";
				$join = NULL;
			} else if ($type == 'by_tag') {
				$arg = ' AND t.title = '.$db->safe($extra);
				$join = "LEFT JOIN Tag_Blog tb ON (tb.blog_id = b.id) LEFT JOIN Tag t ON (tb.tag_id = t.id) ";
			} else if ($type == 'by_friends') {
				$arg = " AND b.user_id IN($extra) ";
				$join = NULL;
			} else {
				$arg = NULL;
				$join = NULL;
			}

			$sql = "SELECT b.*, u.username as username, ud.id as ud_id, ud.key, ud.value 
			FROM Blog b 
			JOIN User u ON (b.user_id = u.id) 
			LEFT OUTER JOIN User_Data ud ON (u.id = ud.user_id AND ud.key = 'Avatar') 
			$join 
			WHERE b.id > 0 
			$arg 
			ORDER BY b.created DESC
			LIMIT $from, $to";
			$query = $db->query($sql) or die($db->error." $sql");

				if($count == 1) {
					return $query->num_rows;
				}

				if($query && $query->num_rows > 0):
					$blogs = array();
						while ($q = $query->fetch_object()):
							$Object = new self($q->id, $q->user_id, $q->title, $q->body, $q->views, $q->comments, $q->vote_count, $q->vote_average, $q->vote_total, $q->vote_user_ids, $q->created, $q->updated, $autoLoad);
							$Object->User = new User($q->user_id, $q->username);
							if(!empty($q->key)):
								$Object->User->Avatar = new User_Data($q->ud_id, $q->user_id, $q->key, $q->value);
							endif;
							$blogs[] = $Object;
						endwhile;
					return $blogs;
				endif;
			return false;

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}		
	}


	public static function Create($userId, $title, $body) {

		try {
			$db = Database::GetInstance();
			$time = time();
			$db->query("INSERT INTO Blog (user_id, title, body, created, updated) VALUES ($userId, ".$db->safe($title).", ".$db->safe($body).", $time, $time) ");
			$id = $db->insert_id;

				if($db->affected_rows > 0) {
					return self::Load($id);
				} else { 
					return false;
				}

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}		
	}


	public function Delete() {

		try {
			Comment_Blog::DeleteByBlogId($this->id);
			$db = Database::GetInstance();
			return $db->query("DELETE FROM Blog WHERE id = ".$this->id);

		} catch(DatabaseException $e) {
			throw new ApplicationException($e->getMessage(), $e->getCode());
		}		
	}


}

?>

  • 0

PHP code obfuscator:

<?php
set_time_limit(0);

$web=isset($_POST['w']) ? 1 : 0;
$no_change=Array();
$no_change_funcs=Array();

if($web)
{
  $tmparr=isset($_POST['vrepl']) ? trim($_POST['vrepl']) : '';

  if($tmparr)
  {
	$tmparr=explode("\n",$tmparr);
	foreach($tmparr as $vname)
	{
	  $vname=str_replace("\r","",$vname);
	  if(!preg_match("/^\\$([a-zA-Z_\x7f-\xff]{1}[a-zA-Z0-9_\x7f-\xff]*)$/i",$vname))
		errpr("Error in non-replaceable variable list");

	  $no_change[]=$vname;
	}
  }



  $tmparr=isset($_POST['frepl']) ? trim($_POST['frepl']) : '';

  if($tmparr)
  {
	$tmparr=explode("\n",$tmparr);
	foreach($tmparr as $fname)
	{
	  $fname=str_replace("\r","",$fname);
	  if(!preg_match("/^([a-zA-Z0-9_]+)$/i",$fname))
		errpr("Error in non-replaceable function list");

	  $no_change_funcs[]=$fname;
	}
  }


  $tmparr=isset($_POST['ffrepl']) ? trim($_POST['ffrepl']) : '';

  if($tmparr)
  {
	$tmparr=explode("\n",$tmparr);
	foreach($tmparr as $fname)
	{
	  $fname=str_replace("\r","",$fname);
	  if(!preg_match("/^([a-zA-Z0-9_]+)$/i",$fname))
		errpr("Error in function list witn non-replaceable variables");

	  $no_str_repl[]=$fname;
	}
  }

  $sfuncname=isset($_POST['sfunc']) ? $_POST['sfunc'] : '';
  if($sfuncname)
  {
	if(!preg_match("/^([a-zA-Z0-9_]+)$/i",$sfuncname))
	  errpr("Wrong function name for crypt");
  }
}
else
{
print <<<HERE
<html><head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>PHP Obfuscator by DX 1.0</title>
<style>
td
{
border-width:1px 1px 1px 1px;
border-style:solid;
border-color:black;
}
INPUT
{
BORDER-RIGHT: rgb(50,50,50) 1px outset;
BORDER-TOP: rgb(50,50,50) 1px outset;
FONT-SIZE: 11px;
font-family:Arial;
BORDER-LEFT: rgb(50,50,50) 1px outset;
BORDER-BOTTOM: rgb(50,50,50) 1px outset;
}
button
{
BORDER-RIGHT: rgb(50,50,50) 1px outset;
BORDER-TOP: rgb(50,50,50) 1px outset;
FONT-SIZE: 10px;
BORDER-LEFT: rgb(50,50,50) 1px outset;
BORDER-BOTTOM: rgb(50,50,50) 1px outset;
width:50px;
}
textarea
{
BORDER-RIGHT: rgb(50,50,50) 1px outset;
BORDER-TOP: rgb(50,50,50) 1px outset;
BORDER-LEFT: rgb(50,50,50) 1px outset;
BORDER-BOTTOM: rgb(50,50,50) 1px outset;
FONT-SIZE: 13px;
font-family:Arial;
}
select
{
FONT-SIZE: 10px;
background-color:#f4f4ff;
}
a,a:active,a:visited
{
background: transparent;
color: #34498B;
text-decoration: none;
font-weight:700;
font-size:10;
font-family:Arial;
background-color:wheat;
}
a:hover
{
background: transparent;
color: blue;
font-weight:700;
font-family:Arial;
font-size:10;
text-decoration: none;
background-color:yellow;
}
</style>
</head>
<body>
<form action="?" method="post">
<input type="hidden" name="w" value="1">
<table style="border-width:1px 1px 1px 1px; border-style:solid; border-collapse:collapse; border-color:black; width:100%; height:100%">
<tr><td colspan=2 align=center style="font-size:18;height:10">PHP Obfuscator by DX 1.0</td></tr>
<tr valign=top><td>Source code (With <? and ?>)<hr>
<textarea style="width:99%;font-family:Lucida Console;" rows=35 name="src"></textarea>
<br><br><center><input type="submit" value="Obfuscate!"></center>
<hr><b>Important!</b><br>Please, don't use \$\$var_name and eval.<br>
</td><td style="width:350;font-face:Arial;font-size:12;">Obfuscation options<hr>
Function name for obfuscation (optional): <input type="text" name="sfunc" value=""><hr>
<input type="checkbox" name="obvars" checked> Replace variables<br>
<input type="radio" value="0" name="vtype" checked> Give short names to variables<br>
<input type="radio" value="1" name="vtype"> Give long names to variables<br>
<hr>
<input type="checkbox" name="obstrs" checked> Static strings obfuscation<br>(speed will decrease)<br>
<input type="radio" value="0" name="stype"> Simple obfuscation<br>
<input type="radio" value="1" name="stype" checked> Encode in base64<br>
<hr>
<input type="checkbox" name="obfuncs" checked> Replace functions<br>
<input type="radio" value="0" name="ftype" checked> Functions short names<br>
<input type="radio" value="1" name="ftype"> Functions long names<br>
<hr>
<input type="checkbox" name="cmpr" checked>Maximum compression<hr>
Non-replaceable variables:<br>
<textarea style="width:340;font-family:Lucida Console;" rows=10 name="vrepl">\$_GET
\$_POST
\$_COOKIE
\$_SERVER
\$_FILE
\$HTTP_GET_VARS
\$HTTP_POST_VARS
\$HTTP_COOIE_VARS
\$GLOBALS
\$HTTP_SERVER_VARS
\$HTTP_POST_FILES
\$_REQUEST
\$_SESSION
\$HTTP_SESSION_VARS
\$_ENV
\$HTTP_ENV_VARS
\$php_errormsg
\$HTTP_RAW_POST_DATA
\$http_response_header
\$argc
\$argv
\$this</textarea>
<br>Non-replaceable functions:<br>
<textarea style="width:340;font-family:Lucida Console;" rows=10 name="frepl">__destruct
__construct
__get
__set
__call
__callStatic
__isset
__unset
__sleep
__wakeup
__toString
__set_state
__clone</textarea>
<br>Functions with non-replaceable parameters:<br>
<textarea style="width:340;font-family:Lucida Console;" rows=10 name="ffrepl">set_error_handler
ob_gzhandler
ibase_set_event_handler
session_set_save_handler
set_exception_handler
xml_set_character_data_handler
xml_set_default_handler
xml_set_element_handler
xml_set_end_namespace_decl_handler
xml_set_external_entity_ref_handler
xml_set_notation_decl_handler
xml_set_processing_instruction_handler
xml_set_start_namespace_decl_handler
xml_set_unparsed_entity_decl_handler
xslt_set_error_handler
readline_callback_handler_install
runkit_sandbox_output_handler
sybase_set_message_handler</textarea>
</td>
</tr></table></body></html>
HERE;
  exit();
}


$replace_vars=isset($_POST['obvars']) ? 1 : 0;
$obf_strings=isset($_POST['obstrs']) ? 1 : 0;
$obf_funcs=isset($_POST['obfuncs']) ? 1 : 0;
$compress_file=isset($_POST['cmpr']) ? 1 : 0;

$vars_mode=isset($_POST['vtype']) ? $_POST['vtype'] : 0;
if($vars_mode!=="1" && $vars_mode!=="0")
  $vars_mode=0;

$string_mode=isset($_POST['stype']) ? $_POST['stype'] : 0;
if($string_mode!=="1" && $string_mode!=="0")
  $string_mode=0;

$func_mode=isset($_POST['ftype']) ? $_POST['ftype'] : 0;
if($func_mode!=="1" && $func_mode!=="0")
  $func_mode=0;

$f=isset($_POST['src']) ? $_POST['src'] : '';

if(ini_get('magic_quotes_gpc')==1)
  $f=stripslashes($f);

if(!$f)
  errpr("Enter php-file code");

$obfuscated=get_obf_code($f,$replace_vars,$vars_mode,$obf_strings,$string_mode,$obf_funcs,$func_mode,$sfuncname);


if($compress_file) $obfuscated=compress_php_src($obfuscated);

$obfuscated=htmlspecialchars($obfuscated);

print <<<HERE
<html><head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>PHP Obfuscator by DX 1.0</title>
</head>
<body>
<center><h3>Obfuskated code</h3></center><hr>
<textarea style="width:99%;font-family:Lucida Console;" rows=35>
$obfuscated
</textarea>
&lt;br&gt;&lt;a href="#" onclick="java script:history.go(-1)">Again</a>;/body&gt;&lt;/html&gt;
HERE;
exit();



function errpr($txt)
{
print &lt;&lt;&lt;HERE
&lt;html&gt;&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8"&gt;
&lt;title&gt;PHP Obfuscator by DX 1.0&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h3&gt;$txt&lt;/h3&gt;&lt;hr&gt;
&lt;a href="#" onclick="java script:history.go(-1)">Back</a>;/body&gt;&lt;/html&gt;
HERE;
exit();
}



function compress_php_src($src)
{
  static $IW=array();

  $tokens=@token_get_all($src);

  $new="";
  $c=sizeof($tokens);
  $iw=false;
  $ih=false;
  $ls="";
  $ot=null;
  for($i=0;$i&lt;$c;$i++)
  {
	$token=$tokens[$i];
	  if(is_array($token))
	  {
		list($tn,$ts)=$token;
		$tname=token_name($tn);
		if($tn==T_INLINE_HTML)
		{
		  $new.=$ts;
		  $iw=false;
		}
		else
		{
		  if($tn==T_OPEN_TAG)
		  {
			if(strpos($ts," ") || strpos($ts,"\n") || strpos($ts,"\t") || strpos($ts,"\r"))
			{
			  $ts=rtrim($ts);
			}

			$ts.=" ";
			$new.=$ts;
			$ot=T_OPEN_TAG;
			$iw = true;
		  }
		  elseif($tn==T_OPEN_TAG_WITH_ECHO)
		  {
			$new.=$ts;
			$ot=T_OPEN_TAG_WITH_ECHO;
			$iw=true;
		  }
		  elseif($tn==T_CLOSE_TAG)
		  {
			if($ot==T_OPEN_TAG_WITH_ECHO)
			{
			  $new=rtrim($new,"; ");
			}
			else
			{
			  $ts=" ".$ts;
			}

			$new.=$ts;
			$ot=null;
			$iw=false;
		  }
		  elseif(in_array($tn,$IW))
		  {
			$new.=$ts;
			$iw=true;
		  }
		  elseif($tn==T_CONSTANT_ENCAPSED_STRING || $tn==T_ENCAPSED_AND_WHITESPACE)
		  {
			if($ts[0]=='"')
			{
			  $ts=addcslashes($ts,"\n\t\r");
			}

			$new.=$ts;
			$iw=true;
		  }
		  elseif($tn==T_WHITESPACE)
		  {
			$nt=@$tokens[$i+1];
			if(!$iw &amp;&amp; (!is_string($nt) || $nt=='$') &amp;&amp; !in_array($nt[0],$IW))
			{
			  $new.=" ";
			}

			$iw = false;
		  }
		  elseif($tn==T_START_HEREDOC)
		  {
			$new.="&lt;&lt;&lt;S\n";
			$iw=false;
			$ih=true;
		  }
		  elseif($tn==T_END_HEREDOC)
		  {
			$new.="S;\n";
			$iw=true;
			$ih=false;

			for($j=$i+1;$j&lt;$c;$j++)
			{
			  if(is_string($tokens[$j]) &amp;&amp; $tokens[$j]==";")
			  {
				$i=$j;
				break;
			  }
			  else if($tokens[$j][0]==T_CLOSE_TAG)
			  {
				break;
			  }
			}
		  }
		  elseif($tn==T_COMMENT || $tn==T_DOC_COMMENT || $tn==T_ML_COMMENT)
		  {
			$iw = true;
		  }
		  else
		  {
			$new.=$ts;
			$iw = false;
		  }
		}

		$ls = "";
	  }
	  else
	  {
		if(($token!=";" &amp;&amp; $token!=":") || $ls!=$token)
		{
		  $new.=$token;
		  $ls=$token;
		}

		$iw=true;

	  }
  }

  return $new;
}



function get_obf_code($src,$obfvars,$varmode,$obfstrings,$strmode,$obffuncs,$funcmode,$sfuncname='')
{
  global $no_change;
  global $allvars;
  global $no_change_funcs;
  global $no_str_repl;

  $tokens=@token_get_all($src);
  $c=sizeof($tokens);

  $allvars[0]=Array();
  $allvars[1]=Array();
  $currvar=0;

  $allfuncs[0]=Array();
  $allfuncs[1]=Array();
  $currfunc=0;

  $lastconstr='';

  $classsk=0;

  $prev=0;

  $currstr=0;

  $ot=0;

  $newcode="";
  $bfr='';
  $addcode1="";
  $sfname=$sfuncname ? $sfuncname : '_'.mt_rand();


  $isstr=0;
  $ineval=0;
  $isfunc=0;

  for($i=0;$i&lt;$c;$i++)
  {
	$token=$tokens[$i];

	if(is_array($token))
	{
	  list($tn,$ts)=$token;

	  if(($tn==T_OPEN_TAG || $tn==T_OPEN_TAG_WITH_ECHO) &amp;&amp; !$ot)
		$ot=1;

	  if($tn==T_CLOSE_TAG &amp;&amp; $ot)
		$ot=0;


	  if($ot)
	  {
		if($tn==T_VAR || $tn==T_PROTECTED || $tn==T_PUBLIC || $tn==T_PRIVATE || $tn==T_CONST)
		  $classsk=1;

		if($tn==T_EVAL)
		  $ineval=1;


		if($isstr==1 &amp;&amp; $tn==T_END_HEREDOC)
		  $isstr=0;


		if($tn==T_START_HEREDOC)
		  $isstr=1;


		if($ineval) {$newcode.=$ts;continue;}


		if($obfvars &amp;&amp; $tn==T_VARIABLE &amp;&amp; !in_array($ts,$no_change))
		{
		  if(!in_array($ts,$allvars[0]))
		  {
			$tmp=$ts;
			$allvars[0][$tmp]=$ts;
			$ts=$varmode==0 ? '$_'.$currvar : '$_'.md5($ts);
			$allvars[1][$tmp]=$ts;
			$currvar++;
		  }
		  else
		  {
			$ts=$allvars[1][$ts];
		  }
		}


		if($tn==T_STRING &amp;&amp; $prev==T_OBJECT_OPERATOR)
		{
		  $ttt=$i+1;
		  $wbfunc=0;
		  while(isset($tokens[$ttt]))
		  {
			$nxt=$tokens[$ttt];

			if($nxt=='(' &amp;&amp; !$isstr)
			{
			  $wbfunc=1;
			  break;
			}

			if(($nxt==';' || $nxt=='=' || $nxt==')'  || is_array($nxt)) &amp;&amp; !$isstr)
			{
			  break;
			}
			$ttt++;
		  }
		}


		if($obfvars &amp;&amp; !$wbfunc &amp;&amp; $tn==T_STRING &amp;&amp; $prev==T_OBJECT_OPERATOR &amp;&amp; !in_array('$'.$ts,$no_change))
		{
		  if(!in_array('$'.$ts,$allvars[0]))
		  {
			$tmp='$'.$ts;
			$allvars[0][$tmp]='$'.$ts;
			$ts=$varmode==0 ? '_'.$currvar : '_'.md5('$'.$ts);
			$allvars[1][$tmp]='$'.$ts;
			$currvar++;
		  }
		  else
		  {
			$ts=substr($allvars[1]['$'.$ts],1);
		  }
		}


		if($tn==T_FUNCTION)
		  $isfunc=1;

		$prev= $tn==T_WHITESPACE ? $prev : $tn;


		if($obffuncs &amp;&amp; $isfunc &amp;&amp; !$fname &amp;&amp; $tn==T_STRING &amp;&amp; strtolower($ts)!='true' &amp;&amp; strtolower($ts)!='false' &amp;&amp; !in_array($ts,$no_change_funcs))
		{
		  if(!in_array($ts,$allfuncs[0]))
		  {
			$tmp=$ts;
			$allfuncs[0][$tmp]=$ts;
			$ts=$funcmode==0 ? '__'.$currfunc : '__'.md5($ts);
			$allfuncs[1][$tmp]=$ts;
			$currfunc++;
		  }
		  else
		  {
			$ts=$allfuncs[1][$ts];
		  }
		}


		if($classsk==0 &amp;&amp; $obfstrings &amp;&amp; !in_array($lastconstr,$no_str_repl) &amp;&amp; $tn==T_CONSTANT_ENCAPSED_STRING &amp;&amp; !$isfunc)
		{
		  if($strmode==0)
		  {
			$addcode1.=$ts.',';
			$ts=$sfname.'('.$currstr.')';
			$currstr++;
		  }
		  else
		  {
			eval('$tmp='.$ts.';');
			$addcode1.="'".base64_encode($tmp)."',";
			$ts=$sfname.'('.$currstr.')';
			$currstr++;
		  }
		}
	  }

	  if($tn==T_STRING)
		$lastconstr=$ts;


	  if($tn==T_END_HEREDOC)
		$ts.="\n";

	  $newcode.=$ts;
	  $bfr=$tn;
	}
	else
	{
	  $newcode.=$token;

	  if($isfunc &amp;&amp; $ot)
	  {
		if($token==')')
		  $isfunc=0;
	  }

	  if($ot)
	  {
		if($isstr==2 &amp;&amp; $token=="'")
		{
		  $isstr=0;
		  continue;
		}

		if($token=="'")
		  $isstr=2;

		if($isstr==3 &amp;&amp; $token=='"')
		{
		  $isstr=0;
		  continue;
		}

		if($token=='"')
		  $isstr=3;

		if($classsk==1)
		{
		  if($token==';')
			$classsk=0;
		}

		if($ineval &amp;&amp; $token==';')
		  $ineval=0;

		if($lastconstr &amp;&amp; $token==';')
		  $lastconstr='';
	  }

	}
  }



  if($obfstrings)
  {
	$addcode1=substr($addcode1,0,strlen($addcode1)-1);

	if($strmode==0)
	  $addcode1="&lt;? function $sfname(\$i)".'{'."\$a=Array($addcode1);return \$a[\$i];".'}'." ?&gt;";
	else
	  $addcode1="&lt;? function $sfname(\$i)".'{'."\$a=Array($addcode1);return base64_decode(\$a[\$i]);".'}'." ?&gt;";
  }


  $newcode.=$addcode1;

  $tokens=token_get_all($newcode);
  $c=sizeof($tokens);
  $newcode="";

  $isstr=0;

  for($i=0;$i&lt;$c;$i++)
  {
	$token=$tokens[$i];

	if(is_array($token))
	{
	  list($tn,$ts)=$token;

	  if(($tn==T_OPEN_TAG || $tn==T_OPEN_TAG_WITH_ECHO) &amp;&amp; !$ot)
		$ot=1;

	  if($tn==T_CLOSE_TAG &amp;&amp; $ot)
		$ot=0;

	  if($ot)
	  {
		if($isstr==1 &amp;&amp; $tn==T_END_HEREDOC)
		  $isstr=0;

		if($tn==T_START_HEREDOC)
		  $isstr=1;


		if($obffuncs &amp;&amp; $isstr==0 &amp;&amp; $tn==T_STRING)
		{
		  if(isset($allfuncs[0][$ts]))
		  {
			$ts=$allfuncs[1][$ts];
		  }
		}
	  }

	  if($tn==T_END_HEREDOC)
		$ts.="\n";

	  $newcode.=$ts;
	}
	else
	{
	  $newcode.=$token;

	  if($ot)
	  {
		if($isstr==2 &amp;&amp; $token=="'")
		{
		  $isstr=0;
		  continue;
		}

		if($token=="'")
		  $isstr=2;

		if($isstr==3 &amp;&amp; $token=='"')
		{
		  $isstr=0;
		  continue;
		}

		if($token=='"')
		  $isstr=3;
	  }
	}
  }

  return $newcode;
}

print "Done!";
?&gt;

  • 0

Well in the case of using PHP with MySQL, there's no reason the whole process has to be complex at all. A set of db container functions or even a db class that are unique to different types of databases could be created that make connecting, executing queries, and fetching data simple. One thing I loved about what I had pieced together was that the following line would connect if needed, execute a query, and fetch the results:

$users = dbFetchAll('SELECT * FROM users ORDER BY username;');

I mention this because, again, it doesn't have to be complex, nor should it be.

  • 0

Most complicated code is not always the best code. In fact, the most cleverly written code is not always the best either if no one can be clever enough to figure it out. The best code is simple, straight to the point, and easy to understand.

This contest = fail.

  • Like 1
  • 0

Sure. It's a cleaned up version of the original and there are things I would change (such as the function names). It also uses mysql_pconnect for persistent connections. Included is even a method to automatically backup the database and prompt a download.

&lt;?php
global $DB_HOST, $DB_DB, $DB_USER, $DB_PASS, $DB_PORT;
$DB_HOST	= 'localhost';
$DB_DB		= 'database';
$DB_USER	= 'username';
$DB_PASS	= 'password';
$DB_PORT	= 3306;

function db_connect()
{
	global $DB_HOST, $DB_DB, $DB_USER, $DB_PASS;

	if(!function_exists('mysql_pconnect'))
		die('MySQL, a critical component for this site, is not accessible through PHP. Contact your system administrator or web host for more details.');

	$_SESSION['db'] = @mysql_pconnect($DB_HOST, $DB_USER, $DB_PASS);

	if(!$_SESSION['db'])
		die('Unable to establish a connection to the database. Contact your system administrator.');

	@mysql_select_db($DB_DB, $_SESSION['db']);
}

function db_backup()
{
	$filename = $_SERVER['HTTP_HOST'] . '_' . date('YmdHi') . '.sql.gz';
	$file = '/tmp/'.$filename;

	passthru("mysqldump --user=$DB_USER --password=$DB_PASS --host=$DB_HOST $DB_DB | gzip &gt; $file");

	$file_part = explode('/', $file);

	header('Content-Description: File Transfer');
	header('Content-Type: application/octet-stream');
	header('Content-Length: ' . (string)(filesize($file)));
	header('Content-Disposition: attachment; filename=' . $file_part[(count($file_part) - 1)]);

	readfile($file);
}

function db_escape($var)
{
	return @mysql_escape_string($var);
}

function db_write($q)
{
	$rs = db_query($q);
	return $rs ? 1 : 0;
}

function db_query($q)
{
	if(!isset($_SESSION['db']) || !$_SESSION['db'])
		db_connect();

	if(!@is_resource($_SESSION['db']))
		db_error('Not connected to a database. Cannot execute query.');

	if(isset($_SESSION['queries']))
		$_SESSION['queries'][] = $q;

	if(!$return = @mysql_query($q, $_SESSION['db']))
		db_error('Could not execute the following query&lt;br /&gt;' . "\n" . '&lt;pre id="query"&gt;' . $q . '&lt;/pre&gt;' . mysql_error($_SESSION['db']));

	return $return;
}

function db_fetch_all($q, $fetch = DB_ASSOC)
{
	$rs = db_query($q);

	switch($fetch)
	{
		case DB_ROW:
			$function = 'mysql_fetch_row';
			break;
		case DB_ARRAY:
			$function = 'mysql_fetch_array';
			break;
		case DB_ASSOC:
		default:
			$function = 'mysql_fetch_assoc';
			break;
	}

	$return = array();

	while($row = @$function($rs))
		$return[] = $row;

	return $return;
}

function db_fetch_one($q)
{
	$rs = db_query($q);
	$row = @mysql_fetch_assoc($rs);

	return count($row) ? $row : 0;
}

function db_count($q)
{
	$rs = db_query($q);
	$row = @mysql_fetch_row($rs);

	return count($row) ? $row[0] : 0;
}

function db_error($err)
{
	// included a file that would read $err inside of the site's content
	exit;
}
?&gt;

  • 0

Hi, I would like to post some of my codes.. This codes are from my site ^^

  Quote
function blogwrite($title, $author, $date, $content, $postnumber) {

echo "<center><div align=\"left\" style=\"width: 540\"><a href=\"index.php?p=comment&post=".$postnumberclass=\"title\" ><b class=\"title\">".$title."</b></center></a>";

echo "<div class='stamp'>Post: ".$postnumber;

echo " - ".$date;

echo " - Written by: ".$author."</div>";

echo "<br >       <p ><font color=\"white\">".$content."</font></p></div></center><br >";

echo "<div align='right'><a class='B' href=\"index.php?p=comment&post=".$postnumber><b>Comments(";

$sqldata = mysql_query("SELECT * FROM comment WHERE page=$postnumber") or die("Can't Retrieve Data");

$rows = mysql_num_rows($sqldata);

echo $rows.")</b></a></div></div>";

echo '<br ><center><div style="border-top: 2px double white;width: 500;"></div></center><br >';

}

The above code is a function.. It is the one that writes on the blog.. How it is order, where title will be positioned, and such...

  Quote
$sqldata = mysql_query("SELECT * FROM blogtable") or die("Can't Retrieve Data");

$rows = mysql_num_rows($sqldata);

$a = $rows;

if (isset($_GET['pages'])) {

$a = $a - (($_GET['pages'] - 1) * 10);

if ($a < 10) {

$b = 0;

} else {

$b = $a - 10;

}

while ($a != $b) {

$sqldata = mysql_query("SELECT * FROM blogtable WHERE postnumber=$a");

$data = mysql_fetch_array($sqldata);

blogwrite($data['title'], $data['author'], $data['date'], $data['content'], $data['postnumber']);

$a--;

}

} elseif ($a > 10) {

$b = $a - 10;

while ($a != $b) {

$sqldata = mysql_query("SELECT * FROM blogtable WHERE postnumber=$a");

$data = mysql_fetch_array($sqldata);

blogwrite($data['title'], $data['author'], $data['date'], $data['content'], $data['postnumber']);

$a--;

}

}

else {

while ($a != 0) {

$sqldata = mysql_query("SELECT * FROM blogtable WHERE postnumber=$a");

$data = mysql_fetch_array($sqldata);

blogwrite($data['title'], $data['author'], $data['date'], $data['content'], $data['postnumber']);

$a--;

}

}

$c = $rows;

$d = 0;

echo "<br ><b><font size=\"1\"><div><center>|</b>";

while ($c != 0) {

$d++;

if ($d == 1 and !isset($_GET['pages'])) {

echo "<b>".$d."| </b>";

} elseif ($d == $_GET['pages']) {

echo "<b>".$d."| </b>";

} else {

echo "<b><a href=\"index.php?pages=".$d>".$d."</a> | </b>";

}

if ($c < 10) {

$c = 0;

} else {

$c = $c - 10;

}

}

The code above organizes the blog entries from pages to pages ^^

See the result of this code in my site http://media6.site88.net

  • 0

This is a part of my Kubix cms.. its over 2 years old, havn't worked on it lately.

&lt;?PHP
////////////////////////////////////////////////////////
//		KUBIX CMS		//						 //
//	  Copyright (C)	  // KUBIX IS FREE SOFTWARE! //
//	  KUBIX PROJECT	  //	 DONT PAY FOR IT	 //
//   ALL RIGHTS RESERVED   //						 //
////////////////////////////////////////////////////////

// Include core files
include "Core/connect.php";
include "Core/functions.php";

// Connect
connect($server, $user, $password, $database);

// Get the options from the kbx_options table
$GetOpts = mysql_query("SELECT * FROM kbx_options");
$SiteName = mysql_result($GetOpts, 0, "SiteName");
$SiteURL = mysql_result($GetOpts, 0, "SiteURL");
$DefaultCat = mysql_result($GetOpts, 0, "DefaultCat");
$DefaultTheme = mysql_result($GetOpts, 0, "DefaultTheme");
$Announcement = mysql_result($GetOpts, 0, "Announcement");
$GuestMSG = mysql_result($GetOpts, 0, "GuestMSG");
$AdSection1 = mysql_result($GetOpts, 0, "AdSection1");
$AdSection2 = mysql_result($GetOpts, 0, "AdSection2");
$AdSection3 = mysql_result($GetOpts, 0, "AdSection3");
$AdSection4 = mysql_result($GetOpts, 0, "AdSection4");

// Get the links from the databse
$GetLinks = mysql_query("SELECT * FROM kbx_links");
$num = mysql_num_rows($GetLinks);

$Links = "";

for($i = 0; $i &lt; $num; $i++)
{
	$LinkTitle = mysql_result($GetLinks, $i, "Title");
	$LinkURL = mysql_result($GetLinks, $i, "URL");

	$Links .= '&lt;a href="' . $LinkURL . '"&gt;' . $LinkTitle . '&lt;/a&gt;&lt;br /&gt;';
}

// Get the categories from the database
$GetCats = mysql_query("SELECT * FROM kbx_cats WHERE Type = 'news'");
$num = mysql_num_rows($GetCats);

$Cats = "";

for($i = 0; $i &lt; $num; $i++)
{
	$CatID = mysql_result($GetCats, $i, "ID");
	$CatName = mysql_result($GetCats, $i, "Name");

	$Cats .= '&lt;a href="index.php?cat=' . $CatID . '"&gt;' . $CatName . '&lt;/a&gt;&lt;br /&gt;';
}

// Get the menu from the databse
$GetMenu = mysql_query("SELECT * FROM kbx_menu");
$num = mysql_num_rows($GetMenu);

$Menu = "";

for($i = 0; $i &lt; $num; $i++)
{
	$MenuTitle = mysql_result($GetMenu, $i, "Title");
	$MenuLinks = mysql_result($GetMenu, $i, "Links");

	$MenuLinks = str_replace('{MENULINKS}', $Links, $MenuLinks);
	$MenuLinks = str_replace('{MENUCATS}', $Cats, $MenuLinks);

	$Menu .= '&lt;div class="menutitle"&gt;' . $MenuTitle . '&lt;/div&gt;';
	$Menu .= '&lt;div class="menu"&gt;' . $MenuLinks . '&lt;/div&gt;';
}

// Handel Logout
if(isset($_GET['act']) &amp;&amp; $_GET['act'] == "Logout")
	header("Location:Core/LoginAuth.php?act=Logout");

// Get user information
if(isLoggedIn())
{
	$uID = $_COOKIE['member_id'];	
	$GetUserInfo = mysql_query("SELECT * FROM kbx_members WHERE id = $uID");
	$uName = mysql_result($GetUserInfo, 0, 'Name');
	$uEmail = mysql_result($GetUserInfo, 0, 'Email');
	$uMSN = mysql_result($GetUserInfo, 0, 'MSN');
	$uYahoo = mysql_result($GetUserInfo, 0, 'Yahoo');
	$uAIM = mysql_result($GetUserInfo, 0, 'AIM');
	$uOtherIM = mysql_result($GetUserInfo, 0, 'OtherIM');
	$uJoined = mysql_result($GetUserInfo, 0, 'Joined');
	$uHomePage = mysql_result($GetUserInfo, 0, 'HomePage');
	$uLevel = mysql_result($GetUserInfo, 0, 'Level');

	if($uHomePage != 0 || $uHomePage != NULL)
		$DefaultCat = $uHomePage;

	// Prepare user level
	$getlev = mysql_query("SELECT * FROM kbx_levels WHERE ID = $uLevel");

	$userLevel = mysql_result($getlev, 0, "Title");
	$uViewSite = mysql_result($getlev, 0, "ViewSite");
	$uComment = mysql_result($getlev, 0, "Comment");
	$uAddNews = mysql_result($getlev, 0, "AddNews");
	$uEditNews = mysql_result($getlev, 0, "EditNews");
	$uEditOwnProfile = mysql_result($getlev, 0, "EditOwnProfile");
	$uEditOtherProfile = mysql_result($getlev, 0, "EditOtherProfile");
}

// Prepare guest message
if(!isLoggedIn())
{
	if($GuestMSG != "")
	{
		$WelcomeGuest = '&lt;div id="GuestMSG"&gt;' . $GuestMSG . '&lt;/div&gt;' . "\n";
	}
	else
		$WelcomeGuest = '';
}
else
	$WelcomeGuest = '';

// Prepare announcement
if($Announcement != "")
{
	if(isAdm())
		$AnnouncementAdm = '&lt;div class="fright"&gt;[&lt;a href="admin.php?mod=opts">Edit</a>;/div&gt;';
	else
		$AnnouncementAdm = '';

	$Announcement = '&lt;div class="alert"&gt;' . $AnnouncementAdm . $Announcement . '&lt;/div&gt;' . "\n";
}
else
	$Announcement = '';

// Prepare userbar
if(isLoggedIn())
{
	if(isMod())
		$UserBarLinks = '&lt;a href="cp/"&gt;Control Panel&lt;/a&gt; · ';
	else
		$UserBarLinks = '';

	$UserBar = '&lt;div class="fright"&gt;' . $UserBarLinks . '&lt;a href="index.php?act=Logout">Logout</a></div>Welcome;a href="profile.php">$uName . '&lt;/a&gt;';
}
else
	$UserBar = 'Welcome: Guest (&lt;a href="login.php">Login</a>lt;a href="register.php">Register</a>
include "Themes/$DefaultTheme/header.php";
?&gt;

  • 0
  Mathachew said:
Well in the case of using PHP with MySQL, there's no reason the whole process has to be complex at all. A set of db container functions or even a db class that are unique to different types of databases could be created that make connecting, executing queries, and fetching data simple. One thing I loved about what I had pieced together was that the following line would connect if needed, execute a query, and fetch the results:

$users = dbFetchAll('SELECT * FROM users ORDER BY username;');

I mention this because, again, it doesn't have to be complex, nor should it be.

Exactly... sometimes the complexity of the code and the skill level of the programmer is found in the simplicity of their code.

Amatuers always tend to find the most difficult way of doing things that are usually very simple. Why write 50 lines of code for something that can be done with 10?

  • 0

howdy.

Firstly hello.

Saw this contest was closed, but though a late entrant may be allowed.

The following is not my code, but is the most complex code I have seen. I've tried to decipher it line by line a few times but never had any success.

I stumbled across it whilst looking at latent semantic indexing. Something used by search engines.

Basically, you take a term/document matrix and calculate the singular value decomposition. You can then use the matrices calculated to identify similar documents -e.g. google's similar pages link.

This php version is only useful for small matrices, so wasn't useful for what I needed it for. Anyhow it works, is complex and fits on two pages if you remove comments and change the font size to about 4 :).

hope you like

&lt;?php
/**
* @package JAMA
*
* For an m-by-n matrix A with m &gt;= n, the singular value decomposition is
* an m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and
* an n-by-n orthogonal matrix V so that A = U*S*V'.
*
* The singular values, sigma[$k] = S[$k][$k], are ordered so that
* sigma[0] &gt;= sigma[1] &gt;= ... &gt;= sigma[n-1].
*
* The singular value decompostion always exists, so the constructor will
* never fail.  The matrix condition number and the effective numerical
* rank can be computed from this decomposition.
*
* @author  Paul Meagher
* @license PHP v3.0
* @version 1.1
*/
class SingularValueDecomposition  {

  /**
  * Internal storage of U.
  * @var array
  */
  var $U = array();

  /**
  * Internal storage of V.
  * @var array
  */
  var $V = array();

  /**
  * Internal storage of singular values.
  * @var array
  */
  var $s = array();

  /**
  * Row dimension.
  * @var int
  */
  var $m;

  /**
  * Column dimension.
  * @var int
  */
  var $n;

  /**
  * Construct the singular value decomposition
  *
  * Derived from LINPACK code.
  *
  * @param $A Rectangular matrix
  * @return Structure to access U, S and V.
  */
  function SingularValueDecomposition ($Arg) {

	// Initialize.

	$A = $Arg-&gt;getArrayCopy();
	$this-&gt;m = $Arg-&gt;getRowDimension();
	$this-&gt;n = $Arg-&gt;getColumnDimension();
	$nu	  = min($this-&gt;m, $this-&gt;n);
	$e	   = array();
	$work	= array();
	$wantu   = true;
	$wantv   = true;	  
	$nct = min($this-&gt;m - 1, $this-&gt;n);
	$nrt = max(0, min($this-&gt;n - 2, $this-&gt;m));   

	// Reduce A to bidiagonal form, storing the diagonal elements
	// in s and the super-diagonal elements in e.

	for ($k = 0; $k &lt; max($nct,$nrt); $k++) {

	  if ($k &lt; $nct) {
		// Compute the transformation for the k-th column and
		// place the k-th diagonal in s[$k].
		// Compute 2-norm of k-th column without under/overflow.
		$this-&gt;s[$k] = 0;
		for ($i = $k; $i &lt; $this-&gt;m; $i++)
		  $this-&gt;s[$k] = hypo($this-&gt;s[$k], $A[$i][$k]);
		if ($this-&gt;s[$k] != 0.0) {
		  if ($A[$k][$k] &lt; 0.0)
			$this-&gt;s[$k] = -$this-&gt;s[$k];
		  for ($i = $k; $i &lt; $this-&gt;m; $i++)
			$A[$i][$k] /= $this-&gt;s[$k];
		  $A[$k][$k] += 1.0;
		}
		$this-&gt;s[$k] = -$this-&gt;s[$k];
	  }		   

	  for ($j = $k + 1; $j &lt; $this-&gt;n; $j++) {
		if (($k &lt; $nct) &amp; ($this-&gt;s[$k] != 0.0)) {
		  // Apply the transformation.
		  $t = 0;
		  for ($i = $k; $i &lt; $this-&gt;m; $i++)
			$t += $A[$i][$k] * $A[$i][$j];
		  $t = -$t / $A[$k][$k];
		  for ($i = $k; $i &lt; $this-&gt;m; $i++)
			$A[$i][$j] += $t * $A[$i][$k];
		  // Place the k-th row of A into e for the
		  // subsequent calculation of the row transformation.
		  $e[$j] = $A[$k][$j];
		}
	  }

	  if ($wantu AND ($k &lt; $nct)) {
		// Place the transformation in U for subsequent back
		// multiplication.
		for ($i = $k; $i &lt; $this-&gt;m; $i++)
		  $this-&gt;U[$i][$k] = $A[$i][$k];
	  }

	  if ($k &lt; $nrt) {
		// Compute the k-th row transformation and place the
		// k-th super-diagonal in e[$k].
		// Compute 2-norm without under/overflow.
		$e[$k] = 0;
		for ($i = $k + 1; $i &lt; $this-&gt;n; $i++)
		  $e[$k] = hypo($e[$k], $e[$i]);
		if ($e[$k] != 0.0) {
		  if ($e[$k+1] &lt; 0.0)
			$e[$k] = -$e[$k];
		  for ($i = $k + 1; $i &lt; $this-&gt;n; $i++)
			$e[$i] /= $e[$k];
		  $e[$k+1] += 1.0;
		}
		$e[$k] = -$e[$k];
		if (($k+1 &lt; $this-&gt;m) AND ($e[$k] != 0.0)) {
		  // Apply the transformation.
		  for ($i = $k+1; $i &lt; $this-&gt;m; $i++)
			$work[$i] = 0.0;
		  for ($j = $k+1; $j &lt; $this-&gt;n; $j++)
			for ($i = $k+1; $i &lt; $this-&gt;m; $i++)
			  $work[$i] += $e[$j] * $A[$i][$j];
		  for ($j = $k + 1; $j &lt; $this-&gt;n; $j++) {
			$t = -$e[$j] / $e[$k+1];
			for ($i = $k + 1; $i &lt; $this-&gt;m; $i++)
			  $A[$i][$j] += $t * $work[$i];
		  }
		}
		if ($wantv) {
		  // Place the transformation in V for subsequent
		  // back multiplication.
		  for ($i = $k + 1; $i &lt; $this-&gt;n; $i++)
			$this-&gt;V[$i][$k] = $e[$i];
		}		
	  }
	} 

	// Set up the final bidiagonal matrix or order p.
	$p = min($this-&gt;n, $this-&gt;m + 1);
	if ($nct &lt; $this-&gt;n)
	  $this-&gt;s[$nct] = $A[$nct][$nct];
	if ($this-&gt;m &lt; $p)
	  $this-&gt;s[$p-1] = 0.0;
	if ($nrt + 1 &lt; $p)
	  $e[$nrt] = $A[$nrt][$p-1];
	$e[$p-1] = 0.0;
	// If required, generate U.
	if ($wantu) {
	  for ($j = $nct; $j &lt; $nu; $j++) {
		for ($i = 0; $i &lt; $this-&gt;m; $i++)
		  $this-&gt;U[$i][$j] = 0.0;
		$this-&gt;U[$j][$j] = 1.0;
	  }
	  for ($k = $nct - 1; $k &gt;= 0; $k--) {
		if ($this-&gt;s[$k] != 0.0) {
		  for ($j = $k + 1; $j &lt; $nu; $j++) {
			$t = 0;
			for ($i = $k; $i &lt; $this-&gt;m; $i++)
			  $t += $this-&gt;U[$i][$k] * $this-&gt;U[$i][$j];
			$t = -$t / $this-&gt;U[$k][$k];
			for ($i = $k; $i &lt; $this-&gt;m; $i++)
			  $this-&gt;U[$i][$j] += $t * $this-&gt;U[$i][$k];
		  }
		  for ($i = $k; $i &lt; $this-&gt;m; $i++ )
			$this-&gt;U[$i][$k] = -$this-&gt;U[$i][$k];
		  $this-&gt;U[$k][$k] = 1.0 + $this-&gt;U[$k][$k];
		  for ($i = 0; $i &lt; $k - 1; $i++)
			 $this-&gt;U[$i][$k] = 0.0;
		 } else {
		   for ($i = 0; $i &lt; $this-&gt;m; $i++)
			 $this-&gt;U[$i][$k] = 0.0;
		   $this-&gt;U[$k][$k] = 1.0;
		 }
	  }
	}

	// If required, generate V.
	if ($wantv) {
	  for ($k = $this-&gt;n - 1; $k &gt;= 0; $k--) {
		if (($k &lt; $nrt) AND ($e[$k] != 0.0)) {
		  for ($j = $k + 1; $j &lt; $nu; $j++) {
			$t = 0;
			for ($i = $k + 1; $i &lt; $this-&gt;n; $i++)
			  $t += $this-&gt;V[$i][$k]* $this-&gt;V[$i][$j];
			$t = -$t / $this-&gt;V[$k+1][$k];
			for ($i = $k + 1; $i &lt; $this-&gt;n; $i++)
			  $this-&gt;V[$i][$j] += $t * $this-&gt;V[$i][$k];
		  }
		}
		for ($i = 0; $i &lt; $this-&gt;n; $i++)
		   $this-&gt;V[$i][$k] = 0.0;
		$this-&gt;V[$k][$k] = 1.0;
	  }
	}

	// Main iteration loop for the singular values.
	$pp   = $p - 1;
	$iter = 0;
	$eps  = pow(2.0, -52.0);
	while ($p &gt; 0) {	  

	  // Here is where a test for too many iterations would go.
	  // This section of the program inspects for negligible
	  // elements in the s and e arrays.  On completion the
	  // variables kase and k are set as follows:
	  // kase = 1  if s(p) and e[k-1] are negligible and k&lt;p
	  // kase = 2  if s(k) is negligible and k&lt;p
	  // kase = 3  if e[k-1] is negligible, k&lt;p, and
	  //		   s(k), ..., s(p) are not negligible (qr step).
	  // kase = 4  if e(p-1) is negligible (convergence).

	  for ($k = $p - 2; $k &gt;= -1; $k--) {
		if ($k == -1)
		  break;
		if (abs($e[$k]) &lt;= $eps * (abs($this-&gt;s[$k]) + abs($this-&gt;s[$k+1]))) {
		  $e[$k] = 0.0;
		  break;
		}
	  }
	  if ($k == $p - 2)
		$kase = 4;
	  else {
		for ($ks = $p - 1; $ks &gt;= $k; $ks--) {
		  if ($ks == $k)
			break;
		  $t = ($ks != $p ? abs($e[$ks]) : 0.) + ($ks != $k + 1 ? abs($e[$ks-1]) : 0.);
		  if (abs($this-&gt;s[$ks]) &lt;= $eps * $t)  {
			$this-&gt;s[$ks] = 0.0;
			break;
		  }
		}
		if ($ks == $k)
		   $kase = 3;
		else if ($ks == $p-1)
		   $kase = 1;
		else {
		   $kase = 2;
		   $k = $ks;
		}
	  }
	  $k++;

	  // Perform the task indicated by kase.
	  switch ($kase) {
		 // Deflate negligible s(p).
		 case 1:
		   $f = $e[$p-2];
		   $e[$p-2] = 0.0;
		   for ($j = $p - 2; $j &gt;= $k; $j--) {
			 $t  = hypo($this-&gt;s[$j],$f);
			 $cs = $this-&gt;s[$j] / $t;
			 $sn = $f / $t;
			 $this-&gt;s[$j] = $t;
			 if ($j != $k) {
			   $f = -$sn * $e[$j-1];
			   $e[$j-1] = $cs * $e[$j-1];
			 }
			 if ($wantv) {
			   for ($i = 0; $i &lt; $this-&gt;n; $i++) {
				 $t = $cs * $this-&gt;V[$i][$j] + $sn * $this-&gt;V[$i][$p-1];
				 $this-&gt;V[$i][$p-1] = -$sn * $this-&gt;V[$i][$j] + $cs * $this-&gt;V[$i][$p-1];
				 $this-&gt;V[$i][$j] = $t;
			   }
			 }
		   }
		   break;
		 // Split at negligible s(k).
		 case 2:
		   $f = $e[$k-1];
		   $e[$k-1] = 0.0;
		   for ($j = $k; $j &lt; $p; $j++) {
			 $t = hypo($this-&gt;s[$j], $f);
			 $cs = $this-&gt;s[$j] / $t;
			 $sn = $f / $t;
			 $this-&gt;s[$j] = $t;
			 $f = -$sn * $e[$j];
			 $e[$j] = $cs * $e[$j];
			 if ($wantu) {
			   for ($i = 0; $i &lt; $this-&gt;m; $i++) {
				 $t = $cs * $this-&gt;U[$i][$j] + $sn * $this-&gt;U[$i][$k-1];
				 $this-&gt;U[$i][$k-1] = -$sn * $this-&gt;U[$i][$j] + $cs * $this-&gt;U[$i][$k-1];
				 $this-&gt;U[$i][$j] = $t;
			   }
			 }
		   }
		   break;		   
		 // Perform one qr step.
		 case 3:				  
		   // Calculate the shift.						  
		   $scale = max(max(max(max(
					abs($this-&gt;s[$p-1]),abs($this-&gt;s[$p-2])),abs($e[$p-2])),
					abs($this-&gt;s[$k])), abs($e[$k]));
		   $sp   = $this-&gt;s[$p-1] / $scale;
		   $spm1 = $this-&gt;s[$p-2] / $scale;
		   $epm1 = $e[$p-2] / $scale;
		   $sk   = $this-&gt;s[$k] / $scale;
		   $ek   = $e[$k] / $scale;
		   $b	= (($spm1 + $sp) * ($spm1 - $sp) + $epm1 * $epm1) / 2.0;
		   $c	= ($sp * $epm1) * ($sp * $epm1);
		   $shift = 0.0;
		   if (($b != 0.0) || ($c != 0.0)) {
			 $shift = sqrt($b * $b + $c);
			 if ($b &lt; 0.0)
			   $shift = -$shift;
			 $shift = $c / ($b + $shift);
		   }
		   $f = ($sk + $sp) * ($sk - $sp) + $shift;
		   $g = $sk * $ek;  
		   // Chase zeros.  
		   for ($j = $k; $j &lt; $p-1; $j++) {
			 $t  = hypo($f,$g);
			 $cs = $f/$t;
			 $sn = $g/$t;
			 if ($j != $k)
			   $e[$j-1] = $t;
			 $f = $cs * $this-&gt;s[$j] + $sn * $e[$j];
			 $e[$j] = $cs * $e[$j] - $sn * $this-&gt;s[$j];
			 $g = $sn * $this-&gt;s[$j+1];
			 $this-&gt;s[$j+1] = $cs * $this-&gt;s[$j+1];
			 if ($wantv) {
			   for ($i = 0; $i &lt; $this-&gt;n; $i++) {
				 $t = $cs * $this-&gt;V[$i][$j] + $sn * $this-&gt;V[$i][$j+1];
				 $this-&gt;V[$i][$j+1] = -$sn * $this-&gt;V[$i][$j] + $cs * $this-&gt;V[$i][$j+1];
				 $this-&gt;V[$i][$j] = $t;
			   }
			 }																	  
			 $t = hypo($f,$g);
			 $cs = $f/$t;
			 $sn = $g/$t;
			 $this-&gt;s[$j] = $t;
			 $f = $cs * $e[$j] + $sn * $this-&gt;s[$j+1];
			 $this-&gt;s[$j+1] = -$sn * $e[$j] + $cs * $this-&gt;s[$j+1];
			 $g = $sn * $e[$j+1];
			 $e[$j+1] = $cs * $e[$j+1];
			 if ($wantu &amp;&amp; ($j &lt; $this-&gt;m - 1)) {
			   for ($i = 0; $i &lt; $this-&gt;m; $i++) {
				 $t = $cs * $this-&gt;U[$i][$j] + $sn * $this-&gt;U[$i][$j+1];
				 $this-&gt;U[$i][$j+1] = -$sn * $this-&gt;U[$i][$j] + $cs * $this-&gt;U[$i][$j+1];
				 $this-&gt;U[$i][$j] = $t;
			   }
			 }				
		   }
		   $e[$p-2] = $f;
		   $iter = $iter + 1;
		   break;
		 // Convergence.
		 case 4:
		   // Make the singular values positive.
		   if ($this-&gt;s[$k] &lt;= 0.0) {
			 $this-&gt;s[$k] = ($this-&gt;s[$k] &lt; 0.0 ? -$this-&gt;s[$k] : 0.0);
			 if ($wantv) {
			   for ($i = 0; $i &lt;= $pp; $i++)
				 $this-&gt;V[$i][$k] = -$this-&gt;V[$i][$k];
			 }
		   }
		   // Order the singular values.  
		   while ($k &lt; $pp) {
			if ($this-&gt;s[$k] &gt;= $this-&gt;s[$k+1])
			  break;
			$t = $this-&gt;s[$k];
			$this-&gt;s[$k] = $this-&gt;s[$k+1];
			$this-&gt;s[$k+1] = $t;
			if ($wantv AND ($k &lt; $this-&gt;n - 1)) {
			  for ($i = 0; $i &lt; $this-&gt;n; $i++) {
				$t = $this-&gt;V[$i][$k+1];
				$this-&gt;V[$i][$k+1] = $this-&gt;V[$i][$k];
				$this-&gt;V[$i][$k] = $t;
			  }
			}
			if ($wantu AND ($k &lt; $this-&gt;m-1)) {
			  for ($i = 0; $i &lt; $this-&gt;m; $i++) {
				$t = $this-&gt;U[$i][$k+1];
				$this-&gt;U[$i][$k+1] = $this-&gt;U[$i][$k];
				$this-&gt;U[$i][$k] = $t;
			  }
			}
			$k++;
		   }
		   $iter = 0;
		   $p--;
		   break;								   
	  } // end switch	  
	} // end while

	/*
	echo "&lt;p&gt;Output A&lt;/p&gt;";   
	$A = new Matrix($A);		
	$A-&gt;toHTML();

	echo "&lt;p&gt;Matrix U&lt;/p&gt;";	
	echo "&lt;pre&gt;";
	print_r($this-&gt;U);		
	echo "&lt;/pre&gt;";

	echo "&lt;p&gt;Matrix V&lt;/p&gt;";	
	echo "&lt;pre&gt;";
	print_r($this-&gt;V);		
	echo "&lt;/pre&gt;";	

	echo "&lt;p&gt;Vector S&lt;/p&gt;";	
	echo "&lt;pre&gt;";
	print_r($this-&gt;s);		
	echo "&lt;/pre&gt;";	
	exit;
	*/

  } // end constructor

  /**
  * Return the left singular vectors
  * @access public
  * @return U
  */
  function getU() {
	return new Matrix($this-&gt;U, $this-&gt;m, min($this-&gt;m + 1, $this-&gt;n));
  }

  /**
  * Return the right singular vectors
  * @access public   
  * @return V
  */
  function getV() {
	return new Matrix($this-&gt;V);
  }

  /**
  * Return the one-dimensional array of singular values
  * @access public   
  * @return diagonal of S.
  */
  function getSingularValues() {
	return $this-&gt;s;
  }

  /**
  * Return the diagonal matrix of singular values
  * @access public   
  * @return S
  */
  function getS() {
	for ($i = 0; $i &lt; $this-&gt;n; $i++) {
	  for ($j = 0; $j &lt; $this-&gt;n; $j++)
		$S[$i][$j] = 0.0;
	  $S[$i][$i] = $this-&gt;s[$i];
	}
	return new Matrix($S);
  }

  /**
  * Two norm
  * @access public   
  * @return max(S)
  */
  function norm2() {
	return $this-&gt;s[0];
  }

  /**
  * Two norm condition number
  * @access public   
  * @return max(S)/min(S)
  */
  function cond() {
	return $this-&gt;s[0] / $this-&gt;s[min($this-&gt;m, $this-&gt;n) - 1];
  }

  /**
  * Effective numerical matrix rank
  * @access public   
  * @return Number of nonnegligible singular values.
  */
  function rank() {
	$eps = pow(2.0, -52.0);
	$tol = max($this-&gt;m, $this-&gt;n) * $this-&gt;s[0] * $eps;
	$r = 0;
	for ($i = 0; $i &lt; count($this-&gt;s); $i++) {
	  if ($this-&gt;s[$i] &gt; $tol)
		$r++;
	}
	return $r;
  }
}
?&gt;

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • That's nice and all. but I generally just stick with Lutris paired with 'ge-proton' (which gets updated fairly often (June 1st was last update) as the 'ge-proton' entry in Lutris uses stuff here... https://github.com/GloriousEggroll/proton-ge-custom/releases ) and the like to play my games. p.s. if a person wants to stick with a specific version from that link you can download a specific version and extract it to "~/.local/share/lutris/runners/proton/". then select it in Lutris options on game shortcut is the basic idea. because by default the standard 'ge-proton' entry will automatically get updated which can occasionally cause issues even though it's usually fine. but manually setting it on a specific version will prevent the standard updates on 'ge-proton' from messing with it on a particular game you may have issues with if that gets updated etc. one good example of the 'ge-proton' updates messing with a game in particular is the 'offline' version of RDR2 1491.50 as I setup a specific version there and after removing the 'vulkan-1 (native)' entry in 'Wine configuration' (if you don't remove this the game flat out won't start up) is when the 'ge-proton' updates, it will restore that 'vulkan-1 (native)' entry and prevent the game from working. you can always remove the entry on the RDR2.exe in Wine configuration specifically after updates, but doing that everytime that updates will get old quickly. hence, keeping it on a specific GE Proton version stops me from having to mess with it as then you just adjust it once and you are done with it. also, when using 'bat' files to start a game (like Hitman: WoA for example using Peacock etc) I had some issues with GE Proton after '9-27', so I got the game locked to '9-27' (April 1st) instead of the current '10-4' (June 1st).
    • Sam Altman says AI could soon help with discovering new knowledge by Hamid Ganji OpenAI is currently at the forefront of developing powerful AI models, while its ChatGPT product is rewriting our traditional way of looking for new information. The company's CEO, Sam Altman, now says AI could even help humans discover new knowledge. He also described AI agents as junior employees. Speaking at the Snowflake Summit 2025, Altman boasted that AI agents can act like junior employees, saying, "You hear people that talk about their job now is to assign work to a bunch of agents, look at the quality, figure out how it fits together, give feedback, and it sounds a lot like how they work with a team of still relatively junior employees." OpenAI CEO also added AI agents could help humans discover new knowledge in "limited cases" or "figure out solutions to business problems that are kind of very non-trivial." While the use of AI for scientific discovery is still viewed with skepticism, the technology has proven its capabilities for new discoveries in several cases. For example, the Microsoft Discovery platform, designed for accelerating scientific research and development by AI agents, was recently able to discover a new chemical for cooling data centers in just 200 hours, a process that normally takes years to research and complete by humans. AI firms are also shifting their focus toward developing AI agents capable of performing various tasks. OpenAI recently unveiled Codex, which contains AI agents for helping programmers write and debug code. According to Altman, OpenAI engineers are already using Codex. As AI agents become more intelligent, more employees should be concerned about losing their jobs. Companies have already started replacing some specific roles with AI. For example, Duolingo has replaced its contract workers with AI, while Shopify managers need to provide reasons why AI cannot handle a job before seeking approval for new hires. Via: Business Insider
    • I personally don't think there will be many survivors past the ESU date, but I can be wrong🙂 >Firefox still supports Windows 7 (until the end of August), which will be just over 16 years since release. Well, yes, but it's an ESR version, which kind of doesn't count as fresh for me. So the last mainline version of Firefox with W7 support was 115, which was released in 2023, exactly around the W7 ESU expiration.
    • Hey, sounds like it’s definitely time for an upgrade. The R7000 had an excellent run! If you want lots of wired ports and future-proofing, the Asus RT-BE88U is a killer choice. It’s got 2x 10GbE, 4x 2.5GbE, and handles WiFi 7 like a champ. Super fast, stable, and the ASUS firmware is solid with loads of features. The TP-Link BE900 is also great, sleek design, strong performance, and a combo 10G port (RJ45/SFP+), but it has fewer wired ports than the Asus. Netgear RS700S is powerful too, but the firmware isn’t as flexible and only has one 10G port. It might feel familiar from your R7000. If wired ports are a big deal, maybe adding a 2.5G or 10G switch later gives you more options. My vote is RT-BE88U all the way.
    • WhatsApp beta users can now craft their own AI chatbots - here's why you might want one by Paul Hill Since the end of 2022, tech companies, and even non-tech companies, have been clamoring to pile AI into their services. Despite what many people say about not liking AI, plenty of people are still using it every day, making it a key offering. Not only that, but for public companies like Meta, the inclusion of AI does very well with investors, so that’s another reason it’s being added. While the most common chatbot people talk about is ChatGPT, which is pretty faceless, there is demand for AI chatbots with a face, this is why people use tools like Character.ai and Replika. One of the only big tech firms that has gone down this route is Meta, which lets you create and share AI characters. To date, some of Meta’s apps, like Messenger, allow you to chat with these AI personas but you can’t do that yet in the stable version of WhatsApp. The company is now testing it with the Android Beta and when it’s ready, it should make a more seamless experience across Meta’s applications. Many of the popular bots that people use including ChatGPT, Gemini, and DeepSeek are faceless and offer the same tone out of the box. To be fair to Gemini, it does allow all users to create Gems now, and they actually offer a bit more flexibility than just creating characters to talk to like in Messenger. The chatbots in Messenger have the benefit of being in the Messenger app, which most people use and giving them a personality and making them feel like an “AI person” fits better in Messenger. Whether we really need these AI bots in Messenger is still up for debate. It’s quite a new feature and some people may find some good uses for them, but as mentioned, they don’t seem as flexible, or provide as detailed responses as custom bots made on Poe or Gemini Gems. They are definitely for having casual conversations with. WhatsApp's new AI chatbot creator We’ve known that the chatbot feature was coming to WhatsApp for a long time already. WhatsApp beta for Android 2.25.1.26, released in January, included the feature for some beta testers. With the latest WhatsApp beta for Android 2.25.18.4, it seems like WhatsApp is trialing the feature with members of the public, suggesting its release is imminent. Screenshots of the app, obtained by WABetaInfo show that you can describe your AI, select its personality, its traits, its image and more. The process seems to be the same as the process already available in Messenger. One of the nice things that Meta provides when creating these AI bots is templates and suggestions such as the attitude of the bot or the instructions for the bot. This is the same as in Messenger and allows you to get started chatting with your custom bots faster. In terms of sharing, you have the option to make the bots private, share them with friends (at least in the case of Messenger and presumably WhatsApp), or share them publicly. If you make something specific for your needs then the private option would be best, while bots with mass appeal could be set to public. Creating bots in WhatsApp is straightforward once you have access to the AI Studio. During the creation process you’ll need to name your AI, define its personality, choose a tone, design an avatar (some will be made for you with Meta’s AI), and create a catchy tagline to attract users if you ever set it to public. Much of the information will be pre-filled based on the initial details you provide about the AI’s role and personality. Some ideas for bots that you can create include a motivational coach, a travel recommendation AI, or a daily planner. While setting up these AI bots is easy to do, users may find their actual benefits limited. Besides the nagging feeling that you’re socializing with a clever bit of code, Meta seems to truncate the answers of these bots so they don’t rattle on, but depending on what you want them to do, you may need them to give a lengthy response, but they won’t. What personalized AI chatbots could offer If you are looking for an AI that chats to you conversationally like real people do, then this could be the feature you’re looking for. The fact that you can personalize bots with specific traits is something you can’t do as easily in apps like ChatGPT and Gemini and the fact that they have an avatar makes them more connectable too. Two of the defining features of Meta’s AI implementation is the ability to create custom AIs with a unique personality and to share them publicly. If you are having difficulty thinking of what a bot could be instructed to do, you can easily find community bots and interact with those instead and may find they provide some value. While these bots could be interesting for some people, they do carry the same risks as other AIs and that is that they can hallucinate. There was also a case in the UK where a man had been encouraged by his Replika to break into Buckingham Palace with a crossbow to kill the then head of state. Similar issues to this could result from Meta’s AI chatbots in time. Potential pitfalls While the feature is pretty interesting there are some things to be aware of. Firstly, the feature is still in beta on WhatsApp so you may run into issues and things could change once it’s finally released. Meta also states that it uses your interactions to improve its AI services, for this reason it is essential not to share personal information as Meta could read it. While Meta does limit the creation of bots that go against its standards, the company also warns that bots can output harmful content, so this could be dangerous for impressionable people who end up acting on what an AI has said with negative outcomes. What to watch for next It’s not clear when these AI chatbots will be available in the stable channel but given that a wider rollout is underway among beta users perhaps we are not too far off. For most people, this is not going to be a must-have feature, just a nice to have. We’ve been using WhatsApp to chat with friends for years, so clearly the app is just fine without the inclusion of AI, but when it’s available, people may be able to get more value out of the app. When the feature launches for all users, bots should be discoverable in the same way they are on Messenger where they’re categorized by category allowing users to begin chats easily. It remains to be seen how users will interact with this feature in the long-run. Last year, we reported that Meta was looking to give bots profiles on its social networks and this was met by somebacklash in our comments section.
  • Recent Achievements

    • Enthusiast
      Epaminombas went up a rank
      Enthusiast
    • Posting Machine
      Fiza Ali earned a badge
      Posting Machine
    • One Year In
      WaynesWorld earned a badge
      One Year In
    • First Post
      chriskinney317 earned a badge
      First Post
    • Week One Done
      Nullun earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      186
    2. 2
      snowy owl
      130
    3. 3
      ATLien_0
      129
    4. 4
      Xenon
      119
    5. 5
      +FloatingFatMan
      93
  • Tell a friend

    Love Neowin? Tell a friend!