SECRET OF CSS

OpenAI Codex — My Trials and Tribulations | by Go Woojin | Jul, 2022


I tested the AI tool with five classic coding problems

1*FiIDOSUteSdwzwk5CXmU2w
OpenAI Codex

Last year, OpenAI announced Codex, a model for efficient programming with the aid of Artificial Intelligence (AI). One of the videos uploaded to the OpenAI YouTube channel showed a live demo that was hard to believe even when seen with one’s own eyes.

With just a few lines of commands, it was possible to create a whole game in JavaScript.

The level of the commands seemed somewhat high, but with Codex you can see that it is immediately able to implement the code and run the game. In this way, Codex is a model that helps people write code much more efficiently than they could on their own.

Thanks to the rapid development of artificial intelligence, things that couldn’t even be imagined a few years ago are becoming a reality. Fortunately, I received permission from OpenAI to test Codex. I wondered how much AI could help us write code.

First, as I showed in the Codex live demo, I thought it would be fun to make a game. I thought it would be best to start with a simple game, so I decided to make a game where you can play rock-paper-scissors with the computer. I soon gave the following instructions to Codex.

"""
Rock-scissor-paper game written in python3
"""

Immediately, Codex showed the below Python 3 code:

import random# Game start
print("Let's play Rock-Scissor-Paper game!")
# Variable settings
user_score = 0
computer_score = 0
# Game process
while True:
user_choice = input("Rock, Scissor, Paper? (R/S/P) : ")
computer_choice = random.choice(["R", "S", "P"])
if user_choice == "R":
if computer_choice == "R":
print("Computer : Rock")
print("Draw!")
elif computer_choice == "S":
print("Computer : Scissor")
print("You win!")
user_score += 1
elif computer_choice == "P":
print("Computer : Paper")
print("You lose!")
computer_score += 1
elif user_choice == "S":
if computer_choice == "R":
print("Computer : Rock")
print("You lose!")
computer_score += 1
elif computer_choice == "S":
print("Computer : Scissor")
print("Draw!")
elif computer_choice == "P":
print("Computer : Paper")
print("You win!")
user_score += 1
elif user_choice == "P":
if computer_choice == "R":
print("Computer : Rock")
print("You win!")
user_score += 1
elif computer_choice == "S":
print("Computer : Scissor")
print("You lose!")
computer_score += 1
elif computer_choice == "P":
print("Computer : Paper")
print("Draw!")
else:
print("Please enter R/S/P.")
continue
print("Your score : " + str(user_score))
print("Computer score : " + str(computer_score))
if user_score == 3:
print("You win!")
break
elif computer_score == 3:
print("You lose!")
break

# Game end
print("Game over!")

I copied them and pasted them into the Online python compiler site. The results were the same as below:

Let's play Rock-Scissor-Paper game!
Rock, Scissor, Paper? (R/S/P) : S
Computer : Scissor
Draw!
Your score : 0
Computer score : 0
Rock, Scissor, Paper? (R/S/P) : R
Computer : Rock
Draw!
Your score : 0
Computer score : 0
Rock, Scissor, Paper? (R/S/P) : P
Computer : Paper
Draw!
Your score : 0
Computer score : 0
Rock, Scissor, Paper? (R/S/P) : R
Computer : Rock
Draw!
Your score : 0
Computer score : 0
Rock, Scissor, Paper? (R/S/P) : R
Computer : Paper
You lose!
Your score : 0
Computer score : 1
Rock, Scissor, Paper? (R/S/P) : R
Computer : Paper
You lose!
Your score : 0
Computer score : 2
Rock, Scissor, Paper? (R/S/P) : R
Computer : Paper
You lose!
Your score : 0
Computer score : 3
You lose!
Game over!

As you can see in the results window, you can have a rock-paper-scissors game where the first person to get 3 points wins. The computer got 3 points first and I lost. The game was over automatically.

After that, I asked Codex to write code that would output a quadratic equation graph using Python 3.

“””
Make a code for drawing simple quadratic equation using python3.
Note that the code should embrace random quadratic equations from user.
“””

Codex gave me the code below:

import matplotlib.pyplot as plt
import numpy as np
# input a, b, c from user
a = int(input("a = "))
b = int(input("b = "))
c = int(input("c = "))
# draw the graph
x = np.linspace(-10, 10, 100)
y = a*x**2 + b*x + c
plt.plot(x, y)
plt.show()

I immediately executed the Python 3 interpreter.

1*d4Wq5DrFjjWkDUjiLmeqNw
The quadratic curve was drawn with the code suggested by CODEX.

You can see that the quadratic equation was successfully drawn by the code suggested by Codex. If I enter the coefficients a, b, and c, then the above code gives me the graph.

I asked for another order, something like drawing an ellipsoid!

""" 
Write a simple code for drawing simple ellipsoid with python3.
"""

Well, I think it was easy for them:

"""
Write a simple code for drawing simple ellipsoid with python3.
"""
import scipy.special as sps
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
a = 1
b = 2
c = 3
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = a * np.outer(np.cos(u), np.sin(v))
y = b * np.outer(np.sin(u), np.sin(v))
z = c * np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b')plt.show()
1*5IHTfzRhDkvW73cRPphASg
The 3D ellipsoid image was drawn by the code suggested by CODEX.

I had a doubt if Codex can actually make a web crawler. Of course, because the crawling code becomes quite long for complex tasks, I asked Codex to do a simple crawling task (such as only loading the title from a Google news site, etc.).

"""
A simple code for showing brief information from Google News.
"""

Codex showed me something like this:

import requests
from bs4 import BeautifulSoup
url = "https://news.google.com/"response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
titles = soup.find_all("h3", class_="ipQwMb ekueJc RD0gLb")for title in titles:
print(title.text)

Since the URL was focused on the English version of Google News, the results were:

Maryland Primary Election Results 2022
Biden holds off — for now — on climate emergency declaration
Sri Lanka: Ranil Wickremesinghe elected president
Uvalde school shooting: What is the employment status of responding officers? We asked each agency
Jan. 6 panel says Secret Service failed to deliver ‘erased’ texts
Vladimir Putin Says Russia Will Honor Gas Commitments, but Warns of New Nord Stream Curbs

How about if I substitute the URL to the Japanese Google News?

東京都 コロナ 4人死亡 2万401人感染確認 2万人超は2月5日以来
世界景気「後退懸念強まる」 IMF専務理事インタビュー
息子の入試に加点してもらい、東京医大に合格…受託収賄罪の文科省元局長に執行猶予付き判決
中学生に袋かぶせて殴り監禁か NPO法人理事長・小学校教員を逮捕
【速報】神奈川・黒岩知事「新規感染者1万人超の見通し」過去最多に(2022年7月20日)
伊藤詩織さん、性被害当時に刑事部長だった中村格警察庁長官に「お話しして欲しい」

Then, let’s change the URL to Korean Google News.

금속노조, 서울·거제서 총파업 집회…"대우조선 투쟁 승리"
민주당 박홍근 교섭단체 대표 연설 “권력 사유화, 반드시 대가”…탄핵 빗대 윤 대통령 직격
권성동, '대통령실 사적 채용' 논란에 “논란 커진 건 저의 불찰”
이명박 이재용 사면?…`광복절 특사`질문에 말 아낀 尹
노동부장관 또 거제행‥대우조선 협상 타결되나?
수학여행 다녀온 전주 고교 학생·교사 159명 확진

When looking at the content of the news, you can see that the latest news articles are being pulled up.

Can I ask for an HTML coding for Codex? I asked the command like this:

<!-- Mimick google main homepage only with HTML & CSS -->

Codex replied with the following code:

<!-- Mimick google main homepage only with HTML & CSS -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Google Homepage</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
</head>
<body>

<div class="wrapper">
<div class="header">
<div class="header-upper">
<div class="header-logo">
<h1>Google</h1>
<h4>www.google.com</h4>
</div>
<div class="search-section">
<div class="search-bar">
<i class="fas fa-search"></i>
<input type="text" placeholder="Search">
<i class="fas fa-microphone"></i>
</div>
<button class="btn-search">
<i class="fas fa-search"></i>
<span>Google Search</span>
</button>
<button class="btn-i-am-feeling-lucky">
<i class="fas fa-lightbulb"></i>
<span>I'm Feeling Lucky</span>
</button>
</div>
</div>
<div class="header-lower">
<div class="header-options">
<span>Advertising</span>
<span>Business</span>
<span>About</span>
</div>
<div class="header-language">
<i class="fas fa-globe-americas"></i>
<span>English</span>
<i class="fas fa-caret-down"></i>
</div>
</div>
</div>

<div class="content">
<div class="image-section">
<img src="https://cdn.dribbble.com/users/2117143/screenshots/5666840/google-dribble_1x.png" alt="google">
</div>
<div class="image-section-content">
<h1>Google offered in:</h1>
<h2>English</h2>
<ul>
<li><a href="">Bahasa Melayu</a></li>
<li><a href="">Català</a></li>
<li><a href="">Čeština</a></li>
<li><a href="">Dansk</a></li>
<li><a href="">Deutsch</a></li>
<li><a href="">English</a></li>
<li><a href="">Espanõl</a></li>
<li><a href="">Filipino</a></li>
<li><a href="">Français</a></li>
</ul>
<ul>
<li><a href="">Hrvatski</a></li>
<li><a href="">Indonesia</a></li>
<li><a href="">Italiano</a></li>
<li><a href="">Latviešu</a></li>
<li><a href="">Lietuvių</a></li>
<li><a href="">Magyar</a></li>
<li><a href="">Nederlands</a></li>
<li><a href="">Norsk</a></li>
<li><a href="">Polski</a></li>
</ul>
<ul>
<li><a href="">Português</a></li>
<li><a href="">Română</a></li>
<li><a href="">Slovenčina</a></li>
<li><a href="">Suomi</a></li>
<li><a href="">Svenska</a></li>
<li><a href="">Tiếng Việt</a></li>
<li><a href="">Türkçe</a></li>
<li><a href="">Български</a></li>
<li><a href="">Pусский</a></li>
</ul>
<ul>
<li><a href="">Српски</a></li>
<li><a href="">한국어</a></li>
<li><a href="">中文(繁體)</a></li>
<li><a href="">中文(简体)</a></li>
<li><a href="">日本語</a></li>
<li><a href="">हिन्दी</a></li>
<li><a href="">ภาษาไทย</a></li>
</ul>
</div>
</div>
<div class="footer">
<div class="footer-options">
<ul>
<li><a href="">Advertising</a></li>
<li><a href="">Business</a></li>
<li><a href="">About</a></li>
</ul>
</div>
</div>
</div>
</body>
</html>

I copied and pasted them into the online HTML interpreter, and checked the results.

1*0Lkcc5ETBKdy2z3rMZ1mqg
The mimicked Google HTML window which was configured by CODEX

Although we can’t see the pretty appearance because the CSS file doesn’t exist, we can see that everything from the header to the search bar to the search button has been implemented.

We can also see the signature button on the Google home page, “I’m Feeling Lucky.” With a little more work, Codex can also be expected to speed up the work.

If you’re learning Python, you’d probably come across the Tic-Tac-Toe game problem.

Codex makes it easy for you to solve:

"""
Make a Tic-Tac-Toe game written in python3. Make sure to write Checkerboard with '|', '-'.
"""

I instructed Codex to check the checkerboard directly from the code window. The resulting code was as follows:

import randomclass TicTacToe(object):
def __init__(self):
self.board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
def print_board(self):
for i in range(0, 3):
for j in range(0, 3):
print('|', end=' ')
print(self.board[i][j], end=' ')
print('|\n')
print('-' * 11)
def get_input(self):
while True:
try:
x, y = input('Please enter two integers between 1 and 3, separated by comma: ').split(',')
except ValueError:
print('Invalid input, try again')
continue
x, y = int(x), int(y)
if 1 <= x <= 3 and 1 <= y <= 3:
break
print('Invalid input, try again')
return x - 1, y - 1
def check(self, x, y, player):
return self.board[x][y] == ' ' and (x, y) in self.generate_moves(player)
def make_move(self, x, y, player):
self.board[x][y] = 'X' if player == 1 else 'O'
def generate_moves(self, player):
moves = []
for i in range(0, 3):
for j in range(0, 3):
if self.board[i][j] == ' ':
moves.append((i, j))
return moves
def has_winner(self):
# check rows
for i in range(0, 3):
if self.board[i][0] != ' ' and self.board[i][0] == self.board[i][1] and self.board[i][1] == self.board[i][2]:
return True
# check columns
for i in range(0, 3):
if self.board[0][i] != ' ' and self.board[0][i] == self.board[1][i] and self.board[1][i] == self.board[2][i]:
return True
# check diagonals
if self.board[0][0] != ' ' and self.board[0][0] == self.board[1][1] and self.board[1][1] == self.board[2][2]:
return True
if self.board[0][2] != ' ' and self.board[0][2] == self.board[1][1] and self.board[1][1] == self.board[2][0]:
return True
return Falsedef is_full(self):
for i in range(0, 3):
for j in range(0, 3):
if self.board[i][j] == ' ':
return False
return True
def game_over(self):
return self.has_winner() or self.is_full()
def play_human(self, player):
print('Player {}\'s turn'.format(player))
x, y = self.get_input()
while not self.check(x, y, player):
print('Invalid move')
x, y = self.get_input()
self.make_move(x, y, player)
def play_computer(self, player):
moves = self.generate_moves(player)
move = random.choice(moves)
x, y = move
print('Player {} moves to ({}, {})'.format(player, x + 1, y + 1))
self.make_move(x, y, player)
def game_loop(self):
player = 1
while not self.game_over():
self.print_board()
if player == 1:
self.play_human(player)
else:
self.play_computer(player)
player = 2 if player == 1 else 1
self.print_board()
if self.has_winner():
print('Game over: Player {} wins'.format(player))
else:
print('Game over: No winner')
if __name__ == '__main__':
game = TicTacToe()
game.game_loop()

I checked them to see if they are working properly.

|   |   |   ||   |   |   ||   |   |   |-----------
Player 1's turn
Please enter two integers between 1 and 3, separated by comma: 1,1
| X | | |
| | | || | | |-----------
Player 2 moves to (1, 2)
| X | O | |
| | | || | | |

If the user inputs an X position with a comma (e.g. 1, 1), the checkerboard will immediately place the piece, and the computer will also place its piece at an arbitrary position and output the state. The game ends when consecutive three pieces (X or O) are placed in any diagonal, horizontal, or vertical form.

| X | O | O ||   | X |   ||   |   | X |-----------
Game over: Player 2 wins

Yes, I won. Making a Tic-Tac-Toe was so easy thanks to Codex.



News Credit

%d bloggers like this: