viernes, 9 de noviembre de 2012

jQuery: Test Time Entry

$(".entry_hora").timeEntry({
    ampmPrefix: ' ',
    spinnerImage: 'spinnerDefault.png'
});

Test Online.
http://jsfiddle.net/ric47121/9QkpK/

Web Oficial:
http://keith-wood.name/timeEntry.html

jueves, 25 de octubre de 2012

jQuery: input money con autoNumeric

$('#auto').autoNumeric({aSep: '.', aDec: ',', aSign: '$ '});

test online:
http://jsfiddle.net/ric47121/TUCCD/1/

documentacion:
http://www.decorplanit.com/plugin/

otros similares:
http://www.jquery4u.com/plugins/10-jquery-currencyprice-plugins/#.UIlcI8XA9Ip

jQuery: Test currency

$('#currencyField').blur(function(e) {
    
    $(this).formatCurrency();
   
});

test online:
http://jsfiddle.net/ric47121/MDkGZ/

lunes, 22 de octubre de 2012

Html: Mostrar pdf en la web (pdf, word, ppt, etc)

mostrar documentos sobre la web con google docs viewer

https://docs.google.com/viewer?hl=es

me sirvio para mostrar la documentacion del sistema que estaba en word.

guardar el documento como pdf, se sube a algun servidor y luego el visor se encarga de hacer todo.

enjoy!

viernes, 28 de septiembre de 2012

Google Maps: mover marcador


marker.setPosition( new google.maps.LatLng( lat, lon ) );
        map.panTo( new google.maps.LatLng( lat, lon ) );

test online rck:
http://jsfiddle.net/ric47121/4YbED/5/

jueves, 27 de septiembre de 2012

PHP: ip 2 country json

<?php 

$ip = $_SERVER['REMOTE_ADDR'];
$json = file_get_contents("http://api.easyjquery.com/ips/?ip=".$ip."&full=true");
$json = json_decode($json,true);

echo "
<pre>";
print_r($json);

?>

url:
http://www.easyjquery.com/detect-get-clients-ip-address-country-using-javascript-php/

otra forma:
http://freegeoip.appspot.com/

miércoles, 26 de septiembre de 2012

Android: postData

Habilitar
android.permission.INTERNET


public void postData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        //HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
        HttpPost httppost = new HttpPost("http://192.168.0.18/test/androidpost.php");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", "12345"));
            nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            
            Toast.makeText(getBaseContext(), "Enviado con exito: "+response.toString(), Toast.LENGTH_LONG).show();
            
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            
            Toast.makeText(getBaseContext(), "Error 1: "+e.toString(), Toast.LENGTH_LONG).show();
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Toast.makeText(getBaseContext(), "Error 2: "+e.toString(), Toast.LENGTH_LONG).show();
        }
    }

Android: GPS Test (Android 2.2) funciona xD

package com.example.gpstest2;

//import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements LocationListener {

    private LocationManager locationManager;
    TextView t;     
    //private String provider;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.setTitle("test gps rck");  
        
        //telnet localhost 5554
        //geo fix 30 26
        
        // Get the location manager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        
        t = (TextView) findViewById(R.id.tit);    
        t.setText("inicio..");
        
        //LocationListener mlocListener = new LocationListener();
        //locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
        //locationManager.requestLocationUpdates(provider, 400, 1, this);
        
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 400, 1, this);
        
        boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        // Check if enabled and if not send user to the GSP settings
        // Better solution would be to display a dialog and suggesting to
        // go to the settings
        if (!enabled) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
            Toast.makeText(getBaseContext(), "gps no esta disponible", Toast.LENGTH_LONG).show();
        }
        
        Toast.makeText(getBaseContext(), "GPS disponible", Toast.LENGTH_LONG).show();

        /*
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null) {
          System.out.println("Provider " + provider + " has been selected.");
          onLocationChanged(location);
        } else {
          //latituteField.setText("Location not available");
          //longitudeField.setText("Location not available");
            Toast.makeText(getBaseContext(), "Location not available", Toast.LENGTH_LONG).show();
        }
        */
    }

    
    @Override
    protected void onResume() {
      super.onResume();
      //locationManager.requestLocationUpdates(provider, 400, 1, this);
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 400, 1, this);
    }

    
    @Override
    protected void onPause() {
      super.onPause();
      locationManager.removeUpdates(this);
    }

    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    public void onLocationChanged(Location loc) {
        // TODO Auto-generated method stub
        //loc.getLatitude();
        //loc.getLongitude();
        
        String Text = "My current location is: Latitud = " + loc.getLatitude() + " Longitud = " + loc.getLongitude();

        Toast.makeText(getBaseContext(), Text, Toast.LENGTH_LONG).show();
        
            
        t.setText("cambio: " + Text);

    }

    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
        Toast.makeText( getBaseContext(),"Gps Disabled",Toast.LENGTH_SHORT ).show();
        
    }

    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
        Toast.makeText( getBaseContext(),"Gps Enabled",Toast.LENGTH_SHORT ).show();
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
        
    }
}

martes, 18 de septiembre de 2012

jQuery: numberfield en todos los navegadores

HTML 5 numberfield funciona en chrome pero no asi en firefox.
solucion:

$('#spinner2').spinner({ min: 2, max: 5 });

test rck:

miércoles, 29 de agosto de 2012

javascript: Armar query SQL a partir de un objeto json

var obj = {
    s_campo1 : "'hola'", //string
    f_campo2 : 'now()', //function
    b_campo3 : true, //booleano
    i_campo4 : 5 //int
}

var query = "INSERT INTO TABLA (" + _.keys(obj).join(",") + ") " ;
    query += "VALUES ";
    query += "("+ _.values(obj).join(",") + ")" ;

console.log(query)

test rck:
http://jsfiddle.net/yAFgu/7/

jueves, 26 de julio de 2012

jQuery: mi primer Plugin 'resaltado de texto con jquery'

$.fn.resaltar= function(options){  

        var opts = $.extend({}, $.fn.resaltar.defaults, options);    
        
        this.each(function(){    
            
            //console.log(this);
            //$(this).css({'background':'rgba(255, 0, 0, .4)'});  //SI
                          
            (function(self){
               var t = 1; 
               var sube =true;
                                
              var timer = setInterval(function(){    
                     // console.log(self) 
                      
                    //$(self).css({'background':'rgba(255, 0, 0, .4)'});        //si
                          
                  //var color = 'rgba(255, 0, 0, .'+t+')'; //comun
                  var color = 'rgba('+opts.r+', '+opts.g+', '+opts.b+', .'+t+')'; 
                  
                  
                  
                 //$(this).css({'background': color}); // NO ANDA!!
                  $(self).css({'background': color}); //SIII
                    //console.log("asdsa", t, sube, color)
                        
                    if(sube) t++;
                       else t--;
                        
                    if(sube && t==9) sube = false;    
                  if(!sube && t==-1) clearInterval(timer)           
                   
                    
                },50);
                      
            })(this);
                  
                  
        });        
    };  
       
    $.fn.resaltar.defaults = {  
        // para el fondo un color por defecto  
        r: '255',
        g: '0',
        b  : '0'
    };  

/*----------------------------*/
//$("#test1").resaltar();  

$("#my").click(function(){
     $("#test1").resaltar();  
    $("#test2").resaltar({r:'0',g:'255',b:'0'});  
});

test rck:
http://jsfiddle.net/ric47121/sUnKf/6/

test Online:
http://ricardolevano.com.ar/test/test_resaltado_jquery_by_rck/test1.html

javascript: Closures y Scope en javaScript

for(i=0;i<3;i++){
    (function(i){
       var pos = i;
       var timer = setInterval(function(){    
                       console.log("toto",pos++)  
                       if(pos==5){
                           console.info("eliminando el timer", i)
                           clearInterval(timer)                                            
                       } 
                 },1000);
    
    })(i);
}

martes, 24 de julio de 2012

jQuery: Simple Loguer

function agregarEvento(){
    //var loguer = $("#loguer-rck");
    $("#loguer-rck").prepend("<li> <span>3:05 pm :</span>  un nuevo item.</li>");
    console.log("agregado")

     //   $("#loguer_conteiner").scrollTop(9999);
    $("#loguer_conteiner").animate({scrollTop:0}, 'slow');
}
        
​test rck:
http://jsfiddle.net/ric47121/98efR/7/

test rck 2 (con resaltado by rck)
http://jsfiddle.net/ric47121/98efR/8/

lunes, 23 de julio de 2012

javaScript: fechas (date.js)

//http://code.google.com/p/datejs/

var t1 = new Date().toString('d/M/yyyy')  
console.log(t1)

var fecha = Date.parse("1986-09-01", "Y-m-d H:i:s");
console.log(fecha.toString('d/M/yyyy'))


test rck:
http://jsfiddle.net/ric47121/pACDm/1/

martes, 17 de julio de 2012

PHP y MySQLi: conexion con mysqli y manejo de errores

<?php
include "db.php";
$conexion = new mysqli($MYSQL_HOST, $MYSQL_LOGIN, $MYSQL_PASS, $MYSQL_DB);

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$result = $conexion->query("select * from users");
echo "Num de filas al iniciar: ".$result->num_rows. "</br>";

while($row = $result->fetch_array(MYSQLI_ASSOC)){
    echo $row['name']." ";
}

echo "<hr>";

$conexion->autocommit(false);

try{

    $result = $conexion->query("INSERT INTO users (name, email) VALUES ('ambro', 'un email');");
        if(!$result) throw new Exception($conexion->error);
        
    echo "id usuario nuevo: ".$conexion->insert_id; //si
    echo "<hr>";

    $result = $conexion->query("INSERT INTO users_comments (id_user, TEXT) VALUES ({$conexion->insert_id}, 'un comentario del user {$conexion->insert_id}');");
        if(!$result) throw new Exception($conexion->error);

    echo "id comentario nuevo: ".$conexion->insert_id; //si
    echo "<hr>";

    $result = $conexion->query("INSERT INTO users_comments (id_user, TEXT) VALUES (85, 'un comentario del user asd');");
        if(!$result) throw new Exception($conexion->error);
            //throw new SqlException( mysqli_error( $connection ) );
        
    $conexion->commit();

}
catch(Exception $e){
    $conexion->rollback();
    die("error lo agarra el catch: <br>".$e->getMessage() );
}

?>

lunes, 16 de julio de 2012

javascript: armar array Asociativo a partir de un array de objetos

var coll = [ 
    {'codigo':1, 'nombre': 'DNI', 'descripcion':'blah..' },
    {'codigo':2, 'nombre': 'PASAPORTE', 'descripcion':'blah 5..' } ,   
    {'codigo':5, 'nombre': 'CEDULA', 'descripcion':'blah 2..' }
]

/*
arma un array asociativo a partir de un array de objetos    
*/
var TIPOS_DOC = transformToArrayAsociativo(coll, k='codigo', v='nombre');

console.log(TIPOS_DOC , TIPOS_DOC[1], TIPOS_DOC['3'])

function transformToArrayAsociativo(coll, key, value){    
    var arr= {};    
    for(var i=0;i<coll.length;i++){
        //console.log(coll[i].codigo)
        var obj = coll[i];
        var k = obj[key];
        var v = coll[i][value];
         
        arr[k] = v;                 
     }
return arr;             
}

test rck:
http://jsfiddle.net/ric47121/93AWd/7/

jQuery: filtrar tabla inline

var todos =[];

$("#table_defensorias tbody tr").each(function(index) {
       //todos.push($(this).text());
        //$(this).find("td").eq(0).css("color","red")
        //colum_1.push($(this).find("td").eq(0).text());
        todos.push({
            colum_0: $(this).find("td").eq(0).text(),
            colum_1: $(this).find("td").eq(1).text()
        }); 
    });

//console.log(todos) //ok

$("#filter_def").keyup(function(){
    //console.log($(this).val());
    
    $("#table_defensorias tbody").html("");
   var srtSearch = $(this).val(); 
   //var filtrados = filtrar(todos, srtSearch);
   
    //var filtrados = _.filter(todos, function(txt){ return /+'srtSearch '+/gi.test(txt); });
    
    var filtrados = _.filter(todos, function(obj){ 
        return (
            (new RegExp(srtSearch,'gi')).test(obj.colum_0) ||
            (new RegExp(srtSearch,'gi')).test(obj.colum_1)
)            
            ; });
    
    //console.log(filtrados)
        
    for(var i=0;i<filtrados.length;i++){
        $('#table_defensorias tbody')
        .append('<tr>'+
        '<td>'+filtrados[i].colum_0+'</td>'+
        '<td>'+filtrados[i].colum_1+'</td>'+
        '<td>'+'</td>'+
        '<td>'+'</td>'+
        '</tr>');
    }

});

test rck:
http://jsfiddle.net/ric47121/49s6W/3/

jQuery: filter ul usando underscore.js

var todos = [];

$("ul li").each(function(index) {
   todos.push($(this).text());
});

$("#filter_def").keyup(function(){
    
    $("ul").html("");
   var srtSearch = $(this).val(); 

    var filtrados = _.filter(todos, function(txt){ return (new RegExp(srtSearch,'gi')).test(txt); });
    
    for(var i=0;i<filtrados.length;i++){
        $('ul').append('<li>'+filtrados[i]+'</li>');
    }

});

test rck:
http://jsfiddle.net/ric47121/Cvq4e/4/