Category Archives: Uncategorized

Oracle: guess the query of a view [SOLVED]

Some time ago, someone at my work created a new View in our Oracle database called AUTORESUZ (notice the capitals!) and I wanted to know how this view was defined, this is, the query that lies under it.

You can list all the views defined at your Oracle database by having a look at all_views table which stores the following information of each view:

SQL> DESC all_views;
 Name					   NULL?    TYPE
 ----------------------------------------- -------- ----------------------------
 OWNER					   NOT NULL VARCHAR2(30)
 VIEW_NAME				   NOT NULL VARCHAR2(30)
 TEXT_LENGTH					    NUMBER
 TEXT						    LONG
 TYPE_TEXT_LENGTH				    NUMBER
 TYPE_TEXT					    VARCHAR2(4000)
 OID_TEXT_LENGTH				    NUMBER
 OID_TEXT					    VARCHAR2(4000)
 VIEW_TYPE_OWNER				    VARCHAR2(30)
 VIEW_TYPE					    VARCHAR2(30)
 SUPERVIEW_NAME 				    VARCHAR2(30)

The query information is stored in “text” row. So, let’s retrieve the query that our AUTORESUZ has defined:

SQL> SELECT text FROM all_views WHERE view_name = 'AUTORESUZ';
 
TEXT
----------
SELECT a1.

OMFG! The query seems to be there, but it is truncated…

In order to view the full query, you must set long with a value greater that text’s length. Like this:

SQL> SELECT text_length FROM all_views WHERE view_name = 'AUTORESUZ';
 
TEXT_LENGTH
-----------
	369
 
SQL> SELECT text FROM all_views WHERE view_name = 'AUTORESUZ';
 
TEXT
----------
SELECT a1.
 
SQL> SET long 369
SQL> SELECT text FROM all_views WHERE view_name = 'AUTORESUZ';         
 
TEXT
--------------------------------------------------------------------------------
SELECT a1.rec_key AS arecord,
  REGEXP_REPLACE(a2.rec_data,'^\|a(.*)','\1') AS nipuz,
  REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(a1.rec_data,'^\|a(.*)\|6\(UZ.*','
\1'), '(.*)\|c(.*)','\1'), '(.*),\|d(.*)','\1') AS autoruz
 
 FROM var_fields2 a1,  var_fields2 a2
 WHERE a1.rec_key LIKE 'a%' AND a1.MARC_TAG='100' AND
  (a1.rec_key=a2.rec_key AND a2.MARC_TAG='090')

Joomla: know the section [SOLVED]

Lets suppose you are developing a joomla module and want to know the section in which you are.

The following code might help :)

<?php
function getSection($iId) {
    $database = &JFactory::getDBO();
    if(Jrequest::getCmd('view',0) == "section") {
        return JRequest::getInt('id');
    }
    elseif(Jrequest::getCmd('view',0) == "category") {
        $sql = "SELECT section FROM #__categories WHERE id = $iId ";
        $database->setQuery( $sql );
        $row=$database->loadResult();
        return $row;
    }
    elseif(Jrequest::getCmd('view',0) == "article") {
        $temp=explode(":",JRequest::getInt('id'));
        $sql = "SELECT sectionid FROM #__content WHERE id = ".$temp[0];
        $database->setQuery( $sql );
        $row=$database->loadResult();
        return $row;
    }
}
 
// use it like:
$sectionId=getSection(JRequest::getInt('id'));
?>

Python & Oracle [SOLVED] ImportError: libclntsh.so.11.1: wrong ELF class: ELFCLASS32

If you are getting a message like this:

>>> import cx_Oracle
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ImportError: libclntsh.so.11.1: wrong ELF class: ELFCLASS32

It means you are having issues with ELF (Executable and Linkable Format)

How to solve em?

First, locate the path to libclntsh.so.11.1 (usually in /usr):

[root@zaguan importaFHdesdeRoble]# find / -name "libclntsh.so.11.1"
/usr/lib/oracle/11.1/client64/lib/libclntsh.so.11.1
/usr/lib64/libclntsh.so.11.1

Note the presence of two files. Lets check wether they are for 32bits or 64bits:

[root@zaguan importaFHdesdeRoble]# file /usr/lib/oracle/11.1/client64/lib/libclntsh.so.11.1
/usr/lib/oracle/11.1/client64/lib/libclntsh.so.11.1: ELF 64-bit LSB shared object, AMD x86-64, version 1 (SYSV), not stripped
 
[root@zaguan importaFHdesdeRoble]# file /usr/lib64/libclntsh.so
/usr/lib64/libclntsh.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), not stripped

If your system is 64 bits (check it out with uname -a) you should be using the ELF 64-bit LSB shared object.

So, you can just:

mv /usr/lib64/libclntsh.so.11.1 /usr/lib64/libclntsh.so.11.1__32bits
cp /usr/lib/oracle/11.1/client64/lib/libclntsh.so.11.1 /usr/lib64/libclntsh.so.11.1

And now, you will be able to import Oracle library from python:

# python
Python 2.4.3 (#1, Apr 14 2011, 20:41:59)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cx_Oracle
>>>

Or, if you want to do it “the right way”. Put this in a script.sh file and alter

#!/bin/bash
PATH=$PATH:$HOME/bin
ORACLE_HOME=/usr/lib/oracle/11.1/client64
LD_LIBRARY_PATH=/usr/lib/oracle/11.1/client64/lib
export ORACLE_HOME
export LD_LIBRARY_PATH
export PATH
 
# ALTER HERE with the path to python and the file which has the python code to connect to Oracle
salida=`/usr/bin/python ./pythoncodefile.py`

Mysql SELECT DISTINCT y tildes en utf8 [RESUELTO]

La verdad es que las tildes siempre son una lata en programación y en consultas a bases de datos MySQL
.
Imagina que tienes una tabla con los siguientes valores

ID value
1 Óscar
2 Oscar

Antes de empezar a hacer queries a la BD, nos aseguraremos de que se tiene en cuenta el utf8:

mysql> set name 'utf8';

Observa lo que sucede si haces un select distinct a secas:

mysql> SELECT DISTINCT value from table;
+--------+
| value   |
+--------+
| Oscar   |
+--------+

Los campos de tipo textual (CHAR y VARCHAR por ejemplo) son case-insensitive y accent-insensitive. Esto es, tanto OSCAR como Óscar, Oscar y ÓSCAR son lo mismo para mysql.

Si queremos que nos distinga esto (que Óscar y Oscar sean distintos), tenemos la opción de usar el modificador MD5 o, más simple, el modificador BINARY

mysql> SELECT DISTINCT binary value from table;
+--------+
| value   |
+--------+
| Oscar   |
+--------+
| Óscar   |
+--------+

ENGLISH:
Distinct works depending on column type.
Varchar is case insensitive and accent agnostic while comparing,
Binary string (Binary) columns require byte-to-byte match.
Keyword BINARY in front of an expression, makes it a byte-to-byte
comparison.

Ver imágenes de imageshack (evitar ranitas) [solucionado]

Si no veis las imágenes de imageshack y aparece la dichosa ranita (cubito de hielo con una rana dentro):
rana imageshack

Se debe a que imageshack controla el valor del campo referer de las cabeceras (headers) http para no permitir el hotlinking desde algunos sitios web.

Podéis solucionarlo siguiendo estos pasos:

Eliminar ranitas de imageshack en FIREFOX

1. Herramientas > Complementos
2. Obtener complementos
3. Buscamos ‘RefControl’
4. Descargamos e instalamos el complemento. Se reiniciará Firefox
5. Herramientas > Opciones RefControl…
6. Añadir sitio. En sitio ponemos imageshack.us
7. En acción, ponemos ‘Bloquear – no enviar referer’
8. Aceptamos, y aceptamos de nuevo.

Eliminar ranitas de imageshack en CHROME

En el icono del escritorio de Google Chrome boton derecho -> Propiedades
En la linea Destino: “C:\Archivos de programa\Google\Chrome\Application\chrome.exe”
Al final del todo tenemos que añadir “–no-referrers” (importante añadir un espacio)
con lo cual la linea Destino quedaria asi:
“C:\Archivos de programa\Google\Chrome\Application\chrome.exe” “–no-referrers”

Eliminar ranitas de imageshack en OPERA

Menú—> Configuración —> Opciones —> Avanzado —> Redes —> Desactivar casilla de “enviar info de referencia”.

También podéis usar tinypic u otros servicios que sí admiten hotlinking para evitar problemas a otros usuarios.

(Via forocoches).

[SOLVED] An Unexpected HTTP Error occurred during the API request – wordpress 3

If you are getting this error in WordPress 3:
An Unexpected HTTP Error occurred during the API request

Edit your wp-includes/class-http.php

Search this:

$defaults = array(
			'method' => 'GET',
			'timeout' => apply_filters( 'http_request_timeout', 5),

And change it to:

$defaults = array(
			'method' => 'GET',
			'timeout' => apply_filters( 'http_request_timeout', 30),

Should work now ;)

If it does not:

Install Core control plugin
Head to it’s menu under Tools, Select the HTTP Access module, Save the page.
Head over to the new HTTP tab along the top of the page.

What transports is it using? Does it make a difference if you disable the currently active transport?

Usual transports are (ordered by priority of use):

PHP HTTP Extension	
cURL	
PHP Streams	
PHP fopen()	
PHP fsockopen()

Next to each transport you will find if they are Available or Not available.

If the cURL transport is the currently active one, Disable that. Should work now!
curl transport disabled wordpress core control

If it does not, refer to this post at wordpress.org

Eliminar tildes con python [SOLUCIONADO]

Es muy probable que si programas en python te encuentres, alguna vez, con una situación en la que debes eliminar las tildes de algún texto.

Esto se puede hacer fácilmente utilizando el módulo unicodedata.

He creado la funcion elimina_tildes tal que asi:

1
2
3
4
5
6
7
import unicodedata
def elimina_tildes(s):
   return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn'))
 
# que se puede usar asi:
>>> print elimina_tildes(u"córcholis")
corcholis

Espero que os resulte útil.

Más detalles en stackoverflow.com

SEO: las mejores herramientas gratis

Os he hablado en muchas ocasiones de SEARCH ENGINE OPTIMIZATION (SEO) y me gustaría destacar algunas de las herramientas seo gratuitas más útiles.

1. Herramienta google para palabras clave: https://adwords.google.es/select/KeywordToolExternal.
Utilice la Herramienta para palabras clave para obtener nuevas ideas sobre palabras clave. Seleccione una de las opciones siguientes para introducir unas palabras o frases descriptivas, o especifique la URL de su sitio web. Sugerencias para utilizar la Herramienta para palabras clave.

2. Una vez seleccionadas las palabras clave (y las long tails, si las hubiera) para las que deseamos posicionarnos podemos chequear la densidad de keywords usando esta herramienta (gratis): densidad de keywords.

3. Tampoco debéis algo de lo que ya os he hablado, la generación de sitemaps con herramientas gratuitas como gsitecrawler.

Espero que os resulte útil esta info.

Google analytics: how to export more than 500 entries of data report [SOLVED]

Currently, only up to 500 rows of Analytics table data can be exported at a time into CSV format. If you need to export larger data sets, like exporting all keywords that sent traffic to your site, you can export multiple times as long as each batch contains at maximum 500 rows.

If you have thousands of rows that require multiple exports, you can use the convenient workaround below to export all your rows in one go.

1. Go the report that contains the data you want to export.

2. Append the query parameter ‘limit’ to the url (to the end of URL!), and hit enter to reload the report. The limit parameter is needed prior to every report export.
For example:

https://www.google.com/analytics/reporting/top_content?id=14120873&pdr=20090101-20091231&cmp=average&trows=5000&gdfmt=nth_day#lts=1268387872421&limit=50000

3. Hit ‘Enter’ and visually confirm that the report now has the new parameter appended to it. While there won’t be any visible difference in user interface, exporting will now yield more rows.

4. Select the Export tab, and click ‘CSV’ (not the option that says ‘CSV for Excel’).
5. The exported data should contain all the rows from your Analytics table.

Via: Google Analytics FAQ’s

httpwatch: record http / https requests

httpwatch is an HTTP viewer and debugger that integrates with IE and Firefox to provide seamless HTTP and HTTPS monitoring without leaving the browser. This kind of software is usually known as sniffer.

httpwatch

Why do you need an HTTP Viewer or Sniffer?

All web applications make extensive use of the HTTP protocol (or HTTPS for secure sites). Even simple web pages require the use of multiple HTTP requests to download HTML, graphics and javascript. The ability to view the HTTP interaction between the browser and web site is crucial to these areas of web development:
* Troubleshooting
* Performance tuning
* Verifying the security of a site

How can HttpWatch help?

HttpWatch integrates with Internet Explorer and Firefox browsers to show you exactly what HTTP traffic is triggered when you access a web page. If you access a site that uses secure HTTPS connections, HttpWatch automatically displays the decrypted form of the network traffic.

httpwatch

Conventional network monitoring tools just display low level data captured from the network. In contrast, HttpWatch has been optimized for displaying HTTP traffic and allows you to quickly see the values of headers, cookies, query strings and more…

HttpWatch also supports non-interactive examination of HTTP data. When log files are saved, a complete record of the HTTP traffic is saved in a compact file. You can even examine log files that your customers and suppliers have recorded using the free Basic Edition.