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

Want to kickstart your project?Use the new AI Studio to create your code

How others used it recently

Generated by the communtiy

generate functionSat, 25 Mar 2023

Si en cualquier momento S1 es HIGH entonces salida1 y salida2 serán LOW (Activar salida1 y esperar 5 segundos si entrada1 es HIGH Activar salida2 y esperar 5 segundos si entrada2 es HIGH)

++ bool S1 = 0; bool S2 = 0; bool S3 = 0; bool S4 = 0; bool S5 = 0; bool S6 = 0; bool S7 = 0; bool S8 = 0; bool S9 = 0; bool S10 = 0; bool S11 = 0; bool S12 = 0; bool S13 = 0; bool S14 = 0; bool S15 = 0; bool S16 = 0; void setup() { pinMode(S1, OUTPUT); pinMode(S2, OUTPUT); pinMode(S3, OUTPUT); pinMode(S4, OUTPUT); pinMode(S5, OUTPUT); pinMode(S6, OUTPUT); pinMode(S7, OUTPUT); pinMode(S8, OUTPUT); pinMode(S9, OUTPUT); pinMode(S10, OUTPUT); pinMode(S11, OUTPUT); pinMode(S12

C
Guest
generate functionSun, 04 Dec 2022

How to access WithdrawChecking() in LoginForm inside MainTransactionForm

//in MainTransactionForm.Xaml.cs public partial class MainTransactionForm : Form { public MainTransactionForm() { InitializeComponent(); } private void withdrawButton_Click(object sender, EventArgs e) { LoginForm loginForm = new LoginForm(); loginForm.WithdrawChecking(); } } //in LoginForm.Xaml.cs class LoginForm { public void WithdrawChecking() { if(true) { MessageBox.Show("withdraw checking"); } } }

C#
Guest
generate functionThu, 01 Jun 2023

(Lista simplemente enlazada) Se pide a Ud. realizar un aplicativo en java correspondiente a una lista simplemente enlazada, la cual ejecute las siguientes instrucciones: • Insertar al inicio de la lis...

// TODO code application logic here package Lista_Simplemente_Enlazadas; import java.util.Scanner; /** * * @author Juan Camilo */ public class Lista_Simplemente_Enlazadas { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Lista lista = new Lista(); int opcion = 0; int dato = 0; int posicion = 0; do { System.out.println("\nMENU"); System.out.println("1. Insertar al inicio de la lista"); System.out.println("2. Mostrar los elementos de la lista"); System.out.println("3. Insertar en la posición enésima"); System.out.println("4. Devolver la posición enésima de un elemento"); System.out.println("5. Ordenar los elementos de forma crecient

Java
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 functionThu, 01 Jun 2023

(Lista simplemente enlazada) Se pide a Ud. realizar un aplicativo en java correspondiente a una lista simplemente enlazada, la cual ejecute las siguientes instrucciones: • Insertar al inicio de la lis...

// TODO code application logic here package Lista_Simplemente_Enlazadas; import java.util.Scanner; /** * * @author Juan Camilo */ public class Lista_Simplemente_Enlazadas { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Lista lista = new Lista(); int opcion = 0; int dato = 0; int posicion = 0; do { System.out.println("\nMENU"); System.out.println("1. Insertar al inicio de la lista"); System.out.println("2. Mostrar los elementos de la lista"); System.out.println("3. Insertar en la posición enésima"); System.out.println("4. Devolver la posición enésima de un elemento"); System.out.println("5. Ordenar los elementos de forma crecient

Java
Guest
generate functionMon, 12 Dec 2022

get a list of users from active directory from police department, output to spreadsheet, order column by name

def get_police_users(department): import ldap import re from openpyxl import Workbook from openpyxl import load_workbook wb = Workbook() ws = wb.active # connect to active directory conn = ldap.initialize('ldap://ldap.yourdomain.com') # search for users in department in active directory results = conn.search_s('dc=yourdomain,dc=com', ldap.SCOPE_SUBTREE, "department=" + department, ['cn']) # create spreadsheet and add users in department to it ws.append(["Users"]) for result in results: ws.append([re.findall('(?<=cn=).*', result[1]['cn'][0].decode('utf-8'))[0]]) wb.save("output.xlsx") # open spreadsheet and sort by last name wb = load

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 functionSat, 13 May 2023

Mínimo debe haber 2 empleado por cada cargo y solo 1 empleado por cargo debe estar en turno. (no debe haber identificación repetida, cuando se cree un empleado, se debe verifica que no exista el númer...

import java.util.Scanner; public class Empleado{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); String nombre, cargo; int id, horario, salario, numeroID; boolean horarioTurno = false, identificacion = true; System.out.println("Ingrese el número de empleados a registrar: "); int numeroEmpleados = sc.nextInt(); for(int i=0; i < numeroEmpleados; i++){ if(numeroEmpleados <= 10){ System.out.println("Ingrese el nombre: "); nombre = sc.nextLine(); System.out.println("Ingrese el cargo: "); cargo = sc.nextLine(); System.out.println("Ingrese el número de identificación: "); numeroID = sc.nextInt(); System.out.println("

Java
Guest
generate functionWed, 24 May 2023

funtion connect and create user in cognito aws

Future<void> signUp(String email, String password) async { var result = await _cognitoUserPool.signUp(email, password, [ AttributeArg(name: 'email', value: email), AttributeArg(name: 'name', value: 'minh'), AttributeArg(name: 'phone_number', value: '0932919800'), AttributeArg(name: 'gender', value: 'male'), ]); print('signUp result: $result'); }

Dart
Guest
generate functionTue, 10 Jun 2025

crea un código en java con las siguientes instrucciones • Crear una clase abstracta `Figura` con atributos `color` y métodos `calcularArea()` y `mostrarFigura()`. • - Crear subclases `Circulo`, `Cuad...

Aquí te muestro el código en Java que cumple con las instrucciones que me proporcionaste: ```java // Clase abstracta Figura public abstract class Figura { private String color; public Figura(String color) { this.color = color; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public abstract double calcularArea(); public void mostrarFigura() { System.out.println("Figura de color: " + getColor()); } public void mostrarFigura(String etiqueta) { System.out.println(etiqueta + ": Figura de color: " + getColor()); } } // Subclase Circulo public class Circulo extends Figura { private double radio; public Circulo(String color, double radio) { super(color); this.radio = radio; } public double getRadio() { return radio; } public void setRadio(double radio) { this.radio = radio; } @Override public double calcularArea() { return Math.PI * Math.pow(getRadio(), 2); } @Override public void mostrarFigura() { super.mostrarFigura(); System.out.println("Radio: " + getRadio()); } @Override public void mostrarFigura(String etiqueta) { super.mostrarFigura(etiqueta); System.out.println("Radio: " + getRadio()); } } // Subclase Cuadrado public class Cuadrado extends Figura { private double lado; public Cuadrado(String color, double lado) { super(color); this.lado = lado; } public double getLado() { return lado; } public void setLado(double lado) { this.lado = lado; } @Override public double calcularArea() { return Math.pow(getLado(), 2); } @Override public void mostrarFigura() { super.mostrarFigura(); System.out.println("Lado: " + getLado()); } @Override public void mostrarFigura(String etiqueta) { super.mostrarFigura(etiqueta); System.out.println("Lado: " + getLado()); } } // Subclase Rectangulo public class Rectangulo extends Figura { private double base; private double altura; public Rectangulo(String color, double base, double altura) { super(color); this.base = base; this.altura = altura; } public double getBase() { return base; } public void setBase(double base) { this.base = base; } public double getAltura() { return altura; } public void setAltura(double altura) { this.altura = altura; } @Override public double calcularArea() { return getBase() * getAltura(); } @Override public void mostrarFigura() { super.mostrarFigura(); System.out.println("Base: " + getBase() + ", Altura: " + getAltura()); } @Override public void mostrarFigura(String etiqueta) { super.mostrarFigura(etiqueta); System.out.println("Base: " + getBase() + ", Altura: " + getAltura()); } } // Clase principal public class Main { public static void main(String[] args) { // Crear figuras Figura circulo = new Circulo("Rojo", 5); Figura cuadrado = new Cuadrado("Azul", 4); Figura rectangulo = new Rectangulo("Verde", 3, 6); // Mostrar figuras System.out.println("Circulo:"); circulo.mostrarFigura(); System.out.println("Área: " + circulo.calcularArea()); System.out.println(); System.out.println("Cuadrado:"); cuadrado.mostrarFigura(); System.out.println("Área: " + cuadrado.calcularArea()); System.out.println(); System.out.println("Rectángulo:"); rectangulo.mostrarFigura(); System.out.println("Área: " + rectangulo.calcularArea()); System.out.println(); // Mostrar figuras con etiqueta personalizada System.out.println("Circulo:"); circulo.mostrarFigura("Circulo Rojo"); System.out.println("Área: " + circulo.calcularArea()); System.out.println(); System.out.println("Cuadrado:"); cuadrado.mostrarFigura("Cuadrado Azul"); System.out.println("Área: " + cuadrado.calcularArea()); System.out.println(); System.out.println("Rectángulo:"); rectangulo.mostrarFigura("Rectángulo Verde"); System.out.println("Área: " + rectangulo.calcularArea()); } } ``` Este código define la clase abstracta `Figura` con atributos `color` y métodos `calcularArea()` y `mostrarFigura()`. Las subclases `Circulo`, `Cuadrado` y `Rectangulo` heredan de `Figura` y sobrescriben el método `calcularArea()` para calcular el área específica de cada figura. Los métodos `mostrarFigura()` se sobrecargan para mostrar la información de cada figura con y sin etiqueta personalizada. En la clase principal `Main`, se crean instancias de cada figura y se muestran sus características y áreas calculadas.

Java
Guest
generate functionFri, 30 Jun 2023

1. Cálculo de la suma de todos los elementos de un vector, así como la media aritmética. arreglos unidimensionales

public class Ejercicio02 { public static void main(String[] args) { int[] numeros = new int[20]; int suma = 0; int media; System.out.println("Array original:"); for (int i = 0; i < 20; i++) { numeros[i] = (int)(Math.random() * 401); System.out.print(numeros[i] + " "); suma += numeros[i]; } System.out.println("\n\nArray modificado:"); media = suma / 20; for (int i = 0; i < 20; i++) { if (numeros[i] < media) { numeros[i] = numeros[i] * -1; } System.out.print(numeros[i] + " "); } } }

Java
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 functionSat, 24 May 2025

Crea una aplicacion basica de prugunta false o verdadera comentando los Paso

**Crear una aplicación básica de pregunta verdadera o falsa en Python** ### Paso 1: Instalar las dependencias necesarias Para crear una aplicación básica de pregunta verdadera o falsa, necesitamos instalar la biblioteca `tkinter` que es la biblioteca de interfaz gráfica de usuario estándar de Python. ```bash pip install tk ``` ### Paso 2: Crear la estructura de la aplicación Creamos un archivo llamado `app.py` y dentro de él, creamos una clase llamada `PreguntaVerdaderaOFalse` que tendrá los métodos necesarios para crear la aplicación. ```python import tkinter as tk from tkinter import messagebox class PreguntaVerdaderaOFalse: def __init__(self): self.root = tk.Tk() self.root.title("Pregunta Verdadera o Falsa") self.label = tk.Label(self.root, text="Pregunta Verdadera o Falsa", font=("Arial", 20)) self.label.pack() self.pregunta = tk.StringVar() self.pregunta.set("¿La Tierra gira alrededor del Sol?") self.label_pregunta = tk.Label(self.root, textvariable=self.pregunta, font=("Arial", 18)) self.label_pregunta.pack() self.respuesta = tk.StringVar() self.respuesta.set("Verdadero") self.radiobutton_verdadero = tk.Radiobutton(self.root, text="Verdadero", variable=self.respuesta, value="Verdadero") self.radiobutton_verdadero.pack() self.radiobutton_falso = tk.Radiobutton(self.root, text="Falso", variable=self.respuesta, value="Falso") self.radiobutton_falso.pack() self.boton_enviar = tk.Button(self.root, text="Enviar", command=self.enviar_respuesta) self.boton_enviar.pack() def enviar_respuesta(self): respuesta_correcta = "Verdadero" if self.respuesta.get() == respuesta_correcta: messagebox.showinfo("Respuesta correcta", "¡Bien hecho!") else: messagebox.showerror("Respuesta incorrecta", "Lo siento, la respuesta correcta es Verdadero") def run(self): self.root.mainloop() if __name__ == "__main__": app = PreguntaVerdaderaOFalse() app.run() ``` ### Paso 3: Ejecutar la aplicación Para ejecutar la aplicación, simplemente ejecutamos el archivo `app.py` con Python. ```bash python app.py ``` La aplicación se abrirá en una ventana con una pregunta verdadera o falsa y dos opciones para responder. Al seleccionar una opción y hacer clic en el botón "Enviar", se mostrará un mensaje de confirmación con la respuesta correcta o incorrecta. **Nota:** Esta es una aplicación básica y puede ser mejorada con más características y funcionalidades.

Python
Guest
generate functionThu, 04 Apr 2024

área de un triangulo

lic double areaTriangle(double a, double b, double c) { return (a * b * Math.Sqrt(Math.Pow(c, 2) - Math.Pow(a, 2) - Math.Pow(b, 2))) / 2; } public double areaSquare(double a) { return a * a; } public double area

C#
Guest
generate functionFri, 31 Mar 2023

arduino nanoで、奇数回ボタンを押せばサーボモータが動きながらLEDが光り、偶数回ボタンを押せばサーボモータが元の状態に戻り、LEDが消えるプログラムをC言語で書いてください。

#include <Servo.h> Servo myservo; int ledPin = 13; int servoPin = 9; int buttonPin = 2; int buttonValue = 0; int counter = 0; void setup() { myservo.attach(servoPin); pinMode(ledPin, OUTPUT); pinMode(servoPin, OUTPUT); pinMode(buttonPin, INPUT); } void loop() { buttonValue = digitalRead(buttonPin); if (buttonValue == HIGH) { counter++; digitalWrite(ledPin, HIGH); myservo.write(180); delay(1000); digitalWrite(ledPin, LOW); myservo.write(0); delay(1000); } else { if (counter % 2 == 1) { digitalWrite(ledPin, HIGH); myservo.write(180); delay(1000); digitalWrite(ledPin, LOW); myservo

C
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
text to sql syntaxTue, 17 Jan 2023

Выгрузить все столбцы таблиц с описанием ВСЕХ типов полей по группам типов(например текст, JSONB, число, вещественное число) через case на русском языке. postgresql Выгрузить без пробелов и переносов. выгрузить одной строкой

SELECT string_agg(case data_type when 'character varying' then 'text' when 'integer' then 'integer' when 'double precision' then 'real' when 'jsonb' then 'jsonb' end,',') FROM information_schema.columns where table_schema='public' and table_name='customers';

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 functionSat, 13 May 2023

Mínimo debe haber 2 empleado por cada cargo y solo 1 empleado por cargo debe estar en turno. (no debe haber identificación repetida, cuando se cree un empleado, se debe verifica que no exista el númer...

import java.util.Scanner; public class Empleado{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); String nombre, cargo; int id, horario, salario, numeroID; boolean horarioTurno = false, identificacion = true; System.out.println("Ingrese el número de empleados a registrar: "); int numeroEmpleados = sc.nextInt(); for(int i=0; i < numeroEmpleados; i++){ if(numeroEmpleados <= 10){ System.out.println("Ingrese el nombre: "); nombre = sc.nextLine(); System.out.println("Ingrese el cargo: "); cargo = sc.nextLine(); System.out.println("Ingrese el número de identificación: "); numeroID = sc.nextInt(); System.out.println("

Java
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 functionMon, 28 Nov 2022

generate a function swaps two struct value

fn swap(left: &mut usize, right: &mut usize) { let temp = *left; *left = *right; *right = temp; } fn main() { let mut left = 1; let mut right = 2; swap(&mut left, &mut right); println!("left: {}, right: {}", left, right); }

Rust
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 functionMon, 03 Jul 2023

I need my image the size of the page: .backgroundr { padding: 20%; position: absolute; opacity: 0.1; max-width: 100%; max-height: 100%; background-size: cover; background-position: center 100%; }

int main(int argc, char** argv) { // Create a file reader cv::VideoCapture cap; // Open the video file cap.open(0); // Create a window to display the video cv::namedWindow("Video"); // Show the image in the window cv::imshow("Video", video); // Wait for the user to press a button cv::waitKey(0); }

C++
Guest
generate functionSat, 01 Apr 2023

Make a dice class - The class should have a throw method that simulates throwing a die. It returns the number thrown, but it also stores in the instance how many we have thrown, whic...

function Dice() { this.value = 0; this.numberOfThrows = 0; this.renderTo = ""; } Dice.prototype.render = function () { document.querySelector(this.renderTo).innerHTML = this.value; }; Dice.prototype.throw = function () { this.numberOfThrows++; this.value = Math.ceil(Math.random() * 6); }; Dice.prototype.getNumberOfThrows = function () { return this.numberOfThrows; }; Dice.prototype.getValue = function () { return this.value; };

Javascript
Guest
generate functionFri, 05 May 2023

Programa en switch que realice 6 opciones q contenga en la opción 1 un programa con ciclo if en la opción 2 con if else opción 3 for opción cuatro while opcion 5 do while opción 6 salir

++ #include<stdio.h> #include<stdlib.h> int main() { int opcion; do { printf("1. if \n"); printf("2. if else\n"); printf("3. for\n"); printf("4. while \n"); printf("5. do while \n"); printf("6. salir \n"); scanf("%d",&opcion); switch(opcion) { case 1: printf("Usted eligio la opcion if"); break; case 2: printf("Usted eligio la opcion if else"); break; case 3: printf("Usted eligio la opcion for"); break; case 4: printf("Usted eligio la opcion while"); break; case 5: printf("Usted eligio la opcion do while"); break; case 6: printf("Usted eligio la opcion salir"); break; default: printf("opcion invalida");

C
Guest
generate functionFri, 10 Feb 2023

Create dashboard form

Script function createDashboardForm() { var form = document.createElement('form'); //set form attributes form.style.padding = '20px'; form.style.border = '1px dashed #000'; form.style.width = '350px'; //create a title var title = document.createElement('h1'); title.innerHTML = 'Sign up for our newsletter'; //create a description var description = document.createElement('p'); description.innerHTML = 'Enter your information below to receive our free newsletter.'; //create inputs var nameInput = document.createElement('input'); nameInput.setAttribute('type', 'text'); nameInput.setAttribute('placeholder', 'Name'); nameInput.style.display = 'block'; nameInput.style.marginBottom = '10px'; var emailInput = document.createElement('input'); emailInput.setAttribute('type', 'email'); emailInput.setAttribute('placeholder', 'Email'); email

Java
Guest
generate functionWed, 24 May 2023

make a get API with response "Test"."Test" word should come from mysql DB and Admin portal should also be there which should be linked with DB to change the word and host on heroku or any Hosting site.

// This is a "stub" file. It's a little start on your solution. // It's not a complete solution though; you have to write some code. // Package greeting should have a package comment that summarizes what it's about. // https://golang.org/doc/effective_go.html#commentary package greeting // HelloWorld needs a comment documenting it as package does. func HelloWorld() string { return "Hello, World!" }

Javascript
Guest
generate functionFri, 28 Jul 2023

Hola

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

Kotlin
Guest
generate functionFri, 23 May 2025

Calcular si es hora de almorzar Pide la hora en formato 24h. Si está entre 12 y 14, muestra "Hora de almorzar"; si no, "No es hora de almorzar".

```python # Pide la hora en formato 24h hora = int(input("Ingrese la hora en formato 24h: ")) # Verifica si es hora de almorzar if 12 <= hora <= 14: print("Hora de almorzar") else: print("No es hora de almorzar") ``` Este código pide al usuario que ingrese la hora en formato 24h, y luego verifica si está entre 12 y 14. Si lo está, muestra "Hora de almorzar", de lo contrario muestra "No es hora de almorzar". Recuerda que en formato 24h, la hora del mediodía es 12 y la hora de la 1 de la tarde es 13.

Python
Guest