Replying to Questions Using ChatGPT

I have just provided over 10 examples of using ChatGPT to answer questions.

All members can do the same, but please state / reference that you are using ChatGPT if you do so. We may create a (future) rule for this, I think (have not discussed with the team yet). In the meantime, anyone who posts a reply using ChatGPT should say so.

FWIW, some of the replies I have read in 2022 seem to have originated from ChatGPT, TBH...

Thanks:

Examples Using ChatGPT ....

Some of these ChatGPT examples show AI answers which are really good.... as you can see.

1 Like

Hi,

Interesting ! I'd certainly agree that some of these answers are pretty much spot-on. A few of them wander off in interesting directions, but you can at least see what it's "thinking", so to speak, and how it gets to where it ends up. But mostly this seems to be doing a pretty good job of answering more straightforward "I have problem X and want result Y, what action Z do I have to perform to get there ?"-style questions.

1 Like

Yeah, this AI in particular seems well trained to Google terms in text and put together a well formatted reply.

At a minimum it adds value to Google in a big way and creates an excellent reference (in many cases) as a starting point.

ChatGPT says ......

See Also

While the answer is not always a good one, I admire the level of understanding the questions.

1 Like

There are a number of examples out there using ChatCPT to write code, most demonstrate that the instructions require further specs (and refinement) and the code is also generally not for production.

However, a few iterations of specifying the code does show promise and can provide a baseline to further refine.

Here are a few examples using ChatGPT to write some programs in Ruby:

(1) Write a ruby program to calculate the distance between two points on the surface of the earth given polar coordinates

ChatGPT

require 'math'

# Haversine formula to calculate distance between two points on the surface of a sphere
def distance(lat1, lon1, lat2, lon2)
  dlat = (lat2 - lat1).to_radians
  dlon = (lon2 - lon1).to_radians
  a = Math.sin(dlat / 2)**2 + Math.cos(lat1.to_radians) * Math.cos(lat2.to_radians) * Math.sin(dlon / 2)**2
  c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
  R = 6371 # Radius of the earth in kilometers
  R * c
end

# Example usage
puts distance(51.5074, 0.1278, 35.6895, 139.6917) # Outputs: 14707.23556565625

Notice that CGPT used long and lat versus polar coordinates, so I asked for a method in Ruby to covert polar coords to long and lat and got another method :slight_smile:

Then I asked....

(2) write a program in ruby to calculate the average velocity of hydrogen atoms in a boiling water on earth at sea level.

ChatGPT

# Determine the temperature of the boiling water in degrees Celsius
temp_c = 100

# Convert the temperature to kelvins
temp_k = temp_c + 273.15

# Calculate the average kinetic energy of the hydrogen atoms
boltzmann_constant = 1.38 * 10**-23
ke = (3.0/2) * boltzmann_constant * temp_k

# Calculate the average velocity of the hydrogen atoms
mass_hydrogen = 1.67 * 10**-27
velocity = Math.sqrt((3 * boltzmann_constant * temp_k) / mass_hydrogen)

puts "The average velocity of hydrogen atoms in boiling water at sea level is #{velocity} meters/second."

Of course, any normal engineer would not take these programs at face value and would check them (at this point in AI evolution), but between the explanations (not posted here) and the code, it's a good start.

I also tried other programs for example:

(3) Write a program in ruby to bind to a unix socket, listen and receive a JSON object, and return a status code

require 'socket'
require 'json'

# Create a socket and bind it to a Unix domain socket
socket = Socket.new(:UNIX, :STREAM)
socket.bind(Socket.pack_sockaddr_un('/path/to/socket'))

# Listen for incoming connections
socket.listen(5)

# Accept an incoming connection
connection, _ = socket.accept

# Read the incoming data as a JSON object
data = connection.read
json = JSON.parse(data)

# Return a status code
connection.write(200)

# Close the connection
connection.close

... same question using bash

# Create a Unix domain socket and bind it to a specified path
nc -lU /path/to/socket &

# Read the incoming data as a JSON object
data=$(nc -U /path/to/socket)
json=$(echo $data | jq -r '.')

# Return a status code
echo "200" | nc -U /path/to/socket

# Close the connection
pkill nc

ask again.... same question

#!/bin/bash

# Create a socket and bind it to a Unix domain socket
socat UNIX-LISTEN:/path/to/socket,fork - &

# Wait for an incoming connection
while true; do
  # Read the incoming data as a JSON object
  data=$(nc -U /path/to/socket)
  json=$(echo $data | jq -r '.')

  # Return a status code
  echo 200 > /path/to/socket
done

and again.... :slight_smile:

#!/bin/bash

# Create a Unix domain socket and bind it to the specified path
socat UNIX-LISTEN:/path/to/socket,fork - &

# Accept an incoming connection
connection=$(socat - UNIX-CONNECT:/path/to/socket)

# Read the incoming data as a JSON object
data=$(echo "$connection" | jq -r .data)

# Return a status code
echo "HTTP/1.1 200 OK" >&3

# Close the connection
exec 3<&-

same question in C++

#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
  // Create a socket and bind it to a Unix domain socket
  int socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);
  struct sockaddr_un addr;
  memset(&addr, 0, sizeof(addr));
  addr.sun_family = AF_UNIX;
  strncpy(addr.sun_path, "/path/to/socket", sizeof(addr.sun_path) - 1);
  bind(socket_fd, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr));

  // Listen for incoming connections
  listen(socket_fd, 5);

  // Accept an incoming connection
  int connection_fd = accept(socket_fd, NULL, NULL);

  // Read the incoming data as a JSON object
  char buffer[1024];
  ssize_t bytes_read = read(connection_fd, buffer, sizeof(buffer));
  std::string data(buffer, bytes_read);
  json j = json::parse(data);

  // Return a status code
  std::string response = "HTTP/1.1 200 OK\n\n";
  write(connection_fd, response.c_str(), response.size());

  // Close the connection
  close(connection_fd);
  close(socket_fd);

  return 0;
}

Yes, this is not production code, but it's a good start for folks... and with a click of the mouse CGPT will do it again, often differently.

Same question asking for C#

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using Newtonsoft.Json;

namespace UnixSocketExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a socket and bind it to a Unix domain socket
            Socket socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
            EndPoint endpoint = new UnixEndPoint("/path/to/socket");
            socket.Bind(endpoint);

            // Listen for incoming connections
            socket.Listen(5);

            // Accept an incoming connection
            Socket connection = socket.Accept();

            // Read the incoming data as a JSON object
            StreamReader reader = new StreamReader(new NetworkStream(connection));
            string data = reader.ReadToEnd();
            dynamic json = JsonConvert.DeserializeObject(data);

            // Return a status code
            StreamWriter writer = new StreamWriter(new NetworkStream(connection));
            writer.WriteLine("HTTP/1.1 200 OK");
            writer.WriteLine();
            writer.Flush();

            // Close the connection
            connection.Close();
            socket.Close();
        }
    }
}

Here are a few more:

Write a bash script to truncate a log file, truncating prior days log entries.

#!/bin/bash

# Set the log file path
log_file="/path/to/log/file.log"

# Get the current date and time in the format YYYY-MM-DD
current_date=$(date +%F)

# Use sed to delete all lines before the current date
sed -i "/^$current_date/,$ d" "$log_file"

Write a shell script to start a docker container at system reboot

Here we need to post the code and explanations from CGPT, to be clear:

To start a Docker container at system reboot, you can use a shell script and add it to your system's startup scripts. Here is an example of a shell script that you can use to start a Docker container at system reboot:

#!/bin/bash

# Start the Docker container
docker start my_container

To add this script to your system's startup scripts, you can place it in the appropriate location for your system. For example, on Ubuntu systems, you can place it in /etc/init.d and make it executable with the following commands:

Copy code

sudo cp start_docker_container.sh /etc/init.d/
sudo chmod +x /etc/init.d/start_docker_container.sh

Then, you can add the script to the system startup scripts with the following command:

sudo update-rc.d start_docker_container.sh defaults

This will cause the script to be run at system startup, starting the Docker container.

I hope this helps! Let me know if you have any questions.

Not bad for an OpenAI :slight_smile:

... and very polite as well.

write a script to check for a running process on macos, send a message if the process is not running and restart the process

#!/bin/bash

# Set the process name and desired status
process="my_process"
status="running"

# Check the status of the process
proc_status=$(ps -ax | grep "$process" | grep -v grep | awk '{print $2}')

# If the process is not running, send a message and restart the process
if [ "$proc_status" != "$status" ]
then
  # Send a message
  osascript -e 'display notification "Process is not running. Restarting process." with title "Process Monitor"'

  # Restart the process
  /path/to/process/start_script.sh
fi

That's cool... I had forgotten about osascript and can't remember the last time I used it. Thanks CGPT :slight_smile:

It close to asking someone to write a script for us, the more we specify, the better the results will match our requirements (in our head).

For example:

write a script in ruby to calculate the number of seconds between two dates including leap years

require 'date'

# Parse the start and end dates
start_date = Date.parse("2020-01-01")
end_date = Date.parse("2022-01-01")

# Calculate the number of days between the two dates
days = (end_date - start_date).to_i

# Calculate the number of leap years between the two dates
leap_years = start_date.step(end_date, 365).count { |date| date.leap? }

# Calculate the total number of seconds
seconds = days * 86400 + leap_years * 86400

puts "Number of seconds: #{seconds}"
3 Likes

impressive :nerd_face:

It forgot the quotes! Correct is:

  # Read the incoming data as a JSON object
  data=$(nc -U /path/to/socket)
  json=$(echo "$data" | jq -r '.')

or straight

  # Read the incoming data as a JSON object
  json=$(nc -U /path/to/socket | jq -r '.')

But later it did put the quotes:

Did it learn in the meantime? Got shellcheck integrated??
I think it got one incorrect template and another correct one.

Another finding:

tries to kill all processes with nc in the name.
Should be at least an exact match:
pkill -x nc
or, most precise, use the shell's job control:
kill %1

1 Like

It's important to point out that, just like people (here included), the first pass at writing code is rarely the final version.

In other words, as stated earlier, software developers use ChatGPT as a starting point to develop code (you can easily confirm this on the net), not for final production code.

It is easy enough for anyone to create shell code with ChatGPT and copy-and-paste that code into shellcheck or do a quick review themselves.

As we all know, OpenAI (included ChatGPT) is a tool and software developers (who are increasingly using CGPT for their first drafts) do not view CGPT code output as final, production quality code.

Also, I have found that as a professional Ruby software developer, when I compare Ruby or Python draft CGPT code to draft Bash code, the Ruby and Python draft CGPT code is "cleaner" because shell code that BASH has quirks which do not really exist in Ruby or Python.

It is a mistake to consider draft CGPT code to be final production quality code.

The same is true for CGTP generated text like articles and essays. For example, there now exists software services which take text and score the likelihood the text was AI generated. There are also services which will take AI generated text and permit the user to change the text in a way which will significantly reduce the "AI likelihood score".

Back to CGTP generated code, at least the AI comments in their draft code and tends to use descriptive variable names, a wise coding practice rarely seen with most shell programmers here and elsewhere.

See Also:

The problem with this demonstration is that the developer asks the AI to write code at such a high level that the demonstration is meaningless. As a ROR person, I would not use ChatGPT in this way, but I would use it do help me outline methods to do specific calculations and methods. All tools need to be used properly to work as intended, and this includes AI software dev tools.

Mostly Nonsense Video Using ChatCPT Inappropriately (IMO)

Additionally, as far a coding goes, this model is in limited beta.

See:

I encourage everyone to play around with the OpenAI API. Currently, I have been working with this Ruby gem, playing around the code completion model. However, Python is better supported, so Python is the way to go for most people, I think.

Who knows.. .maybe I'll write an OpenAI plugin for Discourse so we don't have to copy-and-paste from ChatCPT if we want ChatCPT-like code completion contributions.

1 Like

FWIW, Slack Overflow banned ChatGPT not long ago.

Here, ChatGPT assistance is acceptable as long as any text generated by ChatGPT is referenced as ChatGPT generated.

Also, there are tools becoming available which can detect text generated by AI. I am confident that these AI-text-generation-detection tools will be available as a Discourse plugin sooner than later.

If not, I will modify one of our detection plugins to add this check when members post replies, but for now, we are still in the experimentation and learning phase for OpenAI and ChatGPT capabilities in providing assistance in tech forums.

See also:

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.