Category: Blog

MPlayer Keyboard Controls and Shortcuts

MPlayer Keyboard Controls and Shortcuts

mplayer logo
mplayer logo

    I love MPlayer but I don’t always recall its controls since its default GUI is bare bones and uses the keyboard to do most if not all of its actions. So, I’ve shamelessly referenced another site and am backing it up onto my site. Besides, one never knows how long a site might remain up and this info is too useful to have to recompile if lost.

    To add to all of that, I’ve been thinking about doing a project where I edit the MPlayer source code to add a helpful popup that shows the control options in a pagnated way. I want this page to be a reference for it should I get the willpower to actually try and do this. Anyway, here are 74 MPlayer keyboard controls.

MPlayer Keyboard Shortcuts

Keyboard control
<- and ->Seek backward/forward 10 seconds.
up and downSeek forward/backward 1 minute.
pgup and pgdownSeek forward/backward 10 minutes.
[ and ]Decrease/increase current playback speed by 10%.
{ and }Halve/double current playback speed.
backspaceReset playback speed to normal.
< and >Go backward/forward in the playlist.
ENTERGo forward in the playlist, even over the end.
HOME and ENDnext/previous playtree entry in the parent list
INS and DEL (ASX playlist only)next/previous alternative source.
p / SPACEPause (pressing again unpauses).
.Step forward. Pressing once will pause movie, every consecutive press will play one frame and then go into pause mode again (any other key unpauses).
q / ESCStop playing and quit.
+ and –Adjust audio delay by +/- 0.1 seconds.
/ and *Decrease/increase volume.
9 and 0Decrease/increase volume.
( and )Adjust audio balance in favor of left/right channel.
mMute sound.
_ (MPEG-TS and libavformat only)Cycle through the available video tracks.
# (DVD, MPEG, Matroska, AVI and libavformat only)Cycle through the available audio tracks.
TAB (MPEG-TS only)Cycle through the available programs.
fToggle fullscreen (also see -fs).
TToggle stay-on-top (also see -ontop).
w and eDecrease/increase pan-and-scan range.
oToggle OSD states: none / seek / seek + timer / seek + timer + total time.
dToggle frame dropping states: none / skip display / skip decoding (see -framedrop and -hardframedrop).
vToggle subtitle visibility.
jCycle through the available subtitles.
y and gStep forward/backward in the subtitle list.
FToggle displaying forced subtitles .
aToggle subtitle alignment: top / middle / bottom.
x and zAdjust subtitle delay by +/- 0.1 seconds.
r and tMove subtitles up/down.
i (-edlout mode only)Set start or end of an EDL skip and write it out to the given file.
s (-vf screenshot only)Take a screenshot.
S (-vf screenshot only)Start/stop taking screenshots.
IShow filename on the OSD.
! and @Seek to the beginning of the previous/next chapter.
D (-vo xvmc, -vf yadif, -vf kerndeint only)Activate/deactivate deinterlacer.
Hardware accelerated video output
1 and 2Adjust contrast.
3 and 4Adjust brightness.
5 and 6Adjust hue.
7 and 8Adjust saturation.
SDL Video Output Driver
cCycle through available fullscreen modes.
nRestore original mode.
Multimedia Keyboard
PAUSEPause.
STOPStop playing and quit.
PREVIOUS and NEXTSeek backward/forward 1 minute.
GUI Support (if compiled in)
ENTERStart playing.
ESCStop playing.
lLoad file.
tLoad subtitle.
cOpen skin browser.
pOpen playlist.
rOpen preferences.
If TV or DVB support compiled
h and kSelect previous/next channel.
nChange norm.
uChange channel list.
Navigate menus (if DVNAV support)
keypad 8Select button up.
keypad 2Select button down.
keypad 4Select button left.
keypad 6Select button right.
keypad 5Return to main menu.
keypad 7Return to nearest menu (the order of preference is: chapter->title->root).
keypad ENTERConfirm choice.
Teletext support (if compiled)
XSwitch teletext on/off.
Q and WGo to next/prev teletext page.
mouse control
button 3 and button 4Seek backward/forward 1 minute.
button 5 and button 6Decrease/increase volume.
joystick control
left and rightSeek backward/forward 10 seconds.
up and downSeek forward/backward 1 minute.
button 1Pause.
button 2Toggle OSD states: none / seek / seek + timer / seek + timer + total time.
button 3 and button 4Decrease/increase volume.

If you’d like to check out another reference sheet, have a look at my HTML, CSS, and JavaScript Cheat Sheet that’s linked below!

Web Technologies
HTML, CSS, and JavaScript Cheat Sheet

Prevent SQL Injections

Prevent SQL Injections

sql injections
sql injections

    Preventing SQL injections is pretty easy once you know what you are doing. Some of you who are new to databases might think about character substitutions, character escaping, or just outright banning of certain characters; but, those options are laborious and not nearly as simple or elegant. Instead, we can use a technique called SQL Parameterization. It’s a fancy word for a straightforward process. For this guide, I’ll be referencing a database titled Movies.

    To explain it simply, what we are going to do is use a “?” in place of inserting our value. We then have our value tied to the “?” which will then be interpreted as a string literal. Since it is being handled as a string literal and is being kept from interpretation, this keeps us from having our databases deleted, stolen, or used in unforeseen ways.

The setup looks like this:

// Instead of this.
$updateComm = "SELECT title FROM Movies WHERE id = '" . $ID . "'";

// We have this.
$updateComm = "SELECT title FROM Movies WHERE id = ?";

Again, the question mark is like a reference marker/bind point. Our data gets tied to it and is never interpreted. We next do a prepare statement that’ll allow us to bind values. The first way we can do this is by binding the values to the field individually.

Let’s take a look:

// We first setup a command with the properly inserted question marks.
$updateComm = "UPDATE Movies SET title = ?, link = ?, date = ? WHERE id = ?";
 
// We then set it up for preparation.
$updateStatement = $db->prepare( $updateComm );

// We then insert to the bind points.
// Note: They are in order of appearance in the command. 
//       This is why we bind to title first and then links, etc.
//       Keep this in mind when setting up commands.
//       Also, we don't start at zero but one.
$updateStatement->bindValue( 1, "I, Robot", PDO::PARAM_STR );
$updateStatement->bindValue( 2, "LINK", PDO::PARAM_STR );
$updateStatement->bindValue( 3, "July 7, 2004", PDO::PARAM_STR );
$updateStatement->bindValue( 4, 666999, PDO::PARAM_INT );
 
// We then execute the command which is properly set up.
$updateStatement->execute();

The second option is to just pass the arguments as an array without individual binding. Note once more that it is all based on order of the question marks.

$updateComm = "UPDATE Movies SET title = ?, link = ?, date = ? WHERE id = ?";
 
// We then set it up for preparation.
$updateStatement = $db->prepare( $updateComm );

// Then, just pass parameters as an array to the execute method.
$updateStatement->execute( array( "I, Robot", "LINK", "July 7, 2004", 666999) );

In both cases, everything is properly sanitized for you and you don’t have to worry about rogue single quotes or DROP TABLE commands getting through. You’re done! Easy right? At this point, all you have to do is look up your language and how to do the above steps and implement them for secure database interactions. Look at Rosetta Code for how other languges setup parameterization. In addition, if you’ve read any of my other articles, pick a project like my PHP7, SQLite3, and Ajax Tutorial to practice this on in addition to learning other skills and techniques.

Java – JSP File Uploader Tutorial

Java – JSP File Uploader Tutorial

JSP Image
jsp image

    Java is one of my favorite programming languages due to its straightforward nature and plethora of built-in options. It has a robust tie with web related technologies such as HTML, CSS, and JavaScript and is made easy to leverage through its server Tomcat. In addition to all that, the community is strong and provides additional functionality through Java ARchives (JARs).

    Now, if you have a web application and want dynamic pages and to leverage Java, you can use Java Server Pages (JSP) to create dynamic interfaces and data streams/access. This tutorial will be on how to upload a file through an HTML Form and JSP processing it to save to the server. To do this, you’ll need to use Tomcat with or without Apache/Nginx and Java 8 or up. For this example, I’ll be using Tomcat in standalone than coupling it with one of the other options. I’m programing on an Ubuntu based distribution so be aware of how your system interacts with Java and vise versa.


To Top


To Bottom

Setup

Tomcat Download

    Let’s start off by getting Tomcat and setting it up. Go to Tomcat 9 Download page and look under Binary Distributions. There, click on either the 32bit or 64 bit “core” zip for Windows if on Windows or simply select the first “core” zip in the list if on Linux.
From there, unzip it to a location you want to work from. Mine is in my home directory under a folder called
“Portable_Apps”. I unzip it and called it “Tomcat-9”.

Tomcat Setup

    Once unzipped and located where you want it, you will want to change its setting in order to use it fully. So, head into the directory and you will see many folders. Of them, there are four key folders to really pay attention to for this task. They are “bin”, “conf”, “lib”, and “webapps”. First, head to “conf” and edit the tomcat-users.xml file. In general, you’ll want to add a user that can access the “manager-gui” application that allows you to control what web applications are present. To do this, head to the bottom of the file where the commented out accounts are. Copy or type out an account that isn’t commented out.

Mine looks looks so:

<user username="admin" password="1234" roles="tomcat,manager-gui"/> 

Please note that the password needs to be something that is actually strong and in addition to that you should try to name the user as something that can’t be guessed by others. Anyway, go ahead and save the file. From there, take a look at the server.xml file.

Find:

<Connector port="8080" protocol="HTTP/1.1"
                    connectionTimeout="20000"
                    redirectPort="8443"
                    address="0.0.0.0" />

You can change the port or add multiple Connector sections to have multiple ports accessible for multiple applications. Please note that I have added the “address” part and it is by default not present. The addition let’s my network connect to the application after I’ve allowed the port to be accessed through the firewall rules. In Linux, for me, this was as simple as making sure UFW was installed and up and then in a terminal doing “sudo ufw allow <portNumber>/tcp”.

    OK, before we start Tomcat, we will want to get some additional libraries so that we can handle a file being sent to the JSP file. Go to these links and find the newest versions.

Links: FileUpload and Commons IO

Once downloaded, simply unzip them and ignore all but the JAR that has the name and version number. Move these JARs to the “lib” folder that I mentioned earlier. If you started Tomcat before this step, stop it and then start it so the libraries will load. If not, we are then ready to start Tomcat. To do this, open a command line or terminal and change directories to the “bin” folder.

From there, do:

// Linux
./catalina.sh start

// Windows
.\catalina.bat start

You might need to make the shell file executable and you can do this by running “chmod +x catalina.sh” from the folder in the terminal. If everything went well, you should see “Tomcat started.” as part of the output. You can now go to your webbrowser and type localhost:8080. If you see “If you’re seeing this, you’ve successfully installed Tomcat. Congratulations!” then we are set. To stop the server, simply replace “start” with “stop”. It’s time we managed our applications a bit.

Tomcat Manage Applications

    On the page, to your right, you’ll see a button called “Manager App”. Click it and login using the user information you created earlier. Here, we’ll see all the applications that are present. This coincides with the “webapps” folder I mentioned. In manager, the paths math the folder names in the “webapps” folder. Only “ROOT” doesn’t follow the naming scheme since it is just a forward slash. “ROOT” also is the container for what you saw when you loaded the page. We’ll want to move its contents to another location. In the “webapps” folder add a new folder called “toor”. Then, in the manager page, find the “Deploy” section and type toor into the “Context Path” section. Click “Deploy” and the section will be added. The rest is up to you but I’d Undeploy the “docs” and “examples” section to clear up space. Note, the folders will be deleted if you do this.

    OK, move the “ROOT” contents to the “toor” folder and then create two folders in the “ROOT” folder. They are “data” and “WEB-INF”. In the “WEB-INF” folder add a file called “web.xml”.

In it, add:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0"
  metadata-complete="true">

  <display-name>File Uploader & Downloader</display-name>
  <description>
     File Uploader & Downloader
  </description>
</web-app>

OK, it’s time we write some code.

Code Breakdown

HTML

    There are really only two parts to this section, a form and an iframe. The rest is just fluff that HTML pages need for proper setup. Simply create the structure in an “index.html” file and insert the below into the “body” tag.

This is the important code:

<h2>File Uploader</h2>
    <form action="Uploader.jsp" method="post" enctype="multipart/form-data" target="FormSubmitter">
        <input type="reset" value="Clear">
        <input type="submit" name="submit"  value="Upload" />
        <input type="file" name="file" multiple />
    </form>
<iframe name="FormSubmitter" frameborder="0" style="width:100%;height:35em"></iframe>

Let’s break this down and understand the parts. We have a form and its action is the JSP file, “Uploader.jsp”. The JSP file will process the submitted info to it and save it. The method used is “post” because what is being submitted is a file or files. The encode type is “multipart/form-data” because we will have to submit files and this setting is what is used to do so. From there, to avoid redirecting the page on submission, we send the process to the iframe.

    In the form part, we have three input tags. The first simply clears the form data. The second submits the form or in this case the files. The third is the file selector. Reference the Full HTML section if you need to know the structure of the rest of the file. OK, we can now look at our JSP file, the good meaty Java code that glues this whole thing together.

JSP

    Go ahead and create a JSP file called “Uploader.jsp”. In the beginning, there was imports. In this beginning, we need a few of them.
Let’s look at them:

<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.io.File" %>

If we look at the imports, we already can get an idea of the structure of the program or take guesses as to how it might be written. We will iterate through a list of the uploaded file(s) and probably use the File object to write the selected file to a location. The other imports handle the actual receiving of the data. Now that we have the needed imports, let’s get some initial stuff set up.

Here is the start of the code:

<%
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    String dirPath = getServletContext().getRealPath("/").replace('\\', '/') +
                                                                      "data/";
    String itemName;
    File file;


    out.println(
        "<!DOCTYPE html>"
        + "<html><head>"
        + "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />"
        + "<title>Results</title>"
        + "</head> <body>"
    );

    Let’s break this down and understand the parts. The first is a boolean that we will check against to see if the data being sent is of multipart/form-data. The next part is the proper path to the “data” folder we created a while back. For Windows, I’m pretty sure you don’t need the “replace” part. We then setup a String called “itemName” that’ll be used to get the file name from the iterated data to then join with the “dirPath” so we can save it in the proper location. We also setup a File object we’ll use later. After all that, we print out the initial HTML syntax for return of the listed out “data” folder in HTML. We are well on our way to being able to upload files to our server. Let’s cover the middle meat of our JSP.

Here is the code:

    // Save file if present
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List list = null;

        try { list = upload.parseRequest(request);
        } catch (FileUploadException e) { out.println(e); }

        Iterator itr = list.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            if (!item.isFormField()) {
                try {
                    itemName = item.getName();
                    file = new File(dirPath + itemName);
                    item.write(file);
                } catch (Exception e) { }
            }
        }
    } else {
        out.println("<h2>Not multi-part transmitted...</h2>");
    }

As was stated, we first check to see if the data being sent is of multipart/form-data. If not we just return a message saying it’s incorrectly submitted. If it’s correct, we do some initial setting up processes by creating a FileItemFactory object. This is an interface for creating FileItem instances which are themselves a representation of the file or formfield data which will be stored in memory or on disk as temporary files. Files are stored in memory if small and on disk if too large when checked against the default size or the one you specify (We aren’t specifying size for this guide.). We then use a high level API for processing file uploads by way of the ServletFileUpload object.

    To determine files, we use the “parseRequest” method to get a list of files that are then sent to the previously created List object that is null. We do as previously mentioned and set up an Iterator object and traverse it with a while loop. In the while loop we create our FileItem which represents our listed file. We check to see if the FileItem instance represents a simple form field or an actual file. If it’s a file, we then get its name and then merge that name with the previously determined directory path. (Some of these settings can be setup in the “web.xml” we created but in this case we hard coded it.) This all is set in a new File object. We then use the FileItem object to write its data to the new File object we created and thus “upload” the file. Let’s finish the JSP code by returning a list of the files in the directory.

Here is the code:

    // List directory
    File curentDir = new File(dirPath);
    String[] list = curentDir.list();
    out.println("<ol>");
    for (int i=0; i<list.length; i++) {
            out.print("<li><a href='data/" + list[i] + "'/>" + list[i] + "</a></li>");
    }
    out.println("</ol>");
    out.println("</body></html>");
%>

    This last part is a bit of an added bonus. We will list the directory containing our files. Let’s break it down. We first create a new File Object and reference the “data” directory path. We list it out in a newly created String array object which we will use below. But next, we print out the “ordered list” tag. We then loop through the String array and printout HTML that has the “list item” tag and an anchor” tag nested in it that references the path and name of the file. We then close out all tags and party like it’s 1941.

Conclusion

Discussion

    At this point, you should add some CSS to get things styled the way you want it to. There isn’t too much I’m aware of that needs covering given the simplicity of the task. Upload file, process file, return data, and that’s it. You might want to look at other tasks like filling a database up with user input or make a directory traverser to view videos, images, or text files. It’s all up to you. If you know Java, then JSP is pretty much that but with web technologies.

For Next Time

    For next time, one should look at limiting upload sizes. In this example and for my personal usage, I don’t want a limitation since I’m working with my own files. In production though, it is IMPERATIVE that files be limited in size and there needs to be checks so as the server’s disk space isn’t by accident consumed entirely by a person uploading a file. Other than that, I have no other thoughts on the matter.

Full Code

HTML

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>File Uploader</title>
</head>
<body>


<h2>File Uploader</h2>
    <form action="Uploader.jsp" method="post" enctype="multipart/form-data" target="FormSubmitter">
        <input type="reset" value="Clear">
        <input type="submit" name="submit"  value="Upload" />
        <input type="file" name="file" multiple />
    </form>

<iframe name="FormSubmitter" frameborder="0" style="width:100%;height:35em"></iframe>
</body>
</html>

JSP

<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.io.File" %>

<%
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    String dirPath = getServletContext().getRealPath("/").replace('\\', '/') +
                                                                      "data/";
    String itemName;
    File file;


    out.println(
        "<!DOCTYPE html>"
        + "<html><head>"
        + "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />"
        + "<title>Results</title>"
        + "</head> <body>"
    );

    // Save file if present
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List list = null;

        try { list = upload.parseRequest(request);
        } catch (FileUploadException e) { out.println(e); }

        Iterator itr = list.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            if (!item.isFormField()) {
                try {
                    itemName = item.getName();
                    file = new File(dirPath + itemName);
                    item.write(file);
                } catch (Exception e) { }
            }
        }
    } else {
        out.println("<h2>Not multi-part transmitted...</h2>");
    }

    // List directory
    File curentDir = new File(dirPath);
    String[] list = curentDir.list();
    for (int i=0; i<list.length; i++) {
        String name = list[i].toLowerCase();
        if (name.contains(".png") || name.contains(".jpg")||
            name.contains(".gif") || name.contains(".jpeg")) {
                out.print("<div>" +
                          "<img src='data/" + list[i] + "'/></div>");
        } else {
            out.print("<a href='data/" + list[i] + "'/><div>" + list[i] + "</div></a>");
        }
    }

    out.println("</body></html>");
%>

Images

before file select
before file select
file select
file select
file uploaded
file uploaded

file playing
file playing

If you liked this article, please check out the others I have written. One I recommend is my reference cheat sheet for HTML, CSS, and JavaScript. You can use it while styling your JSP file uploader application.


Web Technologies
Web Technologies

Simple PHP7, SQLite3, and AJAX Tutorial

Simple PHP7, SQLite3, and AJAX Tutorial

Ajax and PHP
Ajax and PHP

    Using PHP and AJAX can be somewhat confusing. But, the benefits are countless when it comes to doing web related projects. So, I wanted to do a simple tutorial/example of how to get things setup and how to do some basic insert and retrieval of data. For this project, I’m using PHP7, SQLite3, AJAX, Firefox, and Atom. You can use any browser with debugging options and any integrated development environment (IDE) or text editor you want. I choose SQLite3 as my database because it’s lightweight and good for applications that need a database.


To Top


To Bottom

Setup

Creating The Layout & Files

Ultimately, my file and directory layout looks like this:

├── ajaxNphp  // This is my working dir
   ├── index.html
   ├── process.php
   └── resources
       └── server.db

The ajaxNphp folder is the root folder of this project. In this folder, we have a resources folder that holds the database and can hold CSS and JavaScript files among other stuff. ***Note: For this project, JavaScript and CSS are inline to the files! I’m trying to keep this as simple as possible.*** For this part, I recommend using the terminal since it can be faster and we will use it for some other stuff during this project. So, KEEP IT UP! Anyway, My project is located in my Downloads folder under the ajaxNphp folder.
So, I open a terminal and type:

cd ~/Downloads/ajaxNphp/

The tilda (~) means your home folder and the rest is pretty self explanatory. I then do:

mkdir resources && touch index.html process.php

This creates the resources directory where our database will go; if successful, it will then create our PHP and HTML files that we will use for the project. The next part is for us to actually install the tools so we can setup our database and start writing code.

The Tools

    I’m using an Ubuntu based operating system so I’ll show the commands you need to get PHP7, SQLite3, and Firefox installed.

sudo apt-get install sqlite3 php-sqlite3 php firefox

OK, now let’s just check that we have the proper versions installed.

PHP Check

// This will somewhat cleanup the version info on retrieval
php -v | awk '{ print $1 $2 }' | head -n1
// I get PHP7.0.25-0ubuntu0.16.04.1 which is PHP 7.0.25, so I'm set.

SQLite Check

sqlite -version
// I get 2.8.17

// If you do too, try:
sqlite3 -version
// If you get a return, then you are set for SQLite3.
// I get a return value so am set.

Ok, so now we need to determine an environment to work with. I recommend Atom because it has a robust set of plugins and themes that make it more pleasant to work with. You’ll need to get it through their website if you wish to use the same thing; but, any text editor will suit this project.

Setup The Database

    OK, so we now need to setup a database that we can query and insert to by using AJAX, PHP7, and SQLite3. I hope you’ve kept your terminal open as we will now change directory (cd) into the resources directory and launch SQLite3. So, here is what we do:

cd resources/ && sqlite3 server.db

We will then be presented with:

SQLite version <Your SQLite3 Version>
Enter ".help" for usage hints.
sqlite>

If you are seeing this, then let’s go ahead and create our database. I setup three columns for this project and they are title, date, and link. Recall, I’m doing a movies database so the first is for movie titles. The second is for when it was released, and the third is the cover image. So let’s create the table in our database.
Simply do:

CREATE TABLE Movies(title MAX, date varchar(10), link MAX);

If it was successful, you should see NO ERRORS and if you run :

.tables

you’ll get it returned. MAX means that the field can take the largest string possible. The varchar(10) means the field is limited to ten characters. There are other data types such as ints, but we will ignore them for now. Now, let’s insert some initial movie data by doing these below commands one at a time. Make sure there is an ending semi-colon for each!

// Date is in MM/DD/YYYY format

INSERT INTO Movies VALUES('Alien', '05/25/1979', 'https://images-na.ssl-images-amazon.com/images/I/61ujvw4OXNL._SX342_.jpg');

INSERT INTO Movies VALUES('Contact', '07/11/1997', 'http://www.filmsgraded.com/posters/01/1/8/8/84a.jpg');

INSERT INTO Movies VALUES('Paul', '03/18/2011', 'https://upload.wikimedia.org/wikipedia/en/thumb/9/96/Paul_poster.jpg/215px-Paul_poster.jpg');

// Check your work
SELECT * FROM Movies;
// You should see the data you entered returned.

// If so, then simply exit.
.exit

Excellent! The commands are pretty simple to understand. They even give a hint of what is going on. We use “INSERT INTO” to start the insert process. We reference our “Movies” table we created and then pass “VALUES” which match up with our title, date, link table layout. We end each command with a semi-colon. Next, we need a server to process PHP commands, interpret our form data, retrieve our data, etc.

Setup The Server

    There are many servers out there one can use and there are some servers that are for testing. If you want to see some options, read my post on Quick Test Servers. For this project, I’m using PHP’s built in server used for testing since it will process PHP and our HTML files.
If you’ve kept the terminal up do this:

cd .. && php -S 127.0.0.1:1212

It’s pretty straightforward for what we are doing here. We moved back to the top directory of the project using cd .. since we only moved down one directory, We then use the “php” command with “-S” as a switch to use its server. We give “-S” an argument of “localhost” (127.0.0.1) and a port of 1212. The port needs to be bigger than 1024 since any port lower and equal to that requires sudo to use. It then waits to process requests. We can use ctrl + c to kill the server which can be helpful for when we want to use ctrl + l to clear the terminal screen of any text output and restart. When your project is complete, you can omit the change directory command and just do the PHP et all part. Add an “&” to the command so that the process is persistent even if the terminal closes. Now, we are truly ready to code!

HTML

Our Basic HTML Template

    Let’s start off with a basic HTML template that we will add to shortly:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Test AJAX/PHP</title>

<script type="text/javascript">
</script>

</head>
<body>

<h2>Save Movie Info</h2>
<form action="process.php" method="post">
    <input type="text" title="Title" placeholder="Title" name="Title" value="">
    <input type="text" title="Date" placeholder="Date" name="Date" value="">
    <input type="text" title="Link" placeholder="Link" name="Link" value="">
    <input type="submit" name="saveInfo" value="Save">
    <button type="reset" value="Reset">Clear</button>
</forn>


<br/><br/>
<h2>Search Movie Info</h2>
<form>
    <input type="text" name="searchField"
           title="Search"
           placeholder="Search..."
           onkeyup="getData(this.value)"/>
</form>
<br/><br/>


<div id="dynDataField"></div>
</body>
</html>

    Let’s break this down. We have two forms with their own input fields. One form is used for saving new movie entries and the other searches the database and gets the data back. The form that saves new movie info has three fields and a submit button. The three fields correspond to the three columns in our database and Movies table. The submit action uses the forms submit action to send our process.php script POST data about the form for processing.

    The search form has one input field and an onkeyup event that calls a function called “getData”. This function has a parameter passed to it of “this.value” which will take the query that one has typed in. AJAX will be used in this instance to get data from the server as we type in a character. We have a div tag with an ID of “dynDataField” that we will reference to insert the returned data from the server. This is our bare bones HTML. But, it is pretty useless. Clicking any of the buttons or typing a search does nothing. So, let’s create an AJAX script to get our already entered data!

AJAX

AJAX Search Script

    At the heart of AJAX, there are 4 core steps for GET and 5 core steps for POST.

  1. Create an XMLHttpRequest object
  2. Setup an onreadystatechange function for the XMLHttpRequest object
  3. Open a connection with the XMLHttpRequest object
  4. With POST: Setup a setRequestHeader with an XMLHttpRequest object
  5. Send the data with an XMLHttpRequest object
    // Step 1: Create object
    var xhttp = new XMLHttpRequest();  // Create the xhttp object
    // Step 2: Setup an onreadystatechange function for the XMLHttpRequest object
    // This is actually run after send is done and the server spits out info.
    xhttp.onreadystatechange = function() {
        // Confirm we have a  successful connection. Then, receive the response info.
        // For PHP it is echo that sends it.
        // Loops seem to cause this to wait which means an array can be traversed
        // and the output could be written as a table, etc.
        if (this.readyState == 4 && this.status == 200) {
            // do something with the returned data
        }
    };
    // Step 3: Open connection
    // More or less, open a connection: @Params POST or GET, path to XML page or php script, set async t/f
    xhttp.open("GET", "process.php", true);
    // Step 4: Send the data and let server process it.
    //         After done processing it, onreadystatechange is triggered.
    xhttp.send();    // Start the process and send GET data


    //      For POST do and add these changes
    //  xhttp.open("POST", "process.php", true);
    // Used in POST to setup data types like JSON, XML, etc... MUST BE DONE AFTER OPEN
    // xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Example data structure for Sending POST with above RequestHeader. See that this mimics GET 
    // xhttp.send("fname=Henry&lname=Ford");
    // xhttp.sebnd(formData);  // Can use a string variable with formatted data structure instead

The above is the process. Here is what we setup in our scripts tag that’s in the head tag:

function getData(query) {
    if (query == "") {
        document.getElementById("dynDataField").innerHTML = "<p></p>";
        return;
    } else {
         var xhttp = new XMLHttpRequest();  // Create the xhttp object
         var formData = "dbQuery=" + query; // Our query being setup for processing
         // This is actually run after open and send are done
         xhttp.onreadystatechange = function() {
             if (this.readyState == 4 && this.status == 200) {
                 updatePage(this);  // Send the returned data to further process
             }
         };
         xhttp.open("POST", "process.php", true);  // Open the connection
         xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
         xhttp.send(formData);    // Start the process

    }
}

function updatePage(returnData) {
    // Get the echoed data and insert to div of dynDataField
    document.getElementById("dynDataField").innerHTML = returnData.responseText;
}

OK, so we have two functions here. One is for getting the data and the other inserts the results into our div. Get data checks to see if the input field is empty and if so leaves things as they are. If there is data in the field, it is then inserted into a variable “formData” and tied in with “dbQuery=”. This is what PHP will look at and use to insert into a database query. We then setup a statechange listener to wait for the server to finish processing the search and we send the result to the other function.

    After this setup part, we do the standard open process but use POST instead of GET. Then, we tell the server what kind of data this is. Recall, GET defines it for us but is limited and less secure while POST has more data formats and better security but we have to define it using the setrequestheader. We then send the data in its formatted string to the server for processing. This w3schools link has some more info about each part. In this instance, the PHP script transfers a string back to the requester. Note, we can transfer JSON, XML, and other data. But, a string or “responseText” is good for now.

Alright, all that’s left is to write our PHP script to process the search and our insert to table option.

PHP

Base PHP

    We have three core parts for the PHP project. We want to determine which form sent the POST. We then call one of two functions. One function will search the database. The other function will insert to the database.
Here is the basic setup:

<?php

// Retrieve data
function searchDB($QUERY) {
}

// Save new entry
function saveInfo($TITLE, $DATE, $INFOLINK) {
}

// Determin action
if(isset($_POST['saveInfo'])) {
    saveInfo($_POST["Title"], $_POST["Date"], $_POST["Link"]);
} elseif (isset($_POST['dbQuery'])) {
    searchDB($_POST['dbQuery']);
} else {
    echo "<h2 style='width:100%;background-color:#ff0000;color:#ffffff;text-align:center;'>Error! Illegal Access Method!</h2>";
}

?>

The part of interest here is the the determine action section. This is how we determine which function to call when a form is submitted or an AJAX call is made. If neither call the script, we drop an error and exit the script. We are simply checking if “saveInfo” or “dbQuery” are set. We then call the proper function and pass the data that is sent. Let’s now setup our search function.

Search Function

    As you might have seen, we are calling our search function “searchDB” and we are passing the “dbQuery” value to it.
So let’s see how we connect to the database and return data:

try {
    $serverPDO = new SQLite3('resources/server.db');
    $query = "SELECT * FROM Movies WHERE title LIKE '%" . $QUERY . "%' OR " .
                                         "date LIKE '%" . $QUERY . "%' OR " .
                                         "link LIKE '%" . $QUERY . "%'";
    $result = $serverPDO->query($query);

    while ($row = $result->fetchArray()) {
        echo "<div style='float: left;margin-left: 1em; margin-right: 1em;'>" .
             "<a href=" . $row["link"] ." target='blank'>" .
             "<img style='width:8em; height:10em;' src='" . $row["link"] . "'/></a><br/>" .
             "Title: " . $row["title"] .
             "<br/>Date: " . $row["date"] . "</div>";
    }

    if ($result->fetchArray() == 0) {
        echo "<div style='float:left;width:100%; background-color:pink;color:#ffffff;text-align:center;'>Nothing Found...</div>";
    } else {
        echo "<div style='float:left;margin-top:2em;width:100%; background-color:lightgreen;color:#ffffff;text-align:center;'>Search Completed...</div>";
    }
} catch (Exception $e) {
    echo "<h2 style='width:100%; background-color:ff0000;color:#ffffff;text-align:center;'>Error!</h2><br/>" . $e;
}

Let’s break this down. In our “searchDB” function, we have a try catch block that checks any exception that might occur. Technically, we really should be more specific to what exceptions might occur but for now, this will suffice. We try to create an SQLite3 database object and give it a local path name of “resources/server.db”. This is set to the “serverPDO” variable. We then create a “query” variable of type string that comprises of an SQL command that very broadly makes the database look at he table and see if any field matches the query. Please note, this is a very in-efficient way to do this as it looks at each field and then sees if any part is like the query both in upper, lower, and mixed casing. If we were being efficient, we’d base our queries on the columns and have either multiple input fields for the search with a “submit” button or use other techniques to keep the searches quick. Since this is a small database, performance isn’t poor and we can get away with this in a general context. Take note that the VALUES section is ordered just like we ordered it when we created the table columns.

    Anyway, we then execute the query and get the result set into the “result” variable. This is essentially a 2D array that comprises an array of result objects that then have an array of values for each object. This is why we use the while loop and access the “row” and then any values there in. We assign the values to a string formatted with HTML markup that is then echoed. After that, we echo whether we traversed an arrays by saying the search was or was not found.

    As I understand it, the “onreadystatechange” is triggered after the script is finished. So, all echos are collected by “onreadystatechange” and once the script sends an exit code the “onreadystatechange” sends what was echoed to whatever you setup to collect and parse the data.

Insert Function

    As you can tell, our insert function will take three paramets which are the title, date, and link.

if ($TITLE != "" && $DATE != "" && $INFOLINK != "") {
    try {
        $serverPDO = new SQLite3('resources/server.db');
        $command = "INSERT INTO Movies VALUES('" . $TITLE . "','" . $DATE . "','" . $INFOLINK . "')";
        $serverPDO->exec($command);

        echo "<h2 style='width:100%;background-color:#0000ff;color:#ffffff;text-align:center;'>Inserted to db...</h2><br/>" .
             "Title: " . $TITLE . "<br/>Date: " . $DATE . "<br/>Link: " . $INFOLINK;
    } catch (Exception $e) {
        echo "<h2 style='width:100%; background-color:ff0000;color:#ffffff;text-align:center;'>Error! Database Insert Failed...</h2><br/>" . $e;
    }
} else {
    echo "<h2 style='width:100%; background-color:ff0000;color:#ffffff;text-align:center;'>Error!</h2><br/>" .
         "<h3>A field is empty...</h3>" . $e;
}

Lets break this down. The first parts are pretty much the same as the search function with the exception of execute than query being the command. We also confirm that each field is filled and if not we generate an error HTML markup. We have a try catch block if they are filled. In the try section, we connect to the database. We create a “command” of type string that inserts the sent data from the form. We then echo a success or failure message. Take note that this insert process is not AJAX. Our page will redirect to the process.php file and the file will output HTML. I’m doing it this way to show you two ways of processing data and why AJAX is useful in that we aren’t being redirected. As you can see, it’s a much cleaner user experience to use AJAX and this PHP example shows why. You can change this to AJAX but I will leave that to you to figure out how.

Conclusion

Discussion

    We are DONE! Pat yourself on the back and get a cold beer or favorite beverage. You now have new possibilities available to you since you understand the basic concepts. Let’s do a quick recap and talk about pitfalls and the next steps one should take.

We start off by creating two files and one sub-folder. We then install our needed programs and a development environment. From there, we create our database in the sub-folder and the table in the database. It is important to recall that one of the fields is limited to a string size of 10. Anyway, we then entered some initial data so we could work with it after creating our code. After launching our PHP server, we create our initial HTML markup and talk about what we will do next. Next, we create our AJAX search script that checks against empties and so on. Since the HTML is done, we move on to the PHP. In the PHP, we check what’s sending the request and determine the necessary action from the POST data. We create our two functions and their logic which get called after the initial checks. Once the script exits, our AJAX sees this and we end the data to a function that then inserts the data to a div tag OR we get an HTML output in the case of the data insert form. We then drink our beverage and think about pitfalls and the next project we will do based off the work done here.

Pitfalls

    The first massive pitfall is that we aren’t sanitizing our data. NEVER do a production project without cleaning input data! I skipped it here because I’m lazy and this article would get longer than I want it to. It can be pretty easy to do though since there are libraries out there one can use. You should use a JavaScript library or your own scripts to check the input. I recommend checking through the server too but the JavaScript should get most issues.

    The next pitfall is that we aren’t checking the length of the date field. This can be done through JavaScript too and PHP can cover the process too. So, this would be one of the next steps to do as well as the above input sanitation.

    The next pitfall is that the search function implements a poor query structure. I mentioned this before but we are collating things to keep in mind so I mention it here too.

    I’m sure there are some other things of note but these three are the biggies. Let’s look at what our next steps might be with such a project.

Next Steps

    Here are some next steps to consider.

  • New Projects:
    • Use cookies to create a login system and account control to then access or create users for the database.
    • Use cookies and AJAX to create a tracking system that’ll insert data to the database about links clicked.
    • Create a meta search engine.
    • Create a password manager..
  • Improve Current Project:
    • Sanitize input fields to avoid exploits and future errors.
    • Implement a date field length check.
    • Make a better search system.

Result Images

ajax and php result
ajax and php result
ajax and php result 2
ajax and php result 2
error handling
error handling
error handling 2
error handling 2

db insert
db insert
HTML, CSS, JavaScript Useful Cheat Sheet!

HTML, CSS, JavaScript Useful Cheat Sheet!


To Top


To Bottom

Web Technologies
Web Technologies

    I love web technologies because they provide a quick return on interest (ROI) and for the beginner gives immediate feedback in terms of accomplishment and sense of progress. There are many frameworks that one can use for a web based project but knowing the base elements these frameworks are comprised from is still important. Here is a reference list/cheat sheet of some of the most common HTML tags, CSS, and JavaScript one will likely use. This is great for Web Devs, Web Admins, coders, programmers, and the like.

HTML Tags

    Most HTML tags are setup as open and close tags. This means that most tags are a pare/set and denote where they start and end. The end tag has a forward slash (/) to indicate the tag is the end tag.

<tag>Stuff in tag...</tag>
(open tag)content(/end tag)

<!--Some tags end like this-->
<tag/>

<div>

    Div tags are considered devision tags and are used to section data on a page. CSS will then be used to style the tag by setting its position, setting the background color, setting the text color, etc. Think of the div as a container and your scaffolding for the page. Div tags are block elements.

<p>

    The P tag stands for paragraph tag and this is like a sub container for the div tag. It often holds text but can contain images, links, and other non-block tags. Browsers will automatically add some space (margin) before and after each <p> element. This behavior can be modified with CSS using the margin properties. P tags are block elements.

<span>

    The span tag is pretty much like the div tag. The difference between the two is that div is a block element which puts it on a separate line. A span tag, however, is an inline element, meaning that it can be on a line with other elements.


<img>

    The img tag stands for images. People like images and I like images.

<img src="https://www.itdominator.com/wp-content/uploads/2017/07/wp-cli.jpg" alt="If image doesn't render, this text will show instead." />

<a>

    Anchor tags link to parts on the same page or to new pages entirely. They are essentially links.

<!--To an external page...-->
<a href="http://www.google.com" target="_blank">Google</a>

<!--This will jump to the content that is wrapped with another anchor tag on the same page.-->
<a href="#colors">Colors</a>

<a name="colors">
<p>Colors are cool. The primary colors are red, green, and blue.</p>
</a>

<table>

    Table is a block element that denotes there will be sub elements of th, tr, td. There are others but these are the core parts. Th stands for table header and
is inset within a tr (table row). Tr is table row which makes a row for the table. Td is table data which is like a column and is inset in a table row too.

border-collapse: separate (default):

FirstnameLastname
TomGar
LoisGriffin

border-collapse: collapse:

FirstnameLastname
PeterGriffin
LoisMatt

form

    A form is used to submit data to the server. There are many form objects one can use. Below is a table covering all HTML5 form objects and their code and examples.

ObjectPreview HTML 5 code
Label

<label>Texte</label>
Button

<input type=”button” name=”name” value=”Bouton”>
Image button


<input type=”image” src=”image/bimage.jpg”>
Text field

<input type=”text” name=”text” value=”empty”>
Password

<input type=”password” name=”monpass” value=”12345″>
Date

<input type=”date” name=”date” value=”<?php echo $today?>”>
Date and time

<input type=”datetime” name=”time” value=”<?php echo $now?>”>
Time<time>2013-06-27</time>
Number

<input type=”number” name=”num” value=”12345″>
Color

<input type=”color” name=”color” value=””>
Search input

<input type=”search” name=”” list=”datalist” value=””>
Data
Dix
<data value=”10″>Ten</data>
Check box

<input type=”checkbox” name=”checkbox1″ value=”checkbox”>
Radio group



<label>Choice 1
<input type=”radio” name=”radio1″ value=”radio1″>
</label>
<label>Choice 2
<input type=”radio” name=”radio1″ value=”radio2″>
</label>
Textarea

<textarea name=”textarea”>content</textarea>
Range


<input type=”range” min=”-100″ max=”100″
value=”0″ step=”2″ name=”power” list=”powers”>
<datalist id=”powers”>
<option value=”0″>
<option value=”-30″>
<option value=”30″>
<option value=”+50″>
</datalist>
Data listTo be used with input
<datalist id=”identifier”>
<option value=”1″>
<option value=”2″>
<option value=”3″>
</datalist>
Select

<select name=”select”>
<option>Alpha</option>
<option>Beta</option>
<option>Delta</option>
</select>
Select list

<select name=”select2″ size=”3″>
<option>Alpha</option>
<option>Beta</option>
<option>Delta</option>
</select>
Menu

  • New
  • Open
  • Save
  • <menu type=”context”>
    <li>New</li>
    <li>Open</li>
    <li>Save</li>
    </menu>
    Toolbar

  • <menu type=”toolbar”>
    <li><button type=”button” onclick=”fnew()”>New</button></li>
    <li><button type=”button” onclick=”fopen()”>Open</button></li>
    <li><button type=”button” onclick=”fsave()”>Save</button></li>
    </menu>
    Combo box


    <input type=”text” list=”comboid”>
    <datalist id=”comboid”>
    <option value=”0″>
    <option value=”-30″>
    <option value=”30″>
    <option value=”+50″>
    </datalist>
    File upload

    <input type=”file” name=”file”>
    Image & caption

    Caption

    <figure>
    <img src=”image/image.gif”>
    <figcaption>Caption</figcaption>
    </figure>
    Fieldset
    Title

    …Content…

    <fieldset>
    <legend>Title </legend>

    <p>Content</p>
    </fieldset>
    Output

    <output onforminput=”value = 2 + 2″></output>
    Meter
    12 units
    <meter min=0 max=24 value=12>12 units</meter>
    Progress 0%
    <progress id=”prog” max=100>
    Summary

    Overview
    term
    definition

    <details>
    <summary>
    Presentation
    </summary>
    <dl>
    <dt>term</dt>
    <dd>definition</dd>


    </dl>
    </details>
    Submit button

    <input type=”submit” name=”submit” value=”Submit”>
    Clear/Reset button

    <input type=”reset” name=”clear” value=”Clear”>

    HTML Entities

        HTML entities are used in place of reserved characters in HTML. Characters that are not present on your keyboard can also be replaced by entities as well. The most common are listed in a table below.

    ResultDescriptionEntity NameEntity Number
    non-breaking space&nbsp;&#160;
    <less than&lt;&#60;
    >greater than&gt;&#62;
    &ampersand&amp;&#38;
    double quotation mark&quot;&#34;
    single quotation mark (apostrophe)&apos;&#39;
    ¢cent&cent;&#162;
    £pound&pound;&#163;
    ¥yen&yen;&#165;
    euro&euro;&#8364;
    ©copyright&copy;&#169;
    ®registered trademark&reg;&#174;

    HTML Notes

    Recommended Default HTML Markup Before Content Is Added

    <!DOCTYPE html> <!--Tells a browser its an html page-->
    <html lang="en">
    <head>
      <meta charset="utf-8">  <!--Encoding model-->
      <title>Title seen on its tab</title>
      <link rel="stylesheet" href="/css/master.css"> <!-- Attach CSS through a path -->%MINIFYHTMLcaa1589338edeeb2c2788d9eea3266e84%</head>
    <body>
    
    <!-- content goes here... -->
    
    
    <script src="resources/scripts/script.js" charset="utf-8"></script>  <!-- Attach Javascript File through path -->
    </body>
    </html>
    

    Block Elements

        In general, HTML elements can be divided into two categories : block level and inline elements. HTML block level elements can appear in the body of an HTML page. It can contain another block level as well as inline elements. By default, block-level elements begin on new lines. Block level elements create larger structures (than inline elements).

    • p
    • h1, h2, h3, h4, h5, h6
    • ol, ul
    • pre
    • address
    • blockquote
    • dl
    • div
    • fieldset
    • form
    • hr
    • noscript
    • table

    Inline Elements

        HTML inline elements can appear in the body of an HTML page. They can contain data and other inline elements. By default, inline elements do not begin on new lines. Inline elements create shorter structures (than block elements).

    • b, big, i, small, tt
    • abbr, acronym, cite, code, dfn, em, kbd, strong, samp, var
    • a, bdo, br, img, map, object, q, script, span, sub, sup
    • button, input, label, select, textarea

    Margins

        Margins are the spacing around an element.

    This span tag has 2em margin set…

    Padding

        Padding is the spacing internal to an element and its “walls”.

    This span tag has 2em padding set…

    CSS

    Examples/Logic

    SelectorExampleExample description
    .class.introSelects all elements with class=”intro”
    #id#firstnameSelects the element with id=”firstname”
    **Selects all elements
    elementpSelects all <p> elements
    element,elementdiv, pSelects all <div> elements and all <p> elements
    element elementdiv pSelects all <p> elements inside <div> elements
    element>elementdiv > pSelects all <p> elements where the parent is a <div> element
    element+elementdiv + pSelects all <p> elements that are placed immediately after <div> elements
    element1~element2p ~ ulSelects every <ul> element that are preceded by a <p> element
    [attribute][target]Selects all elements with a target attribute
    [attribute=value][target=_blank]Selects all elements with target=”_blank”
    [attribute~=value][title~=flower]Selects all elements with a title attribute containing the word “flower”
    [attribute|=value][lang|=en]Selects all elements with a lang attribute value starting with “en”
    [attribute^=value]a[href^=”https”]Selects every <a> element whose href attribute value begins with “https”
    [attribute$=value]a[href$=”.pdf”]Selects every <a> element whose href attribute value ends with “.pdf”
    [attribute*=value]a[href*=”w3schools”]Selects every <a> element whose href attribute value contains the substring “w3schools”
    :activea:activeSelects the active link
    ::afterp::afterInsert something after the content of each <p> element
    ::beforep::beforeInsert something before the content of each <p> element
    :checkedinput:checkedSelects every checked <input> element
    :disabledinput:disabledSelects every disabled <input> element
    :emptyp:emptySelects every <p> element that has no children (including text nodes)
    :enabledinput:enabledSelects every enabled <input> element
    :first-childp:first-childSelects every <p> element that is the first child of its parent
    ::first-letterp::first-letterSelects the first letter of every <p> element
    ::first-linep::first-lineSelects the first line of every <p> element
    ype.asp”>:first-of-typep:first-of-typeSelects every <p> element that is the first <p> element of its parent
    :focusinput:focusSelects the input element which has focus
    :hovera:hoverSelects links on mouse over
    sp”>:in-rangeinput:in-rangeSelects input elements with a value within a specified range
    :invalidinput:invalidSelects all input elements with an invalid value
    :lang(language)p:lang(it)Selects every <p> element with a lang attribute equal to “it” (Italian)
    sp”>:last-childp:last-childSelects every <p> element that is the last child of its parent
    ype.asp”>:last-of-typep:last-of-typeSelects every <p> element that is the last <p> element of its parent
    :linka:linkSelects all unvisited links
    :not(selector):not(p)Selects every element that is not a <p> element
    sp”>:nth-child(n)p:nth-child(2)Selects every <p> element that is the second child of its parent
    hild.asp”>:nth-last-child(n)p:nth-last-child(2)Selects every <p> element that is the second child of its parent, counting from the last child
    f-type.asp”>:nth-last-of-type(n)p:nth-last-of-type(2)Selects every <p> element that is the second <p> element of its parent, counting from the last child
    ype.asp”>:nth-of-type(n)p:nth-of-type(2)Selects every <p> element that is the second <p> element of its parent
    ype.asp”>:only-of-typep:only-of-typeSelects every <p> element that is the only <p> element of its parent
    sp”>:only-childp:only-childSelects every <p> element that is the only child of its parent
    :optionalinput:optionalSelects input elements with no “required” attribute
    ange.asp”>:out-of-rangeinput:out-of-rangeSelects input elements with a value outside a specified range
    sp”>:read-onlyinput:read-onlySelects input elements with the “readonly” attribute specified
    sp”>:read-writeinput:read-writeSelects input elements with the “readonly” attribute NOT specified
    :requiredinput:requiredSelects input elements with the “required” attribute specified
    :root:rootSelects the document’s root element
    ::selection::selectionSelects the portion of an element that is selected by a user
    :target#news:targetSelects the current active #news element (clicked on a URL containing that anchor name)
    :validinput:validSelects all input elements with a valid value
    :visiteda:visitedSelects all visited links

    IDs

        ID selectors are supposed to be unique within the HTML document. When queried with JavaScript it should return a single element but it can return an array/list if the web developer set the document with multiple IDs of the same type. Standards dictate this is poor form if done.

    <!-- The IDs are arbitrary. -->
    
    <div id="left-container"> <!-- Content --> </>
    <div id="middle-container"> <!-- Content --> </>
    <div id="right-container"> <!-- Content --> </>
    

    Classes

        Class selectors don’t have to be unique within the HTML document. When queried with JavaScript it usually returns an array/list.

    <!-- The Class is arbitrary. -->
    
    <div class="book"> <!-- Content --> </>
    <div class="book"> <!-- Content --> </>
    <div class="book"> <!-- Content --> </>
    

    CSS Button Generator Button Generator

        Quickly make buttons…

    Button













    JavaScript

    Get Elements By ID/Class/TagName/CSS Selector

        Getting elements by id, class, and tag among other options is a sizeable chunk of the JavaScripting one will do. This allows us to interact with the DOM

    // Get HTML element(s) with specified id.
      var x = document.getElementById('id');
    
    // Get HTML elements with specified class.
      var x = document.getElementsByClassName('className');
    
    // Get HTML elements with specified tag.
      var x = document.getElementsByTagName('tagName');
    
    // Get HTML elements tht matches a specified CSS selector
    // This example returns a list of all  elements with class="icon".
      var x = document.querySelectorAll("img.icon"); 
    

    Function

        The basic block of coding we all know and have come to love. Yes…the function.

    function sum(a, b) {
        return a + b;      // The function returns the sum of a and b
    }
    var sumVal = sum(2,4);
    alert(sumVal);  // Will pop-up saying 6
    

    If Statement

        Check the conditions.

    if (condition) {
    }
    

    Loops

        Loops baby, they’re needed and these will meet your needs.

    // Standard loop
    for (var i=0; i<array.length; i++) {
       array[i].innerHTML;
    }
    
    // For In Loop
    for (var tag in elements) {
        // Do stuff while there are tags to work on
    }
    
    // While Loop
    while (condition) {
        // Do stuff while condition is met
    }
    
    // Do While
     do {
        // One at least one and keep doing stuff while condition is met
    }
    while (condition);
    

    Switch/Case Statement

        Good for menu stuff, switch/case statements are ready for the job.

    var day;
    switch (new Date().getDay()) {
        case 0:
            day = "Sunday";
            break;
        case 1:
            day = "Monday";
            break;
        case 2:
            day = "Tuesday";
            break;
        case 3:
            day = "Wednesday";
            break;
        case 4:
            day = "Thursday";
            break;
        case 5:
            day = "Friday";
            break;
        case  6:
            day = "Saturday";
    }
    alert(day);
    

    Alert & Console Log

        Error logging is helpful. The two way to do this are through alerts and console logging. Most of the time, alert isn’t used but it can be helpful to warn the user, etc.

    // This will generate a pop-up window with the "Hello, World!" text.
    alert("Hello, World!");
    
    // This will log to the console the "Hello, World!" text.
    To access the console in Firefox, do Ctrl+Shift+J
    console.log("Hello, World!");
    

    Adding Event Listeners

        Event listeners are the next most important after getting an element. They allow us to let the user click on stuff or interact through other ways in order to create dynamic interactions.

    // This attaches a click event to the entire DOM.
    // We can then check which IDs, Classes, etc were clicked to then do other things.
    
    document.addEventListener("click", (e) => {
        if(e.target.id == "alert2")
            alert("You clicked an element with the ID of alert2");
    
    });
    
    
    // This attaches to a specific element with the ID of cars and
    // when clicked alerts us to the innerHTML text.
    
    <p id="cars">Hello, World!</p>
    
    document.getElementById('cars').addEventListener("click", (e) => {
            alert("The content is:  " + e.target.innerHTML);
    });
    
    // This attaches it in a different manner.
    document.getElementById('cars').onclick =  function(){
        // do stuff
    }
    
    // You can add it though a tag as well.
    <div onclick="myFunction()"> I am clickable! </div>
    

    Here is a list of some common HTML event attributes:

    EventDescription
    onchangeAn HTML element has been changed
    onclickThe user clicks an HTML element
    onmouseoverThe user moves the mouse over an HTML element
    onmouseoutThe user moves the mouse away from an HTML element
    onkeydownThe user pushes a keyboard key
    onkeyupThe user releases a keyboard key
    onloadThe browser has finished loading the page

    Arrays

        Arrays in JavaScript are a special object and really act like lists or vectors since we can push new values to it.

    // An empty array
    var cars = [];
    
    // Has nodes/objects
    var cars = ["Toyota", "Sab", "Mazda"];
    
    // Add to array
    cars.push("Nesan');
    
    // Remove from end of array
    cars.pop();
    

    Parent Element

        Sometimes, we need to access the element that contains the element we accessed. This could be because we want to remove the element or we want to add something next to it than in it.

    <div>
        <p id="cars" >
            Cars are cool.
        </p>
    But boats are even more cool.
    </div>
    
    var x = document.getElementById('cars').parentElement;
    alert(x.innerHTML);  // This will present an alert box with "But boats are even more cool."
    
    
    // This will remove the element we accessed from the div
    var childElm = document.getElementById('cars');
    var parentElm = childElm.parentElement;
    
    parentElm.removeChild(childElm);
    

    Cookies

        Sometimes, we need to store user information for later usage. This is where cookies come in.

    function saveAsCookie() {
        var uName = document.getElementsByName("userName")[0].value;
        var eml = document.getElementsByName("email")[0].value;
    
    
        // should set expires date: Ex -> expires=(UTC date).
        // Use secure; in argument to make sure it only transports across HTTPS or secure connections
        document.cookie = "username=" + uName  +"; path=" + document.URL;
        document.cookie = "email=" + eml + "; path=" + document.URL;
    }
    
    function displayCookies() {
        var cookiesField = document.getElementById("cookieField");
        var cookies = document.cookie.split(";");  // Set as an array to traverse....
    
        for (var i=0; i<cookies.length; i++) {
            cookiesField.innerHTML += cookies[i] + "<br/>";
        }
    }
    
    function clerCookies() {
        var expireDate = "Thu, 01 Jan 1970 00:00:00 UTC";
        document.cookie = "username=; expires=" + expireDate;
        document.cookie = "email=; expires= " + expireDate;
    }
    
    <form>
    <input type="text" title="User Name" name="userName" placeholder="User Name" value=""/>
    <input type="text" title="Email" name="email" placeholder="Email" value=""/>
    <input type="button" name="submit"  onclick="saveAsCookie()" value="loginSubmit">
    </form>
    
    <button type="button" name="button" onclick="displayCookies()">Get Cookie</button>
    <button type="button" name="button" onclick="clerCookies()">Clear Cookie</button>
    
    <div id="cookieField"></div>
    

    AJAX

        AJAX is a developer’s dream, because you can:

    • Update a web page without reloading the page
    • Request data from a server – after the page has loaded
    • Receive data from a server – after the page has loaded
    • Send data to a server – in the background
    function loadDoc() {
      var xhttp = new XMLHttpRequest();        // Create the xhttp object
      xhttp.onreadystatechange = function() {  // This is actually run after open and send are done
        if (this.readyState == 4 && this.status == 200) {  // Confirm we have a  successful connection
         // Receive the response info. For PHP it is echo that sends it. Then set into demo div
         document.getElementById("demo").innerHTML = this.responseText;  
        }
      };
      xhttp.open("GET", "ajax_info.txt", true);  // post or get, path to XML page or php script, set async 
      xhttp.send();                              // Start the process
    }
    
    
    <button type="button" name="button" onclick="loadDoc()">Load XML</button>
    <div id="demo">

    String Manipulation

        String Manipulation can be important when handling cookies or data. Sometimes we need to split it into an array, make it lower case or vise versa, find a sub string, or more.
    These should get you started:

    // Find sub string
    var str = "Hello world, welcome to the universe.";
    var n = str.includes("world");
    
    // Find sub string at offset
    var str = "Hello world, welcome to the universe.";
    var n = str.includes("world", 12);
    
    // Replace string 
    var str = "Windows!";
    var res = str.replace("Windows", "Linux");  // old value, new value
    
    // Replace all case sensitive
    var str = "Mr Blue has a blue house and a blue car";
    var res = str.replace(/blue/g, "red");
    
    // Replace all case-insensitive
    var str = "Mr Blue has a blue house and a blue car";
    var res = str.replace(/blue/gi, "red");
    
    // String split
    var str = "How are you doing today?";
    var arry = str.split(" ");  // Split by spaces
    
    // To Upper
    var x = "Linux";
    x.toUpperCase();
    
    // To Lower
    var x = "LINUX";
    x.toLowerCase();
    

    Conclusion

        I think this list is pretty good and fits most user's needs. This should definitely help those who are looking for a certain tag or CSS logic or are just wanting to see a broad selection of what web technologies are based off of. Coders, website developers, Admins, etc should have most of what they need right on the page with good samples to start. Leave a commemt if you'd like me to add something else! Anyway, if you liked this reference sheet/cheat sheet, start using what you have learned by setting up a quick test server! Read my article by clicking the below image!


    Servers

    The Developers Dilemma

    The Developers Dilemma

    Atom Text Editor With Code
    Code In Atom

        I’ve been programming for a while now and am enjoying the process a lot. The challenges, the mental stretches, and the success of seeing one’s dreams and ideas come to fruition can only be experienced rather than explained. Still, not all is wonderful throughout the process. For instance, choosing an IDE, Integrated Development Environment, can and often is an ordeal in and of itself. Each developer has questions and they need to have answers. What is the size of the program? Does it have syntax highlighting? How quickly does it launch? Is it open source? What programming languages work best with it?

        Visual Studio is about 4GB in size and launches slower than molasses falling from a container. DevC++ is about 500MB and launches in half the time Visual Studio does. Finally, Geany, it’s smaller than 120MB and launches faster than ether of them. We then have others like Netbeans, Code:Blocks, Eclipse, and many many more filling the rosters. Still, I have not found an environment that I love and would rave over. Rather, I have one or two that I tolerate and the rest I despise. This is frustrating and has dampened my enjoyment of programming to varying degrees during different situations. I will say that I’m picky though and at times am probably not using an environment to its fullest to better appreciate it. Nevertheless, there should be a half-way point where concessions are made on both sides.

        For instance, I will accept a larger program with more features providing it doesn’t take a decade to launch. Or, I will accept fewer supported programming languages for syntax highlighting, etc. To meet my requirements and needs I’ve taken a slightly different approach to tackle my dilemma. With the exception of Geany, I don’t actually use the above IDEs. I stick to text editors such as gEdit, gVim, Vim, Geany, and Nano. This greatly reduces the disk space a lotted to my IDE as I only need one of the programs. These editors have varying features and different skill requirements too: caugh, vim, caugh. I generally stick with Geany and then Vim as my auxiliary editor which keeps everything light, fast, and colored. But I want more! I need more! I need sub-panes, tree views, integrated terminals, and so on! What a plight!

        Geany has only two panes to work with and even then it’s clunky. The other editors don’t have secondary panes at all. Geany also allows for a single terminal sub-sub-pane. I need more than that and so I ended up finding Sublime. It’s a text editor with nearly everything I want. It really impresses me and I thought it couldn’t get any better as it has multi-panes for code, tree views, etc. Still, it is lacking a few key features needed or wanted. Sublime isn’t open source and it hasn’t any integrated terminal support. I felt lost and still unhappy even in the marvel that is Sublime. I searched, hunted, and scrounged about until I found my holy grail of text editors! The feeling was like an atom bomb hitting me with its glorious radiation and blissfully passing me away to Nirvana. Ironically or with my skilled writing and metaphors, the name of the text editor matches my description. It’s called Atom. It is powerful and open source. My two favorite descriptors together at last!

        Atom is a programmers dream come true. It allows for multiple sub-panes and multiple sub-terminals to code quickly and easily. It supports syntax highlighting and directory views. Plug-ins allow for even more enhancements that I can’t even begin to imagine! Not only that, Atom is as fast and lightweight as Geany. All of this and more under an open source license! All my current needs and picky wants are met and there is a new horizon of options available to me that I can’t wait to explore! I hope everyone will find this diamond in the rough and enjoy it as much as I do!

    The Best Linux, Unix, and BSD Open Source Programs

    The Best Linux, Unix, and BSD Open Source Programs

    Linux Apps

        It’s sometimes hard for me to believe that I’ve been using Linux for well over 6 years. In that time, I have steeped myself in the open source way and used and created many programs for different projects. I am sharing this with the world in hopes of guiding the new and old adopters of Linux, Unix, and BSD in finding wonderful applications that can get any project done. With old users, you might know of all of the ones mentioned here and disagree with my reasoning. Feel free to explain in the comments below and please provide an alternative! Note, I linked to the sites but you can download most of them through your package manager or getting a ppa as needed.

    Graphics

         Let’s start off with the first group, graphics. We need the ability to edit images as they are an important part of our lives. If you are the goto family member who does all he home videos and web work for the family site, then you need these tools! Obviously, you could be an artiest or person who just wants to edit or create an image and these will help you too.

    OK, so, the first three applications are probably not surprising to anyone who are new and old in the open source community. Gimp is the de facto choice to do ones image editing as it is the swiss army knife of image editors. It has a loooonnng history and is easily recommended. Next, Inkscape is a vector graphics editor and can be used to create or edit vector graphics. Illustrations, diagrams, line arts, charts, logos and complex paintings are but a few of the things one can do. It also makes up for Gimp’s lack of vector graphics editing options. Now, Darktable isn’t really an image editor but more a virtual darkroom to work with images and do color corrections. Still, it is a great tool for those editing raw photo files from a camera and then importing it to Gimp to finish with gusto. Once done editing images, we need an image viewer. I love Mirage as it fulfills my needs perfectly as an image viewer. It is lightweight and fast but has features for zooming, rotating, cropping and more. Last listed here is Gpick. I do web work and often need a particular color that a page is using. Gpick gets the color info on the screen for usage in other applications. This is great too for when using Gimp but it can’t select the color outside of its window.

    Multimedia

        Next, we have multimedia programs. This section is clearly important so you can listen to music, view your videos, make videos, edit videos, and more.

    OK, the first two are video players. SMPlayer is more a front end for Mplayer but Mplayer is my favorite player given it’s fast, has simple controls, and it plays plethora of video types. I add/mention VLC here because Mplayer doesn’t always have the ability to play the latest and greatest codec and VLC picks up the slack. After these two, OBS is listed because of the awesome ways to record the desktop. One can stream using it too but I use it to get quality recordings of the desktop to do tutorials with. Next to talk about is Blender. It is here for its Non-Linear Video Editor. The controls can be a steep learning curve to learn; but, once you master them, you can not only do video editing but 3D graphics stuff as well. It’s also the best editor for videos on *Nix systems as others tend to be iffy. Now, Deadbeef is indeed the best music player as it loves to state on its site. It plays all kinds of esoteric (PlayStation sound files for instance) and popular music types with great ease. Not only that, its user interface is dynamic and allows for you to setup the look of the player to your needs. Finally, the last two in the list are excellent audio controllers. The first is Alsamixer which is a graphical control interface through the terminal for the Alsa sound system. The second is Pavucontrol which controls the Pulseaudio sound system through its GTK interface.

    Internet/Network Tools

        In the next group, we have Internet and network programs. This section is clearly important for the fact that we are an interconnected world. To have tools for the Internet is important in order to access it, use it, and maintain it.

    OK, Firefox is a no brainer; though, I have less appreciation for it today than I have had before. It mostly comes down to their new plugin system, the weird applications they ship it with, and the loss of some tools that are near and dear to my heart such as Tabgroups. Anyways, it still is the best browser out there. Now, XChat is great for connecting to IRC channels (chat rooms) and even has a built in list of rooms to connect to. The next to talk about is Qbittorrent. It is a phenomenal torrent client that allows you to search databases from it and it has an excellent interface that is superior to Transmission. Now, Filezilla is great for getting files from different computers using FTP, SFTP, and other protocols. It has a great user interface as well that makes remote file access a breeze.

        It’s worth mentioning that the next few program we are mentioning gets us into territory that depends on the user. You may not need these programs and so it will dictate if you should download them or not. To start, Wireshark for instance is a network monitoring/capture tool. I use it for several projects but if you aren’t doing anything with networks, you likely wont need it. That being said, EtherApe is similar to Wireshark but only in that it can monitor your network. It is cool even if you don’t necessarily need it because it gives a graphical view of the network connections you are making and how much data you are sending. Last, Remmina is useful if you need to remote into computers and need a graphical connection. It has varying connection options such as ssh, RDP, and more.

    Office

        This group covers office tools of which there aren’t many per say. Office work is of course a necessary evil in the world; but, you don’t have to use horrible tools too.

    OK, other than Microsoft Word, the only contender for handling documents is Libreoffice. Period. As for Evince, it is the best PDF viewer out there and I’ve tried every one of them and continue to come back to it. For dictionaries, you really only have two options to chose from. The first is Google and the second it Xfce4 Dictionary. I keep Xfce4 Dictionary just in case I lose Internet access and need to look something up. Finally, using VYM depends on you. I like visualizing my logic and VYM helps me do just that.

    Gaming

        Games. What’s there to say? It’s games….

    OK, yes, Steam is present. It’s not open source but it’s the only exception to the list I’ve made. Next up, PlayOnLinux (PoL). It can be used for more than games but I think it’s safe to say it’s the biggest reason for using it. They may disagree and you might too but you and them are totally wrong…. I am joking but it is pretty true that the biggest reason to use PoL is for the games. Now, DOSBox will get the old but good games playing if you are a connoisseur of such antiquities. It’s the only emulator out there that I am aware of that targets old systems. Next, everything after DOSBox and before QJoypad are games worth downloading that are free and open source. Goodies like Freedoom and my favorite to this day, The Battle for Wesnoth, are listed. Last is QJoypad. I highly recommend this program to get your controllers working. Go to the site to get the latest version as the repos tend to be older.

    Tools/Other

        The final group listed here covers tools and other programs. System cleaning, virtualization, and more is l;isted here.

    Finally, we reach the end of our list of great apps! This section has a number of useful tools such a Virtualbox which will let you run virtual machines. From there, we have Gparted which manages partitions. Bleachbit and Gtkorphan keep the system clean while MidnightCommander is a great terminal file viewer. Gdebi is an excelent graphical interface to install deb packages and Htop views system resource usage from the terminal. Leafpad is a fast and small text editor to make quick changes to text files while Atom will allow for heavy lifting edits such as coding. Terminator is a great terminal that allows for multi-pane views, transparent background, and more. Next, Gufw is a great interface for managing firewall rules and Ghex lets you view hex files and edit them. Last is one of my creations, FXWinWrap. It is a front end for XWinWrap and makes it easier to set the various perameters.

    Well, this complets my list for awesome programs one can use in *Nix like systems. This list is by no means complete but makes a great start. I mentioned web work and one of the tiools I use. Another tool I use is wordpress-cli which helps me manage WordPress through the terminal than the WordPress interface. Linked below is my review for it.


    https://www.itdominator.com/wordpress-cli/

    Wordpress CLI

    W3C Killed Web Security

    W3C Killed Web Security

    W3C Logo
    W3C Logo

        It’s a sad day folks…. The W3C killed web security by accepting DRM without having a caveat that protects against DMCA’s (Digital Millennium Copyright Act) unreasonable reach. Security researchers are out; hackers are in. While I am sure that most users believe that companies and creators have the right to protect their IP (Intellectual Property), I am also sure they believe in having strong security and a reasonable right to use their purchased product in whatever manner they see fit. With the web, it was a last bastion that held to those principles. It was killed both brutally and without much compunction by W3C and its corporate backers in a vain attempt to stem the tide of piracy and illegal copying.

        Let’s be clear here for a moment about the current problem. I don’t have an issue with DRM. I don’t agree with it all the time but neither do I disagree with it all the time. No, the issue is with DMCA and it’s unreasonable reach in trying and failing to protect DRM. There are two sections in the DMCA that are of great interest. The core section I am referring to is Section 1201: Circumvention of copyright protection systems.

        Section 1201 affects the web and all technologies the most and is why it is a sad day for the internet. The EFF letter to W3C addresses some of the concerns regarding Section 1201 in its implementation in web technologies.
    Here are some of the critical points they made when hoping W3C would add a pretext for accepting DRM standards.

        “This covenant would allow the W3C’s large corporate members to enforce their copyrights. Indeed, it kept intact every legal right to which entertainment companies, DRM vendors, and their business partners can otherwise lay claim. The compromise merely restricted their ability to use the W3C’s DRM to shut down legitimate activities, like research and modifications, that required circumvention of DRM….
        More directly, such a covenant would have helped protect the key stakeholders, present and future, who both depend on the openness of the Web, and who actively work to protect its safety and universality. It would offer some legal clarity for those who bypass DRM to engage in security research to find defects that would endanger billions of web users; or who automate the creation of enhanced, accessible video for people with disabilities; or who archive the Web for posterity. It would help protect new market entrants intent on creating competitive, innovative products, unimagined by the vendors locking down web video.”

    There is the crux of the issue and why W3C should have had clear stipulations for implementing DRM into web technologies. There really isn’t anything protecting the user and their right to circumvent DRM when it is not infringing the patent holder or IP source. Security experts are now in a quasi grey area where their work is to determine vulnerabilities but they are violating DMCA. This helps no one but the bad guys and that is just sad in the day and age where billions of users need strong security the most.

        In addition, we don’t know who did and didn’t vote in favor of the implementation of a DRM standard. The votes are secret and that should disturb us even more than the terrible overreach of DMCA’s rules. It is worth noting that W3C’s member votes aren’t always public and by default one must opt-in for public disclosure of said vote. For an organization that affects our lives, to not have public disclosure of votes by default and as enforced practice is egregious. We all know why this is the case though. Companies don’t want to look like the bad guys even when they are. So they hide in anonymity as we all are left to hang by their terrible decisions. We can make some guesses as to who voted for the standardization but don’t know who else are their accomplices. Essentially, a private group gets to affect our lives without us holding them accountable. In addition, their votes wont stop piracy or illegal copying. So all in all, they hurt themselves as well as us with nothing to show for it but the further stripping of our rights.

        While it all looks bad, there are bright spots. The US government is looking to open source its code base as much as it reasonably can. Maybe they’ll step in and decide obtrusive DRM and its protective DMCA rules are too powerful. If interested in some of their projects, check out my article covering some of the best packages released to date.

    WordPress CLI

    WordPress CLI

    WordPress CLI

        As a person who is more comfortable in a terminal environment than GUI, I love finding tools that make my life easier and more comfortable. When I started using WordPress I was often aggravated by the fact that I had to move around an interface rather than just typing up some html or a command to get a task done. Obviously, that method works well for small scale projects but less so when one is managing a lot of content and pages. WordPress just makes life easier in that respect. But I still like having lower level access and this is where WordPress CLI comes in. WordPress CLI is a command line interface for managing WordPress sites. Things like updating the core, plugins, or themes is made faster since I SSH often into my site’s box and can type up some commands quickly to do those tasks and much more. As such, I wanted to make a simple collection of commands that everyone will find useful. But first, we need to install the plugin….

    Installing WordPress CLI

        As per the sites instructions, it is extremely easy to get up and running. All one simply needs to do is download the file, chmod it, and move it to the proper location.
    To download:
    wget https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
    OR
    curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar

    Next, let us make it runnable. Simply type:
    chmod +x wp-cli.phar
    Let’s make sure the file is working properly.
    php wp-cli.phar --info
    From there, we are ready to move it to its new home. Simply type:
    *Note: You might need to use sudo depending on your level of access to the server.
    mv wp-cli.phar /usr/local/bin/wp

    Using WordPress CLI

        OK, now that WordPress CLI is installed we are set to use it. The first thing to do though is cd to the WordPress directory. This is usually somewhere in /var.
    Once there, it’s time to play with some of the commands. First things first, one should know what plugins and themes are installed. To do that, simply type:
    wp plugin list && wp theme list
    This will list all the slugs associated with the plugins themes. One needs them in order to do things like disable, remove, and install them.
    Now, let us say that we got from the above commands:

    Plugins:
    +--------------------------------+----------+--------+---------+
    | name                           | status   | update | version |
    +--------------------------------+----------+--------+---------+
    | add-from-server                | active   | none   | 3.3.3   |
    | akismet                        | active   | none   | 3.3.3   |
    | backup                         | inactive | none   | 1.1.46  |
    | maintenance-mode-free          | active   | none   | 1.2     |
    +--------------------------------+----------+--------+---------+
    
    Themes
    +-----------------+----------+--------+---------+
    | name            | status   | update | version |
    +-----------------+----------+--------+---------+
    | twentyfifteen   | active   | none   | 1.8     |
    | twentyseventeen | inactive | none   | 1.3     |
    | twentysixteen   | inactive | none   | 1.3     |
    +-----------------+----------+--------+---------+
    

    We notice that Akismet is installed and know too that we are transitioning to use a different plugin to handle spam fighting. To uninstall it we do the following:
    wp plugin deactivate akismet && wp plugin delete akismet
    If we want it back, we can do the following:
    wp plugin install akismet && wp plugin activate akismet
    Now, we should update or at least check to see if there is an update needed.
    wp plugin update akismet
    The same principles are used with themes as well. Replace akismet with the theme name from the list and you get the same results but for themes. The only differences are that instead of plugin we use theme in the command and to disable a theme one needs to use the term disable rather than deactivate. Like so:
    wp theme disable twentyfifteen

    Final Thoughts

        As a final thought or two, it is worth noting how to find the slug for a plugin or theme. To do that, go to either https://wordpress.org/plugins/ or https://wordpress.org/themes/. From there, after finding something worth while, look at the end of the url to find what we need. For this example, use the plugin bbpress and look at the end of its URL: https://wordpress.org/plugins/bbpress/. Supplant that information like so:
    wp plugin install bbpress && wp plugin activate bbpress
    This will then install the plugin and activate it.
        Welp, this covers the basics and gets one started but there are other commands that are available. Simply go to their site to find them. Now that we have an new awesome tool to play with, click the image below to look at quick servers one can setup for WordPress.


    https://www.itdominator.com/quick-test-server/

    servers with a blue tinted globe

    Code.gov

    Code.gov

    Picture of code dot gov slogan
    Code.gov

        I just wanted to make a shout out to Code.gov and the work they do. If one isn’t sure of who or what they are they are the US government’s team working to opensource the code used by the government’s agencies. This post comes on the heals of an email I received from their mailing list which reminded me of their transition to open source their code. I can’t think of any better way to express democracy than through opening up a sizable chunk of ones code base.

    Here are 5 projects to keep an eye on


    5 — Consumer Financial Protection Bureau’s Owning a Home Project

        Hey, getting a home isn’t always easy but it can be with these tools provided by Consumer Financial Protection Bureau and its Owning a Home project. Everything is looked at from loan options, terminology, and costs.

    Link: https://github.com/cfpb/owning-a-home

    4 — National Archives and Records Administration’s File Analyzer Project

        So, this project came to my attention because I am programming a CSV file viewer. I’m considering other functions for my application and this file analyzer just might be the thing to give it a cool boost. It says that each file test generates a table of results and that is useful given my CSV viewer dumps a csv file into a GUI table view.

    Link: https://github.com/usnationalarchives/File-Analyzer

    3 — Department of Agriculture’s RIBD Project

        Ahh leisure…. Who doesn’t want to enjoy time off at beautiful federal lands, historic sites, museums, and/or other attractions?
    According to their site, the “Recreation Information Database (RIDB) provides data resources to citizens, offering a single point of access to information about recreational opportunities nationwide.”

    Link: https://usda.github.io/RIDB/

    2 — NSA’s Unfetter Project

        When not spying on us and the world, the NSA is helping us secure our data by giving tools that analyze gaps in our security posture.

    Link: https://iadgov.github.io/unfetter/

    1 — NASA’s 3D Resources

        I am a big fan of space and even bigger fan of making beautiful Blender renders. NASA’s 3D model collection is huge and gives great assets to space fans and art lovers alike to play with.

    Link: https://github.com/nasa/NASA-3D-Resources