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

#1
Vamos al grano y no quiero decir el nombre de la peli...

Pero alguien sabe si en el viejo y bajo mundo ya "liberaron" la película?

Saludos.
#2
Disculpen mi ignoracia pero alguien sabe por que las funciones REGEXP_INSTR y REGEXP_LIKE se quedan trabadas en Oracle 10?

Entiendo que son costosas pero que no respondan ya es mucho...

Mi problema radica en esta consulta (no termina)

Código (sql) [Seleccionar]

SELECT
NVL(REGEXP_INSTR('(HTTP 500) - soapenv:ServerOSB-382500: OSB Service Callout action received SOAP Fault responseOSB-382500OSB Service Callout action received SOAP Fault responsesoapenv:Server(CM1-000559) Stop collection treatment is not allowed on this account.amdocs.csm3g.exceptions.CMValidateException: (CM1-000559) Stop collection treatment is not allowed on this account.StopCollectionPipelinePairNoderequest-ac42ea5.N370c41ec.0.153414147d5.N7967StopCollectionTreatmrntServiceCalloutStagerequest-pipeline; nested',
'(\r|\n|.)*\(HTTP 500\) \- soapenv\:ServerOSB\-382500(.*)\(CM1\-000559\) Stop collection treatment is not allowed on this(\r|\n|.)*'), 0) indexlarge
FROM DUAL;


Solucion:

No usar \r y \n en las expresiones regulares (estas dos me mataban la ejecución) y que no sean mayores a 512 bytes.

Queda la query (use otros parámetros que no son necesarios realmente, igual sin ellos me funciono):

Código (sql) [Seleccionar]
SELECT
NVL(REGEXP_INSTR('(HTTP 500) - soapenv:ServerOSB-382500: OSB Service Callout action received SOAP Fault responseOSB-382500OSB Service Callout action received SOAP Fault responsesoapenv:Server(CM1-000559) Stop collection treatment is not allowed on this account.amdocs.csm3g.exceptions.CMValidateException: (CM1-000559) Stop collection treatment is not allowed on this account.StopCollectionPipelinePairNoderequest-ac42ea5.N370c41ec.0.153414147d5.N7967StopCollectionTreatmrntServiceCalloutStagerequest-pipeline; nested',
'(.)*\(HTTP 500\) \- soapenv\:ServerOSB\-382500(.*)\(CM1\-000559\) Stop collection treatment is not allowed on this(.)*', 1, 1, 0, 'ni'), 0) indexlarge
FROM DUAL;


Saludos.
#3
Java / Depuracion...
17 Abril 2016, 07:19 AM
Alguien sabe si puedo depurar un archivo class sin el código fuente? (algo parecido a OllyDBG) simplemente quiero ver como se va produciendo la secuencia de instrucciones y ver la memoria.

P.D.: No me vale de compilarlo (JD-Core), es simplemente una curiosidad para algo que tengo en mente y si es posible ver el camino para desarrollar una utilidad.

Dulces Lunas!¡.
#4
Java / TWain Applet, problemas con DMS
22 Agosto 2015, 22:10 PM
Hola buena tarde.

Tengo un componente applet el cual funciona perfectamente con la mayoría de los scanners usando el estándar TWain (versión 2), el problema resalta que cuando ejecuto el IE6, IE7, ... , IEXX... para x32, este carga la JVM en x32 como es lógico y debería ser lógico que carga los DLL TWAINDMS.dll que están en el directorio sysWOW64 que son las en sistemas de arquitectura x64, pero resulta que debo poner las de x64 de lo contrario se queda congelo el driver, hay alguna forma de solventar este problema?.

Cabe mencionar que en sistemas de plataforma de x32 carga como Win XP carga la TWAINDMS.dll que se encuentra en system32 como lo haría en cualquier otra plataforma x32, pero se queda congelado perdiendo la comunicación con el driver.

El scanner que intento comunicar es el fujitsu 7160, según la pagina oficial de twain.org solo corre desde W7 pero lo increíble de esto que usando utilidades o jars ejecutados fuera de IE reconoce y no hay congelamiento y por ende pierde la conexión del mismo en sistemas anteriores como Win 7, cualquier otro scanner incluyendo las impresoras multi-funcionales se ejecutan correctamiento.

Las dll del DMS que utilizo son las de las 2.3.0: http://sourceforge.net/projects/twain-dsm/

Las dll que vienen con Win XP las e sustituido con esas aunque al final del día se jode el DMS y tengo que restituir las originales...

¿Existe alguna solución?, e estado viendo la posibilidad de crearme una dll que me comunique por WIA al scanner y cargarla por metodos nativos... e descartado los standard SANE e ISIS para este caso.

¿Existen alguna otra librería que no sea jtwain de asprise?...

Saludos!¡.
#5
Les dejo mi servidor de Mu Online (Seasson 6 Ep 3 Experience 10x Drop 50%).

Lo he montado hace unos días para disfrute GRATUITO (Sin coste alguno).

http://muinfra.sytes.net/
o
http://infrangelux.sytes.net/mu/

Solo descarguen el juego (Zona de descargas), Registren-se en la pagina (Obligatorio si no, NO podrán acceder al juego), una vez descargado el juego si no oyen canciones o si la resolución del juego no les acomoda tienen en las descargas varias utilidades para cambiar la resolución (al ejecutar alguna de estas activa los sonidos y canciones que por default están desactivados).

Ya teniendo una cuenta y el Cliente FULL (750 megas) solo extraigan con winrar el juego y ejecuten el archivo main.exe.

Un video:


Para los mas experimentados:

Experiencia: 10x
Drop: 50%
Versión: Seasson 6 Episodio 3
Reset: 400
Borrar Estas: SI
Borra Skill: NO
Borra Vault: NO
Borra Inventario: NO
Costo Reset: 75 000 000 zen (Vendan los items jewel of guardian dan 20 000 000 se dropean)
Grand Reset: SI

Guías funcionales del juego:

http://infrangelux.sytes.net/mu/index.php?page_id=Guias

Dulces Lunas!¡.
#6
Son varias funciones para tratar a las listas, Absténganse de entregar a sus maestros este código si no lo llegan a comprender lo "básico". NO INCLUÍ las funciones de ordenamiento debido a que tienen un problema, seguro se me paso alguno... igual no es nada del otro mundo (fue cuando incluí la macro LIST_INTEGRAL_RELATIONSHIP).

list.h

#ifndef LIST_H_INCLUDED
#define LIST_H_INCLUDED

/** \autor Ortega Avila Miguel Angel (BlackZeroX).
*
* \website http://infrnagelux.sytes.net/
* \copileft El presente código se da de manera gratuita sin ningún derecho a venta.
* \note muchas de las funciones aqui presentadas "inútiles" como:
* list_before()
* list_after()
* list_getlist()
* Note que esta ultima solo esta activa mientras este declarada la macro.
*
* http://foro.elhacker.net/programacion_cc/srcc99_para_que_dejen_de_preguntar_por_las_listas-t380839.0.html
*
*/

#include <stdbool.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>

#ifndef LIST_INTEGRAL_RELATIONSHIP
/** \brief Al declarar LIST_INTEGRAL_RELATIONSHIP se reduce considerablemente la velocidad
* en el proceso list_sort() debido a que se actualizan TODOS los miembros list de la estructura
* struct list_item de cada elemento; De igual manera aumenta la seguridad de no eliminar o hacer
* operaciones indebidas entre elementos.
*
*/
///#define LIST_INTEGRAL_RELATIONSHIP /**< Comentar/descomentar */
#endif

#define LIST_SIZE_ITEM sizeof(struct list_item)

struct list;
typedef void*               list_value_t; ///typedef uintptr_t            list_value_t;
typedef struct list*        list_t;

/** \brief Definición callback que se encarga de crear un duplicado de un elemento de lista.
* \param item: Valor a duplicar.
*
* \return Retorna el elemento list_value_t duplicado del parámetro value.
*
*/
typedef list_value_t (*list_callback_clone_item)
(const list_value_t value);

/** \brief Definición de callback que se encarga de destruir la memoria asignada al list_value_t.
*
* \param item: Puntero a la estructura que se le pretende liberar su valor asignado debe liberarse solo el miembro value.
*
*/
typedef
void(*list_callback_release_item)
(const list_value_t value);

/** \brief Definición de callback que se encarga comparar dos list_value_t.
*
* \param value1: list_value_t que se comparara con value2.
* \param value2: list_value_t que se comparara con value1.
* \return Retorna el resultado de la comparación.
* LIST_CMP_LESS_THAT: Si value1 < value2.
* LIST_CMP_EQUAL: Si value1 == value2.
* LIST_CMP_GREATER_THAT: Si value1 > value2.
*
*/
typedef
enum list_cmp(*list_callback_compare_item)
(const list_value_t value1,
const list_value_t value2);

enum list_cmp {
   LIST_CMP_EQUAL          = 1,    /**< */
   LIST_CMP_LESS_THAT      = 2,    /**< */
   LIST_CMP_GREATER_THAT   = 4     /**< */
};

enum list_sort {
   LIST_SORT_ASC,  /**< */
   LIST_SORT_DESC  /**< */
};

struct list_item {
   list_value_t        value;  /**< Valor del item actual. */
   struct list_item    *prev;  /**< Apuntador al item derecho. */
   struct list_item    *next;  /**< Apuntador al item izquierdo. */
   #ifdef LIST_INTEGRAL_RELATIONSHIP
   list_t              list;   /**< Apuntador a los datos generales de la lista. */
   #endif
};


struct list {                       /**< Estructura que guarda la información generalizada de una lista de datos */
   struct list_item    *first;     /**< Primer elemento agregado a la lista */
   struct list_item    *last;      /**< Ultimo elemento agregado a la lista */
   #ifdef LIST_INTEGRAL_RELATIONSHIP
   size_t              size;       /**< Cantidad de elementos */
   #endif
   list_callback_clone_item    clone_item;     /**< Puntero a la función callback que realiza las acciones CLONE, RELEASE y COMPARE */
   list_callback_release_item  release_item;   /**< Puntero a la función callback que realiza las acciones CLONE, RELEASE y COMPARE */
   list_callback_compare_item  compare_item;   /**< Puntero a la función callback que realiza las acciones CLONE, RELEASE y COMPARE */
};

/** \brief Obtiene el item siguiente al inicado.
*
* \param item: Item pivote en la lista.
* \return Retorna el struct list_item * siguiente al indicado; NULL si no hay ningun item.
*
*/
struct list_item*
list_after(struct list_item *item);

/** \brief Crea una nueva lista de elementos list_value_t.
*
* \param clone_item: Apuntador a la función callback que retornara la copia del valor a asignar.
* \param release_item: Apuntador a la función callback que liberara la copia del valor duplicado en el list_callback_clone_item.
* \param clone_item: Apuntador a un proceso callback que se encarga de comparar los struct list_item *.
* \return Retorna la nueva cola de datos queue_t que deberá ser destruida con list_release().
*
*/
list_t
list_allocator(list_callback_clone_item clone_item,
              list_callback_release_item release_item,
              list_callback_compare_item compare_item);

/** \brief Agrega n cantidad de elementos repetidos (value) a la lista, reemplazando los existentes.
*
* \param list: Lista en la que se agregara value n veces.
* \param n: Cantidad de valores a agregar a la lista.
* \param value: Valor a agregar n veces a la lista.
* \return Retorna el primer elemento agregado; NULL si no se a agregado ningun elemento.
*
*/
struct list_item*
list_assign(list_t list,
           size_t n,
           list_value_t value);

/** \brief Obtiene el ultimo elemento de una lista.
*
* \param list: Lista de la cual se obtendrá el ultimo elemento struct list_item *.
* \return Devuelve el ultimo struct list_item * de la lista.
*
*/
struct list_item*
list_back(list_t list);

/** \brief Obtiene el item anterior al inicado.
*
* \param item: Item pivote en la lista.
* \return Retorna el struct list_item * anterior al indicado; NULL si no hay ningun item.
*
*/
struct list_item*
list_before(struct list_item *item);

/** \brief Obtiene el primer elemento de una lista.
*
* \param list: Lista de la cual se obtendrá su primer elemento struct list_item *.
* \return Devuelve el primer struct list_item * de la lista.
*
*/
struct list_item*
list_begin(list_t list);

/** \brief Remueve/Libera TODOS los elementos de la lista.
*
* \param list: Puntero a la struct list que se limpiara.
* \return Retorna la cantidad de elementos removidos de la lista.
*
*/
size_t
list_clear(list_t list);

/** \brief Función que clona por completo una lista.
*
* \param list: Lista que será clonada.
* \return Retorna una nueva lista que deberá ser liberada con list_release().
*
*/
list_t
list_clone(list_t list);

/** \brief Copia los elementos de una lista a otra.
*
* \param list: Lista a la que pertenece el item pasado por el parámetro dst.
* \param dst: Elemento pivote en donde se se ubicaran los elementos a copiar desde src.
* \param src: Elemento pivote de una lista que se le clonaran sus elementos para agregarlos en la lista destino dst.
* \param n: Cantidad máxima de elementos que copiaran.
* \return Retorna la cantidad de elementos agregados en la lista dst.
*
*/
size_t
list_copy(list_t list,
         struct list_item *dst,
         struct list_item *src,
         size_t n);

/** \brief Verifica si una lista esta vacia.
*
* \param list: Lista que se verificara.
* \return Retorna:
*  true: si la lista esta vacia.
*  false: Si contiene por lo menos un elemento.
*
*/
bool
list_empty(list_t list);


/** \brief Elimina un struct list_item * de su lista.
*
* \param list: Lista a la que pertenece el item.
* \param item: Elemento que se eliminara/liberara de su lista.
*
*/
void
list_erase(list_t list,
          struct list_item *item);

/** \brief Libera la memoria un struct list_item * NO RELACIONADA con una lista (miembro list debe ser igual a NULL).
*
* \param item: Elemento que se eliminara/liberara de su lista.
* \param callback_release_value: Callback a la función que esta encargada de liberar la memoria del miembro value.
*
*/
void
list_release_item(struct list_item *item,
                 list_callback_release_item callback_release_value);

/** \brief Remueve la relación que tiene el elemento con su lista madre (Usar con cuidado).
*
* \param list: Lista a la que se le extraerá el elemento.
* \param item: Elemento que se extraerá de su lista.
* \return Retorno el valor pasado en el parámetro item si se extrajo correctamente, de lo contrario retorna NULL.
*
*
* \code
* void
* list_release_item(struct list_item *item,
*                   list_callback_release_item callback_release_value) {
*     if (!item)
*         return;
*
*     if (callback_release_value)
*         callback_release_value(item->value);
* #ifdef LIST_INTEGRAL_RELATIONSHIP
*     free(list_extract(NULL, item));
* #else
*     free(list_extract(NULL, item));
* #endif
* }
* \endcode
*
*/
struct list_item*
list_extract(list_t list, struct list_item *item);

/** \brief Busca un valor a partir de un pivote indicado dentro de una lista.
*
* \param list: Lista a la que pertenecen los elementos (incluye parámetro item).
* \param item: Elemento pivote desde el cual se empezara a buscar el valor indicado en value.
* si es NULL iniciara desde el inicio de la lista.
* \param value: Valor a buscar en la lista a partir de el pivote indicado.
* \return Retorna NULL si no se a encontrado dentro de la lista en caso
* contrario retorna el elemento .
*
*/
struct list_item*
list_findnext(list_t list,
             struct list_item *item,
             list_value_t value);


/** \brief Busca un valor a partir de un pivote indicado dentro de una lista.
*
* \param list: Lista a la que pertenecen los elementos.
* \param item: Elemento pivote desde el cual se empezara a buscar el valor indicado en value,
* si es NULL iniciara a buscar desde el final de la lista.
* \param value: Valor a buscar en la lista antes de el pivote indicado.
* \return Retorna NULL si no se a encontrado dentro de la lista en caso
* contrario retorna el puntero al item.
*/
struct list_item*
list_findprev(list_t list,
             struct list_item *item,
             list_value_t value);

#ifdef LIST_INTEGRAL_RELATIONSHIP
/** \brief Obtiene la lista a la cual pertenece un item.
*
* \param item: elemento a consultar.
* \return Devuelve la lista a la cual pertenece dicho item; NULL si no pertenece a ninguna lista.
*
*/
list_t
list_getlist(struct list_item *item);
#endif

/** \brief Mezcla dos listas generando una nueva lista que deberá ser liberada con list_release().
*
* \param list1: Los elementos de esta lista se agregaran al inicio.
* \param list2: Los elementos de esta lista se agregaran al seguidos de los de list1.
* \return Retorna una nueva lista que  contendrán  las copias de las dos listas espesificadas.
*
*/
list_t
list_join(list_t list1,
         list_t list2);

/** \brief Agrega un valor al final de la lista.
*
* \param list: lista a la cual se le agregara un elemento nuevo.
* \param value: Valor a agregar a la lista.
* \return Retorna el puntero al item en la lista, NULL si fallo.
*
*/
struct list_item*
list_pushback(list_t list,
             list_value_t value);

/** \brief Agrega un elemento struct list_item al final de la lista (No crea un duplicado del elemento).
*
* \param list: lista a la cual se le agregara un elemento nuevo.
* \param item: Puntero al elemento struct list_item a relacionar con la lista.
* \return Retorna el puntero al item en la lista (el retorno es igual a el parámetro item), NULL si fallo.
*
*/
struct list_item*
list_pushback_item (list_t list,
                   struct list_item *item);

/** \brief Agrega un valor al inicio de la lista.
*
* \param list: Lista a la cual se le agregara un elemento nuevo.
* \param value: Valor a agregar a la lista.
* \return Retorna el puntero al item en la lista.
*
*/
struct list_item*
list_pushfront(list_t list,
              list_value_t value);

/** \brief Agrega un elemento struct list_item al inicio de la lista (No crea un duplicado del elemento).
*
* \param list: lista a la cual se le agregara un elemento nuevo.
* \param item: Puntero al elemento struct list_item a relacionar con la lista.
* \return Retorna el puntero al item en la lista (el retorno es igual a el parámetro item), NULL si fallo.
*
*/
struct list_item*
list_pushfront_item (list_t list,
                    struct list_item *item);

/** \brief Agrega un valor en la lista después de un elemento indicado como pivote.
*
* \param list: lista en la que se agregara.
* \param pivot: Elemento pivote que esta dentro de una lista, si el valor es NULL value se agregara al final de la lista.
* \param value: Valor a agregar a la lista después del pivote.
* \return Retorna el puntero al item en la lista, NULL si fallo.
*
*/
struct list_item*
list_pushnext(list_t list,
             struct list_item *pivot,
             list_value_t value);

/** \brief Agrega un elemento struct list_item después de un elemento indicado como pivote (No crea un duplicado del elemento).
*
* \param list: lista en la que se agregara.
* \param pivot: Elemento pivote que esta dentro de una lista, si el valor es NULL itemnew se agregara al final de la lista.
* \param itemnew: Puntero al elemento struct list_item a relacionar con la lista.
* \return Retorna el puntero al item en la lista (el retorno es igual a el parámetro itemnew), NULL si fallo.
*
*/
struct list_item*
list_pushnext_item(list_t list,
                  struct list_item *pivot,
                  struct list_item *itemnew);


/** \brief Agrega un elemento en la lista antes de un elemento indicado.
*
* \param list: lista en la que se agregara.
* \param pivot: Elemento pivote que esta dentro de una lista, si el valor es NULL value se agregara al final de la lista.
* \param value: Valor a agregar a la lista antes del pivote.
* \return Retorna el puntero al item en la lista, NULL si fallo.
*
*/
struct list_item*
list_pushprev(list_t list,
             struct list_item *pivot,
             list_value_t value);

/** \brief Agrega un elemento struct list_item antes de un elemento indicado como pivote (No crea un duplicado del elemento).
*
* \param list: lista en la que se agregara.
* \param pivot: Elemento pivote que esta dentro de una lista, si el valor es NULL itemnew se agregara al final de la lista.
* \param itemnew: Puntero al elemento struct list_item a relacionar con la lista.
* \return Retorna el puntero al item en la lista (el retorno es igual a el parámetro itemnew), NULL si fallo.
*
*/
struct list_item*
list_pushprev_item(list_t list,
                  struct list_item *pivot,
                  struct list_item *itemnew);

/** \brief Destruye una lista, los elementos también son liberados.
*
* \param list: Puntero a la struct list a destruir.
*/
void
list_release(list_t list);

/** \brief Obtiene la cantidad de elementos en la lista.
*
* \param list: Lista de la cual se retornaran la cantidad de elementos almacenados en ella.
* \return Retorna la cantidad de elementos en la lista.
*
*/
size_t
list_size(list_t list);

/** \brief Intercambia los elementos de cada lista.
*
* \param list1: Lista involucrada que se cambiaran los elementos con list2.
* \param list2: Lista involucrada que se cambiaran los elementos con list1.
* \return Retorna TRUE si no hubo errores y FALSE si no se puedo intercambiar los elementos.
*
*/
void
list_swap(list_t list1,
         list_t list2);

#endif // LIST_H_INCLUDED



list.c

#include "include/List.h"

/** \brief callback predeterminado que se encarga de crear un duplicado del queue_value_t para el stack_item_t.
 *
 * \param value: queue_value_t que se asignara.
 * \return Debe retornarse el queue_value_t a asignar al stack_item_t que se esta creando.
 *
 */
list_value_t
list_callback_clone_item_default(const list_value_t value) {
   return value;
}


/** \brief callback predeterminado que se encarga de destruir la memoria asignada al stack_item_t.
 *
 * \param value: queue_value_t que se liberara.
 *
 */
void
list_callback_release_item_default(const list_value_t value) {
   /// none code
}


/** \brief callback predeterminado que se encarga comparar dos list_value_t.
 *
 * \param value1: se comparara con value2.
 * \param value2: se comparara con value1.
 * \return Retorna el resultado de la comparación.
 * LIST_CMP_LESS_THAT: Si value1 < value2.
 * LIST_CMP_EQUAL: Si value1 == value2.
 * LIST_CMP_GREATER_THAT: Si value1 > value2.
 *
 */
enum list_cmp
list_callback_compare_item_default(const list_value_t value1,
                                  const list_value_t value2) {
   if (value1 > value2) {
       return LIST_CMP_GREATER_THAT;
   } else if (value1 < value2) {
       return LIST_CMP_LESS_THAT;
   }
   return LIST_CMP_EQUAL;
}

struct list_item*
list_after(struct list_item *item) {
   return item ? item->next : NULL;
}

list_t
list_allocator(list_callback_clone_item       clone_item,
              list_callback_release_item     release_item,
              list_callback_compare_item     compare_item) {
   list_t list = malloc(sizeof (struct list));
   list->first = list->last = NULL;
#ifdef LIST_INTEGRAL_RELATIONSHIP
   list->size = 0;
#endif //LIST_INTEGRAL_RELATIONSHIP
   list->clone_item = clone_item ? clone_item : list_callback_clone_item_default;
   list->release_item = release_item ? release_item : list_callback_release_item_default;
   list->compare_item = compare_item ? compare_item : list_callback_compare_item_default;
   return list;
}

void
list_allocator_array(list_t *array,
                    size_t n,
                    list_callback_clone_item       clone_item,
                    list_callback_release_item     release_item,
                    list_callback_compare_item     compare_item) {
   for (register size_t i = 0; i < n; ++i)
       array[i] = list_allocator(clone_item, release_item, compare_item);
}

struct list_item*
list_assign(list_t list,
           size_t n,
           list_value_t value) {
   struct list_item *ret = NULL;

   if (!list)
       return NULL;

   list_clear(list);
   ret = (n > 0) ? list_pushback(list, value) : NULL;

   for (register size_t i = 1; i < n; i++)
       list_pushback(list, value);

   return ret;
}

struct list_item*
list_back(list_t list) {
   return list ? list->last : NULL;
}

struct list_item*
list_before(struct list_item *item) {
   return item ? item->prev : NULL;
}

struct list_item*
list_begin(list_t list) {
   return list ? list->first : NULL;
}

size_t
list_clear(list_t list) {
   struct list_item *item = NULL;
   size_t     ret = 0;
   while((item = list->first) != NULL) {
       list_erase(list, item);
       ++ret;
   }
   return ret;
}

list_t
list_clone(list_t list) {
   list_t ret = NULL;
   struct list_item *item = NULL;

   if (!list)
       return NULL;

   ret = list_allocator(list->clone_item, list->release_item, list->compare_item);

   for (item = list_begin(list); item != NULL; item = list_after(item))
       list_pushback(ret, item->value);

   return ret;
}

size_t
list_copy(list_t list,
         struct list_item *dst,
         struct list_item *src,
         size_t n) {
   size_t ret = 0;

   if (!(dst && src)) return 0;
#ifdef LIST_INTEGRAL_RELATIONSHIP
   if (!(dst->list && dst->list == list)) return 0;
#endif //LIST_INTEGRAL_RELATIONSHIP

   while (n > 0 && src != NULL) {
       list_pushback(list, src->value);
       src = src->next;
       --n; ++ret;
   }

   return ret;
}

bool
list_empty(list_t list) {
   return  list && list->first && list->last ? true : false;
}

void
list_erase(list_t list,
          struct list_item *item) {
   if (!(item && list)) return;
#ifdef LIST_INTEGRAL_RELATIONSHIP
   else if (item->list != list) return;
#endif //LIST_INTEGRAL_RELATIONSHIP
   if (list && list->release_item)
       list->release_item(item->value);

   free(list_extract(list, item));
}

void
list_release_item(struct list_item *item,
                 list_callback_release_item callback_release_value) {
   if (!item)
       return;

   if (callback_release_value)
       callback_release_value(item->value);
#ifdef LIST_INTEGRAL_RELATIONSHIP
   free(list_extract(NULL, item));
#else
   free(list_extract(NULL, item));
#endif // LIST_INTEGRAL_RELATIONSHIP
}

struct list_item*
list_extract(list_t list,
            struct list_item *item) {
   if (!item) return NULL;
#ifdef LIST_INTEGRAL_RELATIONSHIP
   else if (item->list != list) return NULL;
#endif // LIST_INTEGRAL_RELATIONSHIP

   if (list) {
       if (list->first == item) list->first = item->next;
       if (list->last == item) list->last = item->prev;

   } else if (item->prev || item->next) {
       return NULL;
   }
   if (item->prev) item->prev->next = item->next;
   if (item->next) item->next->prev = item->prev;
   item->prev = NULL;
   item->next = NULL;
#ifdef LIST_INTEGRAL_RELATIONSHIP
   --(list->size);
   item->list = NULL;
#endif // LIST_INTEGRAL_RELATIONSHIP
   return item;
}

struct list_item*
list_findnext(list_t list,
             struct list_item *item,
             list_value_t value) {

   if (!list) return NULL;
   else if (!list->compare_item) return NULL;
   if (!item) item = list->first;
#ifdef LIST_INTEGRAL_RELATIONSHIP
   else if (item->list != list) return NULL;
#endif // LIST_INTEGRAL_RELATIONSHIP

   struct list_item   *now = item;

   do {
       if ((list->compare_item)(now->value, value) & LIST_CMP_EQUAL)
           return now;
       now = now->next;
   } while (now);

   return NULL;
}

struct list_item*
list_findprev(list_t list,
             struct list_item *item,
             list_value_t value) {
   if (!list) return NULL;
   else if (!list->compare_item) return NULL;
   if (!item) item = list->last;
#ifdef LIST_INTEGRAL_RELATIONSHIP
   else if (item->list != list) return NULL;
#endif // LIST_INTEGRAL_RELATIONSHIP

   struct list_item   *now = item;

   do {
       if ((list->compare_item)(now->value, value) & LIST_CMP_EQUAL)
           return now;
       now = now->prev;
   } while (now);

   return NULL;
}

#ifdef LIST_INTEGRAL_RELATIONSHIP
list_t
list_getlist(struct list_item *item) {
   if (!item) return NULL;
   return item->list;
}
#endif // LIST_INTEGRAL_RELATIONSHIP

list_t
list_join(list_t list1,
         list_t list2) {
   list_t              list = list_clone(list1);
   struct list_item    *item = NULL;

   for (item = list_begin(list2); item != NULL; item = list_after(item))
       list_pushback(list, item->value);
   return list;
}

struct list_item*
list_pushback(list_t list,
             list_value_t value) {
   struct list_item   *itemnew = NULL;

   if (list && !list->clone_item)
       return NULL;

   itemnew = malloc(LIST_SIZE_ITEM);
#ifdef LIST_INTEGRAL_RELATIONSHIP
   itemnew->list = NULL;
#endif

   if (list_pushback_item(list, itemnew) != itemnew) {
       free(itemnew);
       return NULL;
   }

   itemnew->value = (list->clone_item)(value);

   return list->last;
}

struct list_item*
list_pushback_item (list_t list,
                   struct list_item *item) {
#ifdef LIST_INTEGRAL_RELATIONSHIP
   if (!(list && item && !item->list))
       return NULL;
#else
   if (!(list && item))
       return NULL;
#endif // LIST_INTEGRAL_RELATIONSHIP

   if (!(list->first && list->last)) {
       list->first = item;
       item->prev = NULL;
   } else {
       list->last->next = item;
       item->prev = list->last;
   }

   item->next = NULL;
#ifdef LIST_INTEGRAL_RELATIONSHIP
   ++(list->size);
   item->list = list;
#endif // LIST_INTEGRAL_RELATIONSHIP
   list->last = item;

   return item;
}

struct list_item*
list_pushfront(list_t list,
              list_value_t value) {
   struct list_item   *itemnew = NULL;

   if (list || !list->clone_item)
       return NULL;

   itemnew = malloc(LIST_SIZE_ITEM);
#ifdef LIST_INTEGRAL_RELATIONSHIP
   itemnew->list = NULL;
#endif // LIST_INTEGRAL_RELATIONSHIP

   if (list_pushfront_item(list, itemnew) != itemnew) {
       free(itemnew);
       return NULL;
   }
   itemnew->value = (list->clone_item)(value);

   return list->first;
}

struct list_item*
list_pushfront_item(list_t list,
                   struct list_item *item) {
#ifdef LIST_INTEGRAL_RELATIONSHIP
   if (!(list && item && !item->list))
       return NULL;
#else
   if (!(list && item))
       return NULL;
#endif // LIST_INTEGRAL_RELATIONSHIP

   if (!(list->first && list->last)) {
       list->last = item;
       item->next = NULL;
   } else {
       list->first->prev = item;
       item->next = list->first;
   }

   item->prev = NULL;

#ifdef LIST_INTEGRAL_RELATIONSHIP
   ++(list->size);
   item->list = list;
#endif // LIST_INTEGRAL_RELATIONSHIP

   list->first = item;

   return item;
}

struct list_item*
list_pushnext(list_t list,
             struct list_item *pivot,
             list_value_t value) {
   if (!list) return NULL;
   if (!pivot) pivot = list->last;
#ifdef LIST_INTEGRAL_RELATIONSHIP
   else if (pivot->list != list) return NULL;
#endif // LIST_INTEGRAL_RELATIONSHIP

   struct list_item *itemnew = malloc(LIST_SIZE_ITEM);

   if (list_pushnext_item(list, pivot, itemnew) != itemnew) {
       free(itemnew);
       return NULL;
   }

   itemnew->value = (list->clone_item)(value);

   return itemnew;
}

struct list_item*
list_pushnext_item(list_t list,
                  struct list_item *pivot,
                  struct list_item *itemnew) {

   if (!(list && itemnew)) return NULL;
   if (!pivot) pivot = list->last;
#ifdef LIST_INTEGRAL_RELATIONSHIP
   else if (pivot->list != list) return NULL;
#endif // LIST_INTEGRAL_RELATIONSHIP

   if (pivot) {
       if (!pivot->next)
           return list_pushback_item(list, itemnew);
       pivot->next->prev = itemnew;
       itemnew->next = pivot->next;
       pivot->next = itemnew;
       itemnew->prev = pivot;
#ifdef LIST_INTEGRAL_RELATIONSHIP
       ++(itemnew->list->size);
       itemnew->list = pivot->list;
#endif // LIST_INTEGRAL_RELATIONSHIP
       return itemnew;
   } else {
       return list_pushback_item(list, itemnew);
   }

   return NULL;
}

struct list_item*
list_pushprev(list_t list,
             struct list_item *pivot,
             list_value_t value) {

   if (!list) return NULL;
   if (!pivot) pivot = list->first;
#ifdef LIST_INTEGRAL_RELATIONSHIP
   else if (pivot->list != list) return NULL;
#endif // LIST_INTEGRAL_RELATIONSHIP

   struct list_item *itemnew = malloc(LIST_SIZE_ITEM);

   if (list_pushprev_item(list, pivot, itemnew) != itemnew) {
       free(itemnew);
       return NULL;
   }

   itemnew->value = (list->clone_item)(value);

   return itemnew;
}

struct list_item*
list_pushprev_item(list_t list,
                  struct list_item *pivot,
                  struct list_item *itemnew) {

   if (!(list && itemnew)) return NULL;
   if (!pivot) pivot = list->first;
#ifdef LIST_INTEGRAL_RELATIONSHIP
   else if (pivot->list != list) return NULL;
#endif // LIST_INTEGRAL_RELATIONSHIP

   if (pivot) {
       if (!pivot->prev)
           return list_pushfront_item(list,itemnew);
       pivot->prev->next = itemnew;
       itemnew->prev = pivot->prev;
       pivot->prev = itemnew;
       itemnew->next = pivot;
#ifdef LIST_INTEGRAL_RELATIONSHIP
       itemnew->list = pivot->list;
       ++(itemnew->list->size);
#endif // LIST_INTEGRAL_RELATIONSHIP
       return itemnew;
   } else {
       return list_pushfront_item(list,itemnew);
   }

   return NULL;
}

void
list_release(list_t list) {
   list_clear(list);
   free(list);
}

void
list_release_array(list_t *array,
                  size_t n) {
   for (register size_t i = 0; i < n; ++i)
       list_release(array[i]);
}

size_t
list_size(list_t list) {
#ifdef LIST_INTEGRAL_RELATIONSHIP
   return list ? list->size : 0;
#else
   size_t ret = 0;
   struct list_item *item = list ? list->first : NULL;
   while (item) {
       ++ret;
       item = item->next;
   }
   return ret;
#endif // LIST_INTEGRAL_RELATIONSHIP
}

void
list_swap(list_t list1,
         list_t list2) {
   if (!(list1 && list2)) return;
   struct list tmp = *list2;
   *list2 = *list1;
   *list1 = tmp;
#ifdef LIST_INTEGRAL_RELATIONSHIP
   for (struct list_item *item = list_begin(list1); item != NULL; item = list_after(item))
       item->list = list1;
   for (struct list_item *item = list_begin(list2); item != NULL; item = list_after(item))
       item->list = list2;
#endif // LIST_INTEGRAL_RELATIONSHIP
}


Dulces Lunas!¡.
#7
.
En los mercados (principalmente los "piratas" o en establecimientos no regulados, o simplemente de marcas desconocidas) se vendes dispositivos USB, MP3, MP4, etc... que aparentan una capacidad mayor al que realmente son.

Alguien tiene algo de información (mas que nada técnica como documentos... nada de la plataforma de Taringa o comentarios ajenos) del como modifican estos dispositivos.

Se que cambian del formato FAT al FAT-32 y crean una nueva partición del dispositivo (el cual esta oculto) y le dan un "Formateo" especial por medio de un software (Esto lo hacen los chinos para vender sus dispositivos mas caros), también se como detectar dichos dispositivos (ya he tenido la mala fortuna, que mejor dicho es lo mejor que me ha pasado debido a que me despierta esta curiosidad, aun que mi bolsillo me agreda).

Dulces Lunas!¡.
#8
Programación C/C++ / Sobre los Cast
26 Octubre 2012, 04:50 AM
.
¿Es bueno hacer varios cast de tipos?, Se que es recomendable pero no lo se hasta que punto.

por ejemplo:

list.h


typedef
enum {
   LIST_CMP_EQUAL          = 0x0,
   LIST_CMP_LESS_THAT      = 1,
   LIST_CMP_GREATER_THAT   = -1
} list_cmp_t;

typedef enum {
   LIST_SORT_ASC,
   LIST_SORT_DESC
} list_sort_t;

typedef void*               list_t;
typedef list_t*             list_ptr_t;

typedef intptr_t            list_value_t;
typedef list_value_t*       list_value_ptr_t;

typedef list_value_ptr_t    list_item_t;
typedef list_item_t*        list_item_ptr_t;

typedef size_t              list_size_t;
typedef list_size_t*        list_size_ptr_t;

/** Definición de Callback que se encarga de crear un duplicado del list_value_t indicado en parámetro value.
* @param value: list_value_t que se duplicara.
* @return Retorna el elemento list_value_t duplicado del parámetro value.
*/
typedef list_value_t(*list_callback_clone_item)(const list_value_t value);

/** Definicion de Callback que se encarga de destruir la memoria asignada al list_value_t.
* @param value: list_value_t que se liberara.
*/
typedef void(*list_callback_release_item)(const list_value_t value);

/** Definicion de CALLBACK que se encarga comparar dos list_value_t.
* @param value1: list_value_t que se comparara con value2.
* @param value2: list_value_t que se comparara con value1.
* @return Retorna el resultado de la comparación.
*    AVL_CMP_LESS_THAT: Si value1 < value2.
*    AVL_CMP_EQUAL: Si value1 == value2.
*    AVL_CMP_GREATER_THAT: Si value1 > value2.
*/
typedef list_cmp_t(*list_callback_compare_item)(const list_value_t value1, const list_value_t value2);


/** Crea una nueva lista de elementos list_value_t.
* @param clone_item: Apuntador a la función CALLBACK que retornara la copia del valor a asignar.
* @param release_item: Apuntador a la función CALLBACK que liberara la copia del valor duplicado en el list_callback_clone_item.
* @param clone_item: Apuntador a un proceso CALLBACK que se encarga de comparar los list_item_t.
* @return Retorna la nueva cola de datos queue_t que debera ser destruida con list_release().
*/
list_t list_allocator(list_callback_clone_item clone_item, list_callback_release_item release_item, list_callback_compare_item compare_item);



Código (c,36) [Seleccionar]


/** Tipo de dato list_data_t **/
typedef struct list_data        list_data_t;

/** Tipo de dato list_data_ptr_t **/
typedef list_data_t*            list_data_ptr_t;

/** Tipo de dato list_data_t **/
typedef struct list_item_data   list_item_data_t;

/** Tipo de dato list_data_ptr_t **/
typedef list_item_data_t*       list_item_data_ptr_t;

struct list_item_data {
   list_value_t            value;  /** Valor del item actual. **/
   list_item_data_ptr_t    prev;   /** Apuntador al item derecho. **/
   list_item_data_ptr_t    next;   /** Apuntador al item izquierdo. **/
   list_data_ptr_t         list;   /** Apuntador a los datos generales de la lista. **/
};

/** Estructura que guarda la información generalizada de una lista de datos **/
struct list_data {
   list_item_data_ptr_t        first;          /** Primer elemento agregado a la lista **/
   list_item_data_ptr_t        last;           /** Ultimo elemento agregado a la lista **/
   list_size_t                 size;           /** Cantidad de elementos **/
   list_callback_clone_item    clone_item;     /** Apuntador a la función CALLBACK que retornara la copia del valor a asignar **/
   list_callback_release_item  release_item;   /** Apuntador a la función CALLBACK que liberara la copia del valor duplicado en el list_callback_allocator **/
   list_callback_compare_item  compare_item;   /** Apuntador a la función CALLBACK que compara dos elementos de la lista **/
};

...

list_item_t
list_begin(list_t list) {
   if (list_empty(list)) return NULL;
   return (list_item_t)(((list_data_ptr_t)list)->first);
}



Tambien en casos donde provienen de un puntero X y se quiere convertir a un int32_t

Código (c,8,18,42,43,57) [Seleccionar]


/** Tipo de dato para la estructura AVL **/
typedef void*               avl_t;
typedef avl_t*              avl_ptr_t;

/** Tipo del dato que guarda el valor de un nodo **/
typedef uintptr_t           avl_value_t;
typedef avl_value_t*        avl_value_ptr_t;

typedef size_t              avl_size_t;
typedef avl_size_t*         avl_size_ptr_t;

/** Funcion que retorna el elemento menor de un elemento avl.
* @param value: Nodo del arbol AVL anteriormente creado con avl_allocator(), sirve como pivote.
* @return
*      NULl: No existe o hubo un error.
*/
avl_value_ptr_t avl_getlower(const avl_value_ptr_t value);

/**
* Funcion que busca un elemento (avl_value_t) en un elemento avl (avl_t)
* @param avl: Arbol AVL anteriormente creado con avl_allocator().
* @param value: Elemento a buscar.
* @return Retorna el apuntador al valor guardado.
*      NULL: No existe el valor buscado.
**/
avl_value_ptr_t avl_find(avl_t avl, const avl_value_t value);

/** Funcion que extrae un nodo del elemento avl indicado.
* @param avl: Apuntador a una variable tipo avl_t anteriormente creada con avl_allocator().
* @param value: Elemento que se buscara.
* @return
*      true: Si se extrajo del elemento avl
*      false: No se extrajo ya que no se encontro o el elemento avl esta vacio o se paso un parametro NULL.
*/
bool avl_remove(avl_t avl, const avl_value_ptr_t value);

avl_value_ptr_t avl_getroot(const avl_t avl);
...
       while (!avl_empty(avl)) {
           //Comprobamos la integridad de eliminación con estas dos lineas.
           avl_value_t elim = (avl_value_t)randomnumber(*avl_getlower(avl_getroot(avl)),
                                                        *avl_getupper(avl_getroot(avl)));
           avl_remove(avl, avl_find(avl, elim));
       }

long min(uint32_t a, uint32_t b) {
   return (a<b) ? a:b;
}

void swap(int32_t *a, int32_t *b) {
   *a ^= *b;
   *b ^= *a;
   *a ^= *b;
}

inline int randomnumber(int32_t lower, int32_t upper) {
   if (min(lower, upper) != lower) {
       swap(&lower, &upper);
   }
   return lower + rand() % ((upper + 1) - lower);
}



Uso los list_t como sinónimo de un tipo void* que apunta a una estructura list_data_t, es decir list_t = void* = list_data_ptr_t esto lo hago debido a que estoy creando varias bibliotecas donde las estructuras están dentro de los archivos .c (algunas) y creando varias funciones para el trato de las mismas... aun estoy espesando a creer que esto es una idiotes pero este no es el punto.

El problema radica al momento de compilar con -std=c99 -ansi -wall -pedantic -pedantic-errors

me salta:



/home/blackzerox/Documentos/Programacion/C/CScript/main.c|123|aviso: formato '%d' espera un argumento de tipo 'int', pero el argumento 2 es de tipo 'avl_size_t' [-Wformat]|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|130|error: el paso del argumento 1 de 'randomnumber' crea un entero desde un puntero sin una conversión|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|17|nota: se esperaba 'int32_t' pero el argumento es de tipo 'avl_t'|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|130|error: el paso del argumento 2 de 'randomnumber' crea un entero desde un puntero sin una conversión|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|17|nota: se esperaba 'int32_t' pero el argumento es de tipo 'avl_t'|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|144|aviso: formato '%d' espera un argumento de tipo 'int', pero el argumento 2 es de tipo 'avl_size_t' [-Wformat]|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|147|aviso: formato '%d' espera un argumento de tipo 'int', pero el argumento 2 es de tipo 'avl_size_t' [-Wformat]|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|160|aviso: formato '%d' espera un argumento de tipo 'int', pero el argumento 2 es de tipo 'avl_size_t' [-Wformat]|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|173|aviso: formato '%d' espera un argumento de tipo 'int', pero el argumento 2 es de tipo 'avl_size_t' [-Wformat]|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|189|aviso: formato '%d' espera un argumento de tipo 'int', pero el argumento 2 es de tipo 'avl_size_t' [-Wformat]|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|192|aviso: formato '%d' espera un argumento de tipo 'int', pero el argumento 2 es de tipo 'avl_size_t' [-Wformat]|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|228|aviso: formato '%d' espera un argumento de tipo 'int', pero el argumento 2 es de tipo 'map_size_t' [-Wformat]|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|248|aviso: formato '%d' espera un argumento de tipo 'int', pero el argumento 2 es de tipo 'map_size_t' [-Wformat]|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|251|aviso: formato '%d' espera un argumento de tipo 'int', pero el argumento 2 es de tipo 'map_size_t' [-Wformat]|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|264|aviso: formato '%d' espera un argumento de tipo 'int', pero el argumento 2 es de tipo 'map_size_t' [-Wformat]|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|276|aviso: formato '%d' espera un argumento de tipo 'int', pero el argumento 2 es de tipo 'map_size_t' [-Wformat]|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|291|aviso: formato '%d' espera un argumento de tipo 'int', pero el argumento 2 es de tipo 'map_size_t' [-Wformat]|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|293|aviso: formato '%d' espera un argumento de tipo 'int', pero el argumento 2 es de tipo 'map_size_t' [-Wformat]|
/home/blackzerox/Documentos/Programacion/C/CScript/main.c|112|aviso: variable 'value' sin usar [-Wunused-variable]|
||=== Build finished: 19 errors, 0 warnings ===|



Pero claro compilando con -w se arregla todo y compila perfectamente, esto es un problema que apenas vengo captando y solucionando con varios cast pero lo veo muy, no encuentro palabras para esto solo no me agrada.



-------------- Build: Debug in CCScript_Linux ---------------

Compiling: main.c
Compiling: src/CSAVL.c
Compiling: src/CSArray.c
Compiling: src/CSBlockmem.c
Compiling: src/CSByte.c
Compiling: src/CSInfija2PreFija.c
Compiling: src/CSList.c
Compiling: src/CSMap.c
Compiling: src/CSQueue.c
Compiling: src/CSStack.c
Compiling: src/CSString.c
Compiling: src/CSUtiles.c
Compiling: src/CSVector.c
Compiling: src/CScript.c
Linking console executable: bin/Debug/CCScript_Linux
Output size is 30,17 KB
Process terminated with status 0 (0 minutes, 2 seconds)
0 errors, 0 warnings




  • ¿En que momentos en necesario realmente usar los cast?.
  • ¿Que tan bueno es usar typedef y en que casos (ademas de simplificar)?.
  • ¿Es indispensable forzar C99 con -std=c99 -ansi -wall -pedantic -pedantic-errors y por ende obligar los cast?.

Dulces Lunas!¡.
#9
Por que me marca error SIEMPRE cuando trato de dimensionar o acceder a la variable udtArray?

Código (delphi) [Seleccionar]


type
  TValue = record
    iFlags: Integer;
    fValue: real;
  end;

  TArrayValue = Array Of TValue;

  TPila = class(TObject)
  private
    udtArray: TArrayValue; // Array Of TValue
  public
    constructor Create(); overload;
    constructor Create(var oPila: TPila); overload;
    procedure Push(udtVar: TValue); overload;
    procedure Push(fValue: Real; iFlags: Integer); overload;
    function Pop(): TValue;
    function Count(): Integer;
    function Get(Index: Integer): TValue;
    procedure Invert();
    procedure Clear();
    procedure Clone(var oPila: TPila);
  end;

implementation

constructor TPila.Create();
begin
  Self.Clear;
end;

constructor TPila.Create(var oPila: TPila);
begin
  Self.Clone(oPila);
end;

procedure TPila.Push(fValue: Real; iFlags: Integer);
var
  iLength: Integer;
  iIndex: Integer;
begin
  iIndex := Self.Count;
  iLength := (iIndex + 1);
  SetLength(Self.udtArray, iLength);
  udtArray[iIndex].iFlags := iFlags;
  udtArray[iIndex].fValue := fValue;
end;

procedure TPila.Push(udtVar: TValue);
begin
  Push(udtVar.fValue, udtVar.iFlags);
end;

function TPila.Pop(): TValue;
var
  iNewLength: Integer;
  udtRet: TValue;
begin
  if (Self.Count = 0) then begin
    udtRet.iFlags := 0;
    udtRet.fValue := 0;
  end else begin
    iNewLength := High(Self.udtArray);
    udtRet := Self.udtArray[iNewLength];
    SetLength(Self.udtArray, iNewLength);
  end;
  Result := udtRet;
end;

function TPila.Count(): Integer;
begin
  Result := Length(Self.udtArray);
end;

procedure TPila.Invert();
var
  i: Integer;
  j: Integer;
begin
  if not (Count = 0) then begin
    j := High(Self.udtArray);
    for i:= Low(Self.udtArray) to (High(Self.udtArray) div 2) do begin
      SwapFloat(Self.udtArray[i].fValue, Self.udtArray[j].fValue);
      SwapInt(Self.udtArray[i].iFlags, Self.udtArray[j].iFlags);
      j := (j - 1);
    end;
  end;
end;

function TPila.Get(Index: Integer): TValue;
var
  udtRet: TValue;
begin
  if (Index < Self.Count) then begin
    udtRet := Self.udtArray[Index];
  end else begin
    udtRet.iFlags := 0;
    udtRet.fValue := 0;
  end;
  Result := udtRet;
end;

procedure TPila.Clear();
begin
  SetLength(Self.udtArray, 0);
end;

procedure TPila.Clone(var oPila: TPila);
begin
  oPila.udtArray := Self.udtArray;
end;
#10
Sugerencias y dudas sobre el Foro / smiles
28 Enero 2012, 02:08 AM
.
No se ustedes si les da peresa estar editando los smiles o emoticos logos o csas asi pero no seria mejor crearse un pequeño script o PHP que elija el logo, e imagenes segun la temporada?, lo menciono por que ya entramos casi a Febrero y la navidad aun continua en el foro (pan de cada año y/o temporada)!¡.

Dulces Lunas!¡.
#11
Programación Visual Basic / [SRC] itsOkCRC32
27 Enero 2012, 00:06 AM
.
La funcion lo que realiza es una verificación del exe para saber si a ido modificaco o no (es una seguridad muy basica).

Edito--->
(NO ES NECESARIO) OJO si lo van a usar deberan realinear el formato PE... o usar los ultimos 4 bytes de el exe (habitualmente son bytes 0)

En un modulo...

Código (vb) [Seleccionar]


Option Explicit

#Const INSERTCRC32TOEXE = False

Public Function itsOkCRC32() As Boolean
'   //
'   //  Funcion itsOkCRC32 creada por BlackZeroX (http://infrangelux.hostei.com)
'   //
'   //  Instrucciones:
'   //  * COMPILA TU EXE FINAL con la constante INSERTCRC32TOEXE = false.
'   //  * Cambia INSERTCRC32TOEXE de false a true ( #Const INSERTCRC32TOEXE = true )
'   //  * Cambia la linea  {Open "c:\testCRC32.exe" For Binary As hFile} de este proceso con
'   //  la ruta del exe que compilaste anteriormente, por ejemplo {Open "c:\testCRC32.exe" For Binary As hFile}
'   //  * Ejecuta el proyecto desde este IDE, si todo a ido correctamente les aparecera un mensaje {"CRC32 configurado Correctamente"}.
'   //  * Comprube tu EXE Final {c:\testCRC32.exe} ejecutandolo directamente.
'   //  Si todo a hido correctamente el exe te mostrara {"CRC32 Correcto"} si solo has generado el exe y no cambiaste {INSERTCRC32TOEXE a true} te mostrara {"CRC32 erroneo"} en este ejemplo.

Dim byteData()              As Byte
Dim dwSizeFile              As Long
Dim dwCRC32ReadFile         As Long
Dim dwCRC32Generate         As Long
Dim oCRC32                  As cCRC32
Dim hFile                   As Integer

    hFile = FreeFile
#If (INSERTCRC32TOEXE = False) Then
    Open App.Path & "\" & App.EXEName & ".exe" For Binary As hFile
#Else
    Open "c:\testCRC32.exe" For Binary As hFile
#End If
        dwSizeFile = LOF(hFile)
        If ((dwSizeFile - 4) > 0) Then
#If (INSERTCRC32TOEXE = True) Then
            ReDim byteData(0 To (dwSizeFile - 1))
#Else
            ReDim byteData(0 To (dwSizeFile - 1 - 4))
#End If
            Get 1, , byteData
            Get 1, , dwCRC32ReadFile
           
            Set oCRC32 = New cCRC32
            dwCRC32Generate = oCRC32.GetByteArrayCrc32(byteData)
            Set oCRC32 = Nothing
           
            If (dwCRC32Generate = dwCRC32ReadFile) Then
                itsOkCRC32 = True
#If (INSERTCRC32TOEXE = True) Then
                MsgBox "CRC32 Ya se encontraba configurado."
            Else
                Put hFile, , dwCRC32Generate
                MsgBox "CRC32 configurado Correctamente."
                End
#End If
            End If
        End If
    Close hFile
   
End Function



cCRC32.cls (Modulo de clase)



Option Explicit

' This code is taken from the VB.NET CRC32 algorithm
' provided by Paul (wpsjr1@succeed.net) - Excellent work!

Private crc32Table() As Long

Public Function GetByteArrayCrc32(ByRef buffer() As Byte) As Long
Dim crc32Result     As Long:    crc32Result = &HFFFFFFFF
Dim i               As long
Dim iLookup         As long
   
   For i = LBound(buffer) To UBound(buffer)
      iLookup = (crc32Result And &HFF) Xor buffer(i)
      crc32Result = ((crc32Result And &HFFFFFF00) \ &H100) And 16777215 ' nasty shr 8 with vb :/
      crc32Result = crc32Result Xor crc32Table(iLookup)
   Next i
   
   GetByteArrayCrc32 = Not (crc32Result)

End Function



Private Sub Class_initialize()

    ' This is the official polynomial used by CRC32 in PKZip.
    ' Often the polynomial is shown reversed (04C11DB7).
    Dim dwPolynomial As Long
    dwPolynomial = &HEDB88320
    Dim i As Integer, j As Integer

    ReDim crc32Table(256)
    Dim dwCrc As Long

    For i = 0 To 255
        dwCrc = i
        For j = 8 To 1 Step -1
            If (dwCrc And 1) Then
                dwCrc = ((dwCrc And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
                dwCrc = dwCrc Xor dwPolynomial
            Else
                dwCrc = ((dwCrc And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
            End If
        Next j
        crc32Table(i) = dwCrc
    Next i

End Sub

Private Sub Class_Terminate()
    Erase crc32Table
End Sub



Ejemplo:

Código (vb) [Seleccionar]


option explicit

Sub main()
    If (itsOkCRC32) Then
        MsgBox "CRC32 Correcto"
    Else
        MsgBox "CRC32 erroneo"
    End If
End Sub



Decargar Ejemplo (Compilar en "C:\" el proyecto con el nombre "testCRC32.exe" o configurar las lineas segun lo requieran y con la constante en false, despues solo ejecutar desde el IDE con la constante en true):
http://infrangelux.sytes.net/FileX/index.php?dir=/BlackZeroX/Programacion/vb6/ejemplos%20VB6&file=itsOKCRC32.zip



Alternativa: http://foro.elhacker.net/programacion_visual_basic/src_self_crc32_check_01_poc-t351610.0.html

Dulces Lunas!¡.
#12
Foro Libre / -> Integrales
2 Diciembre 2011, 04:44 AM
Cual es la integral de log(x)?... se como hacer la de ln(x)... se que ln tiene base e... en el caso de log(x) no me dieron la base (es de un libro de calculo).

Pondria la formula de la integral completa que deseo resolver pero no es mi objetivo primordial... solo desearia saber cual es la integral de log(x) o de log(u) (notece que no es ln(x) ni ln(u)).

Nota: Preferiblemente de log(u) asi obvio a log(x) obviamente en todos los casos despreciando a x.

Dulces Lunas!¡.
#13
Foro Libre / chiste Informatico
24 Noviembre 2011, 07:01 AM
 :silbar: :silbar: :silbar:



;-) ;-) ;-) ;-) ;-) ;-)

Dulces Lunas!¡.
#14
Esta publicación la pongo debido a que muchos de nosotros empezamos a mentar madres a las ISP de manera injustificada... digo injustificada por que muchos de nosotros carecemos en algún momento de alguna Terminología en este caso la palabra Mega... pensamos que significa MegaByte pero no, significa Mega Bit ya que carece de Sufijo como MegaByte, GigaByte ya que:

* Mega (1048576 bits) es distinto de MegaByte (8388608 bits)
* Giga (1073741824 bits) es distinto de GigaByte (8589934592 bits)

En algunos lugares, y en muchos sitios se da el caso de que se contrata 1 Mega y los usuarios erróneamente dan un mal significado a Mega creyendo que se trata de un 1Mega Byte, pero cuando prueban su internet se dan cuenta que no es un Mega de bajada o de subida (para el caso sera lo mismo).

Un ejemplo es el servicio TELMEX Infinitum donde Dicen Claramente 1Mb = MegaBit cabe destacar que MB = MegaByte... (Es estos casos Mb y MB son distintos)...


http://www.telmex.com/mx/hogar/paquetes/paquete-conectes.html
http://www.telmex.com/mx/hogar/paquetes/paquete-acerques.html
http://www.telmex.com/mx/hogar/paquetes/sinlimites.html


En todos los Casos dice Mb y no MB

Si van al Router de este ISP podran ver algo similar a esto:



Como verán la parte resaltada en color rojo se puede apreciar que dice kbps esto no significa KiloBytes / segundo si no que significa  KiloBit / segundo.

Esto es debido a que kB = KiloByte y kb = kilobit pueden revisar esto último en la siguiente liga:

https://es.wikipedia.org/wiki/Kilobit

Citando la liga:

Citar

Un kilobit es una unidad de medida de información (abreviado kb o kbit).

En la práctica la unidad kilobit se usa para medir el tráfico de la información por un canal digital, y se representa como kilobits / segundo (kbps) esta unidad representa la cantidad de bits que se transfieren de un punto a otro en un segundo.


De todo esto se puede deducir lo siguiente...

Las empresas NO te venden un servicio de bytes si no de bits.
Las empresas en sus Anuncios Nunca dicen "MegaByte" dicen "Mega" y 1 Mega en escalas Binarias equivalen a 1 048 576 bits que es lo mismo a 128 kB/s (KiloBytes / segundo).

Por ejemplo con la ayuda de la siguiente escala:


1 unidad = 1 bit.
1 Kilo = 1024 unidades ( las unidades son bits por lo tanto se puede interpretar como 1024 bits o 1 kilo bit).
1 Mega = 1 kilo * 1 kilo = 1024 * 1024 = 1 048 576.
8 bits = Byte.


Más información en la siguiente liga: https://es.wikipedia.org/wiki/Prefijo_binario


Teniendo lo anterior en cuenta y sabiendo que no nos vendes Mega Bytes por segundo si no Mega Bits por segundo podemos deducir:

Si contratamos 4 Megas de bajada a la ISP X que nos da una subida de 512 kb (Notese que es kb NO kB son cosas distintas) de bajada se debe hacer lo siguiente para saber el LIMITE MAXIMO en kB/s (kiloBytes / s) reales:



Desendente de 4 Megas:
4 Mega = 1 Mega * 4 = 4 Mega = 1048576 * 4 = 4 194 304 b/s (pero lo queremos a kb/s no en b/s)
Convertimos a Bytes para eso dividimos los bits en bytes:
4 194 304 / 8 = 524 288 B/s (solo falta pasarlo a kB/s)
La velocidad de Desencente (Descarga) real es de 524 288 b/s (pasándolo a kB/s):
524 288 / 1 Kilo = 524 288 / 1024 = 512 kB/s <--- No podrás superar esta velocidad por mucho que quieras...
La bajada real es de:
512 kB/s <--- Es la velocidad de Subida Real Máxima que tienes contratada expresada en KiloBytes/Segundo.




Ascendente de 512 kb/s (Solo lo dividimos entre 8 para pasarlo a kB/s):
512 / 1 Byte  = 512 / 8 = 64 kB/s <--- No podrás superar esta velocidad por mucho que quieras...
La bajada real es de:
64 kB/s <--- Es la velocidad de Subida REAL Máxima que se tiene contratada expresada en KiloBytes/Segundo...

Como ven solo es Falta de conocimiento... y una Maldita publicidad engañosa de las ISP... que no es engañosa porque en ningún Comercial dicen "Conexión de hasta 1 MegaByte" si no que dicen claramente "Conexión de hasta 1 Mega" y al carecer de un Sufijo se traduce que no dicen en Bytes si no en Bits y debido a esto que casi nadie sabe termina creyendo que son MegaBytes y terminan refrescándole la madre a la ISP y los pobres de Atención a cliente terminan sufirendo de nuestra ignorancia.

Dulces Lunas!¡.
#15
Foro Libre / Creen en los ovnis?
19 Noviembre 2011, 11:19 AM
.
* Antes si alguien intenta agredir de cualquier manera y lo leen No hagan un Flame... pasen a Ignorarlo, solo quiero contar algo que hace unos instantes me ha sucedido y que me ha dejado PERPLEJO.

Bueno la cosa es que hace unos minutos tube un encuentro de urgencia de miar (liberacion de vegiga)... no se preocupen mi vegita esta ya vacia... pero cuando salgo de mi cuarto el cual esta en el techo de la casa de mis padre (mi centro de mando jajaja  :xD jajaja), miro unas luces algo extrañas, similares a un avion o reflejo de un alambre, pero o por Lucifer!¡. no era un avion estaban suspendidas y empesaron a bajar por hay en los volcanes entre el Popo y el iztaccihuatl (Quiero suponer mas no lo afirmo) la cosa es que me medio asuste la verdad, diferencie que no era un avion ni un elicoptero debido a que se veia que hiba a una velocidad demasiado LENTA hasta que la perdi de vista al igual que volvia subir y a perderse de vista, pero muy extraño se quedo sustependido dicho objeto entre las nubes...

Lo grabe en video pero no se ve nada (Camara Digital HD que no tiene vision Nocturna peor tantito).

Ya no creo que Jaime Mausan este Loco...

Nota: No voy a dormir hoy...

Dulces Lunas!¡.
#16
.
Es una correccion al codigo anterior por que contenia HORRORES...

desde el 1 al 999999999999999999999999999999999999999999999999999999999999999999

Ejemplo:

Código (vb) [Seleccionar]


Private Sub Form_Load()
   MsgBox numberToName(InputBox("Ingresa un numero cualquiera", "numberToName", "87984516512"))
End Sub



OutPut (Test Number: 87984516512):
Citar

ochenta y siete mil novecientos ochenta y cuatro millones quinientos dieci seis mil quinientos doce


Código (Vb) [Seleccionar]


'
'   /////////////////////////////////////////////////////////////
'   // Autor:   BlackZeroX ( Ortega Avila Miguel Angel )       //
'   //                                                         //
'   // Web:     http://InfrAngeluX.Sytes.Net/                  //
'   //                                                         //
'   //    |-> Pueden Distribuir Este codigo siempre y cuando   //
'   // no se eliminen los creditos originales de este codigo   //
'   // No importando que sea modificado/editado o engrandecido //
'   // o achicado, si es en base a este codigo                 //
'   /////////////////////////////////////////////////////////////
'   // http://infrangelux.hostei.com/index.php?option=com_content&view=article&id=8:arrtnum2string&catid=2:catprocmanager&Itemid=3
'   /////////////////////////////////////////////////////////////

Option Explicit

Public Function numberToName(ByVal sNumber As String) As String
'   //  MAXIMO  --> 999999999999999999999999999999999999999999999999999999999999999999 ' sección Decillones...

'   //  Millon          1 * 10^6
'   //  Billon          1 * 10^12
'   //  Trillon         1 * 10^18
'   //  Cuatrillón      1 * 10^24
'   //  Quintillón      1 * 10^30
'   //  Sextillón       1 * 10^36
'   //  Sptillon        1 * 10^42
'   //  Octillón        1 * 10^48
'   //  Sextillón       1 * 10^54
'   //  Octillón        1 * 10^60
'   //  <--Son bastantes numeros... como para seguirle no creen?-->

Dim i           As Long
Dim lLn         As Long
Dim sTmp        As String
Dim bCentena    As Byte
Dim bDecena     As Byte
Dim bUnidad     As Byte
Const MAXLEN    As Long = &H42

   lLn = Len(sNumber)
   If (lLn > MAXLEN) Or (lLn = 0) Then Exit Function
   
   sTmp = String$(MAXLEN, "0")
   
   Mid$(sTmp, MAXLEN - lLn + 1) = Mid$(sNumber, 1, lLn)
   
   For i = 1 To MAXLEN Step 3

       bCentena = CByte(Mid$(sTmp, i, 1))
       bDecena = CByte(Mid$(sTmp, i + 1, 1))
       bUnidad = CByte(Mid$(sTmp, i + 2, 1))
       
       numberToName = numberToName & centena(bUnidad, bDecena, bCentena) & _
                                     decena(bUnidad, bDecena) & _
                                     unidad(bUnidad, bDecena) & _
                                     IIf(Not (i = (MAXLEN - &H2)), getLeyenda(sNumber, i, bUnidad, bDecena, bCentena), "")
   Next

End Function

Private Function getLeyenda(ByRef sTmp As String, ByVal i As Long, ByVal bUnidad As Byte, ByVal bDecena As Byte, ByVal bCentena As Byte) As String
'   //  Se obtiene la leyenda con referencia a la ESCALA CORTA.

   Select Case i
       Case &H4
           If ((bCentena + bDecena) = 0) And (bUnidad = 1) Then
               getLeyenda = "decillon "
           ElseIf ((bCentena + bDecena + bUnidad) > 1) Then
               getLeyenda = "decillones "
           End If
           
       Case &HA
           If ((bCentena + bDecena) = 0) And (bUnidad = 1) Then
               getLeyenda = "nonillon "
           ElseIf ((bCentena + bDecena + bUnidad) > 1) Then
               getLeyenda = "nonillones "
           End If
           
       Case &H10
           If ((bCentena + bDecena) = 0) And (bUnidad = 1) Then
               getLeyenda = "octillón "
           ElseIf ((bCentena + bDecena + bUnidad) > 1) Then
               getLeyenda = "octillónes "
           End If
           
       Case &H16
           If ((bCentena + bDecena) = 0) And (bUnidad = 1) Then
               getLeyenda = "septillon "
           ElseIf ((bCentena + bDecena + bUnidad) > 1) Then
               getLeyenda = "septillones "
           End If
           
       Case &H1C
           If ((bCentena + bDecena) = 0) And (bUnidad = 1) Then
               getLeyenda = "sextillón "
           ElseIf ((bCentena + bDecena + bUnidad) > 1) Then
               getLeyenda = "sextillónes "
           End If
           
       Case &H22
           If ((bCentena + bDecena) = 0) And (bUnidad = 1) Then
               getLeyenda = "quintillón "
           ElseIf ((bCentena + bDecena + bUnidad) > 1) Then
               getLeyenda = "quintillónes "
           End If
           
       Case &H28
           If ((bCentena + bDecena) = 0) And (bUnidad = 1) Then
               getLeyenda = "cuatrillón "
           ElseIf ((bCentena + bDecena + bUnidad) > 1) Then
               getLeyenda = "cuatrillónes "
           End If
           
       Case &H2E
           If ((bCentena + bDecena) = 0) And (bUnidad = 1) Then
               getLeyenda = "trillon "
           ElseIf ((bCentena + bDecena + bUnidad) > 1) Then
               getLeyenda = "trillones "
           End If
           
       Case &H34
           If ((bCentena + bDecena) = 0) And (bUnidad = 1) Then
               getLeyenda = "billón "
           ElseIf ((bCentena + bDecena + bUnidad) > 1) Then
               getLeyenda = "billones "
           End If
           
       Case &H3A
           If ((bCentena + bDecena) = 0) And (bUnidad = 1) Then
               getLeyenda = "millón "
           ElseIf ((bCentena + bDecena + bUnidad) > 1) Then
               getLeyenda = "millones "
           End If
           
       Case Else
           If ((bCentena + bDecena + bUnidad) > 1) Then getLeyenda = "mil "
           
   End Select
   
End Function

Private Function centena(ByVal bUnidad As Byte, ByVal bDecena As Byte, ByVal bCentena As Byte) As String
   Select Case bCentena
       Case 1: If (bDecena + bUnidad) = 0 Then centena = "cien " Else centena = "ciento "
       Case 2: centena = "doscientos "
       Case 3: centena = "trescientos "
       Case 4: centena = "cuatrocientos "
       Case 5: centena = "quinientos "
       Case 6: centena = "seiscientos "
       Case 7: centena = "setecientos "
       Case 8: centena = "ochocientos "
       Case 9: centena = "novecientos "
   End Select
End Function

Private Function decena(ByVal bUnidad As Byte, ByVal bDecena As Byte) As String
   Select Case bDecena
       Case 1
           Select Case bUnidad
               Case 0: decena = "diez "
               Case 1: decena = "once "
               Case 2: decena = "doce "
               Case 3: decena = "trece "
               Case 4: decena = "catorce "
               Case 5: decena = "quince "
               Case 6 To 9: decena = "dieci "
           End Select
       Case 2
           If bUnidad = 0 Then
               decena = "veinte "
           ElseIf bUnidad > 0 Then
               decena = "veinti "
           End If
       Case 3: decena = "treinta "
       Case 4: decena = "cuarenta "
       Case 5: decena = "cincuenta "
       Case 6: decena = "sesenta "
       Case 7: decena = "setenta "
       Case 8: decena = "ochenta "
       Case 9: decena = "noventa "
   End Select
   If bUnidad > 0 And bDecena > 2 Then decena = decena + "y "
End Function

Private Function unidad(ByVal bUnidad As Byte, ByVal bDecena As Byte) As String
   If bDecena <> 1 Then
       Select Case bUnidad
           Case 1: unidad = "un "
           Case 2: unidad = "dos "
           Case 3: unidad = "tres "
           Case 4: unidad = "cuatro "
           Case 5: unidad = "cinco "
       End Select
   End If
   Select Case bUnidad
           Case 6: unidad = "seis "
           Case 7: unidad = "siete "
           Case 8: unidad = "ocho "
           Case 9: unidad = "nueve "
   End Select
End Function



Temibles Lunas!¡.
#17
Foro Libre / [Youtube] Por lo hizo un usuario...
8 Noviembre 2011, 10:33 AM
Solo vean este video... la tematica del video no importa revisen a detalle de donde demonios lo estan grabando...

[youtube=425,350]http://www.youtube.com/watch?v=ua2m6aGP34A&feature=fvwp&NR=1[/youtube]

Dulces Lunas!¡.
#18
.
Estando dicutiendo con Psyke1 sobre un metodo de reconocimiento de colores y casi 2 semanas indagando en ello he creado esta clase que verifica si un color es similar a otro (Despresiando el componente Alpha).

Aqui les dejo e modulo de clase:

* La funcion que tiene es que reconoce TONOS de un color y retorna true si es derivado del mismo color ya sea un color mas claro u opaco.

cSpectrumColor.cls

Código (vb) [Seleccionar]


'
'   /////////////////////////////////////////////////////////////
'   //                                                         //
'   // Autor:   BlackZeroX ( Ortega Avila Miguel Angel )       //
'   //                                                         //
'   // Web:     http://InfrAngeluX.Sytes.Net/                  //
'   //                                                         //
'   //    |-> Pueden Distribuir Este Codigo siempre y cuando   //
'   // no se eliminen los creditos originales de este codigo   //
'   // No importando que sea modificado/editado o engrandesido //
'   // o achicado, si es en base a este codigo                 //
'   /////////////////////////////////////////////////////////////
'  // http://infrangelux.hostei.com/index.php?option=com_content&view=article&id=35:cspectrumcolor&catid=15:catmoduloscls&Itemid=24
'   /////////////////////////////////////////////////////////////

Option Explicit

Private lRGBA       As Long

Public Property Get color() As Long
   color = lRGBA
End Property

Public Property Let color(ByVal lColor As Long)
   lRGBA = lColor
End Property

Public Function spectrumEqualL(ByVal lColorRGBA As Long, Optional ByVal lTolerance As Long = 10) As Boolean
Dim oSpectrum       As cSpectrumColor
   Set oSpectrum = New cSpectrumColor
   oSpectrum.color = lColorRGBA
   spectrumEqualL = spectrumEqualC(oSpectrum)
   Set oSpectrum = Nothing
End Function

Public Function spectrumEqualC(ByVal oSpectrum As cSpectrumColor, Optional ByVal lTolerance As Long = 10) As Boolean
Dim lRed(1)             As Long
Dim lGreen(1)           As Long
Dim lBlue(1)            As Long
Dim lBackColor          As Long

   lBackColor = oSpectrum.spectrumScale(oSpectrum.scaleFactorL(lRGBA) - 100)
   Call oSpectrum.componentsRGBA(lRed(1), lGreen(1), lBlue(1), &H0)
   oSpectrum.color = lBackColor

   Call componentsRGBA(lRed(0), lGreen(0), lBlue(0), &H0)

   If (max(lRed(0), lRed(1)) - min(lRed(0), lRed(1)) < lTolerance) Then
       If (max(lGreen(0), lGreen(1)) - min(lGreen(0), lGreen(1)) < lTolerance) Then
           If (max(lBlue(0), lBlue(1)) - min(lBlue(0), lBlue(1)) < lTolerance) Then
               spectrumEqualC = True
           End If
       End If
   End If
End Function

Public Function spectrumScale(ByVal lScale As Double) As Long
Dim lRed                As Long
Dim lGreen              As Long
Dim lBlue               As Long
'Dim lAlpha              As Long
   
   spectrumScale = lRGBA
   Call componentsRGBA(lRed, lGreen, lBlue, &H0)
   Call Me.colorFromRGBA(((lRed * (lScale / 100)) + lRed), ((lGreen * (lScale / 100)) + lGreen), ((lBlue * (lScale / 100)) + lBlue), &H0)
End Function

Public Function scaleFactorL(ByVal lColorRGBA As Long) As Double
Dim lRed                As Long
Dim lGreen              As Long
Dim lBlue               As Long
'Dim lAlpha              As Long
   
   Call componentsRGBA(lRed, lGreen, lBlue, &H0)
   
   Select Case max3(lRed, lGreen, lBlue)
       Case lRed: If (lRed) Then scaleFactorL = (lColorRGBA And &HFF&) * 100 / lRed
       Case lGreen: If (lGreen) Then scaleFactorL = ((lColorRGBA And &HFF00&) \ &H100&) * 100 / lGreen
       Case lBlue: If (lBlue) Then scaleFactorL = ((lColorRGBA And &HFF0000) \ &H10000) * 100 / lBlue
   End Select
   
End Function

Public Function scaleFactorC(ByVal oSpectrum As cSpectrumColor) As Double
   scaleFactorC = scaleFactorL(oSpectrum.color())
End Function

Private Function max(ByVal lVal1 As Long, ByVal lval2 As Long) As Long
   If (lVal1 > lval2) Then
       max = lVal1
   Else
       max = lval2
   End If
End Function

Private Function min(ByVal lVal1 As Long, ByVal lval2 As Long) As Long
   If (lVal1 < lval2) Then
       min = lVal1
   Else
       min = lval2
   End If
End Function

Private Function max3(ByVal lVal1 As Long, ByVal lval2 As Long, ByVal lval3 As Long) As Long
   max3 = max(max(lVal1, lval2), lval3)
End Function

Public Sub componentsRGBA(ByRef lRed As Long, ByRef lGreen As Long, ByRef lBlue As Long, ByRef lAlpha As Long)
   lRed = (lRGBA And &HFF&)
   lGreen = ((lRGBA And &HFF00&) / &H100&)
   lBlue = ((lRGBA And &HFF0000) / &H10000)
   lAlpha = ((lRGBA And &HFF000000) / &H1000000)
End Sub

Public Sub colorFromRGBA(ByVal lRed As Long, ByVal lGreen As Long, ByVal lBlue As Long, ByVal lAlpha As Long)
   lRGBA = (lRed)
   lRGBA = (lRGBA Or ((lGreen And &HFF&) * &H100&))
   lRGBA = (lRGBA Or ((lBlue And &HFF&) * &H10000))
   lRGBA = (lRGBA Or ((lAlpha And &HFF&) * &H1000000))
End Sub



Prueba/Test:

Código (vb) [Seleccionar]



'   //  En un form...
'   //  Se requieren 6 VScroll (con propiedad Index).
'   //  Se requieren 2 PictureBox (con propiedad Index)

Option Explicit

Dim oSpectrum(1)    As cSpectrumColor
   
Private Sub Form_Load()
Dim i           As Long
   Set oSpectrum(0) = New cSpectrumColor
   Set oSpectrum(1) = New cSpectrumColor
   
   For i = VScroll1.LBound To VScroll1.UBound
       VScroll1(i).min = 0
       VScroll1(i).max = 255
   Next
End Sub

Private Sub Form_Terminate()
   Set oSpectrum(0) = Nothing
   Set oSpectrum(1) = Nothing
End Sub

Private Sub VScroll1_Change(Index As Integer)
   Call VScroll1_Scroll(Index)
End Sub

Private Sub VScroll1_Scroll(Index As Integer)
Dim i           As Long
   If (Index > &H2) Then i = 1
   Picture1(i).BackColor = RGB(Int(VScroll1((i * 3)).Value), _
                               Int(VScroll1((i * 3) + 1).Value), _
                               Int(VScroll1((i * 3) + 2).Value))
   oSpectrum(i).color = Picture1(i).BackColor
   Debug.Print oSpectrum(i).spectrumEqualC(oSpectrum(i Xor 1)), i, i Xor 1
End Sub



P.D.: el codigo lo estare editando y publicando en cSpectrumColor.

Temibles Lunas!¡.
#19
Foro Libre / Google mata a Bambi
27 Septiembre 2011, 10:05 AM
Minuto 1:38  :xD :xD :xD :xD :xD :xD... podre animalito.

[youtube=425,350]http://www.youtube.com/watch?v=NrElZQ3ckM4&feature=related[/youtube]

Dulces Lunas!¡.
#20
Programación Visual Basic / [Source] cPushSort
27 Septiembre 2011, 04:33 AM
.
Esta clase solo sive para agregar elementos y buscar dichos elementos de la manera ams rapida posible que con un simple array y un simple for next.

* Permite Agregar un array long (Se puede mejorar el algoritmo respecto a esto, pero lo deje asi.).
* Permite agregar Elementos Unicos en el momento que se desee.
* Retorna la posicion (IndexOf) si se encuentra de lo contrario retorna un valor constante INVALIDVALUEARRAY.
* Permite consultar X elemento ( GetElement).
* Permite eliminar X elemento segun su indice ( Remove(); posiblemente se tenga que buscar primero con IndexOf() ).
* Retorna la cantidad de elementos.
* Tiene una tasa de BUSQUEDA MUY RAPIDA.

Código (vb) [Seleccionar]


'
'   /////////////////////////////////////////////////////////////
'   //                                                         //
'   // Autor:   BlackZeroX ( Ortega Avila Miguel Angel )       //
'   //                                                         //
'   // Web:     http://InfrAngeluX.Sytes.Net/                  //
'   //                                                         //
'   //    |-> Pueden Distribuir Este Codigo siempre y cuando   //
'   // no se eliminen los creditos originales de este codigo   //
'   // No importando que sea modificado/editado o engrandesido //
'   // o achicado, si es en base a este codigo                 //
'   /////////////////////////////////////////////////////////////

Option Explicit

Private lMem()          As Long
Private lCount          As Long
Private bDuplicate      As Boolean

Public Sub clear()
    Erase lMem()
    lCount = 0
End Sub

Public Property Get Count() As Long
    Count = lCount
End Property

'   //  Retorna la cantidad de elementos restantes.
Public Function Remove(ByVal lIndex As Long) As Long
    Remove = RemoveInArrayLong(lIndex, lMem())
End Function

Public Property Get DuplicateElements() As Boolean
    DuplicateElements = bDuplicate
End Property

Public Property Let DuplicateElements(ByVal bBool As Boolean)
    bDuplicate = bBool
End Property

'   //  Agrega un array a la coleccion y retorna la cantidad de elementos agregados a ella.
Public Function AddArray(ByRef lArray() As Long) As Long
Dim i                   As Long
Dim c                   As Long
    If Not (ItsArrayINI(VarPtrA(lArray))) Then Exit Function
    c = lCount
    For i = LBound(lArray()) To UBound(lArray())
        Me.Add lArray(i)
    Next
    AddArray = (lCount - c) '   //  Cantidad de elementos REALMENTE AGREGADOS: es igual a la direfencia del valor anterior y el actual de lCount.
End Function

'   //  Inserta en el Array el elemento Dado de manera Ascendente.
'   //  Agrega lVal en la coleccion de manera ordenada, y retorna el indice de su hubicacion.
'   //  Se retorna el indice de la hubicacion (...cambia este indice si se agrega otro y es menor a este...).
Public Function Add(ByVal lVal As Long) As Long
Dim lRetPos             As Long
    '   //  Buscamos la posicion en donde insertar...
    If ExitsInArray(lVal, lMem(), lRetPos) And Not bDuplicate Then Exit Function
    ReDim Preserve lMem(lCount)
    lCount = (lCount + 1)
    If ((lCount - 1) - lRetPos) Then '   //  Recorremos a la derecha TODOS los elementos.
        CopyMemory VarPtr(lMem(lRetPos + 1)), VarPtr(lMem(lRetPos)), ((lCount - lRetPos) * &H4)
    End If
    lMem(lRetPos) = lVal
    Add = lRetPos
End Function

'   //  Obtenemos una copia de la coleccion de elementos.
Public Function GetArray() As Long()
    GetArray = lMem()
End Function

Public Function IndexOf(ByVal lVal As Long) As Long
    If Not ExitsInArray(lVal, lMem, IndexOf) Then IndexOf = INVALIDVALUEARRAY
End Function

Public Function GetElement(ByVal lIndex As Long) As Long
    If (lIndex < lCount) Then GetElement = lMem(lIndex)
End Function

Private Function ExitsInArray(ByRef lVal As Long, ByRef lArray() As Long, ByRef lRetPos As Long) As Boolean
Dim lLIndex                 As Long
Dim lUIndex                 As Long
Dim iSortType               As Long

    If Not (ItsArrayINI(VarPtrA(lArray))) Then lRetPos = 0: Exit Function
   
    lLIndex = LBound(lArray())
    lUIndex = UBound(lArray())
   
    If (lArray(lUIndex) < lArray(lLIndex)) Then
        SwapLong lLIndex, lUIndex
        iSortType = 1
    End If

    If (lVal < lArray(lLIndex)) Then
        lRetPos = lLIndex
    ElseIf (lVal = lArray(lLIndex)) Then
        lRetPos = lLIndex
        ExitsInArray = True
    Else
        If (lVal > lArray(lUIndex)) Then
            lRetPos = lUIndex
        ElseIf (lVal = lArray(lUIndex)) Then
            lRetPos = lUIndex
            ExitsInArray = True
        Else
            Do Until ExitsInArray
                lRetPos = ((lLIndex + lUIndex) \ 2)
                If ((lRetPos <> lLIndex) And (lRetPos <> lUIndex)) Then
                    If (lArray(lRetPos) < lVal) Then
                        lLIndex = lRetPos
                    ElseIf (lArray(lRetPos) > lVal) Then
                        lUIndex = lRetPos
                    ElseIf (lArray(lRetPos) = lVal) Then
                        ExitsInArray = True
                    End If
                Else
                    Exit Do
                End If
            Loop
        End If
    End If
   
    If Not (ExitsInArray) Then              '   //  Obtenemos la posicion donde deberia estar dicho elemento.
        If (iSortType = 1) Then
            If (lArray(lRetPos) > lVal) Then lRetPos = (lRetPos - 1)
        Else
            If (lArray(lRetPos) < lVal) Then lRetPos = (lRetPos + 1)
        End If
    End If
   
End Function

Private Sub Class_Terminate()
    Call Me.clear
End Sub



En un Modulo...
Código (vb) [Seleccionar]


Option Explicit

Public Const INVALIDVALUEARRAY As Long = (-1)

Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByVal pDest As Long, ByVal pSrc As Long, ByVal ByteLen As Long)
Public Declare Function VarPtrA Lib "msvbvm60.dll" Alias "VarPtr" (ByRef Ptr() As Any) As Long

Public Function ItsArrayINI(ByVal lngPtr As Long, Optional LnBytes As Long = 4) As Boolean
Dim lng_PtrSA                   As Long
    If ((lngPtr <> 0) And (LnBytes > 0)) Then
        Call CopyMemory(ByVal VarPtr(lng_PtrSA), ByVal lngPtr, LnBytes)
        ItsArrayINI = (Not (lng_PtrSA = 0))
    End If
End Function

Public Sub SwapLong(ByRef lVal1 As Long, ByRef lval2 As Long)
    lval2 = lval2 Xor lVal1
    lVal1 = lVal1 Xor lval2
    lval2 = lval2 Xor lVal1
End Sub

'   //  Return (Cantidad de elementos).
Public Function RemoveInArrayLong(ByVal lIndex As Long, ByRef lArray() As Long) As Long
    If (ItsArrayINI(VarPtrA(lArray)) = True) Then
        RemoveInArrayLong = UBound(lArray)
        If Not ((lIndex < 0) Or (lIndex > RemoveInArrayLong)) Then
            If Not (lIndex = RemoveInArrayLong) Then
                Call CopyMemory(ByVal VarPtr(lArray(lIndex)), ByVal VarPtr(lArray(lIndex + 1)), (RemoveInArrayLong - lIndex) * 4)
            End If
            If ((RemoveInArrayLong - 1) > INVALIDVALUEARRAY) Then
                ReDim Preserve lArray(RemoveInArrayLong - 1)
            Else
                Erase lArray()
            End If
        End If
    End If
End Function



Temibles Lunas!¡.
#21
Foro Libre / [Consulta] Calculo vectorial...
21 Septiembre 2011, 07:55 AM
.
Que significa la nAB   se que AB es la dirreccion de un vector es decir que va desde A hasta B pero no se que demonios significa esa n.

Dicha n aparece en la formula para saber el area de un triangulo respecto a vertices (Es una variante para hayar el area).


Esta duda la pongo por que mi profesora se a equivocado tremendamente en un ejercicio y bueno para exponerselo nesesito saber que es esa maldita n.

Es decir se que puedo hayar la distancia entre dos punto y asi aplicar la formula de:

AreaTriangulo = Lado1 * Lado2 * Sin ( Sec ( (A * B) / (||A|| * ||B||) ) )

y se que todo esto es equitativo y debe de dar el mismo resultado como es logico.

Dulces Lunas!¡.
#22
Estoy un poco aburrido y me e puesto a hacer esto:

Esta clase la he creado para tratar un poco las listas enlazadas de la manera:

Elemento 1, Elemento 2, ... , Elemento N

Es decir que la clase EMULA las listas enlazadas que libremente se pueden escribir con punteros en C/C++ pero en listas lineales.

* No estan enlazadas en forma de arbol.

De tal modo que Dejo de sustitucion a  Redim Preserve   NO en todos los casos Ojo.

Ventajas:

* Asigna memoria dependiendo sin cambiar la hubicacion de los demas elementos ( agregacion rapida de elementos ).
* Se trata a la memoria como un bloque de bytes como cualquier otro (Generico).


Desventajas:

* No se puede usar Copymemory para copiar a mas de 1 elemento...
* Solo es utilizable para casos contados...


cListLink.cls

Código (vb) [Seleccionar]


'
'   /////////////////////////////////////////////////////////////
'   // Autor:   BlackZeroX ( Ortega Avila Miguel Angel )       //
'   //                                                         //
'   // Web:     http://InfrAngeluX.Sytes.Net/                  //
'   //                                                         //
'   //    |-> Pueden Distribuir Este codigo siempre y cuando   //
'   // no se eliminen los creditos originales de este codigo   //
'   // No importando que sea modificado/editado o engrandecido //
'   // o achicado, si es en base a este codigo                 //
'   /////////////////////////////////////////////////////////////
'   //                                                         //
'   // * Esta es una lista de 1 solo Orden... es decir no es   //
'   // de ordenamiento en arbol...                             //
'   //                                                         //
'   /////////////////////////////////////////////////////////////
'   // http://infrangelux.hostei.com/index.php?option=com_content&view=article&id=29:clistlink&catid=15:catmoduloscls&Itemid=24
'   /////////////////////////////////////////////////////////////

Option Explicit

Private Const MEM_DECOMMIT = &H4000
Private Const MEM_RELEASE = &H8000
Private Const MEM_COMMIT = &H1000
Private Const MEM_RESERVE = &H2000
Private Const MEM_RESET = &H80000
Private Const MEM_TOP_DOWN = &H100000
Private Const PAGE_READONLY = &H2
Private Const PAGE_READWRITE = &H4
Private Const PAGE_EXECUTE = &H10
Private Const PAGE_EXECUTE_READ = &H20
Private Const PAGE_EXECUTE_READWRITE = &H40
Private Const PAGE_GUARD = &H100
Private Const PAGE_NOACCESS = &H1
Private Const PAGE_NOCACHE = &H200
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByVal pDest As Long, ByVal pSrc As Long, ByVal ByteLen As Long)
Private Declare Function VirtualAlloc Lib "kernel32" (ByVal lpAddress As Long, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As Long
Private Declare Function VirtualFree Lib "kernel32" (ByVal lpAddress As Long, ByVal dwSize As Long, ByVal dwFreeType As Long) As Long
Private Declare Function VirtualLock Lib "kernel32" (ByVal lpAddress As Long, ByVal dwSize As Long) As Long
Private Declare Function VirtualUnlock Lib "kernel32" (ByVal lpAddress As Long, ByVal dwSize As Long) As Long
'Private Declare Function IsBadReadPtr Lib "kernel32" (ByVal lp As Long, ByVal ucb As Long) As Long
'Private Declare Function IsBadWritePtr Lib "kernel32" (ByVal lp As Long, ByVal ucb As Long) As Long
'Private Declare Function IsBadStringPtr Lib "kernel32" Alias "IsBadStringPtrA" (ByVal lpsz As Long, ByVal ucchMax As Long) As Long
'Private Declare Function lstrcpy Lib "kernel32" Alias "lstrcpyA" (ByVal lpStringDest As String, ByVal lpStringSrc As Long) As Long
'Private Declare Function lstrlen Lib "kernel32" Alias "lstrlenA" (ByVal lpString As Long) As Long
Private Declare Sub ZeroMemory Lib "kernel32.dll" Alias "RtlZeroMemory" (ByVal Destination As Long, ByVal Length As Long)

Private Declare Sub PutMem4 Lib "msvbvm60" (ByVal Addr As Long, ByVal NewVal As Long)
Private Declare Sub GetMem4 Lib "msvbvm60" (ByVal Addr As Long, ByVal RetVal As Long)

Dim pfirst          As Long
Dim pLast           As Long
Dim lSize           As Long

Const SIZEAB        As Long = &H8
Const BEFORESIZE    As Long = &H0
Const AFTERSIZE     As Long = (BEFORESIZE + &H4)

Public Function release(ByVal pStream As Long) As Boolean
Dim lSizeF      As Long
Dim pAfter       As Long
Dim pBefore     As Long
   If (pStream = &H0) Then Exit Function
   lSizeF = (SIZEAB + lSize)
   pAfter = after(pStream)
   pBefore = before(pStream)
   VirtualUnlock pStream, lSizeF
   VirtualFree pStream, lSizeF, MEM_DECOMMIT
   VirtualFree pStream, 0, MEM_RELEASE
   If (pAfter) Then putBefore pAfter, pBefore
   If (pBefore) Then putAfter pBefore, pAfter
   If (pStream = pfirst) Then pfirst = pBefore
   If (pStream = pLast) Then pLast = pAfter
   release = True
End Function

Public Function getPtr(ByVal lIndex As Long) As Long
'   //  Retorna el puntero del elemento indicado en lIndex.
Dim pTmp            As Long
Dim i               As Long
   pTmp = first()
   Do Until (pTmp = &H0)
       i = (i + &H1)
       If (i > lIndex) Then Exit Do
       pTmp = after(pTmp)
   Loop
   getPtr = pTmp
End Function

Public Property Get size() As Long
   size = lSize
End Property

Public Property Let size(ByVal lVal As Long)
   Call clear
   lSize = lVal
End Property

Friend Sub writeStream(ByVal pStruct As Long, ByVal pData As Long)
'   //  Setea los valores en el bloque de la memoria de la lista enlazada.
   CopyMemory pStruct, pData, lSize
End Sub

Friend Function readStream(ByVal pStruct As Long, ByVal pData As Long)
'   //  Retorna los valores del bloque de la lista enlazada a una bloque.
   CopyMemory pData, pStruct, lSize
End Function


'   //  Estas funciones otienen el 1er y ultimo elemento agregado a la lista.
Friend Function first() As Long
   first = pfirst
End Function

Friend Function last() As Long
   last = pLast
End Function


'   //  funciones iteradoras.
Friend Function after(ByVal pStruct As Long) As Long    '   //  Rectorna del puntero al bloque que se agrego despues de pStruct
Dim pTmp            As Long
   If (pStruct = &H0) Then Exit Function
   GetMem4 ByVal (pStruct + lSize + AFTERSIZE), VarPtr(pTmp)
   after = pTmp
End Function

Friend Function before(ByVal pStruct As Long) As Long   '   //  Rectorna del puntero al bloque anteriormente agregado de pStruct
Dim pTmp            As Long
   If (pStruct = &H0) Then Exit Function
   GetMem4 ByVal (pStruct + lSize + BEFORESIZE), VarPtr(pTmp)
   before = pTmp
End Function

Friend Function addNew() As Long                        '   //  Agrega un nuevo bloque y lo enlaza.
Dim lSizeF      As Long
Dim pNew        As Long
   lSizeF = (SIZEAB + lSize)
   pNew = VirtualAlloc(ByVal 0&, lSizeF, MEM_COMMIT, PAGE_EXECUTE_READWRITE)
   VirtualLock pNew, lSizeF
   ZeroMemory pNew, lSizeF                             '   //  llenamos de 0 el bloque.
   If (pLast) Then                                     '   //  Actualizamos el ultimo...
       putBefore pNew, pLast
       putAfter pLast, pNew
   End If
   If (pfirst = &H0) Then pfirst = pNew
   pLast = pNew
   addNew = pNew
End Function

Private Sub putAfter(ByVal pStruct As Long, ByVal pAfter As Long)
   If (pStruct = &H0) Then Exit Sub
   PutMem4 (pStruct + lSize + AFTERSIZE), pAfter        '   //  pNew.After
End Sub

Private Sub putBefore(ByVal pStruct As Long, ByVal pBefore As Long)
   If (pStruct = &H0) Then Exit Sub
   PutMem4 (pStruct + lSize + BEFORESIZE), pBefore     '   //  pNOW.BEFORE
End Sub

Public Function clear() As Long                         '   //  Libera la memoria asignada y retorna la cantidad liberada en bytes.
Dim lSizeRet        As Long
Dim pTmp            As Long
   pTmp = first()      '   //  Seteamos el 1ro.
   Do Until (release(pTmp) = False)
       lSizeRet = (lSizeRet + lSize + SIZEAB)
       pTmp = first()
   Loop
   clear = lSizeRet
End Function

Private Sub Class_Terminate()
   Call clear
End Sub



Ejemplo de uso

Código (Vb) [Seleccionar]


Option Explicit

Private Type DATOSPERSONALES
   edad        As Long
   categoria   As Long
   nombre      As String * 20
   apellidoP   As String * 10
   apellidoM   As String * 10
End Type

Private Sub Form_Load()
Dim oList       As cListLink
Dim tDatosP     As DATOSPERSONALES      '   //  Plantilla...
Dim pElement    As Long                 '   //  Puntero al elemento...
   
   Set oList = New cListLink
   
   oList.size = LenB(tDatosP)                                  '   //  Tamaño de la estructura (bloque de datos).
   
   With tDatosP
       .edad = 22
       .categoria = 1
       .nombre = "Miguel Angel"
       .apellidoP = "Ortega"
       .apellidoM = "Avila"
   End With
   Call oList.writeStream(oList.addNew(), VarPtr(tDatosP))     '   //  Escribimos la estructura en una lista enlazada.
   
   With tDatosP
       .edad = 42
       .categoria = 2
       .nombre = "Angel"
       .apellidoP = "Ortega"
       .apellidoM = "Hernandez"
   End With
   Call oList.writeStream(oList.addNew(), VarPtr(tDatosP))     '   //  Escribimos la estructura en una lista enlazada.
   
   With tDatosP
       .edad = 19
       .categoria = 2
       .nombre = "Maria Luisa"
       .apellidoP = "Beltran"
       .apellidoM = "Ramirez"
   End With
   Call oList.writeStream(oList.addNew(), VarPtr(tDatosP))     '   //  Escribimos la estructura en una lista enlazada.
   
   
   'Call oList.release(oList.before(oList.firts()))             '   //  Liberamos el 2 registro ("Angel Ortega Hernandez"), para eso obtenemos el 1 elemento y obtenemos el siguiente elemento con before...
   Call oList.release(oList.getPtr(1))                         '   //  Eliminamos el elemento con Index 1
   
   '   //  Retornamos los elementos...
   
   pElement = oList.first()
   
   Do Until (pElement = &H0)
       
       oList.readStream pElement, VarPtr(tDatosP)
       With tDatosP
           Debug.Print "Nombre:", .nombre
           Debug.Print "ApellidoP:", .apellidoP
           Debug.Print "ApellidoM:", .apellidoM
           Debug.Print "Edad:", .edad
           Debug.Print "Categoria:", .categoria
           Debug.Print
           Debug.Print
           Debug.Print
       End With
       pElement = oList.after(pElement)
   Loop
   
   Set oList = Nothing
   
End Sub



Temibles Lunas!¡.
#23
.
El tema es proponer retos discutir su dificultad y por ende sacar a flote dicho tema respectivamente en un hilo ajeno a este, ya que proponer un reto la vdd no es cosa facil, por ejemplo:

Proponer crear una aplicacion X discutiendo su complejidad.
Proponer la recreacion de la funcion X.
Proponer la creacion de alguna indole X.

Que debera llevar ...?
Que se espera de ...?
Prototipo de la funcion ...?

Por ejemplo: tengo en mente proponer un 3 retos los cuales son:

Crear un interprete...
Crear un lector de estructuras en arbol (como XML, HTTP, etc)...
Otro que no por el momento.

Puedo decir que el interprete tiene una dificultad Intermedio-Avanzado y el lector de estructuras en arbol seria un nivel Intermedio, pero por el momento SUPONGAMOS que en el interprete digo que haga X cosas... pero me lleguen a faltar mas cosillas; es decir discutir SOLAMENTE lo que debe esperarse de este mas que codigo deberia llevar Por ejemplo:

* Manejo de procesos y funciones.
* Manejo de variables con sus tipos X (Dim nombre as tipo).
* Con que tipos de variables debe contar.
* Funciones predeterminadas del interprete (Mid, Left, IndexOf, ...).
* Instrucciones de flujo (If then, select case o Switch, ...).
* Bucles (dow while, for(), ...).
* forma de retornar los valores (por la instruccion return o como lo hace vb6).
* Entre otras cosillas.
* Ademas de incluir ejemplos.

Este ultimo me es interesante puesto que se podrian crear entre 2 o mas personas claro que tambien 1 podria hacerlo, ademas de que fomentaria el compañerismo del foro.

Esta es una propocision.

Cada Post para no hacerlo lago deberia llevar una cita de link mas no citar completamente el tema esto ultimo para mantener un orden en el tema hilo.

Dulces Lunas!¡.
#24
Programación C/C++ / [C]isNumeric (VB6 a C)
16 Agosto 2011, 22:45 PM
.
Se trabajan las funciones a nivel Bit, ambas funciones son mas rapidas que la nativa en vb6.

Funcion en VB6

Codigos para descargar...
Archivos Fuente dll, y Compilados



La funcion isnumeric_Black esta en VB6, es la version en vb6 de la que esta aqui...



http://foro.elhacker.net/programacion_visual_basic/reto_reemplazo_de_funcion_isnumeric-t336067.0.html;msg1652210#msg1652210

main.cpp



y aqui les dejo la traduccion en C (Las funciones IsNumericA y IsNumericW estan configuradas para trabajar con las Strings de VB6)



#include "main.h"

/**
   @Autor          BlackZeroX
   @Web            http://infrangelux.sytes.net/blog/
   @Reference      http://foro.elhacker.net/programacion_visual_basic/reto_reemplazo_de_funcion_isnumeric-t336067.0.html;msg1652210#msg1652210
   @Description    Libreria para verificar si una Cadena de texto ANSI/UNICODE es numerica con los siguientes formatos:
                   * ###e[+/-]###  {+/-646.45e+546,45}.
                   * ###d[+/-]###  {+/-646.45d+546,45}.
                   * Base 16       {&H4561abcdef}.
                   * Base 10       {+/-456,541.456,545}.
   @Returns        0 si la cadena no contiene ningun formato.
                   1 si la cadena pertenece a algun tipo de formato numerico.
**/

#define PUNTO_DECIMAL     0x10000
#define SIGNO_SRC         0x20000
#define NUMBER_HEX        0x40000
#define NUMBER_HEX_ZERO   0x80000
#define NUMBER_HEX_FLAGS  (NUMBER_HEX | NUMBER_HEX_ZERO)
#define NUMBER_POW        0x100000
#define NUMBER_POW_FINISH 0x200000
#define NUMBER_POW_FLAGS  (NUMBER_POW | NUMBER_POW_FINISH)
#define NUMBER_OF_OK      0x400000
#define NUMBER_OF_FINISH  0x800000
#define NUMBER_OF_FLAGS   (NUMBER_OF_OK | NUMBER_OF_FINISH)

DLL_EXPORT int __stdcall IsNumericA (char *pStr) { return pStr ? IsNumericEx(pStr, *((int*)(pStr - 0x4)), 1): 0; }
DLL_EXPORT int __stdcall IsNumericW (char *pStr) { return pStr ? IsNumericEx(pStr, *((int*)(pStr - 0x4)), 2): 0; }

int IsNumericEx (char *pStr, size_t uiLn, int iStep) {
unsigned int i       = 0x0,  //  For()
            iData   = 0x0;  //  Xor, Switcher, Contador (QWord).

   if (!pStr || !uiLn)
       return 0;

   for (i = 0; i < uiLn; i += iStep) {
       if ((iData & NUMBER_HEX) == NUMBER_HEX) {
           if (((*pStr >= 0x30) && (*pStr <= 0x39)) ||
              ((*pStr >= 0x61) && (*pStr <= 0x66)) ||
              ((*pStr >= 0x41) && (*pStr <= 0x46))) {  //  Numeros Hexadecimales
               if ((iData & NUMBER_OF_FLAGS) == 0x0)   //  Ceros a la izquierda
                   iData |= (*pStr == 0x30) ? NUMBER_HEX_ZERO : NUMBER_OF_OK;

               switch (iData & NUMBER_OF_FLAGS) {
                   case NUMBER_OF_OK:
                       iData++;
                       if ((iData & 0xFF) == 0x11)
                           return 0;   //  QWord (Max Double)
                       iData |= NUMBER_OF_OK;
                       if ((iData | NUMBER_HEX_FLAGS) == NUMBER_HEX_FLAGS)
                           iData ^= NUMBER_HEX_ZERO;
                       break;

                   case NUMBER_OF_FINISH:
                   case NUMBER_OF_FLAGS:
                       return 0;
                       break;
              }
           } else {
               switch (*pStr) {
                   case 0x9:
                   case 0xA:
                   case 0xB:
                   case 0xC:
                   case 0xD:
                   case 0x24:
                   case 0x20:
                   case 0xA0:  //   Espacios en Blanco
                       if ((iData | NUMBER_HEX_FLAGS) == NUMBER_HEX_FLAGS)
                           iData = ((iData ^ NUMBER_HEX_ZERO) | NUMBER_OF_OK);
                       if ((iData & NUMBER_OF_FLAGS) == NUMBER_OF_OK)
                           iData |= NUMBER_OF_FINISH;
                       break;

                   case 0x0:    //  NULL Indica que se termina la cadena.
                       if ((iData & NUMBER_OF_FLAGS) == NUMBER_OF_FINISH)
                           return 0;
                       i = uiLn; //  Exit For.
                       break;

                   default:
                       return 0;
                       break;
               }
           }
       } else {
           if ((*pStr >= 0x30) && (*pStr <= 0x39)) {
               iData |= NUMBER_OF_OK;
               if ((iData & NUMBER_OF_FINISH) == NUMBER_OF_FINISH)
                   return 0;
               if ((iData & NUMBER_POW_FLAGS) == NUMBER_POW)
                   iData |= NUMBER_POW_FINISH;

           } else {
               switch ((int)*pStr) {
                   case 0x0:    //  NULL Indica que se termina la cadena.
                       if ((iData & NUMBER_POW_FLAGS) == NUMBER_POW)
                           return 0;
                       i = uiLn;    //  Exit For.
                       break;

                   case 0x2E:   //  "."  Solo 1
                       if (((iData & NUMBER_POW_FLAGS) == NUMBER_POW) ||
                          ((iData & NUMBER_OF_FINISH) == NUMBER_OF_FINISH) ||
                          ((iData & PUNTO_DECIMAL) == PUNTO_DECIMAL))
                           return 0;
                       iData |= PUNTO_DECIMAL;
                       break;

                   case 0x2B:
                   case 0x2D: //  "+|-" Solo 1
                       if ((iData & NUMBER_POW_FLAGS) == NUMBER_POW)
                           iData |= NUMBER_POW_FINISH;

                       else
                           if (((iData & NUMBER_OF_OK) == NUMBER_OF_OK) ||
                              ((iData & PUNTO_DECIMAL) == PUNTO_DECIMAL) ||
                              ((iData & SIGNO_SRC) == SIGNO_SRC))
                           return 0;

                       if ((iData & NUMBER_OF_FINISH) == NUMBER_OF_FINISH)
                           return 0;

                       iData |= SIGNO_SRC;
                       break;

                   case 0x2C:
                       if ( !((iData & NUMBER_OF_OK) == NUMBER_OF_OK) ||
                             ((iData & NUMBER_POW_FLAGS) == NUMBER_POW))
                           return 0;
                       break;

                   case 0x9:
                   case 0xA:
                   case 0xB:
                   case 0xC:
                   case 0xD:
                   case 0x24:  //  Solo se permiten al inicio de un Numero (Espacios en Blanco).
                       if (((iData & PUNTO_DECIMAL) == PUNTO_DECIMAL) ||
                          ((iData & NUMBER_OF_FINISH) == NUMBER_OF_FINISH) ||
                          ((iData & NUMBER_OF_OK) == NUMBER_OF_OK) ||
                          ((iData & NUMBER_POW_FLAGS) == NUMBER_POW))
                           return 0;
                       break;

                   case 0xA0:
                   case 0x20: //  Se permiten al Inicio/final de un numero.
                       if ((iData & NUMBER_OF_OK) == NUMBER_OF_OK)
                           iData |= NUMBER_OF_FINISH;
                       else
                           if (((iData & PUNTO_DECIMAL) == PUNTO_DECIMAL) ||
                              ((iData & NUMBER_POW_FLAGS) == NUMBER_POW))
                               return 0;
                       break;

                   case 0x26:   //  Es un Numero Hexadecimal
                       if (((iData & NUMBER_OF_FINISH) == NUMBER_OF_FINISH) ||
                          ((iData & NUMBER_OF_OK) == NUMBER_OF_OK) ||
                          ((iData & SIGNO_SRC) == SIGNO_SRC) ||
                          ((iData & PUNTO_DECIMAL) == PUNTO_DECIMAL) ||
                          ((iData & NUMBER_POW_FLAGS) == NUMBER_POW))
                           return 0;

                       pStr += iStep;

                       if ((*pStr == 0x48) || (*pStr == 0x68)) {
                           iData |= NUMBER_HEX;
                           iData ^= 0xFF000000;
                           i += iStep;
                       } else {
                           pStr -= iStep;
                       }
                       break;

                   case 0x44:
                   case 0x45:
                   case 0x64:
                   case 0x65:     //  Numeros en Formato ###e-###, ###e+###
                       if (((iData & NUMBER_OF_FINISH) == NUMBER_OF_FINISH) ||
                          ((iData & NUMBER_POW) == NUMBER_POW))
                           return 0;
                       if ((iData & NUMBER_OF_OK) == NUMBER_OF_OK) {
                           iData |= NUMBER_POW;
                           if ((iData & SIGNO_SRC) == SIGNO_SRC)
                               iData ^= SIGNO_SRC; //  Permitimos nuevamente los signos "+" y "-".
                       } else {
                           return 0;
                       }
                       break;

                   default:
                       return 0;
                       break;

               }   //  switch()
           }   //  if()
       }   //  if()
       pStr += iStep;
   }   //  For()

   switch (iData & NUMBER_OF_FLAGS) {
       case NUMBER_OF_OK:
       case NUMBER_OF_FLAGS:
           return 1;
           break;

       default:
           switch (iData & NUMBER_HEX_FLAGS) {
               case NUMBER_HEX_FLAGS:
                   return 1;
                   break;
           }
   }

   return 0;
}



main.h


#ifndef __MAIN_H__
#define __MAIN_H__

#include <windows.h>

#ifdef BUILD_DLL
   #define DLL_EXPORT __declspec(dllexport)
#else
   #define DLL_EXPORT __declspec(dllimport)
#endif

#ifdef __cplusplus
extern "C"
{
#endif

DLL_EXPORT int __stdcall IsNumericA (char*);
DLL_EXPORT int __stdcall IsNumericW (char*);
int IsNumericEx (char *pStr, size_t uiLn, int iStep);

#ifdef __cplusplus
}
#endif

#endif // __MAIN_H__



Dulces Lunas!¡.
#25
Programación C/C++ / Crear DLL
16 Agosto 2011, 04:42 AM
Como creo una DLL en codeblocks pero que pueda usar sus funciones en otro lenguaje por ejemplo VB6, vb .NET etc...

Dulces Lunas!¡.
#26
.
Estoy realizando pruebas con OpenGL+C ( No me recomienden otro por que antes de cambiarme quiero solucionar este problema ), y estoy con las luces. mi problema radica en que la luz no apunta a donde deberia de apunter ( Algo asi como un Eje ), ya que se mueve emisor d ela luz a otra coordenada y obviamente el eje (en este caso esta representado con una espera solida) deberia estar SIEMPRE iluminado, pero no es asi...

alguien me puede ayudar?



#include <windows.h>
#include "include/OpenGL/CGL.h"

// Posicion de la luz X, Y, Y, {el 4to elemento indica si es en una posicion infinita 1=NO, 0=SI}
float fposition[4] = {0.0f, 0.0f, 1.0f, 1.0};

void drawZones()
{
    ::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  // Borramos la pantalla y el buffer de profundidad

    ::glLoadIdentity();
    //  Camara.
    ::gluLookAt( 0, 0, 5,               //  Posicon X, Y, Z.
                 0, 0, -1,              //  Hacia donde vemos X, Y, Z.
                 0.0f, 1.0f, 0.0f );    // Cielo X, Y, Z.

    GLfloat fDirection[] = {0.0,0.0,-1.0}; // Dirrecion hacia adonde apuntamos.
    //Configuramos nuestra Luz.
    ::glEnable ( GL_LIGHT0 );
    ::glLightfv ( GL_LIGHT0, GL_POSITION, fposition );
    ::glLightfv ( GL_LIGHT0, GL_SPOT_DIRECTION, fDirection);
    ::glLightf ( GL_LIGHT0, GL_SPOT_CUTOFF, 5 );

    ::glutSolidSphere(100, 4000, 4000); // Esfero que nos representara las paredes.

    //  Las siguiente son las esferas donde esta la luz.
    //  Posicion del emisor de luz.
    ::glPushMatrix ();
        ::glColor3f ( 1.0f , 0.0f , 0.0f );
        ::glTranslatef ( fposition[0],fposition[1],fposition[2] );
        ::glutWireSphere ( 0.2, 50 , 50 );
    ::glPopMatrix ();

    //  Posicion Destino hacia donde se emite la luz.
    ::glPushMatrix();
        ::glColor3f( 0.0f , 0.0f , 1.0f );
        ::glTranslatef( fDirection[0],fDirection[1],fDirection[2] );
        ::glutSolidSphere( 0.2, 50 , 50 );
    ::glPopMatrix();
    //  Mostramos.
    ::glutSwapBuffers();
}

void keyBoardSFunc(int key, int x, int y)
{
    if (key == GLUT_KEY_LEFT)
        fposition[0] -= 0.1;
    if (key == GLUT_KEY_RIGHT)
        fposition[0] += 0.1;
    if (key == GLUT_KEY_UP)
        fposition[1] -= 0.1;;
    if (key == GLUT_KEY_DOWN)
        fposition[1] += 0.1;
}
void timer( int val ) {
    ::glutTimerFunc       ( 10 , timer,  0);
    ::glutPostRedisplay   (  );
}

int main()
{
    CGL oWindow;

    oWindow.creaVentanaGL ( "Hola Mundo desde OpenGL" , 1024 , 726 , 0 , 0 , false );
    ::glutDisplayFunc ( drawZones );
    ::glutSpecialFunc ( keyBoardSFunc );
    ::glutTimerFunc ( 10, timer, 0 );
    ::glutMainLoop ();

    return EXIT_SUCCESS;
}



CGL.cpp




#include "OpenGL/cgl.h"

//---------------------------------------------------------------
// Nombre: Constructor
// Descripcion: Constructor de la clase. Inicializa las variables
// Parametros: Ninguno
//---------------------------------------------------------------
CGL::CGL()
{
    int_Win = 0;
}

//---------------------------------------------------------------
// Nombre: Destructor
// Descripcion: Destructor de la clase
// Parametros: Ninguno
//---------------------------------------------------------------
CGL::~CGL()
{
    eliminaVentanaGL();
}

//---------------------------------------------------------------
// Nombre: inicializaEscenaGL
// Descripcion: Inicializa los parametros iniciales de la escena
// Parametros:
//        Glsizei ancho: Ancho de la escena
//        Glsizei alto: Alto de la escena
//---------------------------------------------------------------
void CGL::inicializaEscenaGL(GLsizei ancho, GLsizei alto)
{
    if ( alto <= 0 )                                                                    // Previene de la división entre 0
    {
        alto=1;                                                                         // Establece la altura = 1
    }
    ::glViewport            ( 0 , 0 , ancho , alto );                                   // Resetea el actual puerto de visión (ViewPort)
    ::glMatrixMode          ( GL_PROJECTION );                                          // Selecciona la matriz de proyección
    ::glLoadIdentity        (  );                                                       // Resetea la matriz de proyección

    ::gluPerspective        ( 45.0f , (GLfloat)ancho/(GLfloat)alto , 1.0f , 300000.0f );  // Calcula el Aspect Ratio de la ventana

    ::glMatrixMode          ( GL_MODELVIEW );                                           // Selecciona la matriz de modelado
    ::glLoadIdentity        (  );                                                       // Resetea la matriz de modelado
}

//---------------------------------------------------------------
// Nombre: iniGL
// Descripcion: Inicializa los valores iniciales de OGL
// Parametros: Ninguno
//---------------------------------------------------------------
bool CGL::iniGL(void)
{
    GLfloat ambientLight[]  = { 0.1f, 0.1f, 0.1f, 1.0f };
    ::glShadeModel          ( GL_SMOOTH );                                  // Activa sombreado suave (Smooth Shading)
    ::glClearDepth          ( 1.0f );                                       // Depth Buffer Setup
    ::glEnable              ( GL_DEPTH_TEST );                              // Activa Z-Buffer
    ::glDepthFunc           ( GL_LEQUAL );                                  // El tipo de Depth Testing que se va a realizar
    ::glHint                ( GL_PERSPECTIVE_CORRECTION_HINT , GL_NICEST ); // Muy buena correción de perspectiva
    ::glEnable              ( GL_TEXTURE_2D );                              // Activa mapeado de texturas
    ::glColorMaterial       ( GL_FRONT , GL_AMBIENT_AND_DIFFUSE );
    ::glClearColor          ( 0.0f , 0.0f , 0.0f , 1.0f );

    ::glLightModeli         ( GL_LIGHT_MODEL_TWO_SIDE , 1 );                // habilita ambas caras (FRONT-iluminada & BACK-oscurecida) de los poligonos
    ::glLightModelfv        ( GL_LIGHT_MODEL_AMBIENT , ambientLight );      // luz ambiental de toda la escena
    ::glEnable              ( GL_COLOR_MATERIAL);                           // habilita el color para los materiales (poligonos rellenos)
    ::glEnable              ( GL_LIGHTING );

    return true;
}

//---------------------------------------------------------------
// Nombre: eliminaVentanaGL
// Descripcion: Destruye toda la información sobre la ventana GL
// Parametros: Ninguno
//---------------------------------------------------------------
void CGL::eliminaVentanaGL(void)
{
    ::glutDestroyWindow(  this->int_Win );
    this->int_Win = 0;
}

//---------------------------------------------------------------
// Nombre: CrearVentanaGL
// Descripcion: Crea una ventana OGL
// Parametros:
//            char* Titulo: Titulo de la ventana
//            int ancho: Ancho de la ventana o en modo pantalla completa
//            int alto: Alto de la ventana o en modo pantalla completa
//            bool fullscreen: Usar pantalla completa (TRUE) o ventana (FALSE)
//---------------------------------------------------------------
bool CGL::creaVentanaGL(const char* Titulo, GLsizei ancho, GLsizei alto, GLsizei x, GLsizei y, bool fullscreen)
{
    if ( x < 0 ) { x=0; }
    if ( y < 0 ) { y=0; }

    ::glutInitDisplayMode ( GLUT_DOUBLE | GLUT_RGBA );
    ::glutInitWindowPosition ( x , y );
    ::glutInitWindowSize ( ancho , alto );

    this->int_Win = ::glutCreateWindow( Titulo );

    ::glutSetWindow( this->int_Win );

    if ( fullscreen == true )
        ::glutFullScreen();

    inicializaEscenaGL ( ancho , alto );        // Inicializamos la escena en perspectiva GL

    if ( !iniGL() ) {
        eliminaVentanaGL();
        return false;
    }

    return true;
}



CGL.h


#ifndef _cGL_H_
#define _cGL_H_

// INCLUDES //////////////////////////////////////
#include <windows.h>            // Archivo cabecera para Windows
#include <GL/glut.h>

class CGL
{
    public:
        CGL                                         ();
        virtual         ~CGL                        ();
        bool            creaVentanaGL               (const char* Titulo, GLsizei ancho, GLsizei alto, GLsizei x, GLsizei y, bool fullscreen);
        void            inicializaEscenaGL          (GLsizei ancho, GLsizei alto);      // Cambia de tamaño e inicializa la ventana GL
        void            eliminaVentanaGL            (void);                           // Elimina la ventana
        int             int_Win;
        void            inilight                    (GLfloat ligt[]);
    private:
        bool            iniGL                       (void);                        // Todas la inicializaciónes de OpenGl vienen aqui
};

#endif



Temibles Lunas!¡
#27
Desarrollo Web / Una ligera duda...
22 Julio 2011, 07:44 AM
.
Que significa la linea que resalto?

Código (ajax,3) [Seleccionar]


var k=function(){
    var l=$("#dtmain_outer, #hatdoiwas_outer");
    if(l.length>0){
    l.remove();
    C.utils.third_party_addon_detected()
}
setTimeout(k,1000)



No tengo ni idea que significa $( alguien lo sabe? entiendo absolutamente TODO pero mi problema radica en el problema que ya mencione.

Dulces Lunas!¡.
#28
Foro Libre / [?] Necrosis
11 Julio 2011, 07:47 AM
alguien sabe si la necrosis duele?; se de que trata la necrosis, pero la verdad es que no soy doctor no lo he esperimentado, y bueno quisas alguien mas informado sepa de esto.

Anexo:
Hemos adoptado una palo mensajera, dicha paloma anteriormente venia a nuestra casa constantemente devido a que fue agredida de alguna manera ( alguna aguila ), llego sin un ojo y bueno solo llego a nuesra casa seguro por que tenemos rondando mas palomas, pichones ( Libres de irse cuando quieran no esta atadas ni nada similar ), gallos, gallinas, etc... bueno estos ultimos para la cena de algun dia ( Broma, jamas nos comemos a ninguno ), perros, gatos, y alguna que otro Conejo de ciudad gracias al mercado y a la iglesia detras de nuestra casa; Dicha paloma se hiba y regresaba cada dia, pero un dia no llego y duro al rededor de 3 semanas apenas Hoy llego pero con una necrosis en su pie ( Es facil saber cuando es necrosis, en especial cuando es avanzada ), dicha paloma actualmente mi hermana y un servidor estamos pensando en conrtarle la pata, o de plano ya sacrificarla, ahorita solo la tenemos en una jaula ( anteriormente los conejos de Ciudad se comieron a 1 Paloma completa y lo digo literalmente es por ello este trato ).

Solo desearia saber eso.

Nota: Mi familia y un servidor tenemos corazon de pollo con los animales, es decir, no tenemos mera intencion de maltrato animal.

Dulces Lunas!¡.
#29
.
Intento Re-Crear el Redim Preserve de VB6 todo bien pero Cuando deseo volver a redimencionar Crashea alguien sabe por que?

Código (cpp) [Seleccionar]


#include <stdio.h>
#include <string.h>

void** RedimPreserve( void** __pp_vector , size_t _szt_now, size_t _szt_new )
{
    void            **__pp_back     = __pp_vector;
    void            **__new_ptr     = NULL;

    if (_szt_now==_szt_new )
        return __pp_vector;

    if ( _szt_new>0 ) {
        __new_ptr       = new void*[_szt_new];
        if ( _szt_now>0 && __new_ptr!=NULL && __pp_back!=NULL  )
            memcpy          ( __new_ptr , __pp_back , _szt_now*sizeof(void*) );
    } else
        __new_ptr       = NULL;

    if ( __pp_back!=NULL )
        delete[]        __pp_back;

    return __new_ptr;
}



int main () {
    char **_msg = NULL;

    _msg    = (char**)RedimPreserve( (void**)_msg , 00 , 10 );
    _msg    = (char**)RedimPreserve( (void**)_msg , 10 , 11 );
    _msg    = (char**)RedimPreserve( (void**)_msg , 11 , 10 );
    _msg    = (char**)RedimPreserve( (void**)_msg , 10 , 00 );
    _msg    = (char**)RedimPreserve( (void**)_msg , 00 , 13 );
    _msg    = (char**)RedimPreserve( (void**)_msg , 13 , 20 );
    delete[] _msg;
    return 0;
}



Dulces Lunas!¡
#30
.
Me a parecido fantástico este buscador, asi que se los comparto.

Google Code Search

Temibles Lunas!¡.
#31
.
Estoy probando las plantillas que trae la STL y me viene a la mente usar la clase reverse_iterator.

La cuestión es como la uso, hasta ahora solo hice una cutre pero sin usar la plantilla reverse_iterator?

Código (c++) [Seleccionar]


#ifndef cbyte_H
#define cbyte_H

#include <string.h>
#include <iterator>

using namespace std;

#ifndef _BYTE_
#define _BYTE_
typedef unsigned char   byte;
#endif  //#ifndef _BYTE_

class bytesiterator : public iterator<input_iterator_tag, byte> {
   private:
       const byte            *__p_vbyte;
   public:
       bytesiterator ( const byte *__pv_byte ) : __p_vbyte(__pv_byte) {  };
       virtual ~bytesiterator() {};
       bytesiterator   &operator++() {++this->__p_vbyte;return *this;}
       bytesiterator   operator++(int) {bytesiterator tmp(*this); operator++(); return tmp;}
       bytesiterator   &operator--() {--this->__p_vbyte;return *this;}
       bytesiterator   operator--(int) {bytesiterator tmp(*this); operator--(); return tmp;}
       bool operator   ==(const bytesiterator &__r_cbyte) {return this->__p_vbyte==__r_cbyte.__p_vbyte;}
       bool operator   !=(const bytesiterator &__r_cbyte) {return this->__p_vbyte!=__r_cbyte.__p_vbyte;}
       int operator    *() {return *this->__p_vbyte;}
};

class bytesiteratorreverse : public iterator<input_iterator_tag, byte> {
   private:
       const byte            *__p_vbyte;
   public:
       bytesiteratorreverse ( const byte *__pv_byte ) : __p_vbyte(__pv_byte) {  };
       virtual ~bytesiteratorreverse() {};
       bytesiteratorreverse   &operator++() {--this->__p_vbyte;return *this;}
       bytesiteratorreverse   operator++(int) {bytesiteratorreverse tmp(*this); operator++(); return tmp;}

       bytesiteratorreverse   &operator--() {++this->__p_vbyte;return *this;}
       bytesiteratorreverse   operator--(int) {bytesiteratorreverse tmp(*this); operator--(); return tmp;}

       bool operator   ==(const bytesiteratorreverse &__r_cbyte) {return this->__p_vbyte==__r_cbyte.__p_vbyte;}
       bool operator   !=(const bytesiteratorreverse &__r_cbyte) {return this->__p_vbyte!=__r_cbyte.__p_vbyte;}
       int operator    *() {return *this->__p_vbyte;}
};

#ifndef _bytecontainer_
#define _bytecontainer_


class bytes {
   protected:
       byte        *__p_vbytes;
       size_t      _ln;

   public:
       typedef bytesiterator               iterator;
       typedef bytesiteratorreverse        reverse_iterator;

       bytes ( const byte* __p_vbytes , size_t _ln) {
           this->__p_vbytes    = new byte[_ln];
           this->_ln           = _ln;
           memcpy( this->__p_vbytes , __p_vbytes , _ln );
       }
       bytes ( ) {
           this->__p_vbytes    = NULL;
           this->_ln           = 0;
       }
       bytes ( size_t _ln ) {
           this->__p_vbytes    = new byte[_ln];
           this->_ln           = _ln;
           memset( this->__p_vbytes , 0 , _ln );
       }
       virtual ~bytes () { delete[] this->__p_vbytes; }

       size_t  leght() { return this->_ln; }
       byte*   __p()   { return this->__p_vbytes; }
       void clear()    { if ( this->__p_vbytes ) delete[] this->__p_vbytes; this->_ln = 0; }

       iterator begin() {
           //bytesiterator _v_tmp( (const byte*)this->__p_vbytes );
           iterator _v_tmp( (const byte*)this->__p_vbytes );
           return _v_tmp;
       }

       iterator end() {
           //bytesiterator _v_tmp( (const byte*)(&this->__p_vbytes[this->_ln]) );
           iterator _v_tmp( (const byte*)(&this->__p_vbytes[this->_ln]) );
           return _v_tmp;
       }

       reverse_iterator rbegin() {
           //reverse_iterator _v_tmp( (const byte*)(&this->__p_vbytes[this->_ln-1]) );
           reverse_iterator _v_tmp( (const byte*)(&this->__p_vbytes[this->_ln-1]) );
           return _v_tmp;
       }

       reverse_iterator rend() {
           //reverse_iterator _v_tmp( (const byte*)(this->__p_vbytes-sizeof(byte)) );
           reverse_iterator _v_tmp( (const byte*)(this->__p_vbytes-sizeof(byte)) );
           return _v_tmp;
       }

       bytes &operator+=( bytes &__p_cbyte) {
           byte    *__p_vbytes = this->__p_vbytes;
           size_t  _ln         = 0;
           size_t  _pos        = 0;
           if ( __p_cbyte.__p_vbytes!=NULL && __p_cbyte._ln>0 ) {
               if ( this->_ln>0 && this->__p_vbytes!=NULL ) {
                   _ln = this->_ln + __p_cbyte._ln;
                   _pos = this->_ln;
               } else {
                   _ln = __p_cbyte._ln;
               }
               __p_vbytes = new byte[_ln];
               memcpy( &__p_vbytes[_pos] , __p_cbyte.__p_vbytes , __p_cbyte._ln );

               if ( this->__p_vbytes!=NULL && this->_ln>0 ) {
                   memcpy( __p_vbytes , this->__p_vbytes , this->_ln );
                   delete[] this->__p_vbytes;
               }
           }
           this->__p_vbytes    = __p_vbytes;
           this->_ln           = _ln;
           return *this;
       }

       bytes &operator=( bytes &__p_cbyte ) {
           byte    *__p_vbytes = NULL;
           if ( this != &__p_cbyte ) {
               this->_ln           = __p_cbyte._ln;
               if ( this->_ln>0 && __p_cbyte.__p_vbytes != NULL ) {
                   __p_vbytes          = new byte[this->_ln];
                   memcpy( __p_vbytes , __p_cbyte.__p_vbytes , this->_ln );
               } else {
                   this->_ln           = 0;
               }
               delete[] this->__p_vbytes;
               this->__p_vbytes = __p_vbytes;
           }
           return *this;
       }

       operator byte*() {
           return this->__p_vbytes;
       }

       operator size_t() {
           return this->_ln;
       }

       operator long int() {
           return (long int)this->_ln;
       }

       operator unsigned long int() {
           return (unsigned long int)this->_ln;
       }

       bool operator ==( bytes &__pc_byte ) {
           size_t  _szt_pos    = 0;

           if ( __pc_byte.__p_vbytes == this->__p_vbytes ) {
               return true;
           }
           if ( (this->_ln == __pc_byte._ln) && (__p_vbytes != NULL) && (this->__p_vbytes!=NULL) ) {
               while ( _szt_pos<this->_ln ) {
                   if ( __pc_byte.__p_vbytes[_szt_pos] == this->__p_vbytes[_szt_pos] ) {
                       _szt_pos++;
                   } else {
                       return false;
                   }
               };
               return true;
           }
           return false;
       }
};
#endif  //#ifndef _bytecontainer_

#endif // cbyte_H



P.D.: Revise esta liga http://www.cplusplus.com/reference/std/iterator/reverse_iterator/reverse_iterator/ pero cuando la implemento no me sirve ( con respecto a esta clase ).

Dulces Lunas!¡.
#32
.
No estaría mal que pusieran una leyenda debajo de los temas destacados la leyenda "No se hacen tareas" o a la hora de crear un nuevo tema arriba/abajo/izquierda/derecha del campo del cuerpo del tema en esta ultima zona a mi me sobra espacio en la pagina y no estaría mal dicha leyenda o poner las reglas mas destacadas en alguna zona ( reglas que sean aleatorias o que cambien entre ellas. ).

Esto seria para que los moderadores solo lleguen lean y borren sin aviso alguno.

P.D.: la sugerencia se que puede no ser valida con respecto a que existe la sección de reglas del foro pero no estaria mal solo poner dicha leyenda.

Dulces Lunas!¡.
#33
Estoy haciendo infinidad de pruebas con estas sobrecargas que me han gustado demasiado a tal grado que veo por que dicen que c es tan potente, pero bueno yendo al punto mi problema surge al momento de sobrecargar el operador "+" y realizo varias sumas de mi clase.

El resultado de la prueba debería de ser:  620 pero me da 20 alguien sabe a que se debe?.

Código (cpp) [Seleccionar]


class clstest
{
    public:
        clstest();
        virtual ~clstest();
        clstest &operator +( clstest &c1 ) {
            clstest tmp;
            int i = c1;
            tmp = (this->sMsg + i);
            return tmp;
        }
        clstest &operator +( int c1 ) {
            clstest tmp ;
            int a = (this->sMsg + c1);
            tmp = a;
            return tmp;
        }
        clstest &operator = (clstest &c1) {
            if ( this != &c1 ) {
                this->sMsg = c1;
            }
            return *this;
        }
        clstest &operator = (int c1) {
            this->sMsg = c1;
            return *this;
        }
        operator int() {
            return sMsg;
        }
        operator double() {
            return (double)sMsg;
        }
    protected:
    private:
        int sMsg;
};

clstest::clstest()
{
    //ctor
    this->sMsg=0;
}

clstest::~clstest()
{
    //dtor
}

int main()
{
    clstest a;
    a = 45;
    a = a + a + 10;
    a = a + a + 10 + a;
    a = a + a;
    int res = a;
    return 0;
}



Dulces Lunas!¡.
#34
Foro Libre / Consejos para deteccion en 3D.
11 Junio 2011, 11:31 AM
.
Estoy realizando un pequeño motor para un juego en C+OpenGL y me veo en la necesidad de crear una técnica viable para detectar las colisiones

Hay alguna manera lógica de detectar colisiones ( con rangos de error para no exigirle al procesador demasiado ) de manera que dichos objetos estén constantemente en movimiento y cambiando de forma, se que lo puedo hacer con la formula para saber la distancia entre dos puntos, pero la verdadera pregunta es como detectar la colisión entre dos masas?.

Mis opciones hasta ahora son:
*Definir el centro de la masa(figura)  (Detección de colisión por círculos) ( me parece viable, aunque definir el centro lo tendria que hacer en tiempo de diseño de las masas, y estos centros tendrían que ser "invisibles" cosa que no me agrada. ).

*Crear una masa "invisible" (Detección de choques por rectángulos) ( Es decir definir tantos rectángulos en lugares X de la masa y definir los centros de estos rectángulos y posteriormente por medio de 3 de sus vértices de un rectángulo (Coordenadas X,Y,Z de los 3 vértices) la una 4 ajena a este rectángulo. ).

Algunas sugerencias o ideas?

P.D.: No meto códigos ya que solo deseo obtener ideas.

Temibles Lunas!¡.
#35
.
Alguien sabe de donde descargo esta librería con el Header indicado?, ya que mi Compilador no lo trae en su paquete (es el IDE Code::Blocks con el compilador Predeterminado).

dlfcn.h

Dulces Lunas!¡.
#36
.
Crear una función que mueva los bit's (Por si se aparece Karkrack, Cobein o similares NO ASM-Inline) a la izquierda o derecha.

(Los Números binarios se leen de izquierda a derecha, quien no tenga idea use la calculadora de windows o investigue en google como determinar el valor en Base 10).

Los ejemplos son considerando {1 Byte = 8 Bits, con el byte de signo.} la función deberá trabajar con (4 Bytes = 32 bit's = Long)

Ejemplo 1:

Se ingresa el numero  45  de desplazan 2 bit's a la izquierda el resultado es 180
es decir en binario:
00101101  {Desplazando 2 bit's Resultado--->} 10110100

Ejemplo 2:

Se ingresa el numero (-128) se desplazan 5 bit's a la izquierda el resultado es: 0
es decir en binario:
10000000 {Desplazando 5 bit's Resultado--->} 00000000

Ejemplo 3:

Se ingresa el numero 1 se desplazan 5 bit's a la izquierda el resultado es: 32
es decir en binario:
00000001 {Desplazando 5 bit's Resultado--->} 00100000

Ejemplo 4:

Se ingresa el numero 1 se desplazan 5 bit's a la derecha el resultado es: 0
es decir en binario:
00000001 {Desplazando 5 bit's Resultado--->} 00000000

Ejemplo 5:

Se ingresa el numero (-2) se desplazan 5 bit's a la derecha el resultado es: -1
es decir en binario:
11111110 {Desplazando 5 bit's Resultado--->} 11111111

Ejemplo 6:

Se ingresa el numero (-1) se desplazan 5 bit's a la derecha el resultado es: -1
es decir en binario:
11111111 {Desplazando 5 bit's Resultado--->} 11111111

Formato de la funcion:

Código (Vb) [Seleccionar]


Public Function Bits_d(ByVal lVal As Long, Optional lDesplazamiento As Integer) As Long
'   //  lVal                Indica el valor ingresado (Base 10).
'   //  lDesplazamiento     Indica la longitud de bit's a dezplazar.
'   //  Bits_d              Retorna el resultado Final (Base 10)
   ...
End Function




Edito:


Codigo para probar los resultados:

Código (Vb) [Seleccionar]


Private Sub Form_Load()
Dim lres        As Long
    lres = DebugAndRet(Bits_d(267614144, (-1)))
    lres = DebugAndRet(Bits_d(lres, (-6)))
    lres = DebugAndRet(Bits_d(lres, 2))
    lres = DebugAndRet(Bits_d(lres, 2))
    lres = DebugAndRet(Bits_d(lres, 2))
    lres = DebugAndRet(Bits_d(lres, 2))
    lres = DebugAndRet(Bits_d(lres, (-2)))
    lres = DebugAndRet(Bits_d(lres, (-24)))
End Sub

Private Function DebugAndRet(ByVal lVal As Long) As Long
    Debug.Print lVal
    DebugAndRet = lVal
End Function



Resultados en el Debug:



535228288
-105127936
-26281984
-6570496
-1642624
-410656
-1642624
-2147483648



Resultados en Binario:
Pruebas con Test Manual...



00001111111100110111011111000000  <-- {267614144}  <--- De este binario se parte...
00011111111001101110111110000000  <-- {-01}
11111001101110111110000000000000  <-- {-06}
11111110011011101111100000000000  <-- {+02}
11111111100110111011111000000000  <-- {+02}
11111111111001101110111110000000  <-- {+02}
11111111111110011011101111100000  <-- {+02}
11111111111001101110111110000000  <-- {-02}
10000000000000000000000000000000  <-- {-24} <-- {-2147483648}



Dulces Lunas!¡.
#37
.
el código lo pongo publico ya que a mas de a uno le interese a la larga, no soy experto en ASM pero bueno.

Código (vb) [Seleccionar]


Option Explicit

Private Declare Function LoadLibrary Lib "kernel32.dll" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As Long
Private Declare Function GetProcAddress Lib "kernel32.dll" (ByVal hModule As Long, ByVal lpProcName As String) As Long
Private Declare Function CallWindowProc Lib "USER32" Alias "CallWindowProcW" (ByVal lpPrevWndFunc As Long, ByVal hwnd As Long, ByVal msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

Private Sub form_load()
Dim bASM(0 To 27)           As Byte
Dim i                       As Integer
Dim sMsg                    As String
Dim sTitulo                 As String

    sMsg = "Hola Mundo"
    sTitulo = "Titulo de un msgbox"

    '   Cada Instruccion pesa {1 Bytes} y el numero de "_" son la cantidad de bytes esperados habitualmente si son 4 es que sea normalmente un puntero, pero eso depende del formato de la instruccion.
    '   Para informacion de los OpCodes:
    '   //  http://ref.x86asm.net/geek.html
    '   PUSH ____
    '   PUSH ____
    '   PUSH ____
    '   PUSH ____
    '   MOV EAX, ____
    '   CALL EAX
    '   RET
    i = 0
    bASM(i) = &H68: i = LongToByte(vbYesNoCancel, bASM(), i + 1)    ' PUSH {vbYesNoCancel}      5 bytes ( 1(&H68) + long(vbYesNoCancel) ).
    bASM(i) = &H68: i = LongToByte(StrPtr(sTitulo), bASM(), i + 1)  ' PUSH {StrPtr(sTitulo)}    5 bytes ( 1(&H68) + long(StrPtr(sTitulo)) )..
    bASM(i) = &H68: i = LongToByte(StrPtr(sMsg), bASM(), i + 1)     ' PUSH {StrPtr(sMsg)}       5 bytes ( 1(&H68) + long(StrPtr(sMsg)) )..
    bASM(i) = &H68: i = LongToByte(&H0, bASM(), i + 1)              ' PUSH {&H0}                5 bytes ( 1(&H68) + long(&H0) )..
   
    ' MOV {EAX},{LongToByte(GetProcAddress(LoadLibrary("user32.dll"), "MessageBoxW")}
    bASM(i) = &HB8: i = LongToByte(GetProcAddress(LoadLibrary("user32.dll"), "MessageBoxW"), bASM(), i + 1) ' 5 bytes
    bASM(i) = &HFF: i = i + 1 ' CALL ___    1 bytes
    bASM(i) = &HD0: i = i + 1 ' EAX         1 bytes
    bASM(i) = &HC3: i = i + 1 ' RET         1 bytes
    MsgBox CallWindowProc(ByVal VarPtr(bASM(0)), 0&, 0&, 0&, 0&)    ' Run ASM
End Sub

Private Function LongToByte(ByVal lLong As Long, ByRef bReturn() As Byte, Optional i As Integer = 0) As Long
    bReturn(i) = lLong And &HFF
    bReturn(i + 1) = (lLong And &HFF00&) \ &H100
    bReturn(i + 2) = (lLong And &HFF0000) \ &H10000
    bReturn(i + 3) = (lLong And &HFF000000) \ &H1000000
    LongToByte = i + 4
End Function



Dulces Lunas!¡.
#38
Bueno ya sabemos que las funciones con operaciones binarias son mas rápidas y mas practicas a la hora de ejecutarse.

La intención de este tema es que se creen una sola publicacion donde se pueden encontrar estas funciones de manera amena.

Código (vb) [Seleccionar]


'   //  Para valores tipo Long
Private Sub lSwap(ByRef lVal1 As Long, ByRef lVal2 As Long)
   '   //  Intercambia {lVal1} por {lVal2} y {lVal2} a {lVal1} sin variable temporal
   lVal1 = lVal1 Xor lVal2
   lVal2 = lVal2 Xor lVal1
   lVal1 = lVal1 Xor lVal2
End Sub
Private Function lIsNegative(ByRef lVal As Long)
   '   //  Para cualquier valor que lVal pueda tomar.
   '   //  Comprueba si lval es negativo.
   lIsNegative = (lVal And &H80000000)
End Function

Private Function iIsNegative(ByRef iVal As Integer) As Boolean
   '   //  Para cualquier valor que iVal pueda tomar.
   '   //  Comprueba si lval es negativo.
   iIsNegative = (iVal And 32768)
End Function

Private Sub iSwap(ByRef iVal1 As Integer, ByRef iVal2 As Integer)
   '   //  Intercambia {iVal1} por {iVal2} y {iVal2} a {iVal1} sin variable temporal
   iVal1 = iVal1 Xor iVal2
   iVal2 = iVal2 Xor iVal1
   iVal1 = iVal1 Xor iVal2
End Sub

Private Sub bSwap(ByRef iVal1 As byte, ByRef iVal2 As byte)
   '   //  Intercambia {iVal1} por {iVal2} y {iVal2} a {iVal1} sin variable temporal
   iVal1 = iVal1 Xor iVal2
   iVal2 = iVal2 Xor iVal1
   iVal1 = iVal1 Xor iVal2
End Sub

Function max(ByVal val1 As Long, ByVal val2 As Long) As Long
   If (val1 > val2) Then
       max = val1
   Else
       max = val2
   End If
End Function

Function min(ByVal val1 As Long, ByVal val2 As Long) As Long
   If (val1 > val2) Then
       min = val2
   Else
       min = val1
   End If
End Function

Function bSwapBit(ByVal myLong As Long, ByVal bit1 As Byte, ByVal bit2 As Byte) As Long
'   Los bits se CUENTAS DE DERECHA A IZQUIERDA es decir:    31, 30, ... , 3, 2, 1, 0
'   Solo se admite rango 0 al 31.
Dim aux As Long
Dim mask As Long
   
   aux = max(bit1, bit2)
   bit2 = min(bit1, bit2)
   bit1 = aux  '   max
   Debug.Assert (bit1 > 31)    '   No se permiten numero mayores a 32
   Debug.Assert (bit2 < 0)     '   No se permiten valores negativos
   mask = Not ((2 ^ bit1) Or (2 ^ bit2))
   aux = (2 ^ (bit1 - bit2))
   bSwapBit = (myLong And mask) Or _
              (myLong And (2 ^ bit1)) / aux Or _
              (myLong And (2 ^ bit2)) * aux
End Function



Si alguien se sabe mas y quiere aportarlas están en el lugar indicado.

Temibles Lunas!¡.
#39
.

Cita de: BlackZeroX▓▓▒▒░░ en 27 Mayo 2011, 04:55 AM
@Psyke1

Mas que una matriz quedaría precioso en una clase... al rato lo traslado a una clase para aumentar la velocidad de procesamiento, ya que de este modo se le aumenta el peformance ( en relación procesador/tiempo, pero no memoria ) con una clase.


Este código es una mera actualización directa de este otro, se puede decir que es la version 2.0

[source] Números Aleatorio desde X a Y con excepciones.

Vaya solo le falta una opción a mi punto de vista y es meterle una lista de números antes de generar alguno tal cual se le hace en la función solo que ahora seria una propiedad, y podría modificarse en cualquier instante, pero eso se los dejo a ustedes, yo ya hice mi labor.

* El ordenamiento QuickSort se sustituyo por una heuristica mas eficiente.

En un modulo de clase:

cRndNumbersNR.cls

Código (vb) [Seleccionar]


'
' ////////////////////////////////////////////////////////////////
' // Autor: BlackZeroX ( Ortega Avila Miguel Angel )            //
' //                                                            //
' // Web: http://InfrAngeluX.Sytes.Net/                         //
' //                                                            //
' // |-> Pueden Distribuir Este Codigo siempre y cuando         //
' // no se eliminen los creditos originales de este codigo      //
' // No importando que sea modificado/editado o engrandesido    //
' // o achicado, si es en base a este codigo                    //
' ////////////////////////////////////////////////////////////////

Option Explicit

Private Declare Function VarPtrA Lib "msvbvm60.dll" Alias "VarPtr" (ByRef Ptr() As Any) As Long
Private Declare Sub lCopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (ByVal Destination As Long, ByVal Source As Long, ByVal Length As Long)

Private Type stRangos
   lValIni         As Long
   lValEnd         As Long
End Type

Private lcvalmax    As Long
Private lcvalmin    As Long

Private lvcsplit()  As stRangos
Private lacexcep()  As Long

Private bChange     As Long

Private Sub Swapnumbers(ByRef lvalone As Long, ByRef lvaltwo As Long)
'   //  Intercambia el contenido de las variables.
Dim lvaltmp         As Long
   lvaltmp = lvalone
   lvalone = lvaltwo
   lvaltwo = lvaltmp
End Sub

Private Function Fixnumbers(ByRef lvalmin As Long, lvalmax As Long) As Boolean
'   //  Corrige los valores dados.
   If lvalmax < lvalmin Then
       Call Swapnumbers(lvalmin, lvalmax)
       Fixnumbers = True
   End If
End Function

Private Function NumRandom(lvalmin As Long, lvalmax As Long) As Long
'   //  Genera un Numero aleatorio de acuerdo a un rango dado.
   Call Fixnumbers(lvalmin, lvalmax)
   Call Randomize
   NumRandom = (lvalmin - lvalmax) * Rnd + lvalmax
End Function

Public Sub Reset()
'   //  Reinicia y permite nuevamente generar los números aleatorios desde el principio, si no aplica este al generar todos los numeros, entonces no generara mas números y devolverá únicamente 0..
   Erase lvcsplit()
   Erase lacexcep()
   ReDim lvcsplit(0 To 0)
   lvcsplit(0).lValIni = lcvalmin
   lvcsplit(0).lValEnd = lcvalmax
   bChange = False
End Sub

Public Property Get GetMore() As Boolean
'   //  Hay mas ocurrencias? cuando ya no hay se elimina el array de ocurrencias.
   GetMore = Itsarrayini(VarPtrA(lvcsplit)) Or bChange = True
End Property

Private Function Itsarrayini(ByVal lpszv As Long, Optional llen As Long = 4) As Boolean
'   //  Obtiene el limite superior de los numeros a generar de manera aleatoria sin repetir.
Dim lpsz                    As Long
   If lpszv <> 0 And llen > 0 Then
       Call lCopyMemory(ByVal VarPtr(lpsz), ByVal lpszv, llen)
       Itsarrayini = Not lpsz = 0
   End If
End Function

Private Sub SeparateRange(ByVal lDivVal As Long, ByVal lindex As Long, ByRef vArray() As stRangos)
'   //  Es un proceso para aplicar el dicho "Divide y Venceras", esto aumenta mucho la velocidad para no repetir numeros dentro de un rango dado y generados de manera aleatoria.
'   //  Repeti un poco de codigo lo siento xP...
Dim lu          As Long
Dim lpsz        As Long
   
   If (vArray(lindex).lValIni <= lDivVal And lDivVal <= vArray(lindex).lValEnd) Then
       lu = UBound(vArray)
       lpsz = VarPtr(vArray(lindex))
       If (vArray(lindex).lValIni = lDivVal) Then
           vArray(lindex).lValIni = vArray(lindex).lValIni + 1
           If (vArray(lindex).lValIni > vArray(lindex).lValEnd) Then
               If (lu > 0) Then
                   lCopyMemory lpsz, lpsz + &H8, ((lu - lindex) * &H8)
                   lu = lu - 1
                   ReDim Preserve vArray(0 To lu)
               Else
                   Erase vArray()
               End If
           End If
       ElseIf (vArray(lindex).lValEnd = lDivVal) Then
           vArray(lindex).lValEnd = vArray(lindex).lValEnd - 1
           If (vArray(lindex).lValIni > vArray(lindex).lValEnd) Then
               If (lu > 0) Then
                   lCopyMemory lpsz, lpsz + &H8, ((lu - lindex) * &H8)
                   lu = lu - 1
                   ReDim Preserve vArray(0 To lu)
               Else
                   Erase vArray()
               End If
           End If
       Else
           lu = lu + 1
           ReDim Preserve vArray(0 To lu)
           lpsz = VarPtr(vArray(lindex))
           lCopyMemory lpsz + &H10, (lpsz + &H8), (((lu - 1) - lindex) * &H8)
           vArray(lindex + 1).lValEnd = vArray(lindex).lValEnd
           vArray(lindex + 1).lValIni = (lDivVal + 1)
           vArray(lindex).lValEnd = (lDivVal - 1)
           
       End If
   End If
   
End Sub

Public Property Get GetNumRandom() As Long
'   //  Genera un numero aleatorio sin repetir de acuerdo a un rango de valores dados.
Dim lindex          As Long
Dim lu              As Long
Dim lret            As Long
   If (bChange = True) Then
       Call Fixnumbers(lcvalmin, lcvalmax)
       Call Reset
   End If
   If (GetMore = True) Then
       lindex = NumRandom(0, UBound(lvcsplit))
       lret = NumRandom(lvcsplit(lindex).lValIni, lvcsplit(lindex).lValEnd)
       SeparateRange lret, lindex, lvcsplit
       If (Itsarrayini(VarPtrA(lacexcep)) = True) Then
           lu = UBound(lacexcep) + 1
       Else
           lu = 0
       End If
       ReDim Preserve lacexcep(0 To lu)
       lacexcep(lu) = lret
       GetNumRandom = lret
   End If
End Property

Public Property Let minval(ByVal ldata As Long)
'   //  Establece el limite inferior de los numeros a generar de manera aleatoria sin repetir.
   lcvalmin = ldata
   bChange = True
End Property

Public Property Get minval() As Long
'   //  Obtiene el limite inferior de los numeros a generar de manera aleatoria sin repetir.
   minval = lcvalmin
End Property

Public Property Let maxval(ByVal ldata As Long)
'   //  Establece el limite superior de los numeros a generar de manera aleatoria sin repetir.
   lcvalmax = ldata
   bChange = True
End Property

Public Property Get maxval() As Long
'   //  Obtiene el limite superior de los numeros a generar de manera aleatoria sin repetir.
   maxval = lcvalmax
End Property

Public Property Get GetNumbers() As Long()
'   //  Devueve una coleccion de los numeros generados.
   GetNumbers() = lacexcep()
End Property

Public Function RegenerateThis(ByVal lVal As Long) As Boolean
Dim ii              As Long
Dim lub             As Long
    If (lcvalmin <= lVal) And (lcvalmax >= lVal) Then
        If (breglist = True) Then
            If (Itsarrayini(VarPtrA(lacexcep)) = True) Then
                For ii = 0 To UBound(lacexcep)
                    If (lacexcep(ii) = lVal) Then
                        RemoveInArrayLong ii, lacexcep()
                        Exit For
                    End If
                Next ii
            End If
        End If
        If (Itsarrayini(VarPtrA(lvcsplit)) = True) Then
            lub = UBound(lvcsplit)
            For ii = 0 To (lub - 1)
                If (lvcsplit(ii).lValEnd > lVal) And (lvcsplit(ii + 1).lValIni < lVal) Then
                    If ((lvcsplit(ii).lValEnd + 1) = lVal) Then
                        lvcsplit(ii).lValEnd = lVal
                    ElseIf ((lvcsplit(ii + 1).lValIni) = lVal) Then
                        lvcsplit(ii + 1).lValIni = lVal
                    End If
                    Select Case (lvcsplit(ii).lValEnd = lvcsplit(ii + 1).lValIni)
                        Case 0, 1
                            lub = (lub - 1)
                            lvcsplit(ii).lValEnd = lvcsplit(ii + 1).lValEnd
                            ReDim Preserve lvcsplit(0 To lub)
                        Case Else
                            If Not ((lvcsplit(ii).lValEnd + 1) = lvcsplit(ii + 1).lValIni) Then
                                lub = (lub + 1)
                                ReDim Preserve lvcsplit(0 To lub)
                                SwapBlockMemoryInCicle VarPtr(lvcsplit(ii)), (VarPtr(lvcsplit(lub)) + LenB(lvcsplit(0))), LenB(lvcsplit(0))
                                lvcsplit(ii + 1).lValIni = lVal
                                lvcsplit(ii + 1).lValEnd = lVal
                            End If
                    End Select
                    RegenerateThis = True
                Else
                    Exit For
                End If
            Next ii
        Else
            ReDim lvcsplit(0 To 0)
            lvcsplit(0).lValIni = lVal
            lvcsplit(0).lValEnd = lVal
        End If
    End If
End Function

Private Sub Class_Initialize()
'   //  Constructor de la clase, no tengo por que hacer lo siguiente pero como me estoy adaptando a un standart lo hare.
   bChange = False
End Sub



uso simple:

Código (vb) [Seleccionar]


Option Explicit

Private Sub Form_Load()
Dim cls     As cRndNumber
Dim lc      As Long
   Set cls = New cRndNumber
   With cls
   '   //  Este simple codigo probara la velocidad, que de hecho ya es rapido a consideracion de otros que conozco.
       .minval = 0
       .maxval = 99999
       Do While (.GetMore = True)
           DoEvents
           lc = .GetNumRandom
       Loop
       MsgBox "Se recorrieron todos los numeros sin repetir alguno xD"
   '   //  Si se cambian los valores menor y mayor entonces es como si se le aplicara call .Reset
   '   //  Este codigo hara un test de repeticion
       .minval = 0
       .maxval = 99
       Do While (.GetMore = True)
           DoEvents
           Debug.Print .GetNumRandom
       Loop
       
       MsgBox "Se recorrieron todos los numeros sin repetir alguno xD"
   End With
End Sub



Temibles Lunas!¡.
#40
.
Lo que hace este código es que crea numero aleatorio desde un valor mínimo a uno valor máximo pero si se encuentra un numero Z entre los mismo JAMAS saldrá como numero aleatorio.

Una breve introducción antes del código fuente...

Aun no pruebo la velocidad...

OJO: Las esecciones no deben repetirse.


NumerosAleatoriosEx (Numero Inicio, Numero Final, Array de valores a no considerar) {
MatrixRangos() = Realizar una búsqueda de valores para verificar si alguno de los numeros del array estan entre el valor de Inicio o el valor del Final: (un For Next bastara) , y generamos cortes de array's por ejemplo (  Inicio=0 final=10 array={5,8}  este paso genera 3 array que son:  {0,4},{6,7},{9,10} )
iIndice = Generamos un numero aleatorio desde Lbound(MatrixRangos()) hasta Ubound(MatrixRangos())
Retornamos el numero que se genera un numero aleatorio según los rangos que indique MatrixRangos( iIndice )(0) y MatrixRangos( iIndice )(1)
}


Código (Vb) [Seleccionar]


Option Explicit

Private Type stRangos
   lValIni         As Long
   lValEnd         As Long
End Type

Public Sub swapNumbers(ByRef lValOne As Long, ByRef lValTwo As Long)
Dim lValTmp         As Long
   lValTmp = lValOne
   lValOne = lValTwo
   lValTwo = lValTmp
End Sub

Public Function FixNumbers(ByRef lValMin As Long, lValMax As Long) As Boolean
   If lValMax < lValMin Then
       Call swapNumbers(lValMin, lValMax)
       FixNumbers = True
   End If
End Function

Public Function NumeroAleatorio(lValMin As Long, lValMax As Long) As Long
   Call FixNumbers(lValMin, lValMax)
   Call Randomize
   NumeroAleatorio = (lValMin - lValMax) * Rnd + lValMax
End Function

Public Function NumeroAleatorioEx(ByVal lValIni As Long, ByVal lValEnd As Long, ParamArray aNoRepet() As Variant) As Long
'   //  Debera pasarse el parametro {aNoRepet} ordenado de menor a mayor ( indice lbound siendo el valor menor y ubound el valor mayor ).
'   //  La funcion Si no puede generar un numero aleatorio retornara {lValIni-1}
On Error GoTo GetNumber
Dim avArray()       As Variant
Dim lUB             As Long
Dim lNextVal        As Long
Dim li              As Long, lIndex         As Long
Dim tRangos()       As stRangos

   If (Not IsMissing(aNoRepet)) Then
       If (IsArray(aNoRepet(0))) Then
           avArray = aNoRepet(0)
       Else
           avArray = aNoRepet
       End If
       
       lUB = UBound(avArray)
       Call Start_QuickSort(avArray, AcendetOrder)     '   //  http://infrangelux.hostei.com/index.php?option=com_content&view=article&id=14:artquicksortybublesort&catid=2:catprocmanager&Itemid=8
       
       ReDim tRangos(0 To (lUB + 1))                   '   //  Cache de memoria...
       With tRangos(0)
           .lValIni = lValIni
           .lValEnd = lValEnd
       End With
       lNextVal = lValIni
       lIndex = 0
       
       For li = 0 To lUB
           If (avArray(li) <= lValEnd And _
               avArray(li) > lValIni And _
               lNextVal <> avArray(li)) Then
               If (lNextVal > lValIni) Then
                   lIndex = lIndex + 1
                   With tRangos(lIndex)
                       .lValIni = lNextVal
                       .lValEnd = avArray(li) - 1
                   End With
                   lNextVal = (avArray(li) + 1)
                   
               ElseIf (lNextVal = lValIni) Then
                   tRangos(lIndex).lValEnd = avArray(li) - 1
                   lNextVal = (avArray(li) + 1)
                   
               End If
           ElseIf (avArray(li) = tRangos(0).lValIni) Then
               lIndex = lIndex - 1
               lNextVal = tRangos(0).lValIni + 1
           Else
               lNextVal = lNextVal + 1
           End If
       Next
       
       If (lIndex > -1) Then
           If ((tRangos(lIndex).lValEnd + 1) <= lValEnd And lNextVal <= lValEnd) Then
               lIndex = lIndex + 1
               ReDim Preserve tRangos(0 To lIndex)
               With tRangos(lIndex)
                   .lValIni = avArray(lUB) + 1
                   .lValEnd = lValEnd
               End With
           Else
               ReDim Preserve tRangos(0 To lIndex)
           End If
           
       ElseIf (lNextVal > lValEnd) Then
           NumeroAleatorioEx = lValIni - 1
           Exit Function
           
       Else
           lIndex = 0
           tRangos(lIndex).lValIni = lNextVal
           
       End If
       
       li = NumeroAleatorio(0, lIndex)
       NumeroAleatorioEx = NumeroAleatorio(tRangos(li).lValIni, tRangos(li).lValEnd)
       Exit Function
       
   End If
GetNumber:
   NumeroAleatorioEx = NumeroAleatorio(lValIni, lValEnd)
End Function

Private Sub Form_Load()
Dim ii              As Integer
Dim lres            As Long
Dim vArray()        As Variant

Const lValIni       As Long = 5
Const lValEnd       As Long = 10
   
   lres = NumeroAleatorioEx(lValIni, lValEnd)
   ReDim vArray(0 To 0)
   vArray(ii) = lres
   Debug.Print lres
   For ii = 1 To 11
       lres = NumeroAleatorioEx(lValIni, lValEnd, vArray)
       ReDim Preserve vArray(0 To ii)
       vArray(ii) = lres
       If (lres = (lValIni - 1)) Then
           Debug.Print "Ya no se pueden crear mas numeros aleatorios, las esecciones llenan todas las opciones."
       Else
           Debug.Print lres
       End If
   Next ii
End Sub



Salida del ejemplo:



10
7
9
8
6
5
Ya no se pueden crear mas numeros aleatorios, las esecciones llenan todas las opciones.
Ya no se pueden crear mas numeros aleatorios, las esecciones llenan todas las opciones.
Ya no se pueden crear mas numeros aleatorios, las esecciones llenan todas las opciones.
Ya no se pueden crear mas numeros aleatorios, las esecciones llenan todas las opciones.
Ya no se pueden crear mas numeros aleatorios, las esecciones llenan todas las opciones.
Ya no se pueden crear mas numeros aleatorios, las esecciones llenan todas las opciones.



Temibles Lunas!¡.
#41
Foro Libre / Alguien sabe que serie es?
3 Mayo 2011, 09:31 AM
.
Me parecio divertida y buena para pasar el rato alguien sabe cual serie es?

[youtube=425,350]http://www.youtube.com/watch?v=HF_b6FF0RF4[/youtube]

Dulces Lunas!¡.
#42
.
Tal vez a alguien le sirva esta clase que me hice para manipular un conjunto de bytes similar como vb6 las cadenas y evitarme el ajetreo de detectar los desgraciados memory leak que a mas de uno nos frustan el desarrollo/ejecucion de un programa, aun que por hay deben haber algunos agujeros... pero aun así ya funciona y eso es lo que me interesaba realmente. para mi trabajo de universidad.

Disculpen po no usar new() ni delete() para cargar las clases.

cls_byte.h
Código (cpp) [Seleccionar]


#ifndef _CLS_BYTE_H_
#define _CLS_BYTE_H_

#include <fstream>
#include <stdlib.h>
#include <string.h>
#include "Bytes/modutiles.h"

//    #include <stdbool.h> <-- C ANSI... (C99)CLS_BYTE_CPP

class cls_byte;

#ifndef Struct_clsByte_
#define Struct_clsByte_
struct Struct_clsByte
{
   cls_byte    *pbyt_class;
   size_t      szt_count;
};
#endif  // Struct_clsByte_

class cls_byte
{
private:
   size_t        szt_len;
   Byte          *pbyt_data;
public:
   cls_byte();
   ~cls_byte();

   size_t           Getlen ( );
   Byte       *GetBytesPtr ( );
   struct Struct_Byte *GetBytes ( );

   Byte          *SetBytes ( Byte *pByt_Bytes , size_t szt_lnBytes );  // ok
   Byte          *SetBytes ( cls_byte     *pclsbyteFind );
   Byte          *SetBytes ( Struct_Byte  *pclsbyteFind );             // ok

   bool            SetBytesFromFile( const char *pcchr );
   bool            SetBytesFromFile( const char *pcchr , size_t szt_ini );
   bool            SetBytesFromFile( const char *pcchr , size_t szt_ini , long lng_len );

   cls_byte       *Mid     ( size_t szt_start , size_t szt_len );
   cls_byte       *Mid     ( size_t szt_start );

   Struct_clsByte *Split   ( Byte *pbyt_delimiter , size_t szt_lndelimiter , long lng_limit );
   Struct_clsByte *Split   ( Byte *pbyt_delimiter , size_t szt_lndelimiter );
   Struct_clsByte *Split   ( cls_byte *pclsbytelim , long lng_limit );
   Struct_clsByte *Split   ( cls_byte *pclsbytelim );

   cls_byte       *Replace ( cls_byte *pclsbyteFind , cls_byte *pclsbyteReplacement );
   cls_byte       *Replace ( cls_byte *pclsbyteFind , cls_byte *pclsbyteReplacement , size_t szt_Start );
   cls_byte       *Replace ( cls_byte *pclsbyteFind , cls_byte *pclsbyteReplacement , size_t szt_Start , long lng_Count );
   cls_byte       *Replace ( cls_byte *pclsbyteFind , cls_byte *pclsbyteReplacemente , size_t szt_Start , long lng_Count , e_CompareMethod enum_Compare );
   cls_byte       *Replace ( cls_byte *pclsbyteFind , Byte *pByt_Replacement , size_t szt_lnReplacement );
   cls_byte       *Replace ( cls_byte *pclsbyteFind , Byte *pByt_Replacement , size_t szt_lnReplacement , size_t szt_Start );
   cls_byte       *Replace ( cls_byte *pclsbyteFind , Byte *pByt_Replacement , size_t szt_lnReplacement , size_t szt_Start , long lng_Count );
   cls_byte       *Replace ( cls_byte *pclsbyteFind , Byte *pByt_Replacement , size_t szt_lnReplacement , size_t szt_Start , long lng_Count , e_CompareMethod enum_Compare );
   cls_byte       *Replace ( Byte *pByt_Find , size_t szt_lnFind , cls_byte *pclsbyteReplacemente );
   cls_byte       *Replace ( Byte *pByt_Find , size_t szt_lnFind , cls_byte *pclsbyteReplacemente , size_t szt_Start );
   cls_byte       *Replace ( Byte *pByt_Find , size_t szt_lnFind , cls_byte *pclsbyteReplacemente , size_t szt_Start , long lng_Count );
   cls_byte       *Replace ( Byte *pByt_Find , size_t szt_lnFind , cls_byte *pclsbyteReplacemente , size_t szt_Start , long lng_Count , e_CompareMethod enum_Compare );
   cls_byte       *Replace ( Byte *pByt_Find , size_t szt_lnFind , Byte *pByt_Replacement , size_t szt_lnReplacement );
   cls_byte       *Replace ( Byte *pByt_Find , size_t szt_lnFind , Byte *pByt_Replacement , size_t szt_lnReplacement , size_t szt_Start );
   cls_byte       *Replace ( Byte *pByt_Find , size_t szt_lnFind , Byte *pByt_Replacement , size_t szt_lnReplacement , size_t szt_Start , long lng_Count );
   cls_byte       *Replace ( Byte *pByt_Find , size_t szt_lnFind , Byte *pByt_Replacement , size_t szt_lnReplacement , size_t szt_Start , long lng_Count , e_CompareMethod enum_Compare );

   size_t            Index ( cls_byte *pclsbyte );
   size_t            Index ( cls_byte *pclsbyte , size_t szt_Start );
   size_t            Index ( cls_byte *pclsbyte , size_t szt_Start , e_CompareMethod enum_Compare );
   size_t            Index ( Byte *pByt_Find , size_t szt_lsf );
   size_t            Index ( Byte *pByt_Find , size_t szt_lsf , size_t szt_Start );
   size_t            Index ( Byte *pByt_Find , size_t szt_lsf , size_t szt_Start , e_CompareMethod enum_Compare );

   bool              Exits ( cls_byte *pclsbyte );
   bool              Exits ( cls_byte *pclsbyte , size_t szt_Start );
   bool              Exits ( cls_byte *pclsbyte , size_t szt_Start , long lng_interval );
   bool              Exits ( cls_byte *pclsbyte , size_t szt_Start , long lng_interval , e_CompareMethod enum_Compare );
   bool              Exits ( Byte *pByt_Find , size_t szt_lsf );
   bool              Exits ( Byte *pByt_Find , size_t szt_lsf , size_t szt_Start );
   bool              Exits ( Byte *pByt_Find , size_t szt_lsf , size_t szt_Start , long lng_interval );
   bool              Exits ( Byte *pByt_Find , size_t szt_lsf , size_t szt_Start , long lng_interval , e_CompareMethod enum_Compare );
};
//    #include "cls_byte.cpp"
#endif // CLS_BYTE_H



cls_byte.cpp
Código (cpp) [Seleccionar]


#ifndef _CLS_BYTE_CPP
#define _CLS_BYTE_CPP 1

   #include "cls_byte.h"
   
   cls_byte::cls_byte()
   {
       this->szt_len   = 0;
       this->pbyt_data  = NULL;
   }

   cls_byte::~cls_byte()
       { setnewptrf<Byte*>( this->pbyt_data , NULL ); }

   size_t cls_byte::Getlen()
       { return this->szt_len; }

   Byte *cls_byte::GetBytesPtr()
       { return this->pbyt_data; }

   bool cls_byte::SetBytesFromFile(const char *pcchr)
       { return this->SetBytesFromFile( pcchr , 0 , -1 ); }
   bool cls_byte::SetBytesFromFile(const char *pcchr, size_t szt_ini)
       { return this->SetBytesFromFile( pcchr , szt_ini , -1 ); }
   bool cls_byte::SetBytesFromFile(const char *pcchr, size_t szt_ini, long lng_len)
       {
           FILE            *hfile              = fopen( pcchr , "r+b" );
           Struct_Byte     stbyt_data          = { NULL , 0 };
           size_t          szt_end             = 0;

           if ( hfile != NULL )
           {
               stbyt_data.szt_lenbytes             = flen( hfile );
               if ( lng_len <= -1 )
                   lng_len                             = stbyt_data.szt_lenbytes;
               szt_end = 0;
               if ( fix_numbers_range<size_t>( &szt_ini , &szt_end , &lng_len , NULL ,  0 , stbyt_data.szt_lenbytes-1 ) == true )
               {
                   stbyt_data.pbyt_bytes       = (Byte*)malloc(sizeof(Byte)*lng_len);
                   fseek       ( hfile , (long)szt_ini , SEEK_SET);
                   fread       ( (char*)stbyt_data.pbyt_bytes , 1 , lng_len ,  hfile );
               }
               stbyt_data.szt_lenbytes     = (size_t)lng_len;
               fclose      ( hfile );
               this->SetBytes( &stbyt_data );
           }

       }
   Byte *cls_byte::SetBytes(Struct_Byte *pclsbyteFind)
       { return this->SetBytes( pclsbyteFind->pbyt_bytes , pclsbyteFind->szt_lenbytes ); }
   Byte *cls_byte::SetBytes(cls_byte *pclsbyteFind)
       { return this->SetBytes( pclsbyteFind->GetBytesPtr() , pclsbyteFind->Getlen() ); }
   Byte *cls_byte::SetBytes(Byte *pByt_Bytes, size_t szt_lnBytes)
   {
       this->szt_len = szt_lnBytes;
       if ( setnewptrf<Byte*>( this->pbyt_data , ByteClone( pByt_Bytes , this->szt_len ) ) == NULL)
       {
           this->szt_len = 0;
           return pByt_Bytes;
       }
       return NULL;
   }

   Struct_Byte *cls_byte::GetBytes()
   {
       struct Struct_Byte *pstrbyt_ret = (Struct_Byte*)malloc(sizeof(Struct_Byte));
       pstrbyt_ret->pbyt_bytes = ByteClone( this->pbyt_data , this->szt_len );
       pstrbyt_ret->szt_lenbytes =  this->szt_len;
       if ( pstrbyt_ret->pbyt_bytes == NULL )
           pstrbyt_ret->szt_lenbytes = 0;
       return pstrbyt_ret;
   }

   size_t cls_byte::Index(Byte *pByt_Find, size_t szt_lsf)
       { return ByteIndex( this->pbyt_data , this->szt_len  ,pByt_Find , szt_lsf ); }
   size_t cls_byte::Index(Byte *pByt_Find, size_t szt_lsf, size_t szt_Start)
       { return ByteIndex( this->pbyt_data , this->szt_len , pByt_Find , szt_lsf , szt_Start ); }
   size_t cls_byte::Index(Byte *pByt_Find, size_t szt_lsf, size_t szt_Start, e_CompareMethod enum_Compare)
       { return ByteIndex( this->pbyt_data , this->szt_len , pByt_Find , szt_lsf , szt_Start , enum_Compare ); }
   size_t cls_byte::Index(cls_byte *pclsbyte)
       { return ByteIndex( this->pbyt_data , this->szt_len , pclsbyte->pbyt_data , pclsbyte->szt_len ); }
   size_t cls_byte::Index(cls_byte *pclsbyte, size_t szt_Start)
       { return ByteIndex( this->pbyt_data , this->szt_len , pclsbyte->pbyt_data , pclsbyte->szt_len , szt_Start ); }
   size_t cls_byte::Index(cls_byte *pclsbyte, size_t szt_Start, e_CompareMethod enum_Compare)
       { return ByteIndex( this->pbyt_data , this->szt_len , pclsbyte->pbyt_data , pclsbyte->szt_len , szt_Start , enum_Compare ); }


   bool cls_byte::Exits(cls_byte *pclsbyte)
       { return ByteExits( this->pbyt_data , this->szt_len , pclsbyte->pbyt_data , pclsbyte->szt_len ); }
   bool cls_byte::Exits(cls_byte *pclsbyte, size_t szt_Start)
       { return ByteExits( this->pbyt_data , this->szt_len , pclsbyte->pbyt_data , pclsbyte->szt_len , szt_Start ); }
   bool cls_byte::Exits(cls_byte *pclsbyte, size_t szt_Start, long lng_interval)
       { return ByteExits( this->pbyt_data , this->szt_len , pclsbyte->pbyt_data , pclsbyte->szt_len , szt_Start , lng_interval ); }
   bool cls_byte::Exits(cls_byte *pclsbyte, size_t szt_Start, long lng_interval, e_CompareMethod enum_Compare)
       { return ByteExits( this->pbyt_data , this->szt_len , pclsbyte->pbyt_data , pclsbyte->szt_len , szt_Start , lng_interval , enum_Compare ); }
   bool cls_byte::Exits(Byte *pByt_Find, size_t szt_lsf)
       { return ByteExits( this->pbyt_data , this->szt_len , pByt_Find , szt_lsf ); }
   bool cls_byte::Exits(Byte *pByt_Find, size_t szt_lsf, size_t szt_Start)
       { return ByteExits( this->pbyt_data , this->szt_len , pByt_Find , szt_lsf , szt_Start ); }
   bool cls_byte::Exits(Byte *pByt_Find, size_t szt_lsf, size_t szt_Start, long lng_interval)
       { return ByteExits( this->pbyt_data , this->szt_len , pByt_Find , szt_lsf , szt_Start , lng_interval ); }
   bool cls_byte::Exits(Byte *pByt_Find, size_t szt_lsf, size_t szt_Start, long lng_interval, e_CompareMethod enum_Compare)
       { return ByteExits( this->pbyt_data , this->szt_len , pByt_Find , szt_lsf , szt_Start , lng_interval , enum_Compare ); }



   cls_byte *cls_byte::Replace ( cls_byte *pclsbyteFind , cls_byte *pclsbyteReplacement )
       { return this->Replace( pclsbyteFind->GetBytesPtr() , pclsbyteFind->Getlen() , pclsbyteReplacement->GetBytesPtr() , pclsbyteReplacement->Getlen() , 0 , -1 , BINARY ); }
   cls_byte *cls_byte::Replace ( cls_byte *pclsbyteFind , cls_byte *pclsbyteReplacement , size_t szt_Start )
       { return this->Replace( pclsbyteFind->GetBytesPtr() , pclsbyteFind->Getlen() , pclsbyteReplacement->GetBytesPtr() , pclsbyteReplacement->Getlen() , szt_Start , -1 , BINARY ); }
   cls_byte *cls_byte::Replace ( cls_byte *pclsbyteFind , cls_byte *pclsbyteReplacement , size_t szt_Start , long lng_Count )
       { return this->Replace( pclsbyteFind->GetBytesPtr() , pclsbyteFind->Getlen() , pclsbyteReplacement->GetBytesPtr() , pclsbyteReplacement->Getlen() , szt_Start , lng_Count , BINARY ); }
   cls_byte *cls_byte::Replace ( cls_byte *pclsbyteFind , cls_byte *pclsbyteReplacement , size_t szt_Start , long lng_Count , e_CompareMethod enum_Compare )
       { return this->Replace( pclsbyteFind->GetBytesPtr() , pclsbyteFind->Getlen() , pclsbyteReplacement->GetBytesPtr() , pclsbyteReplacement->Getlen() , szt_Start , lng_Count , enum_Compare ); }
   cls_byte *cls_byte::Replace ( cls_byte *pclsbyteFind , Byte *pByt_Replacement , size_t szt_lnReplacement )
       { return this->Replace( pclsbyteFind->GetBytesPtr() , pclsbyteFind->Getlen() , pByt_Replacement , szt_lnReplacement , 0 , -1 , BINARY ); }
   cls_byte *cls_byte::Replace ( cls_byte *pclsbyteFind , Byte *pByt_Replacement , size_t szt_lnReplacement , size_t szt_Start )
       { return this->Replace( pclsbyteFind->GetBytesPtr() , pclsbyteFind->Getlen() , pByt_Replacement , szt_lnReplacement , szt_Start , -1 , BINARY ); }
   cls_byte *cls_byte::Replace ( cls_byte *pclsbyteFind , Byte *pByt_Replacement , size_t szt_lnReplacement , size_t szt_Start , long lng_Count )
       { return this->Replace( pclsbyteFind->GetBytesPtr() , pclsbyteFind->Getlen() , pByt_Replacement , szt_lnReplacement , szt_Start , lng_Count , BINARY ); }
   cls_byte *cls_byte::Replace ( cls_byte *pclsbyteFind , Byte *pByt_Replacement , size_t szt_lnReplacement , size_t szt_Start , long lng_Count , e_CompareMethod enum_Compare )
       { return this->Replace( pclsbyteFind->GetBytesPtr() , pclsbyteFind->Getlen() , pByt_Replacement , szt_lnReplacement , szt_Start , lng_Count , enum_Compare ); }
   cls_byte *cls_byte::Replace ( Byte *pByt_Find , size_t szt_lnFind , cls_byte *pclsbyteReplacement )
       { return this->Replace( pByt_Find , szt_lnFind , pclsbyteReplacement->GetBytesPtr() , pclsbyteReplacement->Getlen() , 0 , -1 , BINARY ); }
   cls_byte *cls_byte::Replace ( Byte *pByt_Find , size_t szt_lnFind , cls_byte *pclsbyteReplacement , size_t szt_Start )
       { return this->Replace( pByt_Find , szt_lnFind , pclsbyteReplacement->GetBytesPtr() , pclsbyteReplacement->Getlen() , szt_Start , -1 , BINARY ); }
   cls_byte *cls_byte::Replace ( Byte *pByt_Find , size_t szt_lnFind , cls_byte *pclsbyteReplacement , size_t szt_Start , long lng_Count )
       { return this->Replace( pByt_Find , szt_lnFind , pclsbyteReplacement->GetBytesPtr() , pclsbyteReplacement->Getlen() , szt_Start , lng_Count , BINARY ); }
   cls_byte *cls_byte::Replace ( Byte *pByt_Find , size_t szt_lnFind , cls_byte *pclsbyteReplacement , size_t szt_Start , long lng_Count , e_CompareMethod enum_Compare )
       { return this->Replace( pByt_Find , szt_lnFind , pclsbyteReplacement->GetBytesPtr() , pclsbyteReplacement->Getlen() , szt_Start , lng_Count , enum_Compare ); }
   cls_byte *cls_byte::Replace(Byte *pByt_Find, size_t szt_lnFind, Byte *pByt_Replacement, size_t szt_lnReplacement)
       { return this->Replace( pByt_Find , szt_lnFind , pByt_Replacement , szt_lnReplacement , 0 , -1 , BINARY ); }
   cls_byte *cls_byte::Replace(Byte *pByt_Find, size_t szt_lnFind, Byte *pByt_Replacement, size_t szt_lnReplacement, size_t szt_Start)
       { return this->Replace( pByt_Find , szt_lnFind , pByt_Replacement , szt_lnReplacement , szt_Start , -1 , BINARY ); }
   cls_byte *cls_byte::Replace(Byte *pByt_Find, size_t szt_lnFind, Byte *pByt_Replacement, size_t szt_lnReplacement, size_t szt_Start, long lng_Count)
       { return this->Replace( pByt_Find , szt_lnFind , pByt_Replacement , szt_lnReplacement , szt_Start , lng_Count , BINARY ); }
   cls_byte *cls_byte::Replace(Byte *pByt_Find, size_t szt_lnFind, Byte *pByt_Replacement, size_t szt_lnReplacement, size_t szt_Start, long lng_Count, e_CompareMethod enum_Compare)
       {
           cls_byte            *cls_Ret    = (cls_byte*)malloc(sizeof(cls_byte));
           Struct_Byte         *pByt_Ret   = NULL;
           Byte                *pByt_ClnF  = ByteClone ( pByt_Find , szt_lnFind );
           Byte                *pByt_ClnR  = ByteClone ( pByt_Replacement , szt_lnReplacement );

           pByt_Ret                = ByteReplace( this->pbyt_data , this->szt_len , pByt_ClnF , szt_lnFind , pByt_ClnR , szt_lnReplacement , szt_Start , lng_Count , enum_Compare );
           cls_Ret->SetBytes       ( pByt_Ret );

           setnewptrf<Byte*>        ( pByt_ClnF , NULL );
           setnewptrf<Byte*>        ( pByt_ClnR , NULL );
           setnewptrf<Byte*>        ( pByt_Ret->pbyt_bytes , NULL );
           setnewptrf<Struct_Byte*> ( pByt_Ret , NULL );

           return cls_Ret;
       }
   cls_byte *cls_byte::Mid(size_t szt_start)
       { return this->Mid   ( szt_start , this->szt_len ); }
   cls_byte *cls_byte::Mid(size_t szt_start, size_t szt_len)
       {
           cls_byte            *cls_Ret    = (cls_byte*)malloc(sizeof(cls_byte));
           Struct_Byte         *pByt_Ret   = NULL;

           pByt_Ret                = ByteMid ( this->pbyt_data , this->szt_len , szt_start , szt_len );
           cls_Ret->SetBytes       ( pByt_Ret );

           setnewptrf<Byte*>        ( pByt_Ret->pbyt_bytes , NULL );
           setnewptrf<Struct_Byte*> ( pByt_Ret , NULL );

           return cls_Ret;
       }

   Struct_clsByte *cls_byte::Split(Byte *pbyt_delimiter, size_t szt_lndelimiter)
       { return this->Split ( pbyt_delimiter , szt_lndelimiter , -1 ); }
   Struct_clsByte *cls_byte::Split(Byte *pbyt_delimiter, size_t szt_lndelimiter, long lng_limit)
       {
           Struct_clsByte      *cls_Ret    = (Struct_clsByte*)malloc(sizeof(Struct_clsByte));
           Struct_Byte_Split   *pByt_Ret   = NULL;
           Byte                *pByt_Clone = ByteClone ( pbyt_delimiter , szt_lndelimiter );

           pByt_Ret                = ByteSplit ( this->pbyt_data , this->szt_len , pByt_Clone , szt_lndelimiter , lng_limit );

           cls_Ret->szt_count      = 0;
           cls_Ret->pbyt_class     = (cls_byte*)malloc(sizeof(cls_byte)*pByt_Ret->szt_ln);

           for ( cls_Ret->szt_count=0 ; cls_Ret->szt_count<pByt_Ret->szt_ln ; ++cls_Ret->szt_count )
           {
               cls_Ret->pbyt_class[ cls_Ret->szt_count ].SetBytes( pByt_Ret->Struct[ cls_Ret->szt_count ] );
               setnewptrf<Byte*>        ( pByt_Ret->Struct[ cls_Ret->szt_count ]->pbyt_bytes , NULL );
               setnewptrf<Struct_Byte*> ( pByt_Ret->Struct[ cls_Ret->szt_count ] , NULL );
           }

           setnewptrf<Byte*>                ( pByt_Clone , NULL );
           setnewptrf<Struct_Byte_Split*>   ( pByt_Ret , NULL );

           return cls_Ret;
       }
   Struct_clsByte *cls_byte::Split(cls_byte *pclsbytelim)
       { return this->Split ( pclsbytelim->GetBytesPtr() , pclsbytelim->Getlen() , -1 ); }
   Struct_clsByte *cls_byte::Split(cls_byte *pclsbytelim, long lng_limit)
       { return this->Split ( pclsbytelim->GetBytesPtr() , pclsbytelim->Getlen() , lng_limit ); }

#endif



Temibles Lunas!¡.
#44
Foro Libre / Goku de tepito...
10 Abril 2011, 07:12 AM
.
Este baboso me toco verlo hace tiempo en persona, por hay me veo... la cuestion es donde, el idiota segun se lo hizo por 20$ pesos ( como 1 dolar y medio ).

Goku de Tepito

es una idiotes pero me hizo cagar de risa.

Dulces Lunas!¡.
#45
Foro Libre / Ayuda matematica-
9 Abril 2011, 03:14 AM
.
Coordenadas esfericas.

OJO mis ejes Z y X son el piso y mi eje Y es mi altitud., de donde Z es lo que se define como que tan seca o lejos esta de un objeto.

Como se calcula en angulo azimutal de dos puntos?

x = d * sin(a) * cos(e)
y = d * sin(e)
z = d * cos(a) * cos(e)

donde:

d = distancia entre dos puntos ( X,Y,Z )
a = angulo azimutal
e = angulo de elevacion

hasta ahora ya pude saber como saber el angulo de elevacion de un punto con respecto al punto origen

e = csc( y/d )

Pero para el angulo de la azimutal

[Aqui empiza mi duca sigan leyendo]

llego a un punto muerto donde ya no se que rayos hacer.

El angulo azimutal involucra a el eje x y el eje z, el eje y solo es involucrado por la elevacion ( Logica Basica )

x = d * sin(a) * cos(e)
z = d * cos(a) * cos(e)

Entonces empesando a despejar

Como en ambas expresiones existen d y cos(e) puedo hacer un reemplazo de terminos asi:

Quitando a cos(e) para simplificar la cosa:

cos(e) = x / ( d*sin(a) )

En la segunda formula reemplazo (  z = d * cos(a) * cos(e) )

z = d * cos(a) * x / ( d*sin(a) )

Simplificando un poco queda:

z = cos(a) * x /  sin(a)

y tratando de despejar a el angulo a obtengo:

z/x = cos(a) / sin(a)    siendo lo mismo a:      z/x = cos(a) * csc(a)

por lo tanto:

cosec ( z/x ) = a * csc( a )
sin(cosec(z/x)) = a*a

por lo tanto

raiz( sin(cosec(z/x)) ) = a

pero al aplicar dicho despeje no me da el angulo ya mensionado. alguien sabe como solucionarlo?

Dulces Lunas!¡.
.