Need help with a project coded in Ruby. It is required that i use counting hashe
ID: 3602888 • Letter: N
Question
Need help with a project coded in Ruby. It is required that i use counting hashes and the Regexp#match method and the MatchData object to get the fields. I am also only supposed to iterate over the array once throughout the entire program.
Below is the output it should generate:
Start with a descriptive header followed by at least one blank line, using the variable for the file name:
----------------------------------------------------
Statistics for the Apache log file access_log
-----------------------------------------------------
The first sub-report is a histogram of IP addresses (in a field of 20 spaces) using the asterisk (*) character, with a short header to explain what the data represent. For example:
Frequency of Client IP Addresses:
::1 *******
192.168.1.142 ************************************
192.168.1.1 *************
192.168.1.34 ****
192.168.1.127 ***************
192.168.1.56 *********
192.168.1.138 *********
192.168.1.156 ***************
The second sub-report is a table showing the number of times each unique URL appears in the file with a short header. Note that the forward slashes (/) are part of the URL patterns and that patterns such as /javajam4 are distinct from /javajam4/. (We are tracking what end-users type in the browser, not the number of pages in the site.) Use printf to display the URL in a consistent field width such that the totals are aligned as shown below. You may have to experiment with different widths to find a spacing that works for all URLs in the file.
Frequency of URLs Accessed:
* 7
/ 10
/noindex/css/bootstrap.min.css 1
/noindex/css/open-sans.css 1
/images/apache_pb.gif 1
/images/poweredby.png 1
/noindex/css/fonts/Bold/OpenSans-Bold.woff 3
/noindex/css/fonts/Light/OpenSans-Light.woff 3
/noindex/css/fonts/Light/OpenSans-Light.ttf 3
/noindex/css/fonts/Bold/OpenSans-Bold.ttf 3
/favicon.ico 4
/index.html 2
/first 1
... and so on ...
The last sub-report is a list of HTTP status codes with percentages of URLs that resulted in each status code, which should be displayed as shown. The percentage is based on the count of each unique code divided by the total number of lines in the file, which you should derive from the size of the Array of lines.
HINT: One or both of the numbers must be converted to a Float using to_f to force the result to be a decimal number. Once you have a decimal result, use round() to get two digits to the right of the decimal point.
HTTP Status Codes Summary:
200: 45.37%
403: 11.11%
404: 35.19%
301: 5.56%
304: 2.78%
The critera for a complete program is below for reference:
1. Create three initially-empty counting Hashes as local variables to tabulate the totals for unique IP addresses, URLs, and HTTP Status codes
2. Read in the Apache log file to create an Array of lines
3. You may only iterate over the Array of lines once in the entire program.
3. In that single iteration, process each line using the Regexp#match method to create one of more MatchData objects that capture the three required fields.
4. In the same iteration, populate each of the three Hashes using IP addresses, URLs, and HTTP Status codes as keys and the count of each unique field as the values.
5. The Hash keys for all the ip address and url Hashes should be Symbols, but the key for status code Hash must be a Fixnum
6. Use the Hash#each iterator on each Hash in turn and a do … end block to generate the output for each of the three reports, following the sample output abovePlace IP addresses in a field of 20 characters so that the histogram *'s are aligned and use a similar implementation for the URL report (appr. 45-50 characters should be enough).
HINT: Look up Kernel#printf in the Ruby docs.
Explanation / Answer
x = 'something'
x = yield(x)
#....
def do_stuff_by_val
do_block_stuff_by_val do |name|
name += 'rocket'
end
end
def do_block_stuff_by_val
company_name = 'hash'
yield(company_name)
puts company_name #prints 'hash', not 'hashrocket'
end
company_name = yield(company_name)
def do_stuff_by_object_reference
do_block_stuff_by_object_reference do |company|
company[:name] = 'hashrocket'
end
end
def do_block_stuff_by_object_reference
company = {}
yield(company)
puts company # { name: 'hashrocket'}
end
bundle install --path ./gems
BUNDLE_PATH: "./gems"
BUNDLE_DISABLE_SHARED_GEMS: "true"
rvm reinstall all --force
stub_request(:get, 'http://www.google.com')
assert_requested(:get, 'http://www.google.com')
get_google = stub_request(:get, 'http://www.google.com')
assert_requested get_google
[1] pry(main)> :one
=> :one
[2] pry(main)> 1 + 1
=> 2
[3] pry(main)> ["t", "h", "r", "e", "e"].join
=> "three"
[4] pry(main)> _in_.to_a
=> [nil, ":one ", "1 + 1 ", "["t", "h", "r", "e", "e"].join "]
[5] pry(main)> _out_.to_a
=> [nil, :one, 2, "three", [nil, ":one ", "1 + 1 ", "["t", "h", "r", "e", "e"].join "]]
[6] pry(main)> _out_[2]
=> 2
[7] pry(main)> _in_[2]
=> "1 + 1 "
ActiveRecord::Base.connection.execute(<<~SQL)
select pg_sleep(86400);
SQL
default: &default
adapter: postgresql
...
variables:
statement_timeout: 5000
expect{ Registration.create(attrs) }.to change{ User.count }.by(1)
expect {
Project.generate(attrs)
}.to change{ Project.count }.by(1).and
change{ User.count }.by(1)
Failure/Error:
expect {
Project.generate(attrs)
}.to change{ Project.count }.by(1).and
change{ User.count }.by(1)
expected result to have changed by 1, but was changed by 0
...and:
expected result to have changed by 1, but was changed by 0
require_relative 'boot'
verbose = $VERBOSE
$VERBOSE = nil
require 'rails/all'
require 'active_support/core_ext/numeric/conversions'
require 'active_job/arguments'
$VERBOSE = verbose
Bundler.require(*Rails.groups)
module MyApp
class Application < Rails::Application
end
end
$ rspec --only-failures
RSpec.configure do |config|
config.example_status_persistence_file_path = "spec/examples.txt"
end
ring is mixed case."
end
def foos(foo, bar = foo.upcase + "!")
puts foo
puts bar
end:001 > begin; raise NameError; rescue; puts "The error we raised was #$!."; end
The error we raised was NameError.
:001 > require 'english'
=> true
:002 > begin; raise NameError; rescue; puts "The error we raised was #$ERROR_INFO."; end
The error we raised was NameError.
irb(main):001:0> seq = (0..Float::INFINITY).each
=> #<Enumerator: 0..Infinity:each>
irb(main):002:0> seq.next
=> 0
irb(main):003:0> seq.next
=> 1
irb(main):004:0> seq.next
=> 2
irb(main):005:0> seq.next
=> 3
puts Time.now.strftime("%H:%M:%S %p")
# 20:40:52 PM
puts Time.now.strftime("%H:%M:%S %p")
# 20:40:52 PM
UserPreferenceType = GraphQL::ObjectType.define do
field :name, types.String, hash_key: 'name'
field :value, types.String, hash_key: 'value'
end
phonewords = {
'a' => 2, 'b' => 2, 'c' => 2,
'd' => 3, 'e' => 3, 'f' => 3,
'g' => 4, 'h' => 4, 'i' => 4,
'j' => 5, 'k' => 5, 'l' => 5,
'm' => 6, 'n' => 6, 'o' => 6,
'p' => 7, 'q' => 7, 'r' => 7, 's' => 7,
't' => 8, 'u' => 8, 'v' => 8,
'w' => 9, 'x' => 9, 'y' => 9, 'z' => 9,
}
phone = "1-800-map-gsub"
puts phone.gsub(/[a-z]/, phonewords)
# => 1-800-627-4782
describe '#record_bad_login!' do
let(:user) { FactoryGirl.create(:user) }
it 'increments the bad login attempts count' do
expect(user.failed_login_attempts).to eq(0)
user.record_bad_login!
expect(user.failed_login_attempts).to eq(1)
end
end
describe '#record_bad_login!' do
let(:user) { FactoryGirl.create(:user) }
it 'increments the bad login attempts count' do
expect { user.record_bad_login! }.to change { user.failed_login_attempts }.from(0).to(1)
end
end
> a, b = false, true
=> [false, true]
> a || b
=> true
> a or b
=> true
> c = a or b
=> true
> c
=> false
2.1.0 :001 > "look at those potatoes".gsub(/p.*s/) do |match|
2.1.0 :002 > match.upcase + '!!!'
2.1.0 :003?> end
=> "look at those POTATOES!!!"
false ^ true ^ true ^ true
# false ^ true is true
true ^ true ^ true
#true and true is false
false ^ true
# true
# print_at_exit.rb
at_exit { puts "Come back later!" }
puts "sleeping for 5 secs"
sleep 5
Gem::Version.new('1.0.1') > Gem::Version.new('1.0')
2.1.0 :001 > "totally gourmet" =~ /totally/
=> 0
undefined_foo #=> NameError: undefined local variable or method `undefined_foo'
defined? undefined_foo #=> nil
defined? nil #=> "nil"
defined? "foo" #=> "expression"
defined? [] #=> "expression"
defined? def x; end #=> "expression"
defined? class Foo; end #=> "expression"
defined? foo = :bar #=> "assignment"
foo = :bar
defined? foo #=> "instance-variable"
foo = :bar
defined? foo #=> "local-variable"
def foo; end
defined? foo() #=> "method"
class Foo; end
defined? Foo #=> "constant"
desc 'foobar does this and that'
task :foobar do
puts 'this and that'
end
task :foobaz do
puts 'not so much'
end
$ rake -T foo
rake foobar # foobar does this and that
task :greeting, [:name] do |task, args|
puts "Hello, #{args.name}!"
end
class Phone
def ring
puts 'brrrrriiing'
end
end
class Smartphone < Phone
def ring
puts 'boop beep boop'
end
end
class Iphone < Smartphone
end
smartphone = Smartphone.new
iphone = Iphone.new
smartphone.ring
#=> boop beep boop
iphone.ring
#=> boop beep boop
def square(x)
puts binding.local_variables.inspect
x.times do |a|
puts binding.local_variables.inspect
end
z = x * x
puts binding.local_variables.inspect
z
end
square(2)
irb > String === 'foo'
=> true
irb > Array === %w(one two three)
=> true
irb > Range === (1..10)
=> true
irb > /car/ === 'carpool'
=> true
> ruby_code = 'a = 1 + 2'
=> a = 1 + 2
> compiled_code = RubyVM::InstructionSequence.compile(ruby_code)
=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
> puts compiled_code.disasm
== disasm: <RubyVM::InstructionSequence:<compiled>@<compiled>>==========
local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1, kw: -1@-1, kwrest: -1])
[ 2] a
0000 trace 1 ( 1)
0002 putobject_OP_INT2FIX_O_1_C_
0003 putobject 2
0005 opt_plus <callinfo!mid:+, argc:1, ARGS_SIMPLE>
0007 dup
0008 setlocal_OP__WC__0 2
0010 leave
=> nil
class ChicagoDevs
include Enumerable
def each &block
['ce','jb', 'jc', 'jd', 'jw', 'bd', 'dp'].each{|member| block.call(member)}
end
end
require 'timeout'
status = Timeout::timeout(5) {
# Something that should be interrupted if it takes more than 5 seconds...
}