Archive for June, 2009
Keyboard ports not working, BIOS not working and yet working!
by z3n on Jun.27, 2009, under Tips & Hints
Problem:
Since i’m broke, i need to get this type of jobs in order to make some dough, it’s not that i don’t like it, but it’s good to have a challenge ahead.
So i got 2 old machines to reinstall the OS, might look a simple task, but it wasn’t. Both machines didn’t regonize the keyboard, one of them, required an adapter from the ps/2 to the big ps/2 which i don’t know the right name.
So i was stuck on the POST, “Keyboard not found press any key to continue” — hahahah — also one of the machines got a battery malfuncion, which means that once it’s unplugged it’s BIOS will reset to factory defaults.
Solution:
First i tried and old `big ps/2` keyboard i have here, i though that my keywboard might be not working right. FAIL.
Then i tried an alternate ps/2 hook i had. FAIL.
On one of the machines i was able to bypass the POST, however, the machine’s devices weren’t configured, so i couldn’t boot. Although the keyboard was working, misteriously, NOT on the POST.
So i decided to do a hard reset on the BIOS, for the first machine it instantly worked, i got the keyboard with the adaptor working just fine, so i could boot the system up and reinstall the OS. Now for the second one, i couldn’t get into BIOS Setup, keyboard wasn’t being detected at all. half FAIL.
I have this ps/2 -> usb thingy, it allows me to plug a ps/2 mouse and a ps/2 keyboard and converts it to a usb port. So i tried this and it, finally worked. In this case i had to enable legacy usb keyboard support on BIOS, in order to have it working after POST.
I also had a spare motherboard battery (from an 386 board) which worked just great on this , also crappy, old computer, so no more BIOS resets.
Hope it lasts for more than a month so i don’t have to redo it for free! :)
Display MySQL tables detailed information
by z3n on Jun.18, 2009, under Coding, Tips & Hints
Problema:
Como saber todas as informações possíveis sobre uma tabela em cada database?
Solução:
show table status;
Fonte:
PHP Benchmark – MySQL vs File vs Semaphore
by z3n on Jun.17, 2009, under Coding, Tips & Hints
Problem:
Which method is faster? MySQL? MySQL HEAP? Direct File access? Semaphore?
Solution:
First a little explanation:
This test will incrase a variable/value from 0 to 10000, I did this test to figure out what’s the best method to do a heavy usage counter.
MySQL: will do a simple update query on a table, update tbl set counter=counter+1 limit 1
MySQL HEAP: will do the same of MySQL, however using a heap table which is stored directly on computer memory, many people claims that this is the fastest method.
Direct File: will store the variable on a file that is readden then written everytime a change is needed.
Semaphore: will store a variable straight into kernel shared memory (those variables will also be avaliable to programs external to apache/php)
Regular Variable: just for comparsion propouse, this test will show how much time it would take to incrase the counter into a regular php variable, not shared or anything.
Test Setup:
Athlon +2200 256kb cache
1GB RAM
Fedora 10
MySQL 5.0.77
PHP 5.2.9
Apache 2.2.9
Results: (test type (numbers added): how much time it took – how many times can be done in a day)
Regular Variable (10000): 0.003432035446167s – 251745651684.61/day
Semaphore (10000): 0.8582170009613s – 1006738387.8812/day
File (10000): 124.96164608002s – 6914121.4692927/day
MySQL (10000): 46.476830005646s – 18589908.130461/day
MySQL Heap (10000): 24.242248058319s – 35640259.018945/day
Conclusion:
As stated on the tests, semaphore is way faster than any other method, it might be a bit tricky to work with but it really did the job well, MySQL HEAP, was the second, althought it’s about 24 times slower, might be a good solution for you if you need to work with databases, however, MySQL HEAP has some limitations that might be a issue. Regular MySQL also shown itself fast, but about 2 times slower than heap. The file method could be faster on a SCSI or SSD, since i don’t have any of those i will stick with my slow SATA disk, however, i don’t think that even on a fast SSD this would be faster than semaphore, one simple reason is that the I/Os would be so many that they would limit the speed and viability of this idea, and also consume massive system resources.
* A note about semaphore: This method uses a shared part of memory, you can raise the limit of shared memory depending on your needs (check shared memory configuration link), note that if you’re going to use this method by many different processes you need to build up a queue system in order to make it work right, php has all the functions able to do it.
* Note 2: Semaphore stored values will not go away if php or apache crashes, they are stored straight into kernel shared memory, unless the whole machine crashes/reboot it will still there.
Links:
Faking Google Analytics Statistics
by z3n on Jun.17, 2009, under Coding, Tips & Hints
Problem:
Let’s assume you want to build up fake statistics on google analytics using a php script.
Solution:
You just need to input the google analytics UA code and you’re ready to go:
-
-
// (c) z3n – R1V1@090617 – z3n666@gmail.com – www.overflow.biz
-
-
// Fake Resolutions
-
$resolutions=array("1024×768","1280×800","1280×1024","1440×900","1680×1050");
-
// Fake Flash Versions
-
$flash=array("10.0%20r2","10.0%20r1","9.0%20r12");
-
// Fake Languages
-
$languages=array("en-us","de","ja","ko","pt-br");
-
-
// functions
-
-
function baseurl($x) { //v1.03
-
$y=str_replace("http://","",$x);
-
$s=strpos($y,"/");
-
if ($s === false) {
-
$s=strpos($y,"?");
-
}
-
if ($s !== false) {
-
$y=substr($y,0,$s);
-
}
-
return "http://".$y;
-
}
-
function getmicrotime() { list($usec, $sec) = explode(" ",microtime());return ((float)$usec + (float)$sec); }
-
function ga_fake($url,$ua) {
-
global $resolutions,$flash,$languages;
-
$gmt=round(getmicrotime(),0); // timestamp
-
$uid=mt_rand(70710490,92710490); // unique id number
-
$bid=mt_rand(21234567,91234567).mt_rand(1018864,9999999).mt_rand(1021,9999); // big random number
-
$java=(rand(0,100) > 85) ? 0 : 1; // java enabled?
-
$x="http://www.google-analytics.com/__utm.gif?utmwv=4.3&utmn=".mt_rand(64045995,94045995)."&utmhn=".str_replace("http://","",baseurl($url))."&utmcs=ISO-8859-1&utmsr=".$resolutions[array_rand($resolutions,1)]."&utmsc=32-bit&utmul=".$languages[array_rand($languages,1)]."&utmje=".$java."&utmfl=".$flash[array_rand($flash,1)]."&utmhid=".mt_rand(1650046796,1890046796)."&utmr=-&utmp=".str_replace(baseurl($url),"",$url)."&utmac=".$ua."&utmcc=__utma%3D".$uid.".".$bid.".".$gmt.".".$gmt.".".$gmt.".1%3B%2B__utmz%3D".$uid.".".$gmt.".1.1.utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B";
-
@file_get_contents($x);
-
}
-
-
// now you just need to call it
-
-
ga_fake("http://someurl/where/the/hit/happened/","UA-123456-78");
Custom Google Search “API” by PHP (No API Needed)
by z3n on Jun.16, 2009, under Coding, Tips & Hints
Problema:
Eu estava procurando por um API para fazer buscas no google para usar em um script em php, podendo assim, manipular os resultados e urls. Depois de alguma busca achei o google search api que funciona com a extenção SOAP do php, porém, este API foi descontinuado e substituído pelo API em AJAX, que não serve o propósito, uma vez que processa os dados no cliente e não no servidor como era a minha idéia inicial.
Solução:
Pode parecer com um hack, porém é a única forma que eu encontrei, e além disso, foi muito mais fácil do que ficar procurando informações sobre o API. Este PHP faz um pedido normal ao google depois corta o resultado usando DOM , filtrando e finalmente retornando os URLs do resultado da busca. Você pode alterar o domínio do google para fazer buscas localizadas em outros países.
-
-
if (!isset($argv[1])) { echo "Usage: ".$_SERVER['PHP_SELF']." [start]";die; } else { $s=$argv[1]; }
-
-
$e=(isset($argv[2])) ? "&start=".$argv[2] : "";
-
-
$x=file_get_contents("http://www.google.com/search?q=".$s."&num=100".$e);
-
-
// apply DOM
-
-
$dom=new DOMDocument();
-
@$dom->loadHTML($x);
-
-
$xpath=new DOMXPath($dom);
-
$a=$xpath->evaluate("/html/body//a");
-
for ($i=$k=0;$i<$a->length;$i++) {
-
$y=$a->item($i);
-
$z=$y->getAttribute('href');
-
// filter out google crap, wikipedia and youtube
-
if (($z{0} != "/") && (strpos($z,"q=cache:") === false) && (strpos($z,"youtube.com/") === false) && (strpos($z,"wikipedia.org/") === false) && (strpos($z,".google.com/") === false)) {
-
$_url[$k]=$z;$k++;
-
}
-
}
-
-
print_r($_url);
-
echo "Found: ".$k." urls.";
*Nota: Você irá precisar de suporte a DOM para rodar este script; Este exemplo foi desenvolvido para aceitar inputs pelo CLI, porém você pode facilmente modifica-lo.
Restarting dead services using cron/bash
by z3n on Jun.11, 2009, under Coding, Linux Happyness
which will restart apache.
Problema:
Um serviço / processo para de funcionar, como reiniciá-lo automaticamente ?
Solução:
Este script resolve:
pstree | grep httpd | wc -l | awk ‘{if ($1 == 0) system(“service httpd restart”) }’
neste exemplo estou checando se o httpd (apache) está rodando, quebrando os pipes fica assim:
o pstree vai listar todos os processos,
grep httpd irá procurar por httpd no pstree,
wc -l irá contar as palavras no que o grep retorna, basicamente irá retornar 0 ou 1,
awk irá comparar o valor do wc -l , se o processo não estiver rodando ($1 == 0) ele irá executar o comando para reiniciá-lo, neste caso, service httpd restart
Você também pode checar pelas portas, como proposto pelo HTNet:
netstat -ln | grep “:80″ | wc -l | awk ‘{if ($1 == 0) system(“service httpd restart”) }’
Depois é só fazer um .sh e colocar no crontab!
Forcing Windows Update Agent to Run
by z3n on Jun.11, 2009, under Tips & Hints
Problem:
How to make windows update agent (the one on tray) to run when you want?
Solution:
net stop wuauserv (not necessarly needed)
wuauclt.exe /detectnow
be patient, it might take a while for it shows up on tray and start downloading
Sources:
Building Vidalia from Source at Fedora Core 6
by z3n on Jun.10, 2009, under Linux Happyness
Problem:
How to build vidalia from source at FC6 ?
Solution:
Ignore the INSTALL file, apparently it’s outdated and qt is no longer the same they link there, you can install all the needed packs from yum:
yum install qt4 qt4-dev* nas tor privoxy qt cmake
Then it’s just build from source:
cd /path/to/vidalia-src
cmake .;make;make install
done!
Source:
Extra:
For me, tor didn’t worked at all it kept connecting forever and couldn’t build a node list, i figured out that the latest tor engine for fc6 installed by yum was 0.1.x which didn’t work with the actual network anymore, so i had install tor 0.2.x from the source, after that it almost connected, tor kept building a nodelist forever, so i checked the message log and figured out that the machine clock was wrong, in order to fix that, i had to sync it using ntp.
Calling a Javascript function from a different frame
by z3n on Jun.09, 2009, under Coding, Tips & Hints
Problema:
Como chamar uma função em outro frame/iframe ?
Solução:
Depende de onde estiver a função, se estiver no _top (se estiver sendo chamada de dentro de um iframe):
top.função();
Ou se for de um frame para outro:
parent.frame['nome_do_frame'].função();
ou
parent.frame[número_do_frame].função();
md5 File Comparsion PHP Script
by z3n on Jun.05, 2009, under Coding, Tips & Hints
Problema:
Como saber quais arquivos são iguais dentro de vários diretórios ?
Solução:
Um script em PHP que checa todos eles usando md5 e compara com os resultados obtidos para saber quais são iguais.
-
-
// (c) z3n – R1V1@090605 – z3n666@gmail.com – www.overflow.biz
-
-
define("is_debug",1);
-
define("_dbp","_debug.log");
-
define('_bf',512288); // debug buffer
-
define('_dw',250); // maximum debug file size, _bf*_dw bytes
-
define('_cr',chr(13).chr(10)); // CRLF definition
-
define('_dt_sml','Y-m-d h:i:s'); // date small format (for debug)
-
ini_set("memory_limit","128M"); // avoid happyness
-
-
// functions
-
-
function _o($x) { if (is_debug) { _dbg($x); } echo $x."\n"; }
-
function _fw($fn,$txt,$m) { /* v1.5 with auto mkdir */ global $__fw,$__fwb;$__fw++;$__fwb+=strlen($txt);$x=1;$fn=str_replace("\\","/",$fn);if (strpos($fn,"/") !== false) { $p=substr($fn,0,strrpos($fn,"/"));if (!is_dir($p)) { _o("Mkdir: ".$p);mkdir($p,777,true); } } if ((is_writable($fn)) || (!file_exists($fn))) { if (!$fp=fopen($fn,$m)) { $x=0;break; } if (!fwrite($fp,$txt)) { $x=0;break; } fclose($fp); } _o("Wrote: ".$fn);return $x; }
-
function _dbg($x,$f=0) { /* v1.9 */ global $_bg,$_dw;if ((is_debug) && ($_dw < _dw)) { if ($x != "") { $_bg.=date(_dt_sml).":".$x._cr; } if ((strlen($_bg) > _bf) || ($f)) { $x=$_bg;$_dw++;$_bg="";_fw(_dbp,$x,"a"); } } }
-
function rddir($dir) { /* v2.11 */
-
global $tfile,$tdir,$ij;$i=0;$j=count($tdir);
-
if (is_dir($dir)) {
-
if ($dh=opendir($dir)) {
-
while (($file=readdir($dh)) !== false) {
-
if (is_dir($dir.$file)) {
-
if (($file != ".") && ($file != "..")) {
-
$tdir[$j]=$dir.$file;$j++;
-
} } else { $tfile[$i]=$file;$i++;
-
} } closedir($dh); } } $ij=$i; }
-
-
// main
-
-
$_bg="";$_dw=$__fw=$__fwb=0;$_x=array();$_f=array();
-
-
if (!isset($argv[1])) { _o("Usage: ".$_SERVER['PHP_SELF']." <path/to/>");die; }
-
-
for ($tdir[0]=$argv[1],$k=$i=0,rddir($tdir[$i]);$i<count($tdir);$i++) {
-
$tdir[$i].="/";
-
for ($j=0,$m=count($tfile),_o("Found: ".$m." files @ ".$tdir[$i]."\nBuilding md5 hash…");$j<$m;$j++) {
-
if (($tfile[$j] != ".") && ($tfile[$j] != "..")) {
-
$h=md5(file_get_contents($tdir[$i].$tfile[$j]));
-
$_x[$k]=$h;
-
$_f[$k]=$tdir[$i].$tfile[$j];
-
$x=array_keys($_x,$h);
-
for ($o=0,$p=count($x);$o<$p;$o++) {
-
if ($x[$o] != $k) {
-
_o($_f[$o]." = ".$_f[$k]." (".$h." – ".$j.")");
-
}
-
}
-
$k++;
-
}
-
}
-
}
-
-
_dbg("",1);_o("Done!");
-
-
?>