Encriptacion de datos en PHP

En PHP existen varias funciones para la encriptacion de datos. Estas funciones son utiles para encriptar ciertas informaciones importantes tales como contrasenas. Entre allas estan las funciones crypt(), crc32(), md5() y sha1. Algunas son mas seguras que otras, en los ejemplos las coloco segun su nivel de seguridad:
 El siguiente es un ejemplo de como usar algunos:


<h2> Encriptaci&otilde;n de datos en PHP </h2>

<?php 
$dato = '123456';

$contrasena_crypt = crypt($dato);
$contrasena_crc32 = crc32($dato);
$contrasena_md5 = md5($dato);
$contrasena_sha1 = sha1($dato);

echo '<strong>crypt </strong>'.$contrasena_crypt.'<br />';
echo '<strong>crc32 </strong>'.$contrasena_crc32.'<br />';
echo '<strong>md5 </strong> '.$contrasena_md5.'<br />';
echo '<strong>sha1 </strong>'.$contrasena_sha1.'<br />';
?>


Si los datos encryptados estan compuestos de palabras y/o numeros consecutivos es muy probable que alguien pueda descifrar el codigo encriptado, por eso es importante que en el caso de las contrasenas se compongan de combinaciones de letras, numeros y caracteres especiales. Existen websites que pueden intentar descifrar estos codigos encriptados tales como: md5decript.org y md5decripter.co.uk por mencionar algunos. 

Lenguaje C : Area del circulo

La formula del area del circulo es A = π * r ^ 2. En donde A es la constante que representara el area,  π es el simbolo del pi que vale 3.14 y r es el valor del radio elevado al cuadrado.

El codigo en lenguaje C, es el siguiente:

   #include<stdio.h>
    main()
    {
     float r,pi,a;
    printf("introduce el valor del radio\n");
    scanf("%f",&r);
    pi= 3.14;
    a= pi*r*r;
    printf("el area del circulo es:%f\n",a);
    getchar();
    getchar();

    }




Manipulacion de tablas HTML con DataTables

En mi experiencia en mejor plugin para la manipulacion de datos en tablas HTML es DataTables. El mismo le permitira ordenar, buscar y mostrar los datos de sus tablas de una forma dinamica, gracias a que es un plugin de la libreria de javascript JQuery.

A continuacion un ejemplo de como instalar DataTable con datos traidos desde la base de datos. 

1. Descargar la version mas reciente de DataTable en la siguiente direccion: http://datatables.net/download/, extraer el archivo .zip

2. Ejecutar el siguiente script para la creacion de la base de datos:

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `datatable_ejemplo`
--
CREATE DATABASE IF NOT EXISTS `datatable_ejemplo` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `datatable_ejemplo`;

-- --------------------------------------------------------

--
-- Table structure for table `cliente`
--

CREATE TABLE IF NOT EXISTS `cliente` (
  `codigo` int(11) NOT NULL AUTO_INCREMENT,
  `nombre` varchar(25) NOT NULL,
  `apellido` varchar(25) NOT NULL,
  `direccion` varchar(45) NOT NULL,
  `telefono` varchar(12) NOT NULL,
  PRIMARY KEY (`codigo`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

--
-- Dumping data for table `cliente`
--

INSERT INTO `cliente` (`codigo`, `nombre`, `apellido`, `direccion`, `telefono`) VALUES
(1, 'Maria', 'Lopez', 'c/ 20 Los Ramos', '829-234-2344'),
(2, 'Juan', 'Gomez', 'c/ D Las Flores', '849-322-2344'),
(3, 'Flavia', 'Pichardo', 'c/77 El tronco', '809-345-6420');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


3.  Abrir un documento php con el formato HTML correspondiente. 

4. Hacer la conexion a la base de datos:

<?php
mysql_connect('localhost','root','') or die ("No se pudo conectar a la base de datos");
mysql_select_db('datatable_ejemplo') or die("No se pudo seleccionar la base de datos");
?>

5. Crear la tabla html que contendra nuestros datos. Es muy importante que la tabla cuente con las etiquetas <theader> y <tfooter> para que el DataTable pueda funcionar. El siguiente es mi codigo para el ejemplo. 

<table id="datatables">
    <thead>
       <tr>
<th> <strong>Codigo </strong>    </th>   
<th> <strong>Nombre </strong>    </th>  
<th> <strong>Apellido </strong>  </th>
<th> <strong>Direccion </strong> </th>
<th> <strong>Telefono </strong> </th>
 </tr>
    </thead>
    <tbody>
       <?php

$sql = "SELECT codigo, nombre, apellido, direccion, telefono FROM cliente";
$re = mysql_query($sql) or die("Error al ejecutar la consulta") . mysql_error();

while ($fila = mysql_fetch_array($re)) {
    
    
    echo '<tr">

<td>' . $fila['codigo'] . '</td> 
<td>' . $fila['nombre'] . '</td> 
<td>' . $fila['apellido'] . '</td> 
<td>' . $fila['direccion'] . '</td> 
<td>' . $fila['telefono'] . '</td> 

</tr>';
    
}

?>
    </tbody>
</table>

6. Luego hay que anadir dentro de las etiquetas <head> el enlace a los estilos css para el dataTable de la siguiente manera:

<style type="text/css" title="currentStyle">
@import "DataTables-1.9.4/media/css/jquery.dataTables.css";
</style>

7. Finalmente necesario insertar justo despues del cierre de la etiqueta <body> los siguientes enlaces:


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <!-- ENLACE A JQUERY ALMACENADO EN LA LIBRERIA DE GOOGLE -->

<script src="DataTables-1.9.4/media/js/jquery.dataTables.js" type="text/javascript"> </script> <!-- ENLACE A LOS SCRIPTS DE JQUERY DE EL DATATABLE -->

<script type="text/javascript" charset="utf-8"> <!-- FUNCION PARA INICIALIZAR EL DATATABLE Y PERSONALIZARLO AL ESPANOL -->

$(document).ready(function() {

$('#datatables').dataTable({


   "aaSorting": [[0, "desc"]],
        "sPaginationType": "full_numbers",
"bAutoWidth": false,
"oLanguage": {
            "sLengthMenu": "Mostrar _MENU_ ",
            "sZeroRecords": "No existen datos para esta consulta",
            "sInfo": "Mostrando del _START_ al _END_ de un total de _TOTAL_ registros",
            "sInfoEmpty": "Mostrando del 0 al 0 de un total de 0 registros",
            "sInfoFiltered": "(De un maximo de _MAX_ registros)",
"sSearch": "Buscar: _INPUT_",
"sEmptyTable": "No hay datos disponibles para esta tabla",
"sLoadingRecords": "Por favor espere - Cargando...",  
"sProcessing": "Actualmente ocupado",
"sSortAscending": " - click/Volver a ordenar en orden Ascendente",
"sSortDescending": " - click/Volver a ordenar en orden descendente",
"oPaginate": {
        "sFirst":    "Primero",
        "sLast":     "Ultimo",
        "sNext":     "Siguiente",
        "sPrevious": "Anterior"
    },
        }
});

})

</script>


El resultado deberia lucir asi:


Este es mi codigo completo:

<?php
mysql_connect('localhost', 'root', '') or die("No se pudo conectar a la base de datos");
mysql_select_db('datatable_ejemplo') or die("No se pudo seleccionar la base de datos");
?>
<html>
<title> DataTable Ejemplo </title>
<head>
<style type="text/css" title="currentStyle">

@import "DataTables-1.9.4/media/css/jquery.dataTables.css";

</style>
</head>

<body>

<table id="datatables">
    <thead>
       <tr>
<th> <strong>Codigo </strong>    </th>
<th> <strong>Nombre </strong>    </th>
<th> <strong>Apellido </strong>  </th>
<th> <strong>Direccion </strong> </th>
<th> <strong>Telefono </strong> </th>
 </tr>
    </thead>
    <tbody>
       <?php

$sql = "SELECT codigo, nombre, apellido, direccion, telefono FROM cliente";
$re = mysql_query($sql) or die("Error al ejecutar la consulta") . mysql_error();

while ($fila = mysql_fetch_array($re)) {
 
 
    echo '<tr">

<td>' . $fila['codigo'] . '</td>
<td>' . $fila['nombre'] . '</td>
<td>' . $fila['apellido'] . '</td>
<td>' . $fila['direccion'] . '</td>
<td>' . $fila['telefono'] . '</td>

</tr>';
 
}

?>
    </tbody>
</table>
</body>


<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <!-- ENLACE A JQUERY ALMACENADO EN LA LIBRERIA DE GOOGLE -->

<script src="DataTables-1.9.4/media/js/jquery.dataTables.js" type="text/javascript"> </script> <!-- ENLACE A LOS SCRIPTS DE JQUERY DE EL DATATABLE -->

<script type="text/javascript" charset="utf-8"> <!-- FUNCION PARA INICIALIZAR EL DATATABLE Y PERSONALIZARLO AL ESPANOL -->

$(document).ready(function() {

$('#datatables').dataTable({


   "aaSorting": [[0, "desc"]],
        "sPaginationType": "full_numbers",
"bAutoWidth": false,


"oLanguage": {
            "sLengthMenu": "Mostrar _MENU_ ",
            "sZeroRecords": "No existen datos para esta consulta",
            "sInfo": "Mostrando del _START_ al _END_ de un total de _TOTAL_ registros",
            "sInfoEmpty": "Mostrando del 0 al 0 de un total de 0 registros",
            "sInfoFiltered": "(De un maximo de _MAX_ registros)",
"sSearch": "Buscar: _INPUT_",
"sEmptyTable": "No hay datos disponibles para esta tabla",
"sLoadingRecords": "Por favor espere - Cargando...",
"sProcessing": "Actualmente ocupado",
"sSortAscending": " - click/Volver a ordenar en orden Ascendente",
"sSortDescending": " - click/Volver a ordenar en orden descendente",

"oPaginate": {
        "sFirst":    "Primero",
        "sLast":     "Ultimo",
        "sNext":     "Siguiente",
        "sPrevious": "Anterior"
    },

        }
});

})

</script>

</html>

Como reinicializar SQL autoincrement a 0

Existen dos formas para reinicializar el autoincrement en SQL a cero luego de haber insertado valores a cierta tabla en la base de datos.

 1. La primera forma consiste en primero eliminar todos los datos contenidos en la tabla ejecutando el query "delete".

Ej: DELETE FROM `productos`;

Para luego establecer el autoincrement de vuelta a 0 de la siguiente manera:

Ej: ALTER TABLE `productos` AUTO_INCREMENT=0;

2. Hay una forma de eliminar los datos y establecer el autoincrement a 0 de una vez:

Ej: TRUNCATE TABLE `productos`;

Ejercicios resueltos en C# : Control de alcoholemia


La Dirección General de Tráfico necesita un programa que, dado el tipo de vehículo que conduce un conductor, su índice de alcohol y si ha sido medido en sangre o en aire, determine si da positivo en el control de alcoholemia o no. La tasa máxima de alcohol tanto en sangre como en aire según el tipo de vehículo se resume en la siguiente tabla:

Vehiculo Indicador Tasa maxima en sangre Tasa maxima en aire
Camión C 0.3 0.15
Autobús A 0.3 0.15
Turismo T 0.5 0.25
Motocicleta M 0.3 0.15


Como realizar este ejercicio en C#?


1ro. Crear un formulario con dos textboxes, el que contendra el Tipo de vehiculo se llamara txttipovehiculo y que contendra el indice de alcohol txtindicealcohol asi como dos radio buttons llamados rbtsangrerbtaire.

2do. El botón "Determinar" hará el trabajo, por lo que este es el codigo que hará que el mismo funcione:


try
            {
                double indecealcohol;
                indecealcohol = Convert.ToDouble(txtindicealcohol.Text);

                if (txttipovehiculo.Text != "C" && txttipovehiculo.Text != "A" && txttipovehiculo.Text != "T" && txttipovehiculo.Text != "M")
                {

                    MessageBox.Show("Indicador no válido!");

                    txttipovehiculo.SelectionStart = 0; //Sombrear el texto
                    txttipovehiculo.SelectionLength = txttipovehiculo.Text.Length; //Sombrear el texto
                    txttipovehiculo.Focus(); 

                } 
                else
                {

                    if (txttipovehiculo.Text == "C")
                    {

                        if (rbtsangre.Checked)
                        {
                            if (indecealcohol >= 0.3)
                            {
                                lblresultado.Text = "Positivo".ToString();
                            }
                            else
                            {
                                lblresultado.Text = "Negativo".ToString();
                            }
                        }
                        else
                        {

                            if (rbtaire.Checked == true)
                            {
                                if (indecealcohol >= 0.15)
                                {
                                    lblresultado.Text = "Positivo".ToString();
                                }
                                else
                                {
                                    lblresultado.Text = "Negativo".ToString();
                                }

                            }
                        }
                    }
                    else
                    {

                        if (txttipovehiculo.Text == "A")
                        {

                            if (rbtsangre.Checked)
                            {
                                if (indecealcohol >= 0.3)
                                {
                                    lblresultado.Text = "Positivo".ToString();
                                }
                                else
                                {
                                    lblresultado.Text = "Negativo".ToString();
                                }
                            }
                            else
                            {
                                if (rbtaire.Checked)
                                {
                                    if (indecealcohol >= 0.15)
                                    {
                                        lblresultado.Text = "Positivo".ToString();
                                    }
                                    else
                                    {
                                        lblresultado.Text = "Negativo".ToString();
                                    }

                                }
                            }

                        }
                        else
                        {
                            if (txttipovehiculo.Text == "T")
                            {

                                if (rbtsangre.Checked)
                                {
                                    if (indecealcohol >= 0.5)
                                    {
                                        lblresultado.Text = "Positivo".ToString();
                                    }
                                    else
                                    {
                                        lblresultado.Text = "Negativo".ToString();
                                    }
                                }
                                else
                                {
                                    if (rbtaire.Checked)
                                    {
                                        if (indecealcohol >= 0.25)
                                        {
                                            lblresultado.Text = "Positivo".ToString();
                                        }
                                        else
                                        {
                                            lblresultado.Text = "Negativo".ToString();
                                        }

                                    }
                                }

                            }
                            else
                            {
                                if (txttipovehiculo.Text == "M")
                                {

                                    if (rbtsangre.Checked)
                                    {
                                        if (indecealcohol >= 0.3)
                                        {
                                            lblresultado.Text = "Positivo".ToString();
                                        }
                                        else
                                        {
                                            lblresultado.Text = "Negativo".ToString();
                                        }
                                    }
                                    else
                                    {
                                        if (rbtaire.Checked)
                                        {
                                            if (indecealcohol >= 0.15)
                                            {
                                                lblresultado.Text = "Positivo".ToString();
                                            }
                                            else
                                            {
                                                lblresultado.Text = "Negativo".ToString();
                                            }

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                

            }
            catch (Exception msg)
            {

                MessageBox.Show(msg.Message);
            }


3ro. Adicionalmente el botón "Limpiar":

            txtindicealcohol.Clear();
            txttipovehiculo.Clear();
            lblresultado.Text = "";
            txttipovehiculo.Focus();


y el botón "Salir":

Close();

Ejercicios resueltos en C#: Precio de pasaje de ferrocarril

"Determinar el precio de un pasaje de ida y vuelta en ferrocarril, conociendo la distancia a recorrer y el número de días de estancia en el destino. Si este es mayor que 7 y la distancia superior a 800km, el pasaje tiene una reducción del 30%. El precio por km es $0.80."

Como realizar este ejercicio en C#?

1ro. Crear un formulario con tres textboxes, el que contendra La distancia recorrer se llamara txtdistancia, el de los dias de estancia txtdiasestancia y el que contendra lel precio del pasaje txtprecio_pasaje.

2do. El botón "Calcular" hará el trabajo, por lo que este es el codigo que hará que el mismo funcione:

    try
            {
                double distancia, dias_estancia, precioxkm, precio_pasaje;

                distancia = Convert.ToInt16(txtdistancia.Text);
                dias_estancia = Convert.ToInt16(txtdiasestancia.Text);
                precioxkm = 0.80;
                if (dias_estancia > 7 && distancia > 800)
                {
                    precio_pasaje = precioxkm * distancia - (precioxkm * distancia * 0.30);
                    txtprecio_pasaje.Text = "$" + precio_pasaje.ToString();
                }
                else
                {
                    precio_pasaje = precioxkm * distancia;
                    txtprecio_pasaje.Text = "$" + precio_pasaje.ToString();
                }

            }
            catch (Exception msg)
            {

                MessageBox.Show(msg.Message);
            }


          

3ro. Adicionalmente el botón "Limpiar":


            txtdiasestancia.Clear();
            txtdistancia.Clear();
            txtprecio_pasaje.Clear();