[PHP]Cases and Switch Statements

Today’s post is to share some knowledge that I have gained on PHP, and each language has their own version of Cases and Switches. Here is a bit of what I have learned to do with Switches. It allows us to have a variable and to execute a certain block of code when the conditions are met.

Breaking out of Loops and Continuing them.

Breaking out of a loop

You can completely break out of a loop when it is still running. This is achieved with the break keyword. Once a loop is exited, the first statement right after it will be executed. The break keyword provides an easy way to exit a loop if an error occurs, or if you found what you were looking for.
Example:

In the above example, the for loop is set to iterate 9 times and print the current value of the variable a during each iteration. The if statement within the loop states that when the variable a is equal to 5, break out of the loop.

Output:

 

Continuing a loop

While you can break out of a loop completely with the break keyword, there is another keyword used when working with loops – the continue keyword. Using the continue keyword in a loop will stop the loop at some point and continue with the next iteration of the loop from the beginning of it.
Example:

In the above example, the for loop is set to iterate 9 times and print the current value of the variable a during each iteration. The if statement within the loop states that when the variable a is equal to 5, stop the loop and continue with the next iteration of the loop from the beginning of it. For this reason, all the numbers except the number 5 are printed.
Output:

NOTE: For the continue keyword to work properly, the conditional statement needs to come first just like in the above example.

Introduction to Java Programming – For Loops

Foor Loops – one of the most common types of loops. The “For” part of “For Loop” seems to have lost its meaning. But you can think of it like this: “Loop FOR a set number of times.”

As said above, a for loops allows you to run a set of code until a certain number of results have been completed. To use a for() loop you must have a value that you are starting at, and then a ending number, and a number to increment it by.

for ( start_valueend_valueincrement_number ) {

start value = i; end value = 5; i++ is i +1

In the example below we are starting with the variable i = 0 and we want it to count up to 5 as long as i is not greater than 5 it will run the System.out.println(“The value of i is ” +i);

I also added +i so it would count out the number it was on.

This outputs

Introduction to Java Programming – More on Loops

Yesterday I introduced you to the while loop, but in Java and other programming languages there are also other types of loops you can perform. So I will go ahead and list the 3 loops that you can perform in Java.

  • While (while) Loop – this is a control structure that allows you to repeat a task a certain amount of times.
  • Do-While (do-while) Loop – do-while loop is similar to the while loop, except that the test condition occurs at the end of the loop.
  • For Loop (for) – for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Example of a While Loop

This would output

 

Example of a do-while loop

 

This would output

 

Example of for loop

 

This would output

 

I will be going over each one of these individually in their own seperate blog posting so it can become easier for all of us to understand.

Introduction to Java – While Loops

In previous articles you learned about variables and types and now it’s time to speak about control statements in Java. There are several types of statements in Java, which are useful for repeating things. Before we are going any further let’s check simple example printing “Hello!” thing to the console ten times:

 

I am about to print "Hello!" ten times.
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
Gosh... That was long. Is there a way to compact repeating things?
 

 
Well there is an easier way and we will demonstrate this by doing a While Loop.

In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The while loop can be thought of as a repeating if statement.

The while construct consists of a block of code and a condition. The condition is evaluated, and if the condition is true, the code within the block is executed. This repeats until the condition becomes false. Because while loop checks the condition before the block is executed, the control structure is often also known as a pre-test loop. Compare with the do while loop, which tests the condition after the loop has executed.

Here is my code, I have added a +1 to each output so you can see it count out to 10 hello’s
public class Application {
public static void main(String[] args) {
int value = 0;

while(value < 10)
{
System.out.println("Hello " + value);

value = value + 1;
}
}

}
I have declared the value as 0, and in programming terms 0 is always going to be your first number. So just because the System.out.printIN only showed you 9 don’t get fooled.

Let’s break down the code from above.

We declared our
int value = 0;
which is our starting point for this exercise.

Then next was our while statement
while(value < 10)
this bit of code is saying run until value reaches 10, if we would have made our int value = 20; we would not be able to run the program, as it is already greater than 10 and would have no work to output.

Introduction to Java Programming – Variables and Types Excercise 2

In the previous posts on Variables and Types First Post Second Post we have gone over how to use them, but now we are going to do some exercises to show what we have learned.
public class Application {
public static void main(String[] args) {

String blank = " ";

String name = "Bob";

String text = "Hello";

String greeting = text + blank + name;

System.out.println(greeting);

System.out.println("Hello" + " " + "Bob");

}
}

This would give us the output of the following for both System.out.printIn();

Hello Bob because we called the string named greeting which has the variables text + blank + name all together already.

Where the second Hello Bob was called individually by each variable/type and then outputted.

let’s do another one,

Introduction to Java – Variables and Types part 2

I was looking over my previous post that I had made on Java Variables and decided that I could take is one step deeper and explain even more. When I say explain it is for the people who are like me and need to know everything about variables.

A variable 3 key features at it’s disposal

  • a Type: which is something you can store inside. Think of it like a box in which you stick things.
  • an identifier: a name of a variable can help you designate what you want the code to represent and help you decode/debug your code in the future.
  • an initializer : you can intialize a variable with a value.

Here are some examples of what I was talking about above.

Code
Explanation
int a; Define a variable called “a” of type int.
int b = 5; Define a variable called “b” of type int and initialize it with 5.
int a, b; Define two variables called “a” and “b”.
int a = 5, b; Define two variables called “a” and “b”. Variable “a” is initialized with 5.

Variable’s value could be changed using the assignment operator:

a = 5;
a = b + 5;
a = a + b;

Variable names in Java are case-sensitive. Variable name:

  1. a sequence of Unicode letters and digits of unlimited length;
  2. can begin with a letter, the dollar sign “$”, or the underscore character “_”;
  3. whitespaces in name is not permitted;
  4. must not be a keyword or reserved word.
Allowed names
Disallowed names
  • name
  • _last_name
  • $myvar
  • RANDOM_NUMBER
  • my2ndName
  • 2nd_name (can’t start with a number)
  • n! (“!” is not allowed)
  • last name (whitespaces are not allowed)

 

Above we showed the names, which are correct from the viewpoint of Java language’s syntax. But Java also has naming conventions and we strongly recommend you to name your variables according to them. There are simple rules of giving good names. Variables’s name:

  1. starts with a letter;
  2. uses camel notation: start name with a small letter. If name consists of two words or more, start all the other words with capitals;
  3. doesn’t contain “$” and “_” characters.
Names violating convention
Names complying with convention
  • last_name
  • $myvar
  • RANDOM_NUMBER (good name for a constant)
  • my2ndName
  • lastName
  • myVar
  • randomNumber
  • mySecondName

I hope this clears up any confusion that you may have on variables.

Java Variable Excercise

The goal of this exercise was to create h3110 w0r1d 2.0 True

I also show in this excercise that you can name your variables anything as when you call them you call them properly. Name your variables something that you can remember and make sense to why you are calling them. So while you are coding you can figure out quickly what it is supposed to do.
public class Main {

public static void main(String[] args) {

short three = 3;

long harryfavoriteband = 3110;

byte zero = 0;

char w = 'w';

int one = 1;

char romeo = 'r';

char delta = 'd';

double dec = 2.0;

boolean harry = true;

 

String output = "H" + harryfavoriteband + " " + w + zero + romeo + one + delta + " " + dec + " " + harry;

System.out.println(output);

}

}

Output : h3110 w0r1d 2.0 True

Installing GitLab to Make Your Own GitHub Server Ubuntu 12.04

Git and GitHub are awesome tools that make managing and administering lots of Git repositories and their associated permissions a breeze. This is wonderful if you’re writing open source software, but when writing closed source software you may not want to trust your code to a third party server. So how can you get the control, flexibility and ease of use of something like Github or BitBucket without hosting your git repositories on servers outside of your control?

Enter GitLab. GitLab provides a simple but powerful web based interface to your Git repositories a la GitHub, only you can host it on your own cloud server, control access as you see fit, and repo size is limited only by how much storage space your server has. This tutorial will walk you through setting up a DigitalOcean VPS as a GitLab server.

It assumes you’re using a brand new Ubuntu 12.04 VPS. We’ll be installing all the necessary software needed to make GitLab work. If you are using an existing VPS (droplet) or a different Linux distro you may have issues, especially with incompatible Python and Ruby versions. Make sure you have Ruby 2.0 and Python 2.7 installed before beginning.

The first step is to install some required packages:

Make sure you don’t have Ruby 1.8 installed (on a default Ubuntu 12.04 VPS it won’t be).

Install Ruby 2.0 (this will take a while):

When it’s finished you can check to make sure that you have Ruby 2 (not 1.8) installed by doing a:

If the output looks like the below then you’re good:

Now we need to install the Bundler gem:

And create a git user for GitLab to use:

Installing the GitLab Shell


Download the GitLab shell with the following commands:

You now have a copy of GitLab Shell 1.7.0, and the example config.yml is ready to go.

If you have a domain name pointed at this VPS, then you should take the time to editconfig.yml to use this domain.

Near the top there will be a line that looks like:

Change the http://localhost/ portion to match your domain name. So if your domain is www.YOURDOMAIN.com the line should look like this:

Now you can run the GitLab shell installer:

Database Setup


We’ll set up GitLab to use a MySQL backend. The first step is to install MySQL with the below command. During the install process it will ask you to set a MySQL root password. Set it to whatever you like, but note it down as you will need it for the next steps.

MySQL is now installed and the root password is set to the value you chose in the last step. We now need to create a MySQL user for GitLab to use. To do this we’ll first save the necessary SQL queries to a temporary file. Type:

 

Paste in the following, changing the $password on the first line to a real password. Keep track of this password as this will be your GitLab’s database password.

Now save the file and execute the following command (entering your MySQL root password from the first step at the prompt) to have MySQL execute your queries:

To make sure your new MySQL user was created successfully let’s log in to mysql using thegitlab user:

If you see some text followed by a:

line then everything worked successfully. Go ahead and type:

 

at the mysql> prompt to exit MySQL, and delete the tempfile file since it contains a password:

 

At this point we have everything configured to install GitLab successfully, so let’s proceed with the installation:

 

Just like we did with the GitLab shell set up, if you have a domain configured for your VPS we need to edit the config.yml to use that domain.

 

Near the top of the file you should a text block that looks like the following:

 

Change the host: entry to match your domain name. If your domain is www.YOURDOMAIN.com, then it should look like this:

 

Let’s also set some linux file permissions, configure the git user’s Git config, and set up some GitLab config and directories for the git user:

 

Now we need to tell GitLab to use the gitlab MySQL user we set up earlier. To do this, edit the config/database.yml file:

 

Near the top there will be a section called production: which will contain username and passwordentries. By default it looks like this:

 

Change the username and password entries to match the GitLab database user we set up earlier. So if the password you used for your GitLab MySQL user was $password the edited file should look like this:

 

Save the file, and we’ll secure it so that other users of the server can’t see the password:

 

Let’s install a few more needed gems (this step may take awhile):

 

And run some final setup (type yes when it asks if you want to continue):

 

After this finishes it will print a lot of information onscreen and at the end will showAdministrator account created and give you your administrator credentials. It should look something like the below:

 

Now let’s set GitLab to start up whenever your server boots:

 

Run the following to make sure everything is working:

 

If there are no error messages and the data outputted by that command looks right then your GitLab install is working. Almost finished! Start up GitLab with this command:

Setting Up NGINX


GitLab works with the nginx web server by default. If you already have your own web server such as Apache set up then these steps don’t apply. Check out these recipes for info on how to configure GitLab with other web servers. Otherwise follow these directions to install and configure nginx to work with GitLab:

 

Edit /etc/nginx/sites-available/gitlab to use your domain name:

 

A little ways from the top of the file you will see an entry server_name which is set toYOUR_SERVER_FQDN. As in the previous steps, replace the YOUR_SERVER_FQDN with your domain name. The original file looks like this:

 

If your domain is www.YOURDOMAIN.com then you should change it to look like this:

 

And restart nginx:

 

Voila! You’re done. Connect to GitLab via your web browser using the Admin login and password from above (default user: admin@local.host, pass: 5iveL!fe) and enjoy GitLab.

Introduction to Java – Variables and Types

 

  • Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in “non-static fields”, that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.
  • Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword finalcould be added to indicate that the number of gears will never change.
  • Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.
  • Parameters You’ve already seen examples of parameters, both in the Bicycle class and in the main method of the “Hello World!” application. Recall that the signature for the main method is public static void main(String[] args). Here, the argsvariable is the parameter to this method. The important thing to remember is that parameters are always classified as “variables” not “fields”. This applies to other parameter-accepting constructs as well (such as constructors and exception handlers).

 

There are 8 types o Variables that are classified as the Primitive Variables of Java, they each do separate tasks in each program and you will mostly use byte, int, long and double in normal programming.

  • byte: The byte data type is an 8-bit signed two’s complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable’s range is limited can serve as a form of documentation.
  • short: The short data type is a 16-bit signed two’s complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
  • int: By default, the int data type is a 32-bit signed two’s complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigneddivideUnsigned etc have been added to theInteger class to support the arithmetic operations for unsigned integers.
  • long: The long data type is a 64-bit two’s complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. The unsigned long has a minimum value of 0 and maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigned,divideUnsigned etc to support arithmetic operations for unsigned long.
  • float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use thejava.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.
  • double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
  • boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its “size” isn’t something that’s precisely defined.
  • char: The char data type is a single 16-bit Unicode character. It has a minimum value of 'u0000' (or 0) and a maximum value of 'uffff' (or 65,535 inclusive).