Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

HTML TABLE (+FORMATTING)

TABLE ( = FORMATTING)


INTRODUCTION

The HTML tables allow web authors to arrange data like text, images, links, other tables, etc. into rows and columns of cells.
The HTML tables are created using the <table> tag in which the <tr> tag is used to create table rows and <td> tag is used to create data cells. The elements under <td> are regular and left aligned by default.

Table Heading

Table heading can be defined using <th> tag. This tag will be put to replace <td> tag, which is used to represent actual data cell. Normally you will put your top row as table heading as shown below, otherwise you can use <th> element in any row. Headings, which are defined in <th> tag are centered and bold by default.

Tables Backgrounds

You can set table background using one of the following two ways −
  • bgcolor attribute − You can set background color for whole table or just for one cell.
  • background attribute − You can set background image for whole table or just for one cell.
You can also set border color also using bordercolor attribute.



<table>...</table>

The table tag identifies and contains all table related content.

<caption> ...</caption>

The caption is a description of what the table is and what it contains.

<thead> ... </thead>

The table headers describe the type of information contained in each coloum underneath.

<tbody> ... </tbody>

The table contains the table's data or information.

<tfoot> .. </tfoot>

Table footers describe all footer content.

<tr> ... </tr>

Contains the information to be included in a single row of the table.

<th> ... </th>

Contains the actual information to be included in a single row of the table.

<td> ... </td>

Contains the actual information or data in a single table cell.

<colgroup> ... </colgroup>

Groups a single (or multiple) column for formatting purposes.

<col / >

Defines a single column of information inside a table.

EXAMPLE

<table>
<colgroup>
<col span="2" style="background-color:#181alt">
<col style="background-color:#2c323c">
</colgroup>
<tr>
<th>isbn</th>
<th>tilte</th>
<th>price</th>
</tr>
<tr>
<td>3476896</td>
<td>my first html</td>
<td>$53</td>
</tr>
</table>

SAMPLE



Python Class Reference

Python Class Reference


What are classes?

Classes are the foundation of object-orineted programming. Classes represent real-world things you want to model in your programs: for example dogs, cars, and robots. You use a class to make objects, which are specific instances of dogs, cars, and robots. A class defines the generalbehaviour that a whole category of object can have, and the information that can be associated with those objects.

Classes can inherit from each other - you can write a class that extends the functionality of an existing class. This allows you to code efficiently for a wide variety of situations.

Creating and using a class consider how we might model a car. What information would we associated with a car, and what behaviour wouldit have? The information is stored in variable called attributes, and the behaviour is represented by functions. Functions that are part of a class are called methods.

#The car class
class Car():
  """A simple attempt to model a car."""

  def_init_(self, make, model, year):
    """Initialize car attributes."""
    self.make = make
    self.model = model
    self.year =year

    #Fuel capacity and level in gallons.
    self.fuel_capacity = 15
    self.fuel_level = 0

  def fill_tank(self):
    """Fill gas tank to capacity."""
    self.fuel_level = self.fuel_capacity
    print("Fuel tank is full.")

  def drive (self):
    """Simulate driving."""
    print("The car is moving.")

Creating and using a class(cont.)

#Creating an object from a class

my_car = Car('audi', 'a4', 2016)

#Acessing attributes values

print(my_car.make)
print(my_car.model)
print(my_car.year)

#Calling methods

my_car.fill_tank()
my_car.drive()

#Creating multiple objects

my_car = Car('audi', 'a4', 2016)
my_old_car = Car('subaru', 'outback', 2013)
my_truck = Car('toyota', 'tacoma', 2010)

Modifying attributes

You can modify an attribute's value directly, or you can write methods that manage updating values more carefully.

#Modifying an attribute directly

my_new_car = Car('audi', 'a4', 2016)
my_new_car.fuel_level = 5

#Writing a method to update an attribute's value

def update_fuel_level(self, new_level):
  """update the fuel level."""
  if new_level <= self.fuel_capacity:
    self.fuel_level = new_level
  else:
    print("The tankl can't hold that much!")

#Writing a method to increment an attribute's value

def add_fuel(self, amount):
  """Add fuel to the tank."""
  if (self.fuel_level + amount <= self.fuel_capacity):
    self.fuel_level += amount
    print("Added fuel.")
  else:
    print("The tank won't hold that much.")

Naming conventions

In python class names are written in CamelCase and object names are written in lowercasewith underscore. Modules that contain classes should still be named in lowercases with underscores.

Class inheritance

If the class you're writing is a specialized version of another class , you can use inheritance, when one class inherits from another, it automatically takes on all the attributes and methods of the parent class. The child class is free to introduce new attributes and methods , and override attributes and methods of the parent class.

To inherit from another class inlcude the names of the parent class in parenthesis when defining the new class.

The __init__() method for a child class 
class ElectricCar(Car):
  """A simple model of an electric car."""
  def__init__(self, make, model, year):
    """Initialize an electric car."""
    super().__init__(make, model, year)

  #Attributes specific to electric cars.
  #Battery capacity in kWh.
  self.battery_size = 70
  #Charge level in %
  self.charge_level = 0

#Adding new methods to the child class

class ElectricCar(Car):
  --snip--
  def charge(self):
    """Fully charge the vehicle."""
    self.charged_level = 100
    print("The vehicle is fully charged.")

#Using child methods and parent methods

my_ecar = ElectricCar('tesla', 'models', 2016)
my_ecar.charge()
my_ecar.drive()


Finding you workflow

There are many ways to model real world objects and situations in code, and sometimes that variety can feel overwhelming. Pick an approach and try it - if your first attempt doesn't work, try a different approach.

Class inheritance(cont.)

#Overriding parent methods
class ElectricCar(Car):
  --snip--
  def fill _tank(self):
    """Display an error message."""
    print("This car has no fuel tank!")

Instances as attributes

A class can have objects as attributes. This allows classes to work together to method complex situations.

#A Battery class
class Battery():
  """A battery for an electric car."""

  def__init__(self, size=70):
    """Initialize battery attributes."""
    #Capacity in KWh, charge level in %.
    self.size = size
    self.charge_level = 0

  def get_range(self):
    """Return the battery's range."""
    if self.size == 70:
    return 240
    elif self.size == 85:
    return 270
#Using an instance as an attribute
class ElectricCar(Car):
  --snip--

  def__init__(self, make, model, year):
    """Intialize an electric car."""
    super().__init__(make, model, year)

    #Attribute specific to electric cars.
    self.battery = Battery()

def charge(self):
    """Fully charge the vehicle."""
    self.battery.charge_level = 100
    print("The vehicle is fully charged.")

#Using the instance
my_ecar = ElectricCar('tesla', 'model x', 2016)

my_ecar.charge()
print(my_ecar.battery.get_range())
my_ecar.drive()

Importing classes

Class files can get long as you add detailed information and functionality. To help keep your program files uncluttered, you can store your classes in modules and import the classes you need into your main program.

Storing classes in a file
"""Represent gas and electric cars."""

Class_Car():
  """A simple attempt to model a car."""
  --snip--

class Battery():
  """A battery for an electric car."""
  --snip--

class ElectricCar(Car):
  """A simple model of an electric car."""
  --snip--

#Importing individual classes from a module
from Car import Car, ElectricCar

my_beetle = Car('volkswagen', 'beetle', 2016)
my_beetle.fill_tank()
my_beetle.drive()

my_tesla = ElectricCar('tesla', 'model's', 2016)
my_tesla.charge()
my_tesla.drive()

#Importing an entire module
import car

my_beetle = car.Car('volkswagen', 'beetle', 2016)
my_beetle.fill_tank()
my_beetle.drive()

my_tesla = car.ElectricCar('tesla', 'models', 2016)
my_tesla.charge()
my_tesla.drive()

#Importing all classes from a module
from car import *

my_beetle = car.Car('volkswagen', 'beetle', 2016)

Classes in python 2.7

#Classes should inherit from object
class ClassName(object):
The Car Class in python 2.7
class car(object):
#Child class__init__()method is different
class ChildClassName(parentclass):
    def__init__(self):
        super(ClassName, self).__init__()
#The ElectricCar class in python 2.7
class ElectricCar(Car):
    def__init__(self, make, model, year):
        super(ElectricCar, self).__init__(make, model, year)

Storing objects in a list

A list can hold as many items as you want, so you can make a large number of objects from a class and store them in a list. Here's an example showing how to make a fleet of rental cars, and make sure all the cars are ready to drive.

#A fleet of rental cars
from car import Car, ElectricCar

# Make liststo hold a fleet of cars.
gas_fleet = []
electric_fleet = []

# Make 500 gas cars and 250 electric cars.
for _ in range(500):
    car = Car ('ford', 'focus', 2016)
    gas_fleet.append(car)
for _ in range (250):
    ecar = ElectricCar('nissan', 'leaf', 2016)
    electric_fleet.append(ecar)

# Fill tha gas cars, and charge electric cars.
for car in gas fleet
    car.fill_tank()
for ecar in electric_fleet:
    ecar.charge()

print("Gas cars:", len(gas_fleet))
print("Electric cars:", len(electric_fleet))

Screenshot

python class

 

Partial Complete Code

 

class Car():
  """A simple attempt to model a car."""
  def __init__(self,make,model,year):
    """Initialize car attributes."""
    self.make = make
    self.model = model
    self.year =year

    #Fuel capacity and level in gallons.
    self.fuel_capacity = 15
    self.fuel_level = 0

  def fill_tank(self):
    """Fill gas tank to capacity."""
    self.fuel_level = self.fuel_capacity
    print("Fuel tank is full.")

  def drive (self):
    """Simulate driving."""
    print("The car is moving.")

  def update_fuel_level(self,new_level):
    """update the fuel level."""
    if new_level <= self.fuel_capacity:
      self.fuel_level = new_level
    else:
      print("The tankl can't hold that much!")

  #Writing a method to increment an attribute's value
  def add_fuel(self, amount):
    """Add fuel to the tank."""
    if (self.fuel_level + amount<= self.fuel_capacity):
      self.fuel_level += amount
      print("Added fuel.")
    else:
      print("The tank won't hold that much.")

#Creating an object from a class


class ElectricCar(Car):
  """A simple model of an electric car."""
  def __init__(self, make, model, year):
    """Initialize an electric car."""
    super().__init__(make, model, year)
    #Attributes specific to electric cars.
    #Battery capacity in kWh.
    self.battery_size = 70
    #Charge level in %
    self.charge_level = 0

#Adding new methods to the child class

class ElectricCar(Car):
  # --snip--
  def charge(self):
    """Fully charge the vehicle."""
    self.charged_level = 100
    print("The vehicle is fully charged.")

#Using child methods and parent methods

my_ecar = ElectricCar('tesla', 'models', 2016)
my_ecar.charge()
my_ecar.drive()


my_car = Car('audi', 'a4', 2016)

#Acessing attributes values

print(my_car.make)
print(my_car.model)
print(my_car.year)

#Calling methods

my_car.fill_tank()
my_car.drive()

#Creating multiple objects

my_car = Car('audi', 'a4', 2016)
my_old_car = Car('subaru', 'outback', 2013)
my_truck = Car('toyota', 'tacoma', 2010)

#Modifying an attribute directly

my_new_car = Car('audi', 'a4', 2016)
my_new_car.fuel_level = 5

#Writing a method to update an attribute's value

HTML INPUT TYPE ATTRIBUETS

INPUT TYPE ATTRIBUETS


type=" "

Specifies the field input type, including text, password,date time,checkbox,password submit etc.

name=" "

Describes the name of the form.

value=" "

escribes the value or input field information.

size=" "

specifies the input element width in characters.

maxlength=" "

Identifies the maximum input element character numbers allowed.

required

another helpfully explicit tag, making sure the <input> element is completely field out prior to the user submitting the form.

step=" "

Identifies the legal number intervals for an input field.

width=" "

Specifies the width (in pixel) of an <input> element.

height=" "

Dictates the height (again, in pixels) of an <input>element.

place holder=" "

provides a helpful hint to the user describing what the <input> element values should be.

pattern-=" " 

Identifies a regular expression that the <input> element  gets checked against making sure the user entered the correct information.

min=" "

The maximum value allowed for each <input> element.

max=" "

The maximum value allowed for each <input> element.

autofocous

Says to make sure that the <input> element comes into focous after the page loads.

disabled 

Disables an <input> element on the form.

<textarea> ... </textarea>

Specifies a large text input for longer messages.

<select> ... </select>

Describe a drop-down box for user's to select one form a variety of options.

SELECT ATTRIBUTES



name=" "

The name for a drop down combination box.

size=" "

Specifies the number of available , visible options in a drop-down.

multiple

allows for multiple selections to be made at one time.

required 

Requires that a value is selected before a user can submit a form.

autofocous

Specifies that a drop-down list automatically comes into focous after a page loads.

<optgroup> ... </optgroup>

specifies the entire grouping of available options.

<option> ... >/options>

Defines one of the available options in the drop down list.

OPTION ATTRIBUTES


value=" "

Explains the options value available for selection.

selected

Define the default selected option for users.

<button> ... </button>

Define the clickable button for users to submit options.


EXAMPLE


<form action="action_page.php" method="post">
<fieldset>
<legend>Personal information:</legend>
First name:<br>
<input type="text" name="firstname" value="mickey" placeholder="first name"><br>
Last name:<br>
<input type="text" name="lastname" value="mouse" placeholder=Last Name"><br><br>
Favorite car brand:<br>
<select>
<option value="volvo">volve</option>
<option value="saab">saab</option>
<option value="mercedes">mercedes</option>
<option value="audi">audi</option>
</select>
<text"area name="description"></textarea>
<input type="submit" value="submit">
</fieldset>
</form>

SAMPLE



Python Passing a list to a function

Python Passing a list to a function



Passing a list to a function

You can pass a list as an argument to a function, and the function can work with the values in the list. Any changes the function makes to the list will affect the original list. You can prevent a function from modifying a list by passing a copy of the list as a argument.

#Passing a list as an argument
def greet users(names):
 """print a simple greeting to everyone ."""
 for name in names:
  msg = "Hello," + name + "!"
  print(msg)

usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

def print_models(unprinted, printed):
 """3d print a set of models."""
 while unprinted:
  current_model = unprinted.pop()
  print("printing " + current_model)
  printed.append(current_model)

#Store some unprinted designs,
# and print each of them.
unprinted = ['phone case', 'pendant', 'ring']
printed = []
print_models(unprinted, printed)

print("\nUnprinted;", unprinted)
print("printed:", printed)

defprint_models(unprinted, printed):
 """3d print a set of models."""
 while unprinted:
  current_model = unprinted .pop()
  print("printing " + current_model
  printed.append(current_model)
# Store some unprinted designs
# and print each of them.
original =['phone case', 'pendan', 'ring']
printed = []

print_models(original[:], printed)
print("\nOriginal:", original)
print("printed:",printed)



Screenshot

list function

Passing an arbitrary number of arguments 

Sometimes you won't know how many arguments a function will need to accept. Python allows you to collect an arbitrary number of arguments
into one parameter using the operator. A parameter that accepts an arbitrary number of arguments must come last in the function definition.

The ** operator allows a parameter to collect an arbitrary number of keyword arguments.


#Collecting an arbitrary number of arguments
def make_pizza(size, *toppings):
 """Make a pizza."""
 print("\nMaking a " + size + "pizza.")
 print("Toppings:")
 for topping in toppings:
  print("-" + topping)

#Make three pizzas with different toppings.
make_pizza('small', 'pepperoni')
make_pizza('large', 'bacon bits', 'pineapple')
make_pizza('medium', 'mushroom', 'peppers', 'onions', 'extra cheese')
#Collecting a arbitrary number of keywords arguments
def build_profile(first, last, **user_info):
 """Build a user's profile dictionary."""
 # Build a dict with the required keys.
 profile = {'first': first, 'last': last}

 # Add any other keys and values.
 for key, value in user_info.items():
  profile[key] = value

 return profile

#Create two users with different kinds 
# of information.
user_0 = build _profile('albert', 'einstein', location='princeton') 
user_1 =build _profile('marie', 'curie', location='paris', field='chemistry')

print(user_0)
print(user_1)

Screenshot 

arbitary list

 

What's the best way to structure a function?

 As you can see there are many ways to write and call a function. When you're starting out, aim for something that simply works. As you gain experience you'll develop an understanding of the more subtle advantages of different structures such as positional and keywords arguments, and the various approaches to importing functions. For now if your functions do what you need them to, you're doing well.

Modules

You can store your functions in a separate file called a module, and then import the functions you need into the file containing your main program. This alows for cleaner program files. (Make sure your module is stored in the same directory as your main program.)

modules.py

#Importing an entire module
import pizza 
pizza.make_pizza('medium', 'pepperoni')
pizza.make_pizza('small', 'bacon', 'pineapple')
#Importing specific function
from pizza import make_pizza

make_pizza('medium', 'pepperoni')
make_pizza('small', 'bacon', 'pineapple')
#Giving a module an alias
import pizza as p

p.make_pizza('medium', 'pepperoni')
p.make_pizza('small', 'bacon', 'pineapple')
#Giving a function an alias
from pizza import make_pizza as mp

mp('medium', 'pepperoni')
mp('small', 'bacon', 'pineapple')
#Importing all functions from a module
from pizza import *

make_pizza('medium', 'pepperoni')
make_pizza('small', 'bacon', 'pineapple')

pizza.py

def make_pizza(size, *toppings):
 """Make a pizza."""
 print("\n Making a " + size + "pizza.")
 print("Topping:")
 for topping in toppings:
  print("-" + topping)

Screenshot 

python modules

 

HTML FORMS (FORMATTING AND ATTRIBUTES)

 FORMS 

(FORMATTING AND ATTRIBUTES)



HTML Forms are required, when you want to collect some data from the site visitor. For example, during user registration you would like to collect information such as name, email address, credit card, etc.
A form will take input from the site visitor and then will post it to a back-end application such as CGI, ASP Script or PHP script etc. The back-end application will perform required processing on the passed data based on defined business logic inside the application.
There are various form elements available like text fields, textarea fields, drop-down menus, radio buttons, checkboxes, etc.

The HTML <form> tag is used to create an HTML form and it has following syntax −
<form action = "Script URL" method = "GET|POST">
   form elements like input, textarea etc.
</form>

Apart from common attributes, following is a list of the most frequently used form attributes −


Sr.NoAttribute & Description
1
action
Backend script ready to process your passed data.
2
method
Method to be used to upload data. The most frequently used are GET and POST methods.
3
target
Specify the target window or frame where the result of the script will be displayed. It takes values like _blank, _self, _parent etc.
4
enctype
You can use the enctype attribute to specify how the browser encodes the data before it sends it to the server. Possible values are −
application/x-www-form-urlencoded − This is the standard method most forms use in simple scenarios.
mutlipart/form-data − This is used when you want to upload binary data in the form of files like image, word file etc.


<form>..</form>

The form element creates a form spelling out how theform will operate based on its attributes.

<action>... </action>

The form action URL specifics where data is to be sent when a site visitor submits the form.

method=" "

The method attributes refers to the HTTP method(get post)" which dictates how to send the form data.

enctype=" "

This attributes dictates how the form data is to be enconded when submitting information back to the web server (for method="post" only).

autocomplete

Dictates wheather a form should have autocomplete on or off.

novalidate

Dictates wheather the form should not be validated when submitted.

accept-charsets

Identifies the character encording upon the form submission.

target

Tells where to display the form response after veing submitted generally one of the following:_blank,_self,_parent,_top.

<fieldset> ... </fieldset>

Identifies the group of all fields on the form.

<label>  ... </label>

A simple field label telling the user what to enter in each field.

<legend> ... </legend>

The form legend acts as a caption for the fieldset element.

<input />

 The form input attributes defines the type of field information to receive from a user.

Css Page Layout

Css Page Layout



CSS page layout techniques allow us to take elements contained in a web page and control where they are positioned relative to their default position in normal layout flow, the other elements around them, their parent container, or the main viewport/window.  The page layout techniques we'll be covering in more detail in this module are
  • Normal flow
  • The display property
  • Flexbox
  • Grid
  • Floats
  • Positioning
  • Table layout
  • Multiple-column layout
Each technique has its uses, advantages, and disadvantages, and no technique is designed to be used in isolation. By understanding what each method is designed for you will be in a good place to understand which is the best layout tool for each task.

Css Page Layout Examples

Box-shadow:

0   0   0    2px     #000,
0   0   0    3px     #999,
0   0   0    9px     #fa0, 
0   0   0   10px    #666,
0   0   0    16px   #fd0,
0   0   0    18px   #000;

CREATIVE PAGE LAYOUT EXTRACT

.columns  { column-count:  4;   column-gap:   10px; }

column-count = determine how many columns we need.

Column-gap = Determine the space between the columns(the gutter).

Css Text Align

The text-align property in CSS is used for aligning the inner content of a block element.

These are the traditional values for text-align:
  • left - The default value. Content aligns along the left side.
  • right - Content aligns along the right side.
  • center - Content centers between the left and right edges. White space on the left and right sides of each line should be equal.
  • justify - Content spaces out such that as many blocks fit onto one line as possible and the first word on that line is along the left edge and the last word is along the right edge.
  • inherit - The value will be whatever the parent element's is.
TEXT ALIGN EXTRACT

ta_1   {  text-align:  left;  }

Text-align = Specific the horizontal alignment of text.

Left = In this case, it sets all textto the left(instead of center or right aligned). 

Examples

This text is left aligned.
This text is right aligned.
I'm centered!
I'm justified. I fill the space exactly (except on the last line), even if I have to stretch a bit at times.
I inherit the alignment of my parent. In this case, that means left.

Css Font Weight

The font-weight property sets the weight, or thickness, of a font and is dependent either on available font faces within a font family or weights defined by the browser

The font-weight property accepts either a keyword value or predefined numeric value. The available keywords are:
  • normal
  • bold
  • bolder
  • lighter
FONT WEIGHT EXTRACT 

bold  {  font-weight:  bold;  }

Font-weight = Sets how thick or thin characters in text should be displayed.

Bold = In this case makes text BOLD. It can be either set to normal, bold, bolder, or, lighter.

Css Margin

The margin property defines the space around an HTML element. It is possible to use negative values to overlap content.
The values of the margin property are not inherited by the child elements. Remember that the adjacent vertical margins (top and bottom margins) will collapse into each other so that the distance between the blocks is not the sum of the margins, but only the greater of the two margins or the same size as one margin if both are equal.
We have the following properties to set an element margin.
  • The margin specifies a shorthand property for setting the margin properties in one declaration.
  • The margin-bottom specifies the bottom margin of an element.
  • The margin-top specifies the top margin of an element.
  • The margin-left specifies the left margin of an element.
  • The margin-right specifies the right margin of an element.
The margin property allows you set all of the properties for the four margins in one declaration.

Extract To Align Text With Display And Margin Property

centre { text-align: centre : margin : auto ; display: block; }

Text-align = Specific the horizontal alignment of text.

Margin = Specific all the margin properties.

Display = Specific the type of box used.

Css Text Decoration

The text-decoration property adds an underline, overline, line-through, or a combination of lines to selected text.

Values 
  • none:  no line is drawn, and any existing decoration is removed.
  • underline:  draws a 1px line across the text at its baseline.
  • line-through:  draws a 1px line across the text at its "middle" point.
  • overline:  draws a 1px line across the text, directly above its "top" point.
  • inherit:  inherits the decoration of the parent.
The blink value is in the W3C spec, but it is deprecated and will not work in any current browser. When it worked, it made the text appear to "blink" by rapidly toggling it between 0% and 100% opacity.
Text Decoration Extract
no_td : hover  { text-decoration : none; }
Text-Decoration = Used to remove underlines from links.
None = In this case, underline is removed when the mouse hovers over the link.
Css Float And Clear
The CSS float property specifies how an element should float.

The CSS clear property specifies what elements can float beside the cleared element and on which side.

Clear And Float Extract

clear  { float: none; clear: both; }

Float = Used to remove underlines from links.

clear: both; = Specific which side(s) of an element floating elements are not allowed. In this case no floating elements allowed on the left or the right side of the text.