cjwbw / magicoder

LLMs with open-source code snippets for generating low-bias and high-quality instruction data for code.

  • Public
  • 362 runs
  • L40S
  • GitHub
  • Paper
  • License
Iterate in playground
  • Prediction

    cjwbw/magicoder:eb7225495efaf9e40a55779adaa6d7964ae94645486de334e10b19b62c456cfa
    ID
    by726rtb4ogl5piyztfd5r5ksm
    Status
    Succeeded
    Source
    Web
    Hardware
    A40 (Large)
    Total duration
    Created

    Input

    max_tokens
    2048
    instruction
    Write a snake game in Python using the turtle library (the game is created by Magicoder).
    temperature
    0

    Output

    Here is a simple snake game in Python using the turtle library. ```python import turtle import time import random delay = 0.1 # Score score = 0 high_score = 0 # Set up the screen wn = turtle.Screen() wn.title("Snake Game by Magicoder") wn.bgcolor("green") wn.setup(width=600, height=600) wn.tracer(0) # Turns off the screen updates # Snake head head = turtle.Turtle() head.speed(0) head.shape("square") head.color("black") head.penup() head.goto(0, 0) head.direction = "stop" # Snake food food = turtle.Turtle() food.speed(0) food.shape("circle") food.color("red") food.penup() food.goto(0, 100) segments = [] # Pen pen = turtle.Turtle() pen.speed(0) pen.shape("square") pen.color("white") pen.penup() pen.hideturtle() pen.goto(0, 260) pen.write("Score: 0 High Score: 0", align="center", font=("Courier", 24, "normal")) # Functions def go_up(): if head.direction!= "down": head.direction = "up" def go_down(): if head.direction!= "up": head.direction = "down" def go_left(): if head.direction!= "right": head.direction = "left" def go_right(): if head.direction!= "left": head.direction = "right" def move(): if head.direction == "up": y = head.ycor() head.sety(y + 20) if head.direction == "down": y = head.ycor() head.sety(y - 20) if head.direction == "left": x = head.xcor() head.setx(x - 20) if head.direction == "right": x = head.xcor() head.setx(x + 20) # Keyboard bindings wn.listen() wn.onkeypress(go_up, "w") wn.onkeypress(go_down, "s") wn.onkeypress(go_left, "a") wn.onkeypress(go_right, "d") # Main game loop while True: wn.update() # Check for a collision with the border if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290: time.sleep(1) head.goto(0, 0) head.direction = "stop" # Hide the segments for segment in segments: segment.goto(1000, 1000) # Clear the segments list segments.clear() # Reset the score score = 0 # Reset the delay delay = 0.1 # Update the score display pen.clear() pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal")) # Check for a collision with the food if head.distance(food) < 20: # Move the food to a random spot x = random.randint(-280, 280) y = random.randint(-280, 280) food.goto(x, y) # Add a segment new_segment = turtle.Turtle() new_segment.speed(0) new_segment.shape("square") new_segment.color("grey") new_segment.penup() segments.append(new_segment) # Shorten the delay delay -= 0.001 # Increase the score score += 10 if score > high_score: high_score = score pen.clear() pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal")) # Move the end segments first in reverse order for index in range(len(segments) - 1, 0, -1): x = segments[index - 1].xcor() y = segments[index - 1].ycor() segments[index].goto(x, y) # Move segment 0 to where the head is if len(segments) > 0: x = head.xcor() y = head.ycor() segments[0].goto(x, y) move() # Check for head collision with the body segments for segment in segments: if segment.distance(head) < 20: time.sleep(1) head.goto(0, 0) head.direction = "stop" # Hide the segments for segment in segments: segment.goto(1000, 1000) # Clear the segments list segments.clear() # Reset the score score = 0 # Reset the delay delay = 0.1 # Update the score display pen.clear() pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal")) time.sleep(delay) wn.mainloop() ``` This game is a simple version of the classic snake game. The snake starts with a single segment and grows in size each time it eats the food. The game ends when the snake hits the border or itself. The score is increased by 10 points for each food eaten. The game speed increases with each food eaten.
    Generated in
  • Prediction

    cjwbw/magicoder:eb7225495efaf9e40a55779adaa6d7964ae94645486de334e10b19b62c456cfa
    ID
    foycdldblik2h3oajujux7xemy
    Status
    Succeeded
    Source
    Web
    Hardware
    A40 (Large)
    Total duration
    Created

    Input

    max_tokens
    2048
    instruction
    Build a console-based Othello game in Java with row and column numbers shown on the board. The game should end when there are no more valid moves for either player.
    temperature
    1

    Output

    Below is the basic structure of Othello game in java. Please note it's a simple command line version of the game, so the UI is very simple, also note that this game is not optimized and does not include complex features such as AI, multiplayer, etc. ```java public class Othello { private static final char EMPTY = '.'; private static final char BLACK = 'B'; private static final char WHITE = 'W'; private int rows, cols; private char[][] board; private char currentPlayer; public Othello(int rows, int cols) { this.rows = rows; this.cols = cols; this.board = new char[rows][cols]; this.currentPlayer = BLACK; this.initializeBoard(); } private void initializeBoard() { if(rows>2 && cols>2 && rows%2==0 && cols%2==0){ board[rows/2-1][cols/2-1] = WHITE; board[rows/2][cols/2] = WHITE; board[rows/2][cols/2-1] = BLACK; board[rows/2-1][cols/2] = BLACK; } else System.out.println("Invalid size"); } private void switchPlayer() { if(this.currentPlayer == BLACK) this.currentPlayer = WHITE; else this.currentPlayer = BLACK; } private boolean placePiece(int row, int col) { if( this.board[row][col]!= EMPTY ){ System.out.println("That spot is already occupied."); return false; } boolean anyLegalMove = false; for(int r = -1; r <= 1; r++){ for(int c = -1; c <= 1; c++){ boolean canFlip = false; for(int dr = row - r, dc = col - c; dr >= 0 && dr < rows && dc >= 0 && dc < cols && this.board[dr][dc]!= EMPTY && this.board[dr][dc]!= this.currentPlayer; dr -= r, dc -= c) if(this.board[dr][dc] == this.currentPlayer) canFlip = true; else if(canFlip){ this.board[row][col] = this.currentPlayer; for(dr = row - r, dc = col - c; dr!= row || dc!= col; dr -= r, dc -= c) this.board[dr][dc] = this.currentPlayer; break; } } } if(canFlip == false){ System.out.println("That move is illegal."); return false; } this.switchPlayer(); return true; } public void play(){ while(canPlacePiece()){ drawBoard(); System.out.println("Current player: " + this.currentPlayer); //Handle user input here //Assume that 0-based index is used int row = 0, col = 0; if(!placePiece(row, col)) { return; } } drawBoard(); determineWinner(); } private boolean canPlacePiece(){ for(int r=0; r<rows; r++) for(int c=0; c<cols; c++) if(this.placePiece(r, c)) return true; return false; } private void drawBoard(){ for(int i = 0; i<this.cols; i++) System.out.print(i + " "); System.out.println(); for(int r=0; r<this.rows; r++){ System.out.print(r + " "); for(int c=0; c<this.cols; c++) System.out.print(this.board[r][c] + " "); System.out.println(); } } private void determineWinner(){ int blackCount = 0, whiteCount = 0; for(int r=0; r<this.rows; r++) for(int c=0; c<this.cols; c++) if(this.board[r][c] == BLACK) blackCount++; else if(this.board[r][c] == WHITE) whiteCount++; System.out.println("Black: " + blackCount + ", White: " + whiteCount); if(blackCount > whiteCount) System.out.println("Black wins!"); else if (whiteCount > blackCount) System.out.println("White wins!"); else System.out.println("It's a draw!"); } } ``` To play the game, create an object of Othello: ```java public static void main(String[] args) { Othello game = new Othello(8, 8); game.play(); } ``` You would replace `row` and `col` on the placePiece with the values provided by the user, and `determineWinner` method would calculate the total number of black and white discs on the board, and print the message indicating the winner or a draw.
    Generated in
  • Prediction

    cjwbw/magicoder:eb7225495efaf9e40a55779adaa6d7964ae94645486de334e10b19b62c456cfa
    ID
    7kwyt63bwmgbqsl6zmalqrpb3i
    Status
    Succeeded
    Source
    Web
    Hardware
    A40 (Large)
    Total duration
    Created

    Input

    max_tokens
    2048
    instruction
    Build a simple neural network in Python using Pytorch to classify handwritten digits from the MNIST dataset. You should use CNN as the model structure, train the model for 5 epochs, draw a chart of the training loss, and show the final result.
    temperature
    1

    Output

    Here is the Python code to create, train, and evaluate a Convolutional Neural Network (CNN) to classify handwritten digits from MNIST dataset. ```python import torch import torch.nn as nn import torchvision.transforms as transforms import torchvision.datasets as dsets import torch.optim as optim import matplotlib.pyplot as plt # Step 1: Loading Data # Transform the data to torch tensors and normalize it by the mean and std deviation transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean=(0.5, ), std=(0.5, )) ]) train_dataset = dsets.MNIST(root='./data', train=True, transform=transform, download=True) test_dataset = dsets.MNIST(root='./data', train=False, transform=transform, download=True) # Prepare Data Loaders train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=100, shuffle=True) test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=100, shuffle=False) # Step 2: Define Model class CNN(nn.Module): def __init__(self): super().__init__() self.layer1 = nn.Sequential( nn.Conv2d(1, 32, kernel_size=5, padding=2), nn.ReLU(), nn.MaxPool2d(2) ) self.layer2 = nn.Sequential( nn.Conv2d(32, 64, kernel_size=5, padding=2), nn.ReLU(), nn.MaxPool2d(2) ) self.fc = nn.Linear(7*7*64, 10, bias=True) torch.nn.init.xavier_uniform_(self.fc.weight) def forward(self, x): out = self.layer1(x) out = self.layer2(out) out = out.view(out.size(0), -1) # Flatten the tensor out = self.fc(out) return out # Step 3: Define a Loss Function and Optimizer model = CNN() criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=0.001) # Training the Model losses = [] epochs = 5 for epoch in range(epochs): total_loss = 0 for i, (images, labels) in enumerate(train_loader): outputs = model(images) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step() total_loss += loss.item() print("Epoch %d, Total Loss: %.4f" % (epoch + 1, total_loss)) losses.append(total_loss) plt.plot(losses) plt.xlabel("Epochs") plt.ylabel("Loss") plt.title("Loss progress during the training") plt.show() # Step 4: Test the Model correct = 0 total = 0 for images, labels in test_loader: outputs = model(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Test Accuracy: %d %%' % (100 * correct / total)) ``` The code above will create and train the CNN model for 5 epochs on the MNIST dataset. Then, it displays a plot of the training loss over epochs and evaluates the model's accuracy on the test dataset. The model architecture is a simple CNN with two convolutional layers, each followed by a ReLU activation function and a max-pooling layer. The output of the second convolutional layer is flattened into a long vector, then passed through a fully connected (linear) layer. We use the Adam optimizer and the cross-entropy loss function for training, then plot the training loss over epochs.
    Generated in
  • Prediction

    cjwbw/magicoder:eb7225495efaf9e40a55779adaa6d7964ae94645486de334e10b19b62c456cfa
    ID
    4bjvzrlbcnaoyxmdqmi76j5hza
    Status
    Succeeded
    Source
    Web
    Hardware
    A40 (Large)
    Total duration
    Created

    Input

    max_tokens
    2048
    instruction
    Build a simple neural network in Python using Pytorch to classify handwritten digits from the MNIST dataset. You should use CNN as the model structure, train the model for 5 epochs, draw a chart of the training loss, and show the final result.
    temperature
    0

    Output

    Here is a simple example of how you can build a convolutional neural network (CNN) using PyTorch to classify handwritten digits from the MNIST dataset. ```python import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt # Define the CNN architecture class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = nn.Dropout2d(0.25) self.dropout2 = nn.Dropout2d(0.5) self.fc1 = nn.Linear(9216, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x): x = self.conv1(x) x = nn.functional.relu(x) x = self.conv2(x) x = nn.functional.relu(x) x = nn.functional.max_pool2d(x, 2) x = self.dropout1(x) x = torch.flatten(x, 1) x = self.fc1(x) x = nn.functional.relu(x) x = self.dropout2(x) x = self.fc2(x) output = nn.functional.log_softmax(x, dim=1) return output # Load the MNIST dataset transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True) testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False) # Initialize the network and the optimizer net = Net() optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.5) criterion = nn.NLLLoss() # Train the network losses = [] for epoch in range(5): # loop over the dataset multiple times running_loss = 0.0 for i, data in enumerate(trainloader, 0): inputs, labels = data optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() losses.append(running_loss) # Plot the training loss plt.plot(losses) plt.xlabel('Epoch') plt.ylabel('Loss') plt.show() # Test the network on the test data correct = 0 total = 0 with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the 10000 test images: %d %%' % (100 * correct / total)) ``` This script first defines a simple CNN architecture, then loads the MNIST dataset and normalizes it. It then trains the network for 5 epochs, storing the loss at each epoch. After training, it plots the training loss. Finally, it tests the network on the test data and prints the accuracy.
    Generated in

Want to make some of these yourself?

Run this model