blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 4
137
| path
stringlengths 2
355
| src_encoding
stringclasses 31
values | length_bytes
int64 11
3.9M
| score
float64 2.52
5.47
| int_score
int64 3
5
| detected_licenses
listlengths 0
49
| license_type
stringclasses 2
values | text
stringlengths 11
3.93M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
d9a2d0c477e9d0a9945284898d80b029ddfbefa2
|
Ruby
|
dlaststark/machine-learning-projects
|
/Programming Language Detection/Experiment-2/Dataset/Train/Ruby/letter-frequency-2.rb
|
UTF-8
| 275
| 3
| 3
|
[] |
no_license
|
def letter_frequency(file)
freq = Hash.new(0)
file.each_char.lazy.grep(/[[:alpha:]]/).map(&:upcase).each_with_object(freq) do |char, freq_map|
freq_map[char] += 1
end
end
letter_frequency(ARGF).sort.each do |letter, frequency|
puts "#{letter}: #{frequency}"
end
| true
|
b4a9afc6dc92bdb97f1a7a96999b4c239d70c140
|
Ruby
|
HenriqueArtur/brasil-system-challenge
|
/classes/Utils.rb
|
UTF-8
| 1,709
| 3.90625
| 4
|
[] |
no_license
|
require 'date'
class Utils
def strReverse(str)
if str.is_a? String
return str.reverse
else
puts "Parametro inválido.\nPasse uma string como parametro"
newStr = gets.chomp
srtReverse(newStr)
end
end
def srtHalf(str)
if str.is_a? String
const = firstHalf?
half = (str.length/2).floor - 1
init = const * (half+1)
final = (const == 0 ? half : str.length - 1 )
return str[init..final]
else
puts "Parametro inválido.\nPasse uma string como parametro"
newStr = gets.chomp
srtHalf(newStr)
end
end
def pwr3Age(age)
if age.is_a? Date
return ((((Date.today - age )/ 365).floor) ** 3)
else
puts 'Data nao válida!'
end
end
def dateSum(date)
if date.is_a? Date
dateToCount = date.strftime('%d%m%Y').split('')
value = 0
dateToCount.each do |index|
value += index.to_i
end
return value
else
puts 'Data nao válida!'
end
end
private
def firstHalf?
puts 'Você deseja imprimir a primeira metade da String ou a segunda?'
puts '[1] - Primeira metade'
puts '[2] - Segunda metade'
response = gets.chomp
if response == '1' || response == '2'
return (response == '1' ? 0 : 1)
else
puts 'Resposta inválida.'
puts "\n"
firstHalf?
end
end
end
| true
|
47e33ab3db9a096ab2554d5337051d5cc23cc7d3
|
Ruby
|
Jackiesan/oo-ride-share
|
/specs/trip_dispatch_spec.rb
|
UTF-8
| 6,951
| 2.78125
| 3
|
[] |
no_license
|
require_relative 'spec_helper'
describe "TripDispatcher class" do
describe "Initializer" do
it "is an instance of TripDispatcher" do
dispatcher = RideShare::TripDispatcher.new
dispatcher.must_be_kind_of RideShare::TripDispatcher
end
it "establishes the base data structures when instantiated" do
dispatcher = RideShare::TripDispatcher.new
[:trips, :passengers, :drivers].each do |prop|
dispatcher.must_respond_to prop
end
dispatcher.trips.must_be_kind_of Array
dispatcher.passengers.must_be_kind_of Array
dispatcher.drivers.must_be_kind_of Array
end
end
describe "find_driver method" do
before do
@dispatcher = RideShare::TripDispatcher.new
end
it "throws an argument error for a bad ID" do
proc{ @dispatcher.find_driver(0) }.must_raise ArgumentError
end
it "finds a driver instance" do
driver = @dispatcher.find_driver(2)
driver.must_be_kind_of RideShare::Driver
end
end
describe "find_passenger method" do
before do
@dispatcher = RideShare::TripDispatcher.new
end
it "throws an argument error for a bad ID" do
proc{ @dispatcher.find_passenger(0) }.must_raise ArgumentError
end
it "finds a passenger instance" do
passenger = @dispatcher.find_passenger(2)
passenger.must_be_kind_of RideShare::Passenger
end
end
describe "loader methods" do
it "accurately loads driver information into drivers array" do
dispatcher = RideShare::TripDispatcher.new
first_driver = dispatcher.drivers.first
last_driver = dispatcher.drivers.last
first_driver.name.must_equal "Bernardo Prosacco"
first_driver.id.must_equal 1
first_driver.status.must_equal :UNAVAILABLE
last_driver.name.must_equal "Minnie Dach"
last_driver.id.must_equal 100
last_driver.status.must_equal :AVAILABLE
end
it "accurately loads passenger information into passengers array" do
dispatcher = RideShare::TripDispatcher.new
first_passenger = dispatcher.passengers.first
last_passenger = dispatcher.passengers.last
first_passenger.name.must_equal "Nina Hintz Sr."
first_passenger.id.must_equal 1
last_passenger.name.must_equal "Miss Isom Gleason"
last_passenger.id.must_equal 300
end
it "accurately loads trip info and associates trips with drivers and passengers" do
dispatcher = RideShare::TripDispatcher.new
trip = dispatcher.trips.first
driver = trip.driver
passenger = trip.passenger
driver.must_be_instance_of RideShare::Driver
driver.trips.must_include trip
passenger.must_be_instance_of RideShare::Passenger
passenger.trips.must_include trip
end
it "stores start_time as instances of Time" do
dispatcher = RideShare::TripDispatcher.new
all_start_times = dispatcher.trips.all? { |trips| trips.start_time.class == Time }
all_start_times.must_equal true
end
it "stores end_time as instances of Time" do
dispatcher = RideShare::TripDispatcher.new
all_end_times = dispatcher.trips.all? { |trips| trips.end_time.class == Time }
all_end_times.must_equal true
end
end
describe "#assign_driver" do
it "assigns the driver to the available driver whose most recent trip ending is the oldest compared to today" do
dispatcher = RideShare::TripDispatcher.new
driver_1 = dispatcher.assign_driver
driver_1.change_to_unavailable
driver_2 = dispatcher.assign_driver
driver_2.change_to_unavailable
driver_3 = dispatcher.assign_driver
driver_3.change_to_unavailable
driver_4 = dispatcher.assign_driver
driver_4.change_to_unavailable
driver_5 = dispatcher.assign_driver
driver_5.change_to_unavailable
assigned_drivers = [driver_1, driver_2, driver_3, driver_4, driver_5]
all_assigned_drivers = assigned_drivers.all? { |driver| driver.class == RideShare::Driver }
all_assigned_drivers.must_equal true
driver_1.id.must_equal 14
driver_1.name.must_equal "Antwan Prosacco"
driver_2.id.must_equal 27
driver_2.name.must_equal "Nicholas Larkin"
driver_3.id.must_equal 6
driver_3.name.must_equal "Mr. Hyman Wolf"
driver_4.id.must_equal 87
driver_4.name.must_equal "Jannie Lubowitz"
driver_5.id.must_equal 75
driver_5.name.must_equal "Mohammed Barrows"
end
it "raises error if there are no drivers available" do
dispatcher = RideShare::TripDispatcher.new
# 46 drivers originally available
46.times do
dispatcher.request_trip(1)
end
proc{dispatcher.assign_driver}.must_raise ArgumentError
end
end
describe "#request_trip(passenger_id)" do
before do
@dispatcher = RideShare::TripDispatcher.new
@passenger = @dispatcher.find_passenger(3)
@driver = @dispatcher.find_driver(14)
@initial_trips_length = @dispatcher.trips.length
@initial_passenger_trips_length = @passenger.trips.length
@initial_driver_trips_length = @driver.trips.length
@new_trip = @dispatcher.request_trip(3)
end
it "returns/creates new instance of Trip" do
@new_trip.must_be_kind_of RideShare::Trip
end
it "adds the new Trip to the collection of trips in TripDispatcher" do
@dispatcher.trips.length.must_equal @initial_trips_length + 1
end
it "adds the new Trip to the collection of trips for Passenger" do
@passenger.trips.length.must_equal @initial_passenger_trips_length + 1
end
it "adds the new Trip to the collection of trips for Driver" do
@driver.trips.length.must_equal @initial_driver_trips_length + 1
end
it "changes drivers status to :UNAVAILABLE" do
@driver.status.must_equal :UNAVAILABLE
end
it "assigns new trip id (trip ids in dispatcher are in consecutive order)" do
@new_trip.id.must_equal 601
end
it "makes the start time and instance of time" do
@new_trip.start_time.must_be_kind_of Time
end
it "assigns end_time, cost, and rating of trip to 'nil' as it is in progress" do
@new_trip.end_time.must_be_nil
@new_trip.cost.must_be_nil
@new_trip.rating.must_be_nil
end
it "is set up for specific attributes and data types" do
[:id, :passenger, :driver, :start_time, :end_time, :cost, :rating].each do |prop|
@new_trip.must_respond_to prop
end
@new_trip.id.must_be_kind_of Integer
@new_trip.driver.must_be_kind_of RideShare::Driver
@new_trip.passenger.must_be_kind_of RideShare::Passenger
end
it "raises error if there are no drivers available" do
dispatcher = RideShare::TripDispatcher.new
# 46 drivers originally available
passenger_id = 1
46.times do |request_trip|
dispatcher.request_trip(passenger_id)
end
proc{dispatcher.request_trip(2)}.must_raise ArgumentError
end
end
end
| true
|
ce682b8e97ecdb485e0a602ce25413ff253b6922
|
Ruby
|
papistan/phase-0-tracks
|
/ruby/hashes.rb
|
UTF-8
| 1,278
| 3.5
| 4
|
[] |
no_license
|
# Interior
# Psuedocode
# Indentify client and save their
# name
# age
# numnber of children
# decor theme
# money is no object?
# favorite colors
# special needs?
client_1 = {
name: "",
age: 0,
children: 0,
decor: "",
money: true,
colors: "",
requests: "",
}
puts "Enter client's first and last name as one word: first_last"
client_1[:name] = gets.chomp
puts "How old are they?"
client_1[:age] = gets.chomp.to_i
puts "How many children?"
client_1[:children] = gets.chomp.to_i
puts "Favorite decor theme?"
client_1[:decor] = gets.chomp
puts "Money is no object? yes/no"
money = gets.chomp
if money == "no"
client_1[:money] = false
end
puts "Favorite colors?"
client_1[:colors] = gets.chomp
puts "Any specials requests?"
client_1[:requests] = gets.chomp
print client_1
print " \n"
puts "Updates? enter below: name, age, children, decor, money, colors, requests or none"
x = gets.chomp
if x == "none"
print client_1
else puts "Enter updated value below"
new_value = gets.chomp
if x == "name" || x == "decor" || x == "colors" || x == "requests"
client_1[x.to_sym] = new_value
elsif x == "money"
if new_value == "no"
client_1[:money] = false
elsif client_1[:money] == true
end
else client_1[x.to_sym] = new_value.to_i
end
print client_1
end
| true
|
67e6b772aae778d264dd673b77f24d8b830aa5cd
|
Ruby
|
melnock/the-bachelor-todo-web-012918
|
/lib/bachelor.rb
|
UTF-8
| 1,271
| 3.546875
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def get_first_name_of_season_winner(data, season)
winner = []
data.each {|seasons, array|
if seasons == season
array.each {|hash|
if hash["status"] == "Winner"
winner << hash.values_at("name")
end
}
end
}
name = winner[0][0].split
name[0]
end
def get_contestant_name(data, occupation)
work = ""
data.each {|seasons, array|
array.each{|hash|
if hash["occupation"] == occupation
work = hash.values_at("name")
end
}
}
work[0]
end
def count_contestants_by_hometown(data, hometown)
home = []
data.each {|seasons, array|
array.each{|hash|
if hash["hometown"] == hometown
home << hash.values_at("name")
end
}
}
home.length
end
def get_occupation(data, hometown)
home = []
data.each {|seasons, array|
array.each{|hash|
if hash["hometown"] == hometown
home << hash.values_at("occupation")
end
}
}
home[0][0]
end
def get_average_age_for_season(data, season)
age = []
data.each {|seasons, array|
if seasons == season
array.each {|hash|
age << hash.values_at("age")
}
end
}
length = age.length
total = 0
age.each{|x| int= x[0].to_f
total = total + int
}
average = (total/length).round
end
| true
|
c4483cbb86299c9e62d8193a890ea26732e230f9
|
Ruby
|
kellyeryan/phrg-regex-lab-pca-000
|
/lib/regex_lab.rb
|
UTF-8
| 996
| 3.375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def starts_with_a_vowel?(word)
if word.match(/\b[AEIOUaeiou][a-z]*\b/)
return true
else
return false
end
end
def words_starting_with_con(text)
text.scan(/\bcon[a-z]*\b/)
end
def words_starting_with_un_and_ending_with_ing(text)
text.scan(/\bun[a-z]*ing\b/)
end
def words_five_letters_long(text)
text.scan(/\b\w{5}\b/)
end
def first_word_capitalized_and_ends_with_punctuation?(text)
if not text.match(/[\?\.\!]$/)
return false
end
text.scan(/.*[\?\.\!]/).each do |sentence|
if not sentence.match(/\A[A-Z]/)
return false
end
end
return true
end
def valid_phone_number?(phone_array)
if phone_array.match(/([0-9] ?){10}/) || phone_array.match(/(\([0-9]{3}\)([0-9]{3}-[0-9]{4})\b)/) || phone_array.match(/\b([0-9]{7})\b/)
true
else
false
end
end
#if phone_array.match(/([0-9] ?){10}/) || phone_array.match(/(\([0-9]{3}\)([0-9]{3}-[0-9]{4})\b)/) || phone_array.match(/\b([0-9]{7})\b/)
#phone_array.match(/(\d{10}|\d{7}|\d{4}|\d{3})/)
| true
|
4aeaf6797c89d942d85b11823e52b1f31b2ff70e
|
Ruby
|
Scientist-Stephen/GoFish
|
/FishGame.rb
|
UTF-8
| 6,203
| 3.671875
| 4
|
[] |
no_license
|
require_relative 'FishDeck.rb'
require_relative 'FishHand.rb'
require_relative 'FishPlayers.rb'
class FishGame
attr_accessor :player
#attr_accessor :player2
#attr_accessor :player3
#attr_accessor :player4
#attr_accessor :player5
attr_accessor :top_card_container, :turn, :winner_message, :player_to_player_result #next turn stores who's turn it is next
#How will I use that with the server?
def initialize(number_of_fish_players)
@player = []
@turn = 0
@winner_message = "Initialization message."
@player_to_player_result = "DEFAULT MESSAGE"
i = 0 ##Revise so i can be 0?
number_of_fish_players.times do #like 5.times do
#puts "iteration i is: #{i}"
@player[i] = FishPlayer.new #Revise to PLAYER CLASS
i += 1
end
@max_turns = (@player.size - 1)
#puts "PLAYER ARRAY: #{@player}"
#puts "players 0: #{@player[0].player_hand.player_cards}, players 1: #{@player[1]}"
end
def deal_to_players(deck_name)
5.times do
@player.each do |player_x|
top_card = deck_name.pop_top_card
player_x.fish_hand.player_cards << top_card
end
end
end
def deck_to_player(game_deck, player_to)
player_to.fish_hand.player_cards << top_card_container = game_deck.pop_top_card
#Pops top deck card and shovels onto player_to 's cards
player_to.fish_hand.looks_for_books
end
def player_to_player(game_deck, wanted_card, player_asked, player_asking) #cards go FROM player_asked TO player_asking (or from the deck to player_asking)
card_holder = player_asked.fish_hand.return_cards_requested(wanted_card) #player in game's return card method and stores
#puts "card holder[0] is: #{card_holder[0]}"
#puts "wanted card is #{wanted_card}"
if card_holder[0] == wanted_card #element 0 will be the wanted_card or hold nothing
player_asked.fish_hand.delete_cards(wanted_card)
player_asking.fish_hand.player_cards.concat(card_holder)
card_holder.clear
player_asking.fish_hand.looks_for_books
@player_to_player_result = "Player received Wanted Cards"
else
@player_to_player_result = "Player had to take a card from the deck"
card_from_deck = deck_to_player(game_deck, player_asking)
player_asking.fish_hand.looks_for_books###--!!--!!--!!--!!--!!--!!--!!--!!--!!--!!--!!--!!--!!--
if card_from_deck == wanted_card
#do nothing
@player_to_player_result = "Player got the card he wanted from the deck."
else
if @turn < @max_turns
@turn += 1
else
@turn = 0
end
end
end
end
def player_with_most_books(game_deck)
end
def players_have_books(game_name) #returns total # books for all players
books_check = 0
index_of_winner = 0
game_name.player.each do |player| #look to see if ANY PLAYERS have books > 0
books_check = books_check + player.fish_hand.books_collected
end
if books_check > 0
return books_check
else
return nil
end
end
def return_book_winner_index(game_name) #For use with most books
most_books = 0
biggest = 0
challenger = 0
game_name.player.each do |player| #look to see if ANY PLAYERS have books > 0
challenger = player.fish_hand.books_collected
if challenger > biggest
biggest = challenger
most_books = game_name.player.index(player) #SHOULD eval to 0, 1, etc.
end
end
if biggest > 0
return most_books
else
return nil
end
end
def players_hand_empty?(game_name)
player_hands_empty = false
game_name.player.each do |player|
player_hands_empty = player.fish_hand.player_cards.empty?
if player_hands_empty == true
return player_hands_empty
end
end
return player_hands_empty
end
def lead_player_books(game_name) #returns # of books for player with the most books
lead_player_index = nil
number_of_most_books = nil
lead_player_index = return_book_winner_index(game_name)#O*&QY#$QWHFHBJHJ --here. IT returns nil and causes the thing at line 145 to throw an error.
if lead_player_index == nil
lead_player_index = 0 ##WNARKLJFSN WHAAAT?
end
number_of_most_books = game_name.player[lead_player_index].fish_hand.books_collected
# puts "number of most books: #{number_of_most_books}"
# p number_of_most_books
if number_of_most_books == nil
return 0
end
return number_of_most_books
end
def game_won?(game_deck, game_name) #####METHOD TO SEE IF THERE IS A WINNER
number_of_books = 0
empty_hand = false
index_of_winner = nil
#empty_hand = player.fish_hand.player_cards.empty?
number_of_most_books = lead_player_books
index_of_winner = return_book_winner_index(@fishgame)
empty_hand = players_hand_empty?(@fishgame)
# puts "book check after each loop and before if: #{number_of_books}"
if game_deck.all_cards.empty? == true && number_of_books == 0 #No winners case
@winner_message = "The deck is empty and no players have any books. The game has ended with NO winners."
return true
elsif empty_hand == true #Case for if player has NO CARDS LEFT
@winner_message = "player #{index_of_winner + 1} has eliminated all cards from his hand, thereby winning the game!"
return true
elsif game_deck.all_cards.empty? == true && number_of_books > 0 && number_of_books < 7 #Deck empty/Most books winner
most_decks = 0
biggest = 0
game_name.player.each do |player| #look to see if ANY PLAYERS have books > 0
challenger = player.fish_hand.books_collected
if challenger > biggest
most_decks = game_name.player.index(player) #SHOULD eval to 0, 1, etc.
end
#puts "MOST DECKS after challenger > biggest: #{most_decks}"
end
@winner_message = "The deck is empty and player #{most_decks + 1} has the most books, and thereby has won."
#puts "Game Deck Empty AND book_check > 1"
#puts "Most decks is now #{most_decks}"
return true
elsif number_of_books >= 7 #Case for one player having over half the books
@winner_message = "player #{index_of_winner + 1} has gained more than half of the available books, having a total of #{number_of_books} books. He has won the game."
return true
else
#Game is not over
return false
end
puts "Winner message: #{@winner_message}"
end
end
| true
|
63e2d1aaa881b2c70a7844924b6174f26fe88daa
|
Ruby
|
flavorjones/calendar-assistant
|
/lib/calendar_assistant/event_set.rb
|
UTF-8
| 4,294
| 2.9375
| 3
|
[
"Apache-2.0"
] |
permissive
|
class CalendarAssistant
#
# note that `events` could be a few different data structures, depending.
#
# - it could be an Array of Events
# - it could be a Hash, e.g. Date => Array of Events
# - it could be a bare Event
#
class EventSet
def self.new(event_repository, events = nil)
if events.is_a?(EventSet::Hash)
return EventSet::Hash.new event_repository, events.try(:events)
end
if events.is_a?(::Hash)
return EventSet::Hash.new event_repository, events
end
if events.is_a?(::Array)
return EventSet::Array.new event_repository, events
end
return EventSet::Bare.new event_repository, events
end
class Base
attr_reader :event_repository, :events
def initialize(event_repository, events)
@event_repository = event_repository
@events = events
end
def ==(rhs)
return false unless rhs.is_a?(self.class)
self.event_repository == rhs.event_repository && self.events == rhs.events
end
def new(new_events)
EventSet.new self.event_repository, new_events
end
def empty?
return true if events.nil?
return events.length == 0 if events.is_a?(Enumerable)
false
end
end
class Hash < EventSet::Base
def ensure_keys(keys, only: false)
keys.each do |key|
events[key] = [] unless events.has_key?(key)
end
if only
events.keys.each do |key|
if !keys.include? key
events.delete(key)
end
end
end
end
def [](key)
events[key] ||= []
end
def []=(key, value)
events[key] = value
end
def available_blocks(length: 1)
event_repository.in_tz do
dates = events.keys.sort
# iterate over the days finding free chunks of time
_avail_time = dates.inject({}) do |avail_time, date|
avail_time[date] ||= []
date_events = events[date]
start_time = date.to_time.to_datetime +
BusinessTime::Config.beginning_of_workday.hour.hours +
BusinessTime::Config.beginning_of_workday.min.minutes
end_time = date.to_time.to_datetime +
BusinessTime::Config.end_of_workday.hour.hours +
BusinessTime::Config.end_of_workday.min.minutes
date_events.each do |e|
# ignore events that are outside my business day
next if Time.before_business_hours?(e.end_time.to_time)
next if Time.after_business_hours?(e.start_time.to_time)
if HasDuration.duration_in_seconds(start_time, e.start_time) >= length
avail_time[date] << AvailableBlock.new(start: start_time, end: e.start_time)
end
start_time = [e.end_time, start_time].max
break if !start_time.during_business_hours?
end
if HasDuration.duration_in_seconds(start_time, end_time) >= length
avail_time[date] << AvailableBlock.new(start: start_time, end: end_time)
end
avail_time
end
new _avail_time
end
end
def intersection(other, length: 1)
set = new({})
set.ensure_keys(events.keys + other.events.keys)
set.events.keys.each do |date|
events[date].each do |event_a|
other.events[date].each do |event_b|
if event_a.contains?(event_b.start_time) ||
event_a.contains?(event_b.end_time - 1) ||
event_b.contains?(event_a.start_time) ||
event_b.contains?(event_a.end_time - 1)
start_time = [event_a.start_time, event_b.start_time].max
end_time = [event_a.end_time, event_b.end_time].min
if HasDuration.duration_in_seconds(start_time, end_time) >= length
set.events[date] << AvailableBlock.new(start: start_time, end: end_time)
end
end
end
end
end
set
end
end
class Array < EventSet::Base
end
class Bare < EventSet::Base
end
end
end
| true
|
e282e2fbf12e89188c77c19b9ed3e352998927e7
|
Ruby
|
alu0100614220/prct12
|
/lib/matrizdensa.rb
|
UTF-8
| 737
| 3.296875
| 3
|
[
"MIT"
] |
permissive
|
class Matrizdensa < Matriz
def initialize (x, y, v)
throw "Dimensiones invalidas" if (x * y) == 0
@xsize= x
@ysize= y
@values= Array.new(x * y)
for i in (0...@xsize) do
for j in (0...@ysize) do
@values[j * @ysize + i] = v[j * @ysize + i]
end
end
end
def getx
@xsize
end
def gety
@ysize
end
def each
y, x= 0, 0
@values.each do |v|
yield v, x, y
if (x += 1) >= @xsize
x= 0; y+= 1
end
end
end
def [](i, j)
@values[j * @ysize + i]
end
def []=(i, j, v)
@values[j * @ysize + i] = v
end
end
| true
|
77d1be2ea078dbd1f608041bb2311a2478b3e3f4
|
Ruby
|
capaca/band-manager-rb
|
/bandmanager/spec/models/song_spec.rb
|
UTF-8
| 1,344
| 2.5625
| 3
|
[] |
no_license
|
require 'test_helper'
class SongTest < ActiveSupport::TestCase
test "Should save a song" do
song = create_song
assert_difference "Song.count" do
song.save
song.release.save
end
end
test "Should destroy a song" do
song = create_song
song.save
assert_difference "Song.count", -1 do
song.destroy
end
end
test "Should validate presence of attributes" do
song = Song.new
assert_error_on_save song, :title, :track_number, :release_id
end
test "Should validate association with a valid release" do
song = create_song(:release => Release.new) # Invalid release (empty)
assert_error_on_save song, :release
end
test "Should not save a song with the same track number in the release scope" do
song = create_song(:track_number => 1)
assert song.save == false
assert song.errors.empty? == false
assert song.errors[:track_number].empty? == false
song = create_song(:release => releases(:violent_mosh), :track_number => 1)
assert song.save
end
# Private methods
private
def create_song(options = {})
song_hash = {
:title => 'Atomic Nightmare',
:track_number => 2,
:lyrics => 'Letras',
:release => releases(:chemical_assault)
}
Song.new(song_hash.merge options)
end
end
| true
|
d9c76aac66f2eecd112edc451c4d3f565e2e6e04
|
Ruby
|
EricaNichol/CodeCore-
|
/react-native/week_1/greg.rb
|
UTF-8
| 240
| 3.609375
| 4
|
[] |
no_license
|
puts "how many lines should triangle have?"
size = gets.chomp.to_i
space = ""
(size - 1).times { space += " " }
zeros = "0"
#2 times string = 2 string
size.times do
puts "#{space}#{zeros}"
space = space.chomp(" ")
zeros += " 0"
end
| true
|
2b3ccb32aeabc713123a1ec419a4794e2112618b
|
Ruby
|
tztz8/CIS-283-Various_Classes
|
/RubyClasses_Freeman.rb
|
UTF-8
| 7,255
| 3.9375
| 4
|
[] |
no_license
|
#################################################################
#
# Name: Timbre Freeman
# Assignment: Ruby Classes
# Date: 01/22/2020
# Class: CIS 283
# Description: Make and use Perosn, Address and Character Class
#
#################################################################
# Person Class
class Person
# first_name, last_name, age, hair_color, eye_color
def initialize (first_name, last_name, age, hair_color, eye_color)
@first_name = first_name
@last_name = last_name
@age = age
@hair_color = hair_color
@eye_color = eye_color
end
# getter and setter
def first_name
@first_name
end
def first_name=(first_name)
@first_name = first_name
end
def last_name
@last_name
end
def last_name=(last_name)
@last_name = last_name
end
def age
@age
end
def age=(age)
@age = age
end
def hair_color
@hair_color
end
def hair_color=(hair_color)
@hair_color = hair_color
end
def eye_color
@eye_color
end
def eye_color=(eye_color)
@eye_color = eye_color
end
# Methods - to_s()
# to_s() - print out a nice representation of the attributes of this person
def to_s
puts "#{first_name} #{last_name} is #{age} old, has #{hair_color} hair color and has #{eye_color} eye color"
end
end
# Address Class
class Address
# line1, line2, city, state, zip
def initialize(line1,line2="",city,state,zip)
@line1 = line1
@line2 = line2
@city = city
@state = state
@zip = zip
end
# getter and setter
def line1
@line1
end
def line1=(line1)
@line1 = line1
end
def line2
@line2
end
def line2=(line2)
@line2 = line2
end
def city
@city
end
def city=(city)
@city = city
end
def state
@state
end
def state=(state)
@state = state
end
def zip
@zip
end
def zip=(zip)
@zip = zip
end
# method - to_s()
# to_s() - print out a nice representation of the attributes of this person
def to_s
puts @line1
puts @line2
puts "#{city}, #{state}, #{zip}"
end
end
# Character Class
class Character
# name, race, hit_points, weapons[] (array of weapon names), gold, clothing[] (array of clothing items)
def initialize(name,race,hit_points,gold,weapons=Array.new,clothing=Array.new)
@name = name
@race = race
@hit_points = hit_points
@weapons = weapons
@gold = gold
@clothing = clothing
end
# getter and setter (no setter for weapons and clothing)
def name
@name
end
def name=(name)
@name = name
end
def race
@race
end
def race=(race)
@race = race
end
def hit_points
@hit_points
end
def hit_points=(hit_points)
@hit_points = hit_points
end
def gold
@gold
end
def gold=(gold)
@gold = gold
end
def weapons
@weapons
end
# When I use some one else library or code it was vary helpful to have a error with tips how to fix my error when trying to do something
def weapons=(*)
puts "Error need to use add_weapon(weapon_name) or drop_weapon(weapon_name)"
end
def clothing
@clothing
end
def clothing=(*)
puts "Error need to use add_clothing(item) or drop_clothing(item)"
end
# method's
# to_s() - print out a nice representation of the attributes of this person
def to_s
puts "Character Name: #{@name}"
puts "Character Race: #{@race}"
puts "Character Hit Points: #{@hit_points}"
print "Character Weapons: "
for weapon in @weapons
print weapon
print " , "
end
puts ""
puts "Character Gold: #{@gold}"
print "Character Clothing: "
for cloth in @clothing
print cloth
print " , "
end
puts ""
end
# add_weapon(weapon_name)
def add_weapon(weapon_name)
@weapons.push(weapon_name)
end
# drop_weapon(weapon_name)
def drop_weapon(weapon_name)
@weapons.delete(weapon_name)
end
# add_clothing(item)
def add_clothing(item)
@clothing.push(item)
end
# drop_clothing(item)
def drop_clothing(item)
@clothing.delete(item)
end
end
# testing Person class
puts "########################"
puts "# Testing Person Class #"
puts "########################"
coder = Person.new("Timbre", "Freeman", 20, "bron", "bron")
coder.to_s
puts "chage coder to bob bobivers 12 blue red"
puts "old f.name #{coder.first_name}"
coder.first_name = "bob"
puts "new f.name #{coder.first_name}"
puts "old l.name #{coder.last_name}"
coder.last_name = "bobivers"
puts "new l.name #{coder.last_name}"
puts "old age #{coder.age}"
coder.age = 1000
puts "new age #{coder.age}"
puts "old hair color #{coder.hair_color}"
coder.hair_color = "blue"
puts "new hair color #{coder.hair_color}"
puts "old eye color #{coder.eye_color}"
coder.eye_color = "red"
puts "new eye color #{coder.eye_color}"
coder.to_s
# testing Address class
puts "#########################"
puts "# Testing Address Class #"
puts "#########################"
#coder_address = Address.new("1023 N Van", "", "spokane", "wa", 99206)
coder_address = Address.new("1023 N van", "spokane", "WA", 99206)
coder_address.to_s
puts "old line1 #{coder_address.line1}"
coder_address.line1 = "no line1"
puts "new line1 #{coder_address.line1}"
puts "old line2 #{coder_address.line2}"
coder_address.line2 = "no line2"
puts "new line2 #{coder_address.line2}"
puts "old city #{coder_address.city}"
coder_address.city = "open"
puts "new city #{coder_address.city}"
puts "old state #{coder_address.state}"
coder_address.state = "code"
puts "new state #{coder_address.state}"
puts "old zip #{coder_address.zip}"
coder_address.zip = 99999
puts "new zip #{coder_address.zip}"
coder_address.to_s
# testing Character class
puts "###########################"
puts "# Testing Character Class #"
puts "###########################"
#coder_character = Character.new("tztz8","elf",0,100,["stord","shild"],["sheart","pants"])
coder_character = Character.new("Timbre","human",0,100)
coder_character.to_s
puts "old name #{coder_character.name}"
coder_character.name = "tztz8"
puts "new name #{coder_character.name}"
puts "old race #{coder_character.race}"
coder_character.race = "elf"
puts "new race #{coder_character.race}"
puts "old hit points #{coder_character.hit_points}"
coder_character.hit_points = 100
puts "new hit points #{coder_character.hit_points}"
puts "old gold #{coder_character.gold}"
coder_character.gold = 0
puts "new gold #{coder_character.gold}"
puts "old weapons #{coder_character.weapons}"
coder_character.weapons = ["stord","shild"]
puts "fail new weapons #{coder_character.weapons}"
puts "adding weapon stord and shild"
coder_character.add_weapon("stord")
coder_character.add_weapon("shild")
puts "new weapons #{coder_character.weapons}"
puts "removing shild"
coder_character.drop_weapon("shild")
puts "new weapons #{coder_character.weapons}"
puts "old clothing #{coder_character.clothing}"
coder_character.clothing = ["sheart","pants"]
puts "fail new clothing #{coder_character.clothing}"
puts "adding cloth sheart and pants"
coder_character.add_clothing("sheart")
coder_character.add_clothing("pants")
puts "new clothing #{coder_character.clothing}"
puts "removing sheart"
coder_character.drop_clothing("sheart")
puts "new clothing #{coder_character.clothing}"
coder_character.to_s
| true
|
96577e2758042566c27eb63df7f112bba1f79629
|
Ruby
|
anthonycarlos/ehash
|
/bin/ehash
|
UTF-8
| 2,843
| 2.578125
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require 'gli'
begin # XXX: Remove this begin/rescue before distributing your app
require 'ehash'
rescue LoadError
STDERR.puts "In development, you need to use `bundle exec bin/ehash` to run your app"
STDERR.puts "At install-time, RubyGems will make sure lib, etc. are in the load path"
STDERR.puts "Feel free to remove this message from bin/ehash now"
exit 64
end
include GLI::App
program_desc 'Encrypted Hash. An array of hashes to store and find stuff.'
version Ehash::VERSION
subcommand_option_handling :normal
arguments :strict
desc 'Describe some switch here'
switch [:s,:switch]
desc 'Describe some flag here'
default_value 'the default'
arg_name 'The name of the argument'
flag [:f,:flagname]
desc 'Describe new here'
arg_name 'Describe arguments to new here'
command :new do |c|
c.desc 'Describe a switch to new'
c.switch :s
c.desc 'The ehash data file to use'
c.default_value File.join(Dir.home, 'ehash.yml')
c.flag :f
c.action do |global_options,options,args|
# Your command logic here
data_file_path = options[:f] || c.default_value
File.open(data_file_path, 'w') { |file| YAML::dump([]) }
# If you have any errors, just raise them
# raise "that command made no sense"
puts "new command ran"
end
end
desc 'Describe password here'
arg_name 'Describe arguments to password here'
command :password do |c|
c.action do |global_options,options,args|
puts "password command ran"
end
end
desc 'Describe add here'
arg_name 'Describe arguments to add here'
command :add do |c|
c.action do |global_options,options,args|
puts "add command ran"
end
end
desc 'Describe update here'
arg_name 'Describe arguments to update here'
command :update do |c|
c.action do |global_options,options,args|
puts "update command ran"
end
end
desc 'Describe delete here'
arg_name 'Describe arguments to delete here'
command :delete do |c|
c.action do |global_options,options,args|
puts "delete command ran"
end
end
desc 'Describe find here'
arg_name 'Describe arguments to find here'
command :find do |c|
c.action do |global_options,options,args|
puts "find command ran"
end
end
desc 'Describe list here'
arg_name 'Describe arguments to list here'
command :list do |c|
c.action do |global_options,options,args|
puts "list command ran"
end
end
pre do |global,command,options,args|
# Pre logic here
# Return true to proceed; false to abort and not call the
# chosen command
# Use skips_pre before a command to skip this block
# on that command only
true
end
post do |global,command,options,args|
# Post logic here
# Use skips_post before a command to skip this
# block on that command only
end
on_error do |exception|
# Error logic here
# return false to skip default error handling
true
end
exit run(ARGV)
| true
|
f8596779613a668b9d8f6bf5cce6dfff796120de
|
Ruby
|
gbuilds/bank-app
|
/bankapp.rb
|
UTF-8
| 1,520
| 3.875
| 4
|
[] |
no_license
|
class Account
attr_reader :name, :balance
def initialize(name, balance=100)
@name = name
@balance = balance
end
public
def display_balance(pin_number)
if pin_number == pin
puts "Balance: $#{@balance}"
else
puts pin_error
end
end
def withdraw(pin_number, amount)
if pin_number == pin
if amount > @balance
puts "Not enough funds in account. Transaction cancelled. $3 Bank fee assessed."
@balance -= 3
else
@balance = @balance - amount
puts "Withdrew $#{amount}. New blalance: $#{@balance}"
end
else
puts pin_error
end
end
def deposit(pin_number, amount)
if pin_number == pin
@balance += amount
puts "Added $#{amount} funds to account. New balance: $#{@balance}."
else
puts pin_error
end
end
private
def pin
@pin = 1234
end
def pin_error
"Access denied: incorrect PIN."
end
end
class CheckingAccount < Account
def order_cheques
puts "Checks mailed to #{@name}"
@balance -= 4
end
end
class SavingsAccount < Account
end
checking_account = CheckingAccount.new("Gordie", 1000)
puts "Created a checking account for #{checking_account.name}"
checking_account.withdraw(1234, 50)
checking_account.display_balance(1234)
checking_account.withdraw(1234, 2000)
checking_account.deposit(1234, 100)
checking_account.display_balance(1234)
checking_account.order_cheques
checking_account.display_balance(1234)
| true
|
497f0be5ed5b78739b9d838bf6ecdd25b320f51a
|
Ruby
|
samullen/ruby-redtail
|
/lib/ruby-redtail/contact/addresses.rb
|
UTF-8
| 2,240
| 2.515625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
module RubyRedtail
class Addresses
def initialize(api_hash)
@api_hash = api_hash
end
# Fetch Address By Contact Id
def fetch (contact_id)
RubyRedtail::Query.run("contacts/#{contact_id}/addresses", @api_hash, "GET")
end
# Update Address
def update (contact_id, address_id, params)
RubyRedtail::Query.run("contacts/#{contact_id}/addresses/#{address_id}", @api_hash, 'PUT', params)
end
# Create New Address
def create (contact_id, params)
update(contact_id, 0, params)
end
# Delete Address
def delete (contact_id, address_id)
RubyRedtail::Query.run("contacts/#{contact_id}/addresses/#{address_id}", @api_hash, 'DELETE')
end
# Fetch Phones By Contact Id
def phones (contact_id)
RubyRedtail::Query.run("contacts/#{contact_id}/phones", @api_hash, "GET")
end
# Update Phone
def update_phone (contact_id, phone_id, params)
RubyRedtail::Query.run("contacts/#{contact_id}/phones/#{phone_id}", @api_hash, 'PUT', params)
end
# Create New Phone
def create_phone (contact_id, params)
update(contact_id, 0, params)
end
# Delete Phone
def delete_phone (contact_id, phone_id)
RubyRedtail::Query.run("contacts/#{contact_id}/phones/#{phone_id}", @api_hash, 'DELETE')
end
# Fetch Internet Addresses By Contact Id
def internet_addresses (contact_id)
RubyRedtail::Query.run("contacts/#{contact_id}/internets", @api_hash, "GET")
end
# Update Internet Address
def update_internet_address (contact_id, internet_id, params)
RubyRedtail::Query.run("contacts/#{contact_id}/phones/#{internet_id}", @api_hash, 'PUT', params)
end
# Create New Internet Address
def create_internet_address (contact_id, params)
update_internet_address(contact_id, 0, params)
end
# Delete Internet Address
def delete_internet_address (contact_id, internet_id)
RubyRedtail::Query.run("contacts/#{contact_id}/phones/#{internet_id}", @api_hash, 'DELETE')
end
# Fetch Assets and Liabilities
def assets_and_liabilities (contact_id)
RubyRedtail::Query.run("contacts/#{contact_id}/assets-liabilities", @api_hash, "GET")
end
end
end
| true
|
ebfc525c4977411e53913e2df94682b94615cc9a
|
Ruby
|
jeaxelrod/railschallenge-city-watch
|
/app/services/dispatcher.rb
|
UTF-8
| 1,624
| 2.75
| 3
|
[] |
no_license
|
class Dispatcher
attr_accessor :emergency
attr_reader :full_response, :available_on_duty_responders
TYPES = [:fire, :police, :medical]
def initialize(emergency)
@emergency = emergency
@resolved = {}
TYPES.each { |type| @resolved[type] = false }
dispatch
end
def available_on_duty_responders
@available_on_duty_responders ||= Responder.where(emergency_id: nil, on_duty: true)
end
def dispatched_responders
@dispatched_responders ||= []
end
private
def dispatch
TYPES.each do |type|
send_responders(type)
end
@full_response = TYPES.inject(true) { |a, e| a && @resolved[e] }
end
def send_responders(type)
responders = on_duty_responders_by_type(type).to_a
severity = severity_by_type(type)
until severity <= 0 || responders.length == 0
responder = match_responder(severity, responders)
severity -= responder.capacity
update_available_responders(responder)
responders.delete(responder)
end
@resolved[type] = true if severity <= 0
end
def on_duty_responders_by_type(type)
type_attr = type.to_s.capitalize
available_on_duty_responders.where(type: type_attr)
end
def severity_by_type(type)
severity_attr = "#{type}_severity"
@emergency[severity_attr]
end
def update_available_responders(responder)
dispatched_responders.push(responder)
@available_on_duty_responders = @available_on_duty_responders.where.not(id: responder.id)
end
def match_responder(severity, responders)
responders.find { |responder| responder.capacity == severity } || responders.pop
end
end
| true
|
309e4eb5481fca0d90c047fe1369bd3fce868493
|
Ruby
|
akanshmurthy/codelearnings
|
/appacademy/w2d4/my-stack.rb
|
UTF-8
| 1,291
| 3.5
| 4
|
[] |
no_license
|
require "byebug"
class MyStack
attr_reader :max, :min
def initialize
@store = []
@min = nil
@max = nil
end
def pop
el = @store.pop
if peek.nil?
@max = nil
@min = nil
else
@max = peek[:max]
@min = peek[:min]
end
el
end
def push(el)
@min = el if min.nil? || el < min
@max = el if max.nil? || el > max
@store.push({value: el, max: max, min: min})
end
def peek
@store.last
end
def size
@store.length
end
end
class MinMaxStackQueue
def initialize()
@in_stack = MyStack.new()
@out_stack = MyStack.new()
end
def enqueue(el)
@in_stack.push(el)
end
def dequeue
flip if @out_stack.size.zero?
@out_stack.pop
end
def flip
until @in_stack.size.zero?
@out_stack.push(@in_stack.pop[:value])
end
end
def peek
@out_stack.peek
end
def size
@in_stack.size + @out_stack.size
end
def min
# if @out_stack.min.nil? || @in_stack.min < @out_stack.min
# @in_stack.min
# else
# @out_stack.min
# end
flip
@out_stack.min
end
def max
# if @out_stack.max.nil? || @in_stack.max > @out_stack.max
# @in_stack.max
# else
# @out_stack.max
# end
flip
@out_stack.max
end
end
| true
|
a2001e3ddddbc283558493c03c889637bdae859d
|
Ruby
|
spektroskop/scheme
|
/cons.rb
|
UTF-8
| 2,004
| 3.109375
| 3
|
[] |
no_license
|
require "./undefined"
require "./empty"
class Object
def list?
if Cons === self
last.cdr.null?
else
null?
end
end
def null?
Empty === self
end
def pair?
Cons === self
end
end
def List(array, tail = Empty)
return Empty if array.empty?
array.reverse.reduce(tail) do |cons, node|
node = List(node) if Array === node
Cons.new(node, cons)
end
end
class Cons
attr_accessor :car, :cdr
def initialize(car, cdr = Empty)
@car, @cdr = car, cdr
end
def each
cur, pre, idx = self, nil, 0
while cur.pair?
yield(cur.car, pre, idx) if block_given?
pre, cur = cur, cur.cdr, idx += 1
end
pre
end
def reduce(expr = Undefined)
each do |car, *args|
expr = expr == Undefined ? car : yield(expr, car, *args)
end
expr
end
def last
each
end
def length
reduce(0) do |res, _|
res += 1
end
end
def reverse
reduce(last.cdr) do |res, cur|
res = Cons.new(cur, res)
end
end
def map(&block)
reverse.reduce(Empty) do |res, cur|
res = Cons.new(block[cur], res)
end
end
def array
reduce([]) do |res, cur|
res << cur
end
end
def append(object)
cons = List(array, last.cdr)
cons.last.cdr = object
cons
end
def to_s
nodes = []
x = each{|node| nodes << node.to_s }
s = nodes.join(" ")
s+= " . " + x.cdr.to_s unless x.cdr.null?
return "(#{s})"
end
def method_missing(sym, *args)
if sym =~ /^c([ad])[ad]*r/
ad = Regexp.last_match[1]
self.class.class_eval %<def #{sym}
#{sym.to_s.sub(ad, "")}.c#{ad}r
end>
send(sym)
else
super
end
end
end
| true
|
9c3dfcfda9a8975599bb84bdd9770a9914bbdca6
|
Ruby
|
timbuchwaldt/torquebox-chef
|
/tb-deployer-client/templates/default/knob_poll.rb.erb
|
UTF-8
| 1,742
| 2.53125
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
require 'net/http'
uri = URI(latest_url)
latest_build_number = Net::HTTP.get(uri)
last_build_file = "<%="#{@app_root}/#{@application_name}"%>_lastbuild.txt"
last_build_number = 0
if File.exists? last_build_file
last_build_number = File.new(last_build_file).read
end
unless last_build_number == latest_build_number
puts "found new build #{latest_build_number}"
puts "stopping torquebox..."
`/sbin/service jboss-as-standalone stop`
puts "calling deploy script as torquebox user..."
`su - torquebox -c "/bin/bash <%="#{@app_root}/#{@application_name}"%>_knob_deploy.sh #{latest_build_number}"`
puts "starting torquebox..."
`/sbin/service jboss-as-standalone start`
puts "updating <%=@application_name%> build status..."
File.open(last_build_file, 'w') { |file| file.write(latest_build_number) }
end
#!/bin/bash
latest_url="<%="http://#{@knob_server}/#{@project_environment}/#{@application_name}/latest.txt"%>"
latest_build_number=$(wget -O- -q $latest_url);
echo $latest_build_number;
last_build_number="";
last_build_file="/opt/torquebox/apps/services_lastbuild.txt";
if [ -f $last_build_file ]; then
last_build_number=$(cat $last_build_file);
fi
if [ "$last_build_number" == "$latest_build_number" ];then
echo "latest build deployed";
echo "latest : $latest_build_number";
echo "last : $last_build_number";
else
echo "found new build..."
echo "stopping torquebox..."
/sbin/service jboss-as-standalone stop;
echo "calling deploy script as torquebox user...";
su - torquebox -c "/bin/bash /opt/torquebox/apps/services_knob_deploy.sh $latest_build_number";
echo "starting torquebox...";
/sbin/service jboss-as-standalone start;
echo $latest_build_number > $last_build_file;
fi
| true
|
6d7640f2f4c1abcfb78804d0d1688640b4a61f50
|
Ruby
|
yuuuuut/DootInternKadai
|
/3-1-backend/app/models/user.rb
|
UTF-8
| 696
| 2.546875
| 3
|
[] |
no_license
|
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
include DeviseTokenAuth::Concerns::User
validates :name, presence: true
has_many :messages, dependent: :destroy
has_many :entries, dependent: :destroy
has_many :rooms, through: :entries
# userとのroomが存在するか確認。
# 存在した場合は、そのroomIdも返す。
def user_with_room(user)
current_user_room_ids = rooms.pluck(:id)
user_room_ids = user.rooms.pluck(:id)
room = current_user_room_ids & user_room_ids
is_room = room.present?
room_id = is_room ? room[0] : ''
[room_id, is_room]
end
end
| true
|
c75cadeeb442a1075b3114965b02e8d436089319
|
Ruby
|
ojasve123/training
|
/ruby/naturalnumbers.rb
|
UTF-8
| 77
| 3.375
| 3
|
[] |
no_license
|
puts "please enter a number"
i = gets.chomp.to_i
for x in 1..i
puts x
end
| true
|
be7004fe7710f36d88f2b7fd5f3ba96bfbf80ca7
|
Ruby
|
DarthMarino/UniversalTranslatorRb
|
/tests/test_universaltranslator.rb
|
UTF-8
| 1,549
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
require 'test-unit'
require 'universaltranslator'
# TestNumberTranslator tests differents inputs a modified universal translator to instead of printing returning errors.
class TestNumberTranslator < Test::Unit::TestCase
# Empty file
def test_one
input = 'input_tes1.txt'
translate = UniversalTranslator.new
assert_equal('File is empty', translate.get_data(input))
end
# Wrong Value
def test_two
input = 'input_tes2.txt'
translate = UniversalTranslator.new
assert_equal('Your value is not valid or is 0', translate.get_data(input))
end
# Non existant File
def test_three
input = 'invalid_input.txt'
translate = UniversalTranslator.new
assert_equal('Input is invalid', translate.get_data(input))
end
# Empty file
def test_four
input = 'input_tes3.txt'
translate = UniversalTranslator.new
assert_equal('There is missing data', translate.get_data(input))
end
# Wrong initial metirc unit
def test_five
input = 'input_tes4.txt'
translate = UniversalTranslator.new
assert_equal('There is an error in a initial metric unit', translate.get_data(input))
end
# Wrong destiny metric unit
def test_six
input = 'input_tes5.txt'
translate = UniversalTranslator.new
assert_equal('There is an error in a destiny metric unit', translate.get_data(input))
end
# Everything went cool
def test_seven
input = 'input_tes7.txt'
translate = UniversalTranslator.new
assert_equal('Succesfully Made Output', translate.get_data(input))
end
end
| true
|
6249d3ce14c3ca47c0c157c27a612c9415cf6615
|
Ruby
|
harisafridi/sort
|
/selectinsort.rb
|
UTF-8
| 298
| 3.71875
| 4
|
[] |
no_license
|
def selectionsort(array)
(0...array.size).each do |j|
min = j
puts "array value: #{j}"
(j+1...array.size).each do |i|
min = i if array[i] < array[min]
end
array[j], array[min] = array[min], array[j]
end
return array
end
list = [7,10,3,99,50]
puts selectionsort(list)
| true
|
862b4430970c43d3c09b1114c1958a6977032d34
|
Ruby
|
dkhan/bible_code
|
/bible_code.rb
|
UTF-8
| 14,038
| 3.21875
| 3
|
[] |
no_license
|
# Galatians 2:20 (KJV): I am crucified with Christ: nevertheless I live; yet not I, but Christ liveth in me: and the life which I now live in the flesh I live by the faith of the Son of God, who loved me, and gave himself for me.
# verse = "χριστω συνεσταυρωμαι ζω δε ουκετι εγω ζη δε εν εμοι χριστος ο δε νυν ζω εν σαρκι εν πιστει ζω τη του υιου του θεου του αγαπησαντος με και παραδοντος εαυτον υπερ εμου"
# BibleCode.decode_all(verse)
# code = BibleCode.new(verse: verse, author: 'KHAN', value: :numeric_value, verbose: false, word_stat: true); pp code.vocabulary.sort;1
# code.break
# code.decode
# code.unique_word_count
# code.translate
# sum = 19061
# sum/7.0 => 2723.0
# 2+7+2+3 => 14 => 7*2
class BibleCode
require 'prime'
require 'json'
attr_reader :verse, :author, :map, :value
KHAN_MAP = {
' ' => { place_value: 0, numeric_value: 0, value: 0, vowel: false },
'α' => { place_value: 1, numeric_value: 1, value: 2, vowel: true },
'β' => { place_value: 2, numeric_value: 2, value: 4, vowel: false },
'γ' => { place_value: 3, numeric_value: 3, value: 6, vowel: false },
'δ' => { place_value: 4, numeric_value: 4, value: 8, vowel: false },
'ε' => { place_value: 5, numeric_value: 5, value: 10, vowel: true },
'ς' => { place_value: 6, numeric_value: 6, value: 12, vowel: false },
'ζ' => { place_value: 7, numeric_value: 7, value: 14, vowel: false },
'η' => { place_value: 8, numeric_value: 8, value: 16, vowel: true },
'θ' => { place_value: 9, numeric_value: 9, value: 18, vowel: false },
'ι' => { place_value: 10, numeric_value: 10, value: 20, vowel: true },
'κ' => { place_value: 11, numeric_value: 20, value: 31, vowel: false },
'λ' => { place_value: 12, numeric_value: 30, value: 42, vowel: false },
'μ' => { place_value: 13, numeric_value: 40, value: 53, vowel: false },
'ν' => { place_value: 14, numeric_value: 50, value: 64, vowel: false },
'ξ' => { place_value: 15, numeric_value: 60, value: 75, vowel: false },
'ο' => { place_value: 16, numeric_value: 70, value: 86, vowel: true },
'π' => { place_value: 17, numeric_value: 80, value: 97, vowel: false },
'ϙ' => { place_value: 18, numeric_value: 90, value: 108, vowel: false },
'ρ' => { place_value: 19, numeric_value: 100, value: 119, vowel: false },
'σ' => { place_value: 20, numeric_value: 200, value: 220, vowel: false },
'τ' => { place_value: 21, numeric_value: 300, value: 321, vowel: false },
'υ' => { place_value: 22, numeric_value: 400, value: 422, vowel: true },
'φ' => { place_value: 23, numeric_value: 500, value: 523, vowel: false },
'χ' => { place_value: 24, numeric_value: 600, value: 624, vowel: false },
'ψ' => { place_value: 23, numeric_value: 700, value: 723, vowel: false },
'ω' => { place_value: 24, numeric_value: 800, value: 824, vowel: true },
'ϡ' => { place_value: 25, numeric_value: 900, value: 925, vowel: false }
}
PANIN_MAP = {
' ' => { place_value: 0, numeric_value: 0, value: 0, vowel: false },
'α' => { place_value: 1, numeric_value: 1, value: 2, vowel: true },
'β' => { place_value: 2, numeric_value: 2, value: 4, vowel: false },
'γ' => { place_value: 3, numeric_value: 3, value: 6, vowel: false },
'δ' => { place_value: 4, numeric_value: 4, value: 8, vowel: false },
'ε' => { place_value: 5, numeric_value: 5, value: 10, vowel: true },
'ζ' => { place_value: 6, numeric_value: 7, value: 13, vowel: false },
'η' => { place_value: 7, numeric_value: 8, value: 15, vowel: true },
'θ' => { place_value: 8, numeric_value: 9, value: 17, vowel: false },
'ι' => { place_value: 9, numeric_value: 10, value: 19, vowel: true },
'κ' => { place_value: 10, numeric_value: 20, value: 30, vowel: false },
'λ' => { place_value: 11, numeric_value: 30, value: 41, vowel: false },
'μ' => { place_value: 12, numeric_value: 40, value: 52, vowel: false },
'ν' => { place_value: 13, numeric_value: 50, value: 63, vowel: false },
'ξ' => { place_value: 14, numeric_value: 60, value: 74, vowel: false },
'ο' => { place_value: 15, numeric_value: 70, value: 85, vowel: true },
'π' => { place_value: 16, numeric_value: 80, value: 96, vowel: false },
'ρ' => { place_value: 17, numeric_value: 100, value: 117, vowel: false },
'σ' => { place_value: 18, numeric_value: 200, value: 218, vowel: false },
'ς' => { place_value: 18, numeric_value: 200, value: 218, vowel: false },
'τ' => { place_value: 19, numeric_value: 300, value: 319, vowel: false },
'υ' => { place_value: 20, numeric_value: 400, value: 420, vowel: true },
'φ' => { place_value: 21, numeric_value: 500, value: 521, vowel: false },
'χ' => { place_value: 22, numeric_value: 600, value: 622, vowel: false },
'ψ' => { place_value: 23, numeric_value: 700, value: 723, vowel: false },
'ω' => { place_value: 24, numeric_value: 800, value: 824, vowel: true }
}
WORD_FORMS = {
"ο" => %w(του τον της τους),
"εζεκιας" => %w(εζεκιας εζεκιαν),
"ιουδας" => %w(ιουδας ιουδαν),
"ιωσιας" => %w(ιωσιας ιωσιαν),
"μανασσης" => %w(μανασσης μανασση),
"οζιας" => %w(οζιας οζιαν),
"σολομων" => %w(σολομων σολομωνα),
"γενναω" => %w(εγεννησεν),
"γενεσις" => %w(γενεσεως),
"βασιλευς" => %w(βασιλεα),
"ιησους" => %w(ιησου),
"χριστος" => %w(χριστου),
"υιος" => %w(υιου),
"αδελφος" => %w(αδελφους),
"αυτος" => %w(αυτου),
"ουριας" => %w(ουριου),
"ιεχονιας" => %w(ιεχονιαν),
"μετοικεσια" => %w(μετοικεσιας),
"βαβυλων" => %w(βαβυλωνος),
}
def initialize(verse:, author: 'KHAN', value: :numeric_value, verbose: false, word_stat: true)
@verse = verse
@author = author
@map = author == 'KHAN' ? KHAN_MAP : PANIN_MAP
@value = value
@verbose = verbose
@word_stat = word_stat
end
def self.decode_all(verse)
BibleCode.new(verse: verse, author: 'KHAN', value: :place_value, verbose: false, word_stat: true).decode
BibleCode.new(verse: verse, author: 'KHAN', value: :numeric_value, verbose: false, word_stat: false).decode
BibleCode.new(verse: verse, author: 'KHAN', value: :value, verbose: false, word_stat: false).decode
BibleCode.new(verse: verse, author: 'PANIN', value: :place_value, verbose: false, word_stat: false).decode
BibleCode.new(verse: verse, author: 'PANIN', value: :numeric_value, verbose: false, word_stat: false).decode
BibleCode.new(verse: verse, author: 'PANIN', value: :value, verbose: false, word_stat: false).decode
end
def analyze
printf "The number of words: %7d %50s\n", word_count, primes(word_count)
printf "The number of letters: %7d %50s\n", letter_count, primes(letter_count)
printf "The number of vowels: %7d %50s\n", vowel_count, primes(vowel_count)
printf "The number of consonants: %7d %50s\n", consonant_count, primes(consonant_count)
printf "The number of words that begin with a vowel: %7d %50s\n", vowel_word_count, primes(vowel_word_count)
printf "The number of words that begin with a consonant: %7d %50s\n", consonant_word_count, primes(consonant_word_count)
printf "The number of words that occur more than once: %7d %50s\n", words_more_than_once_count, primes(words_more_than_once_count)
printf "The number of vocabulary words: %7d %50s\n", vocabulary_count, primes(vocabulary_count)
printf "The number of vocabulary letters: %7d %50s\n", vocabulary_letter_count, primes(vocabulary_letter_count)
printf "The number of vocabulary vowels: %7d %50s\n", vocabulary_vowel_count, primes(vocabulary_vowel_count)
printf "The number of vocabulary consonants: %7d %50s\n", vocabulary_consonant_count, primes(vocabulary_consonant_count)
printf "The number of vocabulary words that begin with a vowel: %7d %50s\n", vocabulary_vowel_word_count, primes(vocabulary_vowel_word_count)
printf "The number of vocabulary words that begin with a consonant: %7d %50s\n", vocabulary_consonant_word_count, primes(vocabulary_consonant_word_count)
printf "The number of vocabulary words that occur more than once: %7d %50s\n", vocabulary_more_than_once_count, primes(vocabulary_more_than_once_count)
printf "The number of vocabulary words that occur in more than one form: %7d %50s\n", vocabulary_more_than_one_form_count, primes(vocabulary_more_than_one_form_count)
printf "The number of vocabulary words that occur only in one form: %7d %50s\n", vocabulary_only_in_one_form_count, primes(vocabulary_only_in_one_form_count)
end
def words
@words ||= verse.split(' ')
end
def letters
@letters ||= verse.gsub(' ', '').chars
end
def letter_count
@letter_count ||= letters.count
end
def vowel_count
letters.select{ |l| map[l][:vowel] }.count
end
def consonant_count
letters.reject{ |l| map[l][:vowel] }.count
end
def word_count
@word_count ||= words.count
end
def vowel_word_count
words.select{|w| map[w[0]][:vowel] }.count
end
def consonant_word_count
words.reject{|w| map[w[0]][:vowel] }.count
end
def words_more_than_once_count
unique_words.values.select{|v|v > 1}.count
end
def decode
if @verbose
words.each do |word|
wc = BibleCode.new(verse: word, author: author, value: value)
printf "%20s %-80s %6s %s\n", word, *wc.decode_word
end
puts "-"*200
end
puts "words: #{word_count} words primes: #{Prime.prime_division(word_count)}" if @word_stat
printf "%-5s %-15s sum: %7d primes: #{primes}\n", author, value, sum
end
def decode_word
[numbers, sum, primes]
end
def break
1.upto(word_count).each do |i|
v = words[0..-i].join(' ')
code = BibleCode.new(verse: v, author: author, value: value)
printf "%7d %50s #{v}\n", code.sum, code.primes
end
end
def sum
numbers.inject(0) { |s, n| s += n }
end
def numbers
verse.chars.map { |l| map[l][value] }
end
def primes(num = sum)
return [] if num == 0
Prime.prime_division(num)
end
def unique_words
return @unique_words if @unique_words
@unique_words = {}
words.each do |word|
if @unique_words[word]
@unique_words[word] += 1
else
@unique_words[word] = 1
end
end
@unique_words
end
def unique_word_count
unique_words.keys.count
end
def vocabulary
return @vocabulary if @vocabulary
@vocabulary = {}
unique_words.each do |word, count|
vw = word
forms = []
WORD_FORMS.each do |w, f|
if f.include?(word)
vw = w
forms = f
break
end
end
if @vocabulary[vw]
@vocabulary[vw][0] += count
else
@vocabulary[vw] = [count, forms]
end
end
@vocabulary
end
def vocabulary_count
vocabulary.keys.count
end
def vocabulary_letter_count
vcode = BibleCode.new(verse: vocabulary.keys.join(' '), author: author, value: value)
vcode.letter_count
end
def vocabulary_more_than_once_count
vocabulary.values.select{|v|v[0] > 1}.count
end
def vocabulary_vowel_count
vcode = BibleCode.new(verse: vocabulary.keys.join(' '), author: author, value: value)
vcode.vowel_count
end
def vocabulary_consonant_count
vcode = BibleCode.new(verse: vocabulary.keys.join(' '), author: author, value: value)
vcode.consonant_count
end
def vocabulary_vowel_word_count
vcode = BibleCode.new(verse: vocabulary.keys.join(' '), author: author, value: value)
vcode.vowel_word_count
end
def vocabulary_consonant_word_count
vcode = BibleCode.new(verse: vocabulary.keys.join(' '), author: author, value: value)
vcode.consonant_word_count
end
def vocabulary_more_than_one_form_count
vocabulary.values.select{|v|v[1].count > 1}.count
end
def vocabulary_only_in_one_form_count
vocabulary.values.select{|v|v[1].count <= 1}.count
end
def dictionary_check
json = File.read("dictionary.json")
dictionary = JSON.parse(json)
vocabulary.keys.each do |word|
puts "#{word}: #{!dictionary[word].nil?}"
end
end
def translate
words.each do |word|
printf "%40s %40s\n", word, Translator.translate(word, 'el-GR', 'en')
end
nil
end
end
class Translator
require 'net/http'
require 'rubygems'
require "uri"
require 'json'
def self.translate(text, from = 'el-GR', to = 'en')
uri = URI.parse("http://mymemory.translated.net/api/get")
response = Net::HTTP.post_form(uri, { "q" => text,"langpair" => "#{from.downcase}|#{to.downcase}", "per_page" => "50" })
json_response_body = JSON.parse response.body
if json_response_body['responseStatus'] == 200
json_response_body['responseData']['translatedText']
else
"<#{text}>"
# puts json_response_body['responseDetails']
end
rescue
"<#{text}>"
end
end
| true
|
f45a4ea44385403afe3208eddbb5cd6e52244b75
|
Ruby
|
l-jdavies/ruby_small_problems
|
/ruby_basics/longest_alphabetical_substring.rb
|
UTF-8
| 895
| 4.34375
| 4
|
[] |
no_license
|
# Find the longest substring in alphabetical order.
# The input will only consist of lowercase characters and will be at least one letter long.
# If there are multiple solutions, return the one that appears first.
# ALGORITHM
# generate substrings
# store substrings in an array
# if substr is in alphabetical order
# add to array of alphabetical substrings
# sort that array
# return last element
def longest(str)
alphabet_substr = find_substr(str).select do |substr|
substr.chars == substr.chars.sort
end
alphabet_substr.sort_by! { |str| str.length }
longest = alphabet_substr.select { |str| str.length == alphabet_substr.last.length }
longest.shift
end
def find_substr(str)
substr_arr = []
idx = 0
loop do
substr_arr << (idx...str.length).map { |sub_length| str[idx..sub_length] }
idx += 1
break if idx == str.length
end
substr_arr.flatten!
end
| true
|
d4807c43af7b05312513eaa2e197b74ecfff2987
|
Ruby
|
brandonrandall/jungle_beat
|
/lib/jungle_beat.rb
|
UTF-8
| 372
| 3.203125
| 3
|
[] |
no_license
|
require './lib/linked_list'
class JungleBeat
attr_reader :list
def initialize
@list = LinkedList.new
end
def append(words)
# binding.pry
appended = words.split.each do |word|
@list.append(word)
end
final = appended.join(" ")
end
def count
@list.count
end
def play
`say -r 500 -v Boing #{@list.to_string}`
end
end
| true
|
362e4644c42e009be369e9566280d27e4efa6e36
|
Ruby
|
Talbatross/18xx
|
/lib/engine/share_price.rb
|
UTF-8
| 2,105
| 2.875
| 3
|
[
"MIT",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
# frozen_string_literal: true
module Engine
class SharePrice
attr_reader :coordinates, :price, :color, :corporations, :can_par, :type
def self.from_code(code, row, column, unlimited_colors, multiple_buy_colors: [])
return nil if !code || code == ''
price = code.scan(/\d/).join('').to_i
color, type =
case code
when /p/
%i[red par]
when /e/
%i[blue endgame]
when /c/
%i[black close]
when /b/
%i[brown multiple_buy]
when /o/
%i[orange unlimited]
when /y/
%i[yellow no_cert_limit]
when /l/
%i[red liquidation]
when /a/
%i[gray acquisition]
end
SharePrice.new([row, column],
price: price,
color: color,
type: type,
unlimited_colors: unlimited_colors,
multiple_buy_colors: multiple_buy_colors)
end
def initialize(coordinates,
price:,
color: nil,
type: nil,
unlimited_colors: [],
multiple_buy_colors: [])
@coordinates = coordinates
@price = price
@color = color
@type = type
@corporations = []
@unlimited_colors = unlimited_colors
@multiple_buy_colors = multiple_buy_colors
end
def id
"#{@price},#{@coordinates.join(',')}"
end
def counts_for_limit
!@unlimited_colors.include?(@color)
end
def buy_multiple?
@multiple_buy_colors.include?(@color)
end
def to_s
"#{self.class.name} - #{@price} #{@coordinates}"
end
def can_par?
@type == :par
end
def end_game_trigger?
@type == :endgame
end
def liquidation?
@type == :liquidation
end
def acquisition?
@type == :acquisition
end
def normal_movement?
# Can be moved into normally, rather than something custom such as not owning a train.
@type != :liquidation
end
end
end
| true
|
a8453014309f9966e62bb1d5197d3609e78dff15
|
Ruby
|
daydreamboy/HelloRuby
|
/ruby_tool/AbstractInterface2.rb
|
UTF-8
| 984
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
##
# Provide an abstract module to define an interface
#
# @see https://metabates.com/2011/02/07/building-interfaces-and-abstract-classes-in-ruby/
module AbstractInterface
class InterfaceNotImplementedError < NoMethodError
end
def self.included(clz)
clz.send(:include, AbstractInterface::Methods)
clz.send(:extend, AbstractInterface::Methods)
clz.send(:extend, AbstractInterface::ClassMethods)
end
module Methods
def api_not_implemented(instance, method_name = nil)
if method_name.nil?
caller.first.match(/in \`(.+)\'/)
method_name = $1
end
raise AbstractInterface::InterfaceNotImplementedError.new("#{instance.class.name} needs to implement '#{method_name}' for interface #{self.name}!")
end
end
module ClassMethods
def needs_implementation(clz, name, *args)
self.class_eval do
define_method(name) do |*args|
clz.api_not_implemented(self, name)
end
end
end
end
end
| true
|
bfd28fc4e2ea255f15ca5cfa5a8188940be68512
|
Ruby
|
TheODI-UD2D/sir_handel
|
/spec/helpers_spec.rb
|
UTF-8
| 8,264
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
module SirHandel
describe Helpers do
let(:helpers) { TestHelpers.new }
it 'returns straight away if rack env is test' do
expect(ENV).to receive(:[]).with('RACK_ENV').and_return('test')
expect(helpers.protected!).to eq(nil)
end
it 'returns nil if authorized is true' do
expect(ENV).to receive(:[]).with('RACK_ENV').and_return('production')
expect(helpers).to receive(:authorized?).and_return(true)
expect(helpers.protected!).to eq(nil)
end
it 'authorises correctly' do
user = 'bort'
password = 'malk'
base64 = Base64.encode64("#{user}:#{password}")
expect(ENV).to receive(:[]).with('TUBE_USERNAME').and_return(user)
expect(ENV).to receive(:[]).with('TUBE_PASSWORD').and_return(password)
expect(helpers).to receive(:env).and_return({
'HTTP_AUTHORIZATION' => "Basic #{base64}\n",
})
expect(helpers.authorized?).to eq(true)
end
context 'round_up' do
it 'rounds up dates' do
(1..23).each do |h|
date = DateTime.parse("2015-08-28T#{"%02d" % h}:00:00+00:00")
expect(helpers.round_up(date)).to eq(DateTime.parse('2015-08-29T00:00:00+00:00'))
end
end
it 'rounds up dates with odd minutes and seconds' do
(1..23).each do |h|
date = DateTime.parse("2015-08-28T#{"%02d" % h}:#{rand(59) % h}:#{rand(59) % h}+00:00")
expect(helpers.round_up(date)).to eq(DateTime.parse('2015-08-29T00:00:00+00:00'))
end
end
it 'leaves midnight untouched' do
date = DateTime.parse("2015-08-28T00:00:00+00:00")
expect(helpers.round_up(date)).to eq(date)
end
end
it 'parameterizing signal names' do
expect(helpers.db_signal 'signal-1').to eq('signal_1')
expect(helpers.web_signal 'signal_1').to eq('signal-1')
end
it 'generates signal urls' do
url = helpers.signal_path('actual_motor_power', :json)
expect(url).to eq('/signals/actual-motor-power.json')
end
it 'generates group urls' do
url = helpers.group_path('my_awesome_group', :json)
expect(url).to eq('/groups/my-awesome-group.json')
end
it 'gets the correct direction' do
expect(helpers.get_direction 137).to eq('southbound')
expect(helpers.get_direction 152).to eq('northbound')
end
it 'gets the correct station' do
{
'walthamstow_central' => [
99,
10
],
'blackhorse_road' => [
161,
104
],
'tottenham_hale' => [
217,
182
],
'seven_sisters' => [
345,
456
],
'finsbury_park' => [
921,
842
],
'highbury_and_islington' => [
1105,
1010
],
'kings_cross_st_pancras' => [
1285,
1146
],
'euston' => [
1321,
1210
],
'warren_street' => [
1427,
1342
],
'oxford_circus' => [
1491,
1416
],
'green_park' => [
1573,
1480
],
'victoria' => [
1677,
1578
],
'pimlico' => [
1785,
1750
],
'vauxhall' => [
1833,
1782
],
'stockwell' => [
1911,
1888
],
'brixton' => [
2031,
1960
]
}.each do |k,v|
expect(helpers.get_station v.first).to eq(k)
expect(helpers.get_station v.last).to eq(k)
end
end
context('heatmap') do
it 'gets a heatmap', :vcr do
date = '2015-12-11T17:10:00Z'
expect(helpers.heatmap(date)).to eq([
{:segment=>1880, :station=>"stockwell", :direction=>"northbound", :load=>24.693536979882015},
{:segment=>1964, :station=>"brixton", :direction=>"northbound", :load=>17.095417370699824},
{:segment=>1992, :station=>nil, :direction=>"northbound", :load=>18.329726308058518},
{:segment=>1917, :station=>"stockwell", :direction=>"southbound", :load=>24.366488606437073},
{:segment=>1873, :station=>"vauxhall", :direction=>"southbound", :load=>28.98719850867903},
{:segment=>1785, :station=>"pimlico", :direction=>"southbound", :load=>36.73602159776647},
{:segment=>1681, :station=>"victoria", :direction=>"southbound", :load=>56.06988627133098},
{:segment=>1547, :station=>"green_park", :direction=>"southbound", :load=>56.56282629450064},
{:segment=>1475, :station=>"oxford_circus", :direction=>"southbound", :load=>56.538939424921395},
{:segment=>1385, :station=>"warren_street", :direction=>"southbound", :load=>48.57996416533404},
{:segment=>1309, :station=>"kings_cross_st_pancras", :direction=>"southbound", :load=>38.07107592136177},
{:segment=>1125, :station=>"highbury_and_islington", :direction=>"southbound", :load=>32.11768913273878},
{:segment=>1019, :station=>"finsbury_park", :direction=>"southbound", :load=>33.125},
{:segment=>893, :station=>"seven_sisters", :direction=>"southbound", :load=>28.536587980535902},
{:segment=>281, :station=>"tottenham_hale", :direction=>"southbound", :load=>21.004141865079365},
{:segment=>195, :station=>"blackhorse_road", :direction=>"southbound", :load=>21.567191324113722},
{:segment=>111, :station=>"walthamstow_central", :direction=>"southbound", :load=>22.165366806091015},
{:segment=>37, :station=>nil, :direction=>"southbound", :load=>10.715567765567766},
{:segment=>140, :station=>"tottenham_hale", :direction=>"northbound", :load=>43.709910864677596},
{:segment=>492, :station=>"finsbury_park", :direction=>"northbound", :load=>52.43755024477124},
{:segment=>902, :station=>"highbury_and_islington", :direction=>"northbound", :load=>58.4012182147943},
{:segment=>1026, :station=>"kings_cross_st_pancras", :direction=>"northbound", :load=>63.339533032226825},
{:segment=>1286, :station=>"warren_street", :direction=>"northbound", :load=>74.67550085210414},
{:segment=>1412, :station=>"oxford_circus", :direction=>"northbound", :load=>69.93843811024149},
{:segment=>1492, :station=>"green_park", :direction=>"northbound", :load=>64.38442669056744},
{:segment=>1610, :station=>"victoria", :direction=>"northbound", :load=>45.8240911034118},
{:segment=>1766, :station=>"vauxhall", :direction=>"northbound", :load=>29.731479498880667}
])
end
end
context 'date_step' do
let(:from) { DateTime.parse("2015-09-23T09:00:00") }
let(:to) { DateTime.parse("2015-09-23T09:30:00") }
it 'gets a default date step' do
range = helpers.date_step(from, to)
expect(range).to eq([
DateTime.parse("2015-09-23T09:00:00"),
DateTime.parse("2015-09-23T09:05:00"),
DateTime.parse("2015-09-23T09:10:00"),
DateTime.parse("2015-09-23T09:15:00"),
DateTime.parse("2015-09-23T09:20:00"),
DateTime.parse("2015-09-23T09:25:00"),
DateTime.parse("2015-09-23T09:30:00")
])
end
it 'gets a date step every 10 minutes' do
range = helpers.date_step(from, to, 10)
expect(range).to eq([
DateTime.parse("2015-09-23T09:00:00"),
DateTime.parse("2015-09-23T09:10:00"),
DateTime.parse("2015-09-23T09:20:00"),
DateTime.parse("2015-09-23T09:30:00")
])
end
end
context 'generating urls' do
it 'generates a url with an interval' do
url = helpers.signal_url('my-cool-signal', '2015-09-23T09:00:00', '2015-09-23T10:00:00', '5s', 'csv')
expect(url).to eq('/signals/my-cool-signal/2015-09-23T09:00:00/2015-09-23T10:00:00.csv?interval=5s')
end
it 'generates a url without an interval' do
url = helpers.signal_url('my-cool-signal', '2015-09-23T09:00:00', '2015-09-23T10:00:00', nil, 'csv')
expect(url).to eq('/signals/my-cool-signal/2015-09-23T09:00:00/2015-09-23T10:00:00.csv')
end
end
end
end
| true
|
5222259b2b3d60f38b94765692bd468882458227
|
Ruby
|
robertkchang/receipt
|
/lib/shopping.rb
|
UTF-8
| 540
| 3.28125
| 3
|
[
"MIT"
] |
permissive
|
require_relative 'receipt'
require_relative 'shopping_cart'
#
# Interactively accepts one or more item,
# calculates the sales tax and total,
# and displays the itemized receipt
#
class Shopping
########
# Main #
########
input_list = []
begin
puts 'Enter an item (<ENTER> on empty line to quit):'
input = gets.chomp
input_list << input unless input.to_s.empty?
end until input.to_s.empty?
begin
(Receipt.new ShoppingCart.new input_list).calculate.print
rescue
puts "Error: #{$!}"
end
end
| true
|
7b9c8cad77ab8572d3ee8e2ebba9e851841c91f4
|
Ruby
|
kldgarrido/command_line
|
/model.rb
|
UTF-8
| 277
| 3.328125
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
class Quiz
include Comparable
attr_reader :question, :answer
def initialize(question, answer)
@question = question
@answer = answer
end
def <=>(anOther)
@question <=> anOther.question
@answer <=> anOther.answer
end
end
| true
|
159440d634e5ac9be5b47e1eac7d0ad5c6b60d8d
|
Ruby
|
vdepetigny/THPTwitter
|
/stream.rb
|
UTF-8
| 1,226
| 2.546875
| 3
|
[] |
no_license
|
# ligne très importante qui appelle la gem.
require 'twitter'
# n'oublie pas les lignes pour Dotenv ici…
require 'dotenv'
Dotenv.load
# quelques lignes qui appellent les clés d'API de ton fichier .env
def streaming_twitter
client_stream = Twitter::Streaming::Client.new do |config|
config.consumer_key = ENV["TWITTER_CONSUMER_KEY"]
config.consumer_secret = ENV["TWITTER_CONSUMER_SECRET"]
config.access_token = ENV["TWITTER_ACCESS_TOKEN"]
config.access_token_secret = ENV["TWITTER_ACCESS_TOKEN_SECRET"]
end
return client_stream
end
def login_twitter
client = Twitter::REST::Client.new do |config|
config.consumer_key = ENV["TWITTER_CONSUMER_KEY"]
config.consumer_secret = ENV["TWITTER_CONSUMER_SECRET"]
config.access_token = ENV["TWITTER_ACCESS_TOKEN"]
config.access_token_secret = ENV["TWITTER_ACCESS_TOKEN_SECRET"]
end
return client
end
def like_follow_live
streaming_twitter.filter(track: "hello"){|object| puts object.text if object.is_a?(Twitter::Tweet)}
end
# client = streaming_twitter
# topics = ["bonjour", "bonjour_monde"]
# puts topics
# client.filter(track: topics.join(",")) do |tweet|
# puts tweet.text
# end
# end
like_follow_live
| true
|
9f13fdf3239ee03514c20b9e321b379ee6570ca8
|
Ruby
|
robyparr/adjourn
|
/app/helpers/meetings_helper.rb
|
UTF-8
| 1,021
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
# typed: true
module MeetingsHelper
def recent_meetings(meetings)
meetings.select { |it| it.recent? }
end
def upcoming_meetings(meetings)
meetings
.select { |it| it.upcoming? }
.sort_by { |it| it.start_date }
end
def display_recent_and_upcoming_meetings_section?(page)
page.nil? || page.to_i == 1
end
def meetings_list(meetings, page)
return meetings unless display_recent_and_upcoming_meetings_section?(page)
neither_upcoming_nor_recent_meetings(meetings)
end
def neither_upcoming_nor_recent_meetings(meetings)
meetings.select { |it| !it.upcoming? && !it.recent? }
end
def upcoming_meeting_item_classes(meeting)
html_class = "collection-item"
html_class += " green lighten-4" if meeting.in_progress?
html_class
end
def when_in_words(meeting)
return "Now" if meeting.in_progress?
if meeting.upcoming?
"in #{time_ago_in_words(meeting.start_date)}"
else
"#{time_ago_in_words(meeting.end_date)} ago"
end
end
end
| true
|
7bc2d153aa384c11027496dc034876a041b1550f
|
Ruby
|
haracane/kajax
|
/lib/mysql_util.rb
|
UTF-8
| 1,110
| 2.515625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
dirpath = File.expand_path(File.dirname(__FILE__))
$:.push(dirpath)
require 'rubygems'
require 'mysql'
module MysqlUtil
def self.get_option_hash(psql_option)
psql_option_list=psql_option.split(/\s+/)
ret = {}
ret[:db_host]='localhost'
ret[:db_port]=3306
ret[:db_name]='db'
ret[:db_user]='postgres'
ret[:db_password]=''
while 0 < psql_option_list.size do
val = psql_option_list.shift
case val
when '-h'
ret[:db_host] = psql_option_list.shift
when '-P'
ret[:db_port] = psql_option_list.shift.to_i
when '-u'
ret[:db_user] = psql_option_list.shift
when '-p'
ret[:db_password] = psql_option_list.shift
when '-D'
ret[:db_name] = psql_option_list.shift
else
if val =~ /--password=/ then
ret[:db_password] = $'
end
end
end
return ret
end
def self.get_connection_from_option(psql_option)
ret = self.get_option_hash(psql_option)
return Mysql::connect(ret[:db_host], ret[:db_user], ret[:db_password], ret[:db_name], ret[:db_port])
end
end
| true
|
4f802c8d4997ecbe1b1e459317982d9bb8ceb5a6
|
Ruby
|
giannioneill/myexp-meandre
|
/lib/file_types_handler.rb
|
UTF-8
| 1,895
| 2.75
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"MIT"
] |
permissive
|
# myExperiment: lib/file_types_handler.rb
#
# Copyright (c) 2008 University of Manchester and the University of Southampton.
# See license.txt for details.
# Helper class to deal with File types and processors.
# Based on the WorkflowTypesHandler
class FileTypesHandler
# Gets all the workflow processor classes that have been defined in the \lib\file_processors directory.
# Note: for performance reasons this is a "load once" method and thus requires a server restart if new processor classes are added.
def self.processor_classes
if @@processor_classes.nil?
@@processor_classes = [ ]
ObjectSpace.each_object(Class) do |c|
if c < FileProcessors::Interface
@@processor_classes << c
end
end
end
return @@processor_classes
end
def self.for_mime_type(type)
if @@mime_type_map.nil?
@@mime_type_map = {}
processor_classes.each do |c|
@@mime_type_map[c.mime_type] = [] if @@mime_type_map[c.mime_type].nil?
@@mime_type_map[c.mime_type] << c
end
end
@@mime_type_map[type]
end
def self.for_file(type, file_data)
self.for_mime_type(type).each do |c|
return c if c.recognises_file?(file_data)
end
end
protected
# List of all the processor classes available.
@@processor_classes = nil
@@mime_type_map = nil
end
# We need to first retrieve all classes in the workflow_processors directory
# so that they are then accessible via the ObjectSpace.
# We assume (and this is a rails convention for anything in the /lib/ directory),
# that filenames for example "my_class.rb" correspond to class names for example MyClass.
Dir.chdir(File.join(RAILS_ROOT, "lib/file_processors")) do
Dir.glob("*.rb").each do |f|
("file_processors/" + f.gsub(/.rb/, '')).camelize.constantize
end
end
| true
|
869ab230e88e847326710e034b1dc01a56996d42
|
Ruby
|
krisswiltshire30/Bank-ruby
|
/spec/unit/account_spec.rb
|
UTF-8
| 867
| 2.796875
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require './lib/account.rb'
RSpec.describe Account do
describe 'Deposit' do
it 'Should return a string containing how much has been deposited' do
expect(subject.deposit(50)).to eq('£50 deposited into your to account')
end
end
describe 'Withdraw' do
it 'Should return a string containing how much has been deposited' do
subject.deposit(50)
expect(subject.withdraw(20)).to eq('£20 withdrawn from your account')
end
end
describe 'Bank Statement' do
it 'Should return a bank statment' do
Timecop.freeze(Time.local(2019, 9, 13))
subject.deposit(50)
expect { subject.bank_statement }
.to output("date || credit || debit || balance\n13/09/19 || 50.00 || || 50.00\n").to_stdout
expect(subject.bank_statement).to include('Statement printed')
end
end
end
| true
|
4c03395f221a7ba5ef41894495dc71cb484ca2cd
|
Ruby
|
gjanee/advent-of-code-2015
|
/11.rb
|
UTF-8
| 2,299
| 4.03125
| 4
|
[] |
no_license
|
# --- Day 11: Corporate Policy ---
#
# Santa's previous password expired, and he needs help choosing a new
# one.
#
# To help him remember his new password after the old one expires,
# Santa has devised a method of coming up with a password based on the
# previous one. Corporate policy dictates that passwords must be
# exactly eight lowercase letters (for security reasons), so he finds
# his new password by incrementing his old password string repeatedly
# until it is valid.
#
# Incrementing is just like counting with numbers: xx, xy, xz, ya, yb,
# and so on. Increase the rightmost letter one step; if it was z, it
# wraps around to a, and repeat with the next letter to the left until
# one doesn't wrap around.
#
# Unfortunately for Santa, a new Security-Elf recently started, and he
# has imposed some additional password requirements:
#
# - Passwords must include one increasing straight of at least three
# letters, like abc, bcd, cde, and so on, up to xyz. They cannot
# skip letters; abd doesn't count.
# - Passwords may not contain the letters i, o, or l, as these letters
# can be mistaken for other characters and are therefore confusing.
# - Passwords must contain at least two different, non-overlapping
# pairs of letters, like aa, bb, or zz.
#
# For example:
#
# - hijklmmn meets the first requirement (because it contains the
# straight hij) but fails the second requirement (because it
# contains i and l).
# - abbceffg meets the third requirement (because it repeats bb and
# ff) but fails the first requirement.
# - abbcegjk fails the third requirement, because it only has one
# double letter (bb).
# - The next password after abcdefgh is abcdffaa.
# - The next password after ghijklmn is ghjaabcc, because you
# eventually skip all the passwords that start with ghi..., since i
# is not allowed.
#
# Given Santa's current password (your puzzle input), what should his
# next password be?
Input = "cqjxjnds"
def next_password(s)
while true
s = s.succ
break if s =~ /abc|bcd|cde|def|efg|fgh|pqr|qrs|stu|tuv|uvw|wxy|xyz/ &&
s !~ /i|o|l/ &&
s =~ /((.)\2).*(?!\1)(.)\3/
end
s
end
s = next_password(Input)
puts s
# --- Part Two ---
#
# Santa's password expired again. What's the next one?
puts next_password(s)
| true
|
dda815dce242679fc99b31c4b00a0fc3e11828ed
|
Ruby
|
skuhlmann/sales_engine
|
/lib/merchant_repository.rb
|
UTF-8
| 1,740
| 3.046875
| 3
|
[] |
no_license
|
require_relative 'merchants_parser'
require_relative 'merchants'
class MerchantRepository
attr_reader :merchants, :sales_engine
def initialize(file_path, sales_engine)
@merchants = MerchantsParser.new(file_path).all(self)
@sales_engine = sales_engine
end
def all
merchants
end
def random
merchants.sample
end
def find_by(attribute, value)
merchants.find {|merchant| merchant.send(attribute.to_sym) == value}
end
def find_all_by(attribute, value)
merchants.find_all {|merchant| merchant.send(attribute.to_sym) == value}
end
def find_by_id(value); find_by(:id, value) end
def find_by_created_at(value); find_by(:created_at, value) end
def find_by_updated_at(value); find_by(:updated_at, value) end
def find_all_by_id(value); find_all_by(:id, value) end
def find_all_by_created_at(value); find_all_by(:created_at, value) end
def find_all_by_updated_at(value); find_all_by(:updated_at, value) end
def find_by_name(value)
merchants.find {|merchant| merchant.name.downcase == value.downcase}
end
def find_all_by_name(value)
merchants.find_all {|merchant| merchant.name.downcase == value.downcase}
end
def find_items_for(id)
sales_engine.find_items_by_merchant(id)
end
def find_invoices_for(id)
sales_engine.find_invoices_by_merchant(id)
end
def find_customer_with_pending_invoices(customer_id)
sales_engine.find_customers_with_pending_invoices(customer_id)
end
def most_items(x)
merchants.sort_by(&:items_sold).reverse.take(x)
end
def revenue(date)
revenues = merchants.map {|merchant| merchant.revenue(date)}.reduce(:+)
end
def most_revenue(x)
merchants.sort_by(&:revenue).reverse.take(x)
end
def inspect
"#<#{self.class} #{@merchants.size} rows>"
end
end
| true
|
0506f1ae4390aef443f51737ec1cd833f5c3d5b5
|
Ruby
|
bainezydave/gentech-ruby
|
/day_10/error.rb
|
UTF-8
| 272
| 3.859375
| 4
|
[] |
no_license
|
system "clear"
begin
puts "Enter a number"
num1 = gets.chomp.to_i
puts "Enter another number"
num2 = gets.chomp.to_i
puts "The division of 2 numbers is #{num1/num2}"
rescue
loop do
puts "The second number should not be 0"
end
end
| true
|
25c46170404307e81633fde1c64842891965309d
|
Ruby
|
dball1126/W2D2
|
/chess/game.rb
|
UTF-8
| 384
| 2.875
| 3
|
[] |
no_license
|
require_relative "board"
require_relative "display"
require_relative "player"
class Game
def initialize
@board = board
@display = display
@players = Hash.new{ |h, k| h[k] = nil }
@current_player = #symbol or player
end
def play
end
private
def notify_players
end
def swap_turn!
end
end
| true
|
6d385123ad5869f4c806b04b48d59b56f405606d
|
Ruby
|
judywu29/ruby_pj
|
/envato_algorigthms/binary_search.rb
|
UTF-8
| 341
| 3.6875
| 4
|
[] |
no_license
|
#O(logN)
def bsearch(arr, key)
min = 0; max = arr.size-1;
while min <= max
mid = min + (max - min) / 2 #plus min!!!!!!!!!!!!
return mid if key == arr[mid]
key < arr[mid] ? max = mid - 1 : min = mid + 1
end
return -1
end
ar = [23, 45, 67, 89, 123, 568]
p bsearch(ar, 23) #0
p bsearch(ar, 123) #4
p bsearch(ar, 120) #-1
| true
|
690b60b1e4de36b52c07995cf9dbf0438092778e
|
Ruby
|
Jwarholic/GiphyQuotes
|
/app/models/quote.rb
|
UTF-8
| 1,110
| 2.5625
| 3
|
[] |
no_license
|
module Quote
#Hides API Key
KEY = ENV['QUOTES']
#Quote API
def self.quote(word)
uri = URI.parse("http://quotes.rest/quote.json?category=#{word}")
request = Net::HTTP::Get.new(uri)
request["X-Theysaidso-Api-Secret"] = KEY
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
http.request(request)
end
end
end
#API Notes
# uri = URI.parse("http://quotes.rest/quote/categories.json?start=10000")
# uri = URI.parse("http://quotes.rest/qod.json?category=management")
# request = Net::HTTP::Get.new(uri)
# request["X-Theysaidso-Api-Secret"] = "api key"
# response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
# http.request(request)
# end
#IF A QUOTE IS FOUND THIS IS THE WAY TO GRAB THE TEXT.
# conversion = JSON.parse(response.body)
# puts conversion["contents"]["quotes"][0]["quote"]
#ELSE
#SEND NO CATEGORY FOUND TO USER
#send back no results found to the user.
#conversion["contents"]["quotes"].nil?
#10 RESPONSES
#academics
#adaptation
#afraid
#alive
#cautious
#celebrate
#embarrassing
#emotional
| true
|
e94d4f76a60dcd0ced381a4ee56d1f10143dfcf7
|
Ruby
|
samworrall/Oystercard2
|
/lib/oystercard.rb
|
UTF-8
| 684
| 3.453125
| 3
|
[] |
no_license
|
class Oystercard
attr_reader :balance, :entry_station, :journeys
LIMIT = 90
MINIMUM_FARE = 1
def initialize
@balance = 0
@journeys = []
end
def top_up(value)
raise "Maximum limit of £#{LIMIT} exceeded" if @balance + value > LIMIT
@balance += value
end
def touch_in(station)
fail "Insufficient funds" if @balance < MINIMUM_FARE
@entry_station = station
end
def touch_out(station)
deduct(MINIMUM_FARE)
journeys << {@entry_station => station}
@entry_station = nil
end
def in_journey?
@entry_station != nil
end
private
def deduct(value)
raise "Invalid amount" if value < 0
@balance -= value
end
end
| true
|
e76348428f7386bf0888281bd556cd7d8b4f7950
|
Ruby
|
RafaelCostta13/ExerciciosEmRuby
|
/04 - Capítulo/Exercícios Resolvidos/01 - Exercicio.rb
|
UTF-8
| 1,364
| 3.875
| 4
|
[] |
no_license
|
=begin
01 - A nota final de um estudante é calculada a partir de três notas atribuídas, respectivamente,
a um trabalho de laboratório, a uma avaliação semestral e a um exame final. A média das três notas mencionadas
obedece aos pesos a seguir:
Nota PESO
Trabalho de laboratório 2
Avaliação semestral 3
Exame final 5
Faça um programa que receba as três notas, calcule e mostre a média ponderada e o conceito que segue
a tabela:
MÉDIA CONTEITO
8 - 10 A
7 - 8 B
6 - 7 C
5 - 6 D
0 - 5 E
=end
PESO_TRABALHO = 2
PESO_AV_SEMESTRAL = 3
PESO_EXAME = 5
puts "Informe a nota do trabalho de labortório :"
nota_trab_lab = gets.to_f
puts "Informe a nota da aviação semestral :"
nota_sem = gets.to_f
puts "Informe a nota do exame final :"
nota_sem = gets.to_f
soma_peso = PESO_TRABALHO + PESO_AV_SEMESTRAL + PESO_EXAME
media = ((nota_trab_lab * PESO_TRABALHO) + (nota_sem * PESO_AV_SEMESTRAL) + (nota_sem * PESO_EXAME)) / soma_peso
if media > 8
puts "A media foi #{media} e o conceito foi A"
elsif media > 7 && media <= 8
puts "A media foi #{media} e o conceito foi B"
elsif media > 6 && meida <= 7
puts "A media foi #{media} e o conceito foi C"
elsif media > 5 && media <= 6
puts "A media foi #{media} e o conceito foi D"
else
puts "A media foi #{media} e o conceito foi E"
end
| true
|
2035bc624934894cc105205c3c113ff3f61bce9a
|
Ruby
|
sallartiste/ruby
|
/eath-2/classes/animaux.rb
|
UTF-8
| 367
| 4.09375
| 4
|
[] |
no_license
|
class Animal
def set_parole(parole)
@parole = parole
end
def get_parole
return @parole
end
def set_age(age)
@age = age
end
def get_age
return @age
end
end
cochon = Animal.new
cochon.set_parole("groin, groin!")
cochon.set_age(12)
puts "Le cochon font: #{cochon.get_parole} lorsqu'ils ont #{cochon.get_age}"
| true
|
44c88bf6097096f48c07de02b389255c1928b547
|
Ruby
|
sans-pulp/ar-exercises
|
/exercises/exercise_5.rb
|
UTF-8
| 595
| 3.21875
| 3
|
[] |
no_license
|
require_relative '../setup'
require_relative './exercise_1'
require_relative './exercise_2'
require_relative './exercise_3'
require_relative './exercise_4'
puts "Exercise 5"
puts "----------"
# Your code goes here ...
#Total revenue for all stores
@total_revenue = Store.sum("annual_revenue")
puts "Total Revenue: #{@total_revenue}"
@average_revenue = Store.average("annual_revenue").truncate(2).to_s('F')
puts "Average Store Revenue: #{@average_revenue}"
@high_revenue_stores = Store.where("annual_revenue > 1000000")
puts "Number of stores earning > $1M/year: #{@high_revenue_stores.count}"
| true
|
8edda100b67db53797a84fa317534cae4787144d
|
Ruby
|
daveguymon/Learn-Ruby-Hard-Way
|
/ex11a.rb
|
UTF-8
| 241
| 3.5625
| 4
|
[] |
no_license
|
print "What is your name? "
name = gets.chomp
print "What is your quest? "
quest = gets
print "What is the wind velocity of a sparrow?"
velocity = gets.chomp
puts "Your name is #{name}. Your quest is #{quest}. The velocity is #{velocity}."
| true
|
50cfdf7a2f3e75b039f7b6e309df5c3bf9e9f001
|
Ruby
|
ThriveADRIAN/mars_rover
|
/mars_rover.rb
|
UTF-8
| 2,674
| 3.765625
| 4
|
[] |
no_license
|
class MarsRover
# constructor method
def initialize
@x_up_right
@y_up_right
@x_coord
@y_coord
@heading
end
# instance methods
def read_instruction_line(file,split_char)
line = file.readline
line = line.chomp!
line = line.split(split_char)
end
def set_up_right_coordinates(line_reader)
@x_up_right = line_reader[0]
@y_up_right = line_reader[1]
end
# read first line for Top Right Coordinates
def handle_top_right_coords_instruction(file)
line_reader = self.read_instruction_line(file, " ")
self.set_up_right_coordinates(line_reader)
end
def set_rover_start_coordinates(line_reader)
@x_coord = line_reader[0].to_i
@y_coord = line_reader[1].to_i
@heading = line_reader[2]
end
# read line for Rover Position
def handle_rover_position_instruction(file)
line_reader = self.read_instruction_line(file, " ")
self.set_rover_start_coordinates(line_reader)
end
# If spin_direction is left then left_spin_heading value will be evaluated
# or if spin_direction is right then right_spin_heading will evaluated
# i.e. Left Turn from N or Right Turn from S results in W
def evaluate_spin(spin_direction,left_spin_heading, right_spin_heading)
@heading == left_spin_heading && spin_direction == "left" ||
@heading == right_spin_heading && spin_direction == "right"
end
def spin(direction)
if self.evaluate_spin(direction,"N","S")
@heading = "W"
elsif self.evaluate_spin(direction,"W","E")
@heading = "S"
elsif self.evaluate_spin(direction,"S","N")
@heading = "E"
elsif self.evaluate_spin(direction,"E","W")
@heading = "N"
end
end
def move_forward
if @heading == "E"
@x_coord += 1
elsif @heading == "N"
@y_coord += 1
elsif @heading == "W"
@x_coord -= 1
elsif @heading == "S"
@y_coord -= 1
end
end
def parse_instructions(instruction_set)
instruction_set.each do |i|
if i == "L"
self.spin("left")
elsif i == "R"
self.spin("right")
elsif i == "M"
self.move_forward
end
end
end
def output_rover_coordinates
puts @x_coord.to_s + " " + @y_coord.to_s + " " + @heading
end
# read line for Rover Instructions and Update Rover Position
def handle_rover_move_instructions(file)
line_reader = self.read_instruction_line(file, "")
self.parse_instructions(line_reader)
self.output_rover_coordinates
end
def handle_instruction_file(file)
self.handle_top_right_coords_instruction(file)
while !file.eof?
self.handle_rover_position_instruction(file)
self.handle_rover_move_instructions(file)
end
end
end
my_rover = MarsRover.new
file = File.open("mars_rover_input.txt", 'r')
my_rover.handle_instruction_file(file)
file.close
| true
|
39b221202318d62545164ed2e1e2a5b5ab865f7c
|
Ruby
|
yhuang/ruby_lessons
|
/08_pig_latin/pig_latin_translator.rb
|
UTF-8
| 482
| 3.1875
| 3
|
[] |
no_license
|
module PigLatinTranslator
def translate_word(word)
reg_exp = Regexp.new(/(qu|[^aeiouy]*)([aeiouy]+\w*)/)
match_data = reg_exp.match(word)
if match_data.nil?
return ''
elsif match_data[1].nil?
return match_data[2] + 'ay'
else
return match_data[2] + match_data[1] + 'ay'
end
end
def translate(msg)
words_array = []
msg.split(/ /).each do |w|
words_array << translate_word(w)
end
words_array.join(" ")
end
end
| true
|
4971c683d9dd32dd8739c410c85190dff64849d2
|
Ruby
|
SebEchegaray/planets
|
/controllers/planets_controller.rb
|
UTF-8
| 1,195
| 2.578125
| 3
|
[] |
no_license
|
get '/info' do
planets = all_planets()
erb :'info/index', locals: { planet: planets }
end
get '/info/add' do
erb :'info/new', locals: { edit: false }
end
post '/info' do
name = params[:name]
diameter = params[:diameter]
distance = params[:distance]
mass = params[:mass]
moon_count = params[:moon_count]
image_url = params[:image_url]
create_planet(name, diameter, distance, mass, moon_count, image_url)
redirect '/'
end
# Display individual planet
get '/info/:id' do |id|
planet = db_actions("SELECT * FROM planets WHERE id = #{id}")
erb :'info/show', locals: { edit: true, info: planet[0] }
end
# Update individual planet
get '/info/:id/edit'do |id|
planet = db_actions("SELECT * FROM planets WHERE id = #{id}")
erb :'info/new', locals: { edit: true, info: planet[0] }
end
put '/info/:id/add' do |id|
name = params[:name]
diameter = params[:diameter]
distance = params[:distance]
mass = params[:mass]
moon_count = params[:moon_count]
image_url = params[:image_url]
update_planet(name, diameter, distance, mass, moon_count, image_url, id)
redirect "/info/#{id}"
end
delete '/info/:id/delete' do |id|
delete_planet(id)
redirect '/'
end
| true
|
5ff232f444f6317147f4eb1ceaa73c9c86719f7e
|
Ruby
|
sergeynakul/thinknetica2019
|
/Lesson2/shop_cart.rb
|
UTF-8
| 544
| 3.578125
| 4
|
[] |
no_license
|
shop_cart = {}
loop do
print "Введите название товара: "
item = gets.chomp
break if item == "стоп"
print "Введите стоимость товара: "
price = gets.to_f
print "Введите кол-во купленного товара: "
quantity = gets.to_f
shop_cart[item] = { price: price, quantity: quantity, amount: price * quantity }
end
total_price = shop_cart.sum{ |price:, quantity:, amount:| amount }
puts shop_cart
puts "Общая сумма покупок: #{total_price}"
| true
|
1dfa9622ece982c8f8015cd09d6a3cefb104a70d
|
Ruby
|
plastictrophy/viddl-rb
|
/lib/viddl-rb.rb
|
UTF-8
| 2,436
| 2.640625
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
$LOAD_PATH << File.join(File.dirname(__FILE__), '..', 'helper')
require "rubygems"
require "nokogiri"
require "mechanize"
require "cgi"
require "open-uri"
require "stringio"
require "download-helper.rb"
require "plugin-helper.rb"
#require all plugins
Dir[File.join(File.dirname(__FILE__),"../plugins/*.rb")].each { |p| require p }
module ViddlRb
class PluginError < StandardError; end
def self.io=(io_object)
PluginBase.io = io_object
end
#set the default PluginBase io objec to a StringIO instance.
#this will suppress any standard output from the plugins.
self.io = StringIO.new
#returns an array of hashes containing the download url(s) and filenames(s)
#for the specified video url.
#if the url does not match any plugin, return nil and if a plugin
#throws an error, throw PluginError.
#the reason for returning an array is because some urls will give multiple
#download urls (for example a Youtube playlist url).
def self.get_urls_and_filenames(url)
plugin = PluginBase.registered_plugins.find { |p| p.matches_provider?(url) }
if plugin
begin
#we'll end up with an array of hashes with they keys :url and :name
urls_filenames = plugin.get_urls_and_filenames(url)
rescue StandardError => e
message = plugin_error_message(plugin, e.message)
raise PluginError, message
end
urls_filenames
else
nil
end
end
#returns an array of download urls for the given video url.
def self.get_urls(url)
urls_filenames = get_urls_and_filenames(url)
urls_filenames.nil? ? nil : urls_filenames.map { |uf| uf[:url] }
end
#returns an array of filenames for the given video url.
def self.get_filenames(url)
urls_filenames = get_urls_and_filenames(url)
urls_filenames.nil? ? nil : urls_filenames.map { |uf| uf[:name] }
end
#saves a video using DownloadHelper. returns true if no errors occured or false otherwise.
def self.save_file(file_uri, file_name, path = Dir.getwd, amount_of_tries = 1)
DownloadHelper.save_file(file_uri, file_name, path, amount_of_retries)
end
#<<< helper methods >>>
#the default error message when a plugin fails to download a video.
def self.plugin_error_message(plugin, error)
"Error while running the #{plugin.name.inspect} plugin. Maybe it has to be updated? Error: #{error}."
end
private_class_method :plugin_error_message
end
| true
|
4f02cd6b7579ebeb4b8585982c172d7b035647ad
|
Ruby
|
ejaypcanaria/onquiry_on_rails
|
/app/models/question.rb
|
UTF-8
| 800
| 2.546875
| 3
|
[] |
no_license
|
class Question < ActiveRecord::Base
before_validation :generate_permalink
belongs_to :user
has_many :answers
validates :question, presence: true, uniqueness: {message: "already exists.", case_sensitive: false}, length: { maximum: 255 }
validates :permalink, presence: true, length: { maximum: 255 }
def to_param
self.permalink
end
def already_exist?
unless self.errors.empty?
self.errors.full_messages.each do |message|
return true if message == "Question already exists."
end
end
end
def user_already_answered?(userId)
self.answers.each do |answer|
return true if answer.user.id == userId
end
return false
end
private
def generate_permalink
self.permalink = self.question.parameterize
end
end
| true
|
1e9c23124d6510c469878132a32dd3ba3ffc8000
|
Ruby
|
subintp/stockexchange_ruby
|
/models/trade.rb
|
UTF-8
| 282
| 2.796875
| 3
|
[] |
no_license
|
class Trade
attr_accessor :sell_order_id, :sell_price,
:quantity, :buy_order_id
def initialize(args)
@sell_order_id = args[:sell_order_id]
@sell_price = args[:sell_price]
@quantity = args[:quantity]
@buy_order_id = args[:buy_order_id]
end
end
| true
|
409df041c21465688b8caff19c9d89158358aab6
|
Ruby
|
jaywood128/ruby-music-library-cli-online-web-pt-102218
|
/lib/concerns/findable.rb
|
UTF-8
| 465
| 2.578125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
module Concerns::Findable
def find_by_name(name)
all.detect {|object| object.name == name}
#find will return nil of the name isn't in @@all
end
def find_or_create_by_name(name)
find_by_name(name) || create(name) #if find_by_name(name) returns nil, the right side is executed
end
def find_or_create_by_file(name)
self.find_by_name(name) || self.create(name) #if find_by_name(name) returns nil, the right side is executed
end
end
| true
|
5786a1d0ff5fd104d7ca97ef642c05b13c124927
|
Ruby
|
horthbynorthwest/bank-tech-test
|
/lib/statement.rb
|
UTF-8
| 441
| 3
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require_relative 'bank_account'
class Statement
def show_statement(list)
header
statement_content(list)
end
private
def header
puts 'date || credit || debit || balance'
end
def statement_content(list)
list.reverse.each do |t|
puts "#{t.date} || #{format(t.credit)} || #{format(t.debit)} || #{format(t.balance)}"
end
end
def format(num)
'%.2f' % num
end
end
| true
|
070d88f73704b68e7b9a4d0e0570a83ba50fb1bd
|
Ruby
|
dhserver/desafios
|
/ciclos_y_metodos/desafios_zip/solo_impares.rb
|
UTF-8
| 79
| 2.9375
| 3
|
[] |
no_license
|
n = ARGV[0].to_i
for i in 1..n
a = (i*2)-1
print "#{a} "
end
puts
| true
|
abd32b294fb75a0bc762b170eab4c79054872d55
|
Ruby
|
thebravoman/software_engineering_2014
|
/class017_test/files_for_exam_2/results/Momchil_Angelov_18_5fcdeb_csv_writer.rb
|
UTF-8
| 184
| 3.046875
| 3
|
[] |
no_license
|
require 'csv'
class CSVWriter
def write(student)
CSV.open("results.csv", "w") do |csv|
student.sort.each do |key, value|
csv << ["#{key}", "#{value}"]
end
end
end
end
| true
|
20fbec92754cbe7b6cb0d51fb140e2b118784380
|
Ruby
|
treacher/toy-robot
|
/lib/file_runner.rb
|
UTF-8
| 601
| 2.921875
| 3
|
[] |
no_license
|
class FileRunner
def initialize(file)
@simulation = Simulation.new
@parser = FileParser.new(file)
parse_actions
end
def execute_actions
parser.parsed_actions.each do |action|
if action[:action] == :place
handle_place_action(action)
else
simulation.send(action[:action].downcase)
end
end
end
private
attr_reader :simulation, :parser
def handle_place_action(action)
args = action.reject { |k, _v| k == :action }
simulation.send(action[:action].downcase, args)
end
def parse_actions
@parser.parse_actions
end
end
| true
|
2221e1de89f7abb444f0c73361ffebf826b61874
|
Ruby
|
gilesbowkett/lattice
|
/lib/grid.rb
|
UTF-8
| 2,929
| 3.21875
| 3
|
[] |
no_license
|
module DropX
class Grid
def initialize
@grid = []
7.times {@grid << Array.new(7)}
@tagged_to_explode = []
end
def [](index)
@grid[index]
end
alias :row :[]
def to_s
@grid.reverse.inject("") do |string, row|
string << "#{row.inspect}\n"
end
end
def insert(ball, column)
raise RowOverflow if column > 6
@grid.each do |row|
next unless row[column].nil?
row[column] = ball
return
end
raise ColumnOverflow
end
def contents(x, y)
@grid[y][x]
end
def column(index)
@grid.collect do |row|
row[index]
end
end
def cleared?
@grid.flatten.compact.empty?
end
def explode!(&block)
explode_horizontal
explode_vertical
blowback(&block)
kaboom
gravity!
if @tagged_to_explode.empty?
return false
else
@tagged_to_explode = []
return true
end
end
def check_explosion(ball, array, row_number, column_number)
if ball.is_a?(Ball) && array.sequence?(ball)
@tagged_to_explode << [row_number, column_number]
end
end
def explode_horizontal
@grid.each_with_index do |row, row_number|
row.each_with_index do |ball, column_number|
check_explosion(ball, row, row_number, column_number)
end
end
end
def explode_vertical
(0..6).each do |column_number|
column(column_number).each_with_index do |ball, row_number|
check_explosion(ball, column(column_number), row_number, column_number)
end
end
end
def kaboom
@tagged_to_explode.each do |row, column|
@grid[row][column] = nil
end
end
def blowback(&block)
# collect all the coordinates for explosions, and then communicate
# the blowback to the balls one unit away. ? balls don't change
# on explosion; they change on proximity to it.
# refactor later to collect, maybe
@blowback = []
@tagged_to_explode.each do |row, column|
@blowback << @grid[row - 1][column] unless 0 == row
@blowback << @grid[row + 1][column] unless 6 == row
@blowback << @grid[row][column - 1] unless 0 == column
@blowback << @grid[row][column + 1] unless 6 == column
end
shatter = (! @blowback.compact.empty?) && @blowback.inspect =~ /\?/
@blowback.compact.uniq.each {|ball| ball.advance_state!}
block.call if block_given? and shatter
end
def clear_column(column_number)
(0..6).each do |row_number|
@grid[row_number][column_number] = nil
end
end
def gravity!
(0..6).each do |column_number|
balls = column(column_number).drop
clear_column(column_number)
balls.each do |ball|
insert(ball, column_number)
end
end
end
end
end
| true
|
9282a078178604b11d785441dcd0395de941bd02
|
Ruby
|
tdshap/wdi-rosencrantz
|
/w05/d03/Classwork/dog_breeds/add_dog.rb
|
UTF-8
| 455
| 3.234375
| 3
|
[] |
no_license
|
puts "Hello. Welcome to the dog database. What is the breed of dog you want to update?"
breed = gets.chomp
puts "What is the dog's name?"
name = gets.chomp
puts "What is the dog's age?"
age= gets.chomp
dog_to_update = Dog.find_by(:breed breed)
id = dog_to_update[:id]
HTTParty.put("http://127.0.0.1:4567/dog/#{id}",{:body => {:age => "#{age}", :name => "#{name}", :breed => "#{breed}"}})
puts "Thank you! Your dog has been added to the database"
| true
|
6bfd2bc98c92aec86eeb0f37e3e8d95118ca15c3
|
Ruby
|
dgsuarez/programs_that_understand
|
/ruby/db_adapters.rb
|
UTF-8
| 512
| 3.25
| 3
|
[] |
no_license
|
# This is a classic metaprogramming use case: Avoid repeating yourself when you
# need to initialize a class based on it's name
module Adapters
class MysqlAdapter; end
class PostgresAdapter; end
class SqlserverAdapter; end
class OracleAdapter; end
end
# Using `const_get` we can resolve a class name (a string), into a real
# reference to the class.
def adapter(db_name)
adapter_class_name = "#{db_name.capitalize}Adapter"
Adapters.const_get(adapter_class_name)
end
p adapter(:sqlserver).new
| true
|
9e699a73337c3f1342c456effc0920fea21c7d3a
|
Ruby
|
Thieurom/nand2tetris
|
/06/src/parser.rb
|
UTF-8
| 2,364
| 3.40625
| 3
|
[] |
no_license
|
require_relative 'instruction_type'
require_relative 'symbol_table'
class Parser
def initialize(source_file)
@source = source_file
@symbols = SymbolTable.new
@next_address = 16
@instructions = []
end
def parse
load_from_source
scan_labels
out = []
@instructions.each do |instruction|
out << parse_instruction(instruction) if instruction_type(instruction) != Instruction::TYPE_L
end
out
end
private
def instruction_type(instruction)
if instruction[0] == '@'
Instruction::TYPE_A
elsif instruction[0] == '('
Instruction::TYPE_L
else
Instruction::TYPE_C
end
end
def load_from_source
File.foreach(@source) do |line|
text = line.gsub(/\/\/.*$/, '').strip
@instructions << text if text.length > 0
end
end
def scan_labels
current = 0
@instructions.each do |instruction|
if instruction_type(instruction) == Instruction::TYPE_L
symbol = instruction[1..-2]
@symbols.add(symbol, current) if !@symbols.contains?(symbol)
else
current += 1
end
end
end
def parse_instruction(instruction)
type = instruction_type(instruction)
if type == Instruction::TYPE_A
{
'type' => type,
'value' => a_field(instruction)
}
else
dest, comp, jump = c_fields(instruction)
{
'type' => type,
'dest' => dest,
'comp' => comp,
'jump' => jump
}
end
end
def a_field(instruction)
symbol = instruction[1..-1]
return symbol.to_i if is_number?(symbol)
if !@symbols.contains?(symbol)
@symbols.add(symbol, @next_address)
@next_address += 1
end
@symbols.address(symbol)
end
def c_fields(instruction)
dest = ''
comp = ''
jump = ''
comp_start_index = 0
comp_end_index = -1
equal_sign_index = instruction.index('=')
deli_sign_index = instruction.index(';')
if equal_sign_index
dest = instruction[0..(equal_sign_index - 1)]
comp_start_index = equal_sign_index + 1
end
if deli_sign_index
jump = instruction[(deli_sign_index + 1)..-1]
comp_end_index = deli_sign_index - 1
end
comp = instruction[comp_start_index..comp_end_index]
return dest, comp, jump
end
def is_number?(s)
/\A\d+\z/.match(s)
end
end
| true
|
8443c2e0e77c0009db6e23b581d65840a9cf8962
|
Ruby
|
gpsing7v/student_shuffle.names
|
/student_shuffle.rb
|
UTF-8
| 111
| 2.84375
| 3
|
[] |
no_license
|
students = ["Student", "Billy", "Sue", "Mickey", "Mouse",
"Donald", "Duck", "Daffey", "Pluto"]
puts students
| true
|
0fdb2ab615c7ef9a265520cbc073cf55162133d2
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/gigasecond/8dc7c648a3cc4d13a8434456cbe9c4b5.rb
|
UTF-8
| 153
| 2.96875
| 3
|
[] |
no_license
|
require 'date'
require 'time'
class Gigasecond
def initialize(birthday)
@date = birthday + ((10 ** 9)/(60 * 60 * 24))
end
attr_reader :date
end
| true
|
782c87986086cf023320b506fa72c8e0ef993865
|
Ruby
|
chrisb/openfire
|
/lib/openfire/client.rb
|
UTF-8
| 735
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
module Openfire
class Client
include ActiveSupport::Configurable
config.services = [ 'Group', 'Room', 'User' ]
def initialize(url,secret)
@services = config.services.map { |s| "Openfire::Service::#{s}".constantize.new url: url, secret: secret }
end
def get_service(service)
klass_name = "Openfire::Service::#{service.to_s.classify}"
klass = klass_name.constantize rescue nil
@services.each { |s| return s if s.is_a?(klass) }
raise "unknown service: #{service}"
end
def method_missing(meth, *args, &block)
@services.each do |service|
if service.respond_to?(meth)
return service.send meth, *args
end
end
super
end
end
end
| true
|
657abf1371b5de833c787ccbff573aa55a209735
|
Ruby
|
EricRichardson/aoc_2020
|
/day10/solution.rb
|
UTF-8
| 360
| 2.546875
| 3
|
[] |
no_license
|
def solve
one_diff = 0
three_diff = 1 # for the device
small_count = 0
file_name = 'other.txt'
adaptors = File
.readlines(file_name)
.map(&:to_i)
.sort
.inject(0) do |last, adp|
diff = adp - last
one_diff += 1 if diff == 1
three_diff += 1 if diff == 3
adp
end
one_diff * three_diff
end
puts solve
| true
|
9786b8bc8bb20ac543ba1ea2a6e9dff6e911192c
|
Ruby
|
soffes/quesadilla
|
/lib/quesadilla/extractor/emoji.rb
|
UTF-8
| 1,100
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
# encoding: UTF-8
module Quesadilla
class Extractor
# Extract named emoji.
#
# This module has no public methods.
module Emoji
private
require 'named_emoji'
# Emoji colon-syntax regex
EMOJI_COLON_REGEX = %r{:([a-zA-Z0-9_\-\+]+):}.freeze
def replace_emoji
codes = {}
# Replace codes with shas
i = 0
while match = @original_text.match(Markdown::CODE_REGEX)
original = match[0]
key = Digest::SHA1.hexdigest("#{original}-#{i}")
codes[key] = original
@original_text.sub!(original, key)
i += 1
end
# Replace emojis
match = @original_text.match(EMOJI_COLON_REGEX)
match.captures.each do |match|
sym = match.downcase.to_sym
next unless NamedEmoji.emojis.keys.include?(sym)
@original_text.sub!(":#{sym}:", NamedEmoji.emojis[sym])
end if match && match.captures
# Unreplace codes
codes.each do |key, value|
@original_text.sub!(key, value)
end
end
end
end
end
| true
|
6f09455e4b132e4df1f03108f0ecb677cb7ed1e2
|
Ruby
|
nemoDreamer/ruby-extensions
|
/modules/module.Testable.rb
|
UTF-8
| 1,649
| 3.234375
| 3
|
[] |
no_license
|
begin
# add color support to module.Testable if available
require_relative '../classes/class.String.rb'
rescue LoadError
if !'string'.methods.include? :color
class String
def color (*args) self end
def bold () self end
end
end
end
module Testable
# --------------------------------------------------
# Basic Assertions
# --------------------------------------------------
def assert_is comparison, strict = true
if strict
self === comparison
else
self == comparison
end
end
def assert_is_true
self.assert_is true
end
def assert_is_false
!self.assert_is_true
end
def assert_contains pattern
if self.is_a? String
self.index(pattern) != nil
else
nil
end
end
def assert_contains_not pattern
!assert_contains pattern
end
# --------------------------------------------------
# Pretty Formatting
# --------------------------------------------------
def pretty *args
should = (args[0].is_a? Symbol) ? false : args.shift
assertion = args.shift
result = self.method(assertion).call(*args)
should = should || assertion.to_s.gsub(/[_-]/, ' ')
args = args.to_s.gsub(/^\[(.*)\]$/, '\\1')
self.inspect.rjust(25) + ' ' + (should.ljust(25) + ' ' + (result ? args : args.bold)).color(result ? 'gray' : 'red')
end
# Short-hands
# --------------------------------------------------
def should_be comparison, strict = true
pretty 'should be', :assert_is, comparison, strict
end
def should_contain pattern
pretty 'should contain', :assert_contains, pattern
end
def should_not_contain pattern
pretty 'should not contain', :assert_contains_not, pattern
end
end
| true
|
af4e74e00512d65be91fd4476b06b7d8fbbb3f80
|
Ruby
|
amckemie/Rock_Paper_Scissors_Project
|
/spec/invites_cmd_spec.rb
|
UTF-8
| 2,558
| 2.671875
| 3
|
[] |
no_license
|
require 'spec_helper.rb'
describe 'invites_cmd' do
it 'exists' do
expect(InvitesCmd).to be_a(Class)
end
let(:user1) {RPS.db.create_user(:name => "Ashley", :password => "abc12")}
let(:user2) {RPS.db.create_user(:name => "Katrina", :password => "123kb")}
let(:invite_result) {@cd.create_invite(user1.name, user2.name)}
before(:each) do
@cd = RPS::InvitesCmd.new
RPS.db.clear_table("games")
RPS.db.clear_table("matches")
RPS.db.clear_table("users")
RPS.db.clear_table("invites")
end
describe '#create_invite' do
it 'should get the inviters id and give both ids to the create_invite method in the database' do
expect(invite_result[:success?]).to eq(true)
expect(invite_result[:invite].invitee).to eq(user2.id)
expect(invite_result[:invite].inviter).to eq(user1.id)
end
it "should return an error if either user does not exist" do
result = @cd.create_invite(user1.name, "Clay")
expect(result[:error]).to eq("That user doesn't exist.")
end
end
describe 'list_invites' do
it "lists all pending invites for a user with inputted id" do
invite_result
result = @cd.list_invites(user2.name)
expect(result[:success?]).to eq(true)
expect(result[:invites].size).to eq(1)
result2 = @cd.list_invites(user1.name)
expect(result2[:success?]).to eq(true)
expect(result2[:invites].size).to eq(0)
end
it "returns an error message if the user doesn't exist" do
result = @cd.list_invites("Clay")
expect(result[:error]).to eq("That user doesn't exist.")
end
end
describe 'accept_invite' do
let(:invite_response) {@cd.accept_invite(invite_result[:invite].id, invite_result[:invite].inviter, true)}
let(:invite2) {@cd.create_invite(user2.name, user1.name)}
it "creates a match between the inviter and invitee if accepted" do
expect(invite_response[:match]).to be_a(RPS::Matches)
end
it "doesn't create a match between the inviter and invitee if not accepted" do
result = @cd.accept_invite(invite2[:invite].id, 3, false)
expect(result[:success?]).to eq(true)
expect(result[:match]).to eq(nil)
end
it "deletes the invite once the invitee sends their response" do
invites = RPS.db.list_invites
expect(invites.size).to eq(0)
end
it "returns an error if the invite does not exist" do
result = @cd.accept_invite(5, 5, true)
# binding.pry
expect(result[:error]).to eq("That invite doesn't exist.")
end
end
end
| true
|
0f5fb2f680eafbcde7e8f65800d0fc6dff3d77c8
|
Ruby
|
mark/string_formatter
|
/spec/string_formatter_spec.rb
|
UTF-8
| 2,944
| 3.015625
| 3
|
[] |
no_license
|
require 'spec_helper'
describe StringFormatter do
describe "Basic behavior" do
class PersonFormatter < StringFormatter
f { first_name }
l { last_name }
end
Person = Struct.new(:first_name, :last_name) do
include Formattable
define_format_string :format, :with => PersonFormatter
end
it "should generate the right string format" do
p = Person.new("Bob", "Smith")
p.format('%f %l').must_equal "Bob Smith"
p.format('%l, %f').must_equal "Smith, Bob"
end
end
describe "Punctuation formatter" do
class PunctuationDummy
include Formattable
class PunctuationFormatter < StringFormatter
punctuation
pipe { "PIPE" }
end
define_format_string :format, with: PunctuationFormatter
end
it "should handle punctuation formats" do
PunctuationDummy.new.format('%|').must_equal "PIPE"
end
end
describe "Default formatter" do
class DefaultDummy
include Formattable
class DefaultFormatter < StringFormatter; b { "Default" }; end
define_format_string :format, with: DefaultFormatter, default: true
end
subject { DefaultDummy.new }
it "should work with %" do
string = subject % "%b"
string.must_equal "Default"
end
it "should still work with the named method" do
string = subject.format "%b"
string.must_equal "Default"
end
end
describe "Inline formatters" do
class InlineDummy
include Formattable
define_format_string :strf do
f { "Foo" }
end
class InheritableFormatter < StringFormatter; a { "Foo" }; end
define_format_string :strf2, with: InheritableFormatter do
b { "Bar" }
end
end
it "should automtatically define a formatter class if a block is provided" do
InlineDummy.new.strf("%f").must_equal "Foo"
end
it "should inherit from the formatter provided with :with" do
skip
InlineDummy.new.strf2("%a %b").must_equal "Foo Bar"
end
end
describe "Multicharacter formatters" do
class MulticharDummy
include Formattable
class MulticharFormatter < StringFormatter
foo { "FOO" }
end
define_format_string :format, with: MulticharFormatter
end
it "should allow longer format sequences" do
MulticharDummy.new.format("%foo").must_equal "FOO"
end
end
describe "Formatters with options" do
class OptionDummy
include Formattable
class OptionFormatter < StringFormatter
a(/\d/) { |n| "A[#{n}]" }
end
define_format_string :format, with: OptionFormatter
end
subject { OptionDummy.new }
it "should pass in the option when one is provided" do
subject.format('%1a').must_equal "A[1]"
end
it "should not use the option when it isn't valid" do
subject.format('%xa').must_equal "xa"
end
end
end
| true
|
e914e6efb6c482f66f5631c8294b2907753dc73c
|
Ruby
|
denisnurboja/Assignments
|
/ParsingJSON.rb
|
UTF-8
| 693
| 4
| 4
|
[] |
no_license
|
# Assignment 17
# Require JSON to parse data in Ruby.
require 'json'
# Read external JSON file and set it to the variable 'file'.
file = File.read('assignment17.json')
# Parse the 'questions' object inside of the JSON 'file'; leaving out the
# 'questions' object will print all 3 questions and error out.
questions = JSON.parse(file)['questions']
answers = []
questions.each do |question|
puts question
response = gets.chomp
answers.push(response)
end
puts 'Summary of our very quick Q&A:'
summary = Hash[*questions.zip(answers).flatten]
summary.each do |thequestions, theanswers|
puts "The question was: #{thequestions}"
puts "- Your answer was: #{theanswers.capitalize}"
end
| true
|
c7d28efb27202c9c325b149b8e729d375ebe9b64
|
Ruby
|
tiyd-ror-2016-06/playr
|
/app/models/hangman.rb
|
UTF-8
| 657
| 3.078125
| 3
|
[] |
no_license
|
class Hangman < ActiveRecord::Base
belongs_to :player, class_name: "User"
@word_list = ["test", "example", "thing"]
def self.start user
word = @word_list ? @word_list.sample : Word.all.sample
create! word: word, lives_left: 6, player: user
end
def self.word_list= l
@word_list = l
end
def record_guess letter
unless word.include? letter
self.lives_left -= 1
end
self.guesses += letter
self.save!
end
def board
word.split("").map do |l|
guesses.include?(l) ? l : "_"
end
end
def letters_guessed
guesses.split ""
end
def missed_guesses
letters_guessed - board
end
end
| true
|
bc5c19086c4520b82ebd6293e02deef189dd04df
|
Ruby
|
marlonsingleton/crimson-stone
|
/lesson_1/nothing_to_return.rb
|
UTF-8
| 308
| 3.65625
| 4
|
[] |
no_license
|
=begin
def scream(words)
words = words + "!!!!"
return
puts words
end
scream("Yippeee")
=end
puts "
def scream(words)
words = words + \"!!!!\"
return
puts words
end
scream(\"Yippeee\")
The method returns nothing because the explicit 'return'
within the code block was not passed a value.
"
| true
|
61efc235eb3c9e9bbc0e178b787b6eb2be305bee
|
Ruby
|
bakutinamari/mary
|
/t.rb
|
UTF-8
| 271
| 3.09375
| 3
|
[] |
no_license
|
puts "Введите ваше имя"
name = gets.chomp
puts "Введите ваш рост"
height = gets.chomp
h = height.to_i
height_2 = (h-110)*1.15
if height_2 >=0
puts "#{name},ваш вес #{height_2}"
else
puts "Ваш вес уже оптимальный"
end
| true
|
4970d9c1b3fd818f979bee8adef7d98a14b682eb
|
Ruby
|
aaronsweeneyweb/airport_challenge
|
/spec/airport_spec.rb
|
UTF-8
| 944
| 3
| 3
|
[] |
no_license
|
require 'airport'
describe Airport do
it { is_expected.to respond_to(:land).with(1).argument}
it { is_expected.to respond_to(:take_off).with(1).argument}
describe '#land' do
it 'can see a landed plane' do
plane1 = (double :plane)
subject.land(plane1)
expect(subject.planes).to include plane1
end
end
describe '#take_off' do
it 'lets a plane take off' do
expect(subject).to respond_to(:take_off)
end
end
describe '#initializing capacity' do
it 'has a #DEFAULT_CAPACITY of 20' do
expect(subject.capacity).to eq described_class::DEFAULT_CAPACITY
end
it 'has an overridden capacity when specified' do
subject = Airport.new(50)
expect(subject.capacity).to eq 50
end
end
it 'should raise an error when airport is full' do
described_class::DEFAULT_CAPACITY.times { subject.land(double :plane) }
expect {subject.land(double :plane)}.to raise_error 'Airport is full'
end
end
| true
|
55248dcda1b4cca7b4fe027f4b97c38b05e3074d
|
Ruby
|
hillmandj/clrs-algorithms
|
/ch-4/code/linear_runtime_maximum_subarray.rb
|
UTF-8
| 2,505
| 4.03125
| 4
|
[] |
no_license
|
#!/usr/bin/env ruby
# CODE FOR 4.1-5
def linear_maximum_subarray(a)
# Initialize values that we'll be returning
low = 0
high = 0
max_sum = 0
# These are the values we'll use to keep track of where the
# maximum subarray is, and the corressponding index.
i = 0
current_sum = 0
0.upto(a.length - 1).each do |j|
# As we go left to right, add to current_sum
current_sum += a[j]
# If the sum is greater than the max_sum, we set our return
# values to what is current
if current_sum > max_sum
low = i
high = j
max_sum = current_sum
end
# If the current_sum is less than 0, we know that we are
# no longer in a place where the maximum subarray exists.
#
# We must reset our current_sum and i placeholders so that
# we can start checking the next span of the array for the
# maximum subarray.
if current_sum < 0
current_sum = 0
i = j + 1
end
end
{ low: low, high: high, value: max_sum }
end
def sentinal_linear_maximum_subarray(a)
low = 0
high = 0
# These are sentinals for the minimum integer value in ruby
# This algorithm is better than what's up top since it will
# return the highest value if every item in the array is
# negative.
#
# This is calculated by taking the total number of bytes that
# make up an integer (1.size == 8) times the number of bits in
# a byte (8), removing 1 since one is used for the sign (totals 63).
# We then bit shift any integer (in this case 1) that many times.
max_sum = -(1 << (1.size * 8 - 1))
current_sum = -(1 << (1.size * 8 - 1))
i = 0
0.upto(a.length - 1).each do |j|
if current_sum > 0
current_sum += a[j]
else
current_sum = a[j]
i = j
end
if current_sum > max_sum
low = i
high = j
max_sum = current_sum
end
end
{ low: low, high: high, value: max_sum }
end
if __FILE__ == $0
a = [13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7]
puts "This is a: #{a * ', '}"
result = linear_maximum_subarray(a)
puts "This is result: #{result}"
sentinal_result = sentinal_linear_maximum_subarray(a)
puts "This is sentinal result: #{sentinal_result}"
a = [-1, -2, -3]
puts "This is another a: #{a * ', '}"
result = linear_maximum_subarray(a)
sentinal_result = sentinal_linear_maximum_subarray(a)
puts "This is result (only shows that profit is 0): #{result}"
puts "This is sentinal result (actual subarray): #{sentinal_result}"
end
| true
|
41f8067e2774c562b2a7203eb9fe1afac2ee0500
|
Ruby
|
faust45/bharati_ru
|
/lib/page_path.rb
|
UTF-8
| 1,689
| 2.796875
| 3
|
[] |
no_license
|
class PagePath
attr_reader :helper
delegate :ico_beta, :link_to, :content_tag, :root_path, :to => :helper
def initialize(helper, &block)
@helper = helper
@block = block
@prefix = ''
@path = Path.new(helper)
end
def to_s
@block.bind(self).call
@path.to_s
end
def method_missing(method, *args)
text = args.first
@path.add(method, text)
end
def main_path
link_to('<span>Бхарати<span>.ру</span></span>'.html_safe + ico_beta, root_path)
end
class Path
attr_reader :routes
def initialize(routes)
@routes = routes
@first_item = ''
@prefix_parts = []
@parts = []
@values = {}
end
def current_path
collect_values
collect_paths
end
def add(item, text)
el = {
:item => item,
:title => text
}
if @root.blank?
@root = el
else
@parts << el
end
end
def collect_values
@first_item = @root[:item]
path_for(@root)
@parts.each do |p|
item = p[:item]
value = routes.instance_variable_get("@#{item}")
end
end
def to_s
@parts.each do |part|
helper.link_to(part[:title], part[:path])
end
end
private
def path_for(item)
routes.send("#{item}_path", *values)
end
def values
@prefix_parts.map{|p| value_for(p) }
end
def value_for(item)
end
def path_method(item)
if @prefix.blank?
@first_item = item
item
else
@prefix_parts << item
@prefix_parts.join('_') + @first_item
end
end
end
end
| true
|
73fbb3add31677e2ade043b45c4ef019f5256ac9
|
Ruby
|
jjc224/Matasano
|
/Ruby/25.rb
|
UTF-8
| 6,166
| 3.34375
| 3
|
[] |
no_license
|
# Challenge 25: break random access read/write AES-CTR.
require_relative 'matasano_lib/aes_128'
require_relative 'matasano_lib/url'
require_relative 'matasano_lib/monkey_patch'
include MatasanoLib
# irb(main):003:0> MatasanoLib::AES_128::random_key
# => "/\x82\x82\xC8\"\xEE\\i_\x1F\x06\xA0\xAC;\x06)"
AES_KEY = '971fe7b9c17f4ad77fef00d8b487c413'.unhex
# Encrypt the recovered plaintext from this file (the ECB exercise) under CTR with a random key (for this exercise the key should be unknown to you, but hold on to it).
def encryption_oracle
# From an early-on AES-128-ECB exercise. 'YELLOW SUBMARINE' is the 128-bit key.
ciphertext = URL::decode64('http://cryptopals.com/static/challenge-data/25.txt')
plaintext = AES_128.decrypt(ciphertext, 'YELLOW SUBMARINE', :mode => :ECB)
AES_128.encrypt(plaintext, AES_KEY, :mode => :CTR)
end
ciphertext = encryption_oracle
# Now, write the code that allows you to "seek" into the ciphertext, decrypt, and re-encrypt with different plaintext. Expose this as a function, like, "edit(ciphertext, key, offset, newtext)".
def edit(ciphertext, key, offset, new_text)
plaintext = AES_128.decrypt(ciphertext, key, :mode => :CTR)
plaintext[offset % plaintext.size, new_text.size] = new_text[0..plaintext.size] # Modulo so it wraps around to imitate a fixed-size buffer, such as a disk.
AES_128.encrypt(plaintext, key, :mode => :CTR)
end
# Imagine the "edit" function was exposed to attackers by means of an API call that didn't reveal the key or the original plaintext; the attacker has the ciphertext and controls the offset and "new text".
def write_to_disk(offset, new_text)
edit(encryption_oracle, AES_KEY, offset, new_text)
end
# Recover the original plaintext.
# ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Food for thought:
# A folkloric supposed benefit of CTR mode is the ability to easily "seek forward" into the ciphertext; to access byte N of the ciphertext, all you need to be able to do is generate byte N of the keystream. Imagine if you'd relied on that advice to, say, encrypt a disk.
# ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# This is trivially broken: all I need to do is edit the "disk data" (saved ciphertext) to all zeroes and let it re-encrypt, as 0 ^ keystream[i] = keystream[i].
# Once I have the AES-encrypted keystream, all I need to do is XOR the original ciphertext with that to acquire the plaintext.
# Furthermore, since CTR mode turns a block cipher into a stream cipher, I can decrypt it all at once rather than in 128-bit chunks/blocks.
keystream = write_to_disk(0, "\0" * ciphertext.size)
plaintext = XOR.crypt(ciphertext, keystream).unhex
puts plaintext
# Output:
# ----------------------------------------------------------
# [josh@jizzo:~/Projects/Matasano/Ruby on master] ruby 25.rb
#
# I'm back and I'm ringin' the bell
# A rockin' on the mike while the fly girls yell
# In ecstasy in the back of me
# Well that's my DJ Deshay cuttin' all them Z's
# Hittin' hard and the girlies goin' crazy
# Vanilla's on the mike, man I'm not lazy.
#
# I'm lettin' my drug kick in
# It controls my mouth and I begin
# To just let it flow, let my concepts go
# My posse's to the side yellin', Go Vanilla Go!
#
# Smooth 'cause that's the way I will be
# And if you don't give a damn, then
# Why you starin' at me
# So get off 'cause I control the stage
# There's no dissin' allowed
# I'm in my own phase
# The girlies sa y they love me and that is ok
# And I can dance better than any kid n' play
#
# Stage 2 -- Yea the one ya' wanna listen to
# It's off my head so let the beat play through
# So I can funk it up and make it sound good
# 1-2-3 Yo -- Knock on some wood
# For good luck, I like my rhymes atrocious
# Supercalafragilisticexpialidocious
# I'm an effect and that you can bet
# I can take a fly girl and make her wet.
#
# I'm like Samson -- Samson to Delilah
# There's no denyin', You can try to hang
# But you'll keep tryin' to get my style
# Over and over, practice makes perfect
# But not if you're a loafer.
#
# You'll get nowhere, no place, no time, no girls
# Soon -- Oh my God, homebody, you probably eat
# Spaghetti with a spoon! Come on and say it!
#
# VIP. Vanilla Ice yep, yep, I'm comin' hard like a rhino
# Intoxicating so you stagger like a wino
# So punks stop trying and girl stop cryin'
# Vanilla Ice is sellin' and you people are buyin'
# 'Cause why the freaks are jockin' like Crazy Glue
# Movin' and groovin' trying to sing along
# All through the ghetto groovin' this here song
# Now you're amazed by the VIP posse.
#
# Steppin' so hard like a German Nazi
# Startled by the bases hittin' ground
# There's no trippin' on mine, I'm just gettin' down
# Sparkamatic, I'm hangin' tight like a fanatic
# You trapped me once and I thought that
# You might have it
# So step down and lend me your ear
# '89 in my time! You, '90 is my year.
#
# You're weakenin' fast, YO! and I can tell it
# Your body's gettin' hot, so, so I can smell it
# So don't be mad and don't be sad
# 'Cause the lyrics belong to ICE, You can call me Dad
# You're pitchin' a fit, so step back and endure
# Let the witch doctor, Ice, do the dance to cure
# So come up close and don't be square
# You wanna battle me -- Anytime, anywhere
#
# You thought that I was weak, Boy, you're dead wrong
# So come on, everybody and sing this song
#
# Say -- Play that funky music Say, go white boy, go white boy go
# play that funky music Go white boy, go white boy, go
# Lay down and boogie and play that funky music till you die.
#
# Play that funky music Come on, Come on, let me hear
# Play that funky music white boy you say it, say it
# Play that funky music A little louder now
# Play that funky music, white boy Come on, Come on, Come on
# Play that funky music
| true
|
63ce22434771fabb38c11a3d64cbfe719c1843a6
|
Ruby
|
zachholcomb/practice_ruby
|
/lib/pascals.rb
|
UTF-8
| 293
| 3.375
| 3
|
[] |
no_license
|
class Triangle
def initialize(num)
@level = num
end
def rows
start_rows = [[1]]
return start_rows if @level == 1
(2..@level).reduce(start_rows) do |finish, row|
new_row = [0, *finish.last, 0].each_cons(2).map(&:sum)
finish.append(new_row)
end
end
end
| true
|
ed00d08a799b4744f7a8722073267f5fd35c7349
|
Ruby
|
wefasdfaew2/betting
|
/lib/migration.rb
|
UTF-8
| 2,423
| 2.59375
| 3
|
[] |
no_license
|
module Migration
extend self
def get_team(team_name)
team = Team.find_by_name(team_name)
team = Team.create({name: team_name}) if team.nil?
team
end
def run_migration
league = League.find_by_name("Ligat ha al")
(27..36).each { |idx|
page_url = "http://football.org.il/Leagues/Pages/FullRoundGamesList.aspx?team_id=%D7%9B%D7%9C%20%D7%94%D7%A7%D7%91%D7%95%D7%A6%D7%95%D7%AA&round_number=#{idx}&league_id=-1"
page = Nokogiri::HTML(RestClient.get(page_url))
fixture = Fixture.create({number: idx})
games_trs = page.css("tr[class='BDCItemStyle']") + page.css("tr[class='BDCItemAlternateStyle']")
fixture_date = nil
games_trs.each { |game_tr|
date_str = game_tr.css("td[class='BDCItemText']")[1].text
sp_date = date_str.split("/")
sp_date[2] = "20" + sp_date[2]
fixed_string = sp_date.join("-")
p fixed_string
fixture_date = DateTime.parse(fixed_string, '%d-%m-%Y') if fixture_date.nil?
home_team = get_team(game_tr.css("td[class='BDCItemText']")[2].css("a[class='BDCItemLink']")[0].text)
away_team = get_team(game_tr.css("td[class='BDCItemText']")[2].css("a[class='BDCItemLink']")[1].text)
fixture.matches.build({home_team: home_team, away_team: away_team})
}
fixture.date = fixture_date
league.fixtures.push(fixture)
league.save
}
end
def get_scores_for_fixture_id(id)
fixture = Fixture.find(id)
return if fixture.nil?
page_url = "http://football.org.il/Leagues/Pages/FullRoundGamesList.aspx?team_id=%D7%9B%D7%9C%20%D7%94%D7%A7%D7%91%D7%95%D7%A6%D7%95%D7%AA&round_number=#{fixture.number}&league_id=-1"
page = Nokogiri::HTML(RestClient.get(page_url))
games_trs = page.css("tr[class='BDCItemStyle']") + page.css("tr[class='BDCItemAlternateStyle']")
games_trs.each { |game_tr|
home_team = get_team(game_tr.css("td[class='BDCItemText']")[2].css("a[class='BDCItemLink']")[0].text)
away_team = get_team(game_tr.css("td[class='BDCItemText']")[2].css("a[class='BDCItemLink']")[1].text)
next if home_team.nil? || away_team.nil?
match = fixture.find_game_by(home_team, away_team)
next if match.nil?
score = game_tr.css("td[class='BDCItemText']")[4].text
next unless score.include?('-')
match.score = score
match.save
}
end
end
| true
|
3c81dee0b42fccab81806a3a871f64c5753b4ca2
|
Ruby
|
Nova840/phase-0
|
/week-5/gps2_2.rb
|
UTF-8
| 2,746
| 4.125
| 4
|
[
"MIT"
] |
permissive
|
# Method to create a list
# input:
# steps:
# define the method with parameters
# cart = {}
#
# output: puts 'Created cart successfully!'
def create_cart(user_cart)
cart = user_cart
puts 'Created cart successfully!'
p cart
end
# Method to add an item to a list
# input: item name and optional quantity
# steps:
# define the method with parameters item name and quantity
# add item to hash with value quantity
# puts informational message
# output: modified hash with added item
def add_item(name,quantity,cart)
unless cart.has_key?(name)
cart[name] = quantity
puts 'Item successfully added!'
else
puts 'Item already added!'
end
p cart
end
# Method to remove an item from the list
# input: item name
# steps:
# define the method with parameter item name
# remove item from list
# puts informational message
# output: modified hash
def remove_item(name, cart)
if cart.delete(name) != nil
puts 'Item successfully removed!'
else
puts 'No such item in cart!'
end
p cart
end
# Method to update the quantity of an item
# input: item name and quantity
# steps:
# define the method with parameters item name and quantity
# set the quanity to new quantity
# puts informational message
# output: modified hash
def update_item(name,quantity, cart)
if cart.has_key?(name)
cart[name] = quantity
puts 'Quantity of item successfully updated!'
else
puts 'Item doesn\'t exist!'
end
p cart
end
# Method to print a list and make it look pretty
# input: none
# steps:
# define the method
# hash.each
# puts the product and (quantity)
# output: none
def display_cart(cart)
cart.each do |item, quantity|
puts item.to_s + ' (' + quantity.to_s + ')'
end
end
my_cart = create_cart({'potatoes' => 2, 'garlic' => 5, 'loaves' => 3})
add_item('banana', 4, my_cart)
remove_item('banana', my_cart)
update_item('potatoes', 10, my_cart)
display_cart(my_cart)
=begin
Reflection:
What did you learn about pseudocode from working on this challenge?
Psuedocode can help you code by giving you instructions to work off of.
What are the tradeoffs of using Arrays and Hashes for this challenge?
With hashes you have to specify a key when with arrays you just use an index.
What does a method return?
A method returns what you tell it to return, in this case the cart.
What kind of things can you pass into methods as arguments?
You can pass any kind of object as a parameter.
How can you pass information between methods?
Have a variable with a larger scope or pass it into the parameters.
What concepts were solidified in this challenge, and what concepts are still confusing?
The concept of scope was became more solidified in this challenge.
=end
| true
|
d5904bb2514d7cf88e7388b29c8446c77413badf
|
Ruby
|
kedarmhaswade/lilutils
|
/test/misc/misc_pascal_test.rb
|
UTF-8
| 695
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
require "test/unit"
require File.dirname(__FILE__) + '/../../lib/lilutils'
require 'stringio'
class PascalTest < Test::Unit::TestCase
PASCAL = LilUtils::Misc::Pascal
# Called before every test method runs. Can be used
# to set up fixture information.
def setup
# Do nothing
end
# Called after every test method runs. Can be used to tear
# down fixture information.
def teardown
# Do nothing
end
def test_first_six
rows = {1 => [1], 2 => [1, 2, 1], 3 => [1, 3, 3, 1], 4 => [1, 4, 6, 4, 1],
5 => [1, 5, 10, 10, 5, 1], 6 => [1, 6, 15, 20, 15, 6, 1]}
rows.each_pair do |row_no, row |
assert_equal(row, PASCAL.row(row_no))
end
end
end
| true
|
fc8d47edda5207628012e3ed02e497855b177e9a
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/anagram/54079dd27fc943299805397ddcbb4e62.rb
|
UTF-8
| 666
| 3.65625
| 4
|
[] |
no_license
|
require 'forwardable'
class Anagram
def initialize(word)
@word = Word.new(word)
end
def match(words)
words.select { |word| @word.anagram?(Word.new(word)) }
end
end
class Word
extend Forwardable
include Comparable
def_delegator :@word, :downcase
def initialize(word)
@word = word
end
def letters
Letters.new(self)
end
def ==(other)
downcase == other.downcase
end
def anagram?(other)
self != other && letters == other.letters
end
end
class Letters
def initialize(word)
@chars = word.downcase.chars.sort
end
def ==(other)
chars == other.chars
end
protected
attr_reader :chars
end
| true
|
51622b7197f76d666b8e2b19e16cbdb0781e06c1
|
Ruby
|
austinb847/ping_pong_ruby
|
/lib/ping_pong.rb
|
UTF-8
| 464
| 3.421875
| 3
|
[] |
no_license
|
require('pry')
class Integer
def ping_pong
num_to_count_to = self
range = (1..num_to_count_to)
ping_pongs = []
range.each() do |number|
if (number.%(3).eql?(0)) & (number.%(5).eql?(0))
ping_pongs.push("ping pong")
elsif (number.%(3).eql?(0))
ping_pongs.push("ping")
elsif (number.%(5).eql?(0))
ping_pongs.push("pong")
else
ping_pongs.push(number)
end
end
ping_pongs
end
end
| true
|
16078ea34309d336c27fad3455ea12d46a18c2d0
|
Ruby
|
Winy81/Rails_game
|
/app/helpers/characters_helper.rb
|
UTF-8
| 1,546
| 2.765625
| 3
|
[] |
no_license
|
module CharactersHelper
include Services::DateTransformer
def life_length_counter(character)
if character.status == 'alive'
length = Time.now - character.created_at
result(length)
else
length = (character.created_at - character.died_on).abs
result(length)
end
end
def params_builder_of_action(character,wallet,fed_points,cost,happiness_points,activity_points,source)
params_of_fed_state = character.fed_state + fed_points
params_of_happiness = character.happiness + happiness_points
params_of_activity = character.activity_require_level + activity_points
params_of_amount = wallet + cost
{fed_state: params_of_fed_state,
amount: params_of_amount,
happiness: params_of_happiness,
activity_require_level: params_of_activity,
extra: source}
end
def params_builder_of_action_process(fed_state,amount,activity_state,happiness_state,source)
{fed_state: fed_state,
amount: amount,
activity_require_level: activity_state,
happiness: happiness_state,
extra: source }
end
def formated_time_layout(full_days,hours)
"#{full_days} Days and #{hours} Hours"
end
def amount_of_cost_on_actions(amount)
"Going to Cost: #{amount} Gold"
end
def amount_of_earn_on_actions(amount)
"Going to Get: #{amount} Gold"
end
private
def result(seconds)
hours = seconds.to_i / SECOND_IN_A_HOUR
full_days = hours_to_full_days(hours)
hours = rest_of_hours(hours)
formated_time_layout(full_days,hours)
end
end
| true
|
7a1e242054e407beaa31bbc92286bc1be6d3ddfb
|
Ruby
|
rpazyaquian/wdi_1_miniproject_game
|
/spec/menu_spec.rb
|
UTF-8
| 3,541
| 3.3125
| 3
|
[] |
no_license
|
require 'pry'
require_relative '../lib/menu'
describe Menu do
before(:each) do
def say_hello
"Hello!"
end
options = {
say_hello: {
text: "Say hello",
action: method(:say_hello).to_proc
}
}
@menu = Menu.new(options)
def say_goodbye
"Goodbye!"
end
other_options = {
say_goodbye: {
text: "Say goodbye",
action: method(:say_goodbye).to_proc
}
}
@another_menu = Menu.new(other_options)
end
describe "#new" do
it "instantiates a new Menu object" do
expect(@menu).to be_a(Menu)
end
it "takes a list of options and associated actions" do
expect(@menu.options).to include(:say_hello)
end
it "takes another menu as a potential option" do
# basically, an option can be another menu, and calling that option's action opens that other menu
menu_option = {
menu_option: {
text: 'Another menu',
action: @another_menu
}
}
@menu.add(menu_option)
expect(@menu.options).to include(:menu_option)
end
end
describe "#add" do
it "adds options passed to it" do
new_option = {
new_option: {
text: "New option",
action: "new option!?"
}
}
@menu.add(new_option)
expect(@menu.run(:new_option)).to eq "new option!?"
end
end
describe "#run" do
it "executes an option's action given its symbol" do
expect(@menu.run(:say_hello)).to eq "Hello!"
end
it "returns an error when an option doesn't exist" do
expect(@menu.run(:invalid_option)).to eq :invalid_option
end
end
describe "#translate_string" do
it "translates a string input into its matching symbol" do
expect(@menu.translate_string('Say hello')).to eq :say_hello
end
end
describe "#prompt" do
it "prompts the user for a selection and returns the selection" do
STDIN.stub(gets: 'Say hello')
expect(@menu.prompt).to eq "Hello!"
end
it "recursively prompts the user when the selection is a menu" do
menu_option = {
menu_option: {
text: 'Another menu',
action: @another_menu
}
}
@menu_only = Menu.new(menu_option)
STDIN.stub(:gets).and_return('Another menu', 'Say goodbye')
expect(@menu_only.prompt).to eq 'Goodbye!'
end
it "must work if there is more than one possible option" do
menu_option = {
menu_option: {
text: 'Another menu',
action: @another_menu
},
dummy_option: {
text: "Dummy option",
action: "dummy option!!!!"
}
}
@menu_with_other_option = Menu.new(menu_option)
STDIN.stub(:gets).and_return('Another menu', 'Say goodbye')
expect(@menu_with_other_option.prompt).to eq 'Goodbye!'
end
it "must work if options are merged" do
first_option = {
dummy_option: {
text: "Dummy option",
action: "dummy option!!!!"
}
}
merged_option = {
merged_option: {
text: 'Merged menu',
action: @another_menu
}
}
# this test frusrtated me until i realized
# i didn't change 'Another menu' to 'Merged menu'
# :(
STDIN.stub(:gets).and_return('Merged menu', 'Say goodbye')
@merged_menu = Menu.new(first_option)
@merged_menu.add(merged_option)
expect(@merged_menu.prompt).to eq "Goodbye!"
end
end
end
| true
|
6742e75792f5f50d33fe58f8c20ccc615d031a03
|
Ruby
|
renevp/bakery
|
/lib/order_line_processing.rb
|
UTF-8
| 1,958
| 3.328125
| 3
|
[] |
no_license
|
class OrderLineProcessing
attr_accessor :max_items, :items
def initialize(max_items, items)
@max_items = max_items
@items = items.sort.reverse
@error = ""
end
def process_order_line
@quantities = []
@results = []
return display_error() if is_items_error?
@remaining = max_items
current = 0
loop do
if current >= items.count
current = start_over()
return display_error() if !current
end
calculate_quantity_for_item(current)
current += 1
break if first_result_founded?
end
end
def results
if @error.empty?
return [items, @quantities]
end
return @error
end
private
def display_error
@error = "There is not solution for #{items} and #{max_items}"
end
def calculate_quantity_for_item(current)
if @remaining >= items[current]
@quantities[current] = calculate_quantity(current)
@remaining -= calculate_results(current)
else
@quantities[current] = 0
end
@results[current] = calculate_results(current)
end
def start_over
@remaining = max_items
flag = true
current = 0
i = 0
while( i <= items.count && flag == true )
if @quantities[i] > 0
substract_quantity_for_item(i)
current = i + 1
flag = false
end
@results[i] = calculate_results(i)
i += 1
return false if i >= items.count
end
current
end
def substract_quantity_for_item(i)
@quantities[i] -= 1
@remaining -= calculate_results(i)
end
def total
@results.reduce(:+)
end
def first_result_founded?
total == max_items
end
def calculate_results(current)
@quantities[current] * items[current]
end
def calculate_quantity(current)
@remaining / items[current]
end
def is_items_error?
max_items < items.min || items.include?(0)
end
end
| true
|
bd8fe60df96ff363222d8cf292554d76436bbb3c
|
Ruby
|
camertron/gelauto
|
/spec/gelauto_spec.rb
|
UTF-8
| 4,671
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'spec_helper'
describe Gelauto do
before { index.reset }
let(:index) { Gelauto.method_index }
context 'with simple types' do
it 'identifies method signatures correctly' do
img = nil
Gelauto.discover do
img = GelautoSpecs::Image.new('foo.jpg', 800, 400)
expect(img.aspect_ratio).to eq(2.0)
end
init = get_indexed_method(img, :initialize)
expect(init).to accept(path: String, width: Integer, height: Integer)
expect(init).to hand_back_void
aspect_ratio = get_indexed_method(img, :aspect_ratio)
expect(aspect_ratio).to hand_back(Float)
end
end
context 'with Sorbet generic types' do
it 'uses T.nilable with T.any correctly' do
Gelauto.discover do
GelautoSpecs::Utility.safe_to_string(nil)
GelautoSpecs::Utility.safe_to_string(1.0)
GelautoSpecs::Utility.safe_to_string(2)
end
safe_to_string = get_indexed_method(GelautoSpecs::Utility, :safe_to_string)
expect(safe_to_string.to_sig).to eq('sig { params(input: T.nilable(T.any(Float, Integer))).returns(String) }')
end
it 'uses T.Hash and T::Array with T.untyped correctly' do
Gelauto.discover do
GelautoSpecs::Utility.safe_get_keys({})
end
safe_get_keys = get_indexed_method(GelautoSpecs::Utility, :safe_get_keys)
expect(safe_get_keys.to_sig).to eq('sig { params(input: T::Hash[T.untyped, T.untyped]).returns(T::Array[T.untyped]) }')
end
end
context 'with generic types' do
before do
Gelauto.discover do
@client = GelautoSpecs::Client.new(url: 'http://foo.com', username: 'bar')
@response = @client.request('body', param1: 'abc', param2: 'def')
expect(@response.to_a).to eq([200, 'it worked!'])
end
end
it 'identifies signature for Client#initialize' do
init = get_indexed_method(@client, :initialize)
expect(init).to accept(options: { Hash => { key: Symbol, value: String } })
expect(init).to hand_back_void
end
it 'identifies signature for Client#request' do
request = get_indexed_method(@client, :request)
expect(request).to accept(body: String, headers: { Hash => { key: Symbol, value: String } })
expect(request).to hand_back(GelautoSpecs::Response)
end
it 'identifies signature for Response#initialize' do
init = get_indexed_method(@response, :initialize)
expect(init).to accept(status: Integer, body: String)
expect(init).to hand_back_void
end
it 'identifies signature for Response#to_a' do
to_a = get_indexed_method(@response, :to_a)
expect(to_a).to hand_back(Array => { elem: [Integer, String] })
end
end
context 'with existing signatures' do
before do
Gelauto.discover do
@request = GelautoSpecs::Request.new
@request.to_a('Hello', 'World')
@request.to_s(100)
end
end
it 'skips existing sig, adds missing sig' do
file = File.read('spec/support/annotated.rb')
expect(file.lines.count).to eq(17)
# does not add a signature to the method with an existing signature
annotated = annotate(@request, :to_a, file)
expect(annotated.lines.count).to eq(17)
# does add a signature to the method without a signature
annotated = annotate(@request, :to_s, file)
expect(annotated.lines.count).to eq(18)
end
end
context 'with nested generic types' do
before do
Gelauto.discover do
GelautoSpecs::System.configure(YAML.load_file('spec/support/config.yml'))
end
end
it 'identifies signatures for System.configure' do
configure = get_indexed_method(GelautoSpecs::System, :configure)
expect(configure).to accept(
config: {
Hash => {
key: String,
value: [
{
Array => {
elem: [
String,
{
Hash => {
key: String,
value: {
Hash => {
key: String,
value: [
String,
{
Array => {
elem: String
}
}
]
}
}
}
}
]
}
}
]
}
}
)
end
end
end
| true
|
786ee7698e7f0c9a22375cbe5fcfbf4f1fa09b9a
|
Ruby
|
clemensg/algorithms
|
/ruby/mergesort/mergesort.rb
|
UTF-8
| 524
| 3.875
| 4
|
[
"MIT"
] |
permissive
|
# Mergesort
# Clemens, 2015
#
# [5], [3] => [3, 5]
def merge(a, b)
c = []
until a.empty? && b.empty? do
if a.first && ((b.first && a.first <= b.first) || !b.first)
c << a.shift
else
c << b.shift
end
end
return c
end
def mergesort(n)
if n.nil? || n.empty?
return []
elsif n.length == 1
return n
else
first = n[0..(n.length/2)-1]
second = n[n.length/2..-1]
#puts "first: #{first}, second: #{second}"
return merge(mergesort(first), mergesort(second))
end
end
| true
|
ba06037dd5f49c17da1bd246896b7361c19b478e
|
Ruby
|
fraterrisus/advent2018
|
/day15/part1.rb
|
UTF-8
| 7,078
| 3.390625
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require './unit.rb'
require 'colorize'
if ARGV[1]
@part_two = true
elf_attack_power = ARGV[1].to_i
else
@part_two = false
elf_attack_power = 3
end
tokens = IO.readlines(ARGV[0]).map { |l| l.rstrip.split(//) }
xdim = tokens.map(&:size).max
@floor = Array.new
tokens.size.times { @floor << Array.new(xdim) }
units = []
tokens.each_with_index do |row,y|
row.each_with_index do |space,x|
case space
when '#'
@floor[y][x] = :wall
when 'G'
unit = Unit.new(:goblin, x, y, 3)
units << unit
@floor[y][x] = unit
when 'E'
unit = Unit.new(:elf, x, y, elf_attack_power)
units << unit
@floor[y][x] = unit
when '.'
#redundant
@floor[y][x] = nil
else
raise "Unexpected floor token #{space} at (#{x},#{y})"
end
end
end
def print_board(floor)
puts
print " "
i = 0
floor[0].size.times do
print i%10
i += 1
end
puts
puts
i = 0
floor.each do |row|
print "#{i%10} "
i += 1
row.each do |space|
case space
when :wall
print '#'.light_white
when Unit
print 'E'.blue if space.elf?
print 'G'.green if space.goblin?
when nil
print '.'
when Numeric
print (97 + (space%26)).chr.red
else
raise "Unexpected space #{space.inspect}"
end
end
puts
end
end
def should_update(p,x,y,v)
return true if p[y][x].nil?
return true if p[y][x].is_a?(Numeric) && p[y][x] > v
false
end
def reachable_points(pos)
x0, y0 = pos
worklist = [ pos ]
# deep copy
points = Array.new
@floor.each do |row|
points << row.dup
end
points[y0][x0] = 0
while worklist.any?
x,y = worklist.shift
#puts "Working on #{x},#{y}"
newdist = points[y][x] + 1
[ [x-1,y], [x+1,y], [x,y-1], [x,y+1] ].each do |a,b|
if should_update(points,a,b,newdist)
#puts " Updating #{a},#{b} = #{newdist}"
points[b][a] = newdist
worklist << [a, b]
end
end
end
points
end
tick = 0
while true
puts
puts "----- Tick #{tick} -----"
units.each { |u| u.new_turn }
#print_board @floor
# Units execute in Reading Order, so iterate over the board in Reading Order,
# skipping squares that don't contain a Unit that hasn't gone yet this round.
@floor.each do |row|
row.each do |current_unit|
next unless current_unit.is_a? Unit
next if current_unit.done?
#print_board @floor
puts current_unit.inspect
# Make sure we don't let the same unit move twice in the same tick.
current_unit.done!
# Look for targets -- live units on the other team
targets = units.select(&:alive?) \
.select { |u| u.enemy_of? current_unit }
# If there are no alive enemy targets, my team wins.
if targets.empty?
puts
puts "No enemy units: game over!"
puts "Rounds completed: #{tick}"
hp = units.select(&:alive?).map(&:hp).sum
puts "Total HP remaining on winning team: #{hp}"
puts "Outcome: #{tick * hp}"
exit 0
end
# If no target is adjacent to where I already am, try to move.
if targets.select { |t| t.adjacent_to? current_unit }.empty?
# Find all reachable squares via breadth-first search.
reachable = reachable_points current_unit.coordinates
#puts " Reachable points:"
#print_board reachable
puts " Trying to move"
destination = [Float::INFINITY, Float::INFINITY]
distance = Float::INFINITY
gunning_for = nil
# For each target, examine the four adjacent squares. If I can't reach
# that square (or it's a wall), skip it. Otherwise, check to see if it
# is closer (or equidistant but better in Reading Order) than my
# current best guess. If so, select that one and remember what I did.
targets.each do |t|
[ [t.x,t.y-1], [t.x-1,t.y], [t.x+1,t.y], [t.x,t.y+1] ].each do |a,b|
r = reachable[b][a]
if r.is_a?(Numeric)
if (r < distance) || # potential square is closer
(r == distance && b < destination[1]) || # or equidistant but better in reading order
(r == distance && b == destination[1] && a < destination[0])
destination = [a,b]
distance = r
gunning_for = t
puts " Picking target at #{gunning_for.coordinates.inspect} destination #{destination.inspect} d:#{distance}"
end
end
end
end
# If I didn't find anyone to target, skip the rest of my turn.
next unless gunning_for
# Okay, I know where I'm going, the question now is how do I get there.
# It's likely that there are multiple paths that will get me to the
# destination, so do a reverse "reachable points" BFS from the
# destination square (not the enemy) to figure out which paths are the
# fastest.
reverse = reachable_points destination
# Now pick between them, again looking for the one that is closest (has
# the lowest distance), breaking ties in reading order.
destination = [Float::INFINITY, Float::INFINITY]
distance = Float::INFINITY
me = current_unit
[ [me.x,me.y-1], [me.x-1,me.y], [me.x+1,me.y], [me.x,me.y+1] ].each do |a,b|
r = reverse[b][a]
if r.is_a? Numeric
if (r < distance) ||
(r == distance && b < destination[1]) ||
(r == distance && b == destination[1] && a < destination[0])
destination = [a,b]
distance = r
end
end
end
# Move there. This involves updating the unit so it knows its new
# position as well as adjusting the board state to set the old square
# to nil (empty) and the new square to this unit.
puts " Stepping to: #{destination.inspect}"
x,y = current_unit.coordinates
@floor[y][x] = nil
current_unit.move_to destination
x,y = destination
@floor[y][x] = current_unit
end
# If there is a target adjacent to me, attack them.
puts " Trying to attack"
adjacent_targets = targets.select { |t| t.adjacent_to? current_unit }.sort_by(&:hp)
if adjacent_targets.any?
vulnerable_targets = adjacent_targets \
.select { |t| t.hp == adjacent_targets[0].hp } \
.sort_by! { |t| t.coordinates.reverse }
my_target = vulnerable_targets[0]
puts " Attacking target #{my_target.inspect}"
my_target.hurt_by! current_unit
unless my_target.alive?
@floor[my_target.y][my_target.x] = nil
if @part_two && my_target.elf?
puts " Tragedy! an elf has died."
exit 1
end
end
puts " Result #{my_target.inspect}"
else
puts " No targets"
end
end
end
tick += 1
end
| true
|
306fcee1c41c78533d680366ba5b1655d7facaa8
|
Ruby
|
toinou3010/git-thp-floraJ
|
/Cours_du_13-4-21/exo_11.rb
|
UTF-8
| 221
| 3.140625
| 3
|
[] |
no_license
|
today = 2021
puts "Quelle est ton age ?"
user_age = gets.to_i
user_birth_date = today - userage
f = -1
for i in user_birth_date..today
print i
f += 1
puts " : il y a #{user_age - f} ans, tu avais #{f} ans"
end
| true
|
332202e553c65172ae457b74a52540908237d997
|
Ruby
|
sbower/fishy_site
|
/site.rb
|
UTF-8
| 364
| 2.546875
| 3
|
[] |
no_license
|
require 'rubygems'
require 'sinatra'
require 'haml'
get '/' do
data = File.new("data", "r")
line = data.gets
(@room_temp, @tank_temp, @light_on) = line.split("|")
data.close
if @light_on.eql?("0") then
@light = "off"
else
@light = "on"
end
haml :index
end
get '/about' do
haml :about
end
get '/contact' do
haml :contact
end
| true
|
88ab359ee2d7464b70c0bc3b93e2da614803bb29
|
Ruby
|
StephanYu/roman_arabic_numerals
|
/lib/script.rb
|
UTF-8
| 279
| 3.1875
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require './number'
num = Number
ARGF.each do |line|
line = line.chomp
if num.arabic?(line)
p num.to_roman(line)
elsif num.roman?(line)
p num.to_arabic(line)
else raise "Input on line #{ARGF.lineno} with value #{line} is not valid."
end
end
| true
|
7197b72a58c6e9079717e983ae4ca7961cb7309d
|
Ruby
|
iexus/learningruby
|
/dojos/phonetic_search/spec/phonectic_matcher_spec.rb
|
UTF-8
| 3,335
| 3.296875
| 3
|
[] |
no_license
|
require_relative "../lib/phonetic_matcher"
describe Phonetic::PhoneticMatcher do
let (:surnames_text) {
surnames = []
file_address = File.join(File.dirname(__FILE__), "surnames.txt")
File.open(file_address, "r") do |f|
f.each_line do |line|
surnames << line.delete("\n")
end
end
return surnames
}
describe "alphabetising text" do
it 'will remove all non-alphabetical characters' do
result = subject.alphabetise 'letters2387numbers*&^$\\symbols'
expect(result).to eq 'lettersnumberssymbols'
end
it 'will retain spaces between words' do
result = subject.alphabetise 'Mac Donalds Farm'
expect(result).to eq 'Mac Donalds Farm'
end
end
describe "discarding vowel like characters" do
it 'will remove the following letters after the first: a-e-i-o-u-h-w-y' do
expect(subject.discard 'Aardvark').to eq 'Ardvrk'
end
it 'will handle a small word' do
expect(subject.discard 'b').to eq 'b'
end
it 'will not retain white space whilst removing' do
expect(subject.discard 'Brilliant Bonobo').to eq 'BrllntBnb'
end
end
describe "generating possible matches" do
it "will generate a coded key of possible matches" do
expect(subject.generate_match_key "acbdm").to eq "01234"
expect(subject.generate_match_key "egftn").to eq "01234"
expect(subject.generate_match_key "d").to eq "3"
expect(subject.generate_match_key "n").to eq "4"
end
it "will not care about case" do
expect(subject.generate_match_key "ACBDM").to eq "01234"
end
it "will add not replace letters which do not have an equivalent" do
expect(subject.generate_match_key "hlr").to eq "hlr"
end
it "will consider consecutive letters as one instance" do
expect(subject.generate_match_key "aaabbccchhh").to eq "021h"
expect(subject.generate_match_key "aeiou").to eq "0"
end
end
describe "generating surnames mappings" do
it "will create a map based on generated key for a surname" do
#Take Smith, discard letters and get Smt
#convert this into a key and we get 143
expected_result = { "143" => ["Smith"] }
expect(subject.generate_surname_map ["Smith"]).to eq expected_result
end
it "will add multiple surnames to the same key if they match" do
#Jonas goes to jns which maps to 141
#Johns goes to jns ..
#Saunas goes to sns which maps to 141
expected_result = { "141" => ["Jonas", "Johns", "Saunas"]}
expect(subject.generate_surname_map ["Jonas", "Johns", "Saunas"]).to eq expected_result
end
it "will have multiple keys in the mapping" do
expected_result = { "141" => ["Jonas", "Johns", "Saunas"],
"143" => ["Smith"] }
expect(subject.generate_surname_map ["Jonas", "Johns", "Saunas", "Smith"]).to eq expected_result
end
end
describe "finding surname matches" do
it "will return an array of matches if found" do
subject.generate_surname_map surnames_text
expect(subject.find_match "Jones").to eq ["Jonas", "Johns", "Saunas"]
end
it "will say that Winton is totally like Van Damme" do
subject.generate_surname_map surnames_text
expect(subject.find_match "Winton").to eq ["Van Damme"]
end
end
end
| true
|
4420208fd62460cc7ca4a94fa55f3f7aa661b847
|
Ruby
|
epotocko/has_sparse_attributes
|
/lib/active_record/has/sparse_attributes.rb
|
UTF-8
| 3,888
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
require 'active_record/has/sparse_attributes/storage'
require 'active_record/has/sparse_attributes/column_storage'
require 'active_record/has/sparse_attributes/table_storage'
module ActiveRecord #:nodoc:
module Has #:nodoc:
module SparseAttributes #:nodoc:
def self.included(base) #:nodoc:
base.extend(ClassMethods)
end
module ClassMethods #:nodoc:
def has_sparse_attributes(attribute_names, *options)
options = options.extract_options!
options[:storage] ||= :column
options[:serialize] ||= false
storage = options[:storage].to_sym
# First-time initialization
if not self.methods.include?('sparse_attributes')
class_eval <<-EOV
cattr_accessor :sparse_attributes, :instance_accessor => false
@@sparse_attributes = {}
cattr_accessor :sparse_attribute_storage_configs
@@sparse_attribute_storage_configs = []
before_update :sparse_attributes_before_update
before_save :sparse_attributes_before_save
after_save :sparse_attributes_after_save
def self.has_sparse_attribute?(name)
attribute = name.to_s
attribute = attribute[0..-2] if attribute.ends_with?('=')
return @@sparse_attributes.has_key?(attribute.to_sym)
end
include ActiveRecord::Has::SparseAttributes::InstanceMethods
EOV
end
# Add getters and setters for each sparse attribute
attribute_names.each do |name|
class_eval <<-EOV
def #{name}()
get_sparse_attribute(:#{name})
end
def #{name}=(v)
set_sparse_attribute(:#{name}, v)
end
EOV
end
if storage == :column
storage_config = ColumnStorageConfig.new(self, options)
elsif storage == :table
storage_config = TableStorageConfig.new(self, options)
else
raise StandardError.new("Invalid storage option for has_sparse_attributes")
end
self.sparse_attribute_storage_configs << storage_config
storage_id = self.sparse_attribute_storage_configs.length - 1
attribute_names.each do |name|
self.sparse_attributes[name.to_sym] = storage_id
end
end
end
module InstanceMethods
def get_sparse_attributes()
r = {}
self.class.sparse_attributes.each_key do |k|
v = self.get_sparse_attribute(k)
r[k] = v unless v.nil?
end
return r
end
def get_sparse_attribute(name)
self.get_sparse_attribute_storage(name).get(name)
end
def set_sparse_attribute(name, value)
self.get_sparse_attribute_storage(name).set(name, value)
end
protected
attr_accessor :sparse_attribute_storage
def get_sparse_attribute_storage(name)
create_sparse_attribute_storage()
self.sparse_attribute_storage[self.class.sparse_attributes[name.to_sym]]
end
def create_sparse_attribute_storage()
if self.sparse_attribute_storage.nil?
self.sparse_attribute_storage = []
self.class.sparse_attribute_storage_configs.each do |config|
self.sparse_attribute_storage << config.instance(self)
end
end
end
def sparse_attributes_before_update(*args)
create_sparse_attribute_storage()
self.sparse_attribute_storage.each do |store|
store.before_update(*args)
end
end
def sparse_attributes_before_save(*args)
create_sparse_attribute_storage()
self.sparse_attribute_storage.each do |store|
store.before_save(*args)
end
end
def sparse_attributes_after_save(*args)
create_sparse_attribute_storage()
self.sparse_attribute_storage.each do |store|
store.after_save(*args)
end
end
end
end
end
end
| true
|
7d1a70836233fb88b88a82cecacb6fcdcd8a6657
|
Ruby
|
dantrovato/launch-school
|
/small_problems/easy8/9_convert_number_to_reversed_array_of_digits.rb
|
UTF-8
| 2,077
| 4.65625
| 5
|
[] |
no_license
|
=begin
Convert number to reversed array of digits
Write a method that takes a positive integer as an argument and returns that
number with its digits reversed. Examples:
reversed_number(12345) == 54321
reversed_number(12213) == 31221
reversed_number(456) == 654
reversed_number(12000) == 21 # Note that zeros get dropped!
reversed_number(1) == 1
=end
p reversed_number(12345) == 54321
p reversed_number(12213) == 31221
p reversed_number(456) == 654
p reversed_number(12000) == 21 # Note that zeros get dropped!
p reversed_number(1) == 1
=begin
MY SLUSH 1
def reversed_number(number)
array = []
number.to_s.chars.reverse_each { |digit| array << digit }
result = array.map(&:to_i)
total = 0
result.each do |digit|
total = total * 10 + digit
end
p total
end
MY SLUSH 2
def reversed_number(number)
p number.to_s.reverse.to_i
end
Hide Solution & Discussion
Solution
def reversed_number(number)
string = number.to_s
reversed_string = string.reverse
reversed_string.to_i
end
Discussion
This exercise has a lot of different solutions. We'll use an approach that talks
more about logical steps than procedural descriptions. Instead of saying "Iterate
over the number's digits and put them together in reverse order," which will
probably lead to a loop-based method, we'll talk in more general terms that model
what we know we can with strings and numbers: "Convert the number to a string
(Integer#to_s). Reverse the string (String#reverse). Convert the result to a number
(String#to_i)."
This task list lets us write out the solution in a natural way. In our solution,
we use Integer#to_s to convert the number to a String, then String#reverse to
reverse the String, and then use String#to_i to get the final result.
It's fine if you used a loop to solve this yourself; we haven't seen many solutions
like this so far. The key to this approach is to break the problem down into
logical steps that mirror the operations you can perform on the types used in your
method. With time, this will seem more natural than writing a loop.
=end
| true
|
51499c9fe9ca259ee10b9e0dc3a1bce8eb8a8c80
|
Ruby
|
rafer/chess
|
/lib/chess/move.rb
|
UTF-8
| 1,017
| 3.140625
| 3
|
[] |
no_license
|
module Chess
class Move
class IllegalMove < ArgumentError; end
def initialize(origin, destination)
@origin = origin
@destination = destination
end
def bind(board)
@board = board
@piece = board[@origin]
@mover = @piece.color
@captured_piece = board[@destination]
end
# All of the methods below this only apply if the move has been bound
attr_reader :mover
attr_reader :captured_piece
def legal?
@piece.move_to?(@destination)
end
def execute
raise IllegalMove unless legal?
piece = board.pick_up(@origin)
captured_piece = board.pick_up(@destination)
board.place(@destination, piece)
end
def undo
piece = board.pick_up(@destination)
board.place(@origin, piece)
board.place(@destination, @captured_piece) if @captured_piece
end
private
def board
raise 'This move has not been bound to a board' if @board.nil?
return @board
end
end
end
| true
|
853e675b6e7a29c7aa9d7fbe012e6a4ace835462
|
Ruby
|
crawsible/advent-2019
|
/04/lib/viable_password_counter.rb
|
UTF-8
| 866
| 3.390625
| 3
|
[] |
no_license
|
class ViablePasswordCounter
def initialize(range)
@range = range
end
def count
range.count do |number|
same_adjacent_digits?(number) && no_descending_digits?(number)
end
end
def a_count
range.count do |number|
a_same_adjacent_digits?(number) && no_descending_digits?(number)
end
end
private
attr_reader :range
def same_adjacent_digits?(number)
number = number.to_s
5.times do |i|
return true if number.match(/(#{number[i]}+)/).captures.first.length == 2
end
false
end
def a_same_adjacent_digits?(number)
number = number.to_s
5.times do |i|
return true if number[i] == number[i+1]
end
false
end
def no_descending_digits?(number)
number = number.to_s
5.times do |i|
return false if number[i].to_i > number[i+1].to_i
end
true
end
end
| true
|
0163da1615da070f63bb89fffd19cc16fd9d0476
|
Ruby
|
mindaslab/ilrx
|
/function_variable_arguments.rb
|
UTF-8
| 157
| 3.40625
| 3
|
[] |
no_license
|
# function_variable_arguments.rb
def some_function a, *others
puts a
puts "Others are:"
for x in others
puts x
end
end
some_function 1,2,3,4,5
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.