Big background image?

So you got a big background image and you want to have it size correctly when you play with the screen sizes? Here are two quick ways to do that.

One is you can do this

background: url("./images/melt_down.jpg") no-repeat center center fixed;
background-size: cover;

That will have the background picture cover the whole area.

or you can try this.

background-size: 100% 100%;

That will size the image for you automatically as well. Of course you should play with the margin % sizes.

If these two solutions don’t cut it you can always just use media queries and specify the background image sizes in pixels at certain break points you see. To find your break points just move the browser window from big to small and back and notice sizes where you should change the size of the background or whatever other elements need to be moved. This is completely up to the user but as you do this you will find natural break points that will catch your eye. Thanks for reading!

– Out

Centering technique html css

We can center a section of html in one way by creating a class for the section, say class=”container”.  Then we can set its margin attribute to margin: 0 auto;, this will set margin-top and margin-bottom to 0px and set the left and right margins to auto.  That means the browser will automatically set equal margin sizes on left and right of the container.

All you need now is to provide a width.  This can be a fixed px size like say 600px;, or you can use a percent to be more responsive.  This will center your container.

 

.container { margin: 0 auto; padding-left: 30px; padding-right: 30px; width: 960px; }

HTML CSS

So I have been relearning the right way about html and css.  There are so many rules and edge cases that I never really grasped everything that was going on.  So I took a bottom up approach that was project based because if you don’t work on projects and have any context, what ever book you read about css html design patterns will go one ear and out the other.

I spend most of my time on quora or stackoverflow for fixing edge cases and on forums to see what others have done for centering situations or when containers collapse due to floating content on html block level elements.

Here is a great reference book to learn all the basics of html css and their design patterns.

http://learn.shayhowe.com/

You don’t have to read it back to back.  I would find a project work on it, then as I come across problems or concepts that don’t come clear.  Just refer to the table of contents in this site and have a quick read.  You will find great, clearly written explanations of why things happen the way they do in html/css.

mutating the caller

Explain why the last line in the below code prints “hello world”. What does this demonstrate?


def change(param)
param << " world"
end

greeting = "hello"
change(greeting)

puts greeting

The last line here prints “hello world” because even though the variable greeting is set as “hello”, when the method was run it was given that variable as a parameter and the code in the method mutated the caller. This changed the orignal value of greeting to “hello world”. This demonstrates mutating the caller.

variable pointers

Explain why b is still “hello”.


a = "hello"
b = a
a = "hi"
a << " world"

puts a # hi world
puts b # hello

b is still “hello” because when you declared `b = a`, ruby had that variable b point to the actual memory location of a. It makes sense to save memory and just point to that space.

Once you reassigned `a = “hi”` what happens now is that a is given its own location in memory since a is being reassigned. so now a would give you ‘hi’ and b would give you ‘hello’. notice there are 2 different memory locations now, one holding the value or variable b the other for variable a value. If you check the object ids for each variable you will notice they are different.

Then we did `a << ” world”` this just mutated and appended the string ” world” to a. SO now we get for a, “hi world”, and b gives us “hi”
This is an example of variable pointers.

method scope?

Explain why the following code raises an exception.


str = &quot;hello&quot;

def a_method
puts str
end

This code will raise an exception NameError: undefined local variable or method str for main:Object, because this would be a method call to a_method. Inside this method it asks for ruby to puts str, str variable is initialized outside this method. But on a method call you cannot pass in local variables unless you pass them in as parameters to the method. Methods have their own scope.

So I would pass in the variable to this method like so.


str = 'hello'

def a_method(str)
puts str
end

a_method(str)

 

 

Explain why the last line outputs “hello”. What’s the underling principle in this code example?


str = &quot;hello&quot;

def a_method
str = &quot;world&quot;
end

puts str

The last line outputs “hello” because it was initialized outside the scope of this method, and since the method isn’t passing in the variable str it cannot assess that variable. SO when we do puts str it sees that it was initialized as “hello”, it cannot see what happened inside the method since it cannot access the variable in the method since it wasnt brought in as a parameter.

this is an example of method scope and variable scope. Methods have their own scope. Since the variable str wasn’t brought in as a parameter to the method, inside the method variable str is initialized in its own scope(not accessible outside this method).

Once outside this method, we have no access to the variable str that was initialized inside the method. Instead we have access to the local variable str that was initialized outside our method, in the current scope and the value of str = “hello” .

 

 

ruby scope examples

In the code below, explain why the last line outputs 2.
What’s the underlying principle this example illustrates?


str = 1

loop do
str = 2
break
end

puts str # output is 2`

the output of the last line is 2, because in ruby if a local variable is initialized outside a block with inner scope, the inner scope has access to that variable. The rule in ruby is that “Inner scope can access variables initialized in outer scope but not vice versa”

 

Explain why the code below raises an exception.


loop do
str = 2
break
end

puts str

This code raises an exception of undefined local variable or method for str because loop do..end is a method block invocation thus creating inner scope. The str = 2 was initialized inside this scope and not initialized outside the scope. SO if you try and access that local variable thats create in the scope of this block it will not have access to the variable. If you initialized this variable outside the block above the code you will be able to access the str variable on the outside.

Hashes

Question:  Build me a method that takes a query shown below and returns those products from the array.

</pre>
PRODUCTS = [
{ name: "Thinkpad x210", price: 220 },
{ name: "Thinkpad x220", price: 250 },
{ name: "Thinkpad x250", price: 979 },
{ name: "Thinkpad x230", price: 300 },
{ name: "Thinkpad x230", price: 330 },
{ name: "Thinkpad x230", price: 350 },
{ name: "Thinkpad x240", price: 700 },
{ name: "Macbook Leopard", price: 300 },
{ name: "Macbook Air", price: 700 },
{ name: "Macbook Pro", price: 600 },
{ name: "Macbook", price: 1449 },
{ name: "Dell Latitude", price: 200 },
{ name: "Dell Latitude", price: 650 },
{ name: "Dell Inspiron", price: 300 },
{ name: "Dell Inspiron", price: 450 }
]

query = {
price_min: 240,
price_max: 280,
q: "thinkpad"
}

query2 = {
price_min: 300,
price_max: 450,
q: 'dell'
}

&nbsp;

def hash_getter(query)
PRODUCTS.select do |hsh|
((hsh[:name].start_with? query[:q].capitalize) && ((hsh[:price]) >= query[:price_min]) && (hsh[:price] <= query[:price_max] ))
end
end

bubble sort ruby

Basically bubble sort will sort a collection by looping through a collection and checking if the current position array[i] value in the collection is greater than the next position array[i+1] in the collection.  We also set a swapped variable = false.  If the first value is greater than the next value, then we swap those values and set swapped variable to = true.


arr = [2,49, 400,25,4, 23, 1, 4,2, 3000, 42]

def bubble_sort(array)
length = array.length

loop do
swapped = false
(length -1).times do |i|
if array[i] > array[i+1]
array[i], array[i+1] = array[i+1], array[i]
swapped = true
end
end
break if !swapped
end
array
end
puts bubble_sort arr

In the inner loop if we swap a value, meaning the collection was not sorted, we set the swapped value to true.

Notice that I have a variable of swapped = false, so essentially we will continue to loop after the inner loop finishes unless the swapped value becomes false.  Then I can break out of my outer loop and return the array.

Bubble sort is a slow algorithm, bad at scaling.  If we increase our collection size by even a little it will dramatically increase our run time.  There is a relationship between the input size and run time.

The worst case scenario is when our collection is given in descending order.  This means we have to do the maximum number of swaps to sort it.  In the worst case if we have n amount of elements in the array, we have to perform ` cn2` where c is a constant even if n changes.  If every swap takes a constant amount of time, the run time of bubble sort will increase quadratically as input size increases.  This means bubble sort is O(n2), or run time scales quadratically.  

The amount of memory this sort takes can also be approximately measured using big O.  In this case we don’t allocate any additional memory so bubble sort’s space complexity is O(1) or constant.

Black jack OOP

Another basic OOP ruby program, this time twenty-one or blackjack.  Come try it out on your console!

class Card
FACES = (2..10).to_a + [‘J’, ‘Q’, ‘K’, ‘A’]
SUITS = [‘H’, ‘D’, ‘S’, ‘C’]

def initialize(suit, face)
@suit = suit
@face = face
end

def to_s
“The #{face} of #{suit}”
end

def face
case @face
when ‘J’ then ‘Jack’
when ‘Q’ then ‘Queen’
when ‘K’ then ‘King’
when ‘A’ then ‘Ace’
else
@face
end
end

def suit
case @suit
when ‘H’ then ‘Hearts’
when ‘D’ then ‘Diamonds’
when ‘S’ then ‘Spades’
when ‘C’ then ‘Clubs’
end
end

def ace?
face == ‘Ace’
end

def king?
face == ‘King’
end

def queen?
face == ‘Queen’
end

def jack?
face == ‘Jack’
end
end

class Deck
attr_accessor :cards

def initialize
@cards = []
Card::SUITS.each do |suit|
Card::FACES.each do |face|
@cards << Card.new(suit, face)
end
end
scramble!
end

def scramble!
cards.shuffle!
end

def deal_one
cards.pop
end
end

module Hand
def show_hand
puts “—-#{name}’s Hand —-”
cards.each do |card|
puts “=> #{card}”
end
puts “=> Total: #{total}”
puts “”
end

def total
total = 0
cards.each do |card|
if card.ace?
total += 11
elsif card.jack? || card.queen? || card.king?
total += 10
else
total += card.face.to_i
end
end

# correct for aces
cards.select(&:ace?).count.times do
break if total <= 21
total -= 10
end
total
end

def add_card(new_card)
cards << new_card
end

def busted?
total > 21
end
end

class Participant
include Hand

attr_accessor :name, :cards
def initialize
@cards = []
set_name
end
end

class Player < Participant
def set_name
name = ”
loop do
puts “What’s your name?”
name = gets.chomp
break unless name.empty?
puts “Sorry, must enter a value.”
end
self.name = name
end

def show_flop
show_hand
end
end

class Dealer < Participant
ROBOTS = [‘R2D2’, ‘Hal’, ‘Chappie’, ‘Sonny’, ‘Number 5’]

def set_name
self.name = ROBOTS.sample
end

def show_flop
puts “—- #{name}’s Hand —-”
puts “#{cards.first}”
puts ” ?? ”
puts “”
end
end

class TwentyOne
attr_accessor :deck, :player, :dealer

def initialize
@deck = Deck.new
@player = Player.new
@dealer = Dealer.new
end

def reset
self.deck = Deck.new
player.cards = []
dealer.cards = []
end

def deal_cards
2.times do
player.add_card(deck.deal_one)
dealer.add_card(deck.deal_one)
end
end

def show_flop
player.show_flop
dealer.show_flop
end

def player_turn
puts “#{player.name}’s turn…”

loop do
puts “Would you like to (h)it or (s)tay?”
answer = nil
loop do
answer = gets.chomp.downcase
break if [‘h’, ‘s’].include?(answer)
puts “Sorry, must enter ‘h’ or ‘s’.”
end

if answer == ‘s’
puts “#{player.name} stays!”
break
elsif player.busted?
break
else
# show update for hit
player.add_card(deck.deal_one)
puts “#{player.name} hits!”
player.show_hand
break if player.busted?
end
end
end

def dealer_turn
puts “#{dealer.name}’s turn…”

loop do
if dealer.total >= 17 && !dealer.busted?
puts “#{dealer.name} stays!”
break
elsif dealer.busted?
break
else
puts “#{dealer.name} hits!”
dealer.add_card(deck.deal_one)
end
end
end

def show_busted
if player.busted?
puts “It looks like #{player.name} busted! #{dealer.name} wins!”
elsif dealer.busted?
puts “It looks like #{dealer.name} busted! #{player.name} wins!”
end
end

def show_cards
player.show_hand
dealer.show_hand
end

def show_result
if player.total > dealer.total
puts “It looks like #{player.name} wins!”
elsif player.total < dealer.total
puts “It looks like #{dealer.name} wins!”
else
puts “It’s a tie!”
end
end

def play_again?
answer = nil
loop do
puts “Would you like to play again? (y/n)”
answer = gets.chomp.downcase
break if [‘y’, ‘n’].include? answer
puts “Sorry, must be y or n.”
end

answer == ‘y’
end

def start
loop do
system ‘clear’
deal_cards
show_flop

player_turn
if player.busted?
show_busted
if play_again?
reset
next
else
break
end
end

dealer_turn
if dealer.busted?
show_busted
if play_again?
reset
next
else
break
end
end

# both stayed
show_cards
show_result
play_again? ? reset : break
end

puts “Thank you for playing Twenty-One. Goodbye!”
end
end

game = TwentyOne.new
game.start