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 - JaAViEr

#1
Hola!

Siguiendo con las prácticas en PyQT4, traigo una aplicación "juego" que luce 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
Enseguida explico más o menos en que consiste.

La aplicación se encarga de generar Números/Letras/Números y Letras (según cada gusto) de forma totalmente aleatoria, con la longitud que tu desees. Además de seleccionar un tiempo "límite" para memorizar el valor generado, una vez acabado este tiempo límite, el valor es oculto, para que tu escribas la respuesta y evaluar si lo que memorizaste corresponde realmente a la cifra que generó y mostró por los X segundos que lo configuraste.

Una vez lanzada la aplicación y configurada, damos clic en ¡Establecer Configuración! , lo que nos da un nuevo cuadro, que luce así:
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
Damos clic en "Comenzar" y tendremos esto:
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
Una vez acabado el tiempo, el QLineEdit se resetea para que ingreses lo que memorizaste:
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
Una vez ingresado el valor que memorizaste, presiona ENTER, si el valor fue correcto, entonces tu racha aumentará en +1 , de lo contrario se reiniciará a 0.
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
Sin más que agregar, el código:
Código: python
# -*- coding: utf-8 -*-
'''
Juego Memoriza :: Entrenando tu Memoria
Autor: JaAViEr | 0x5d
Twitter: https://twitter.com/javieresteban__
Website: http://codigo.ga
'''
from PyQt4 import QtCore, QtGui
import sys
from random import randint, sample
import threading
from time import sleep

try:

_fromUtf8 = QtCore.QString.fromUtf8

except AttributeError:

def _fromUtf8(s):

return s
try:

_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):

return QtGui.QApplication.translate(context, text, disambig, _encoding)

except AttributeError:

def _translate(context, text, disambig):

return QtGui.QApplication.translate(context, text, disambig)

class formA(QtGui.QWidget):

def __init__(self, parent=None):

self.largo = 4
QtGui.QWidget.__init__(self, parent)
self.resize(359, 131)
self.gridLayout = QtGui.QGridLayout(self)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.tabWidget_inicial = QtGui.QTabWidget(self)
self.tabWidget_inicial.setStyleSheet(_fromUtf8("font-weight:bold;"))
self.tabWidget_inicial.setObjectName(_fromUtf8("tabWidget_inicial"))
self.tab = QtGui.QWidget()
self.tab.setObjectName(_fromUtf8("tab"))
self.gridLayout_2 = QtGui.QGridLayout(self.tab)
self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
self.label_tipo = QtGui.QLabel(self.tab)
self.label_tipo.setObjectName(_fromUtf8("label_tipo"))
self.gridLayout_2.addWidget(self.label_tipo, 0, 2, 1, 1)
self.pushButton_comenzar = QtGui.QPushButton(self.tab)
self.pushButton_comenzar.setObjectName(_fromUtf8("pushButton_comenzar"))
self.gridLayout_2.addWidget(self.pushButton_comenzar, 2, 0, 1, 3)
self.spinBox_largo = QtGui.QSpinBox(self.tab)
self.spinBox_largo.setMinimum(1)
self.spinBox_largo.setProperty("value", 4)
self.spinBox_largo.setObjectName(_fromUtf8("spinBox_largo"))
self.gridLayout_2.addWidget(self.spinBox_largo, 1, 0, 1, 1)
self.comboBox_tipo = QtGui.QComboBox(self.tab)
self.comboBox_tipo.setObjectName(_fromUtf8("comboBox_tipo"))
self.comboBox_tipo.addItem(_fromUtf8(""))
self.comboBox_tipo.addItem(_fromUtf8(""))
self.comboBox_tipo.addItem(_fromUtf8(""))
self.gridLayout_2.addWidget(self.comboBox_tipo, 1, 2, 1, 1)
self.label_largo = QtGui.QLabel(self.tab)
self.label_largo.setObjectName(_fromUtf8("label_largo"))
self.gridLayout_2.addWidget(self.label_largo, 0, 0, 1, 1)
self.label_tiempo = QtGui.QLabel(self.tab)
self.label_tiempo.setObjectName(_fromUtf8("label_tiempo"))
self.gridLayout_2.addWidget(self.label_tiempo, 0, 1, 1, 1)
self.spinBox_tiempo = QtGui.QSpinBox(self.tab)
self.spinBox_tiempo.setPrefix(_fromUtf8(""))
self.spinBox_tiempo.setObjectName(_fromUtf8("spinBox_tiempo"))
self.spinBox_tiempo.setMinimum(1)
self.gridLayout_2.addWidget(self.spinBox_tiempo, 1, 1, 1, 1)
self.tabWidget_inicial.addTab(self.tab, _fromUtf8(""))
self.gridLayout.addWidget(self.tabWidget_inicial, 0, 0, 1, 1)

self.valores_elementos()
self.connect(self.pushButton_comenzar, QtCore.SIGNAL("clicked()"), self.establecer_configuracion)

def establecer_configuracion(self):

self.tiempo = int(self.spinBox_tiempo.value())
self.largo = int(self.spinBox_largo.value())
form_b.show()
form_b.label_segundos_restantes.setText("%s segundos" % self.tiempo)


def valores_elementos(self):

self.setWindowTitle(_translate("self", "Memoriza :: www.codigo.ga", None))
self.label_tipo.setText(_translate("self", "Tipo de juego", None))
self.pushButton_comenzar.setText(_translate("self", "¡Establecer configuración!", None))
self.comboBox_tipo.setItemText(0, _fromUtf8("Números"))
self.comboBox_tipo.setItemText(1, _translate("self", "Letras", None))
self.comboBox_tipo.setItemText(2, _translate("self", "Números y Letras", None))
self.label_largo.setText(_translate("self", "Largo", None))
self.label_tiempo.setText(_translate("self", "Tiempo para memorizar", None))
self.spinBox_tiempo.setSuffix(_fromUtf8(" segundos"))
self.tabWidget_inicial.setTabText(self.tabWidget_inicial.indexOf(self.tab), _translate("self", "Configuración de Memoriza", None))


class formB(QtGui.QWidget):

def __init__(self, parent=None):

self.valor_generado = ""
self.racha = 0
QtGui.QWidget.__init__(self, parent)
self.setObjectName(_fromUtf8("self"))
self.resize(215, 104)
self.gridLayout = QtGui.QGridLayout(self)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.splitter = QtGui.QSplitter(self)
self.splitter.setOrientation(QtCore.Qt.Vertical)
self.splitter.setObjectName(_fromUtf8("splitter"))
self.label_memoriza = QtGui.QLabel(self.splitter)
self.label_memoriza.setStyleSheet(_fromUtf8("font-weight: bold; font-size: 17px;"))
self.label_memoriza.setObjectName(_fromUtf8("label_memoriza"))
self.lineEdit_valor_memorizar = QtGui.QLineEdit(self.splitter)
self.lineEdit_valor_memorizar.setReadOnly(True)
self.lineEdit_valor_memorizar.setObjectName(_fromUtf8("lineEdit_valor_memorizar"))
self.gridLayout.addWidget(self.splitter, 0, 0, 1, 2)
self.label_tiempo_restante = QtGui.QLabel(self)
self.label_tiempo_restante.setObjectName(_fromUtf8("label_tiempo_restante"))
self.gridLayout.addWidget(self.label_tiempo_restante, 1, 0, 1, 1)
self.label_segundos_restantes = QtGui.QLabel(self)
self.label_segundos_restantes.setStyleSheet(_fromUtf8("font-style: italic; font-weight: bold;"))
self.label_segundos_restantes.setObjectName(_fromUtf8("label_segundos_restantes"))
self.gridLayout.addWidget(self.label_segundos_restantes, 1, 1, 1, 1)
self.pushButton_comenzar = QtGui.QPushButton(self)
self.pushButton_comenzar.setObjectName(_fromUtf8("pushButton_comenzar"))
self.gridLayout.addWidget(self.pushButton_comenzar, 3, 0, 1, 2)
self.label_racha = QtGui.QLabel(self)
self.label_racha.setObjectName(_fromUtf8("label_racha"))
self.gridLayout.addWidget(self.label_racha, 2, 0, 1, 1)
self.label_valor_racha = QtGui.QLabel(self)
self.label_valor_racha.setStyleSheet(_fromUtf8("font-weight:  bold;"))
self.label_valor_racha.setObjectName(_fromUtf8("label_valor_racha"))
self.gridLayout.addWidget(self.label_valor_racha, 2, 1, 1, 1)

self.connect(self.pushButton_comenzar, QtCore.SIGNAL("clicked()"), self.empezar)
self.connect(self.pushButton_comenzar, QtCore.SIGNAL("returnPressed()"), self.empezar)
self.connect(self.lineEdit_valor_memorizar, QtCore.SIGNAL("returnPressed()"), self.cambia_valor)
self.renombrar_elementos_widget()
QtCore.QMetaObject.connectSlotsByName(self)

def cambia_valor(self):

qstring = str(self.lineEdit_valor_memorizar.text())
# mensaje = QtGui.QMessageBox()

if qstring == self.valor_generado and len(self.valor_generado) > 0 and len(qstring) > 0:

# mensaje.setText(_fromUtf8("¡Respuesta correcta!"))
self.pushButton_comenzar.setFocus(True)
self.lineEdit_valor_memorizar.setText("")
self.valor_generado = False
self.racha = self.racha + 1
self.label_valor_racha.setText(str(self.racha))
self.empezar()

else:

self.lineEdit_valor_memorizar.setText("")
self.valor_generado = False
# mensaje.setText(_fromUtf8("¡Respuesta Incorrecta!"))
self.racha = 0
self.correr = False
self.label_valor_racha.setText("0")
self.empezar()

# mensaje.exec_()

def generar_numero(self):

valor = ""
for i in range(form_a.largo,):

valor = valor + str(randint(0, 9))

return valor

def generar_letras(self):

valor = ""
lista = list("abcdefghijklmnopqrstuvwxyz")
len_lista = len(lista) - 1
for i in range(form_a.largo):

valor = valor + lista[randint(0,len_lista)]

return valor

def generar_alfanumerico(self):

valor = ""
lista_abc = list("abcdefghijklmnopqrstuvwxyz")
lista_digitos = list("0123456789")
largo = form_a.largo / 2
len_lista_abc = len(lista_abc) - 1
len_lista_digitos = len(lista_digitos) - 1
for i in range(largo):

valor = valor + lista_abc[randint(0,len_lista_abc)]

for i in range(largo):

valor = valor + lista_digitos[randint(0,len_lista_digitos)]

return ''.join(sample(valor, len(valor)))

def empezar(self):

opcion = form_a.comboBox_tipo.currentIndex()
self.lineEdit_valor_memorizar.setReadOnly(True)
if opcion == 0:
self.valor_generado = self.generar_numero()
self.lineEdit_valor_memorizar.setText(self.valor_generado)
elif opcion == 1:
self.valor_generado = self.generar_letras()
self.lineEdit_valor_memorizar.setText(self.valor_generado)
elif opcion == 2:
self.valor_generado = self.generar_alfanumerico()
self.lineEdit_valor_memorizar.setText(self.valor_generado)

t = Timer()
t.start()

def renombrar_elementos_widget(self):

self.setWindowTitle(_translate("self", "Tablero", None))
self.label_memoriza.setText(_translate("self", "<html><head/><body><p align=\"center\"><span style=\" font-size:13pt;\">Memoriza</span></p></body></html>", None))
self.lineEdit_valor_memorizar.setText(_translate("self", "", None))
self.label_tiempo_restante.setText(_translate("self", "Tiempo restante", None))
self.label_segundos_restantes.setText(_translate("self", "10 segundos", None))
self.label_racha.setText(_translate("self", "Racha", None))
self.label_valor_racha.setText(_translate("self", "0", None))
self.pushButton_comenzar.setText(_translate("self", "Comenzar", None))

class Timer(threading.Thread):

def __init__(self, parent=None):

threading.Thread.__init__(self, parent)

def run(self):

tiempo_restante = form_a.tiempo

for i in range(form_a.tiempo):
form_b.label_segundos_restantes.setText("%s segundos" % tiempo_restante)
tiempo_restante = tiempo_restante - 1
sleep(1)

form_b.label_segundos_restantes.setText("0 segundos")
form_b.lineEdit_valor_memorizar.setText("")
form_b.lineEdit_valor_memorizar.setReadOnly(False)
form_b.lineEdit_valor_memorizar.setFocus(True)

app = QtGui.QApplication(sys.argv)
form_b = formB()
form_a = formA()
form_a.show()
app.exec_()


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

Saludos, Javier.
#2
FUENTE ORIGINAL : No tienes permitido ver los links. Registrarse o Entrar a mi cuenta


Hola, muy buen día.

El código Javascript que publicaré más abajo se encarga de capturar todas las palabras dentro de algún elemento, clase o id. Nos creará un pequeño formulario "flotante", en el cuál nos pedirá "Longitud", "Veces", "Elemento" (Filtros).

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

¿ Que es eso de "Filtros"?
Los dos primeros son una especie de filtros, así mostramos resultados más específicos.

       
  • Longitud: Busca palabras con la longitud que tu deseas (&gt;=)
  • Veces: Cantidad de veces que aparece en la web
  • Elemento: Acá ingresamos en que elemento de la web deseamos buscar Las palabras más utilizadas. El script al usar jQuery, nos permite insertar en este campo ".clases", "#ids" o simplemente elementos como &lt;body&gt;
Una vez rellenes los campos, el programa te dará una salida con una tabla como esta:

Ejemplo basado en el portal de noticias No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
Sin más, el código:
Código: javascript
var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-latest.js';
document.getElementsByTagName('head')[0].appendChild(script);

var times_form;
var element_form;
var length_form;
var l_temp;
var dict = {};
var new_dict = {};
var splited = "";
var counter;
var get_data = function (text, length) {

splited = text.split(" ");

  for ( var a in splited ) {

if( dict[splited[a]] ) {

      splited[a] = splited[a].toLowerCase();
dict[splited[a]] = dict[splited[a]] + 1;
   
} else {
   
      if ( splited[a].length >= length ) {

      splited[a] = splited[a].toLowerCase();
        dict[splited[a]] = 1;
   
    }
   
    }
 
}
 
};

var extract = function (element, length, times) {

  new_dict = {};
  dict = {};
 
  $(element).each( function () {
 
  get_data($(this).text(), length);
 
});

  for ( var c in dict ) {
 
    if ( dict[c] >= times ) {
   
      new_dict[c] = dict[c];
   
    }
 
  } 

  var output = "<table border='1'>"+
      "<thead>"+
      "<th>Palabra</th>"+
      "<th>Longitud</th>"+
      "<th>Apariciones</th>"+
      "</thead>"+
      "<tbody>";
  counter = 0;
  for( var l in new_dict ) {

    counter++;
    l_temp = l.replace("<", "&lt;");
    l_temp = l_temp.replace(">", "&gt;");
    output = output + "<tr>"+
      "<td>" + l_temp + "</td><td>" + l.length + "</td><td>" + new_dict[l] + "</td>"+
      "</tr>";
   
  }
  output = output + "</tbody></table>";
 
  show_results(output);
  return new_dict;

};

var find = function (word) {

  if ( new_dict[word] ) {
 
  show_results(String(new_dict[word]));
 
  } else {
 
  show_results("Word Not found");
 
  }

};

var search = function () {

  length_form = $("input[name=length_craw]").val();
  times_form = $("input[name=times_craw]").val();
element_form = $("input[name=element_craw]").val();
  if( length_form.length > 0 && times_form.length > 0 && element_form.length > 0 ) {
 
    extract(element_form, length_form, times_form);
 
  }

};

var show_form = function () {

  $("<div class='show_words' style='border-radius:5px;box-shadow:0px 0px 10px #000;overflow:scroll;font-family:Trebuchet MS;width:auto;height:6cm;background-color:#fff;border:1px solid;position:fixed;top:12%;left:2%;padding:5px;z-index:30;'>"+
    "<center><h2>Palabras más utilizadas</h2></center><input style='padding: 2px;border: 1px solid;border-radius: 4px;margin: 4px;' name='length_craw' placeholder='Longitud'>&nbsp;<input style='padding: 2px;border: 1px solid;border-radius: 4px;margin: 4px;' name='times_craw' placeholder='Veces'><br/>"+
    "<input style='padding: 2px;border: 1px solid;border-radius: 4px;margin: 4px;' name='element_craw' placeholder='Elemento'>&nbsp;<button onclick='search()' style='padding: 2px;border: 1px solid;border-radius: 4px;margin: 4px;'>¡Buscar!</button>&nbsp;<button onclick='$(\".show_words\").fadeOut();' style='padding: 2px;border: 1px solid;border-radius: 4px;margin: 4px;'>Cerrar</button>"+
    "<div class='words_content'></div></div>").appendTo("body");

};

var show_results = function (content) {

  $(".words_content").html("Total:" + counter + "<br/>" + content);

};

show_form();


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



Sin más que agregar... gracias por leer :-)

Saludos, Javier.
#3
Python / [Python-CGI] PC Control Remoto - JaAViEr
Octubre 30, 2014, 04:55:20 AM
¿ Qué es PC Control Remoto ?

PC Control Remoto es un programa/web desarrollado bajo el lenguaje de programación Python en conjunto con su librería CGI, la cuál nos permitirá montar un servidor CGI y poder llevar acabo nuestro cometido.

Este programa nos permitirá acceder a nuestro computador forma remota, con tu Navegador favorito, conectado vía LAN o a Internet (configuración aparte), desde cualquier navegador. Las funciones que nos brinda son las siguiente:

       
  • Consola - Terminal remota: Puedes ejecutar cualquier comando y obtener su salida desde tu navegador.
       
  • Comándos rápidos: Entre estos comándos rápidos tenemos las posibilidad de:

         
    • Apagar PC. (60 segundos).
         
    • Reiniciar PC. (60 segundos).
         
    • Cancelar Apagado/Reinicio.
         
    • Matar un proceso.
         
    • Iniciar un proceso.
El programa en general se compone de:
Además de otros componentes como Topcoat (CSS), jQuery (JS).


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

Solo extraer en una carpeta y ejecutar No tienes permitido ver los links. Registrarse o Entrar a mi cuenta PUERTO

Adjunto el código de cada archivo Python mencionado anteriormente

server.py

Código: python
'''
Autor: JaAViEr
Twitter: @javieresteban__
Website: http://codigo.ga
'''
from CGIHTTPServer import CGIHTTPRequestHandler
from BaseHTTPServer import HTTPServer
import socket
import sys

try:

port = int(sys.argv[1])

if port:

ip_interna = socket.gethostbyname(socket.gethostname())
print "Panel de control: http://%s:%s/cgi-bin/index.py" % (ip_interna, port)
server_address=('', port)
httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_forever()

except:

print "-"*40
print "Uso:"
print sys.argv[0], "PUERTO"
print "-"*40
print "Ejemplo de uso:"
print sys.argv[0], "5050"
print "-"*40

Luego de No tienes permitido ver los links. Registrarse o Entrar a mi cuenta, deben pasar como parámatro el puerto al cual estará asociado el servidor.




index.py

Código: python
#-*- encoding:utf-8 -*-
'''
Autor: JaAViEr
Twitter: @javieresteban__
Website: http://codigo.ga
'''
import cgi
import os
import Cookie
import md5

lista_usuarios = ["admin", "JaAViEr"] #Usuarios
lista_passwords = ["root", "toor"] # Contraseñas
method = os.environ.get("REQUEST_METHOD")
logueado = False
contenido_cookies = os.environ.get('HTTP_COOKIE')

tag_head = ''' <meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/topcoat/css/topcoat-mobile-dark.min.css" class="uib-framework-theme">
<link rel="stylesheet" type="text/css" href="/css/index_main.less.css" class="main-less">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<style type="text/css">
/* Prevent copy paste for all elements except text fields */
*  { -webkit-user-select:none; -webkit-tap-highlight-color:rgba(255, 255, 255, 0); }
input, textarea  { -webkit-user-select:text; }
</style>
<script type="application/javascript" src="/js/jquery.min.js"></script>
<script type="application/javascript" src="/js/index_user_scripts.js"></script>'''

def code_login(accion=False):

if accion == 'error':

mensaje_error = '''
  <div class="topcoat-navigation-bar widget uib_w_1 d-margins" data-uib="topcoat/nav" data-ver="0">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Verifica tus credenciales por favor[/size][/center]
</div>
  </div>
'''

else:

mensaje_error = ''

return '''
<!DOCTYPE html>
<html>

  <head>
''' + tag_head + '''
<title>Indetifícate en el sistema</title>
  </head>

  <body>
    <div class="uwrap">
      <div class="upage" id="mainpage">
        <div class="upage-outer">
          <div class="upage-content" id="mainsub">

            <div class="grid grid-pad urow uib_row_2 row-height-2" data-uib="layout/row" data-ver="0">
              <div class="col uib_col_2 col-0_12-12" data-uib="layout/col" data-ver="0">
                <div class="widget-container content-area vertical-col">

                  <div class="topcoat-navigation-bar widget uib_w_1 d-margins" data-uib="topcoat/nav" data-ver="0">
                    <div class="topcoat-navigation-bar__item center full">
                      <h1 class="topcoat-navigation-bar__title">Indentifícate[/size][/center]
                    </div>
                  </div>
                  <span class="uib_shim"></span>
                </div>
              </div>
              <span class="uib_shim"></span>
            </div>

            <div class="grid grid-pad urow uib_row_3 row-height-3" data-uib="layout/row" data-ver="0">

<form action="" method="POST">
<div class="col uib_col_3 col-0_12-12" data-uib="layout/col" data-ver="0">
<div class="widget-container content-area vertical-col">
<div class="table-thing widget uib_w_2 d-margins" data-uib="topcoat/input" data-ver="0">
<label class="narrow-control label-top-left">Usuario</label>
<input class="wide-control topcoat-text-input" type="text" placeholder="Usuario" name="usuario">
</div>
<div class="table-thing widget d-margins" data-uib="topcoat/input" data-ver="0">
<label class="narrow-control label-top-left">Contraseña</label>
<input class="wide-control topcoat-text-input" type="password" placeholder="Contraseña" name="password">
</div>
<button class="widget d-margins topcoat-button--cta" data-uib="topcoat/button" data-ver="0">Ingresar</button><span class="uib_shim"></span>
</div>
''' +mensaje_error+ '''
</form>
              </div>
              <span class="uib_shim"></span>
            </div>
          </div>
          <!-- /upage-content -->

        </div>
        <!-- /upage-outer -->

      </div>
      <!-- /upage -->

    </div>
    <!-- /uwrap -->
  </body>

</html>'''

code = '''<!DOCTYPE html>
<!--HTML5 doctype-->
<html>

<head>
''' + tag_head + '''
<title>Control Remoto :: 2014</title>
</head>

<body>
<!-- content goes here-->
<div class="uwrap">
<div class="upage" id="mainpage">
<div class="upage-outer">
<div class="upage-content" id="mainsub">

<div class="grid grid-pad urow uib_row_1 row-height-1" data-uib="layout/row" data-ver="0">
<div class="col uib_col_2 col-0_12-12" data-uib="layout/col" data-ver="0">
<div class="widget-container content-area vertical-col">

<div class="topcoat-navigation-bar widget uib_w_2 d-margins" data-uib="/topcoat/nav" data-ver="0">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Panel de Control Remoto[/size][/center]
</div>
</div>
<button class="widget uib_w_4 d-margins topcoat-button--large--cta" data-uib="/topcoat/button" data-ver="0">Consola - Terminal</button>
<button class="widget uib_w_3 d-margins topcoat-button--large--cta" data-uib="/topcoat/button" data-ver="0">Enviar comando rápido</button>
<button class="widget uib_w_5 d-margins topcoat-button--large" onclick='location.href="logout.py"' data-uib="/topcoat/button" data-ver="0">Salir</button>
<span class="uib_shim"></span>
</div>
</div>
<span class="uib_shim"></span>
</div>

</div>
<!-- /upage-content -->

</div>
<!-- /upage-outer -->

</div>
<div class="upage hidden" id="uib_page_3">
<div class="upage-outer">
<div id="uib_page_3sub" class="upage-content ">
</div>
</div>
<!-- /upage-outer -->
te </div>
<div class="upage hidden" id="uib_page_2">
<div class="upage-outer">
<div id="uib_page_2sub" class="upage-content ">
</div>
</div>
<!-- /upage-outer -->
</div>
<div class="upage hidden" id="uib_page_1">
<div class="upage-outer">
<div id="uib_page_1sub" class="upage-content ">
</div>
</div>
<!-- /upage-outer -->
</div>

<!-- /upage -->

</div>
<!-- /uwrap -->
</body>

</html>'''

def verificar_login(u, p):

if u in lista_usuarios and p in lista_passwords:

session = u + p
session = md5.md5(session).hexdigest()
return True

else:

return False

if contenido_cookies: #Si hay cookies...

valores_cookie = Cookie.SimpleCookie(contenido_cookies)
session_actual = valores_cookie['sess'].value # session_actual = cookie "sess"

if session_actual == "false": # No logueado

logueado = False

else: # Verifica login

for a, b in zip(lista_usuarios, lista_passwords):

session_temporal = a + b
session_temporal = md5.md5(session_temporal).hexdigest()

if session_actual == session_temporal:

logueado = True # Login coincide
break

else:

pass

else: #No logueado, sess = false

print "Set-Cookie:sess=false"

print "Content-Type: text/html"

if method == "POST":

form = cgi.FieldStorage()
usuario = form.getvalue('usuario')
password = form.getvalue('password')

if verificar_login(usuario, password):

session = usuario + password
session = md5.md5(session).hexdigest()
print "Set-Cookie:sess=%s" % session
print
print code

else:

print
print code_login('error')

elif method == "GET":

if not logueado:

print code_login()

else:

print code


terminal.py

Código: python
#-*- encoding:utf-8 -*-
'''
Autor: JaAViEr
Twitter: @javieresteban__
Website: http://codigo.ga
'''
import cgi
import os
import Cookie
import md5

print "Content-Type: text/html"
print

code_terminal = '''
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" type="text/css" href="/topcoat/css/topcoat-mobile-dark.min.css" class="uib-framework-theme">
    <link rel="stylesheet" type="text/css" href="/css/terminal_main.less.css" class="main-less">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<title>Terminal</title>
    <script src="/js/jquery.min.js"></script>
  </head>

  <body>
    <div class="uwrap">
      <div class="upage" id="mainpage">
        <div class="upage-outer">
          <div class="upage-content" id="mainsub">

            <div class="grid grid-pad urow uib_row_1 row-height-1" data-uib="layout/row" data-ver="0">
              <div class="col uib_col_1 col-0_12-12" data-uib="layout/col" data-ver="0">
                <div class="widget-container content-area vertical-col">

                  <div class="topcoat-navigation-bar widget uib_w_1 d-margins" data-uib="/topcoat/nav" data-ver="0">
                    <div class="topcoat-navigation-bar__item center full">
                      <h1 class="topcoat-navigation-bar__title">Consola - Terminal[/size][/center]
                    </div>
                  </div>
                  <div class="table-thing widget uib_w_2 d-margins" data-uib="/topcoat/textarea" data-ver="0">
                    <label class="narrow-control label-inline"></label>
                    <textarea class="wide-control topcoat-textarea" type="text" placeholder="Comandos" name="comando"></textarea>
                  </div>
<button class="widget uib_w_2 d-margins topcoat-button--cta" data-uib="topcoat/button" data-ver="0" onclick='execute();'>¡Ejecutar!</button>
<button class="widget uib_w_2 d-margins topcoat-button" data-uib="topcoat/button" data-ver="0" onclick='location.href="index.py"'>Volver</button>
<hr>
Salida:
<span id="loader"></span>
                  <span class="uib_shim"></span>
                </div>
              </div>
              <span class="uib_shim"></span>
            </div>
          </div>
          <!-- /upage-content -->

        </div>
        <!-- /upage-outer -->

      </div>
      <!-- /upage -->

    </div>
    <!-- /uwrap -->
<script language="JavaScript">

function execute(){

comando = $("textarea[name=comando]").val();
$("#loader").load("terminal.py", {"comando":comando});

}
</script>
  </body>

</html>'''

logueado = False
lista_usuarios = ["admin", "JaAViEr"] #Usuarios
lista_passwords = ["root", "toor"] # Contraseñas
method = os.environ['REQUEST_METHOD']
lectura_cookies = os.environ.get('HTTP_COOKIE')

if lectura_cookies:

valores_cookie = Cookie.SimpleCookie(lectura_cookies)
session_actual = valores_cookie['sess'].value # session_actual = cookie "sess"

if session_actual != "false":

for a, b in zip(lista_usuarios, lista_passwords):

session_temporal = a + b
session_temporal = md5.md5(session_temporal).hexdigest()

if session_actual == session_temporal:

logueado = True # Login coincide
break

else:

pass
else:

pass

if logueado:
if method == "GET":

print code_terminal

elif method == "POST":

form = cgi.FieldStorage()
comando = form.getvalue("comando")
lineas = comando.split("\n")
print '''
<span  style="font-family:Trebuchet Ms; color: #fff;" class="wide-control">
<br />
'''
for l in lineas:

try:

run = os.popen(l, "r")
run_content = run.read()
run_content = run_content.replace("\n", "<br>")
run_content = run_content.replace(" ", "&nbsp;")
print run_content
run.close()

except:

print "Error al ejecutar comando %s" % (l)

print "</span>"
else:
print "<script>location.href='index.py';</script>"

comando_rapido.py
Código: python
#-*- encoding:utf-8 -*-
'''
Autor: JaAViEr
Twitter: @javieresteban__
Website: http://codigo.ga
'''
import cgi
import os
import subprocess
import Cookie
import md5

print "Content-Type: text/html"
print
code_terminal = '''
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" type="text/css" href="/topcoat/css/topcoat-mobile-dark.min.css" class="uib-framework-theme">
    <link rel="stylesheet" type="text/css" href="/css/terminal_main.less.css" class="main-less">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<title>Comandos rápidos</title>
    <script src="/js/jquery.min.js"></script>
  </head>

  <body>
    <div class="uwrap">
      <div class="upage" id="mainpage">
        <div class="upage-outer">
          <div class="upage-content" id="mainsub">

            <div class="grid grid-pad urow uib_row_3 row-height-3" data-uib="layout/row" data-ver="0">
              <div class="col uib_col_3 col-0_12-12" data-uib="layout/col" data-ver="0">
                <div class="widget-container content-area vertical-col">

                  <div class="topcoat-navigation-bar widget uib_w_1 d-margins" data-uib="topcoat/nav" data-ver="0">
                    <div class="topcoat-navigation-bar__item center full">
                      <h1 class="topcoat-navigation-bar__title">Comandos rápidos[/size][/center]
                    </div>
                  </div>
                  <span class="uib_shim"></span>
                </div>
              </div>
              <span class="uib_shim"></span>
            </div>

            <div class="grid grid-pad urow uib_row_4 row-height-4" data-uib="layout/row" data-ver="0">
              <div class="col uib_col_4 col-0_12-12" data-uib="layout/col" data-ver="0">
                <div class="widget-container content-area vertical-col">

<button class="widget uib_w_2 d-margins topcoat-button--cta" data-uib="topcoat/button" data-ver="0" onclick="comando('apagar'); return false;">Apagar</button>
<button class="widget uib_w_3 d-margins topcoat-button--cta" data-uib="topcoat/button" data-ver="0" onclick="comando('reiniciar'); return false;">Reiniciar</button>
<button class="widget uib_w_4 d-margins topcoat-button--cta" data-uib="topcoat/button" data-ver="0" onclick="comando('cancelar salida'); return false;">Cancelar Apagado/Rein.</button>
<button class="widget uib_w_5 d-margins topcoat-button--cta" data-uib="topcoat/button" data-ver="0" onclick="matar_proceso('mostrar'); return false;">Matar proceso</button>
<span id="matar_proceso" style="display:none">
<hr>
<input class="wide-control topcoat-text-input" type="text" placeholder="proceso.ext" name="proceso">
<button class="widget uib_w_6 d-margins topcoat-button wide-control" data-uib="topcoat/button" data-ver="0" onclick="matar_proceso('kill'); return false;">¡Matar ahora!</button>
<hr>
</span>
<button class="widget uib_w_6 d-margins topcoat-button--cta" data-uib="topcoat/button" data-ver="0" onclick="iniciar_proceso('mostrar'); return false;">Iniciar proceso</button>
<span id="iniciar_proceso" style="display:none">
<hr>
<input class="wide-control topcoat-text-input" type="text" placeholder="proceso.ext" name="iniciar_proceso">
<button class="widget uib_w_6 d-margins topcoat-button wide-control" data-uib="topcoat/button" data-ver="0" onclick="iniciar_proceso('iniciar'); return false;">¡Iniciar ahora!</button>
<hr>
</span>
<button class="widget uib_w_2 d-margins topcoat-button" data-uib="topcoat/button" data-ver="0" onclick='location.href="index.py"'>Volver</button>
  <span class="uib_shim"></span>
 
                </div>
              </div>
              <span class="uib_shim"></span>
            </div>
          </div>
          <!-- /upage-content -->

        </div>
        <!-- /upage-outer -->

      </div>
      <!-- /upage -->

    </div>
    <!-- /uwrap -->
  </body>
  <span id="loader" style="display:none;"></span>
  <script language="JavaScript">
 
  function comando(cmd){
 
$("#loader").load("comando_rapido.py", {"comando":cmd});
 
  }
  function matar_proceso(param){
 
if(param == 'mostrar'){
$("#matar_proceso").fadeIn();
$("#iniciar_proceso").fadeOut();
}else if(param == 'kill'){
proceso = $("input[name=proceso]").val();
$("#loader").load("comando_rapido.py", {"kill": proceso});
$("#matar_proceso").fadeOut();
$("input[name=proceso]").val("");
}
  }
 
  function iniciar_proceso(accion){
 
  if (accion == "mostrar"){
 
$("#matar_proceso").fadeOut();
$("#iniciar_proceso").fadeIn();

  }else if(accion == "iniciar"){
 

nuevo_proceso = $("input[name=iniciar_proceso]").val();
$("#loader").load("comando_rapido.py", {"correr": nuevo_proceso});
$("#iniciar_proceso").fadeOut();
$("input[name=iniciar_procesoproceso]").val("");
 
  }
 
  }
  </script>


</html>'''

logueado = False
lista_usuarios = ["admin", "JaAViEr"] #Usuarios
lista_passwords = ["root", "toor"] # Contraseñas
method = os.environ['REQUEST_METHOD']
lectura_cookies = os.environ.get('HTTP_COOKIE')
if lectura_cookies:
valores_cookie = Cookie.SimpleCookie(lectura_cookies)
session_actual = valores_cookie['sess'].value # session_actual = cookie "sess"

if session_actual != "false":
for a, b in zip(lista_usuarios, lista_passwords):

session_temporal = a + b
session_temporal = md5.md5(session_temporal).hexdigest()

if session_actual == session_temporal:
logueado = True # Login coincide
break

else:

pass
else:

pass

if logueado:
if os.name == "nt":

so = "windows"

else:

so = "unix"

if method == "GET":

print code_terminal

elif method == "POST":

form = cgi.FieldStorage()
comando = form.getvalue("comando")
kill = form.getvalue("kill")
correr = form.getvalue("correr")
iniciar_proceso = ""
matador = ""

try:

if correr:

if so == "windows":

iniciar_proceso = "start %s" % (correr)

elif so == "unix":

iniciar_proceso = "%s" % (correr)

subprocess.call(iniciar_proceso)

if kill:

if so == "windows":

matador = "taskkill /F /IM %s" % (kill)

elif so == "unix":

matador = "pkill -9 %s" % (kill)

kill = subprocess.call(matador)
kill.close()

if comando == "apagar":

if so == "windows":

accion = "shutdown /S /T 60"

elif so == "unix":

accion = "sudo poweroff"


elif comando == "reiniciar":

if so == "windows":

accion = "shutdown /R /T 60"

elif so == "unix":

accion = "sudo reboot"

#accion = ""

elif comando == "cancelar salida":

if so == "windows":

accion = "shutdown /A"

elif so == "unix":

accion = ""

#accion = ""


action = subprocess.call(accion)
action.close()
except:

pass

else:
print "<script>location.href='index.py';</script>"

logout.py

Código: python
import cgi
'''
Autor: JaAViEr
Twitter: @javieresteban__
Website: http://codigo.ga
'''
print "Content-Type: text/html"
print "Set-Cookie: sess=false"
print "Location:index.py"
print
print "<script>location.href='index.py';</script>"


Un par de Screenshots de como luce el programa...
Identificación
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
Panel de control
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
Consola-Terminal Remota
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
Comando rápidos
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
Comandos rápidos - Iniciar Proceso
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
Comandos rápidos - Matar Proceso
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta


Fuente Original: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
#4
Python / [Python] Utilizando orientación a objetos [2]
Septiembre 27, 2014, 03:27:20 AM
Heredando Clases
Veamos... La Herencia en Python es de lo más sencillo que puede haber (Si lo comparas con otros lenguajes). Veamos un ejemplo en código:
Código: python

class Clase_A:
 
    def __init__(self):
     
      pass
   
    def funcion_a(self):
       
        print "FUNCION DE CLASE_A"

class Clase_B(Clase_A):
 
  pass

Bien, tenemos "Clase_A", dentro tiene la función "funcion_a", que solo imprime "FUNCION DE CLASE_A".
Para que la Clase "Clase_B" pueda heredar la función "funcion_a"(Originaria de la  Clase_A) debemos añadir entre paréntesis la clase que vamos a heredar:
Código: python

class Clase_B(Clase_A):

Con eso ya le indicamos a Python que Clase_B heredará todo lo que hay en Clase_A, por lo que ahora podemos crear una instancia de Clase_B y llamar a la función funcion_a tranquilamente.

Creemos la instancia para la Clase Clase_B:
Código: python
c=Clase_B()

Ahora podemos acceder a funcion_a (De Clase_A) con nuestra instancia de Clase_B.
Código final:
Código: python

class Clase_A:
 
    def __init__(self):
     
      pass
   
    def funcion_a(self):
       
        print "FUNCION DE CLASE_A"

class Clase_B(Clase_A):
 
  pass

c=Clase_B()
c.funcion_a()

Output:
Código: php

FUNCION DE CLASE_A

Utilizando variables en Clases
Quise escribir un poco sobre esto porque recuerdo que yo tuve problemas con esto y no lo entendí hasta que le metí manos al código. Así que espero se entienda.

Cuando creamos una Función dentro de una Clase y declaramos alguna variable, esta variable va a ser accesible solo desde la Función en la cuál fue creada, veamos un ejemplo:
Código: python
class Ejemplo:
 
  def funcion_saludo(self, nombre):
   
    print "Hola,", nombre
   
  def funcion_despedida(self):
   
    print "Hasta luego,", nombre

instancia=Ejemplo()
instancia.funcion_saludo("Javier")
instancia.funcion_despedida()

Como te habrás fijado, en la Función funcion_saludo hemos pasado el parámetro "nombre", para luego imprimirlo, pero si queremos acceder a la variable "nombre" desde la Función funcion_despedida nos arrojará un error pues nos dirá que la variable "nombre" no ha sido definida.
Entonces... ¿ Como accedo a esa variable? ¡Es realmente sencillo !

Para que puedas acceder a una variable desde toda una Clase y no solo desde la función donde se definió, debes crear una variable con el prefijo "self.", veamos el caso anterior, pero esta vez con el prefijo "self.nombre":
Código: python
class Ejemplo:
 
  def funcion_saludo(self, nombre):
   
    self.nombre=nombre
    print "Hola,", self.nombre # O print "Hola,", nombre
   
  def funcion_despedida(self):
   
    print "Hasta luego,", self.nombre

instancia=Ejemplo()
instancia.funcion_saludo("Javier")
instancia.funcion_despedida()
'''La Funcion funcion_despedida no necesita
parametro, pues utilizaremos el mismo
valor de la Funcion funcion_saludo.'''

Como puedes ver, hemos declarado que self.nombre=nombre, así podremos acceder a la variable "nombre" de una manera global (gracias a la magia del "self.") a lo largo de nuestra Clase, sin tener que estar pasando parámetros a cada función y re-utilizando datos ya ingresados en otras funciones.

Fuente: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
#5
Python / [Python] Utilizando orientación a objetos [1]
Septiembre 27, 2014, 03:17:52 AM
No vamos a ver en profundo los conceptos sobre orientación a objetos e iremos directamente al código. Se comentará más o menos lo primordial.

De primera veremos:

       
  • Estructura de una Clase.
       
  • Añadir funciones personalizadas a una Clase.
       
  • Llamar funciones insertas en una Clase.
Estructura de una clase
Código: python

class Mi_Clase:
 
  def __init__(self):

      print "Mi_Clase inicializada!"   

inicializar=Mi_Clase()

Declaramos la clase Mi_Clase. Dentro de toda clase está la posibilidad de añadir la función __init__, que tiene por "tarea" ejecutar todo el código que esté dentro de la función al momento en que se crea una instancia sobre la Clase que lo contiene.

En este caso, al invocar a "Mi_Clase":
Código: python
inicializar=Mi_Clase()

Ya por defecto hemos llamado también a la función __init__

Nota: Cada función que añadas dentro de tus Clases debe siempre llevar el parámetro self y luego separado de comas, los parámetros de tu función.

Añadiendo funciones una clase
Añadir una función a nuestra clase es tan sencillo como seguir la estructura del mismo __init__, obviamente que con un nombre diferente.
Por ejemplo:
Código: python
class Mi_Clase:
 
  def __init__(self):

      print "Mi_Clase inicializada!"   
 
  def saludar(self, nombre):
   
      return "Bienvenido %s !" % nombre

inicializar=Mi_Clase()

Hemos añadido la función saludar(). Para acceder a aquella función debes recurrir a la instancia que creaste sobre la Clase, en este caso llamada inicializar, por lo tanto para utilizar dicha función nos queda algo como esto:
Código: python

inicializar.saludar("Javier")

Recordemos que...
Código: python

inicializar=Mi_Clase()

Por lo que
Código: text

inicializar.saludar("Javier") Es el equivalente a decir Mi_Clase().saludar("Javier")

Accediendo a funciones de una Clase
Código: python
class Mi_Clase:
 
  def __init__(self):

      print "Mi_Clase inicializada!"   
 
  def saludar(self, nombre):
   
      return "Bienvenido %s !" % nombre

inicializar=Mi_Clase()
print inicializar.saludar("Javier")

Output:
Código: text

Mi_Clase inicializada!
Bienvenido Javier !


En la segunda parte veremos:

       
  • Como utilizar la Herencia en nuestra Clase
       
  • Como utilizar variables dentro de una Clase

Fuente: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
#6
Off Topic / [Dato]BTC Cloud Mining - FUNCIONANDO
Julio 13, 2014, 11:36:10 PM
Hola, muy buenos días.

Hace unos días me topé con un servicio de No tienes permitido ver los links. Registrarse o Entrar a mi cuenta, el cuál nos permite minar BTC sin tener que comprar algún tipo de Hardware, solo invirtiendo BTC en GHS (Potencia) , los BTC minados son depositados a tu cuenta y puedes re-invertir lo ganado en más potencia, lo que obviamente se traduce en mayor cantidad de GHS = Mayor cantidad de ganancias en BTC.

¡ Se los recomiendo a toda costa !

Una vez que adquieres GHS , el proceso de minado comienza automáticamente.

Luego de No tienes permitido ver los links. Registrarse o Entrar a mi cuenta vas a "Balance" y puedes hacer depósitos en BTC a la cuenta que se te ha asignado, de esa forma puedes invertir tus BTC en más GHS.

Saludos, Javier.
#7
( Fuente: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta )

Si estás usando OpenCart y te diste cuenta que todo estaba en inglés no solo en el Inicio, sino que también en tu Panel de Administración, te recomiendo seguir leyendo esta entrada para aprender paso a paso como pasar de Inglés a Español.

Para poder traducir tu tienda, debes descargar el parche de idioma español primero, el cuál puedes No tienes permitido ver los links. Registrarse o Entrar a mi cuenta.


Agregando un nuevo idioma
Bien, una vez que ya tengamos el parche en nuestro computador, lo subiremos vía FTP a nuestro servidor, recuerda extraer el archivo No tienes permitido ver los links. Registrarse o Entrar a mi cuenta en la raíz de tu tienda, por ejemplo una tienda alojada en No tienes permitido ver los links. Registrarse o Entrar a mi cuenta , extraería el contenido del zip en /public_html/www/demo/.


Entramos en nuestro Panel de Administración OpenCart (/admin) y nos dirigimos de inmediato a System / Localisation / Languages :

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

Dentro nos encontraremos con esto:

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

Damos clic en Insert, una vez dentro te pedirá rellenar una información, tal cual la siguiente imagen (por favor rellena con los mismos datos que aparecen):

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

Una vez hayas rellenado todo el formulario, guarda la configuración dando clic en Save (Esquina superior derecha).


Configurando el idioma principal
Bien, ya hemos añadido el idioma Español a nuestra tienda, ahora vamos a configurar nuestra preferencia, dejando el español como idioma principal. Para aquello nos tenemos que dirigir al menú System / Settings, ya dentro de dicha opción nos devolverá:

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

A lo que daremos clic en Edit en la tienda que desean configurar para idioma español, Your Store en mi caso .

Ahora que estamos dentro nos vamos a la pestaña Local:

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

Y cambiamos Language y Administration Language por:

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

Una vez hecho esto damos nuevamente clic en Save y nuestra tienda y panel de administración han sido correctamente configurados al idioma español.

¿  Sencillo no ?

Ante cualquier consulta no dudes en exponerla comentando esta entrada, con gusto intentaremos ayudarte.

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

Saludos, Javier.
#8
(Fuente original No tienes permitido ver los links. Registrarse o Entrar a mi cuenta)

Hola !

En esta oportunidad veremos como utilizar Goolgle Analytics con WordPress. ¡ Vamos directo al grano !


¿ Cómo lo hago ?

Primero que todo, si no tienes una cuenta en Google Analytics, puedes asociar tu cuenta de Gmail No tienes permitido ver los links. Registrarse o Entrar a mi cuenta .
Ya asociada nuestra cuenta, tendremos que rellenar un formulario con datos sobre nuestro sitio web, aceptar las políticas de uso y privacidad. Posterior a eso, nos dirigimos a Administrador y veremos esto:

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

Cuando des clic en Código de seguimiento tendrás que copiar tu ID:


(Obviamente con tu propio ID, en este caso mi id es UA-49848020-1)


¿ Dónde encuentro el plugin ?

Puedes descargar el plugin desde No tienes permitido ver los links. Registrarse o Entrar a mi cuenta


Instalando plugin

Una vez completada la descarga del plugin, vamos a nuestro panel de administración (/wp-admin) y ubicamos en nuestro menú Plugins / Añadir nuevo, donde nos encontraremos con esto:
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

En Subir nos pedirá buscar el plugin en formato .zip

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

Damos clic en "Instalar Ahora"...
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Configurando el plugin


Una vez instalado el plugin tenemos que configurarlo, ahora es cuando entra en juego tu ID de Seguimiento.
Vamos a Ajustes / Google Analytics...


Pegamos nuestro ID de seguimiento en el recuadro y le damosNo tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Una vez finalizados estos pasos, al ingresar en tu cuenta de Google Analytics podrás ver los informes generados por las visitas a tu blog.

¡ Espero haya sido de utilidad ! Recuerda que ante cualquier consulta , no dudes en dejarla en nuestros comentarios .

Saludos, Javier.
#9
Hola, muy buenos días !

En esta oportunidad vengo a presentar un mini proyecto que estoy iniciando con mucho entusiasmo, espero algunas personas se animen y ayuden a expandir este módulo ! . Sin más preámbulos...



¿ Qué es PyDB ?

PyDB es un módulo que te ayudará a crear Bases de Datos a partir de archivos de texto, siempre y cuando estos archivos contengan una estructura legible para PyDB


¿ Dónde descargo el módulo ?

El enlace para descargar el módulo es No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
En el mismo README.txt está la documentación de cada función del PyDB, como se utilizan y los parámetros que le deben pasar a cada función.

Funciones :

  • Añadir valor. (En SQL -> INSERT INTO)
  • Eliminar valor. (En SQL -> DELETE FROM tabla WHERE columna=valor)
  • Actualizar valor (En SQL -> UPDATE)
  • Ver Tabla.
  • Consultar valor (En SQL -> SELECT campo FROM tabla)
  • Ver columnas de tabla .
¿ Cuál es la estrucutra de la Base de Datos ?
Base_Datos.Txt :
Código: php

Tabla(columna1, columna2){
    columna1=Contenido columna1; columna2=Contenido columna2;
}
Personas(nombre, edad, correo){
    nombre=Javier Guajardo; edad=19; [email protected];
    nombre=Juan Andres; edad=25; [email protected];
}

Ejemplo de login con PyDB , disponible para la descarga en No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Nota: Recuerda tener el módulo No tienes permitido ver los links. Registrarse o Entrar a mi cuenta en la misma carpeta de donde invocarás el archivo.

Espero sus más sinceras opiniones !

Saludos, Javier.
#10
Python / Tools Python CGI + Source | JaAViEr::0x5d
Abril 23, 2013, 10:13:29 PM
Hola, buen día damas y caballeros :P.

En esta ocasión vengo a mostrar el código de fuente de unas aplicaciones que pasé a Python CGI , para poder ejecutarlas en el servidor y no depender de una maquina con Python instalado...


Sus respectivos códigos de fuente...
De/Codificador Base64:
Código: python

#!/usr/bin/python
#Autor: 0x5d::JaAViEr
#Twitter: @0x5d
import cgi, os, base64

def form_inicial():
form_html = '''
<form action="" method="POST">
<textarea name="content"></textarea><br />
<select name="option">
<option value="encode">Codificar</option>
<option value="decode">Decodificar</option>
</select><br />
<input type="Submit" value="Enviar"><br />
Creado bajo Python CGI.<br />
Autor : JaAViEr (0x5d)
</form>'''
return base("De/Codificar Base64", form_html)

def base(title, content):
code = '''
<div class="ui-widget-content">
<div class="ui-widget-header">%s</div>
%s
</div>
'''%(title, content)
return code

print "content-type:text/html\r\n\r\n"

print '''
<title>De/Codificador Base64</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/cupertino/jquery-ui.css" />
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css" />
<style>
div {
text-align:center;
font-size:0.5cm;
}
input, select {
height:0.7cm;
font-size:0.4cm;
}
</style>
'''

form = cgi.FieldStorage()
opcion = form.getvalue("option")
texto = form.getvalue("content")
method = os.environ['REQUEST_METHOD']
if method == "POST":
if opcion:
if opcion == "encode":
print form_inicial()
print base("Salida", "<textarea>"+cgi.escape(base64.b64encode(texto))+"</textarea>")
elif opcion == "decode":
print form_inicial()
print base("Salida", "<textarea>"+cgi.escape(base64.b64decode(texto))+"</textarea>")
else:
print form_inicial()
print base("Error", "Opción incorrecta")
else:
print form_inicial()
print base("Error", "Por favor selecciona una opción")
else:
print form_inicial()


Cifrar Rot13 / Atbash:
Código: python

#!/usr/bin/python
#Autor: 11Sep
#To CGI: 0x5d::JaAViEr
#Twitter: @0x5d
import cgi, os

def  formulario_inicial():
form_html = '''
<form action="" method="POST">
Data: <br/>
<textarea name="contenido"></textarea><br />
<select name="opcion">
<option value="rot13">ROT13</option>
<option value="atbash">Atbash</option>
</select><br />
<input type="Submit"><br/>
Programado por <b>11Sep</b><br />
Programado en CGI por <b>JaAViEr::0x5d</b>
</form>
'''
return base("Cifrar Rot13/Atbash", form_html)

def base(title, content):
code = '''
<div class="ui-widget-content">
<div class="ui-widget-header">%s</div>
%s
</div>
'''%(title, content)
return code

def rot13(palabra):
    Cifrado = ''
    for i in palabra:
        buff = ord(i)
        if (buff >= 65 and buff <= 90) or (buff >= 97 and buff <= 122):
            if ((buff + 13 > 90 and buff + 13 <= 103) or (buff + 13 > 122 and buff + 13 <= 135)):
                Cifrado += chr(buff -13)
            else:
                Cifrado += chr(buff + 13)
    return Cifrado
   
def atbash(palabra):
    V1 = "abcdefghijklm"
    V2 = "zyxwvutsrqpon"
   
    Buff = ""
   
    for i in range(len(palabra)):
        for a in range(len(V1)):
            if V1[a] == palabra[i]:
                Buff += V2[a]
            elif V2[a] == palabra[i]:
                Buff += V1[a]
    return Buff

print "content-type:text/html\r\n\r\n"
print '''
<title>Cifrar Rot13/Atbash 11Sep::JaAViEr</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/blitzer/jquery-ui.css" />
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css" />
<style>
div {
text-align:center;
font-size:0.5cm;
}
input, select {
height:0.7cm;
font-size:0.4cm;
}
</style>
'''
form = cgi.FieldStorage()
method = os.environ['REQUEST_METHOD']
contenido = form.getvalue("contenido")
opcion = form.getvalue("opcion")
if method == "POST":
if opcion:
if opcion == "rot13":
print formulario_inicial()
print base("Salida", "<textarea>"+rot13(contenido)+"</textarea>")
elif opcion == "atbash":
print formulario_inicial()
print base("Salida", "<textarea>"+atbash(contenido)+"</textarea>")
else:
print formulario_inicial()
print base("ERROR","Opción inválida")
else:
print formulario_inicial()

Enviar peticiones POST:
Código: python

#!/usr/bin/python
#Autor: 0x5d::JaAViEr
#Twitter: @0x5d
import cgi, os, urllib, sys

def base(title, content):
code = '''
<div class="ui-widget-content">
<div class="ui-widget-header">%s</div>
%s
</div>
'''%(title, content)
return code

print "content-type:text/html\r\n\r\n"
print '''
<title>Enviar datos POST online :: JaAViEr(0x5d)</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/cupertino/jquery-ui.css" />
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<link rel="stylesheet" href="http://jqueryui.com/resources/demos/style.css" />
<style>
div {
text-align:center;
font-size:0.5cm;
}
input, select {
height:0.7cm;
font-size:0.4cm;
}
</style>
'''
form = cgi.FieldStorage()
method = os.environ['REQUEST_METHOD']
campos = form.getvalue("campos")
valores = form.getvalue("valores")
url = form.getvalue("url")
if method == "POST":
dic = {}
if not "http://" in url:
  print base("ERROR!","No se puede conectar a %s<br/><a href='send_post.py'>Volver</a>"%cgi.escape(url))
  sys.exit(1)
if len(campos)>0 and len(valores)>0:
for d,i in zip(campos.split(),valores.split(":-:")):
dic['%s'%d] = i
try:
print urllib.urlopen(url, urllib.urlencode(dic)).read()
except:
print "No se puede conectar a", cgi.escape(url)
else:
form_html = '''
<form action="" method="POST">
URL: <input type="Text" name="url" value="http://"><br />
Campos (separados por un espacio): <input type="Text" name="campos"><br />
Campos (separados por ":-:"): <input type="Text" name="valores"><br />
<input type="Submit"><br/>
Funcionando bajo Python CGI<br />
Author: <u>JaAViEr::0x5d</u>
</form>
'''
print base("ENVIAR DATOS POR POST", form_html)
form_example = '''
URL: <input type="Text" name="url" value="http://web.com/login.php" disabled><br />
Campos (separados por un espacio): <input type="Text" name="campos" value="user password" disabled><br />
Campos (separados por ":-:"): <input type="Text" name="valores" value="0x5d:-:miclave123" disabled><br />
<input type="Submit" onclick=alert("TEST");><br/>
'''
print base("Ejemplo de uso", form_example)


Fuente: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
   
Saludos , Javier.
#11
Hola, buen día.

Creo que me presenté hace como unos años... Pero veo tanto usuario nuevo que nadie me debe conocer por acá(y dudo que por otros lados). Mi nombre es Javier, nick JaAViEr ó 0x5d (@0x5d - Twitter), programador amante de Python (<3), a ratos me da por programar un PHP (+jQuery) + Python y a veces sale algo guapo. Soy Chileno(decorazón) , tengo 19 años :D

Espero verlos por Python colegas.

Saludos.
#12
Hola, buen día.
Voy al grano :P El primer código que les mostraré extrae las imágenes del sitio ingresado.
Mientras que el segundo extraerá los links y el nombre del link.
Código: python

# Autor: JaAViEr (0x5d)
# Twitter: 0x5d
var = urllib.urlopen(raw_input("URL :: > ")).read()
url_imagenes = []
clear = ""
for imagen in re.findall("<img (.*)>",var):
  if "src" in imagen.lower():
    for imagenes in imagen.split():
      if re.findall("src=(.*)",imagenes):
    clear = imagenes[:-1].replace("src=\"","")
    url_imagenes.append(clear.replace("src='",""))
print "Imágenes:"
for salida in url_imagenes:
  print salida

Extractor de links:
Código: python

# Autor: JaAViEr (0x5d)
# Twitter: 0x5d
var = urllib.urlopen(raw_input("URL ::>")).read()
limpiando = ""
enlaces = []
nuevos = []
for url,nombre in re.findall("<a (.*)>(.*)</a>",var):
  if "href" in url.lower():
    for a in url.split():
      if re.findall("href=(.*)",a):
    limpiando = a[:-1].replace("href=\"","")
    enlaces.append("%s -> %s"%(limpiando,nombre))
for i in enlaces:
  if i not in nuevos:
    nuevos.append(i)
    print i

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

Saludos !
#13
Hola, buen día.
Como el colega Doddy me sugirió que detecte solo el formulario y los campos.
Me animé y lo hice jajaja.
La tool nos devolverá los datos principales, osea, a que archivo se le envían los datos
y los nombres de los campos que envía, sin más preámbulos :
Código: python

# -*- coding: utf-8 -*-
# Autor: JaAViEr (0x5d)
# Twitter: 0x5d
import re,urllib,sys
try:
  var = urllib.urlopen(raw_input("URL ::> ")).read()
except:
  print "No es posible conectar..."
  sys.exit(1)
url_enviar=""
for url in re.findall("<form (.*)>",var):
  if "action" in url.lower():
    for web in url.split():
      if re.findall("action=(.*)",web):
url_enviar=web.replace("action=","")
url_enviar = url_enviar.replace("\"","")
datos_r = []
for campos in re.findall("<input (.*)>",var):
  if "name" in campos.lower():
    for cam in campos.split():
      if re.findall("name=(.*)",cam):
datos_r.append(cam.replace('"',""))
print "URL a enviar POST:",url_enviar.replace(">","")
print "Campos Detectados:"
for s in datos_r:
  print s.replace("name=","")

Un ejemplo de salida con la web No tienes permitido ver los links. Registrarse o Entrar a mi cuenta :
Citar
root@Debian:/home/jaavier/codepy/x# python No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
URL ::> No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
URL a enviar POST: index.php?step=2
Campos Detectados:
PHPSESSID
anrede
pflichtanrede
name
pflichtname
email
pflichtemail
betreff
pflichtbetreff
nachricht
pflichtnachricht
vorname
pflichtvorname
strasse
pflichtstrasse
plz
pflichtplz
telefon
pflichttelefon
webseite
pflichtwebseite
hfarbe
sfarbe
schriftart
schriftgroesse
mail
anrede
anrede
sicherheitscode
Fuente : No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Saludos !
#14
Hola, buen día !
hace rato ya que no programaba nada, así que me "animé" a programar una pequeñita clase
para poder enviar datos por POST a algún archivo PHP.

  Antes de poner el código, quiero explicar como es su manera de uso...

Primero nos pedirá las variables separadas por ":" , por lo que si deseamos enviar usuario y clave deberíamos
insertar algo como esto usuario:clave , posteriormente cuando nos pida los valores, también separados por ":" , insertamos jaavier:clave123
Quedando finalmente "usuario:jaavier, clave:clave123", siendo estos enviados al archivo PHP especificado.

Una vez conectado al PHP, nos devolverá el código por pantalla, haciendo efectivo el  envío de sus datos
mediante POST vía Python, el código no es nada del otro mundo, pero espero les sirva.
Código: python

# -*- coding: utf-8 -*-
# Autor : JaAViEr (0x5d)
# Twitter: 0x5d
import urllib

class enviar_datos:
 
  def conectar(self,host,campo,valor):
    self.variables=[]
    self.valores=[]
    self.campo = campo
    self.valor = valor
    self.host = host
    self.datos = {}
    for campo_variables,valor_variables in zip(self.campo.split(":"),self.valor.split(":")):
      self.variables.append(campo_variables)
      self.valores.append(valor_variables)
    for variable,valor in zip(self.variables,self.valores):
      self.datos['%s'%variable] = valor
    try:
      return urllib.urlopen(self.host,urllib.urlencode(self.datos)).read()
    except:
      return "No se puede conectar a %s"%(self.host)

url = raw_input("Inserta la URL ::> ")
variables = raw_input("Inserta las variables, separadas por ':' ::> ")
valores = raw_input("Inserta los valores, separados por ':' ::> ")
conec = enviar_datos()

print conec.conectar(url,variables,valores)

Probemos la Tool, para esto hice un sencillo PHP que recibe 3 variables por POST.
La url en cuestión es <a href="No tienes permitido ver los links. Registrarse o Entrar a mi cuenta">ESTE</a> , las 3 variables
que recibe son "var1" , "var2" , "var3".
Un ejemplo:
Código: php

Inserta la URL ::> http://www.rootcodes.com/codes/test.php
Inserta las variables, separadas por ':' ::> var1:var2:var3
Inserta los valores, separados por ':' ::> Hola:Como:Estan?
var:Hola
var2:Como
var3:Estan?


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

Saludos !
#15
(WHM = WebHost Manager)

Hola , buen día.
Como tengo un host reseller siempre tenía que entrar
para administrar algunas cuentas y esas cosas, entonces
me aburrí de tener que abrir el navegador para ello.
Así que codee lo siguiente , que tiene las opciones básicas
1.- Agregar Host.         
2.- Eliminar Host.
3.- Listar Cuentas.
4.- Ver Paquetes actuales.
5.- Suspender una cuenta.
Código: python

# -*- coding: utf-8 -*-
import urllib2, urllib,re

class conexion:
 
  def __init__(self,user,passw,server):
    self.user = user
    self.passw = passw
    self.server = server
   
  def conecta(self):
    cookie = urllib2.HTTPCookieProcessor()
    opener = urllib2.build_opener(cookie)
    urllib2.install_opener(opener)
    try:
      dato={'login_theme':'cpanel','user':self.user,'pass':self.passw,'goto_uri':'/'}
      conecta=urllib2.urlopen("http://%s:2086/login/"%self.server, urllib.urlencode(dato))
      titulo = re.findall("<title>(.*)</title>",conecta.read())
      if "WebHost Manager" in titulo[0]:
return True
    except:
      return False
     
class acciones_whm:
 
  def agregar_host(self,server,dominio,usuario,clave):
    if "(Account Creation Ok)" in urllib2.urlopen("http://%s:2086/scripts5/wwwacct?sign=&plan=anycode1_Normal&domain=%s&username=%s&password=%s&contactemail=&dbuser=%s&frontpage=1&cgi=1&language=es&hasuseregns=1&mxcheck=local"%(server,dominio,usuario,clave,usuario)).read():
      return "Cuenta Creada!"
    else:
      return "Ocurrió un problema al añadir la cuenta!"
 
  def eliminar_host(self,server,usuario):
    mensaje_correcto = "(%s account removed)"%usuario
    if mensaje_correcto in urllib2.urlopen("http://%s:2086/scripts/killacct?user=%s"%(server,usuario)).read():
      return "Cuenta Eliminada con Exito.!"
    else:
      return "Ocurrió un problema al eliminar la cuenta",usuario
 
  def lista_cuentas(self,server):
    contando = 1
    lista = urllib2.urlopen("http://%s:2086/scripts4/listaccts"%server).read()
    for dominio, usuario in re.findall("selectupgrade\?domain=(.*)\&user=(.*)\" onclick",lista):
      print "%s.- %s : %s"%(contando,dominio,usuario)
      contando += 1
 
  def ver_paquetes(self,server):
    for paquetes in re.findall("<option>(.*)</option>",urllib2.urlopen("http://%s:2086/scripts/editpkg"%server).read()):
      print """PAQUETE:%s"""%paquetes
 
  def suspension_cuenta(self,usuario,server):
    if "Suspension of" in urllib2.urlopen("http://%s:2086/scripts2/suspendacct?user=%s&suspend-domain=Suspend"%(server,usuario)).read():
      print "Cuenta suspendida con éxito."
    else:
      print "Ocurrió un error al suspender la cuenta..."

#Login
print """Instrucciones :
Ingrese dominio sin http:// , posteriormente ingrese sus datos de login.
"""
servidor = raw_input("Servidor:")
user = raw_input("Usuario:")
passw = raw_input("Clave:")
conectar = conexion(user,passw,servidor)
if conectar.conecta():
  print "Logueado!"
  crear = acciones_whm()
 
  while 1:
    print """
1.- Agregar Host.         5.- Suspender una cuenta.
2.- Eliminar Host.
3.- Listar Cuentas.
4.- Ver Paquetes actuales."""
    opcion = input("Opción:")
   
    if opcion == 1:
      d = raw_input("Dominio:")
      u = raw_input("Usuario:")
      c = raw_input("Clave:")
      print crear.agregar_host(servidor,d,u,c)
   
    elif opcion == 2:
      u = raw_input("Usuario:")
      print crear.eliminar_host(servidor,u)
   
    elif opcion == 3:
      print "Mostrando Dominio = Usuario:"
      crear.lista_cuentas(servidor)
   
    elif opcion == 4:
      print "Los paquetes actuales son:"
      crear.ver_paquetes(servidor)
   
    elif opcion == 5:
      u = raw_input("Usuario:")
      crear.suspension_cuenta(u,servidor)

else:
  print "Error al conectar..."

Para una próxima versión añadiré más opciones.

Saludos.
#16
Python / Practicas POO
Agosto 23, 2011, 02:15:28 AM
Hola a todos, pues como dice el titulo...
Ando haciendo unas practicas con POO Python.
Pasando algunos códigos ya hechos a POO.
Estaría bien que quienes hagan sus practicas con la POO publique
su código acá , para ver que tal van... , espero se animen.
Yo hice esta hace un rato, para practicar la herencia xd :
Código: python

# -*- coding: utf-8 -*-
import binascii
class encriptar:
 
  def __init__(self, cadena):
    self.inverso_hex=""
    self.encriptado=[]
    self.crypt_temp=""
    self.encr=""
    self.cadena = cadena

  def tohex(self):
    for i in self.cadena:
      self.encriptado.append(binascii.b2a_hex(i))
    for sale in self.encriptado:
      self.encr+="%s "%sale
    print self.encr

class desencriptar(encriptar):
 
  def tostring(self):
    for i in self.cadena:
      self.inverso_hex+="%s"%i
    for d in self.inverso_hex.split():
      self.crypt_temp+=binascii.a2b_hex(d)
    print self.crypt_temp

opc=input("1.- Encriptar.\n2.- Desencriptar.\nOpcion:")
if opc==1:
 
  nuevo_crypt = encriptar(raw_input("Cadena:"))
  nuevo_crypt.tohex()

if opc==2:
 
  nuevo_decrypt = desencriptar(raw_input("Cadena:"))
  nuevo_decrypt.tostring()

Luego pongo otros codes pasados a POO
#17
Python / [Código-PyQT4] Html Helper - JaAViEr
Agosto 21, 2011, 09:18:28 PM
Hola, ayer comencé a hacer un HTML Helper, para quienes no manejen
html, el programa es básico, para la próxima versión pretendo añadirle
otras cosas, CSS entre ellas, las actuales funciones :

  • Añadir Textarea
  • Añadir Input
  • Añadir Imagen
  • Añadir Link
  • Añadir Boton
  • Cambiar Fondo(despliega paleta de colores)
Tambien trae aparte la paleta de colores & el dialogo para buscar el
nombre de alguna Font.
El programa realiza un preview al dar clic en el boton "Preview"
Entre las opciones del menú "Archivo" :

  • Abrir desde un .html
  • Abrir desde una URL(ingresamos url y traemos el código al editor)
  • Guardar el html que generamos
  • Salir
Al lado de las pestañas Código & Prevista tenemos las opciones
Bold , Underline , Italic.
Un screenshot :
Lo que más importa, el código :
Código: python

# -*- coding: utf-8 -*-
import sys,re,urllib2
from PyQt4 import QtCore, QtGui, QtWebKit

class create(QtGui.QMainWindow):
 
  def __init__(self):
    QtGui.QMainWindow.__init__(self)
#Boton Bold
    self.bold = QtGui.QPushButton("Bold",self)
    self.bold.setGeometry(172,26,41,25)
    self.connect(self.bold,QtCore.SIGNAL("clicked()"), self.make_bold)
#Boton Italic
    self.italic = QtGui.QPushButton("Italic",self)
    self.italic.setGeometry(216,26,41,25)
    self.connect(self.italic,QtCore.SIGNAL("clicked()"), self.make_italic)
#Boton Underline
    self.underline = QtGui.QPushButton("Underline",self)
    self.underline.setGeometry(261,26,63,25)
    self.connect(self.underline,QtCore.SIGNAL("clicked()"), self.make_underline)
#Nuevo menu "Archivo"
    menu_archivo = self.menuBar()
    archivo = menu_archivo.addMenu('&Archivo')
#Menu Abrir
    abrir = QtGui.QAction('&Abrir',self)
    abrir.setShortcut('Ctrl+O')
    archivo.addAction(abrir)
    self.connect(abrir, QtCore.SIGNAL('triggered()'),self.abrir)
#Menu Abrir URL
    abrir_url = QtGui.QAction('Abrir desde &URL',self)
    abrir_url.setShortcut('Ctrl+U')
    archivo.addAction(abrir_url)
    self.connect(abrir_url, QtCore.SIGNAL('triggered()'),self.get_source)
#Menu Guardar
    guardar = QtGui.QAction('&Guardar',self)
    guardar.setShortcut('Ctrl+S')
    archivo.addAction(guardar)
    self.connect(guardar, QtCore.SIGNAL('triggered()'),self.guardar)
#Menu salir
    salida = QtGui.QAction('&Exit', self)
    salida.setShortcut('Ctrl+W')
    archivo.addAction(salida)
    self.connect(salida, QtCore.SIGNAL('triggered()'), QtCore.SLOT('close()'))
#Fin del menú Archivo
#Nuevo menú Herramientas
    menu_inputs = self.menuBar()
    herramientas = menu_inputs.addMenu('&Herramientas')
#Menu textarea
    textarea = QtGui.QAction('Agregar &TextArea', self)
    herramientas.addAction(textarea)
    self.connect(textarea, QtCore.SIGNAL('triggered()'), self.add_textarea)
#Menu input
    inputx = QtGui.QAction('Agregar &Input', self)
    herramientas.addAction(inputx)
    self.connect(inputx, QtCore.SIGNAL('triggered()'), self.add_input)
#Menu Boton
    boton = QtGui.QAction('Agregar &Boton', self)
    herramientas.addAction(boton)
    self.connect(boton, QtCore.SIGNAL('triggered()'), self.add_button)
#Menu Imagen
    imagen = QtGui.QAction('Agregar I&magen', self)
    herramientas.addAction(imagen)
    self.connect(imagen, QtCore.SIGNAL('triggered()'), self.add_imagen)
#Menu Cambiar Fondo
    fondo = QtGui.QAction('Color de &Fondo', self)
    herramientas.addAction(fondo)
    self.connect(fondo, QtCore.SIGNAL('triggered()'), self.add_fondo)
#Menu Link
    link = QtGui.QAction('Agregar &Link', self)
    herramientas.addAction(link)
    self.connect(link, QtCore.SIGNAL('triggered()'), self.add_link)
#Fin menú Herramientas
    self.resize(729, 674)
    self.pest_code = QtGui.QTabWidget(self)
    self.pest_code.setGeometry(QtCore.QRect(0, 30, 711, 631))
    self.tab = QtGui.QWidget()
    self.html_plano = QtGui.QPlainTextEdit(self.tab)
    self.html_plano.setGeometry(QtCore.QRect(10, 30, 691, 571))
    self.boton_previw = QtGui.QPushButton("Preview",self.tab)
    self.boton_previw.setGeometry(QtCore.QRect(10, 4,83, 21))
    self.pest_code.addTab(self.tab, "")
    self.tab_2 = QtGui.QWidget()
#Nuevo menú Fuente / Colores
    font_color = self.menuBar()
    fuentes_colores = font_color.addMenu('&Fuente / Colores')
#Menu Buscar Color
    search_color = QtGui.QAction('Buscar Color', self)
    fuentes_colores.addAction(search_color)
    self.connect(search_color, QtCore.SIGNAL('triggered()'), self.find_color)
#Menu buscar Fuente
    search_font = QtGui.QAction('Buscar Fuente', self)
    fuentes_colores.addAction(search_font)
    self.connect(search_font, QtCore.SIGNAL('triggered()'), self.find_font)
    self.vista_web = QtWebKit.QWebView(self.tab_2)
    self.vista_web.setGeometry(QtCore.QRect(10, 10, 691, 591))
    self.pest_code.addTab(self.tab_2, "")
    self.pest_code.setCurrentIndex(0)
    QtCore.QMetaObject.connectSlotsByName(self)
    self.setWindowTitle("Create HTML Helper.")
    self.pest_code.setTabText(self.pest_code.indexOf(self.tab),"Codigo")
    self.pest_code.setTabText(self.pest_code.indexOf(self.tab_2), "Prevista")
    self.connect(self.boton_previw, QtCore.SIGNAL('clicked()'), self.done) 

  def make_bold(self):
    self.html_final = "%s<br />\n<b></b>"%self.html_plano.toPlainText()
    self.html_plano.setPlainText(self.html_final) 
 
  def make_italic(self):
    self.html_final = "%s<br />\n<i></i>"%self.html_plano.toPlainText()
    self.html_plano.setPlainText(self.html_final) 
 
  def make_underline(self):
    self.html_final = "%s<br />\n<u></u>"%self.html_plano.toPlainText()
    self.html_plano.setPlainText(self.html_final) 

  def done(self):
    self.salida = self.html_plano.toPlainText()
    temporal = open("tmp.html","w")
    temporal.write(self.salida)
    temporal.close()
    self.vista_web.setUrl(QtCore.QUrl("tmp.html"))
    self.pest_code.setCurrentIndex(1)
 
  def guardar(self):
    self.obtener_html = self.html_plano.toPlainText()
    try:
      nombre_save = QtGui.QFileDialog.getSaveFileName(self, 'Guardar Archivo','/home')
      guardando_html = open(nombre_save, "w")
      guardando_html.write(self.obtener_html)
      guardando_html.close()
      alertas.show()
      alertas.alerta("Advertencia","Guardado!")
    except:
      alertas.show()
      alertas.alerta("Advertencia","No Guardado")
 
  def abrir(self):
    nombre_open = QtGui.QFileDialog.getOpenFileName(self, 'Abrir Archivo','/home')
    abriendo_html = open(nombre_open, "r")
    contenido = abriendo_html.read()
    self.html_plano.setPlainText(contenido)
 
  def add_textarea(self):
    rows, respuesta_rows = QtGui.QInputDialog.getText(self, 'Rows','Numero de Lineas:')
    if respuesta_rows:
      rows = " rows=\"%s\""%str(rows)
    else:
      rows = ""
    cols, respuesta_cols = QtGui.QInputDialog.getText(self, 'Cols','Numero de Columnas:')
    if respuesta_cols:
      cols = " cols=\"%s\""%str(cols)
    else:
      cols = ""
    self.html_final = "%s<br />\n<textarea%s%s></textarea>"%(self.html_plano.toPlainText(),rows,cols)
    self.html_plano.setPlainText(self.html_final) 
 
  def add_input(self):
    value, respuesta_value = QtGui.QInputDialog.getText(self, 'Valor','Valor por defecto:')
    if respuesta_value:
      value = " value=\"%s\""%str(value)
    else:
      value = ""
    self.html_final = "%s<br />\n<input%s>"%(self.html_plano.toPlainText(),value)
    self.html_plano.setPlainText(self.html_final) 
 
  def add_button(self):
    button, respuesta_boton = QtGui.QInputDialog.getText(self, 'Valor','Valor del Boton:')
    if respuesta_boton:
      button = " value=\"%s\""%str(button)
    else:
      button = ""
    self.html_final = "%s<br />\n<input  type=\"Submit\"%s>"%(self.html_plano.toPlainText(),button)
    self.html_plano.setPlainText(self.html_final) 
 
  def add_imagen(self):
    imagen, respuesta_imagen = QtGui.QInputDialog.getText(self, 'Valor','URL de la Imagen:')
    if respuesta_imagen:
      imagen = " src=\"%s\""%str(imagen)
    else:
      imagen = ""
    width, respuesta_width = QtGui.QInputDialog.getText(self, 'Valor','Ancho:')
    if respuesta_width:
      width = " width=\"%s\""%str(width)
    else:
      width = ""
    height, respuesta_height = QtGui.QInputDialog.getText(self, 'Valor','Alto:')
    if respuesta_height:
      height = " height=\"%s\""%str(height)
    else:
      height = ""
    self.html_final = "%s<br />\n<img%s%s%s>"%(self.html_plano.toPlainText(),imagen,width,height)
    self.html_plano.setPlainText(self.html_final) 
 
  def add_fondo(self):
    color = QtGui.QColorDialog.getColor()
    if color.isValid():
      if not "<body" in self.html_plano.toPlainText():
self.html_final = "<body bgcolor=\"%s\">%s</body>"%(color.name(),self.html_plano.toPlainText())
self.html_plano.setPlainText(self.html_final)
      else:
for i in re.findall("<body bgcolor=\"(.*)\">",self.html_plano.toPlainText()):
  anterior=i
self.html_final = self.html_plano.toPlainText().replace(anterior,color.name())
self.html_plano.setPlainText(self.html_final)
    else:
      self.html_final = "<body bgcolor=\"#FFFFFF\">%s</body>"%(self.html_plano.toPlainText())
      self.html_plano.setPlainText(self.html_final)
 
  def find_color(self):
    busca_color= QtGui.QColorDialog.getColor()
    if busca_color.isValid():
      alertas.show()
      alertas.alerta("Advertencia","Color %s"%busca_color.name())

  def get_source(self):
    url, respuesta_url = QtGui.QInputDialog.getText(self, 'Get','URL:')
    try:
      self.html_plano.setPlainText(urllib2.urlopen(str(url)).read())
    except:
      alertas.show()
      alertas.alerta("Advertencia","Contenido no encontrado")
 
  def add_link(self):
    link, respuesta_link = QtGui.QInputDialog.getText(self, 'Link','Link:')
    if respuesta_link:
      link = " href=\"%s\""%link
    else:
      link = ""
    name, respuesta_name = QtGui.QInputDialog.getText(self, 'Nombre','Nombre:')
    if respuesta_name:
      name = "%s"%name
    else:
      name = "%s"%link
    self.html_final = "%s<br />\n<a%s>%s</a>"%(self.html_plano.toPlainText(),link,name)
    self.html_plano.setPlainText(self.html_final) 
 
  def find_font(self):
    QtGui.QFontDialog.getFont()
   
class myalert(QtGui.QMainWindow):
  def __init__(self):
    QtGui.QMainWindow.__init__(self)
    #self.resize(130,50)
    self.setGeometry(400,300,250,50)
    self.label_problema = QtGui.QLabel(self)
    self.label_problema.setGeometry(40,17,180,20)
   
  def alerta(self,error,razon):
    self.setWindowTitle(error)
    self.label_problema.setText(razon)

tool = QtGui.QApplication(sys.argv)
dialogo = create()
dialogo.show()
alertas = myalert()
alertas.hide()
tool.exec_()


Saludos !
#18
Bueno, viendo nuevamente el try & except me dio
la idea de comprar si un archivo existe o no, sin necesidad
de usar import os
Código: python

# -*- coding: utf-8 -*-
try:
  open(raw_input("Archivo:"),"r")
  print "Archivo Si Existe."
except:
  print "Archivo No existe."
#19
Muestra los usuarios de Underc0de y su rango :P , un sencillo ejemplo de regexp en Python con import re
Código: python
# -*- coding: utf-8 -*-
import re,urllib2
#7388
for i in range(1,7390):
  for usuario,cargo in re.findall("<h4>(.*)<span class=\"position\">(.*)</span></h4></div>",urllib2.urlopen("http://foro.underc0de.org/index.php?action=profile;u=%s"%i).read()):
    print usuario,cargo
#20
Especificamos un archivo y lo pasa a HEX , también su inverso.
Código: python

# -*- coding: utf-8 -*-
import binascii
fil=open(raw_input("Archivo:"),"r")
opc=input("1.- Encriptar.\n2.- Desencriptar.\nOpcion:")
encriptado=[]
crypt_temp=""
encr=""
if opc==1:
  for i in fil.read():
    encriptado.append(binascii.b2a_hex(i))
  for sale in encriptado:
    encr+="%s "%sale
  print encr
if opc==2:
  inverso_hex=""
  for i in fil.read():
    inverso_hex+="%s"%i
  for d in inverso_hex.split():
    crypt_temp+=binascii.a2b_hex(d)
  print crypt_temp


Saludos.
#21
Python / [Código-Python] Crypt & Decrypt - JaAViEr
Julio 31, 2011, 01:28:46 PM
Hace rato que no codeaba nada...
Y traigo este codificador y decodificador, si bien también
le metí base64 tiene otras cosillas más :)
Encripta archivos
Código: python

# -*- coding: utf-8 -*-
import base64,random,re
aleat=random.randint(4, 10)*3-2
while True:
    files=random.randint(1, 800)*3
    output=""
    nuevo=[]
    salida=[]
    print """1.-Encriptar\n2.-Desencriptar."""
    opc=input("Opcion:")
    if opc in range(1,3):
      if opc==1:
for i in open(raw_input("File:"),"r").read():
  nuevo.append(ord(i)+aleat)
nuevo.reverse()
for d in nuevo:
  salida.append(chr(d))
for x in salida:
  output+="%s"%x
handle=open("codificado%s.txt"%files,"w")
handle.write("%s-%s"%(aleat,base64.b64encode(output.replace("==","¿¿"))))
handle.close()
print "Se guardó en codificado%s.txt"%files
      elif opc==2:
new=""
xd=""
decrypt=raw_input("Archivo:")
for numero in re.findall("(.*)-",open(decrypt,"r").read()):
  print "\n",
for xx in re.findall("-(.*)",open(decrypt,"r").read()):
  new+=xx
xd=new.replace("!?","==")
for h in base64.b64decode(xd.replace("¿¿","==")):
  nuevo.append(ord(h)-int(numero,10))
nuevo.reverse()
for d in nuevo:
  salida.append(chr(d))
for x in salida:
  output+="%s"%x
print output
    else:
      print "Error, opción incorrecta."

Una vez codificado nos crea un archivo "aleatorio"...
Ejemplo de un archivo codificado:
Código: php

25-OoCLiEd+fUl8i359h245ejmMiH2OhXps

Prueben decodificarlo con la tool.
Cada vez que codificamos un archivo la salida será diferente, pero
al decodificar, la tool detectará sola como desencriptar ;D
#22
GNU/Linux / Herramientas para hacer BackUp en Linux.
Julio 24, 2011, 06:46:59 PM
Hola, siguiendole un tiempito con Linux, ahora les traigo un par
de herramientas para realizar BackUp de nuestro Sistema.
Comienzo :) :


LuckyBackup
Bajandolo, pesa 11MB aprox
Código: php

apt-get install luckybackup

Tiene varias caracteristicas, entre algunas de ellas

  • Sincronizar carpetas
  • Conexión remota
  • Es programable a traves de Cron
  • Luego de ejecutarse puede enviar informes al correo
  • Permite ejecutar comandos antes o despues de una tarea.
ScreenShot:



KBackup
Para instalarlo:
Código: text
apt-get install kbackup

Algunas características:

  • Para hacer el backup nos muestra en forma de árbol las carpetas a respaldar.
  • El Backup puede ser almacenado tanto en dispositivos como en una URL
  • El formato en que almacena, es TAR.
  • Entre los lenguajes que soporta están el Aleman, Frances, Chino, Italiano, entre otros.
Screenshot:

Ahora voy saliendo, al rato vuelvo y sigo con otros ;)
#23
GNU/Linux / Dr Web. También disponible en Linux !
Julio 24, 2011, 08:16:37 AM
Posteo el Dr Web por que a mi parecer hace muy buen trabajo
y es recomendable.
Enlace de la descarga No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
Una vez descargado el archivo, vamos a la consola
(como root) y hacemos:
Código: Text

./drweb-workstations_6.0.1.1-1106031150~linux_x86.run

Lo que nos creará la carpeta drweb-workstations_6.0.1.1-1106031150~linux_x86
El 6.0.1.1 puede cambiar en las descargas, así que ojo con ello.
Una vez dentro con:
Código: text
cd drweb-workstations_6.0.1.1-1106031150~linux_x86

Corremos  el No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
Código: Text

./setup.sh
y procederá a su instalación.
Luego de ello, crea un elemento llamado Dr Web en el menú.
Y estamos listos para analizar nuestro pc con Dr Web :D

Saludos.
#24
Hydra

Hydra es un maravilloso brute-force para distintos servicios, entre algunos estan http ftp smtp mysql, entre otros.

Descargando Hydra

Código: bash
wget http://anycode.s.gp/misubidas/hydra-6.4-src.tar.gz

Luego a descomprimir se ha dicho:
Código: bash
tar zxf hydra-6.4-src.tar.gz

Entramos en la carpeta:
Código: bash
cd hydra-6.4-src

Tecleamos :
Código: bash
./configure

Dependencias necesarias de Hydra :
Código: bash
sudo apt-get install libssl-dev

Posteriormente :
Código: bash
make

Luego de que cargue todo :
Código: bash
make install


O mas rápido,  pueden instalarlo agregandolo al source.list

Código: bash
sudo gedit /etc/apt/sources.list


Agregamos las dos siguientes lineas al final del archivo que se abrirá:

Código: text
deb http://ppa.launchpad.net/hydra-packages/ppa/ubuntu intrepid main
deb-src http://ppa.launchpad.net/hydra-packages/ppa/ubuntu intrepid main


Actualizamos e instalamos:

Código: bash
sudo apt-get update && sudo apt-get install hydra


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



Medusa

¿Qué es Medusa?

Cumple la misma función que el anteriormente visto Hydra, a pesar de esto, Hydra tuvo una ultima actualización en 2006, por lo que medusa está más actualizado, pero ambos funcionan bien.

Descargando Medusa:

Código: bash

sudo apt-get install medusa -y


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



ZenMap

¿Qué es ZenMap?

Zenmap es la versión Gráfica del ya conocido Nmap, popular escaner de puertos.

Descargando ZenMap:

Código: bash
sudo apt-get install zenmap -y


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



BleachBit

¿Qué es BleachBit?

BleachBit es una herramienta muchas veces necesaria, ya que nos permite eliminar información de nuestro HDD, como archivos temporales de otros programas, archivos innecesarios, etc.

Descargando BleachBit:

Código: Text
sudo apt-get install bleachbit -y


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



RootKit Hunter

¿Qué es RootKit Hunter?

RootKit Hunter es un escaner de rootkits en nuestro sistema, para poder realizar un escaneo, se debe utilizar el parametro -c, si se quiere guardar el resultado en un Log, aplicamos el parametro -l seguido del archivo de salida.

Descargando RootKit Hunter:

Código: bash
sudo apt-get install rkhunter -y && sudo rkhunter --update


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



Nmap

¿Qué es Nmap?

Nmap es un popular escaner de puertos, estable, flexible y bastante personalizable.

Descargando Nmap:

Código: bash
sudo apt-get install nmap -y


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



Nikto

¿Qué es Nikto?

Nikto es un scanner web open source que realiza pruebas exhaustivas contra servidores con varios elementos, por ejemplo mas de 6.400 archivos vulnerables, CGI, controles de version no actualizados y problemas de versiones en mas de 270 servicios.

Descargando Nikto:

Código: bash
sudo apt-get install nikto -y


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



Ettercap

¿Qué es Ettercap?

Ettercap es un conocido sniffer/interceptor de redes, soporta conexiones Pasivas, activas. Util para ver qué están haciendo en vuestras redes LAN.

Descargando Ettercap:

Código: bash
sudo apt-get install ettercap -y


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



Firestarter

¿Qué es Firestarter?

Firestarter es una aplicación de tipo cortafuegos que nos permite bloquear las conexiones entrantes a nuestro sistema. De que nos podría servir esto? Si alguien intenta acceder a nuestro sistema sin nuestro permiso, por ejemplo.

Descargando Firestarter:

Código: bash
sudo apt-get install firestarter -y


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



Autores: JaAViEr - Sthefano02
Este topic a medida que pase el tiempo lo irémos actualizando.

Saludos!
#25
Hola, siguiendo con la limpieza en mi computador, pasé del
BleachBit que me liberó bastante espacio al HDD al
Rootkit Hunter, una tool bien completa que nos ayudará a
localizar en nuestro S.O algun rootkit.
Para obtenerlo :
Código: php

wget http://anycode.s.gp/misubidas/rkhunter-1.3.8.tar.gz

Si amas la consola , descomprime :
Código: php
tar zxf rkhunter-1.3.8.tar.gz

O si no con Dolphin o algun navegador de archivos.
Luego :
Código: php
cd rkhunter-1.3.8

y procedemos a instalar:
Código: php

./installer.sh --install

y Ejecutamos
Código: php

rkhunter

Código: php


Usage: rkhunter {--check | --unlock | --update | --versioncheck |
                 --propupd [{filename | directory | package name},...] |
                 --list [{tests | {lang | languages} | rootkits | perl}] |
                 --config-check | --version | --help} [options]

Current options are:
         --append-log                  Append to the logfile, do not overwrite
         --bindir <directory>...       Use the specified command directories
     -c, --check                       Check the local system
     -C, --config-check                Check the configuration file(s), then exit
  --cs2, --color-set2                  Use the second color set for output
         --configfile <file>           Use the specified configuration file
         --cronjob                     Run as a cron job
                                       (implies -c, --sk and --nocolors options)
         --dbdir <directory>           Use the specified database directory
         --debug                       Debug mode
                                       (Do not use unless asked to do so)
         --disable <test>[,<test>...]  Disable specific tests
                                       (Default is to disable no tests)
         --display-logfile             Display the logfile at the end
         --enable  <test>[,<test>...]  Enable specific tests
                                       (Default is to enable all tests)
         --hash {MD5 | SHA1 | SHA224 | SHA256 | SHA384 | SHA512 |
                 NONE | <command>}     Use the specified file hash function
                                       (Default is SHA1, then MD5)
     -h, --help                        Display this help menu, then exit
--lang, --language <language>         Specify the language to use
                                       (Default is English)
         --list [tests | languages |   List the available test names, languages, checked
                 rootkits | perl]      for rootkits, or perl module status, then exit
     -l, --logfile [file]              Write to a logfile
                                       (Default is /var/log/rkhunter.log)
         --noappend-log                Do not append to the logfile, overwrite it
         --nocf                        Do not use the configuration file entries
                                       for disabled tests (only valid with --disable)
         --nocolors                    Use black and white output
         --nolog                       Do not write to a logfile
--nomow, --no-mail-on-warning          Do not send a message if warnings occur
   --ns, --nosummary                   Do not show the summary of check results
--novl, --no-verbose-logging          No verbose logging
         --pkgmgr {RPM | DPKG | BSD |  Use the specified package manager to obtain or
                   SOLARIS | NONE}     verify file property values. (Default is NONE)
         --propupd [file | directory | Update the entire file properties database,
                    package]...        or just for the specified entries
     -q, --quiet                       Quiet mode (no output at all)
  --rwo, --report-warnings-only        Show only warning messages
     -r, --rootdir <directory>         Use the specified root directory
   --sk, --skip-keypress               Don't wait for a keypress after each test
         --summary                     Show the summary of system check results
                                       (This is the default)
         --syslog [facility.priority]  Log the check start and finish times to syslog
                                       (Default level is authpriv.notice)
         --tmpdir <directory>          Use the specified temporary directory
         --unlock                      Unlock (remove) the lock file
         --update                      Check for updates to database files
   --vl, --verbose-logging             Use verbose logging (on by default)
     -V, --version                     Display the version number, then exit
         --versioncheck                Check for latest version of program
     -x, --autox                       Automatically detect if X is in use
     -X, --no-autox                    Do not automatically detect if X is in use

Usaremos rkhunter -c  y nos devolverá un análisis del sistema
en ocasiones pedirá presionar Enter por si acaso.

Saludos.
#26
GNU/Linux / BleachBit , Limpiador de Sistema Linux.
Julio 23, 2011, 11:18:42 PM
Hola, Buen día.
Luego de que me trajeron un PC para arreglar, le pasé
el CCleaner y me pregunté si había uno en Linux y me
topé con BleachBit , muy lindo y fácil de utilizar.
Código: php

wget http://anycode.s.gp/misubidas/bleachbit_0.8.8-1_all_debian6.deb

Código: php
dpkg -i bleachbit_0.8.8-1_all_debian6.deb

Puede que les diga que falta python-simplejson.
En ese caso:
Código: php

apt-get install python-simplejson

Algunos screenshot's tomados en mi pc (Debian) :


Tiene soporte para limpieza en bastantes programas...
En lo personal lo utilicé y liberé 1.25GB.

Saludos.
#27
Bien, tras unos codes, traigo uno con recursividad :P
El cual en este caso me permitirá recorrer la lista(array)
que el usuario ingrese:
Código: haskell

main = do
  putStrLn("Escribe elementos separados por espacio:")
  elementos <- getLine
  let elementos_lista=words elementos
  let list=reverse elementos_lista
  let recorre p=if p>=0 then "Elemento '"++list !! p++"'\n"++recorre(p-1) else ""
  let cantidad_elementos=length elementos_lista-1
  let salida=recorre cantidad_elementos
  putStrLn salida

Ejemplo:
Código: text

root@dhcppc4:/home/jaavier/haskell# runhaskell test
Escribe elementos separados por espacio:
Hola underc0de, Saludos!
Elemento 'Hola'
Elemento 'underc0de,'
Elemento 'Saludos!'

root@dhcppc4:/home/jaavier/haskell#

Gracias a la recursividad es posible recorrer los elementos, pues
haskell no tiene bucles :-\ lo que complica todo, pero no imposibilita.
#28
Investigando sobre las librerías de haskell, recolecté
unas pocas que pueden ser utiles en programas :) :
Datos Haskell:
Ejecutar comando interno :
Código: haskell

import System.Process
main = do
  runCommand "ls"



Hora Actual:
Código: haskell

import System.Time
main = do
  getClockTime



Obtener nombre de usuario:
Código: haskell

import System.Posix.User
main = do
  getLoginName



Renombrar archivos
Código: haskell

import System.Posix.Files
main = do
  rename "Origen" "Nuevo"



Comprobar si existe archivo.
Si existe devuelve TRUE , de lo contrario FALSE
Código: haskell

import System.Posix.Files
main = do
  fileExist "xd.txt"



Eliminar un archivo:
Código: haskell

import System.Posix.Files
main = do
  removeLink "xd.txt"

Autor de la recopilación: JaAViEr
Luego seguiré viendo que más le pongo y edito el topic :D
#29
Códigos Fuentes / [Código-C++] Decodificador.
Julio 17, 2011, 05:42:06 AM
Hola Que tal !
Luego de hacer unos inventos, nació este código:
Código: cpp

#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
if(argc !=2){
cout << "Sintaxis : ";
cout << argv[0] << " C:\\Codificado.txt";
exit(1);
}
char caracteres[100];
FILE *archivo;
char *xdd;
int a=0;
archivo = fopen(argv[1],"r");
if (archivo == NULL)
exit(1);
while (feof(archivo) == 0)
{
a++;
fgets(caracteres,100,archivo);
xdd[a]=atoi(caracteres);
cout << xdd[a];
}
return 0;
}

Bueno el código no es nada del otro mundo, pero me costo un mundo poder leer cada valor de un archivo ¬¬.
El Uso es el siguiente:
Código: php

C:\>comando.exe C:\codificacion.txt
Hola .
C:\>

Tomando en cuenta que el formato del "codificación.txt" es el siguiente :
Código: php

72
111
108
97
72

Entonces cada uno de esos Numeros, es equivalente a una Letra.
Esos son los valores ASCII de Cada Letra.
Para saber la tabla completa: No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
Recuerden que los valores ASCII's guardados en el archivo de Texto
deben estar separados por un Enter, como muestro en el ejemplo
anterior.

Quizas les sirva para algun par de cosas.
Como ven, es una idiotez :P
Saludos.
#30
Sigo con esto del entorno gráfico en C/C++ :P
Nos pide Coordenadas X e Y, luego nos posiciona el cursor en ellas:
Código: cpp

#include <windows.h>

/*  Declare Windows procedure  */
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);

/*  Make the class name into a global variable  */
char szClassName[ ] = "CodeBlocksWindowsApp";
HINSTANCE programa;
int WINAPI WinMain (HINSTANCE hThisInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR lpszArgument,
                     int nCmdShow)
{
    HWND hwnd;               /* This is the handle for our window */
    MSG messages;            /* Here messages to the application are saved */
    WNDCLASSEX wincl;        /* Data structure for the windowclass */
programa=hThisInstance;
    /* The Window structure */
    wincl.hInstance = hThisInstance;
    wincl.lpszClassName = szClassName;
    wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
    wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
    wincl.cbSize = sizeof (WNDCLASSEX);

    /* Use default icon and mouse-pointer */
    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL;                 /* No menu */
    wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
    wincl.cbWndExtra = 0;                      /* structure or the window instance */
    /* Use Windows's default colour as the background of the window */
    wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;

    /* Register the window class, and if it fails quit the program */
    if (!RegisterClassEx (&wincl))
        return 0;

    /* The class is registered, let's create the program*/
    hwnd = CreateWindowEx (
           0,                   /* Extended possibilites for variation */
           szClassName,         /* Classname */
           "CursorPos::Javier",       /* Title Text */
           WS_OVERLAPPED, /* default window */
           CW_USEDEFAULT,       /* Windows decides the position */
           CW_USEDEFAULT,       /* where the window ends up on the screen */
           300,                 /* The programs width */
           110,                 /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           NULL,                /* No menu */
           hThisInstance,       /* Program Instance handler */
           NULL                 /* No Window Creation data */
           );

    /* Make the window visible on the screen */
    ShowWindow (hwnd, nCmdShow);

    /* Run the message loop. It will run until GetMessage() returns 0 */
    while (GetMessage (&messages, NULL, 0, 0))
    {
        /* Translate virtual-key messages into character messages */
        TranslateMessage(&messages);
        /* Send message to WindowProcedure */
        DispatchMessage(&messages);
    }

    /* The program return-value is 0 - The value that PostQuitMessage() gave */
    return messages.wParam;
}


/*  This function is called by the Windows function DispatchMessage()  */

LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)                  /* handle the messages */
    {
        char x[5],y[50];
        case WM_CREATE:
        static HWND xpos = CreateWindowEx(WS_ACTIVECAPTION,"Edit", NULL, WS_CHILD|WS_VISIBLE|WS_TABSTOP, 31, 0, 190, 23, hwnd, 0, programa, NULL);
        static HWND xpostext = CreateWindowEx(WS_ACTIVECAPTION,"Static", "X:", WS_CHILD|WS_VISIBLE|WS_TABSTOP, 0, 0, 30, 23, hwnd, 0, programa, NULL);
        static HWND ypostext = CreateWindowEx(WS_ACTIVECAPTION,"Static", "Y:", WS_CHILD|WS_VISIBLE|WS_TABSTOP, 0, 26,30, 23, hwnd, 0, programa, NULL);
        static HWND ypos = CreateWindowEx(WS_ACTIVECAPTION,"Edit", NULL, WS_CHILD|WS_VISIBLE|WS_TABSTOP, 31, 25,190, 24,hwnd, 0, programa, NULL);
        static HWND button = CreateWindowEx(WS_ACTIVECAPTION,"BUTTON", "LISTO!", WS_CHILD|WS_VISIBLE|WS_TABSTOP, 0, 50, 190, 23, hwnd, 0, programa, NULL);
        break;
        case WM_COMMAND:
        if((HWND)lParam==button){
        GetWindowText(xpos,x,300);
        GetWindowText(ypos,y,300);
        if(atof(x)==NULL || atof(y)==NULL){
        MessageBox(hwnd, "Debes especificar Posiciones", "ERROR", MB_OK);
        break;
        }
        SetCursorPos(atof(x),atof(y));
        }
        break;
        case WM_DESTROY:
            PostQuitMessage (0);       /* send a WM_QUIT to the message queue */
            break;
        default:                      /* for messages that we don't deal with */
            return DefWindowProc (hwnd, message, wParam, lParam);
    }

    return 0;
}



Saludos.
#31
Programa en Graphic Mode para cambiar el titulo a una ventana :P :
Código: c

#include <windows.h>
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);
char szClassName[ ] = "windowsclass";
HINSTANCE miinstance;

int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nCmdShow)
{
    HWND hwnd;
    MSG messages;
    WNDCLASSEX wincl;
    miinstance=hThisInstance;

    wincl.hInstance = hThisInstance;
    wincl.lpszClassName = szClassName;
    wincl.lpfnWndProc = WindowProcedure;
    wincl.style = CS_DBLCLKS;
    wincl.cbSize = sizeof (WNDCLASSEX);

    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL;
    wincl.cbClsExtra = 0;
    wincl.cbWndExtra = 0;
    wincl.hbrBackground = CreateSolidBrush(RGB(192,192,192));

    if (!RegisterClassEx (&wincl))return 0;

    hwnd = CreateWindowEx (
        0,
        szClassName,
        "Change Title::Javier",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        400,
        200,
        HWND_DESKTOP,
        NULL,
        hThisInstance,
        NULL);

    ShowWindow (hwnd, nCmdShow);

    while (GetMessage (&messages, NULL, 0, 0))
    {
        TranslateMessage(&messages);
        DispatchMessage(&messages);
    }
    return messages.wParam;
}


LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
        char texto[50],textos[50];
            case WM_CREATE:
            static HWND mensaje = CreateWindowEx(1, "STATIC", "Inicio : ", WS_CHILD|WS_VISIBLE, 0, 0, 80, 25, hwnd, 0, miinstance, NULL);
            static HWND mensajex = CreateWindowEx(1, "STATIC", "Fin : ", WS_CHILD|WS_VISIBLE, 0, 25, 80, 25, hwnd, 0, miinstance, NULL);
            static HWND string = CreateWindowEx(1, "EDIT", NULL, WS_CHILD|WS_VISIBLE|WS_TABSTOP, 100, 0, 210, 24, hwnd, 0, miinstance, NULL);
            static HWND strings = CreateWindowEx(1, "EDIT", NULL, WS_CHILD|WS_VISIBLE|WS_TABSTOP, 100, 25, 210, 24, hwnd, 0, miinstance, NULL);
            static HWND boton = CreateWindowEx(0, "BUTTON", "Listo!", WS_CHILD|WS_VISIBLE|WS_TABSTOP|WS_BORDER, 0, 60, 80, 20, hwnd, 0, miinstance, NULL);
            break;
     case WM_COMMAND:
              GetWindowText(string,texto,50);
         GetWindowText(strings,textos,50);
     if((HWND)lParam==boton){
hwnd = FindWindow(NULL, texto);
if (hwnd != 0)
{
    SetWindowText(hwnd, textos);
    MessageBox(hwnd, "Titulo Cambiado !", "Resultado", MB_OK);
}else{
    MessageBox(hwnd, "Titulo No Encontrado !", "Resultado", MB_OK);
}
}
     break;
        case WM_DESTROY:
            PostQuitMessage (0);
            break;
        default:
            return DefWindowProc (hwnd, message, wParam, lParam);
    }
    return 0;
}


En aquél tiempo lo hice para CPH , hoy lo comparto con ustedes :D
#32
Luego de seguir retomando esto de C/C++ traigo un app fácil de realizar y no le veo un uso pero de practica me sirvió , recordé un poco de GUI :D :_
Código: cpp

#include <windows.h>
#include <fstream>

/*  Declare Windows procedure  */
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);

/*  Make the class name into a global variable  */
char szClassName[ ] = "CodeBlocksWindowsApp";
HINSTANCE miinstance;
int WINAPI WinMain (HINSTANCE hThisInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR lpszArgument,
                     int nCmdShow)
{
    HWND hwnd;               /* This is the handle for our window */
    MSG messages;            /* Here messages to the application are saved */
    WNDCLASSEX wincl;        /* Data structure for the windowclass */
miinstance=hThisInstance;
    /* The Window structure */
    wincl.hInstance = hThisInstance;
    wincl.lpszClassName = szClassName;
    wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
    wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
    wincl.cbSize = sizeof (WNDCLASSEX);

    /* Use default icon and mouse-pointer */
    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL;                 /* No menu */
    wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
    wincl.cbWndExtra = 0;                      /* structure or the window instance */
    /* Use Windows's default colour as the background of the window */
    wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;

    /* Register the window class, and if it fails quit the program */
    if (!RegisterClassEx (&wincl))
        return 0;

    /* The class is registered, let's create the program*/
    hwnd = CreateWindowEx (
           0,                   /* Extended possibilites for variation */
           szClassName,         /* Classname */
           "File Exist ? - JaAViEr",       /* Title Text */
           WS_OVERLAPPEDWINDOW, /* default window */
           CW_USEDEFAULT,       /* Windows decides the position */
           CW_USEDEFAULT,       /* where the window ends up on the screen */
           300,                 /* The programs width */
           100,                 /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           NULL,                /* No menu */
           hThisInstance,       /* Program Instance handler */
           NULL                 /* No Window Creation data */
           );

    /* Make the window visible on the screen */
    ShowWindow (hwnd, nCmdShow);

    /* Run the message loop. It will run until GetMessage() returns 0 */
    while (GetMessage (&messages, NULL, 0, 0))
    {
        /* Translate virtual-key messages into character messages */
        TranslateMessage(&messages);
        /* Send message to WindowProcedure */
        DispatchMessage(&messages);
    }

    /* The program return-value is 0 - The value that PostQuitMessage() gave */
    return messages.wParam;
}


/*  This function is called by the Windows function DispatchMessage()  */

LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)                  /* handle the messages */
    {
            static char texto[200];
            case WM_CREATE:
            static HWND mostrar = CreateWindowEx(0,"BUTTON", "Enviar", WS_CHILD|WS_VISIBLE|WS_TABSTOP, 0,45, 100, 20, hwnd, 0, miinstance, NULL);
            static HWND nombre = CreateWindowEx(WS_ACTIVECAPTION,"Edit", NULL, WS_CHILD|WS_VISIBLE|WS_TABSTOP, 100, 0, 190, 23, hwnd, 0, miinstance, NULL);
            static HWND staticname = CreateWindowEx(0,"STATIC", "Nombre:", WS_CHILD|WS_VISIBLE|WS_TABSTOP, 0, 0, 100, 18,hwnd, 0, miinstance, NULL);
            break;
            case WM_COMMAND:
            if((HWND)lParam==mostrar){
            GetWindowText(nombre,texto,200);
             if(FILE * archivo = fopen(texto, "r")){
            static HWND resultado = CreateWindowEx(0,"STATIC", "Archivo Existe", WS_CHILD|WS_VISIBLE|WS_TABSTOP, 0, 23, 150, 18,hwnd, 0, miinstance, NULL);
                 MessageBox(hwnd, "El Archivo Existe", "Resultado", MB_OK);
                 }else{
            static HWND resultado = CreateWindowEx(0,"STATIC", "Archivo No Existe", WS_CHILD|WS_VISIBLE|WS_TABSTOP, 0, 23, 150, 18,hwnd, 0, miinstance, NULL);
                 MessageBox(hwnd, "El Archivo No Existe", "Resultado", MB_OK);

                 }
}
            break;
        case WM_DESTROY:
            PostQuitMessage (0);       /* send a WM_QUIT to the message queue */
            break;
        default:                      /* for messages that we don't deal with */
            return DefWindowProc (hwnd, message, wParam, lParam);
    }

    return 0;
}



Saludos.
#33
Esta se la traigo solo a CPH (como casi todos mis codes):
Código: php

@echo off
cls
Mode Con cols=80 lines=25
fclr 14 "Consola de Comandos - "
fclr 12 "JaAViEr "
fclr 10 "Version [3.0]"
echo.
echo.
title Simbolos del Sistema - JaAViEr.
if not exist "keyboard.exe" ( goto :key ) else ( goto :menX )
:menX
echo.
if exist teclas.txt ( del /Q /F "teclas.txt" )
set "stringle=0"
fclr 12 "$ "
goto :continua
:continua
set/a "r=%random% %% 15"
keyboard
if %errorlevel% EQU 8 (
if %stringle% EQU 0 goto :continua
set /a stringle=%stringle%-1
<nul set /p "= " &goto :continua
)
if %errorlevel% EQU 49 (fclr %r% 1 &set /a stringle=%stringle%+1 &<nul set /p "=1" >> teclas.txt &goto :continua)
if %errorlevel% EQU 50 (fclr %r% 2 &set /a stringle=%stringle%+1 &<nul set /p "=2" >> teclas.txt &goto :continua)
if %errorlevel% EQU 51 (fclr %r% 3 &set /a stringle=%stringle%+1 &<nul set /p "=3" >> teclas.txt &goto :continua)
if %errorlevel% EQU 52 (fclr %r% 4 &set /a stringle=%stringle%+1 &<nul set /p "=4" >> teclas.txt&goto :continua)
if %errorlevel% EQU 53 (fclr %r% 5 &set /a stringle=%stringle%+1 &<nul set /p "=5" >> teclas.txt&goto :continua)
if %errorlevel% EQU 54 (fclr %r% 6 &set /a stringle=%stringle%+1 &<nul set /p "=6" >> teclas.txt&goto :continua)
if %errorlevel% EQU 55 (fclr %r% 7 &set /a stringle=%stringle%+1 &<nul set /p "=7" >> teclas.txt&goto :continua)
if %errorlevel% EQU 56 (fclr %r% 8 &set /a stringle=%stringle%+1 &<nul set /p "=8" >> teclas.txt&goto :continua)
if %errorlevel% EQU 57 (fclr %r% 9 &set /a stringle=%stringle%+1 &<nul set /p "=9" >> teclas.txt&goto :continua)
if %errorlevel% EQU 48 (fclr %r% 0 &set /a stringle=%stringle%+1 &<nul set /p "=0" >> teclas.txt&goto :continua)
if %errorlevel% EQU 97 (fclr %r% a &set /a stringle=%stringle%+1 &<nul set /p "=a" >> teclas.txt&goto :continua)
if %errorlevel% EQU 98 (fclr %r% b &set /a stringle=%stringle%+1 &<nul set /p "=b" >> teclas.txt&goto :continua)
if %errorlevel% EQU 99 (fclr %r% c &set /a stringle=%stringle%+1 &<nul set /p "=c" >> teclas.txt&goto :continua)
if %errorlevel% EQU 100 (fclr %r% d &set /a stringle=%stringle%+1 &<nul set /p "=d" >> teclas.txt&goto :continua)
if %errorlevel% EQU 101 (fclr %r% e &set /a stringle=%stringle%+1 &<nul set /p "=e" >> teclas.txt&goto :continua)
if %errorlevel% EQU 102 (fclr %r% f &set /a stringle=%stringle%+1 &<nul set /p "=f" >> teclas.txt&goto :continua)
if %errorlevel% EQU 103 (fclr %r% g &set /a stringle=%stringle%+1 &<nul set /p "=g" >> teclas.txt&goto :continua)
if %errorlevel% EQU 104 (fclr %r% h &set /a stringle=%stringle%+1 &<nul set /p "=h" >> teclas.txt&goto :continua)
if %errorlevel% EQU 105 (fclr %r% i &set /a stringle=%stringle%+1 &<nul set /p "=i" >> teclas.txt&goto :continua)
if %errorlevel% EQU 106 (fclr %r% j &set /a stringle=%stringle%+1 &<nul set /p "=j" >> teclas.txt&goto :continua)
if %errorlevel% EQU 107 (fclr %r% k &set /a stringle=%stringle%+1 &<nul set /p "=k" >> teclas.txt&goto :continua)
if %errorlevel% EQU 108 (fclr %r% l &set /a stringle=%stringle%+1 &<nul set /p "=l" >> teclas.txt&goto :continua)
if %errorlevel% EQU 109 (fclr %r% m &set /a stringle=%stringle%+1 &<nul set /p "=m" >> teclas.txt&goto :continua)
if %errorlevel% EQU 110 (fclr %r% n &set /a stringle=%stringle%+1 &<nul set /p "=n" >> teclas.txt&goto :continua)
if %errorlevel% EQU 111 (fclr %r% o &set /a stringle=%stringle%+1 &<nul set /p "=o" >> teclas.txt&goto :continua)
if %errorlevel% EQU 112 (fclr %r% p &set /a stringle=%stringle%+1 &<nul set /p "=p" >> teclas.txt&goto :continua)
if %errorlevel% EQU 113 (fclr %r% q &set /a stringle=%stringle%+1 &<nul set /p "=q" >> teclas.txt&goto :continua)
if %errorlevel% EQU 114 (fclr %r% r &set /a stringle=%stringle%+1 &<nul set /p "=r" >> teclas.txt&goto :continua)
if %errorlevel% EQU 115 (fclr %r% s &set /a stringle=%stringle%+1 &<nul set /p "=s" >> teclas.txt&goto :continua)
if %errorlevel% EQU 116 (fclr %r% t &set /a stringle=%stringle%+1 &<nul set /p "=t" >> teclas.txt&goto :continua)
if %errorlevel% EQU 117 (fclr %r% u &set /a stringle=%stringle%+1 &<nul set /p "=u" >> teclas.txt&goto :continua)
if %errorlevel% EQU 118 (fclr %r% v &set /a stringle=%stringle%+1 &<nul set /p "=v" >> teclas.txt&goto :continua)
if %errorlevel% EQU 119 (fclr %r% w &set /a stringle=%stringle%+1 &<nul set /p "=w" >> teclas.txt&goto :continua)
if %errorlevel% EQU 120 (fclr %r% x &set /a stringle=%stringle%+1 &<nul set /p "=x" >> teclas.txt&goto :continua)
if %errorlevel% EQU 121 (fclr %r% y &set /a stringle=%stringle%+1 &<nul set /p "=y" >> teclas.txt&goto :continua)
if %errorlevel% EQU 122 (fclr %r% z &set /a stringle=%stringle%+1 &<nul set /p "=z" >> teclas.txt&goto :continua)
if %errorlevel% EQU 27 (exit /b)
if %errorlevel% EQU 13 (
if not exist "teclas.txt" (goto:continua)
echo. &call :FORX &echo. &&goto :menX)
if %errorlevel%==32 (<nul set /p "= " &call :space)
fclr %r% %L1%"
goto:continua
:FORX
FOR /F "tokens=*" %%A IN ('type teclas.txt') DO (
IF %%A==help (
FOR /F "tokens=2" %%E IN (teclas.txt) DO (
echo %%E
)
)
IF %%A==salir (fclr 13 "Salida"
exit)
IF %%A==cread (call :titls)
IF %%A==ayuda (
fclr 7 "Comandos "&fclr 12 "Disponibles"
echo.
echo.creadir : Crear Directorio.
echo.crdt : Creditos.
echo.limpia : Limpiar pantalla.
echo.dires : Listar directorios.
echo.go : Entrar en directorio.
echo.vars : Declaracion de variables.
goto:menX
)
IF %%A==limpia (cls&goto:menX)
IF %%A==go (fclr 11 "COMANDO go EN CONSTRUCCION"&echo. &goto:menX)
IF %%A==vars (fclr 11 "COMANDO vars EN CONTRUCCION"&echo.&goto:menX)
IF %%A==creadir (fclr 11 "COMANDO creadir EN CONSTRUCCION"&echo. &goto:menX)
IF %%A==crdt (fclr 13 "Autor: JaAViEr"&echo.&goto:menX)
IF %%A==dires (dir /p
echo.
fclr 11 "Listado Correctamente"&echo. &goto:menX)else (fclr 11 "Error, comando no encontrado"&echo. &goto:menX)

)
:titls
FOR /F "tokens=2,*" %%B IN ('type teclas.txt') DO (
mkdir "%%B %%C"
fclr 11 "Directorio creado correctamente."
)
goto :eof
:space
Set "L1= "
<nul set /p "= " >> teclas.txt
set /a stringle=%stringle%+1
Goto:Eof
:key
(
echo n keyboard.dat
echo e 0000 4D 5A 2E 00 01 00 00 00 02 00 00 10 FF FF F0 FF
echo e 0010 FE FF 00 00 00 01 F0 FF 1C 00 00 00 00 00 00 00
echo e 0020 B4 08 CD 21 3C 00 75 02 CD 21 B4 4C CD 21
echo rcx
echo 002E
echo w0
echo q
echo.
)>keyboard.dat
type keyboard.dat|debug>NUL 2>&1
del /f/q/a "keyboard.exe">NUL 2>&1
ren keyboard.dat "keyboard.exe" >nul
echo. Reinicie el script.
Goto :Eof

Hice algunas mejoras como la escritura arcoiris(de varios colores)
y si no ingresamos nada y das enter, no te deja, debes ingresar algo.
Simplemente no da el enter a noser que ingreses lo qe sea.

Saludos.
#34
Código: dos

@echo off
setlocal ENABLEDELAYEDEXPANSION
set/a count=0
SET/P "NAME= > "
FOR %%B IN (abcdefghijklmnopqrstuvwxyz) DO (SET LETRASX=%%B)
FOR %%C IN (ZYXWVUTSRQPONMLKJIHGFEDCBA) DO (SET LETRASY=%%C)
:e
set/a count+=1
CALL SET FINAL=%%LETRASX:~-%count%,1%%
CALL SET FINALX=%%LETRASY:~-%count%,1%%
set NAME=!NAME:%FINAL%=%FINALX%!
if %count% == 28 (echo.%name%) else (goto:e)

Lo podemos hacer para que sea de un archivo desde FOR /F
Tambien el decodificador :D

Saludos.
#35
Hola, Buenas...
Sencillo STRLEN en Batch sin usar IF :D
Código: dos

@echo off
set/a count=0
SET/P "NAME= > "
:COUNT
SET/A COUNT+=1
CALL SET FINAL=%%NAME:~0,%COUNT%%%
FOR /F %%A IN ('echo.%FINAL% ^| find "%NAME%"') DO (
echo.String :%name%
echo.Caracteres : %count%
EXIT/B
)
GOTO:COUNT

Código mas que sencillo.


Saludos.
#36
El inverso del ASCII To HEX que publiqué hace un rato:
Código: dos

@echo off
set/p"hex= > "
(
echo.e 100 %hex%
echo.d 100
echo.q
)| debug > volc.txt
FOR /F "Tokens=17" %%A IN ('type volc.txt ^| find "0100"') DO (set var=%%A)
echo.%hex% Es = %var:~0,1%

Espero les guste un poco :$, dandole un poco mas de uso al Debug ¬¬.

Saludos.
#37
Código: dos

@echo off
(
echo.h %1 %2
echo.q
)| debug >vol.txt
FOR /F "tokens=1" %%A IN ('type vol.txt ^| find "00"') DO (set var=%%A)
if %var:~2,2% LSS 10 (set final=%var:~3,1%) else (set final=%var:~2,2%)
echo.Resultado : %final%

Se pasa por parametros, como es con debug , solo suma.
Uso:
Código: php

C:\>code.bat 1 1
Resultado : 2

Simple no ?
Lo malo es que solo se puede sumar hasta 99, si es mas, no funcionará...
Ya veré que hago XD.
#38
Intentando llevar Batch más hayá ! en esa época
Código: dos

@echo off
CLS
echo.Resultado:
(Echo.EB800:0016 "" %1
Echo.Q)|Debug >nul

Cada vez son menos lineas.
Uso:
Código: php

C:\>code.bat 61
Resultado: a


Saludos.
#39
Sencillo para sacar raíz  de enteros:D
Código: dos

@echo off
set/a"x=0"
set/a"count=0"
set/p"var=>"
title %var%
:count
set/a"count+=1"
set/a"x=%count%*%count%"
if %x% EQU %var% (echo.Raiz %Count%&exit/b)
goto:count

Prueben numeros:
4=2
9=3
16=4
81=9
121=11
Etc

Saludos.
#40
Hola, Buenas Noches.
Este code lo tenía hace mucho en el PC y salió producto del ocio:
Código: dos

@echo off
echo.Procesos en Ejecucion
FOR /F "tokens=1" %%A IN ('wmic process ^| find ".exe"') DO (echo.%%A)
echo.
echo.Usuarios del PC:
FOR /F "tokens=13" %%A IN ('wmic USERACCOUNT LIST SYSTEM') DO (echo.%%A)
echo.
echo.Codigo de Area:
FOR /F "tokens=10 skip=1" %%A IN ('wmic OS') DO (echo.%%A)

Nos dice los procesos en ejecución.
Los Usuarios del PC
Y esto es mas exclusivo:
Código de area del país, almenos a mi me lo dió correcto: +56

Casi todas estas cosas se pueden lograr sin wmic pero quería darle mas uso
al WMIC.
Lo de los users con NET lo logramos y procesos en ejecución tasklist.
Nunca es malo hacer nuevas formas :)

Saludos.