Tuesday, July 31, 2012

Microsoft Word 2007: Automatic content table

Go to References tab > Content Table > insert content table.
 PD: you have to handle the styles to be able to generate automatic content table

Here is a video tutorial about that:
http://www.youtube.com/watch?v=8sMzWVGiBQ4

Monday, July 30, 2012

Python: split string by given separator

use .split() method:


myString = "1-2-3-4-5-6-7-8"
mySplittedStringArray = myString.split('-')
print mySplittedStringArray # ['1', '2', '3', '4', '5', '6', '7', '8']


Resource:
http://www.tutorialspoint.com/python/string_split.htm
http://jolthgs.wordpress.com/2012/02/12/metodos-join-y-split-en-python/

MSSQL 2008 : Cannot open database requested by the login. The login failed

I got this error:

sqlalchemy.exc.ProgrammingError: (ProgrammingError) ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open database "ICBF_GDOC_TESTS" requested by the login. The login failed. (4060) (SQLDriverConnect); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open database "ICBF_GDOC_TESTS" requested by the login. The login failed. (4060)') None None.

In my case, the issue was that the database name was wrong , that was all :/

Wednesday, July 25, 2012

PHP: decode HTML special Chars


<?php
$str = "<p>this -&gt; &quot;</p>\n";


echo htmlspecialchars_decode($str); // <p>this -> "</p>


// note that here the quotes aren't converted
echo htmlspecialchars_decode($str, ENT_NOQUOTES); // <p>this -> &quot;</p>
?>


Reference:
http://php.net/manual/en/function.htmlspecialchars-decode.php

Tuesday, July 24, 2012

Python: Pass a method as a parameter


def method1():
    return 'hello world'


def method2(methodToRun):
    result = methodToRun()
    return result


method2(method1)


Reference:
http://stackoverflow.com/questions/706721/how-do-i-pass-a-method-as-a-parameter-in-python

Python: weird SyntaxError: invalid syntax

The code was apparently normal:

def myFunctionTestOK():
   return "hi there ok"

def myFunctionTestFail():
   return "hi there fail"

and the error was:

Traceback (most recent call last):  
  File "C:\mytest.py", line 5
    return "hi there fail"
                          ^
SyntaxError: invalid syntax

I was using the Pydev Eclipse Plugin. After a lot of time trying to identify the error I decide to open the file using Notepad ++ http://notepad-plus-plus.org/

clicking in the 'show all characters' button:


I found out that there was missing a (LF) just after the line return "hi there fail":




so I put the cursor just after "hi there fail" and pressed enter:




And finally deleted the line with the single (CR):




Now everything works smoothly.

Python: UnicodeEncodeError: 'ascii' codec can't encode character in position : ordinal not in range(128)

If you get this error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

Use the .encode() method instead of using str():


a = u'bats\u00E0'
print a # batsà
print str(a) # UnicodeEncodeError: 'ascii' codec can't encode ...
print a.encode('utf-8') # batsà


Reference:
http://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20

Monday, July 23, 2012

Python: try except generic exception

   try:
       myInt = int ("100000A") # throws exception
       #myInt = int ("100000") # doesn't throw exception
       print "myInt:" , myInt
   except Exception, e:
       print "My Error: " , str(e)

Resource:
http://www.daniweb.com/software-development/python/threads/169976/python-try...except-printing-exception

Linux: change another's user password from root

To change the password for the user 'roger' (only you are logged in as root)...

passwd roger
Enter existing password (can be either roger's password or root's password)
Enter new password
Enter new password again (to validate)


Resource:
http://www.ahinc.com/linux101/users.htm

Simple WYSIWYG HTML Editor Sample

the file structure of the project is:

./project
./project/myWYSIWYGTest.html --- here is the source code of the example
./project/ckeditor --source code of the ckeditor lib, download where http://ckeditor.com/download

the code of the myWYSIWYGTest html page is:

<html>
    <head>
        <script type="text/javascript" src="./ckeditor/ckeditor.js">
        </script>
    </head>
    <body>
        <textarea class="ckeditor" name="editor1"></textarea>
    </body>
</html>

Reference:
http://nightly.ckeditor.com/7582/_samples/replacebyclass.html

Linux: cp command


cp -r /home/hope/files/* /home/hope/backup

Copies all the files, directories, and subdirectories in the files directory into the backup directory.

Example:

cp -r /home/john/Desktop/shared_folder/* /media/DISK/disk1


Reference:
http://www.computerhope.com/unix/ucp.htm

Thursday, July 19, 2012

SQL Server: update column with sequential value

I have a database table that has a lot of data already in the table and I need to add a new column to this table to include a new sequential number.  In addition to adding the column I also need to populate the existing records with an incremental counter.


So I can do this by doing the following:


// adds new columns
ALTER TABLE [dbo].[d_expedientes] ADD [type_expediente] [int] default 0;


// set the value of the new column to 1,2,3,4,5,...

DECLARE @type_expediente INT 
SET @type_expediente = 0 
UPDATE d_expedientes
SET @type_expediente = type_expediente = @type_expediente + 1 


Reference:
http://www.mssqltips.com/sqlservertip/1467/populate-a-sql-server-column-with-a-sequential-number-not-using-an-identity/

Wednesday, July 18, 2012

Oracle: condition CASE in select sentence


SELECT 
TRANSACCION.num_tarjeta
,TRANSACCION.fecha_hora_tran
, TRANSACCION.monto_1 as monto
,  CASE 
WHEN TRANSACCION.ciudad != ' ' 
THEN TRANSACCION.ciudad 
ELSE 'No Disponible' 
END AS ciudad 
, CLASE_TRANSA.DESCRIPCION AS MEDIO
FROM 
TRANSACCION 
left outer join CIUDADES 
ON TRANSACCION.ciudad = CIUDADES.cod_ciud  
left outer join CLASE_TRANSA
ON TRANSACCION.clase = CLASE_TRANSA.CODIGO


Reference:
http://www.adp-gmbh.ch/ora/sql/case_when.html

Saturday, July 14, 2012

Linux: find a file

find <dir_where_you_want_to_search> -name <file_nameyou_want_to_search>:


find /home/john -name 'httpd-xampp.conf'


Note: In ubuntu use sudo at the beginning :
sudo find /home/john -name 'httpd-xampp.conf'


Resource:
http://www.codecoffee.com/tipsforlinux/articles/21.html

Linux: open a .tar.gz file

PHP: get keys from array

Use array_keys() method:

$array = array("color" => "blue", "size"  => "small");
print_r(array_keys($array)); /* prints the following:
Array
(
    [0] => color
    [1] => size
)*/

Reference:
http://php.net/manual/en/function.array-keys.php


HTML: Simple Table

Using <Table> tag:

<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>


Result:


row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2


Resource:
http://www.w3schools.com/html/html_tables.asp

Oracle: filter date type column in where sql clause

Use to_date() method:


where (DPFOLIO.BUDGET_PROD.MONTH > to_date('12/31/2005 12:00:00 AM','MM/DD/YYYY HH12:MI:SS AM'))

Reference:

http://en.allexperts.com/q/Oracle-1451/oracle-date-filtering-cause.htm

Friday, July 13, 2012

PHP: split string by multiple delimiters


Use preg_split() method:

$pattern = '/[;,]/'; //regex
$string = "something here ; and there, oh,that's all!";
$myArray = preg_split( $pattern, $string );


Reference:
http://stackoverflow.com/questions/1452777/how-to-split-a-string-by-multiple-delimiters-in-php

PHP: get string length

$str = 'abcdef';
echo strlen($str); // 6


Resource:
http://php.net/manual/es/function.strlen.php

PHP: Capture var_dump into string


Using output buffering:

<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>


Resource:
http://stackoverflow.com/questions/139474/how-can-i-capture-the-result-of-var-dump-to-a-string

Oracle: limit results like Mysql limit clause

Compare against ROWNUM:

select * from >myTable where ROWNUM <= 5;


Reference:
http://stackoverflow.com/questions/470542/how-do-i-limit-the-number-of-rows-returned-by-an-oracle-query-after-ordering

Thursday, July 12, 2012

PHP: substring

Use substr method:

$myString = "0123456789"
// substr( string_wanna_substring , initial position(0-index),quantity-of-digits-wanna-take);             
// the var is $myString, the init position is 3 (0-index) so it beings from number 3, take 3 chars beginning with 3 so the //final result is 345
$mySubString = substr( $myString ,3,3); // 345


Reference:
http://php.net/manual/es/function.substr.php

PHP: get the type of a variable

use gettype method:


$var1 = "Hello";
gettype($var1); // String


Reference:
http://php.net/manual/es/function.gettype.php

Tuesday, July 10, 2012

PHP: static method

class Foo {
    public static function aStaticMethod() {
        // ...
    }
}
Foo::aStaticMethod();

Resource:
http://php.net/manual/es/language.oop5.static.php

PHP: find key into array


Use the in_array() method:


$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Got Irix";
}
if (in_array("mac", $os)) {
    echo "Got mac";
}

Resource:
http://php.net/manual/en/function.in-array.php

PHP: simple array

$array = array(1, 2, 3, 4, 5);

Resource:
http://php.net/manual/es/language.types.array.php

Monday, July 9, 2012

Eclipse: Subversive compare editor doesn't work with php files


I also had the problem mentioned above:

Whenever I attempt to compare my working file with the one in the repository, I get a blank screen or it hangs with the message "Initializing...". It doesn't work regardless of what perspective I'm in or if I compare with the base revision or the latest from the repository.

I'm using eclipse 3.6.1 with subversive 0.7.9

The Solution was update the pdt eclipse plugin:

There is a bug mentioned here https://bugs.eclipse.org/bugs/show_bug.cgi?id=326194 that has a workaround. Apparently it will be fixed in the next release, but you can add the update site http://download.eclipse.org/tools/pdt/updates/2.2/milestones to your eclipse installation and it should fix your compare editor.

Resource:
http://stackoverflow.com/questions/5060114/subclipse-problem-comparing-php-files

Wednesday, July 4, 2012

Symfony2 and EXTJS4.1: Load the ExtJS client into Symfony2

I have a JavaScript Client with the following file/folder structure:

./client
./client/index.html --- main html file in the ExtJS architecture where are loader the libs and the resources
./client/app --- folder with the extjs architecture
./client/app/data
./client/app/model
./client/app/store
./client/app/view
./client/app/app.js
./client/libs  --- folder with the external libraries
./client/libs/ext-4.1.0-gpl
./client/libs/jquery-1.6.4
./client/resources --- folder with my resources like, css and images
./client/resources/css
./client/resources/images

After installing Symfony2, copy your JavaScript Client (ie. client) inside the Symfony/web/ so you can access in your browser the Symfony/web/client/index.html without bothering with the assets stuff. The assets are useful for your PHP server business logic, not for your full HTML/JavaScript client.


PHPMailer5.1: ERROR: Failed to connect to server: Unable to find the socket transport "ssl"

If you get this error:

"SMTP -> ERROR: Failed to connect to server: Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP? (32) 
SMTP Error: Could not connect to SMTP host. Mailer Error: SMTP Error: Could not connect to SMTP host."


You have to add or enable the following line in the php.ini file:
extension=php_openssl.dll


Resource:
http://www.devcha.com/2010/01/php-fsockopen-unable-to-connect-ssl.html

MSSQL 2008: Make and Restore a Database BackUp

Here are the steps, in spanish ;)

1) Ingresar al menú de MS SQL Server, opción Enterprise Manager
2) Ingresar al servidor origen y seleccionar la base de datos a copiar
3) Presionar clic derecho del ratón sobre la base de datos, en la opción "All Tasks" seleccionar "Backup Database"
4) Se presentará una ventana con titulo SQL Server Backup
5) Selecciona en el área de "Backup" la opción de "Database Complete"
6) En el área de "Destination" presionar el botón de "Add" y se presentará una ventana con el titulo de "Select Backup Destination"
7) Seleccionar "Backup Device", y en la lista de opciones seleccionar la opción de "New backup device" y presionar el botón de "OK", se presentará una ventana con titulo "Backup Device Properties", ingresas el nombre y seleccionas el directorio donde se almacenará en archivo (el nombre se coloca automáticamente)
8) Después regresas a la primera ventana que se presento (SQL Server Backup) y presionar el botón de "OK"
9) Copias ese archivo al servidor destino,
10) Seleccionar la opción MS SQL Server - Enterprise Manager
11) Presionar clic derecho del ratón sobre la base de datos, en la opción "All Tasks" seleccionar "Restore Database"
12) En la opción "General", seleccionar la base de datos a restaurar en el control "Restore as database", esta opción esta por defecto
13) En el área "Restore" de la opción "General", seleccionar la opción "From Device", y seleccionar el archivo donde se realizo la copia de seguridad del servidor origen
14) Seleccionar la opción "Options",
15) Por defecto se crean las rutas de la base de datos origen, para modificarlas es necesario seleccionar la opción "Force restore ver existing database"
16) Presionar el botón de "OK"

Resource:
http://www.todoexpertos.com/categorias/tecnologia-e-internet/bases-de-datos/sql-server/respuestas/397691/copiar-base-de-datos

Eclipse Subversive Plugin : Checkout operation for '...' failed. Java heap space

The problem is caused by a bug in the SVNKit connector, so the solution is to use the JavaHL connector:

1. in eclipse go to Help –> Install New Software…
2. Work with: –> choose the community.polarion.com update site
3. expand Subversive SVN Connectors
4. choose the JavaHL version corresponding with your version of subversion
5. click Next, and then follow the instructions to complete installation
6. Window –> Preferences –> expand "Team" –> select "SVN" –> select the "SVN Connector" tab –> change the SVN Connector to JavaHL –> OK

Resource: