Friday, September 11, 2026

codigo python para crear solucion local en dotnet

Estoy probando que el sistema cree solo el codigo.

Final Code (generador_desde_ollama.py)

import os
import re
import ollama

# 1. Target local model configuration updated to 3b
MODELO_IA = "qwen2.5-coder:3b" 

PROMPT_SISTEMA = """
Eres un asistente experto que genera fragmentos exclusivos de código C# listo para usar.
"""

# Using raw string r"" to instantly bypass all Python SyntaxWarning escape sequence bugs
PROMPT_USUARIO = r"""
Necesito que crees un fragmento de código de un bucle 'for' en C# para .NET 10.
El bucle debe contar del 1 al 10.
Dentro del bucle debe hacer exactamente esto:
Console.WriteLine($"Número: {i}");
log.Info($"Número: {i}");

REGLA ESTRICTA: Devuelve ÚNICAMENTE el bloque de código C# del bucle for dentro de un bloque markdown ```csharp ... ```. No escribas introducciones, inicializaciones de log, ni saludos.
"""

print(f"🤖 Conectando a Ollama local usando el modelo: {MODELO_IA}...")

try:
    # 2. Call the Ollama local instance
    response = ollama.generate(
        model=MODELO_IA, 
        prompt=f"{PROMPT_SISTEMA}\n\n{PROMPT_USUARIO}"
    )
    respuesta_ia = response['response']
    
    # Calculate execution metrics
    tiempo_total = response.get('total_duration', 0) / 1e9 
    tokens_generados = response.get('eval_count', 0)
    velocidad_tokens = tokens_generados / tiempo_total if tiempo_total > 0 else 0

    # 3. Print the formatting metrics block
    print("\n" + "-"*60)
    print(f"⏱️  [Tiempo total de respuesta]: {tiempo_total:.2f} segundos")
    print(f"📊 [Velocidad de generación]: {velocidad_tokens:.2f} tokens por segundo")
    print("-"*60 + "\n")

    # 4. Extract the C# core loop block using regex
    match = re.search(r"```csharp(.*?)```", respuesta_ia, re.DOTALL)
    if match:
        codigo_bucle_csharp = match.group(1).strip()
    else:
        codigo_bucle_csharp = respuesta_ia.strip()

    # 5. Pack 'ReplyFromGoogle.py' with explicit folder management and compilation routines
    contenido_reply_script = f"""import os
import subprocess

print("🚀 [ReplyFromGoogle] Iniciando la automatización de la compilación...")

# Paso 1: Crear directorio de ejecución aislado
os.makedirs('./ProyectoDotNet', exist_ok=True)

# Paso 2: Cambiar directorio de contexto para .NET CLI
os.chdir('./ProyectoDotNet')

# Paso 3 y 4: Inicializar proyecto .NET y descargar versión segura mitigando vulnerabilidades NU1902
print("📦 Inicializando proyecto de consola .NET y descargando log4net 3.3.0...")
subprocess.run(['dotnet', 'new', 'console', '--force'], check=True, stdout=subprocess.DEVNULL)
subprocess.run(['dotnet', 'add', 'package', 'log4net', '--version', '3.3.0'], check=True, stdout=subprocess.DEVNULL)

# Paso 5: Escribir Program.cs estructurado con usings fijos al inicio para prevenir error CS1529
codigo_final_csharp = \"\"\"using System;
using System.IO;
using System.Reflection;
using log4net;
using log4net.Config;
using log4net.Appender;
using log4net.Layout;
using log4net.Repository.Hierarchy;

var hierarchy = (Hierarchy)LogManager.GetRepository(Assembly.GetEntryAssembly()!);
var layout = new PatternLayout("%date [%thread] %-5level - %message%newline");
layout.ActivateOptions();

var logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log.txt");
var appender = new FileAppender {{
    File = logPath,
    AppendToFile = true,
    Layout = layout
}};
appender.ActivateOptions();

hierarchy.Root.AddAppender(appender);
hierarchy.Root.Level = log4net.Core.Level.All;
BasicConfigurator.Configure(hierarchy);

ILog log = LogManager.GetLogger(typeof(Program));

// --- Código del Bucle Generado por la IA ---
{codigo_bucle_csharp}
// ------------------------------------------
\"\"\"

with open('Program.cs', 'w', encoding='utf-8') as f:
    f.write(codigo_final_csharp)

print("⚡ Compilando y ejecutando el programa .NET...")
resultado = subprocess.run(['dotnet', 'run'], capture_output=True, text=True)

print("\\n--- 🖥️ SALIDA DE LA CONSOLA .NET ---")
print(resultado.stdout)
if resultado.stderr:
    print(resultado.stderr)

# Paso 7: Leer y mostrar el archivo de log binario generado en la ruta interna
archivo_log = os.path.join("bin", "Debug", "net10.0", "log.txt")
if os.path.exists(archivo_log):
    print("\\n--- 📄 CONTENIDO DEL ARCHIVO LOG LOCAL (log.txt) ---")
    with open(archivo_log, "r") as f:
        print(f.read())
else:
    print("\\n❌ Error: El archivo de log no se generó en la ruta esperada.")
"""

    # 6. Save the structural recipe file locally
    archivo_salida = "ReplyFromGoogle.py"
    with open(archivo_salida, "w", encoding="utf-8") as f:
        f.write(contenido_reply_script)

    print(f"✨ ¡Éxito! Receta empaquetada de manera segura en: {archivo_salida}")
    print(f"Para iniciar la compilación completa de .NET, ejecuta: python3 {archivo_salida}")

except Exception as e:
    print(f"❌ Ocurrió un error en el proceso: {e}")


y para llamar

# 1. Download the 3B model inside your Ollama environment
ollama pull qwen2.5-coder:3b

# 2. Clear old run targets
rm -rf ./ProyectoDotNet
rm -f ReplyFromGoogle.py

# 3. Generate the script using the 3B model
python3 generador_desde_ollama.py

# 4. Fire the newly written recipe
python3 ReplyFromGoogle.py

quise inicialmente usar google, pero al crear la API Key iba a cobrar, por eso volvi al modelo local

esta termino siendo la salida.

🤖 Conectando a Ollama local usando el modelo: qwen2.5-coder:3b...

------------------------------------------------------------
⏱️  [Tiempo total de respuesta]: 9.03 segundos
📊 [Velocidad de generación]: 4.65 tokens por segundo
------------------------------------------------------------

✨ ¡Éxito! Receta empaquetada de manera segura en: ReplyFromGoogle.py
Para iniciar la compilación completa de .NET, ejecuta: python3 ReplyFromGoogle.py
🚀 [ReplyFromGoogle] Iniciando la automatización de la compilación...
📦 Inicializando proyecto de consola .NET y descargando log4net 3.3.0...
⚡ Compilando y ejecutando el programa .NET...

--- 🖥️ SALIDA DE LA CONSOLA .NET ---
Número: 1
133 [1] INFO Program (null) - Número: 1
Número: 2
160 [1] INFO Program (null) - Número: 2
Número: 3
160 [1] INFO Program (null) - Número: 3
Número: 4
160 [1] INFO Program (null) - Número: 4
Número: 5
160 [1] INFO Program (null) - Número: 5
Número: 6
160 [1] INFO Program (null) - Número: 6
Número: 7
160 [1] INFO Program (null) - Número: 7
Número: 8
160 [1] INFO Program (null) - Número: 8
Número: 9
160 [1] INFO Program (null) - Número: 9
Número: 10
160 [1] INFO Program (null) - Número: 10


--- 📄 CONTENIDO DEL ARCHIVO LOG LOCAL (log.txt) ---
2026-09-12 03:15:19,729 [1] INFO  - Número: 1
2026-09-12 03:15:19,757 [1] INFO  - Número: 2
2026-09-12 03:15:19,757 [1] INFO  - Número: 3
2026-09-12 03:15:19,757 [1] INFO  - Número: 4
2026-09-12 03:15:19,757 [1] INFO  - Número: 5
2026-09-12 03:15:19,757 [1] INFO  - Número: 6
2026-09-12 03:15:19,757 [1] INFO  - Número: 7
2026-09-12 03:15:19,757 [1] INFO  - Número: 8
2026-09-12 03:15:19,757 [1] INFO  - Número: 9
2026-09-12 03:15:19,757 [1] INFO  - Número: 10


dot net 10 dotnet 10 bookworm

 

curl -sSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin --channel LTS


export DOTNET_ROOT=$HOME/.dotnet

export PATH=$PATH:$HOME/.dotnet


Ollama Raspberry

curl -fsSL https://ollama.com/install.sh | sh

 

sudo systemctl edit ollama.service

#para red

[Service]

Environment="OLLAMA_HOST=0.0.0.0:11434"

#Environment="OLLAMA_KEEP_ALIVE=24h"

Environment="OLLAMA_NUM_PARALLEL=1”

Environment="OLLAMA_MAX_LOADED_MODELS=1”

Environment="OLLAMA_KEEP_ALIVE=5m”

sudo systemctl daemon-reload

sudo systemctl restart ollama

 

ollama run gemma4:e2b

 

Configurar la memoria Swap en la Raspberry Pi

Para evitar que el sistema cierre Ollama por falta de memoria (errores Out-Of-Memory), aumenta el archivo de intercambio (Swap):

Abre el archivo de configuración: sudo nano /etc/dphys-swapfile

Cambia CONF_SWAPSIZE=100 por CONF_SWAPSIZE=2048 (o 4096 si tienes espacio en la MicroSD/SSD).

Reinicia el servicio de swap:

bash

sudo /etc/init.d/dphys-swapfile stop

sudo /etc/init.d/dphys-swapfile start



 

 

 

 

 

 

API

curl http:// localhost:11434/api/generate -d '{

  "model": " qwen2.5-coder:3b ",

  "prompt": "¿Cómo se creo roma en 5 lineas?",

  "stream": false

}'

qwen2.5-coder:3b

para bajar

ollama run gemma4:e2b --keepalive 0s

 

 

sudo nano prueba.py

 

import requests

import json

 

url = "http://localhost:11434/api/generate"

payload = {

    "model": " qwen2.5-coder:3b",

    "prompt": "Escribe un saludo corto.",

    "stream": False

}

 

response = requests.post(url, json=payload)

 

if response.status_code == 200:

    resultado = response.json()

    print("Respuesta:", resultado.get("response"))

else:

    print("Error:", response.status_code)

 

 

 

Tuesday, September 8, 2026

Definir plan de energia en ubuntu server 26.04 y velocidad del procesador

 


echo "2600000" | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_max_freq

sudo cpufreq-set -r -g performance

echo "1" | sudo tee /sys/devices/system/cpu/cpufreq/boost

Sunday, September 6, 2026

Mejorar el consumo innecesario de RAM en windows 11

 

disable prefect

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management\PrefetchParameters


servicios 

bajar

sysadmin

Thursday, August 20, 2026

Activar WOL en ubuntu 24 lts

 Pasos para activar WoL por consola

1. Identificar tu interfaz de red
Ejecuta el siguiente comando para ver el nombre de tu tarjeta de red (por ejemplo, enp3s0 o eth0): [1]
  • ip link
2. Instalar y comprobar el estado actual
Instala la herramienta de red si no la tienes: [1, 2]
  • sudo apt update && sudo apt install ethtool
Revisa si tu tarjeta soporta WoL y su estado actual (busca la línea Wake-on:):
  • sudo ethtool <tu-interfaz> (cambia <tu-interfaz> por el nombre obtenido antes, ej. enp3s0)
  • Si aparece Wake-on: g, ya está activo. Si aparece d, debes activarlo. [1, 2]
3. Activar WoL de forma temporal
Activa el encendido por paquete mágico ejecutando: [1]
  • sudo ethtool -s <tu-interfaz> wol g [1]
4. Hacer la configuración permanente con Systemd
Crea un archivo de servicio para que Ubuntu aplique el cambio en cada arranque: [1, 2]
  • sudo nano /etc/systemd/system/wol.service
Pega el siguiente contenido (reemplaza enp3s0 por el nombre real de tu interfaz): [1]
ini
[Unit]
Description=Activar Wake-on-LAN
After=network.target

[Service]
Type=oneshot
ExecStart=/usr/sbin/ethtool -s enp3s0 wol g

[Install]
WantedBy=multi-user.target
Use code with caution.
Guarda el archivo (en nano presiona Ctrl + O, luego Enter, y sal con Ctrl + X). Finalmente, habilita e inicia el servicio: [1, 2, 3]
  • sudo systemctl daemon-reload
  • sudo systemctl enable wol.service
  • sudo systemctl start wol.service [1]

Friday, July 10, 2026

winget de instalacion de programas

 winget install --id Notepad++.Notepad++ -e

winget install -e --id Microsoft.VisualStudioCode

winget install Microsoft.VisualStudio.2022.Community

winget install -e --id Microsoft.SQLServerManagementStudio.22

winget install -e --id 7zip.7zip

winget install --id=SmartBear.SoapUI -e

winget install Postman.Postman

winget install -e --id Mozilla.Firefox

winget install -e --id KaiKramer.KeyStoreExplorer

winget install -e --id OBSProject.OBSStudio

winget install -e --id PuTTY.PuTTY

winget install -e --id VideoLAN.VLC

winget install -e --id WinMerge.WinMerge

winget install -e --id TeamViewer.TeamViewer

winget install -e --id Google.Chrome

winget install -e --id Mozilla.Firefox

winget install -e --id Valve.Steam

winget install -e --id Discord.Discord



winget uninstall "Microsoft Noticias"

winget uninstall "Enlace Móvil"

winget uninstall "Xbox TCUI"

winget uninstall "Xbox Identity Provider"

winget uninstall "Outlook for Windows"

winget uninstall xbox

winget uninstall "Microsoft To Do"

winget uninstall "Microsoft 365 Copilot"

winget uninstall "MSN El tiempo"

winget uninstall "Microsoft Bing"


En el caso de que aparezca el error 

Failed when searching source: msstore

An unexpected error occurred while executing the command:

0x8a15005e : The server certificate did not match any of the expected values.


winget settings --enable BypassCertificatePinningForMicrosoftStore


Monday, June 29, 2026

Re instalar adding microsoft Teams en outlook

 https://learn.microsoft.com/en-us/answers/questions/5514779/how-to-reinstall-microsoft-teams-add-in-for-outloo


%SystemRoot%\System32\regsvr32.exe /n /i:user "C:\Users\xxxx\AppData\Local\Microsoft\TeamsMeetingAdd-in\1.26.11802\x64\\Microsoft.Teams.AddinLoader.dll"

Sunday, June 14, 2026

bloquear navegadores via web config HTTP_USER_AGENT

Posterior a ataques via navegador tor o curl llegué a esta configuracion bien util que soporta chrome y edge , todo el resto lo bloquea.

 <system.webServer>
    <rewrite>
          <rules>
          <rule name="Bloquear navegadores no permitidos" stopProcessing="true">
            <match url=".*" />
            <conditions>
              <!-- El signo de exclamación (!) invierte la lógica: bloquea si NO coincide con la expresión regular -->
                <!-- 1. Exclude Chrome -->
                <add input="{HTTP_USER_AGENT}" pattern=".*Chrome.*" negate="true" />
                <!-- 2. Exclude Firefox -->
                <add input="{HTTP_USER_AGENT}" pattern=".*Edge.*" negate="true" />
            </conditions>
            <action type="CustomResponse" statusCode="403" statusReason="Navegador no soportado" statusDescription="Tu navegador no está permitido para acceder a este sitio." />
          </rule>
          </rules>
    </rewrite>


Cambiar resolucion de la pantalla del celular via ADB Samsung Galaxy S8

 Instalé Revolution X y solo aparece en la maxima resolucion, por ende anda mas lento y consume mas recursos.


si lo dejo con la resolucion menor anda mas fluido


adb shell wm size 720x1480 que es la resolucion HD

adb shell wm density 280 

Friday, May 1, 2026

Levantar AI en raspberry Ollama

 # Instalar Ollama

curl -fsSL https://ollama.com/install.sh | sh

# Verificar instalacion

ollama --version

# Iniciar el servicio

sudo systemctl enable ollama

sudo systemctl start ollama

 

https://gemma4-ai.com/es/blog/gemma4-raspberry-pi 

sudo apt install docker.io

https://projects.raspberrypi.org/en/projects/llm-rpi/3

esto ultimo para poder ver ollama web.

sudo docker run -d -p 192.168.1.xxx:3000:8080 -v ollama:/root/.ollama -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:ollama


Friday, March 27, 2026

Para evitar que Linux hiberne o se suspenda al cerrar la tapa mediante consola

 # 1. Editar el archivo de configuración

sudo nano /etc/systemd/logind.conf

# 2. Buscar y modificar/descomentar (quitar el #) la línea:
HandleLidSwitch=ignore

# 3. Guardar y salir (Ctrl+O, Enter, Ctrl+X)

# 4. Reiniciar el servicio para aplicar cambios
sudo systemctl restart systemd-logind

Friday, March 13, 2026

PowerShell para organizar archivos por año mes y dia

 $origen = "D:\DeleteMe"

Get-ChildItem $origen -File | ForEach-Object {

    # Obtener fecha de modificación en formato YYYYMMDD

    $fecha = $_.LastWriteTime.ToString("yyyyMMdd")

    # Crear carpeta destino

    $carpetaDestino = Join-Path $origen $fecha

    if (!(Test-Path $carpetaDestino)) {

        New-Item -ItemType Directory -Path $carpetaDestino | Out-Null

    }

    # Mover archivo

    Move-Item $_.FullName $carpetaDestino

}

Wednesday, October 29, 2025

Espacio disponible en Sharepoint

 https://admin.cloud.microsoft/?#/reportsUsage/SharePointStorage




Friday, August 8, 2025

lets encrypt para nginx

 https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-20-04-es


sudo apt install certbot python3-certbot-nginx

sudo nano /etc/nginx/sites-available/example.com

...

server_name example.com www.example.com;

...

sudo certbot certonly --webroot -w /var/www/html/ -d tuSitio.ddns.net

#para validar configuracion 
sudo nginx -t

#para recargar la nueva configuracion
sudo systemctl reload nginx


#para validar la actualizacion
sudo systemctl status certbot.timer

#para actualizar
sudo certbot renew --dry-run


#basado en 
https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-20-04-es

Friday, May 2, 2025

Msg 15138, Level 16, State 1, Line 7 The database principal owns a schema in the database, and cannot be dropped.

 Msg 15138, Level 16, State 1, Line 7 The database principal owns a schema in the database, and cannot be dropped.



SELECT SCHEMA_NAME, 

    SCHEMA_OWNER

FROM INFORMATION_SCHEMA.schemata

WHERE SCHEMA_OWNER = 'USERNAME';

--mi arreglo--

alter authorization on schema::db_ddladmin TO dbo;

alter authorization on schema::db_owner TO dbo;


posterior a eso puedo borrar y crear el usuario con problema

Friday, April 25, 2025

obtener ip publica desde power shell

 Invoke-RestMethod -Uri "https://ipinfo.io/ip"



telnet por powershell

 Telnet de Power Shell:


debe ser con acceso de admin

Test-NetConnection -ComputerName 193.127.xxx.xxx -port 22

Thursday, April 24, 2025

Generar PFX desde un certificado auto generado

 

openssl pkcs12 -export -in certificate.crt -inkey privatekey.key -certfile ca-bundle.crt -out output.pfx


al querer cargar en windows 2016 arroja error.

con este otro comando permite instalar

openssl pkcs12 -export -certpbe PBE-SHA1-3DES -keypbe PBE-SHA1-3DES -nomac -inkey tetra.key -in tetra.crt -out tetra.pfx

Thursday, March 27, 2025

Convertir PPK a p12 - how to export to p12 from PPK

Basado en 

Steps to import Private Key (PPK) in SAP PI/PO for... - SAP Community

se debe de instalar

C:\cygwin64\bin>openssl

openssl.exe req -new -x509 -days 3650 -key PrivatePEM.pem -out x509_Private.pem


despues

openssl.exe pkcs12 -export -in x509_Private.pem -inkey PrivatePEM.pem -out PrivateP12.p12

Enter pass phrase for PrivatePEM.pem:

Enter Export Password:

Verifying - Enter Export Password: