100% found this document useful (2 votes)
3K views

Download Full Full-Stack Web Development with Go: Build your web applications quickly using the Go programming language and Vue.js 1st Edition Nanik Tolaram PDF All Chapters

Go

Uploaded by

widarzablon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
3K views

Download Full Full-Stack Web Development with Go: Build your web applications quickly using the Go programming language and Vue.js 1st Edition Nanik Tolaram PDF All Chapters

Go

Uploaded by

widarzablon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Experience Seamless Full Ebook Downloads for Every Genre at textbookfull.

com

Full-Stack Web Development with Go: Build your web


applications quickly using the Go programming
language and Vue.js 1st Edition Nanik Tolaram

https://textbookfull.com/product/full-stack-web-development-
with-go-build-your-web-applications-quickly-using-the-go-
programming-language-and-vue-js-1st-edition-nanik-tolaram/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Full-Stack Web Development with Jakarta EE and Vue.js:


Your One-Stop Guide to Building Modern Full-Stack
Applications with Jakarta EE and Vue.js Daniel Andres
Pelaez Lopez
https://textbookfull.com/product/full-stack-web-development-with-
jakarta-ee-and-vue-js-your-one-stop-guide-to-building-modern-full-
stack-applications-with-jakarta-ee-and-vue-js-daniel-andres-pelaez-
lopez/
textboxfull.com

Let s Go Learn to build professional web applications with


Go Alex Edwards

https://textbookfull.com/product/let-s-go-learn-to-build-professional-
web-applications-with-go-alex-edwards/

textboxfull.com

Let s Go Learn to build professional web applications with


Go Alex Edwards

https://textbookfull.com/product/let-s-go-learn-to-build-professional-
web-applications-with-go-alex-edwards-2/

textboxfull.com

Go Web Programming 1st Edition Sau Sheong Chang

https://textbookfull.com/product/go-web-programming-1st-edition-sau-
sheong-chang/

textboxfull.com
Mastering Full Stack React Web Development 1st Edition
Tomasz Dyl

https://textbookfull.com/product/mastering-full-stack-react-web-
development-1st-edition-tomasz-dyl/

textboxfull.com

Pro MERN Stack: Full Stack Web App Development with Mongo,
Express, React, and Node Vasan Subramanian

https://textbookfull.com/product/pro-mern-stack-full-stack-web-app-
development-with-mongo-express-react-and-node-vasan-subramanian/

textboxfull.com

Essential ASP.NET Web Forms Development: Full Stack


Programming with C#, SQL, Ajax, and JavaScript 1st Edition
Robert E. Beasley
https://textbookfull.com/product/essential-asp-net-web-forms-
development-full-stack-programming-with-c-sql-ajax-and-javascript-1st-
edition-robert-e-beasley/
textboxfull.com

Full Stack Web Development with Jakarta EE and Vue js Your


One Stop Guide to Building Modern Full Stack Applications
with Jakarta EE and Vue js 1st Edition Daniel Andres
Pelaez Lopez
https://textbookfull.com/product/full-stack-web-development-with-
jakarta-ee-and-vue-js-your-one-stop-guide-to-building-modern-full-
stack-applications-with-jakarta-ee-and-vue-js-1st-edition-daniel-
andres-pelaez-lopez/
textboxfull.com

Pro MERN Stack: Full Stack Web App Development with Mongo,
Express, React, and Node 2nd Edition Vasan Subramanian

https://textbookfull.com/product/pro-mern-stack-full-stack-web-app-
development-with-mongo-express-react-and-node-2nd-edition-vasan-
subramanian/
textboxfull.com
Full-Stack Web Development
with Go

Build your web applications quickly using the Go programming


language and Vue.js

Nanik Tolaram

Nick Glynn

BIRMINGHAM—MUMBAI
Full-Stack Web Development with Go
Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted
in any form or by any means, without the prior written permission of the publisher, except in the case
of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information
presented. However, the information contained in this book is sold without warranty, either express
or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable
for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and
products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot
guarantee the accuracy of this information.

Group Product Manager: Pavan Ramchandani


Publishing Product Manager: Bhavya Rao
Senior Content Development Editor: Feza Shaikh
Technical Editor: Saurabh Kadave
Copy Editor: Safis Editing
Project Coordinator: Manthan Patel
Proofreader: Safis Editing
Indexer: Tejal Daruwale Soni
Production Designer: Shyam Sundar Korumilli
Marketing Coordinator: Anamika Singh

First published: February 2023

Production reference: 1270123

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-80323-419-9

www.packtpub.com
To my dearest Mum, who always supported me in pursuing my dreams and encouraged me to keep on
going no matter what life brought.

To my late Dad, who stood by me and encouraged me to write my very first book when I was
17 years old.

To my beautiful wife and best friend, for allowing me the time to write the book and supporting me in
every step of our life.

To both my sons, Rahul and Manav, for allowing me to spend time in front of the computer on
weekends to chase my dream and passion. Last but not least, to God, for giving me this life and the
opportunity to be where I am in this world.

– Nanik Tolaram

I would like to thank my family for their love; my beautiful daughter Inara, for always being there
to brighten my day; and my beautiful partner Kate, for all her support in my business efforts and in
writing this book.

– Nick Glynn
Contributors

About the authors


Nanik Tolaram is a big proponent of open source software. He has dabbled in different programming
languages, such as Java, JavaScript, C, and C++. He has developed different products from the ground
up while working in start-up companies. He is a software engineer at heart, but he loves to write
technical articles and share his knowledge with others. He learned to program with Go during the
COVID-19 pandemic and hasn’t looked back.

I want to thank the Packt team – Feza Shaikh, Bhavya Rao, Manthan Patel, and Mark D’Souza – for
their guidance and patience in helping us complete the book.

Nick Glynn is the founder and current chief product officer of FeeWise, a US payments and finance
platform.
He has previously worked in CTO, senior, and principal engineering roles developing products, training,
and consulting for companies such as Intel, Qualcomm, Hewlett Packard, L3, and many more.
With a broad range of experience from board bring-up, Linux driver development, and systems
development up through to building and deploying platforms that power investment and financial
institutions, Nick is always looking to build pragmatic solutions to real-world problems.
Nick also continues his independent efforts as a trainer and consultant, delivering courses and expertise
globally through his company Curiola (www.curiola.com).
About the reviewers
Pablo David Garaguso was born in Mar del Plata, Argentina. He graduated with two degrees in
computer sciences and enterprise systems from CAECE University and later on received an MBA
from CEMA University in Buenos Aires, Argentina. He has worked as an attached professor, project
leader, and international manager, and currently occupies a position as a solutions architect in R&D
for FamilySearch Int. Europe. Based in Finland, he has published a variety of books according to his
many interests, from novels and fiction to software engineering. His latest book, Vue 3 Applications
and Design Patterns, will be published by Packt in 2023.

Suraj Bobade is an experienced software professional, currently located in Pune, India. He completed
a B.Tech in computer science from Walchand College of Engineering, Sangli.
He is passionate about software development with a keen interest in product management. He builds
user-first feature-rich products while driving critical software and product design decisions.
Go has been his go-to choice for building the microservice backend and prototypes. Considering the
simplicity and increasing adoption by the open source community, Suraj is optimistic that readers of
this book will learn in-demand skills.

Tan Quach is an experienced software engineer with a career spanning over 25 years and exotic locations
such as London, Canada, Bermuda, and Spain. He has worked with a wide variety of languages and
technologies for companies such as Deutsche Bank, Merrill Lynch, and Progress Software, and loves
diving deep into experimenting with new ones.
Tan’s first foray into Go began in 2017 with a proof-of-concept application built over a weekend and
productionized and released 3 weeks later. Since then, Go has been his language of choice when
starting any project.
When he can be torn away from the keyboard, Tan enjoys cooking meat over hot coals and open
flames and making his own charcuterie.

Nima Yahyazadeh is a Software Architect focused on developing solutions for startups. He has years
of experience developing distributed and cloud-native solutions. He has worked at medium to large
corporations such as Amazon Web Services, Intel, and Appian. He is currently the founder and CEO
of a consulting company, Lenzo LLC, that has helped more than five startups to architect, develop, and
deliver exciting features to their customers. He is passionate about AWS, Kubernetes, Elasticsearch,
Kafka, and Golang.
Table of Contents
Prefacexi

Part 1: Building a Golang Backend


1
Building the Database and Model 3
Technical requirements 4 Using sqlc 11
Installing Docker 4 Setting up the database 13
Setting up Postgres 5 Generating CRUD with sqlc 14
Designing the database 6 Building the makefile 21
Installing sqlc 9 Summary22

2
Application Logging 23
Technical requirements 23 Writing log messages to the
Exploring Go standard logging 23 logging server 30
Using golog 26 Configuring multiple outputs 33
Local logging 29 Summary36

3
Application Metrics and Tracing 37
Technical requirements 37 The OpenTelemetry APIs and SDK 39
Understanding OpenTelemetry 38 Tracing applications 40
viii Table of Contents

Installing Jaeger 41 Adding metrics using Prometheus 50


Adding metrics using Prometheus 52
Integrating the Jaeger SDK 43
Integration with Jaeger 44 Running docker-compose 58
Summary60

Part 2: Serving Web Content


4
Serving and Embedding HTML Content 63
Technical requirements 63 Rendering static content 72
Handling HTTP functions and Rendering dynamic content 74
Gorilla Mux 63 Using Go embed to bundle
Hello, World with defaults 64 your content 78
Building on the basics with Gorilla Mux 67 Summary83

5
Securing the Backend and Middleware 85
Technical requirements 85 Adding cookies and sessions 92
Adding authentication 86 Cookies and session handling 92
Creating our dummy user 88 Storing session information 95
Authenticating a user 89 Using Redis for a session  95

Adding middleware 90 Summary97


Basic middleware 90

6
Moving to API-First 99
Technical requirements 99 Exposing our REST API 102
Structuring an application 100 Cross-Origin Resource Sharing (CORS) 104
Defining packages 100 JSON middleware 105
Session middleware 107
Table of Contents ix

Converting to and from JSON 108 Using JSONError 112


Defining request model 109 Using JSONMessage 114
Defining a response model 111
Summary115
Reporting errors with JSON 112

Part 3: Single-Page Apps with Vue and Go


7
Frontend Frameworks 119
Technical requirements 119 Application and components 124
Server-side rendering versus single- Login page using Vue 124
page apps 119 Using Vite 127
Introducing React, Vue, and more 120 Using Vue Router to move around 130
React120 Routing the login page 132
Svelte121
Vue121 Summary133

Creating a Vue app 124

8
Frontend Libraries 135
Technical requirements 135 Setting up Buefy 141
Understanding Vuetify 136 UI components 142
Setting up Vuetify 136 Validating data entry with Vuelidate 143
Using UI components 137 Better input handling with Cleave.JS 148
Understanding Buefy 139 Summary150
Bulma sample 140

9
Tailwind, Middleware, and CORS 151
Technical requirements 151 Introducing Tailwind 151
x Table of Contents

Creating a new Tailwind and Vite project 153 CORS for secure applications 163
Consuming your Golang APIs 156 Creating Vue middleware 166
Summary168

10
Session Management 169
Technical requirements 169 Navigation guards 179
Session management and JWTs 169 Defaults and error pages 182
What’s a JWT? 170 Summary182
(Re)introducing Vue Router 178

Part 4: Release and Deployment


11
Feature Flags 185
Technical requirements 185 The high-level architecture of
An introduction to feature flags 186 feature flags 190
Feature flag configuration 186 Integration of the feature flag 190
Use cases for using feature flags 188 Web application 191
Microservice integration 193
Installing the feature flag server 188
Summary198

12
Building Continuous Integration 199
Technical requirements 199 Dockerfile210
Importance of CI 200 GitHub Packages 210
Setting up GitHub 200 Publishing to GitHub Packages 212
GitHub Actions 204 Pulling from GitHub Packages 216

Publishing Docker images 209 Summary217


Table of Contents xi

13
Dockerizing an Application 219
Technical requirements 219 Running images as containers 227
Installing Docker 219 Building and packaging images 229
Using Docker 221 Docker Compose 233
Docker images 222 Summary235

14
Cloud Deployment 237
Technical requirements 237 The init command 245
AWS refresher 238 The plan command 247
The destroy command 250
Amazon Elastic Compute Cloud 239
Virtual Private Cloud 240 Coding in Terraform 252
Database storage 241 Providers252
Elastic Container Service 242
AWS tools 242
Terraform examples 254
Pulling from GitHub Packages 255
Understanding and using Terraform 243 AWS EC2 setup 257
What is Terraform? 244 Deploying to ECS with a load balancer 261
Installing Terraform 244
Summary269
Terraform basic commands 245

Index271

Other Books You May Enjoy 274


Preface
Full-Stack Web Development with Go walks you through creating and developing a complete modern
web service, from authn/authz, interop, server-side rendering, and databases, to modern frontend
frameworks with Tailwind and Go-powered APIs, complete with step-by-step explanations of essential
concepts, practical examples, and self-assessment questions. The book will begin by looking at how
to structure the app and look at the relevant pieces, such as database and security, before integrating
all the different parts together to build a complete web product.

Who this book is for


Developers with experience of a mixture of frontend and backend development will be able to put
their knowledge to work with the practical guide in this book. The book will give them the know-how
to glue together their skills and allow them to build a complete stack web application.

What this book covers


Chapter 1, Building the Database and Model, looks at building our database for our sample application.
We will also explore different ways to communicate with databases using Golang.
Chapter 2, Application Logging, considers how designing an application requires examining it internally
without going through reams of code, and the only way to do this is by logging. We will learn how
to do this by running a centralized logger that will host all of our logging information. We will also
learn how to log from inside our application.
Chapter 3, Application Metrics and Tracing, considers how having logging applied inside our application
will assist in troubleshooting issues when the application is running. The other thing that helps is
information about the interaction of the different components inside our application, which we will
also look at in this chapter.
Chapter 4, Serving and Embedding HTML Content, sees us begin work on implementing the REST
endpoints needed for our financial application. The first version of the app will show simple content
rendered by the backend.
Chapter 5, Securing the Backend and Middleware, notes that we need to secure our application so
that we can ensure users see only the data that they should. We will discuss some of the ways we can
protect our endpoints using cookies, session management, and other types of middleware available.
Chapter 6, Moving to API - First, starts by laying the groundwork for frontend applications to consume
our data. We’ll introduce marshaling/unmarshaling data into custom structures and see how to set
up JSON-consuming endpoints and use cURL to verify.
xiv Preface

Chapter 7, Frontend Frameworks, discusses the state of web development, introduces the React and
Vue frameworks, and sees us employ them to create a simple app that's similar to our previous one.
Chapter 8, Frontend Libraries, examines how to leverage tools and libraries to help us, as full stack
developers, work fast!
Chapter 9, Tailwind, Middleware, and CORS, has us securing our app and getting it talking to our
Go-powered backend.
Chapter 10, Session Management, focuses on session management while introducing state management
with Vuex and how to structure apps based on user permissions.
Chapter 11, Feature Flags, introduces feature flags (sometimes called feature toggles) as a technique
deployed to enable/disable certain features of the application as required, depending on a given
condition. For example, if a newly deployed application containing a new feature has a bug and we
know it will take time for the bug to be fixed, the decision can be made to turn off the feature without
deploying any new code to do so.
Chapter 12, Building Continuous Integration, notes that while building applications is a big part of the
puzzle, we need to be sure that what the team builds can be validated and tested properly. This is where
continuous integration comes in. Having a proper continuous integration process is super important
to ensure that everything deployed to production has been tested, verified, and checked securely.
Chapter 13, Dockerizing an Application, notes that while developing an application is one side of the coin,
the other side is to make sure that it can be deployed and used by our end user. To make deployment
simpler, we can package applications such that they can be run inside a container. Operationally, this
allows applications to be deployed in the cloud from anywhere.
Chapter 14, Cloud Deployment, shows how deploying applications to a cloud environment is the last
step in delivering features for the end user to use. Cloud deployment is complex and sometimes quite
specific to particular cloud vendors. In this chapter, we will focus on deploying applications into the
AWS cloud infrastructure.

To get the most out of this book


You will need the following installed on your computer: Node.js (version 16 or above), Docker (or
Docker Desktop), the Golang compiler, and an IDE such as GoLand or VSCode.

Software/hardware covered in the book Operating system requirements


Golang 1.16 and above macOS, Linux, Windows (via WSL2)
Docker macOS, Linux, Windows (via WSL2)
An IDE (VSCode or GoLand) macOS, Linux, Windows
Preface xv

If you are using the digital version of this book, we advise you to type the code yourself or access
the code from the book’s GitHub repository (a link is available in the next section). Doing so will
help you avoid any potential errors related to the copying and pasting of code.

Download the example code files


You can download the example code files for this book from GitHub at https://github.com/
PacktPublishing/Full-Stack-Web-Development-with-Go. If there’s an update to
the code, it will be updated in the GitHub repository.

Download the color images


We also provide a PDF file that has color images of the screenshots and diagrams used in this book.
You can download it here: https://packt.link/EO4sG.

Conventions used
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file
extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “We call
next.ServerHTTP(http.ResponseWriter, *http.Request) to continue and indicate
successful handling of a request.”
A block of code is set as follows:

go func() {
...
s.SetAttributes(attribute.String(“sleep”, “done”))
s.SetAttributes(attribute.String(“go func”, “1”))
...
}()

Any command-line input or output is written as follows:

[INFO] 2021/11/26 21:11 This is an info message, with colors


(if the output is terminal)

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in
menus or dialog boxes appear in bold. Here is an example: “You will get a Login unsuccessful message.”
xvi Preface

Tips or important notes


Appear like this.

Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at customercare@
packtpub.com and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen.
If you have found a mistake in this book, we would be grateful if you would report this to us. Please
visit www.packtpub.com/support/errata and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would
be grateful if you would provide us with the location address or website name. Please contact us at
[email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you
are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts


Once you’ve read Full-Stack Web Development with Go, we’d love to hear your thoughts! Please click
here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering
excellent quality content.
Preface xvii

Download a free PDF copy of this book


Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere? Is your eBook
purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical
books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content
in your inbox daily
Follow these simple steps to get the benefits:

1. Scan the QR code or visit the link below

https://packt.link/free-ebook/9781803234199

2. Submit your proof of purchase


3. That’s it! We’ll send your free PDF and other benefits to your email directly
Part 1:
Building a Golang Backend

In Part 1, we will build the backend components for our sample application. We will build the database
with the models for the Go backend of our application. We will also build secure REST API endpoints
that will have logging and tracing functionalities.
This part includes the following chapters:

• Chapter 1, Building the Database and Model


• Chapter 2, Application Logging
• Chapter 3, Application Metrics and Tracing
1
Building the Database
and Model
In this chapter, we will design the database that our sample application will use. We will walk
through the design of the database and look at some of the tools that we are going to use to help us
on our database design journey. We will be using the Postgres database and will look at how to run
it locally using Docker. What is Docker? In simple terms, Docker is a tool that allows developers to
run a variety of applications such as the database, the HTTP server, system tools, and so on – locally
or in the cloud. Docker removes the need to install all the different dependencies required to use a
particular application such as a database, and it makes it easier to manage and maintain applications
than installing on bare metal in both local and cloud environments. This is possible using Docker
because it packages everything into a single file similar to how a compressed file contains different
files internally.
We will learn how to design a database that supports the features that we want to build, such as
the following:

• Creating an exercise
• Creating a workout plan
• Logging in to the system

We will also explore tools that will help in automatic code generation based on SQL queries, which reduces
the amount of database-related code that needs to be written to a large extent. Readers will learn to use
the tool to also auto-generate all the relevant CRUD operations without writing a single line of Go code.
In this chapter, we’ll be covering the following:

• Installing Docker
• Setting up Postgres
• Designing the database
4 Building the Database and Model

• Installing sqlc
• Using sqlc
• Setting up the database
• Generating CRUD with sqlc
• Building the makefile

Technical requirements
In this book, we will be using version 1.16 of the Go programming language, but you are free to use
later versions of Go, as the code will work without any changes. To make it easy, all the relevant files
explained in this chapter can be checked out at https://github.com/PacktPublishing/
Full-Stack-Web-Development-with-Go/tree/main/Chapter01. To work on the
sample code in this chapter, make sure you change the directory to Chapter 1 – Full-Stack-
Web-Development-with-Go/chapter1. If you are using Windows as a development machine,
use WSL2 to perform all the different operations explained in this chapter.

Installing Docker
In this book, we will be using Docker to do things such as running databases and executing database
tools, among others. You can install either Docker Desktop or Docker Engine. To understand more
about the difference between Docker Desktop and Engine, visit the following link: https://
docs.docker.com/desktop/linux/install/#differences-between-docker-
desktop-for-linux-and-docker-engine. The authors use Docker Engine in Linux and
Docker Desktop for Mac.
If you are installing Docker Desktop on your local machine, the following are the links for the different
operating systems:

• Windows – https://docs.docker.com/desktop/windows/install/
• Linux – https://docs.docker.com/desktop/linux/install/
• macOS – https://docs.docker.com/desktop/mac/install/

If you want to install Docker binaries, you can follow the following guide: https://docs.docker.
com/engine/install/binaries/.
Setting up Postgres 5

Setting up Postgres
The database we chose for the sample application is Postgres; we chose Postgres over other databases
because of the wide variety of open source tools available for building, configuring, and maintaining
Postgres. Postgres has been open source from version 1 since 1989 and it is used by big tech startups
worldwide. The project has a lot of community support in terms of tools and utilities, which makes it
easier to manage and maintain. The database is suitable for small all the way to big replicated data stores.
The easiest way to run it locally is to run it as a Docker container. First, use the following command
to run Postgres:

docker run --name test-postgres \


-e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres

The command will run postgres on port 5432; if by any chance you have other applications or
other Postgres instances listening to this port, the command will fail. If you need to run Postgres on a
different port, change the -p parameter (for example, -p 5555:5432) to a different port number.
If successful, you will see the container ID printed out. The ID will differ from what is shown here:

f7bdfb7d2c10c5f0c9227c9b0a720f21d3c7fa65907eb-
0c546b8f20f12621102

Check whether Postgres is up and running by using docker ps. The next thing to do is use the
psql-client tool to connect to Postgres to test it out. A list of the different Postgres client tools
available on different platforms can be found here: https://wiki.postgresql.org/wiki/
PostgreSQL_Clients.
We will use the standard postgres psql tool using Docker. Open another terminal and use the
following Docker command to run psql:

docker exec -it test-postgres psql -h localhost -p 5432 -U


postgres -d postgres

What we are doing is executing the psql command inside the running Postgres container. You will
see output such as the following, indicating that it has successfully connected to the Postgres database:

psql (12.3, server 14.5 (Debian 14.5-1.pgdg110+1))


WARNING: psql major version 12, server major version 14.
         Some psql features might not work.
Type "help" for help.

postgres=#
6 Building the Database and Model

On a successful connection, you will see the following output. Note that the warning message mentions
server major version 14 – this is to indicate that the server version is newer than the current psql
version as per the documentation (https://www.postgresql.org/docs/12/app-psql.
html). The psql client will work without any problem with the Postgres server:

psql (12.3, server 14.0 (Debian 14.0-1.pgdg110+1))


WARNING: psql major version 12, server major version 14.
         Some psql features might not work.
Type "help" for help.
postgres=#

Exit psql to go back to the command prompt by typing exit.


The following is some guidance on common errors when trying to connect to the database:

Error Message Description


psql: error: could not connect The password specified when running Postgres
to server: FATAL: password does not match with the password passed in
authentication failed for user using psql. Check the password.
“postgres”
psql: error: could not connect to server: could The IP address that you use to connect to Postgres
not connect to server: Host is unreachable is wrong.

With this, you have completed the local setup of Postgres and are now ready to start looking into
designing the database.

Designing the database


In this section, we will look at how to design the database to allow us to store information for the
fitness tracking application. The following screenshot shows a mockup of the application:
Designing the database 7

Figure 1.1 – Screenshot of the sample application

Looking at these functionalities, we will look at designing a database structure that will look like the
following entity relationship diagram:

Entity relationship diagram


An entity relationship diagram shows the relationships of entity sets stored in a database.
8 Building the Database and Model

Figure 1.2 – Entity relationship diagram of our fitness application

Let’s drill further into each table to understand the data that they contain:

Table Name Description


Users This table contains user information for login purposes. Passwords will be stored
as a hash, not plaintext.
Images This table contains images of exercises that users want to do. This table will store all
the exercise images that the user uploads.
Exercises This table contains the name of the exercise that the user wants to do. Users will
define what kind of exercise they want to do.
Sets This table contains the number of sets of each exercise that the user wants to do.
Workouts This table contains the workouts that the user wants to do. Users define a workout
as a combination of exercises with the number of sets that they want to do.
Installing sqlc 9

The trade-off we are making to store images in the database is to simplify the design; in reality, this
might not be suitable for bigger images and production. Now that we have defined the database
structure and understand what kind of data it will store, we need to look at how to implement it. One
of the major criteria that we want to focus on is to completely separate writing SQL from the code;
this way, we have a clear separation between the two, which will allow higher maintainability.

Installing sqlc
We have defined the database structure so now it’s time to talk a bit more about the tool that we are
going to be using called sqlc. sqlc is an open source tool that generates type-safe code from SQL; this
allows developers to focus on writing SQL and leave the Go code to sqlc. This reduces the development
time, as sqlc takes care of the mundane coding of queries and types.
The tool is available at https://github.com/kyleconroy/sqlc. The tool helps developers
focus on writing the SQL code that is needed for the application and it will generate all the relevant code
needed for the application. This way, developers will be using pure Go code for database operations.
The separation is clean and easily trackable.
The following diagram shows the flow that developers normally adopt when using the tool at a high level.

Figure 1.3 – Flow to use sqlc to generate Go code

All SQL code will be written in .sql files, which will be read and converted by the sqlc tool into the
different Go code.
10 Building the Database and Model

Download and install SQL binary by using the following command:

go install github.com/kyleconroy/sqlc/cmd/sqlc@latest

Make sure your path includes the GOPATH/bin directory – for example, in our case, our path looks
like the following:

…:/snap/bin:/home/nanik/goroot/go1.16.15/go/bin:/home/nanik/go/
bin

If you don’t have GOPATH as part of the PATH environment variable, then you can use the following
command to run sqlc:

$GOPATH/bin/sqlc
Usage:
  sqlc [command]

Available Commands:
  compile     Statically check SQL for syntax and type
  errors
  completion  Generate the autocompletion script for the
  specified shell
  generate    Generate Go code from SQL
  help        Help about any command
  init        Create an empty sqlc.yaml settings file
  upload      Upload the schema, queries, and configuration
  for this project
  version     Print the sqlc version number

Flags:
  -x, --experimental   enable experimental features (default:
false)
  -f, --file string    specify an alternate config file
(default: sqlc.yaml)
  -h, --help           help for sqlc

Use "sqlc [command] --help" for more information about a command.


At the time of writing, the latest version of sqlc is v1.13.0.
Other documents randomly have
different content
Before going on to the few additional conditions and combinations
that complete the algebra, let’s study some analogies that will make
clear the AND/OR principles of operation. We can think of AND as
two bridges in sequence over two rivers. We can reach our
destination only if both bridges are working. However, suppose there
are two parallel bridges and only one river. We can then cross if
either or both of the bridges is working. A closer example is that of
electrical switches. Current will flow through our AND circuit if—and
only if—both switches are closed. When the switches are in parallel
—an OR circuit—current will flow if either, or both, are closed.
The truth tables resemble the bridge or switch arrangements. We
can proceed across the line of 1’s and 0’s in the first table only if
both switches are closed. The symbol 1 means that the switch is
closed, so we can cross only the bottom line. In the second table,
we are told we can proceed across the line if either switch is closed.
Thus we can cross lines 2, 3, and 4. We can use many symbols in
our two-valued system.
Symbol
Bridge No
Bridge
Power No
Power
1 0
True False
A little imagination suggests a logic computer of sorts with one
switch, a battery, and a light bulb. Suppose we turn on the switch
when we drive into our garage. A light in the hallway then indicates
that the car is available. By using two switches we can indicate that
a second car is also in the garage; or that either of them is, simply
by choosing between AND logic and OR logic. Childish as this seems,
it is the principle of even our most complex thinking processes. You
will remember that the brain is considered a digital computer, since
neurons can only be on or off. All it takes is 10 billion neuron
switches!
Remington Rand UNIVAC

AND and OR gates in series. Switches 1 and 2, plus 3 or 4, are needed to light the
bulb.

In addition to the conjunctives AND and OR, Boolean algebra


makes use of the principle of negation. This is graphically illustrated
thus:

Original Negation
A Ā
1 0
0 1
The negation device used in computer circuitry is called an inverter,
since it changes its input from a 1 to a 0, or vice versa. The
usefulness of such an element is obvious when we remember the
computer trick of subtracting by adding complements. The inverter
circuit used with a code like the excess-3 readily forms these
complements.
Further sophistication of the basic Boolean forms leads to units
other than the AND and OR gates. Possible are NOT, NOR, and
exclusive-OR forms. In the latter, there is an output if one and only
one input is present. The NOR circuit is interesting in that it was
made possible with the introduction of the transistor; the vacuum
tube does not permit this configuration.
Computer Control Co.

The functions of two binary variables.

Present-day symbolic logic is not the pure Boolean as presented


back in 1854. Boole’s OR was the exclusive, one and only one, type.
Today the logician generally assumes the either-or connotation. The
logic has also been amplified, using the commutative, associative,
and distributive laws much like those of conventional algebra. We
are indebted to De Morgan for most of this work, showing that A
and B equals B and A; A and (A and B) equals (A and B) and A; and
so on. While these seem intuitively true, the implications are
nonetheless of great importance both in pure logic and its practical
use in circuitry.
A graphic representation of the metamorphosis from symbolic to
actual implementation of Boolean equations follows: The implication
of importance is that logic applies equally well whether we are
making a qualifying statement such as “A man must have strength
and courage to win a barehanded fight with a lion,” or wiring a
defensive missile so that it will fire only if a target is within range
and is unfriendly.
In the early period of computer design the engineer was faced
with the problem of building his own switches and gates. Today
many companies offer complete “packaged” components—AND
gates, OR gates, and the other configurations. This is the modular
approach to building a computer and the advantages are obvious.
The designer can treat the components simply as “black boxes” that
will respond in a prescribed way to certain input conditions. If he
wants, the engineer can go a step further and buy a ready-built logic
panel consisting of many components of different types. All he need
do to form various logic circuits is to interconnect the proper
components with plug-in leads. This brings us to the point of
learning what we can do with these clever gates and switches now
that we have them available and know something about the way
they work.
We talked about the computer adder circuit earlier in this chapter.
It is made up of two half-adders, remember, with perhaps an
additional OR gate, flip-flop, etc. Each half-adder is composed of two
AND gates and an OR gate. So we have put together several
basically simple parts and the result is a piece of equipment that will
perform addition at a rate to make our heads swim.
There are other things we can do with Boolean logic besides
arithmetic. A few gates will actuate a warning signal in a factory in
case either of two ventilators is closed and the temperature goes up
beyond a safe point; or in case both vents are closed at the same
time. We can build a logic computer that will tell us when three of
four assembly lines are shut down at the same time, and also which
three they are.
General Electric Co., Computer Dept.

Electronic computers are built up of many “building blocks” like this one.

Logic problems abound in puzzle books, and many of us spend


sleepless nights trying to solve them in our heads. An example is the
“Farnsworth Car Pool” problem. Rita Farnsworth asks her husband if
someone in his car pool can drive for him tomorrow so that she may
use the car. Joe Farnsworth replies, “Well, when I asked Pete if he
would take my turn he said he was flying to Kansas City today, but
he’d be glad to drive tomorrow if he didn’t have to stay over and
that his wife has been staying home lately and he will drive her car if
she doesn’t go to work. Oscar said that since his own car is due back
from the garage tomorrow he can drive it even if his wife does use
hers, provided the garage gets his back to him. But if this cold of
mine gets any worse I’m going to stay home even if those fellows
have to walk to work, so you can certainly have the car if I don’t go
to work.” This dialogue of Joe’s confuses Rita and most of us are in
the same state.
Autonetics Division, North American Aviation, Inc.

Testing an assembled digital computer.

The instruction manual for BRAINIAC, a do-it-yourself computer


that sells for a few dollars, gives a simple wiring diagram for solving
Rita’s dilemma. Electrically the problem breaks down into three OR
gates and one AND gate. All Mrs. Farnsworth has to do is set in the
conditions and watch the indicator light. If it glows, she gets the car!
These are of course simple tasks and it might pay to hire a man to
operate the vents, and ride to work on the bus when the car pool
got complicated. But even with relatively few variables, decision-
making can quickly become a task requiring a digital computer
operating with Boolean logic principles.
Science Materials Center
Problem in logic reduced to electrical circuits.

The Smith-Jones-Robinson type of problem in which we must find


who does what and lives where is tougher than the car pool—tough
enough that it is sometimes used in aptitude tests. Lewis Carroll
carried this form of logical puzzler to complicated extremes involving
not just three variables but a dozen. To show how difficult such a
problem is, an IBM 704 required four minutes to solve a Carroll
puzzle as to whether any magistrates indulge in snuff-taking. The
computer did it the easy way, without printing out a complete “truth
table” for the problem—the method a man would have to use to
investigate all the combinations of variables. This job would have
taken 13 hours! While the question of the use of snuff is perhaps
important only to tobacconists and puzzle-makers, our technical
world today does encounter similar problems which are not practical
of solution without a high-speed computer. A recent hypothetical
case discussed in an electronics journal illustrates this well.
A missile system engineer has the problem of modifying a Nike-
Ajax launching site so that it can be used by the new Nike-Hercules
missile. He must put in switching equipment so that a remote control
center can choose either an Ajax system, or one of six Hercules
systems. To complicate things, the newer Hercules can be equipped
with any of three different warheads and fly either of two different
missions. When someone at the control center pushes a button, the
computer must know immediately which if any of the missiles are in
acceptable condition to be fired.
This doesn’t sound like too big a problem. However, since there
are twelve on-off signals to be considered, and since each has two
possible states, there are 4,096 possible missile combinations. Not
all these are probable, of course, but there is still sufficient variation
to make it humanly impossible to check all of them and close a firing
switch in the split second the control center can allow.
The answer lies in putting Boolean algebra on the job, with a
system of gates and inverters capable of juggling the multiplicity of
combinations. Then when the word comes requesting a missile
launch, the computer handles the job in microseconds without
straining itself unduly.
Just as Shannon pointed out twenty-five years ago, switching
philosophy can be explained best by Boolean logic, and the method
can be used not only to implement a particular circuit, but also to
actually design the circuit in the first place. A simple example of this
can be shown with the easy-to-understand AND and OR gates. A
technician experimenting with an AND gate finds that if he simply
reverses the direction of current, he changes the gate into an OR
gate. This might come as a surprise to him if he is unfamiliar with
Boolean logic, but a logician with no understanding of electrical
circuits could predict the result simply by studying the truth tables
for AND and OR.
Reversing the polarity is equivalent to changing a 1 to a 0 and vice
versa. If we do this in the AND gate table, we should not be
surprised to find that the result looks exactly like the OR table! It
acts like it too, as the technician found out.
Boolean logic techniques can be applied to existing circuits to
improve and/or simplify them. Problems as simple as wiring a light
so that it can be turned on and off from two or more locations, and
those as complex as automating a factory, yield readily to the simple
rules George Boole laid down more than a hundred years ago.
Watching a high-speed electronic digital computer solve
mathematical problems, or operate an industrial control system with
speed and accuracy impossible for human monitors, it is difficult to
believe that the whole thing hinges on something as simple as
switches that must be either open or closed. If Leibnitz were alive,
he could well take this as proof of his contention that there was
cosmological significance in the concept of 1 and 0. Maybe there is,
after all!
Industrial Electronic Engineering & Maintenance

“Luckily I brought along a ‘loaner’ for you to use while I repair your computer.”
“Whatever that be which thinks, understands, wills, and
acts, it is something celestial and divine.”

—Cicero
6: The Electronic Brain

The idea of a man-made “brain” is far from being new. Back in


1851, Dr. Alfred Smee of England proposed a machine made up of
logic circuits and memory devices which would be able to answer
any questions it was asked. Doctor Smee was a surgeon, keenly
interested in the processes of the mind. Another Britisher, H. G.
Wells, wrote a book called Giant Brain in 1938 which proposed much
the same thing: a machine with all knowledge pumped into it, and
capable of feeding back answers to all problems.
If it was logical to credit “human” characteristics to the machines
man contrived, the next step then was to endow the machine with
the worst of these attributes. In works including Butler’s Erewhon,
the diabolical aspects of an intelligent machine are discussed. The
Lionel Britton play, Brain, produced in 1930, shows the machine
gradually becoming the master of the race. A more physical danger
from the artificial brain is the natural result of giving it a body as
well. We have already mentioned Čapek’s R.U.R. and the Ambrose
Bierce story about a chess-playing robot without a built-in sense of
humor, who strangles the human being who beats him at a game.
With these stories as models, other writers have turned out huge
quantities of work involving mechanical brains capable of all sorts of
mischief. Most of these authors were not as well-grounded
scientifically as the pioneering Dr. Smee who admitted sadly that his
“brain” would indeed be a giant, covering an area about the size of
London!
The idea of the giant brain was given new lease by the early
electronic computers that began appearing in the 1940’s. These
vacuum-tube and mechanical-relay machines with their rows of
cabinets and countless winking lights were seized on gleefully by
contemporary writers, and the “brain” stories multiplied gaudily.
Many of the acts of these fictional machines were monstrous, and
most of the stories were calculated to make scientists ill. Many of
these gentlemen said the only correct part of the name “giant brain”
was the adjective; that actually the machine was an idiot savant, a
sort of high-speed moron. This opinion notwithstanding, the name
stuck. One scholar says that while it is regrettable that such a vulgar
term has become so popular, it is hardly worth while campaigning
against its use.
An amusing contemporary fiction story describes an angry crowd
storming a laboratory housing a “giant brain,” only to be placated by
a calm, sensibly arguing scientist. The mob dispersed, he goes back
inside and reports his success to the machine. The “brain” is
pleased, and issues him his next order.
“Nonsense!” scoff most computer people. A recent text on
operation of the digital computer says, “Where performance
comparable with that of the human brain is concerned, man need
have little fear that he will ever be replaced by this machine. It
cannot think in any way comparable to a human being.” Note the
cautious use of “little,” however.
Another authority admits that the logic machines of the monk
Ramón Lull were very clever in their proof of God’s existence, but
points out that the monk who invented them was far cleverer since
no computer has ever invented a monk who could prove anything at
all!
The first wave of ridiculous predictions has run its course and
been followed by loud refutations. Now there is a third period of
calmer and more sensible approach. A growing proportion of
scientists take a middle-of-the-stream attitude, weighing both sides
of the case for the computer, yet some read like science fiction.
Cyberneticist Norbert Wiener, more scientist than fictioneer,
professes to foresee computerized robots taking over from their
masters, much as a Greek slave once did. Mathematician John
Williams of the Rand Corporation thinks that computers can, and
possibly will, become more intelligent than men.
Equally reputable scientists take the opposite view. Neuro-
physiologist Gerhard Werner of Cornell Medical College doubts that
computers can ever match the creativity of man. He seems to share
the majority view today, though many who agree will add, tongue in
cheek, that perhaps we’d better keep one hand on the wall plug just
in case.
Thinking Defined
The first step in deciding whether or not the computer thinks is to
define thinking. Far from being a simple task, this definition turns
out to be a slippery thing. In fact, if the computer has done no more
than demand this sort of reappraisal of the human brain’s working, it
has justified its existence. Webster lists meanings for “think” under
two headings, for the transitive and intransitive forms of the verb.
These meanings, respectively, start out with “To form in the mind,”
and “To exercise the powers of judgment ... to reflect for the
purpose of reaching a conclusion.”
Even a fairly simple computer would seem to qualify as a thinker
by these yardsticks. The storing of data in a computer memory may
be analogous to forming in the mind, and manipulating numbers to
find a square root certainly calls for some sort of judgment. Learning
is a part of thinking, and computers are proving that they can learn
—or at least be taught. Recall of this learning from the memory to
solve problems is also a part of the thinking process, and again the
computer demonstrates this capability.
One early psychological approach to the man-versus-machine
debate was that of classifying living and nonliving things. In Outline
of Psychology, the Englishman William McDougall lists seven
attributes of life. Six of these describe “goal-seeking” qualities; the
seventh refers to the ability to learn. In general, psychologist
McDougall felt that purposive behavior was the key to the living
organism. Thus any computer that is purposive—and any
commercial model had better be!—is alive, in McDougall’s view. A
restating of the division between man and machine is obviously in
order.
Dr. W. Ross Ashby, a British scientist now working at the University
of Illinois, defines intelligence as “appropriate selection” and goal-
seeking as the intelligent process par excellence, whether the
selecting is done by a human being or by a machine. Ashby does
split off the “non goal-seeking” processes occurring in the human
brain as a distinct class: “natural” processes neither good nor bad in
themselves and resulting from man’s environment and his evolution.
Intelligence, to Ashby, who long ago demonstrated a mechanical
“homeostat” which showed purposive behavior, is the utilization of
information by highly efficient processing to achieve a high intensity
of appropriate selection. Intelligent is as intelligent does, no
distinction being made as to man or machine. Humanoid and
artificial would thus be meaningless words for describing a computer.
Ashby makes another important point in that the intelligence of a
brain or a machine cannot exceed what has been put into it, unless
we admit the workings of magic. Ashby’s beliefs are echoed in a way
by scientist Oliver Selfridge of Lincoln Laboratory. Asked if a machine
can think, Selfridge says, “Certainly; although the machine’s
intelligence has an elusive, unnatural quality.”
“Think, Hell, COMPUTE!” reads the sign on the wall of a computer
laboratory. But much of our thinking, perhaps some of the “natural”
processes of our brains, doesn’t seem to fit into computational
patterns. That part of our thinking, the part that includes looking at
pretty girls, for example, will probably remain peculiar to the human
brain.
The Human Brain
Mundy Peale, president of Republic Aviation Corporation,
addressing a committee studying the future of manned aircraft, had
this to say:
Until someone builds, for $100 or less with unskilled labor, a computer no larger
than a grapefruit, requiring only a tenth of a volt of electricity, yet capable of
digesting and transmitting incoming data in a fraction of a second and storing
10,000 times as much data as today’s largest computers, the pilots of today have
nothing to worry about.

The human brain is obviously a thing of amazing complexity and


fantastic ability. Packed into the volume Mr. Peale described are
some 10 billion neurons, the nerve cells that seem to be the key to
the operation of our minds. Hooked up like some ultra-complicated
switchboard, the network of interconnections stores an estimated
200,000,000,000,000,000,000 bits of information during a lifetime!
By comparison, today’s most advanced computers do seem
pathetically unimpressive.
We have discussed both analog and digital computers in preceding
chapters. It is interesting to find that the human brain is basically a
digital type, though it does have analog overtones as well. Each of
the neurons is actually a switch operated by an electric current on a
go/no-go, all-or-nothing basis. Thus a neuron is not partly on or
partly off. If the electrical impulse exceeds a certain “threshold”
value, the switch operates.
Tied to the neurons are axons, the long “wires” that carry the
input and output. The axons bring messages from the body’s
sensors to the neurons, and the output to other neurons or to the
muscles and other control functions. This grapefruit-size collection of
electrochemical components thus stores our memories and effects
the operation we call thinking.
Since brain impulses are electrical in nature, we speak of them in
electrical terms. The impulses have an associated potential of 50
millivolts, that is, fifty thousandths of a volt. The entire brain
dissipates about 10 watts, so that each individual neuron requires
only a billionth of a watt of power. This amount is far less than that
of analogous computer parts.
A neuron may take a ten-thousandth of a second to respond to a
stimulus. This seemingly rapid operation time turns out to be far
slower than present-day computer switches, but the brain makes up
for this by being a “parallel operation” system. This means that
many different connections are being made simultaneously in
different branches, rather than being sequential, or a series of
separate actions.
Packaging 10 billion parts in a volume the size of a grapefruit is a
capability the computer designer admires wistfully. Since the brain
has a volume of about 1,000 cubic centimeters, 10 million neurons
fit into a space of one cubic centimeter! A trillion would fit in one
cubic foot, and man-made machines with even a million components
per cubic foot are news today.
Even when we are resting, with our eyes closed, a kind of stand-
by current known as the alpha rhythm is measurable in our brains.
This current, which has a frequency of about 10 cycles per second,
changes when we see or feel something, or when we exercise the
power of recall. It disappears when we sleep soundly, and is
analogous to the operating current in a computer. Also, there is
“power” available locally at the neurons to “amplify” weak signals
sufficiently to trigger off following branches of neurons.
Philosophers have proposed two general concepts of the human
brain and how it functions. The a priori theory presupposes a certain
amount of “wired-in” knowledge: instincts, ideals, and so on. The
other theory, that of the tabula rasa or clean slate new brain, argues
that each of us organizes an essentially random net of nerves into
ordered intelligence. Both theories are being investigated with
computers, and as a result light is beginning to be shed on the
workings of our brains.

The Upjohn Company, Ezra Stoller Associates Photo


“A moment at a concert” is diagrammed by brain model, showing eyes, ears,
nerves, and structures analogous to brain. Picture at top represents perception.

There is another division of philosophical thought in the


mechanistic versus elan vital argument. In other words, is the entire
mind to be found in its constituent parts, or is there an intangible
extra something that really breathes life into us? Whatever the
correct concept, the brain does record impressions it can later recall.
No one yet knows just how this is done, but several theories have
been advanced. One of these describes a “chain circuit” set up in a
neuron network by messages from the body’s sensors. This circuit,
once started, continues to circle through the brain and is on tap
whenever that particular experience needs to be recalled. The term
“reverberate” is used in connection with this kind of memory,
seeming to be a good scientific basis for the poetic “echoes of the
past.” Reverberation circuits also provide the memory for some
computers.
Among other explanations of memory is that of conditioning the
neurons to operate more “easily,” so that certain paths are readily
traversed by brain impulses. This could be effected by chemical
changes locally, and such a technique too is used in computers.
However the brain accomplishes its job, it is certain that it evolved
in its present form as a result of the environment its cells have had
to function in for billions of years. Its prime purpose has been one of
survival, and for this reason some argue that it is not particularly
well adapted to abstract reasoning. Although the brain can do a wide
variety of things from dreaming to picking out one single voice amid
the hubbub of noise at a social gathering—a phenomenon scientists
have given the descriptive name of “cocktail party effect”—men like
Ashby consider it a very inflexible piece of equipment not well suited
to pure logic. As a test of your brain as a logical device, consider the
following problem from the Litton Industries “Problematical
Recreations.”
If Sara shouldn’t, then Wanda would. It is impossible that the statements: “Sara
should” and “Camille couldn’t” can both be true at the same time. If Wanda could,
then Sara should and Camille could. Therefore Camille could. Is this conclusion
valid?

If your head starts to swim, you are not alone. Very few humans
solve such problems easily. Interestingly, those who do, make good
computer programmers.
The Computer’s Brain
Just as we have an anthropomorphic God, many people have done
their best to endow the computer with human characteristics. Not
only in fiction but also in real life, the electronic brains have been
described as neurotic and frustrated on occasion, and also as being
afraid and even having morning sickness! A salesman for a line of
computers was asked to explain in understandable terms the
difference between two computers whose specifications confused a
customer. “Let’s put it this way,” the salesman said, “The 740 thinks
the 690 is a moron!”
We can begin to investigate the question of computer intelligence
by again looking up a definition. The word “compute” means literally
to think, or reckon, with. Early computers such as counting sticks,
the abacus, and the adding machine are obviously something man
thinks with. Even though we may know the multiplication tables, we
find it easier and safer to use a mechanical device to remember and
even to perform operations for us.
These homely devices do not possess sufficient “intelligence” to
raise any fears in our minds. The abacus, for example, displays only
what we might charitably call the property of memory. It has a
certain number of rows, each row with a fixed number of beads.
While it is not fallible, as is the human who uses it, it is far more
limited in scope. All it can ever do is help us to add or subtract, and
if we are clever, to multiply, divide, do square roots, and so on. If we
are looking for purposive behavior in computing machines, it is only
when we get to the adding machine that a glimmer appears. When a
problem is set in and the proper button pushed, this device is
compelled to go through the gear-whirring or whatever required to
return it to a state of equilibrium with its problem solved.
So far we might facetiously describe the difference in the goal-
seeking characteristics of man and machine by recalling that man
seeks lofty goals like climbing mountains simply because they are
there, while the computer seeks its goal much like the steel ball in
the pinball machine, impelled by gravity and the built-in springs and
chutes of the device. When we come to a more advanced computer,
however, we begin to have difficulty in assessing characteristics. For
the JOHNNIAC, built by Rand and named for John von Neumann,
can prove the propositions in the Principia Mathematica of
Whitehead and Russell. It can also “learn” to play a mediocre game
of chess.
If we investigate the workings of a digital computer, we find much
to remind us of the human brain. First is the obvious similarity of on-
off, yes-no operation. This implies a power source, usually electrical,
and a number of two-position switches. The over-all configuration of
the classic computer resembles, in principal if not physical
appearance, that of the human brain and its accessories.
As we have learned, the electronic computer has an input section,
a control, an arithmetic (or logic) section, a memory, and an output.
Looking into the arithmetic and memory sections, we find a number
of comparisons with the brain. The computer uses power, far more
than the brain. A single transistor, which forms only part of a neuron,
may use a tenth of a watt; the brain is ahead on this score by a
factor of millions to one.
Electronic switches have an advantage over the neuron in that
they are much faster acting. So fast have they become that
engineers have had to coin new terms like nanosecond and
picosecond, for a billionth and a trillionth of a second. Thus, the
computer’s individual elements are perhaps 100,000 times faster
than those of the brain.
There is no computer in existence with the equivalent of 10 billion
neurons. One ambitious system of computers does use half a million
transistors, plus many other parts, but even these relatively few
would not fit under a size 7-1/2 hat. One advanced technique, using
a “2-D” metal film circuitry immersed in liquid helium for
supercooling, hopefully will yield a packaging density of about 3-1/2
million parts per cubic foot in comparison with the brain’s trillion-part
density.
We have mentioned the computer memory that included the
“delay line,” remindful of the “chain circuit” in the brain. Electrical
impulses were converted to acoustic signals in mercury, traversed
the mercury, and were reconverted to electrical impulses. Early
memory storage systems were “serial” in nature, like those stored on
a tape reel. To find one bit of information required searching the
whole reel. Now random-access methods are being used with
memory core storage systems so wired that any one bit of
information can be reached in about the same amount of time. This
magnetic core memory stores information as a magnetic field, again
analogous to a memory theory for the human brain except that the
neuron is thought to undergo a chemical rather than magnetic
change.
General Electric Co., Computer Dept.

Tiny ferrite cores like these make up the memory of some computers. Each core
stores one “bit” of information.

Until recently, computers have been primarily sequential, or


serially operating, machines. As pointed out earlier, the brain
operates in parallel and makes up for its slower operating individual
parts in this way. Designers are now working on parallel operation
for computers, an improvement that may be even more important
than random-access memory.
Bionics
It is obvious that while there are many differences in the brain and
the computer there are also many striking similarities. These
similarities have given rise to the computer-age science of “bionics.”
A coinage of Major J. E. Steele of the Air Force’s Wright Air
Development Center, bionics means applying knowledge of biology
and biological techniques to the design of electronic devices and
systems. The Air Force and other groups are conducting broad
research programs in this field.
As an indication of the scope of bionics, Dr. Steele himself is a
flight surgeon, primarily trained as neurologist and psychiatrist, with
graduate work in electronics and mathematics. Those engaged in
bionics research include mathematicians, physical scientists,
embryologists, philosophers, neurophysiologists, psychologists, plus
scientists and engineers in the more generally thought of computer
fields of electronics and other engineering disciplines.
A recent report from M.I.T. is indicative of the type of work being
done: “What the Frog’s Eyes Tell the Frog.” A more ambitious project
is one called simply “Hand,” which is just that. Developed by Dr.
Heinrich Ernst, “Hand” is a computer-controlled mechanical hand
that is described as the first artificial device to possess a limited
understanding of the outside world. Although it will undoubtedly
have industrial and other applications, “Hand” was developed
primarily as a study of the cognitive processes of man and animals.
Besides the Air Force’s formal bionics program, there are other
research projects of somewhat similar nature. At Harvard,
psychologists Bruner and Miller direct a Center for Cognitive Studies,
and among the scientists who will contribute are computer experts.
Oddly, man knows little of his own cognitive or learning process
despite the centuries of study of the human mind. It has been said
that we know more about Pavlov’s dog and Skinner’s pigeons than
we do about ourselves, but now we are trying to find out. Some find
it logical that man study the animals or computer rather than his
own mind, incidentally, since they doubt that an intelligence can
understand itself anyway.
As an example of the importance placed on this new discipline,
the University of California at Los Angeles recently originated a
course in its medical school entitled “Introduction to the Function
and Structure of the Nervous System,” designed to help bridge the
gap between engineering and biology. In Russia, M. Livanov of the
Soviet Academy Research Institute of Physiology in Higher Nervous
Activity has used a computer coupled with an electric
encephaloscope in an effort to establish the pattern of cortical
connections in the brain.
While many experts argue that we should not necessarily copy the
brain in designing computers, since the brain is admittedly a survival
device and somewhat inflexible as a result of its conditioning, it
looks already as if much benefit has come from the bionics
approach.
The circuitry of early computers comprised what is called
“soldered” learning. This means that the connections from certain
components hook up to certain other components, so that when
switches operated in a given order, built-in results followed. One
early teaching device, called the Electric Questionnaire, illustrates
this built-in knowledge. A card of questions and answers is slipped
over pegs that are actually terminals of interconnected wires. Probes
hooked to a battery are touched to a question and the supposed
correct answer. If the circuit is completed, a light glows; otherwise
the learner tries other answers until successful.
More sophisticated systems are those of “forced” learning and free
association. Pioneer attempts at teaching a computer to “perceive”
were conducted at Cornell University under contract with the Air
Force to investigate a random-network theory of learning formulated
by Dr. Frank Rosenblatt. Specifically, the Perceptron learns to
recognize letters placed in front of its “eyes,” an array of 400
photocells. The human brain accomplishes perception in several
steps, though at a high enough rate of operation to be thought of as
a continuous, almost instantaneous, act. Stimuli are received by
sense organs; impulses travel to neurons and form interconnections
resulting in judgment, action if necessary, and memory. The
Perceptron machine functions in much the same manner.

Electronics

Simplified version of a mammalian visual system (A) and Perceptron simulating the
biological network (B).

The forced learning technique, in which Perceptron was told when


it correctly identified a letter, and when it missed, was used first.
Later it was found that “corrective” or reinforced teaching, which
notes only errors, was more effective. After Perceptron had seen
each letter fifteen times and received proper correction, it could
subsequently identify all the letters correctly.
Announcement of Perceptron triggered many wild headlines and a
general misconception in the public mind. Dr. Rosenblatt and other
developers wisely refuse to comment on the potential of his
machine, but the number of experiments being conducted indicates
wide scientific interest, and perceptron has attained the prestige of
an uncapitalized generic term. However, the theory of its random
process has been questioned by scientists including Theodore Kalin,
one of the builders of an early electrical logic machine. Kalin feels
that intelligence presupposes a certain minimum of a priori
knowledge: the wired-in learning of the computer or the instincts or
inherited qualities of animals. This of course echoes the thoughts of
Kant who deplored the notion as similar to all the books and papers
in a library somehow arranging themselves properly on the shelves
and in filing cabinets.
Indeed, the whole idea of finding human intelligence mirrored in
the electronic innards of the computer has been flatly denounced at
some scientific symposiums. Computers given an intelligence test at
the University of Michigan “flunked,” according to researchers.
Another charge is that the reaction of the brain’s neuron depends on
its history and thus cannot be compared with the computer.
However, other researchers seem to have anticipated this weakness
and are working on electronic or electrochemical neurons that also
are conditioned by their input. Despite criticism, the bionics work
proceeds on a broad front.
More recently a machine called Cybertron has been developed by
the Raytheon Company. This more sophisticated machine is being
trained to recognize sonar sounds, using the corrective technique. If
Cybertron errs, the teacher pushes a “goof” button. When the
machine is fully developed, Raytheon feels it will be able to
recognize all typical American word sounds, using its 192 learning
elements, and to type them out.
Computers generally do “logical” operations. Many human
problems do not seem to be logical, and can be solved only by
experience, as the mathematician Gödel demonstrated some years
ago. Since Cybertron solves such “alogical” problems, its builders
prefer not to call it a computer, but rather a self-organizing data-
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like