« first day (454 days earlier)      last day (2801 days later) » 

01:34
does this make sense?
class HotTopicFinder
  def initialize
    @array = ["montreal", "toronto", "montreal", "canada", "montreal", "toronto", "food", "montreal", "food"]
    @queries = []
    read_array
  end

  def read_array
    @hash = Hash.new(0)
    @array.each do |query|
      @hash[query] += 1
    end
    sort_array
  end

  def sort_array
    @queries = @hash.sort_by{ |k, v| v }.reverse
  end

  def find_hot_topics(number_of_topics)
    @queries.slice(0, number_of_topics)
  end
end
01:55
@Nima How much feedback do you want :p
I guess the TLDR is that @array and @hash are not great variable names; Use %w(....) to produce an array of strings, and your methods share a bunch of shared state when they don't have to.
They can technically be run in any order right now, but each one depends on the output from the previous one, so they can actually only be run in one specific order.
Pass your variables into the methods instead of making them instance variables so that the inputs and outputs of each method is clear
Finally read_array and sort_array can be reduced to a simple set of chained operations: @array.group_by(&:itself).sort_by { |k,v| v.count }.reverse.map(&:first)
im actually trying to nail an interview question i got
And instead of @queries.slice(0, number_of_topics) use @queries.first(number_of_topics)
the question was: "given an array of million strings", make a function that will return the most duplicated string
like find_most_duplicate(2) would find the 2 most duplicated strings
class HotTopicFinder
  attr_reader :array
  def initialize
    generate_words
    @queries = []
    read_array
    puts "ready!"
  end

  def generate_words
    puts "generating 1_000_000_0 words.."
    @array = []
    1_000_000_0.times { @array << (0...3).map {(65 + rand(26)).chr }.join }
  end

  def read_array
    puts "reading array.."
    @hash = Hash.new(0)
    @array.each do |query|
      @hash[query] += 1
    end
    sort_array
  end

  def sort_array
    puts "sorting array.."
    @queries = @hash.sort_by{ |k, v| v }.reverse
kinda giving it a go ..
@array = 1_000_000.times.map { ... }
yup
making an imaginary array of 1,000,00 items lol
02:10
Hmm
This I think would perform much better:
1,000,000,0
letters = ('a'..'z').to_a
words = data = 1_000_000.times.map { letters.sample(5).join('') }
oo
i didnt know about sample
thanks @meagar :)
It's a super useful method
 
2 hours later…
03:42
Hi every one
Hey aldo
I need some help
I am trying to do some error catching but I am not sure how
have you looked at airbrake
airbrake.io or you can look at the gem documentation github.com/airbrake/airbrake
its relay simple to set up
just follow the documentation
thanks I will do that
another option is raygun
I was looking it up on heroku and its free for dev
it has some really nice features where airbrake is $9 to start
03:49
Thanks
I will look into both of those
but my app is not on heroku
I am sure that you can use them in any server
 
3 hours later…
06:22
I have a question that will generate some opinionated answers. I just want to test the waters. :-)
Do you use current_user straight in your view, or do you assign it to an instance variable in your controller? (I.e. @user = current_user.)
 
7 hours later…
13:11
Good morning everyone.
Good morning
@Drenmi I don't think I have a hard-and-fast rule, but I do like for most of the coupling between the view and the app's state to be via instance variables set by the controller.
Among other things, it makes it easier to write a view test.
Good morning, Rubyists.
13:27
hi all
How is everyone today?
good thanks how about u
All good just working on some assignments!
@WayneConrad ..thanks.. my problem with the other approach is that i need to find the max(n) values
which is why im doing @queries.slice
not sure how efficient slice is on an array with a million record
Guys what am I doing wrong?
Create an ArrayModifier class. It should take an array as an argument to its initialize function, and have one instance method:

exclaim -- Loops through the array of strings and returns a new array. The new array will consist of the elements of the original array concatenated with a "!"."
class ArrayModifier
attr_accessor :array

def initialize(array)
@array = array
end

def exclaim
new_array = []
array.each do |num|
new_array << "#{num}!"
end
end

end

RSpec returns this:
I do not need to use the bang operator because << pushes into the Array correct?
13:47
@JonathanMusso .. you are not returning your new_array
def exclaim(array)
  new_array = []
  array.each do |num|
    new_array << "#{num}!"
  end
  new_array
end
Ahhhh, wow...Thanks @Nima
its always the stupid mistakes that get us
lol
Always.
one day i spend hours debugging something just to find out im looking at the remote file instead of my local one..
lol
With me, sometimes it's just the stupid that gets me.
13:52
Indeed....I was looking at that for quite a while wondering why it isn't working...lol.
I just read that I could of used the .map method to append the ! to the array...before realizing that I was not calling the array. omg xD
lol
wow this is cool
data.bsearch {|number| number > 40_000_000 }
bsearch
def exclaim(array)
  array.map { |n| "#{num}!" }
end
@Nima Interesting... What's the use case?
@WayneConrad

require 'benchmark'

data = (0..50_000_000)

Benchmark.bm do |x|
  x.report(:find) { data.find {|number| number > 40_000_000 } }
  x.report(:bsearch) { data.bsearch {|number| number > 40_000_000 } }
end

         user       system     total       real
find     3.020000   0.010000   3.030000   (3.028417)
bsearch  0.000000   0.000000   0.000000   (0.000006)
I love people who benchmark. They make life better.
i know lol
13:59
binary search is O(log2). find is O(n).
im just going all these data stuff for my interview today
14:13
Remember, tiny shampoo bottles
lol thx jared
and a brown paper bag too :)
Good morning, pearly developers
Good morning, kbz.
Actual rails/ruby question. Anyone have thoughts on how to implement an API that pulls data from a remote DB. Simple as setting up an ActiveModel and establish_connection to it then treat it as a rails object?
I've done this, but it was complicated for me. I didn't know how to set up rails tests that dealt with multiple databases, so I put the third-party library access into a separate library that uses activerecord. The rails project uses the library to get to the third-party db, but during tests, it stubs that library out.
It was somewhat non-trivial to figure out. I should blog it.
14:20
@Jared if your API host can connect to your database server, than it's no different than building an API that reads from a local DB.
Hmm. There's nothing to stop what Jared is suggesting from working. So maybe I should have just done that, and during tests, stub out those models. That would have been infinitely simpler.
@WayneConrad Thank you sir for the example of .map
Your API is just slightly slower...
Yea, that's what I was thinking. Just need to become a pro at mocking for my tests. thanks guys :D
@WayneConrad Packaging up the DB connection to the 3rd party is definitely a more robust route. Especially if its going to change drastically at any point
@Jared I guess so. The experiment I did was to have that library participate in its own mockiness. When the rails project needs to mock/stub the library, it access a class in the library that exists just for setting up mockiness. That worked nice, and is something I really should blog.
To clarify, it's not rspec mock/stub that's being used. It's old-fashioned hand-rolled test doubles
14:27
get on it so i can copy and paste ;)
@Jared You can use something like VCR to record and replay requests, but it can just move the burden to maintaining VCR cassettes...
@Jared :D
i love VCR
@meagar at first I was pretty sure you meant a real VCR. But Google said different and it definitely looks interesting
HA, yeah, sorry, not a literal VCR.
well if theres a railscast there is no reason I can't be a pro in under 30min
ryan is just amazing
 
1 hour later…
15:58
hi
hey
16:53
letters = *("A".."Z")

  Benchmark.bm do |x|
    x.report("Array.new") do
      @queries = []
      @queries = Array.new(1_000_000_0){ letters.sample(5).join }
    end

    x.report("1_000_000_0.times") do
      @queries = []
      1_000_000_0.times { @queries << letters.sample(5).join }
    end
  end
user     system      total        real
Array.new 56.370000   1.600000  57.970000 ( 58.618850)
1_000_000_0.times113.130000   1.870000 115.000000 (115.753889)
I wonder if it's the call to the block that is costing Array(...) {} so much time.
What if you benchmark this as well? Array.new(1_000_000_0){}
1_000_000_0.times { @queries << letters.sample(5).join }
is very expensive
x.report("Array.new(1_000_000_0){}:") { Array.new(1_000_000_0){} }
gives
  user     system      total        real
Array.new(1_000_000_0){}:  0.580000   0.020000   0.600000 (  0.598963)
its the operation inside the block letters.sample(5).join that is slowing it i guess
Oh, Oh, I misread. The Array solution is much faster than then << solution. OK.
I goofed up reading the unaligned numbers.
yea lol sorry about that
17:16
Cool benchmark. What do you suppose makes the Array(...){} solution faster?
maybe its the << inside times?
I think so. Any guess why?
have to dive into the C++ code of ruby for that maybe
lol
It's in C... but from what I recall, [] allocates only a small amount of memory. << will have to periodically increase the amount of memory allocated to the array. My guess is that those periodic increases are expensive when compared to Array(n), which allocates memory only once.
right C
oh god help..
class Query
  attr_accessor :queries

  def initialize(file)
    @queries = []
    @file = File.open(file)
    puts "ready!"
  end

  def generate_queries
    puts "generating queries.."
    letters = *("A".."Z")
    @queries = Array.new(1_000_000_0){ letters.sample(5).join }
    file = File.new('queries.txt', 'w')
    file.puts(@queries.join("\n").to_s)
    file.close
  end

  def read_queries
    puts "reading array.."
    @hash = Hash.new(0)

    @file.each_line do |query|
      query = query.gsub("\n", "")
    Benchmark.bm do |x|
      x.report("reading queries") do
        q = Query.new("queries.txt")
        q.read_queries
      end
    end

user     system      total        real
107.340000   1.550000 108.890000 (109.110249)
processing a file with 10m lines, converting it into a hash to find the most duplicated records
takes 109 seconds to just read it and process it
17:25
sort file | uniq -c | sort -rn | head -10
^ try that. Replace file with the filename.
what does that do ?
Finds the 10 most duplicated lines.
It's shell, not Ruby.
yea i realized
It should be fast.
results = `sort...`
return results ;)
17:27
That's a legit solution as long as you don't need portability.
lol but the point is to implement it in ruby
like find the most (n) duplicated values
so if a file has a, b, c, a, a, a, b .
then i could ask for the most 2 duplicated values and get
a, b
kinda like how google analytics has "top" keywords or something
I'd be tempted to modify my group_by solution and see how it performs.
like max_by ?
this one?

def most_common_value(a)
  a.group_by do |e|
    e
  end.values.max_by(&:size).first
end
Yeah. Instead of just taking .first, take[0...10] or however many you need.
Oh, you said 2. so [0...2]
lets benchmark it lol
17:32
Yeah!
.. and the race is on!
this is my new method:
def read_queries
    puts "reading array.."
    @hash = Hash.new(0)

    @file.each_line do |query|
      @queries << query.gsub("\n", "")
    end

    @queries.group_by do |e|
      e
    end.values.max_by(&:size)[0..2]
  end
Looks good. You can get rid of @hash. gsub("\n|, "") can be replaced by chomp.
we have a winner!
45.380000 1.840000 47.220000 ( 47.259165)
We must go faster!
17:38
processed 10m records
in 47s
Now let's replace group_by do |e| e end with group_by(&:itself) and see what happens.
And for grins and giggles, how fast is the shell solution?
class Query
  attr_accessor :queries

  def initialize(file)
    @queries = []
    @file = File.open(file)
    puts "ready!"
  end

  def generate_queries
    puts "generating queries.."
    letters = *("A".."Z")
    @queries = Array.new(1_000_000_0){ letters.sample(5).join }
    file = File.new('queries.txt', 'w')
    file.puts(@queries.join("\n").to_s)
    file.close
  end

  def read_queries
    puts "reading array.."
    @hash = Hash.new(0)

    @file.each_line do |query|
      @queries << query.chomp
@WayneConrad .. and the result..
drums..
with group_by do |e|:
21.790000 0.750000 22.540000 ( 22.570711)
with (&:itself):
20.980000 0.730000 21.710000 ( 21.722772)
this the total it took to:
Read the entire file into an array
Sort the array
The unix solution will blow all of those away.
is unix usually single threaded too or?
No, unix will create a separate process for each command, so they run in parallel
17:53
damn it.. the requirements demands that the array is like this:
["word", number_of_occurences]
lol
like find_hot_queries(1)
would return that
nvm
the issue is with max_by , i should use max_by(n)
Wow cool code @Nima I can understand most of it :D
lol i've had a lot of help from @WayneConrad
Heh. After I finish this last module I am going to take a break and try building my own little program for IRB to practice everything I have learned this far.
irb is great!
but "pry" makes it more fun
Hm I don't know what that is let me take a look
Is there a way to allow IRB to use tab for indentation ?
Wow, very cool!
18:06
when playing in IRB i usually test stuff there and then just make a plain messing_around.rb and just run that. makes me much more sane than running one line at a time
Ok thanks, makes sense, open your file and test it through IRB.
I've got an emacs session almost permanently open to /tmp/foo.rb, which is my sandbox. Most of my SO answers were copy/pasted from /tmp/foo.rb
@WayneConrad almost permanently in the tmp dir... something isn't adding up
@Jared :) Hence the "almost". What I've really got is a terminal in my terminal multiplexor that's running an emacs that's open to "/tmp/foo.rb", and for which the compile-command is set to "ruby /tmp/foo.rb" so it's just a few keystrokes to run it.
this discussion could not get any geekier lol
18:18
sneaky
@Nima I'm tempted to take that as a challenge.
lol hah
we used to be "uncool" ..
now everyone suddenly thinks programming in "rad"
the original hipsters
Hmm, emacs is similar to vim right? I've ran through a bit of the Vim tutor in my course so far.
lol
18:19
Actually, I am still really, really uncool.
Hipsters, oh gawd lol
Emacs is more or less vim with a nice gui and formatting
Emacs is similar to vim in that it's mostly keyboard driven. Mouse addicts need not apply.
Vim has a (I think) more ergonomic default key binding than does Emacs. Emacs has more kitchen sinks built into it.
There are games cooked into Emacs, I think. I mean, it has everything.
I remember one guy tried to make that point by setting his shell to emacs.
wayne how many people do you have working under you?
lol
18:41
@Nima None
 why on earth does this take 17s

@hash = Hash.new(0)

    @file.each_line do |query|
      @hash[query.chomp] += 1
    end
@queries = @hash.sort_by { |k, v| v }.reverse << only takes 3s
Because many lines, if I had to guess.
@hash[query.chomp] += 1 << is expesnive
if i were to do this:
@file.each_line do |query|
@queries << query
end
it takes 5s
If every line is terminated identically, then you can leave off the chop here, and just do the chop when you go to print them. Or, if you're truly lazy, don't chop the lines anywhere... just print them with "print" instead of "puts"
@WayneConrad do you work in a firm?
18:55
@JonathanMusso yes
@Nima Not doing the chop might save you a little.
That's cool, pure Ruby or do you work with Rails too?
Both, but the Rails app I work on just serves up a JSON API. I'm not the vaunted "full stack developer."
That's really neat. I haven't touched Rails yet, other than just making a test application and pushing it to Git. After I complete this next exercise I think I am going to break from the curriculum and try to build my own tiny Ruby program before continuing.
@Nima You should try the block form of File.open, because it'll close the file for you:
File.open(path) do |file|
   file.puts "stuff"
end
Also, if you're just trying to read lines into an array, use @file.each_line.to_a
19:03
^. Or if you just want to read the lines all into memory, then File.readlines(path)
19:15
memory cap is 1gb
wow I actually solved 2/4 checkpoints with some dirty code me thinkgs
@Nima Just read and process a line at a time, then.
@JonathanMusso I can't see "dirty code" without snickering like a fifth grader.
Haha, let me finish the remainder of the program then I will show you my code
19:36
@JonathanMusso Cool
Woohoo, one more bug smashed.
I've only got one more open bug... this could be a very good day.
random coder trivia, why do we call them bugs >.>
Supposedly because a bug was found in the cabinet of a malfunctioning mainframe back in Grace Hopper's day.
oh wow..
https://truesecdev.wordpress.com/2015/04/09/hidden-backdoor-api-to-root-privileges-in-apple-os-x/
@Jared Haha! That's great. That they wrote "first actual case of bug being found" seems to indicate it was already a term of art...
19:38
not starting a flame war but apple's response is fascinating
They're only closing it because they've added a different one for the NSA to use. No sense in leaving the one people already know about... let's move on to the still secret one.
> Apple indicated that this issue required a substantial amount of changes on their side, and that they will not back port the fix to 10.9.x and older.
Hmm. How big a deal is it to upgrade the OS on your laptop or whatever?
@WayneConrad final result:

21.250000 0.870000 22.120000 ( 22.150686)
@WayneConrad final code:

class Query
  attr_accessor :queries

  def self.generate_queries
    puts "generating queries.."
    letters  = *("A".."Z")
    @queries = Array.new(1_000_000_0) { letters.sample(5).join }
    file     = File.new('queries.txt', 'w')
    file.puts(@queries.join("\n").to_s)
    file.close
  end

  def initialize(file)
    @queries = []
    @file    = File.open(file)
    puts "ready!"
  end

  def read_queries
    puts "reading array.."

    @file.each_line do |query|
      @queries << query.chomp
processed 10m records in a text file +D the lookup (find_hot_query) takes about 0.7s which is pretty fast
Are you generating a new list of queries for each test run, or reusing the same?
19:49
q = Query.new("queries.txt")

Benchmark.bm do |x|
  x.report("reading queries") do
    q.read_queries
  end

  x.report("q.find_hot_query") do
    q.find_hot_query(2)
  end

  x.report("q.query_stat") do
    q.query_stat("IMONS")
  end
end
reading queries     21.250000   0.870000  22.120000 ( 22.150686)
q.find_hot_query  0.640000   0.000000   0.640000 (  0.648309)
q.query_stat        0.000000   0.000000   0.000000 (  0.000022)
i only generated 10m random string once in a file.
i just assumed that comes from a database or something
Yep. Nice.
@WayneConrad thanks for the help
:)
It was fun.
im off 2 my interview now
wish me luck!
+D
Good luck!
Whoever hires you will get someone who's hungry to learn and works hard at it.
19:59
.... i hope its not where I work, i'll be out of a job so fast :x
@Nima Best of luck man!!!
20:11
anyone ever tried to pass omniauth credentials that wasn't through a form?
aka directly the omniauth engine
Never did anything with omniauth
its nice when used correctly, as a login form... however bending it to apparently make frankenstein's monster is quite troublesome :P
"Use as directed" seems to be a common theme in Rails.
20:32
It looks like I have to use each_with_index to complete my assignment. Trying to follow along the doc example, I haven't learned about hashes yet but one question about this
hash = Hash.new
%w(cat dog wombat).each_with_index { |item, index|
hash[item] = index
}
hash #=> {"cat"=>0, "dog"=>1, "wombat"=>2}
%w(cat dog wombat) is shorthand for ["cat", "dog", "wombat"] right?
@JonathanMusso Correct
20:48
@JonathanMusso weirdly you can even use any open/close for that. %w!a b c! works too >.>
Oh yeah, I forgot about that.
Okay thanks guys. I just tested it on IRB with an array, - TypeError: no implicit conversion of String into Integer
I guess it is meant to work with hash because it has a key and value?
correct. Hashes can have :symbols, 'strings' for keys. Arrays use only integers for indexing
21:15
Ok thanks @Jared. I will be back in a bit, hopefully get this assignment completed tonight.
Well i'm about to duck out for the night, so hopefully google is a good replacement ;)
@JonathanMusso FYI, you can accomplish the same thing with %w(cat dog wombat).each_with_index.to_h
21:35
@meagar Nice.
22:20
What are the best free editors for ruby these days?
I found a couple closed questions on SO that pointed to Aptana, but the IDE I downloaded from there is from 2010 and wants Java 6 :-/
22:51
ewhhh
have you looked into sublime or text mate?
and vim still works ;)
23:13
+1 for Vim
+1 for Emacs, but +0.99 for Vim.
hehe :P
@WayneConrad so your the person who uses emacs
I think it's me and Stallman.
23:32
:P
so i have a weird questoin :l
i have a table named accounts, and there is a user in the table named "root" now there's going to be many "root" users because there are going to be many devices, so how would i associate the "root" user with the column "device_id" ...yeah yeah i know not a great question :/
You would have a device_id column n the user table. Add a unique constraint on (device_id, username). device_id is a foreign key into the devices table.
ohhh thank you, it'll probably take me an hour to figure out what you just said :P
Ok. You have two tables, users and devices, right?
yup
users has an 'id' column, the typical rails autoincrement primary key. Same for devices. Right?
23:43
yes
Ok. So you'll add a column to users called "device_id". This is a foreign key into the devices table, referencing the "id" column in devices. Make sense so far?
in the devices table, there is a column for "device_id" and a column for "name"
both are strings
There should also be an "id" column, which is the rails autoincrementing primary key. users.device_id should refer to devices.id, not to devices.device_id.
Life in rails is much easier if all foreign keys reference the rails artificial primary key rather than the natural (domain) primary key.
sort of, i understand the id of foreign keys, but i've only messed around with like once :/
In Rails, you don't actually have to add the foreign key constraint to the database schema, but it's a great idea to do so.
23:45
hmmm
A database without constraints is an invitation for your data to become awful.
i'll take that into consideration
so step 1, create a migration with a device_id column in the "accounts" table.
I've rescued a few projects from the mess they were in because someone said "I'll take that into consideration" and then didn't :)
@Chris Yes.
hehe hey man im a noob :P
Then add the relationship to the models. The usual belongs_to/has_many kind of thing.
23:48
yeah i was reading the active record guide :l
Then add a rails validation to the user model saying that the combination of (username, device_id) must be unique. Because no device should have two users with the same username, right?
whoa your jumping ahead now :P
should i specify a constraint in the migration or do that in the models?
DB constraints go in migrations. Model constraints ("validations") go in models. They compliment each other. The model constraint works well with form validation. The DB constraint makes sure that if the model constraint ever goofs up, the data stays clean.
ahhhh
The DB constraint also keeps the data clean when something other than rails is modifying it. Say, a CLI tool or a database GUI tool.
23:55
good to know ;)
i usually just use psql
and my "skills" are quite limited
Oh, a Postgres guy! Yay!
hehe
i like it :D
It focuses more on correctness than does mysql, I think. And... come on, schema modifications in a transaction. How is that not the coolest thing ever?
the migratoin file looks like the following, ghostbin.com/paste/b55s6
i need to add the constraint before running though
When I'm working with Rails and Postgres, all my migrations are done in a transaction.
23:58
"migrations done in a transaction" <= that just went over my head
:P
A database transaction is a way to group together a bunch of related SQL statements such that they either all work, or all fail.

« first day (454 days earlier)      last day (2801 days later) »