|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Equipped with an Intel Pentium Duo Processor, 4GB system memory, a 15.5" high definition LCD display and the latest wireless technology, this Sony VAIO handles everything from rich digital entertainment to your day to day tasks. It features a sophisticated new design and all new Windows 7 Home Premium for a smoother and faster user experience.
FEATURES:
Please Note: This product contains both English and French operating instructions and system software. In this context GB or Gigabytes refers to 1 Billion Bytes. The actual formatted capacity will be less. Folks, I know I've been quiet here lately - in part because I was writing for Suite101, in part because I moved to Canada and back, and who knows - maybe I'll move to Canada again some day... anyway, I really feel like writing a bit about my personal feelings about the world around me for a change. So if you subscribe to my feeds or check my front page from time to time, you will see:
You may be asking yourself why I don't set up a separate blog, and the reason is: because that's who I am - a technical person who also has thoughts of things other than programming that I'd like to share. Please be patient as I will try to write in both Portuguese and English, and I promise I'll do my best not to bore you to death. Cheers, Aviso: Este post apresenta meu ponto de vista sobre um dos aspectos do Cristianismo. É recomendado que se tenha a mente aberta ou então que nem prossiga na leitura. Não sou contra Cristo - pelo contrário, simpatizo com diversas religiões, Cristãs e não Cristãs. Apenas não concordo 100% com o que está escrito na bíblia. Introdução Um tempo atrás comecei a assistir à série "Dexter", que é sobre de um inspetor de criminalística que no seu tempo livre gosta de matar serial killers que escapam da justiça. Isso me fez pensar sobre toda a questão de bem versus mal, nossa história desde tempos imemoriais e a situação do cotidiano. Minha conclusão é a seguinte: Deus em sua infinita sabedoria nos deu a matemática. E é na matemática - mais especificamente na multiplicação - que podemos usar nossa lógica (também nos dada por Deus) e chegar à conclusão que "dar a outra face" pode não ter sido exatamente o que Jesus quis dizer quando esteve aqui e foi assassinado por nós. Passamos por diversos terrores através dos tempos - do império romano, da horda de mongóis de Gengis Kahn, passando pela inquisição e mais recentemente o holocausto - a maioria (?? talvez todas) das vezes por motivos de poder e controle das massas. Uma que me chamou a atenção foi da igreja católica e a inquisição que matou tantas e tantas pessoas das formas mais horrendas. Quando penso nisso, lembro daquela parte da biblia onde diz que Jesus "deu a outra face" e nos ensina a fazer o mesmo. Por mais que tente, isso é algo que eu simplesmente não consigo engolir. E quando coloquei todos esses pedaços juntos, me ocorreu que a vida e a matemática são muito parecidas em um determinado aspecto. Das Leis da Multiplicação Vejamos: considere que o bem e boas ações sejam equivalentes a números positivos (são atos positivos, certo?), e que o mal e atos violentos sejam equivalentes a números negativos. Cenário 1: Conclusão: Um ato positivo, quando aplicado a outro ato positivo resulta em coisas positivas. Cenário 2: Conclusão: Um ato/número positivo quando multiplicado por um ato/número negativo é sobrepujado e o resultado é negativo. O negativo SEMPRE vence. Cenário 3: Conclusão: Positivo quando aplicado a um Negativo resulta em um negativo ainda maior. Cenário 4: Conclusão: Um número negativo quando multiplicado por outro número negativo resulta em um número positivo! Nesse post usei o mesmo exemplo para todos os cenários, mas posso pensar em muitos mais que vejo no dia a dia. Até mesmo a censura que por muito tempo foi vista como algo negativo está tendo um papel de auxílio à negatividade. Elaborarei mais sobre isso em outro post. Das Autoridades Bandidas Dependemos das autoridades para nossa proteção. Concordo que não podemos sair por aí matando tudo quando é gente que nos parece ser bandido. Afinal, podemos estar errados e assim sendo geraríamos um resultado negativo. Não, não podemos nos arriscar a isso. As autoridades têm como obrigação nos proteger tanto nas ruas contra ladrões, estupradores, etc., quanto nos tribunais contra estelionatários e criminosos de colarinho branco. No entanto, alguns bandidos agem como lobos em pele de cordeiro e se infiltram na polícia ou viram advogados de defesa mesmo sabendo que seus clientes são culpados. Estes entes negativos podem ser enquadrados em uma categoria ainda pior de negatividade. Eles usam seu status de autoridade e potencializam ainda mais a negatividade do mundo. Conclusão Se todo o mau fosse erradicado do planeta da forma que fosse, o resultado seria positivo. A idéia de que devemos dar a outra face e perdoar me soa demais como estratégia de uma entidade dominadora (encaremos - o mau domina nosso mundo hoje) para que seus dominados não se revoltem. Duvido muito que Jesus tenha nos mandado dar a outra face. Mandou-nos amarmos uns aos outros, mas fica difícil amar o bandido que violentou uma menina na frente do namorado e depois os matou... Fica ainda mais difícil amar o advogado ou juíz que não prendeu o bandido por que ele não foi pego em flagrante. Pessoal, Até hoje meu blog tem sido principalmente em inglês e voltado ao público técnico. Como tem acontecido muita coisa não técnica ultimamente, resolvi também compartilhar isso com vocês. Prometo tentar não matá-los de tédio e acho que muitos vão se identificar com o que estarei escrevendo. Um abraço a todos Vinny Hey folks! I'd like to announce that I've debuted on suite101.com. My first article there was how to optimize your job hunting using RSS feeds. In this article, I provide an explanation of Ajax with a historical introduction. If you are eager to start seeing the code, please scroll down.
What’s Ajax?
Ajax stands for Asynchronous Javascript And XML. It’s a way to call back-end scripts asynchronously – that is, without impacting user experience/flow. Basically, you don't even see the cursor become an hourglass or whatever other "waiting/processing" icon your system uses. It's not a language, but a technique. As for back-end scripts, you can use whatever you feel more comfortable with: PHP, Perl, Java, JSP, Shell, C, etc. The way to choose which technology to use as back-end is not outside the scope of this article.
Historical approach for calling back-end apps
Throughout web-development history, the very first way used to achieve back-end processing followed by front-end display was to create a form and set the back-end script as the action to that form. Upon submission, the form fields would be sent to the back-end script as a series of special environment variables, which would then be handled by the programmed logic. The back-end output would be displayed on the screen (either the same page/frame or a different page/frame, depending on the target attribute of the form). The catch 22 of this approach is that if you want to present another form after processing, that form must be produced by the back-end script, which leads to maintenance mayhem – to add or remove a field, you have to do so in both the original HTML and in the HTML of the back-end script. I recently decided to rewrite an application that I created for an English school where I used to work, and this time I want to do it right. I chose to write it in PHP with Object Orientation in mind, and use PDO+MySQL for the DAO portion. The reason for using PDO is that it's the closest thing to the DBI that I found for PHP - and the reason for PHP is that it's just plain simpler than using pure Perl, and I don't have the time to learn Catalyst or some other Perl Web framework. Anyway, here's what I'm doing for the PDO portion. First I created a
<?php
class Db{
public $dbh = null;
public function Db($db_type,$db_host,$db_user,
$db_pass,$db_base,$tbl_prefix){
if ($db_type == 'mysql') { // in case I want to add oracle in the future
$mysql_DSN = "mysql:host=".$db_host.";dbname=".$this->db_base;
try {
$this->dbh = new PDO($mysql_DSN, $db_user, $db_pass,
array(PDO::ATTR_PERSISTENT => true, PDO::ERRMODE_WARNING => true,
PDO::ATTR_ERRMODE => true));
}
catch(PDOException $e){
$rc[msg] = $e->getMessage();
die($rc[msg] . " " . __LINE__);
}
return $this->dbh;
}
}
}
?>
Secondly, I created the DAO classes which extend the DB. They are responsible for
<?php
class StudentsDao extends Db {
public $sth = array();
// Constructor
public function StudentsDao($db_type=NULL,$db_host=NULL,$db_user=NULL,
$db_pass=NULL,$db_base=NULL,$tbl_prefix=NULL) { // These params are to be passed to Db class
// Connect to DB
$this->Db($db_type,$db_host,$db_user,
$db_pass,$db_base,$tbl_prefix);
// Prepares queries
$this->sth = $this->prepare($tbl_prefix); // Look at prepare() further down
} // end of function StudentsDao
// Function that prepares queries
public function prepare() {
$sth = null; // will hold our temporary array
// get all students
$string = sprintf('select * from %s.%sstudents where id = ?',DB_BASE,TBL_PREFIX); // I have these constants defined in the main page
$sth['getStudentById'] = $this->dbh->prepare($string);
// update Student by Id
$string = sprintf('update %s.%sstudents
set field1 = ?, field2 = ?, field3 = ?
where id = ?',DB_BASE,TBL_PREFIX); // Note that this table has 3 control fields (id, sys_creation_date, and sys_update_date) prior to field1, field2, and field3 - I don't want them to be touched
$sth['updStudentById'] = $this->dbh->prepare($string);
return $sth;
} // end of prepare()
// Here we have the handlers for the queries prepared above.
// Fetches all students
public function getStudentById($id) {
$s = $this->sth['getStudents'];
$s->execute(array($id)) || die(print_r($s->errorInfo,1));
$result = $s->fetchAll(PDO::FETCH_ASSOC);
if (sizeof($result) == 0) {
// no data found
$out[err_cd] = 1;
}
else {
// data was found
$out[err_cd] = 0;
$out[data] = $result;
}
return $out;
}
// Updates student by Id - this is a tricky one
public function updateStudentById($data,$id){ // $data can have data regarding one or more fields
// Populate current fields
$fields = $this->getStudentById($id); // get current values
// Remove unwanted fields
$fields = array_slice($fields[data][0],3); // remove the 3 initial control fields
// Replace with new fields
foreach($data as $k=>$v){
$fields[strtolower($k)] = $v;
}
$fields['id'] = $id;
$s = $this->sth['updStudentById'];
$s->execute(array_values($fields)) || die(print_r($s->errorInfo,1));
$count = $s->rowCount();
if ($count == 1) {
$out[err_cd] = 0;
}
else {
$out[err_cd] = -1;
}
$out[err_msg] = $this->status[$out[err_cd]];
return $out;
}
?>
In the example above, you will probably frown on the fact that I'm calling I wanted to be able to pass the function an associative array containing only the fields I want to update - be it only My original idea was to basically, to emulate something like this:
That would set Here's the question part: The technique shown in the example will basically pull all values from the record and populate them in the Here's a quickie for you Ajax coders who need a function to parse your form fields into a URL query string. It handles input fields (text, hidden, whatever), radio and checkbox elements, and single/multiple select menus. Just make sure that all your form fields have IDs.
function build_post_string(frm) {
var poststr;
var poststr_array = [];
if (!frm.id) {
// assume it's a string. get the form object
frm = document.getElementById(frm);
}
for (i=0;i<frm.elements.length;i++){
var elem = frm.elements[i];
if (!elem.id) {
// skip any fields that don't have IDs
continue;
}
if (elem.type == 'radio' || elem.type == 'checkbox') {
// only grab radio buttons and checkboxes that are checked
if (!elem.checked) {
continue;
}
}
// get select values
if (elem.nodeName.match(/SELECT/i) && elem.multiple) {
//var sel = elem;
var sel_array = new Array();
for (var o=0;o<elem.options.length;o++) {
if (elem.options[o].selected) {
sel_array[sel_array.length] = elem.id+"="+elem.options[o].value;
}
}
var sel_str = sel_array.join('&');
// build key/value pairs for SELECTs
poststr_array[poststr_array.length] = sel_str;
}
else if (elem.nodeName.match(/SELECT/i)) {
poststr_array[poststr_array.length] = elem.id+'='+elem.options[elem.selectedIndex].value;
}
else {
// build key/value pairs for everything else
poststr_array[poststr_array.length] = elem.id+"="+elem.value;
}
}
// build poststr
poststr = poststr_array.join("&");
return poststr;
}
A couple of weeks ago I finally got a new laptop at work - which meant of course that I had to reinstall everything. Although we use Windows XP, there's one app that I have to run through Linux. The solution was Sun's VirtualBox running Ubuntu 9.04. When I tried to run the app, I realized that I still needed to install DBI and DBD::Oracle - which brings me to this article. Nothing better than a reinstall to generate article material DBD::Oracle is usually a pain to install if you haven't already done it a gazillion times. After that, it's just an annoying itch. In this article I'll cover installing DBD::Oracle using Oracle Instant Client, Ubuntu 9.04, and Perl 5.10. Since we're using the Instant Client, you'll need some Oracle DB you can connect to in order to do the testing. You can choose to skip testing altogether, but you might be into a surprise later. Continue reading... |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Copyright © 2010 use strict ;#) - All Rights Reserved |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||