Code faster with the help of AI

Generate code just by typing a text description. AI will create the code for you. Test it now

Questions about programming?Chat with your personal AI assistant

How others used it recently

Generated by the communtiy

code to explanationFri, 06 Jan 2023

if(dw_hourmeter_value >= HOUR_METER_MAX) /*if hour meter cross the maximum value, so roll-over hour meter value and trip meter shold rese...

the if statement checks the value of dw_hour_meter_value and if the value is greater or equal to the HOUR_METER_MAX then the value of dw_hour_meter_value is set to 0, the gsw_hour_meter_count is set to 0, the fnby_WritePort function is used to write 0 to the AMIL, the fnv_TripA_reset function and the fnv_TripB_reset function are called to reset the trip a and trip b variables.

Guest
generate functionThu, 29 Jun 2023

Realice una función int sumoveravg(int valores[ ], int n) que recibe como parámetro un arreglo de n elementos enteros y retorne la suma de los elementos que están por encima del promedio. Se conoce la función float avg(int nums[ ], int n), que retorna el promedio de los n números en 'nums'.

#include <stdio.h> float avg(int nums[ ], int n) { int i, sum = 0; for(i = 0; i < n; i++) { sum += nums[i]; } return ((float)sum)/n; } int main() { int nums[] = {1, 2, 3, 4, 5}; printf("%f", avg(nums, 5)); }

C
Guest
generate functionMon, 08 May 2023

Write a C program to implement Caesar cipher encryption-decryption

#include <stdio.h> int main() { char message[100], ch; int i, key; printf("Enter a message to encrypt: "); gets(message); printf("Enter key: "); scanf("%d", &key); for(i = 0; message[i] != '\0'; ++i){ ch = message[i]; if(ch >= 'a' && ch <= 'z'){ ch = ch + key; if(ch > 'z'){ ch = ch - 'z' + 'a' - 1; } message[i] = ch; } else if(ch >= 'A' && ch <= 'Z'){ ch = ch + key; if(ch > 'Z'){ ch = ch - 'Z' + 'A' - 1; } message[i] = ch; } } printf("Encrypted message: %s", message); return 0

C
Guest
generate functionFri, 16 Jun 2023

construya un programa en c que al recibir como datos N números enteros, obtenga la suma de los números pares y calcule el promedio de los impares

#include <stdio.h> int main(int argc, char const *argv[]) { int n; scanf("%d", &n); int numbers[n]; for (int i = 0; i < n; i++) { int number; scanf("%d", &number); numbers[i] = number; } int sumOfEvens = 0; int sumOfOdds = 0; for (int i = 0; i < n; i++) { int number = numbers[i]; if (number % 2 == 0) { sumOfEvens += number; } else { sumOfOdds += number; } } printf("%d\n", sumOfEvens); if (sumOfOdds == 0) { printf("No hay números impares"); } else { printf("%.2

C
Guest
generate functionWed, 26 Jul 2023

Haz un mapa de Argentina

import matplotlib.pyplot as plt import cartopy.crs as ccrs plt.axes(projection=ccrs.PlateCarree()) plt.contourf(lon, lat, temp_data[0, :, :], 60, transform = ccrs.PlateCarree()) plt.colorbar(orientation='horizontal', shrink = 0.8) plt.show()

Python
Guest
generate functionSat, 22 Apr 2023

create a function that takes key and plain text as inputs and outputs a cipher text using hill cipher algorithm

public string hillCipher(string key, string plainText) { string cipherText = ""; int[] keyInt = key.Select(c => (int)c).ToArray(); int[] plainTextInt = plainText.Select(c => (int)c).ToArray(); int[,] keyMatrix = new int[2, 2]; int[,] plainTextMatrix = new int[2, 1]; keyMatrix[0, 0] = keyInt[0] - 65; keyMatrix[0, 1] = keyInt[1] - 65; keyMatrix[1, 0] = keyInt[2] - 65; keyMatrix[1, 1] = keyInt[3] - 65; plainTextMatrix[0, 0] = plainTextInt[0] - 65; plainTextMatrix[1, 0] = plainTextInt[1] - 65; int[,] cipherTextMatrix = new int[2, 1]; cipherTextMatrix[0, 0] = (keyMatrix[0,

C#
Guest
generate functionMon, 27 Mar 2023

1 2

def add(a, b): print(a) print(b) return a + b add(1, 2)

Python
Guest
generate functionSat, 03 Dec 2022

void型の関数 histgram2() は、4つの引数をもち、順に [0,100] の範囲の値を要素にもつint型の配列変数 a[]、配列 a[] のサイズを表すint型の値 n、および、ヒストグラムの値を代入するためのint型の配列変数 h[]、ヒストグラムの区間の幅を表す int型の値 m である。 histgram2() は、与えられた配列変数 a[] の要素の値が、[0,m-1], [m...

void histgram2(int a[], int n, int h[], int m) { int i, j, k; i = 0; j = 0; k = 0; while (i < n) { if (m * k <= a[i] && a[i] < m * (k + 1)) { h[k]++; } else { k++; h[k]++; } i++; } }

C
Guest
testsSat, 22 Apr 2023

Crear un código de una calculadora

import unittest class TestCadena(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') def test_isupper(self): self.assertTrue('FOO'.isupper()) self.assertFalse('Foo'.isupper()) def test_split(self): s = 'hello world' self.assertEqual(s.split(), ['hello', 'world']) # check that s.split fails when the separator is not a string with self.assertRaises(TypeError): s.split(2) if __name__ == '__main__': unittest.main()

Guest
generate functionSat, 22 Apr 2023

create a function that takes key and plain text as inputs and outputs a cipher text using hill cipher algorithm

public string hillCipher(string key, string plainText) { string cipherText = ""; int[] keyInt = key.Select(c => (int)c).ToArray(); int[] plainTextInt = plainText.Select(c => (int)c).ToArray(); int[,] keyMatrix = new int[2, 2]; int[,] plainTextMatrix = new int[2, 1]; keyMatrix[0, 0] = keyInt[0] - 65; keyMatrix[0, 1] = keyInt[1] - 65; keyMatrix[1, 0] = keyInt[2] - 65; keyMatrix[1, 1] = keyInt[3] - 65; plainTextMatrix[0, 0] = plainTextInt[0] - 65; plainTextMatrix[1, 0] = plainTextInt[1] - 65; int[,] cipherTextMatrix = new int[2, 1]; cipherTextMatrix[0, 0] = (keyMatrix[0,

C#
Guest
generate functionFri, 05 May 2023

Create a Google Chrome extension that, upon activation, opens a new tab in the browser with its graphical interface. The interface should have the necessary options and filters to search for a keyword...

# -*- coding: utf-8 -*- # Copyright (c) 2019, DigiThinkIT and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class ProductDetector(Document): pass

Python
Guest
generate functionSat, 14 Dec 2024

una interfaz en donde muestre la tabla que sean productos vencidos de la tabla inventario con el nombre de la sucursal

Para crear una interfaz gráfica en Python que muestre la tabla de productos vencidos de la tabla inventario, podemos utilizar la biblioteca `tkinter` para crear la interfaz y `sqlite3` para interactuar con la base de datos. A continuación, te muestro un ejemplo de cómo podrías hacerlo: ```python import tkinter as tk from tkinter import ttk import sqlite3 # Conectar a la base de datos conn = sqlite3.connect('inventario.db') cursor = conn.cursor() # Crear la tabla inventario si no existe cursor.execute(''' CREATE TABLE IF NOT EXISTS inventario ( id INTEGER PRIMARY KEY, nombre_producto TEXT, fecha_vencimiento DATE, cantidad INTEGER, sucursal TEXT ) ''') # Función para obtener los productos vencidos def obtener_productos_vencidos(): cursor.execute(''' SELECT * FROM inventario WHERE fecha_vencimiento < DATE('now') ''') productos_vencidos = cursor.fetchall() return productos_vencidos # Función para crear la tabla en la interfaz def crear_tabla(): for widget in tabla_frame.winfo_children(): widget.destroy() productos_vencidos = obtener_productos_vencidos() if productos_vencidos: columnas = ['ID', 'Nombre Producto', 'Fecha Vencimiento', 'Cantidad', 'Sucursal'] tree = ttk.Treeview(tabla_frame, columns=columnas, show='headings') for columna in columnas: tree.heading(columna, text=columna) for producto in productos_vencidos: tree.insert('', 'end', values=producto) tree.pack(fill='both', expand=True) else: label = ttk.Label(tabla_frame, text='No hay productos vencidos') label.pack(fill='both', expand=True) # Crear la interfaz root = tk.Tk() root.title('Productos Vencidos') tabla_frame = ttk.Frame(root) tabla_frame.pack(fill='both', expand=True) boton = ttk.Button(root, text='Actualizar tabla', command=crear_tabla) boton.pack(fill='x') crear_tabla() root.mainloop() # Cerrar la conexión a la base de datos conn.close() ``` En este ejemplo, creamos una interfaz con un botón que, cuando se presiona, actualiza la tabla con los productos vencidos de la base de datos. La tabla se muestra en un frame dentro de la interfaz principal. Recuerda que debes crear una base de datos llamada `inventario.db` en el mismo directorio que el script, y que la tabla `inventario` debe tener las columnas `id`, `nombre_producto`, `fecha_vencimiento`, `cantidad` y `sucursal`.

Python
Guest
generate functionTue, 21 Mar 2023

Add to this the code for generating a grid on the chart, as well as specifying the percentage difference directly on the chart bars plt.figure(figsize = (12, 4)) plt.bar(data.index, data['nutri'], co...

plt.figure(figsize = (12, 4)) plt.bar(data.index, data['nutri'], color = 'darkblue', label = 'nutri') plt.bar(data.index, data['mineral'], color = 'brown', label = 'mineral') plt.title('Comparison of Nutrient and Mineral Content') plt.xlabel('Nutrient|Mineral') plt.ylabel('Amount') plt.legend() plt.show()

Python
View User
generate functionTue, 25 Apr 2023

El Banco Gerencial de Desarrollo BGD, quiere determinar cuánto pagará un cliente que tome un préstamo no mayor de 200,000.00 para pagarlo en 24 meses a una Tasa de Interés de 2% mensual. Se requiere saber el valor o monto total que pagará el cliente en 2 años entre capital e intereses.

def main() principal = 200000 monthly_interest_rate = 0.02 number_of_payments = 24 payment = principal * ((monthly_interest_rate * (1 + monthly_interest_rate)**number_of_payments) / ((1 + monthly_interest_rate)**number_of_payments - 1)) return payment

C#
Guest
generate functionSat, 06 May 2023

Login con conexión a MySQL con contraseña encriptada

import mysql.connector import hashlib import sys def login(username, password): """ """ # Create connection mydb = mysql.connector.connect( host="localhost", user="user", passwd="pass", database="mydatabase" ) # Create cursor to execute queries cursor = mydb.cursor() # Create query and execute query = f"SELECT * FROM login WHERE username = '{username}'" cursor.execute(query) # Fetch all results result = cursor.fetchall() # Check if query was successful if result == []: print("Invalid username and/or password") return # Check if user exists if len(result) != 1: print("ERROR: More than one user exists") return # Check if password is correct # Load password from database db_password = result[0][1] # Encrypt password

Python
Guest
generate functionTue, 28 Mar 2023

Menu de 3 opciones una opcion recopilar datos personales y guardarlos en una base de datos la segunda opción que recopile notas de 3 cursos y tercera opción que recopile ausencias y tardías

def menu(): print("1. datos personales") print("2. Notas de cursos") print("3. Ausencias y Tardías") print("4. Salir") opcion = int(input("Ingrese una opción >> ")) if opcion == 1: datos_personales() elif opcion == 2: notas() elif opcion == 3: ausencias() elif opcion == 4: exit() else: print("Opción incorrecta") def datos_personales(): print("Ingrese sus datos") nombre = input("Nombre >> ") apellido = input("Apellido >> ") edad = input("Edad >> ") sexo = input("Sexo >> ") print("") print("Datos Ingresados") print("Nombre: "

Python
Guest
translateThu, 23 Mar 2023

Pedir por teclado el tamaño de un arreglo de números y pedir los valores numéricos con los que se rellena. Los valores no se pueden repetir. Mostrar el arreglo con los valores al final.

#include <stdio.h> int main(int argc, char const *argv[]) { int n; printf("Ingrese tamaño del arreglo: \n"); scanf("%d", &n); int numbers[n]; for (int i = 0; i < n; i++) { printf("Ingrese un numero: \n"); scanf("%d", &numbers[i]); } for (int i = 0; i < n; i++) { printf("El numero %d es: %d \n", i, numbers[i]); } return 0; }

C
Guest
generate functionFri, 28 Jul 2023

Hola

fun hola(name: String) { println("Hola $name") } hola("Miguel")

Kotlin
Guest
generate functionFri, 21 Apr 2023

suma de matrices con vectores

import numpy as np def add_matrix_and_vector(x, y): return x + y matrix = np.array([[1, 2], [3, 4]]) vector = np.array([6, 7]) add_matrix_and_vector(matrix, vector)

Python
Guest
generate functionSat, 03 Dec 2022

void型の関数 histgram2() は、4つの引数をもち、順に [0,100] の範囲の値を要素にもつint型の配列変数 a[]、配列 a[] のサイズを表すint型の値 n、および、ヒストグラムの値を代入するためのint型の配列変数 h[]、ヒストグラムの区間の幅を表す int型の値 m である。 histgram2() は、与えられた配列変数 a[] の要素の値が、[0,m-1], [m...

void histgram2(int a[], int n, int h[], int m) { int i, j, k; i = 0; j = 0; k = 0; while (i < n) { if (m * k <= a[i] && a[i] < m * (k + 1)) { h[k]++; } else { k++; h[k]++; } i++; } }

C
Guest
generate functionWed, 20 Nov 2024

function that adds 1 to a counter when the method is called

Here's a simple example of a class in Java that has a method to increment a counter: ```java public class Counter { private int count; public Counter() { this.count = 0; } public void increment() { this.count++; } public int getCount() { return this.count; } public static void main(String[] args) { Counter counter = new Counter(); System.out.println("Initial count: " + counter.getCount()); counter.increment(); System.out.println("Count after increment: " + counter.getCount()); counter.increment(); System.out.println("Count after second increment: " + counter.getCount()); } } ``` In this example, the `Counter` class has a private integer field `count` to store the current count. The `increment` method increments the count by 1. The `getCount` method returns the current count. When you run this code, it will output: ``` Initial count: 0 Count after increment: 1 Count after second increment: 2 ``` This demonstrates that the `increment` method is working correctly and incrementing the counter each time it's called.

Java
Guest
generate functionSat, 22 Apr 2023

create a function that takes key and plain text as inputs and outputs a cipher text using hill cipher algorithm

public string hillCipher(string key, string plainText) { string cipherText = ""; int[] keyInt = key.Select(c => (int)c).ToArray(); int[] plainTextInt = plainText.Select(c => (int)c).ToArray(); int[,] keyMatrix = new int[2, 2]; int[,] plainTextMatrix = new int[2, 1]; keyMatrix[0, 0] = keyInt[0] - 65; keyMatrix[0, 1] = keyInt[1] - 65; keyMatrix[1, 0] = keyInt[2] - 65; keyMatrix[1, 1] = keyInt[3] - 65; plainTextMatrix[0, 0] = plainTextInt[0] - 65; plainTextMatrix[1, 0] = plainTextInt[1] - 65; int[,] cipherTextMatrix = new int[2, 1]; cipherTextMatrix[0, 0] = (keyMatrix[0,

C#
Guest
text to sql syntaxWed, 22 Mar 2023

Crear dos tablas con constraints

1: Create table clientes ( id int not null primary key, name varchar(255) not null, email varchar(255) not null, password varchar(255) not null) 2: Create table admin ( id int not null primary key, name varchar(255) not null, email varchar(255) not null, password varchar(255) not null)

Guest
generate functionSun, 30 Apr 2023

Implementar una Calculadora de Números Enteros, mediante un proyecto de consola en C++, cuyo algoritmo permita: 1. Mostrar un menú de 6 opciones: • 1. Sumar dos números. • 2. Restar dos números. • 3. ...

#include <iostream> using namespace std; int menu(){ int option; cout << "1. Sumar dos numeros.\n"; cout << "2. Restar dos numeros.\n"; cout << "3. Multiplicar dos numeros.\n"; cout << "4. Dividir dos numeros.\n"; cout << "5. Número Primo?.\n"; cout << "6. Salir.\n"; cout << "Ingrese opción: "; cin >> option; return option; } int suma(int a, int b){ return a+b; } int resta(int a, int b){ return a-b; } int multiplicacion(int a, int b){ return a*b; } int division(int a, int b){ if (b == 0){ return 0; } return a/b; }

C++
Guest
generate functionWed, 02 Aug 2023

I want to make a panel with a text box and a button to execute and another to delete and another to copy from the clipboard

# public static Panel CreatePanel() { var panel = new Panel(); var textBox = new TextBox(); textBox.Location = new Point(10, 10); textBox.Size = new Size(200, 50); panel.Controls.Add(textBox); var button = new Button(); button.Location = new Point(10, 70); button.Size = new Size(200, 50); button.Text = "Execute"; panel.Controls.Add(button); return panel; } private void button1_Click(object sender, EventArgs e) { var panel = CreatePanel(); Controls.Add(panel); }

C
Guest
generate functionMon, 13 Jan 2025

Elaborar un programa que permita calcular el área de un rombo, se debe ingresar como datos la longitud de la diagonal mayor y la diagonal menor

Aquí te presento un programa en C++ que calcula el área de un rombo a partir de la longitud de sus diagonales. ```cpp #include <iostream> #include <cmath> // Función para calcular el área de un rombo double calcularAreaRombo(double diagonalMayor, double diagonalMenor) { // Verificar si las diagonales son iguales (rombo equilátero) if (diagonalMayor == diagonalMenor) { // En este caso, el área es la mitad del producto de las diagonales return (diagonalMayor * diagonalMenor) / 2; } else { // En este caso, el área es la mitad del producto de las diagonales return (diagonalMayor * diagonalMenor) / 2; } } int main() { double diagonalMayor, diagonalMenor; // Pedir la longitud de la diagonal mayor std::cout << "Ingrese la longitud de la diagonal mayor: "; std::cin >> diagonalMayor; // Pedir la longitud de la diagonal menor std::cout << "Ingrese la longitud de la diagonal menor: "; std::cin >> diagonalMenor; // Calcular el área del rombo double areaRombo = calcularAreaRombo(diagonalMayor, diagonalMenor); // Mostrar el resultado std::cout << "El área del rombo es: " << areaRombo << std::endl; return 0; } ``` Este programa utiliza una función llamada `calcularAreaRombo` que recibe como parámetros las longitudes de las diagonales mayor y menor del rombo. La función calcula el área del rombo utilizando la fórmula: Área = (diagonalMayor \* diagonalMenor) / 2 Si las diagonales son iguales, el rombo es equilátero y el área se calcula de la misma manera. En el `main`, se pide al usuario que ingrese las longitudes de las diagonales mayor y menor, se calcula el área del rombo utilizando la función `calcularAreaRombo` y se muestra el resultado. Recuerda que este programa asume que las diagonales son positivas y no nulas. Si se ingresa un valor negativo o cero, el programa puede producir resultados incorrectos.

C++
Guest
generate functionSat, 14 Dec 2024

una interfaz en donde muestre la tabla que sean productos vencidos de la tabla inventario con el nombre de la sucursal

Para crear una interfaz gráfica en Python que muestre la tabla de productos vencidos de la tabla inventario, podemos utilizar la biblioteca `tkinter` para crear la interfaz y `sqlite3` para interactuar con la base de datos. A continuación, te muestro un ejemplo de cómo podrías hacerlo: ```python import tkinter as tk from tkinter import ttk import sqlite3 # Conectar a la base de datos conn = sqlite3.connect('inventario.db') cursor = conn.cursor() # Crear la tabla inventario si no existe cursor.execute(''' CREATE TABLE IF NOT EXISTS inventario ( id INTEGER PRIMARY KEY, nombre_producto TEXT, fecha_vencimiento DATE, cantidad INTEGER, sucursal TEXT ) ''') # Función para obtener los productos vencidos def obtener_productos_vencidos(): cursor.execute(''' SELECT * FROM inventario WHERE fecha_vencimiento < DATE('now') ''') productos_vencidos = cursor.fetchall() return productos_vencidos # Función para crear la tabla en la interfaz def crear_tabla(): for widget in tabla_frame.winfo_children(): widget.destroy() productos_vencidos = obtener_productos_vencidos() if productos_vencidos: columnas = ['ID', 'Nombre Producto', 'Fecha Vencimiento', 'Cantidad', 'Sucursal'] tree = ttk.Treeview(tabla_frame, columns=columnas, show='headings') for columna in columnas: tree.heading(columna, text=columna) for producto in productos_vencidos: tree.insert('', 'end', values=producto) tree.pack(fill='both', expand=True) else: label = ttk.Label(tabla_frame, text='No hay productos vencidos') label.pack(fill='both', expand=True) # Crear la interfaz root = tk.Tk() root.title('Productos Vencidos') tabla_frame = ttk.Frame(root) tabla_frame.pack(fill='both', expand=True) boton = ttk.Button(root, text='Actualizar tabla', command=crear_tabla) boton.pack(fill='x') crear_tabla() root.mainloop() # Cerrar la conexión a la base de datos conn.close() ``` En este ejemplo, creamos una interfaz con un botón que, cuando se presiona, actualiza la tabla con los productos vencidos de la base de datos. La tabla se muestra en un frame dentro de la interfaz principal. Recuerda que debes crear una base de datos llamada `inventario.db` en el mismo directorio que el script, y que la tabla `inventario` debe tener las columnas `id`, `nombre_producto`, `fecha_vencimiento`, `cantidad` y `sucursal`.

Python
Guest
generate functionTue, 23 Apr 2024

Pide al usuario que ingrese el número de lados de un poligono. Utiliza un bucle while para solicitar los valores de los ángulos internos del poligono hasta que se ingresen todos. Calcula y muestra la suma de los ángulos internos.

nclude <iostream> #include <cmath> #include <cstdlib> #include <ctime> #include <algorithm> #include <iterator> #include <vector> #include <map> #include <set> #include <queue> #include <stack> #include <bitset> #include <string> #include <sstream> #include <complex> #include <limits> #include <cctype

C++
Guest
generate functionSat, 03 Dec 2022

void型の関数 histgram2() は、4つの引数をもち、順に [0,100] の範囲の値を要素にもつint型の配列変数 a[]、配列 a[] のサイズを表すint型の値 n、および、ヒストグラムの値を代入するためのint型の配列変数 h[]、ヒストグラムの区間の幅を表す int型の値 m である。 histgram2() は、与えられた配列変数 a[] の要素の値が、[0,m-1], [m...

void histgram2(int a[], int n, int h[], int m) { int i, j, k; i = 0; j = 0; k = 0; while (i < n) { if (m * k <= a[i] && a[i] < m * (k + 1)) { h[k]++; } else { k++; h[k]++; } i++; } }

C
Guest
ContactPrivacy Policysoluraweb.com