Mostrando entradas con la etiqueta codi. Mostrar todas las entradas
Mostrando entradas con la etiqueta codi. Mostrar todas las entradas

20100124

How to get a contrasting font color for a given background ?

This is a sample code to give a font color with a good contrast for a given background color.

That php code snipped could be useful in case you give your users the option to set a custom background but not the font color (to avoid too many options) and you want that your text are always visible.

It simply returns a font color white or black depending on the background, but you can modify the function get_contrast if you want something more sophisticated.

The main function is:


function get_font_color($color)
{
$ar=html2rgb($color);
return get_contrast($ar[0], $ar[1], $ar[2]);
}


Supporting functions:

function get_contrast ($r, $g, $b)
{// returns white or black depending on the background
// in red green and blue
$a = 1 - ( 0.299*$r + 0.587*$g + 0.114*$b)/255;
if ($a<0.5)
{
return '#000';
}
else
{
return '#fff';
}
}

function html2rgb($color)
{// gets an array of R,G,B from an hexadecimal
// color in html format
if ($color[0] == '#') $color = substr($color, 1);

if (strlen($color) == 6)
{
list($r, $g, $b) = array($color[0].$color[1],
$color[2].$color[3],
$color[4].$color[5]);
}
elseif (strlen($color) == 3)
{
list($r, $g, $b) = array($color[0].$color[0],
$color[1].$color[1],
$color[2].$color[2]);
}
else
{
return false;
}
$r = hexdec($r); $g = hexdec($g); $b = hexdec($b);

return array($r, $g, $b);
}


Unit testing:

$i=0;
while ($i<1600000)
{
$rgb='#'.strtoupper(str_pad(dechex($i), 6, '0', STR_PAD_LEFT));
echo '<div style="background-color:'.$rgb.'; color:'.get_font_color($rgb).'">'.$rgb.'</div>';
$i++;
}


Thanks to this web entries:
Determine font color based on background color
Convert RGB from an HTML Hex Color

20091210

Tutorial de memcache

Memcache es una extensió de PHP que interactua amb memcached, que a la seva vegada es un daemon de cache en memoria, molt simple, que enmagatzema parells key=>value on value pot ser qualsevol cosa serialitzable amb PHP.

Per instal.lar amb Ubuntu farem el següent:
apt-get install memcached
apt-get install php5-memcache

Reiniciar apache:
/etc/init.d/apache2 restart

Es pot fer un php amb un phpinfo(); per veure si hi ha un apartat memcache

Per veure si esta funcionant el memcached (el daemon):
netstat -tap | grep memcached

Per modificar els parametres de memoria etc. editar /etc/memcached.conf

per exemple, per configurar 300Mbs de memoria disponible per variables a memcached modificarem el flag -m del fitxer de configuració:
-m 300

Reiniciar memcached
/etc/init.d/memcached restart

Per consultar les estadistiques en temps real del memcached:

telnet localhost 11211
>stats

Exemple de output:


Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
stats
STAT pid 4666
STAT uptime 153661
STAT time 1260523656
STAT version 1.2.2
STAT pointer_size 64
STAT rusage_user 4.850000
STAT rusage_system 15.100000
STAT curr_items 16001
STAT total_items 57971
STAT bytes 282532500
STAT curr_connections 1
STAT total_connections 120074
STAT connection_structures 32
STAT cmd_get 120016
STAT cmd_set 57971
STAT get_hits 66178
STAT get_misses 53838
STAT evictions 0
STAT bytes_read 1108602586
STAT bytes_written 1317300490
STAT limit_maxbytes 314572800
STAT threads 1
END


Ara només cal modificar el nostre codi per enmagatzemar rows de la base de dades, durant un cert temps, en aquests exemples, creem una clau $action.'/'.$param1.'/'.$param2 o sigui per exemple 'category/23/1' i el valor serà el resultat de la base de dades (una array de rows).

La instrucció set enmagatzema a memcached:

$mc->set($action.'/'.$param1.'/'.$param2, $rows, 1, 3600);

El primer parametre es la clau, el segon el valor, el tercer si volem comprimir el contingut o no i el quart el temps en segons que tindrem el valor al memcache (1 hora)

La següent vegada que haguem de fer la consulta farem el següent:

$rows=$mc->get($action.'/'.$param1.'/'.$param2);

Si ens retorna null, es que no hi es, pero durant una hora, no ens caldrà repetir la consulta.

Exemples de codi:


function get_last($num=16, $offset=1, $flag = 1)
{
$sql = "SELECT v.*
, p.title portal_title
, p.url portal_url
, p.id portal_id
FROM ep_videos v, ep_portals p
WHERE v.portal_id = p.id
AND v.status = 'O'
ORDER BY v.added DESC
LIMIT ".(($offset-1)*$num).", ".$num;

$action='home';
$param1='1';
$param2=$offset;
$mc=new Memcache;
$cr=$mc->connect('localhost', 11211);
if ($cr)
{// tenim memcached
$rows=$mc->get($action.'/'.$param1.'/'.$param2);
if ($rows==null)
{// no el tenim a cache
$rows=parent::get_data($sql);
$mc->set($action.'/'.$param1.'/'.$param2, $rows, 1, 3600);
}
}
else
{// no tenim memcached
$rows=parent::get_data($sql);
}

return $rows;
}

function get_last_in_category($id, $num=16, $offset=1)
{
$sql = "SELECT v.*
, p.title portal_title
, p.url portal_url
, p.id portal_id
FROM ep_portals p
, ep_videos v
, ep_categories_videos cv
WHERE cv.video_id = v.id
AND cv.category_id = ".$id."
AND v.status='O'
AND v.portal_id = p.id
ORDER BY v.added DESC
LIMIT ".(($offset-1)*$num).", ".$num;

$action='category';
$param1=$id;
$param2=$offset;
$mc=new Memcache;
$cr=$mc->connect('localhost', 11211);
if ($cr)
{// tenim memcached
$rows=$mc->get($action.'/'.$param1.'/'.$param2);
if ($rows==null)
{// no el tenim a cache
$rows=parent::get_data($sql);
$mc->set($action.'/'.$param1.'/'.$param2, $rows, 1, 3600);
}
}
else
{// no tenim memcached
$rows=parent::get_data($sql);
}

return $rows;

//return parent::get_data($sql);
}

function get_last_in_tag($id, $num=16, $offset=1)
{
$sql = "SELECT v.*
, p.title portal_title
, p.url portal_url
, p.id portal_id
FROM ep_portals p
, ep_videos v
, ep_tags_videos cv
WHERE cv.video_id = v.id
AND cv.tag_id = ".$id."
AND v.status='O'
AND v.portal_id=p.id
ORDER BY v.added DESC
LIMIT ".(($offset-1)*$num).", ".$num;

$action='tag';
$param1=$id;
$param2=$offset;
$mc=new Memcache;
$cr=$mc->connect('localhost', 11211);
if ($cr)
{// tenim memcached
$rows=$mc->get($action.'/'.$param1.'/'.$param2);
if ($rows==null)
{// no el tenim a cache
$rows=parent::get_data($sql);
$mc->set($action.'/'.$param1.'/'.$param2, $rows, 1, 3600);
}
}
else
{// no tenim memcached
$rows=parent::get_data($sql);
}

return $rows;

//return parent::get_data($sql);
}

20091015

Create the first bracket of a tournament


Bueno tetes, no tinc molt de temps però si algun cop us heu trobat en el cas de com crear un bracket per un torneig, no es del tot trivial.

Us deixo un troç de codi que el seu output es una array on cada element s'ha d'emparellar amb el següent per construir un bracket inicial d'un torneig ben balancejadet (com els de dragonball, vamos)

Evidentment $inicial es el primer jugador i $final es l'ultim, segur que no funciona si no son números de jugadors correctes, com 8,16,32,64... etc.


$inicial=1;
$final=32;
$num_jugadores=$final-($inicial-1);
$emparejamientos=array(1,4,2,3);
$num_jugadores_tmp=4;
while ($num_jugadores_tmp!=$num_jugadores)
{// desdoblabiento
$num_jugadores_tmp=$num_jugadores_tmp*2;
$emparejamientos_tmp=array();
foreach($emparejamientos as $emparejamiento)
{
array_push($emparejamientos_tmp, $emparejamiento);
array_push($emparejamientos_tmp
, ($num_jugadores_tmp+1)-$emparejamiento);
}
$emparejamientos=$emparejamientos_tmp;
}
print_r($emparejamientos);


Resultat per 16 jugadors:

Array ( [0] => 1 [1] => 16 [2] => 8 [3] => 9 [4] => 4
[5] => 13 [6] => 5 [7] => 12 [8] => 2 [9] => 15
[10] => 7 [11] => 10 [12] => 3 [13] => 14 [14] => 6
[15] => 11 )


I després de tractar-ho i simular resultats:

Ronda 1
1: 1 vs. 16 winner=1
2: 8 vs. 9 winner=9
3: 4 vs. 13 winner=13
4: 5 vs. 12 winner=12
5: 2 vs. 15 winner=2
6: 7 vs. 10 winner=7
7: 3 vs. 14 winner=14
8: 6 vs. 11 winner=6