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
7ff84587b1c66f491e1cf3f4b1405a76be1bc52e
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/word-count/0387763ad7e54b64acdab88c09a2e524.rb
UTF-8
197
2.921875
3
[]
no_license
class Phrase < Struct.new :phrase def word_count phrase.scan(WORDS).group_by(&:downcase). map(&COUNT).reduce :merge end WORDS = /\w+/ COUNT = -> (( k, v )) {{ k => v.count }} end
true
1621975c6232e16fae21b41effe0e800ade15fe1
Ruby
mhahmadi/numbeers
/app/helpers/transactions_helper.rb
UTF-8
1,479
2.65625
3
[]
no_license
module TransactionsHelper def self.first_pour_of_day() Transaction.where("created_at >= ?", Time.zone.now.beginning_of_day).first end def total_pours() Transaction.count() end def most_pours_by_a_user() pours = Transaction.all() if pours.blank? "No Pours Yet!?" else h = pours.group(:contact_id).count().max_by{|k,v| v} h[1] end end def last_pour() lastpour = Transaction.last if lastpour.nil? "No Pours Yet!?" else lastpour.created_at.strftime("%a - %b %d, %Y \n %I:%M %p") end end #User Transactions def user_total_pours(user) pours = Transaction.where(contact_id: user.id) if pours.nil? "No Pours Yet1?" else pours.count() end end def user_last_pour(user) lastpour = Transaction.where(contact_id: user.id).last if lastpour.nil? "No Pours Yet!?" else lastpour.created_at().strftime("%a - %b %d, %Y \n %I:%M %p") end end def user_pours_current_keg(user, keg) if keg.blank? "No Pours Yet!?" else pours = Transaction.where(contact_id: user.id, keg_id: keg.id) if pours.nil? "No Pours Yet!?" else pours.count() end end end def user_pours_past_week(user) pours = Transaction.where('created_at >= ? AND contact_id = ?', 1.week.ago, user.id) if pours.nil? "No Pours in the Past Week!?" else pours.count() end end end
true
f734da000dc1b92dae75657db947a88dc16e2fc6
Ruby
google-code/asproject
/rb/lib/tasks/flash_log.rb
UTF-8
1,093
2.75
3
[ "MIT" ]
permissive
module AsProject class FlashLog attr_accessor :version def initialize @path_finder = PathFinder.new verify_config_file end def get_file return @path_finder.flash_player_log end private def verify_config_file config = @path_finder.flash_player_config if(!File.exists?(config)) content = @path_finder.flash_player_config_content write_config(config, content) end end private def write_config(location, content) puts <<EOF Correctly configured mm.cfg file not found at: #{location} This file is required in order to capture trace output. Would you like this file created automatically? [Yn] EOF answer = $stdin.gets.chomp.downcase if(answer.index('y') || answer == '') File.open(location, 'w') do |f| f.write(content) end puts ">> Created: " + File.expand_path(location) else raise BuildError.new("Unable to create mm.cfg file at: #{location}") end end end end
true
189a044d85c3be3490333539b7d844050d982dc9
Ruby
ruby-llvm/ruby-llvm
/test/memory_access_test.rb
UTF-8
1,494
2.625
3
[ "BSD-3-Clause", "Ruby", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
# frozen_string_literal: true require "test_helper" class MemoryAccessTestCase < Minitest::Test def test_simple_memory_access assert_equal 1 + 2, simple_memory_access_function(1, 2).to_i end def test_array_memory_access assert_equal 3 + 4, array_memory_access_function(3, 4).to_i end private def setup LLVM.init_jit end def simple_memory_access_function(value1, value2) run_function([LLVM::Int, LLVM::Int], [value1, value2], LLVM::Int) do |builder, function, *arguments| entry = function.basic_blocks.append builder.position_at_end(entry) pointer1 = builder.alloca(LLVM::Int) pointer2 = builder.alloca(LLVM::Int) builder.store(arguments.first, pointer1) builder.store(arguments.last, pointer2) builder.ret(builder.add(builder.load(pointer1), builder.load(pointer2))) end end def array_memory_access_function(value1, value2) run_function([LLVM::Int, LLVM::Int], [value1, value2], LLVM::Int) do |builder, function, *arguments| entry = function.basic_blocks.append builder.position_at_end(entry) pointer = builder.array_alloca(LLVM::Int, LLVM::Int(2)) builder.store(arguments.first, builder.gep(pointer, [LLVM::Int(0)])) builder.store(arguments.last, builder.gep(pointer, [LLVM::Int(1)])) builder.ret(builder.add(builder.load(builder.gep(pointer, [LLVM::Int(0)])), builder.load(builder.gep(pointer, [LLVM::Int(1)])))) end end end
true
5f55a229284611b5347f21f913e6687a3a1bf4d9
Ruby
cielavenir/procon
/hackerrank/sherlock-and-pairs.rb
UTF-8
129
2.609375
3
[ "0BSD" ]
permissive
#!/usr/bin/ruby gets.to_i.times{ gets p gets.split.map(&:to_i).sort.chunk{|e|e}.reduce(0){|s,(k,v)| n=v.size s+n*(n-1) } }
true
8005ea4602f73ae9c5faca783c96875a1c1abb27
Ruby
beckybair/ruby_challenges
/scrape_recipe.rb
UTF-8
716
3.625
4
[]
no_license
# Scrape a Recipe #Start your script by requiring the nokogiri gem and also one of its dependencies: require 'nokogiri' require 'open-uri' #Next, get the HTML for the recipe page and assign it to a variable: doc = Nokogiri::HTML(open("http://www.marthastewart.com/312598/brick-pressed-sandwich")) #Search the HTML for different types of elements until you find the right element for the list of ingredients: #Once you find the class for the list of ingredients, grab the list: list = doc.css('.components-item') #Now you have a bunch of elements with more HTML and content inside. You need to loop through the elements and puts the content that is each ingredient. list.each do |item| puts item.inner_html end
true
fc695bc83d41373996d64898a22fbfb6c9577855
Ruby
akshay-vishnoi/Advance-Ruby
/e-3/e-3.rb
UTF-8
261
3.421875
3
[]
no_license
#main puts "\nEnter name of the function" func_name = gets.chomp puts "\nEnter 1-line statement for function" func_statement = gets.chomp instance_eval "def #{func_name} #{func_statement} end" puts "\nCalling method: #{func_name}()\n" instance_eval func_name
true
3cde0f2fd527f6e70d517ce9ec7546f8fc7f858e
Ruby
nicoasp/TOP---Ruby-oop-project
/project2/algorythm.rb
UTF-8
4,087
3.4375
3
[]
no_license
=begin Create a set S of the 1296 possible codes (1111, 1112... 6665, 6666) Use check_guess method on code [1, 1, 2, 2] and obtain hint Process 1 Run check_guess method with [1, 1, 2, 2] using every other possible code as solution. Each code that doesn't produce the same hint for [1, 1, 2, 2] as the solution code, take out of the possible solutions set S. Minimax process: For each of 1295 remaining unused codes, for each possible color/white peg score (15 possibilities including * * * *) calculate how many possibilities in S would be eliminated (that means running Process 1) Save as the "score" of that unused code the minimum number of possibilities it might eliminate Choose as next guess one of the highest scoring, if possible belonging to S =end class CodeBreaker attr_accessor :solutions_set, :total_set, :next_guess, :last_hint, :guesses_made attr_reader :solution_code, :possible_hints def initialize @total_set = [] (1..6).each do |n1| (1..6).each do |n2| (1..6).each do |n3| (1..6).each do |n4| @total_set.push([n1, n2, n3, n4]) end end end end @solutions_set = [] (1..6).each do |n1| (1..6).each do |n2| (1..6).each do |n3| (1..6).each do |n4| @solutions_set.push([n1, n2, n3, n4]) end end end end @solution_code = [rand(6)+1, rand(6)+1, rand(6)+1, rand(6)+1] @possible_hints = [["*", "*", "*", "*"], ["*", "*", "*", "o"], ["*", "*", "*"], ["*", "*", "o", "o"], ["*", "*", "o"], ["*", "*"], ["*", "o", "o", "o"], ["*", "o", "o"], ["*", "o"], ["*"], ["o", "o", "o", "o"], ["o", "o", "o"], ["o", "o"], ["o"], []] @next_guess = [1, 1, 2, 2] @total_set.delete(@next_guess) @guesses_made = 1 @last_hint = [] @array_of_scores = [] end def check_guess(code, other_code) hint = [] helper_code = [] helper_solution = [] code.each_with_index do |guess, index| if other_code[index] == guess hint.push("*") else helper_code.push(guess) helper_solution.push(other_code[index]) end end helper_code.each do |color| if helper_solution.include?(color) hint.push("o") helper_solution.delete(color) end end hint end def check_guess_with_solution @last_hint = check_guess(@next_guess, @solution_code) end def choose_guess max_indexes = [] max_score = @array_of_scores.max if max_score == 0 return false end @array_of_scores.each_with_index do |score, index| if score == max_score max_indexes.push(index) end end max_in_solutions = false max_indexes.each do |index| if @solutions_set.include?(@total_set[index]) @next_guess = @total_set[index] @guesses_made += 1 @total_set.delete(@next_guess) max_in_solutions = true return true end end unless max_in_solutions @next_guess = @total_set[max_indexes[0]] @guesses_made += 1 @total_set.delete(@next_guess) end end def delete_impossible_codes unless @last_hint == ["*", "*", "*", "*"] @solutions_set.delete(@next_guess) end @total_set.each do |possible_code| helper_hint = check_guess(@next_guess, possible_code) unless helper_hint == @last_hint @solutions_set.delete(possible_code) end end end def count_potential_deletes @total_set.each do |unused_code| deletes_by_solution = [] @possible_hints.each do |possible_hint| deletes = 0 @solutions_set.each do |possible_code| helper_hint = check_guess(unused_code, possible_code) unless helper_hint == possible_hint deletes += 1 end end deletes_by_solution.push(deletes) end @array_of_scores.push(deletes_by_solution.min) end @array_of_scores end end a = CodeBreaker.new # Use check_guess method on code [1, 1, 2, 2] and obtain hint a.check_guess_with_solution until a.last_hint == ["*", "*", "*", "*"] || a.solutions_set.length == 1 a.delete_impossible_codes a.count_potential_deletes a.choose_guess a.check_guess_with_solution end puts "Finished!" puts "Guesses made: #{a.guesses_made}" puts a.solutions_set.inspect puts a.solution_code.inspect
true
9e33f16312ffd9c785bea6de7a89a2c34bb9de77
Ruby
yokoyamaJP/rubytest
/iterator/main2.rb
UTF-8
514
3.234375
3
[]
no_license
require "./portfolio.rb" require "./account.rb" portfolio = Portfolio.new portfolio.add_account(Account.new("account1", 1000)) portfolio.add_account(Account.new("account2", 2000)) portfolio.add_account(Account.new("account3", 3000)) portfolio.add_account(Account.new("account4", 4000)) portfolio.add_account(Account.new("account5", 5000)) puts "portfolio.any? >3000" puts portfolio.any? { |account| account.balance > 3000 } puts "portfolio.all? >=2000" puts portfolio.all? { |account| account.balance >= 2000 }
true
a029591ec6b06221d9c24713a849655c87d17d3c
Ruby
amundskm/chess
/lib/chess.rb
UTF-8
13,904
3.78125
4
[]
no_license
class Piece # Create a chess peices with a name, # of moves, and color attr_accessor :num_moves, :white_pieces, :black_pieces attr_reader :name, :color, :unicode @@white_pieces = [] @@black_pieces = [] def initialize(name, color, unicode) @name = name @color = color @num_moves = 0 @unicode = unicode @@white_pieces << self if color == 'white' @@black_pieces << self if color == 'black' end def move @num_moves += 1 end def self.get_black_pieces @@black_pieces end def self.get_white_pieces @@white_pieces end end class Board #create a chess board, each space has a name, coordiates, and a piece attr_accessor :piece, :spaces, :children, :parent attr_reader :name, :x, :y, :color def initialize(name, x, y, color) @name = name @x = x @y = y @piece = nil @children = [] @parent = nil @color = color @@spaces << self end def get_touching @touching end def self.empty @@spaces = [] end def add_piece(unit) @piece = unit end def delete @piece = nil end def self.find_space(name) @@spaces.each do |space| return space if space.name === name end end def self.find_space_at(x,y) @@spaces.each do |space| return space if (space.x == x && space.y == y) end end def self.find_piece(piece, color) @@spaces.each do |space| if space.piece != nil return space if (space.piece.name == piece) && (space.piece.color == color) end end end def self.get_spaces @@spaces end end class Chess #create new game of chess def initialize Board.empty build_board build_pieces gameplay end def gameplay while true ['white','black'].each do |player| draw_board while true start, finish = get_input(player) if test_input(start, finish, player) unless check(player) start_space = Board.find_space(start) finish_space = Board.find_space(finish) move_piece(start_space, finish_space) break end else puts "That is not a legal move" end end (player == 'white')? (color = 'black') : (color = 'white') return if checkmate(check(color), color) end end end def build_board 8.times do |y| 8.times do |x| letter = (x + 97).chr space_name = letter + (y+1).to_s if y.even? && x.even? color = '⬜' elsif y.even? && x.odd? color = '⬛' elsif y.odd? && x.odd? color = '⬜' elsif y.odd? && x.even? color = '⬛' end Board.new(space_name, x ,y, color) end end end def build_pieces #add white peices to board Board.find_space('a1').add_piece(Piece.new('rook1', 'white', '♖')) Board.find_space('h1').add_piece(Piece.new('rook2', 'white', '♖')) Board.find_space('b1').add_piece(Piece.new('knight1', 'white', '♘')) Board.find_space('g1').add_piece(Piece.new('knight2', 'white', '♘')) Board.find_space('c1').add_piece(Piece.new('bishop1', 'white', '♗')) Board.find_space('f1').add_piece(Piece.new('bishop2', 'white', '♗')) Board.find_space('d1').add_piece(Piece.new('queen', 'white', '♕')) Board.find_space('e1').add_piece(Piece.new('king', 'white', '♔')) 8.times do |num| letter = (num + 97).chr name = letter + 2.to_s Board.find_space(name).add_piece(Piece.new('pawn', 'white', '♙')) end #add black peices to board Board.find_space('a8').add_piece(Piece.new('rook1', 'black', '♜')) Board.find_space('h8').add_piece(Piece.new('rook2', 'black', '♜')) Board.find_space('b8').add_piece(Piece.new('knight1', 'black', '♞')) Board.find_space('g8').add_piece(Piece.new('knight2', 'black', '♞')) Board.find_space('c8').add_piece(Piece.new('bishop1', 'black', '♝')) Board.find_space('f8').add_piece(Piece.new('bishop2', 'black', '♝')) Board.find_space('d8').add_piece(Piece.new('queen', 'black', '♛')) Board.find_space('e8').add_piece(Piece.new('king', 'black', '♚')) 8.times do |num| letter = (num + 97).chr name = letter + 7.to_s Board.find_space(name).add_piece(Piece.new('pawn', 'black', '♟')) end end def draw_board 8.times do |y| line = '' 8.times do |x| space = Board.find_space_at(x,y) if space.piece != nil line += " #{space.piece.unicode}" else line += " #{space.color}" end end puts line end end def move_piece(start, finish) finish.piece = start.piece start.delete finish.piece.move end def get_input(player) # INPUT: none # OUTPUT: 2 part string array, first part the space the player wants move from, second # part the splace the player wants to move to. while true puts "#{player} what space would you like to move and where" puts "input in the format <space_name> to <space_name>" puts "example: a2 to a3" input= gets.chomp check = input.scan(/(\w)(\d) to (\w)(\d)/).flatten start_string = check[0] + check[1] finish_string = check[2] + check[3] start = Board.find_space(start_string) finish = Board.find_space(finish_string) return start, finish if check.length == 4 puts "what you have entered does not have the correct format. Please try again." end end def test_input(start, finish, player) # INPUT: start = string, name of starting space finish = string, name of ending space # OUTPUT: returns false if it is not a legal move piece = start.piece return false unless piece.color == player if piece.name.include? "pawn" return pawn_move(start, finish) elsif piece.name.include? "rook" return rook_move(start, finish) elsif piece.name.include? "knight" return knight_move(start, finish) elsif piece.name.include? "bishop" return bishop_move(start, finish) elsif piece.name.include? "queen" return queen_move(start, finish) end false end def pawn_move(start, finish) # INPUT: start = starting space, finish = ending space # OUTPUT: boolean if it is a legal move color = start.piece.color x_dist = start.x - finish.x (color == 'white')? (y_dist = finish.y - start.y) : (y_dist = start.y - finish.y) return true if (x_dist == 1) && (y_dist == 1) && (finish.piece) return true if (x_dist == 0) && (y_dist == 2) && (no_jump(start,finish)) && (finish.piece == nil) && (start.piece.num_moves == 0) return true if (x_dist == 0) && (y_dist == 1) && (finish.piece == nil) return false end def rook_move(start, finish) # INPUT: start = starting space, finish = ending space # OUTPUT: boolean if it is a legal move color = start.piece.color x_dist = start.x - finish.x (color == 'white')? (y_dist = finish.y - start.y) : (y_dist = start.y - finish.y) return true if (x_dist == 0) && no_jump(start, finish) && ((finish.piece == nil) ||(finish.piece.color != color)) return true if (y_dist == 0) && no_jump(start, finish) && ((finish.piece == nil) ||(finish.piece.color != color)) return false end def bishop_move(start, finish) # INPUT: start = starting space, finish = ending space # OUTPUT: boolean if it is a legal move color = start.piece.color x_dist = start.x - finish.x (color == 'white')? (y_dist = finish.y - start.y) : (y_dist = start.y - finish.y) return true if (x_dist.abs == y_dist.abs) && no_jump(start, finish) && ((finish.piece == nil) ||(finish.piece.color != color)) return false end def knight_move(start, finish) # INPUT: start = starting space, finish = ending space # OUTPUT: boolean if it is a legal move color = start.piece.color x_dist = start.x - finish.x (color == 'white')? (y_dist = finish.y - start.y) : (y_dist = start.y - finish.y) return true if (x_dist.abs + y_dist.abs == 3) && (x_dist.abs <= 2) && (y_dist.abs <= 2) && ((finish.piece == nil) ||(finish.piece.color != color)) return false end def king_move(start, finish) # INPUT: start = starting space, finish = ending space # OUTPUT: boolean if it is a legal move color = start.piece.color x_dist = start.x - finish.x (color == 'white')? (y_dist = finish.y - start.y) : (y_dist = start.y - finish.y) return true if (x_dist.abs <= 1) && (y_dist.abs <= 1) && ((finish.piece == nil) ||(finish.piece.color != color)) return false end def queen_move(start, finish) # INPUT: start = starting space, finish = ending space # OUTPUT: boolean if it is a legal move color = start.piece.color x_dist = start.x - finish.x (color == 'white')? (y_dist = finish.y - start.y) : (y_dist = start.y - finish.y) return true if (x_dist == 0) && no_jump(start, finish) && ((finish.piece == nil) ||(finish.piece.color != color)) return true if (y_dist == 0) && no_jump(start, finish) && ((finish.piece == nil) ||(finish.piece.color != color)) return true if (x_dist.abs == y_dist.abs) && no_jump(start, finish) && ((finish.piece == nil) ||(finish.piece.color != color)) return false end def no_jump(start, finish) # INPUT: start = starting space, finish = ending space # OUTPUT: boolean if it is a legal move x_dist = (start.x - finish.x).abs + 1 y_dist = (start.y - finish.y).abs + 1 piece_path = [] if x_dist == 0 (start.y..finish.y).each do |y| piece_path << Board.find_space_at(start.x, start.y + y) end elsif y_dist == 0 (start.x..finish.x).each do |x| piece_path << Board.find_space_at(start.x + x, start.y) end elsif y_dist.abs == x_dist.abs (start.x - finish.x >= 0)? (x_move = -1) : (x_move = 1) (start.y - finish.y >= 0)? (y_move = -1) : (y_move = 1) num = x_dist.abs num.times do |move| piece_path << Board.find_space_at(start.x + x_move * move, start.y + y_move*move) end else return false end piece_path.each_with_index do |space, index| if (index != 0) && (index != piece_path.length + 1) if space.piece != nil return false end end end true end def check(color) #INPUTS: color #OUTPUTS: space that has king in check, or false # if the player moves the piece from its current position to the new position, will the king be vulnerable to attack? king = Board.find_piece('king', color) if color == 'white' pieces = Piece.get_black_pieces check_color = 'black' else pieces = Piece.get_white_pieces check_color = 'white' end pieces.each do |piece| space = Board.find_piece(piece.name, check_color) if test_input(space, king, check_color) puts 'game over' return space end end false end def checkmate(check_space, color) #Input: space that has king in check, color of attacking player #output: boolean if game is over or now return false if check_space == false start = check_space finish = Board.find_piece('king', color) x_dist = start.x - finish.x (color == 'white')? (y_dist = finish.y - start.y) : (y_dist = start.y - finish.y) piece_path = [] if x_dist == 0 (start.y..finish.y).each do |y| piece_path << Board.find_space_at(start.x, y) end elsif y_dist == 0 (start.x..finish.x).each do |x| piece_path << Board.find_space_at(x, start.y) end elsif y_dist.abs == x_dist.abs (start.x..finish.x).each do |x| piece_path << Board.find_space_at(x, start.y + (x - start.x)) end end if color == 'white' pieces = Piece.get_white_pieces else pieces = Piece.get_black_pieces end pieces.each do |piece| check = Board.find_piece(piece.name, color) piece_path.each do |space| return false if test_input(check, space, color) end end true end end new_game = Chess.new
true
479f54bf86c095fd1d74fe9f9ca3925258d05f40
Ruby
PD2015/launch_school
/oop/lesson_5/twenty_one2.rb
UTF-8
3,989
3.8125
4
[]
no_license
# ************************** CARD ************************************ class Card attr_reader :value def initialize(value) @value = value end end # ************************** DECK ************************************ class Deck CARD_VALUES = (%w(Ace Jack Queen King ) + (1..10).to_a) * 4 attr_reader :cards def initialize @cards = [] set_new_deck end def set_new_deck CARD_VALUES.each { |value| cards << Card.new(value) } cards.shuffle! end def deal_one cards.pop end end # ************************** M HAND ************************************ module Hand def values cards.map(&:value) end def display_cards joiner(values) end def total sum = 0 values.each do |value| sum += if value == 'Ace' 11 elsif value.to_i == 0 10 else v = value.to_i v end end if sum > 21 values.count { |value| value == 'Ace' }.times do sum -= 10 end end sum end private def joiner(card_values, separator = ',', final_separator= '&') return card_values.join if card_values.size < 2 comma_added_values = card_values.map do |num| num.to_s + separator unless num == card_values[-2, 2] end comma_added_values.pop comma_added_values[-1] = "#{card_values[-2]} #{final_separator} #{card_values.last}" comma_added_values.join(' ') end end # ************************** PARTICIPANT ************************************ class Participant include Hand attr_accessor :cards, :name def initialize(name) @cards = [] @name = name end def hit? total < 17 end def bust? total > 21 end end # ************************** GAME ************************************ class Game attr_accessor :deck, :player, :dealer def initialize @deck = Deck.new @player = Participant.new('Player') @dealer = Participant.new('Dealer') deal_initial_2_cards end def clear system 'clear' end def deal_initial_2_cards 2.times do player.cards << deck.deal_one dealer.cards << deck.deal_one end end def display_welcome_message puts "---- Welcome to Twenty One ----" end def display_participants_hands puts <<-OUTPUT #{player.name} has #{player.display_cards}, total: #{player.total}. #{dealer.name} has #{dealer.values[1]} & an unknown card. OUTPUT end def player_turn answer = '' loop do answer = player_choice(answer) break if answer == 's' player.cards << deck.deal_one clear display_participants_hands break if player.bust? end end def player_choice(answer) loop do puts "Would you like to hit(h) or stick(s)?" answer = gets.chomp.downcase break if ['h', 's'].include?(answer) puts "Sorry thats not a valid choice" end answer end def dealer_turn loop do break if dealer.hit? == false dealer.cards << deck.deal_one break if dealer.bust? end end def display_final_results puts <<-OUTPUT #{player.name} has #{player.display_cards}, total: #{player.total}. #{dealer.name} has #{dealer.display_cards}, total: #{dealer.total}. OUTPUT end def display_winner p = player.total d = dealer.total if p > d && p <= 21 puts "You've Won that round!" elsif p < d && d <= 21 puts "The Dealer Won that round." elsif p < d && p <= 21 puts "You've Won that round! The Dealer went bust." elsif p > 21 puts "Sorry, thats you bust. The dealer Wins that round" elsif p == d puts "That round is a draw!" end end def display_goodbye_message puts "Thanks for playing, catch you later." end def start clear display_welcome_message display_participants_hands player_turn dealer_turn clear display_final_results display_winner display_goodbye_message end end Game.new
true
83e0cda68e4c815fed6cd5380d028d4d7091f8af
Ruby
chris-groves/algorithms
/Own-Algorithms/Most-Frequent-Words/spec/most_frequent_words_spec.rb
UTF-8
1,397
3.109375
3
[]
no_license
require 'most_frequent_words' describe Words do describe 'find most_frequent_words' do it 'returns "cat" for an array with one word' do words = Words.new(["cat"]) expect(words.most_frequent_words(["cat"])).to eq ["cat"] end it 'returns "dog" for an array with three words' do words = Words.new(["cat", "dog", "dog"]) expect(words.most_frequent_words(["cat", "dog", "dog"])).to eq ["dog", "cat"] end it 'returns "dog", "cat" for an array with two words' do words = Words.new(["cat", "dog"]) expect(words.most_frequent_words(["cat", "dog"])).to eq ["cat","dog"] end it 'returns "dog" and "cat" for an array with four words' do words = Words.new(["cat", "dog", "dog", "cat"]) expect(words.most_frequent_words(["cat", "dog", "dog", "cat"])).to eq ["cat", "dog"] end it 'returns "dog" and "cat" for an array with five words' do words = Words.new(["cat", "dog", "dog", "cat", "mouse"]) expect(words.most_frequent_words(["cat", "dog", "dog", "cat", "mouse"])).to eq ["cat", "dog"] end it 'returns "dog" and "cat" for an array with five words' do words = Words.new(["cat", "dog", "dog", "dog", "cat", "mouse", "hamster", "guinea pig"]) expect(words.most_frequent_words(["cat", "dog", "dog", "dog", "cat", "mouse", "hamster", "guinea pig"])).to eq ["dog", "cat"] end end end
true
db9f4120e5b6dc87319ff2ac54f25104115964ef
Ruby
levimllr/sinatra-basic-forms-lab-teacher-onboarding
/models/puppy.rb
UTF-8
266
2.921875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Puppy attr_accessor :name, :breed, :months_old @@all = [] def self.all @@all end def initialize(puppy_hash) @name = puppy_hash[:name] @breed = puppy_hash[:breed] @months_old = puppy_hash[:months_old] @@all << self end end
true
7c5289c6c1d2cd0c409406bccecbb9079a21cc0b
Ruby
olook/chaordic-packr
/lib/chaordic-packr/variant.rb
UTF-8
900
2.8125
3
[]
no_license
require "chaordic-packr/packable_with_info" require 'oj' module Chaordic module Packr # Product variant class Variant attr_accessor :name, :sku, :price, :old_price # @param [String] name Product name. # @param [String] sku Product storage identification. # @param [Numeric] price Product price. # @param [Numeric] old_price Old product price. # @return [Item] def initialize(name, sku = nil, price = nil, old_price = nil) self.name = name.to_s self.sku = sku.to_s if sku self.price = price.to_f if price self.old_price = old_price.to_f if old_price self end # @return [Hash] Hash for variant. def to_hash h = { 'name' => name } h['sku'] = sku if sku h['price'] = price if price h['oldPrice'] = old_price if old_price h end end end end
true
c8cfe59f270126546ec5af6b0d8aaedbb31f4353
Ruby
emaadmanzoor/arguman-scraper
/lib/scraper/scraper.rb
UTF-8
2,078
2.5625
3
[ "MIT" ]
permissive
module Scraper class Scraper def self.get_debates(from, upto, except, verbose, matcher, dry) url = "http://arguman.org/api/v1/arguments/?page=#{from}" loop do puts "\n#{url}" response = HTTParty.get(url) json = response.parsed_response json["results"].each do |res| next if (!dry && Debate[res["id"]]) next if except.include? res["id"].to_i next if res["title"] =~ /[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0-9,.;:\/\s"’'\(\)\%&$£€+\-*_ =!?]/ next if (matcher && !res["title"].include?(matcher)) unless dry user = User.find_or_create(:id=>res["user"]["id"]) do |u| u.id = res["user"]["id"] u.username = res["user"]["username"] end Debate.create do |d| d.id = res["id"] d.title = res["title"] d.user = user end end puts "#{res["title"]} from #{res["user"]["username"]} #{res["id"]}" if verbose end url = json["next"] nextpagenumber = (url.match /page=(\d+)/)[1].to_i break if url.nil? || nextpagenumber > (upto + 1) end end def self.get_arguments(verbose) Debate.dataset.all.each do |d| d.retrieve_arguments(verbose) end end def self.num_debates Debate.dataset.count end def self.build_apxd(dir, ids, &block) if ids.empty? Debate.dataset.each do |d| d.build_apxd_file(dir) yield if block end else ids.each do |id| Debate[id].build_apxd_file(dir) yield if block end end end def self.stats num = Array.new(50) {0} max = 0 Debate.dataset.each do |d| size = d.arguments.size max = size if size > max num[size/10] += 1 end val = [["Max #args", max]] num.each_with_index do |v,it| val << ["#{it*10}-#{(it+1)*10}", v] if v > 0 end val end end end
true
ee03005927d8ee36ff174237559b472a064e8046
Ruby
utarsuno/ruuuby
/lib/ruuuby/math/space/discrete/nucleotide_space.rb
UTF-8
1,809
2.6875
3
[ "MIT" ]
permissive
# encoding: UTF-8 # mathematics related code module ::Math # math related code that can be categorized under +Space+ module Space class NucleotideSpace < ::Math::Space::TypesSpaceⓣ¹ def initialize @space_type = 'types' @symbol = :🧬 @num_dimensions = 1 end def ∋ˢ?(the_obj); the_obj.ⓣ.ancestors.∋?(Singleton); end # @param [Symbol] kclass # @param [Class] owner (default⟶Kernel) # # @return [Boolean] def ∃ᶜ?(kclass, owner=::Kernel) 🛑sym❓('kclass', kclass) 🛑 ::Ruuuby::DescriptiveStandardError.new(self, "provided param owner{#{owner.to_s}} must be a module but received type{#{owner.Ⓣ}}") unless owner.is_a?(::Module) owner.∃const?(kclass) && owner.const_get(kclass).instance_of?(::Class) end # @param [Symbol] kmodule # @param [Module, Class] owner (default⟶Kernel) # # @raise [ArgumentError] # # @return [Boolean] def ∃ᵐ?(kmodule, owner=::Kernel) 🛑sym❓('kmodule', kmodule) 🛑 ::Ruuuby::DescriptiveStandardError.new(self, "provided param owner{#{owner.to_s}} must be a module but received type{#{owner.Ⓣ}}") unless owner.is_a?(::Module) if owner.∃const?(kmodule) c = owner.const_get(kmodule) (c.instance_of?(::Module) && c.class == ::Module) else false end end # @param [Symbol] kmodule # # @raise [ArgumentError] # # @return [Boolean] true, if arg(`kmodule`) was found as a global module def ∃ᴹ?(kmodule); self.∃ᵐ?(kmodule, ::Kernel); end #def ∋?(n); n.nucleotide?; end #def ∌?(n); !(self.∋?(n)); end include ::Singleton end end end
true
66e90a8744fc1ef566ea6efb3ad0e352cf2a1ceb
Ruby
devops-israel/tessera-dsl-plugin
/lib/tessera-api.rb
UTF-8
3,348
2.515625
3
[]
no_license
#!/usr/bin/env ruby require 'net/http' require 'json' require 'time' class Hash def diff(other) (self.keys + other.keys).uniq.inject({}) do |memo, key| unless self[key] == other[key] if self[key].kind_of?(Hash) && other[key].kind_of?(Hash) memo[key] = self[key].diff(other[key]) else memo[key] = [self[key], other[key]] end end memo end end end class TesseraAPI attr_accessor :config, :filter def initialize(configfile = 'etc/tessera-dsl.conf') @config = {} IO.foreach(configfile) do |line| line.chomp! key, value = line.split("=", 2) @config[key.strip.to_sym] = value.strip end end def send_request (method, url, data = nil) uri = URI.parse(@config[:tessera_url] + url) http = Net::HTTP.new(uri.host) request = eval("Net::HTTP::#{method.capitalize}.new('#{uri.request_uri}')") if data request.initialize_http_header({'Content-Type' =>'application/json'}) request.body = data.to_json end response = http.request(request) json = JSON.parse(response.body, {:symbolize_names => true}) json end def get_dashboard (id = nil) dashboard = send_request("get", "/api/dashboard/" + (!id.nil? ? id.to_s : "")) if id dashboard[:definition] = send_request("get", "/api/dashboard/" + id.to_s + "/definition") end dashboard end def method_missing(meth, *args, &block) if meth.to_s =~ /^get_dashboard_by_(.+)$/ run_get_dashboard_by_method($1, *args, &block) else super end end def run_get_dashboard_by_method(attrs, *args, &block) attrs = attrs.split('_and_') conditions = Hash[attrs.zip args.flatten] conditions = Hash[conditions.map { |k,v| [k.to_sym, v] }] dashboards = get_dashboard dashboard = dashboards.select { |d| d.merge(conditions) == d } if !dashboard.empty? dashboard = get_dashboard(dashboard.first[:id]) dashboard[:conditions] = conditions dashboard else return nil end end def create_filter(json) @filter = [] attrs = @config[:identity].split('_and_') attrs.each do |attr| @filter.push(json[attr.to_sym]) end @filter end def update_dashboard(data, *args) dashboard = self.send("get_dashboard_by_#{self.config[:identity]}", args.flatten) if dashboard id = dashboard[:id] conditions = dashboard[:conditions] dashboard.delete(:conditions) %w{creation_date definition_href href id last_modified_date view_href}.each do |param| data[param.to_sym] = dashboard[param.to_sym] end %w{dashboard_href href}.each do |param| data[:definition][param.to_sym] = dashboard[:definition][param.to_sym] end dashboard[:tags].each do |tag| tag.delete(:count) tag.delete(:id) end dashboard[:tags] = dashboard[:tags].map{ |t| t.values }.flatten if data.diff(dashboard) == {} puts "No update is required for #{conditions.to_s}" else puts "Updating #{conditions.to_s}" data[:last_modified_date] = Time.now.utc.iso8601(6) send_request("put", "/api/dashboard/" + id.to_s, data) send_request("put", "/api/dashboard/" + id.to_s + "/definition", data[:definition]) end else create_dashboard(data) end end def create_dashboard(data) puts "Dashboard not found. Creating new one." data[:creation_date] = Time.now.utc.iso8601(6) send_request("post", "/api/dashboard/", data) end end
true
cd9eab7ec9f2d6e704fa2bdafd9f8ea0fe5a0222
Ruby
Mattlk13/maglev
/src/test/github338.rb
UTF-8
1,172
3.46875
3
[]
no_license
require 'socket' server = TCPServer.new "127.0.0.1", 2000 # Server bind to port 2000 output = [] def read_socket_message(socket, chunk_size = 2) buffer = "" while ! buffer.end_with?("\n") IO.select([socket]) buffer << socket.read_nonblock(chunk_size) end buffer end server_thread = Thread.new do loop do client = server.accept # Wait for a client to connect message = read_socket_message(client) output << "Server :: client says: #{message}" if message == "die!\n" output << "Server :: farewell cruel world!" client.close break else client.puts "Hello!" client.close end end end client_thread = Thread.new do socket = TCPSocket.new('127.0.0.1', 2000) socket.puts("ping") response = read_socket_message(socket) output << "Client :: server says: #{response}" socket = TCPSocket.new('127.0.0.1', 2000) socket.puts("die!") end client_thread.join server_thread.join expected = ["Server :: client says: ping\n","Client :: server says: Hello!\n","Server :: client says: die!\n","Server :: farewell cruel world!"] raise "TCPSocket#read_nonblock didn't work" unless output == expected
true
1625332f3a6c496e2d13b88d2e904db12433ffb7
Ruby
justonemorecommit/puppet
/lib/puppet/functions/then.rb
UTF-8
2,620
3.359375
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
# Calls a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) # with the given argument unless the argument is `undef`. # Returns `undef` if the argument is `undef`, and otherwise the result of giving the # argument to the lambda. # # This is useful to process a sequence of operations where an intermediate # result may be `undef` (which makes the entire sequence `undef`). # The `then` function is especially useful with the function `dig` which # performs in a similar way "digging out" a value in a complex structure. # # @example Using `dig` and `then` # # ```puppet # $data = {a => { b => [{x => 10, y => 20}, {x => 100, y => 200}]}} # notice $data.dig(a, b, 1, x).then |$x| { $x * 2 } # ``` # # Would notice the value 200 # # Contrast this with: # # ```puppet # $data = {a => { b => [{x => 10, y => 20}, {not_x => 100, why => 200}]}} # notice $data.dig(a, b, 1, x).then |$x| { $x * 2 } # ``` # # Which would notice `undef` since the last lookup of 'x' results in `undef` which # is returned (without calling the lambda given to the `then` function). # # As a result there is no need for conditional logic or a temporary (non local) # variable as the result is now either the wanted value (`x`) multiplied # by 2 or `undef`. # # Calls to `then` can be chained. In the next example, a structure is using an offset based on # using 1 as the index to the first element (instead of 0 which is used in the language). # We are not sure if user input actually contains an index at all, or if it is # outside the range of available names.args. # # @example Chaining calls to the `then` function # # ```puppet # # Names to choose from # $names = ['Ringo', 'Paul', 'George', 'John'] # # # Structure where 'beatle 2' is wanted (but where the number refers # # to 'Paul' because input comes from a source using 1 for the first # # element). # # $data = ['singer', { beatle => 2 }] # $picked = assert_type(String, # # the data we are interested in is the second in the array, # # a hash, where we want the value of the key 'beatle' # $data.dig(1, 'beatle') # # and we want the index in $names before the given index # .then |$x| { $names[$x-1] } # # so we can construct a string with that beatle's name # .then |$x| { "Picked Beatle '${x}'" } # ) # notice $picked # ``` # # Would notice "Picked Beatle 'Paul'", and would raise an error if the result # was not a String. # # * Since 4.5.0 # Puppet::Functions.create_function(:then) do dispatch :then do param 'Any', :arg block_param 'Callable[1,1]', :block end def then(arg) return nil if arg.nil? yield(arg) end end
true
7fbadcbe814cad13d46dddd997bb7dd689a61905
Ruby
drbarq/MILLENNIAL-TRANSLATION-SERVICE
/app/getdata.rb
UTF-8
636
2.609375
3
[]
no_license
require "pry" require_all "./app" class GetData def self.get_word_definition(word) url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define?term=" #basic URI for the API endpoint @@data = RestClient::Request.execute(method: :get, url: url+word, #api request for the data headers:{ "X-RapidAPI-Host" => "mashape-community-urban-dictionary.p.rapidapi.com", "X-RapidAPI-Key" => "XX" }) @@response = JSON.parse(@@data) end def self.definition(word) @@response["list"][0]["definition"] end def self.word(word) @@response["list"][0]["word"] end end
true
e31ffff84e554811d9f8363e1140ba5ec2574e03
Ruby
DavidPenafiel/ruby_noob2017
/12 lecturareves.rb
UTF-8
604
3.1875
3
[]
no_license
puts "LECTURA NORMAL\n" File.open('12hola').readlines.each do |linea| puts linea end puts "\nINVERTIR DIRECTO EN RECORRIDO" File.open('12hola').readlines.each do |linea| puts linea.reverse end puts "\nUSANDO ARREGLOS PARA INVERTIR EL ORDEN DE LAS LÍNEAS" new_array = [] File.open('12hola').readlines.each do |linea| new_array << linea.chomp #.reverse end puts new_array.reverse puts "\nGUARDADNDO EL ARREGLO EN OTRO DOCUMENTO" file = File.open('12invertido','w') new_array.reverse.each do |linea| file.puts linea end file.close File.open('12invertido').readlines.each do |linea| puts linea end
true
58938f8ea61754cdb7b1c3774628c0c269bde483
Ruby
Nepsaco/ruby-enumerables-hash-practice-green-grocer-lab-denver-web-100719
/grocer.rb
UTF-8
1,443
3.3125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' def consolidate_cart(cart) final_cart = {} cart.each do |element| element_name = element.keys[0] element_values = element.values[0] if final_cart.has_key?(element_name) final_cart[element_name][:count] += 1 else final_cart[element_name] = { count: 1, price: element_values[:price], clearance: element_values[:clearance] } end end final_cart end def apply_coupons(cart, coupons) coupons.each do |coupon| item = coupon[:item] coupon_name = "#{item} W/COUPON" if cart.has_key?(item) if cart[item][:count] >= coupon[:num] if !cart.has_key?(coupon_name) cart[coupon_name] = {price: coupon[:cost] / coupon[:num], clearance: cart[item][:clearance], count: coupon[:num]} else cart[coupon_name][:count] += coupon[:num] end cart[item][:count] -= coupon[:num] end end end cart end def apply_clearance(cart) cart.each do |product, stats| if stats[:clearance] stats[:price] -= stats[:price] * 0.2 end end cart end def checkout(cart, coupons) final_cart = consolidate_cart(cart) applied_coupons = apply_coupons(final_cart, coupons) applied_clearance = apply_clearance(applied_coupons) total = applied_clearance.reduce(0) {|acc, (key,value)| acc += value[:price]*value[:count]} total > 100 ? total * 0.9: total end
true
479f2e4d706ca4a7478393bac9aed376ec54eac4
Ruby
DavidAlexSiler/badges-and-schedules-atlanta-web-060319
/conference_badges.rb
UTF-8
517
3.90625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def badge_maker(name) return "Hello, my name is #{name}." end def batch_badge_creator(array) badges = [] array.each do |name| badges << badge_maker(name) end return badges end def assign_rooms(array) new_arr = [] room = 1 array.each do |name| new_arr << "Hello, #{name}! You'll be assigned to room #{room}!" room +=1 end return new_arr end def printer(array) batch_badge_creator(array).each do |msg| puts msg end assign_rooms(array).each do |msgs| puts msgs end end
true
025032374850332e230086aab956ca6a4141db14
Ruby
adammccormack/bank-tech-test
/lib/account.rb
UTF-8
763
3.546875
4
[]
no_license
class Account DEFAULT_BALANCE = 0 attr_reader :balance, :transactions def initialize @balance = DEFAULT_BALANCE @transactions = [] end def deposit(amount) @balance += amount transactions.push({date: Time.now.strftime("%d/%m/%Y"), amount: amount, balance: balance }) end def withdraw(amount) @balance -= amount transactions.push({date: Time.now.strftime("%d/%m/%Y"), amount: amount, balance: balance }) end def print_statement transactions.each do |element| puts "#{element[:date]} #{element[:amount]} #{element[:balance]}" end end account = Account.new account.deposit(1) account.deposit(1) account.print_statement end
true
c95be306e1354014db619605bdf21527b01713af
Ruby
janice-wong/vitals-platform-code-test
/update_quality.rb
UTF-8
1,435
3.15625
3
[]
no_license
require 'award' class Item attr_reader :quality, :expires_in def initialize(quality, expires_in) @quality, @expires_in = quality, expires_in end def update_award_quality end end class BlueFirst < Item def update_award_quality @quality += 1 @quality += 1 if @expires_in <= 0 @quality = 50 if @quality > 50 @expires_in -= 1 end end class BlueCompare < Item def update_award_quality if @expires_in > 0 @quality += 1 @quality += 1 if @expires_in <= 10 @quality += 1 if @expires_in <= 5 @quality = 50 if @quality > 50 else @quality = 0 end @expires_in -= 1 end end class BlueStar < Item def update_award_quality @quality -= 2 if @expires_in > 0 @quality -= 4 if @expires_in <= 0 @quality = 0 if @quality < 0 @expires_in -= 1 end end class Normal < Item def update_award_quality @quality -= 1 if @expires_in > 0 @quality -= 2 if @expires_in <= 0 @quality = 0 if @quality < 0 @expires_in -= 1 end end CLASS_NAMES = { 'Blue First' => BlueFirst, 'Blue Compare' => BlueCompare, 'Blue Star' => BlueStar, 'Blue Distinction Plus' => Item, 'NORMAL ITEM' => Normal } def update_quality(awards) awards.each do |award| test = CLASS_NAMES[award.name].new(award.quality, award.expires_in) test.update_award_quality award.quality = test.quality award.expires_in = test.expires_in end end
true
d39cdc61ab60777b5988a014e3cd033a043e4334
Ruby
andytinycat/sensu-apihelper
/lib/sensu-apihelper/client.rb
UTF-8
2,116
2.78125
3
[ "MIT" ]
permissive
require 'rest_client' require 'net/http' require 'json' module Sensu module Apihelper # Representation of a Sensu client. class Client attr_accessor :name, :ip, :subscriptions, :last_check_in, :check_statuses # Return all Sensu clients. def self.get_all json = JSON.parse Net::HTTP.get URI($api_url + "/clients") json.map do |client_json| Client.new(client_json) end end # Get a client by name. def self.get_by_name(name) json = JSON.parse Net::HTTP.get URI($api_url + "/clients/#{name}") Client.new(json) end # Create a new Sensu client from the JSON return from the Sensu API. def initialize(json) # Massage into a hash for speed and convenience history_json = JSON.parse Net::HTTP.get URI("#{$api_url}/clients/#{json["name"]}/history") @history_data = Hash[history_json.map { |h| [h["check"], h] }] @name = json["name"] @ip = json["address"] @subscriptions = json["subscriptions"] @last_check_in = json["timestamp"] @json = json @check_statuses = checks.map do |check| CheckStatus.new(self.name, check.name, @history_data) end end def checks checks = @subscriptions.map do |subscription| Check.get_by_subscription(subscription) end checks.flatten end def critical_count @check_statuses.select {|check_status| check_status.critical?}.length end def warning_count @check_statuses.select {|check_status| check_status.warning?}.length end def unknown_count @check_statuses.select {|check_status| check_status.unknown?}.length end def ok_count @check_statuses.select {|check_status| check_status.ok?}.length end # Look up custom client attributes. def [](key) case key.class when Symbol @json[key.to_s] when String @json[key] end end end end end
true
a888933c76e128e82f2c9aea5be9ad493f79b00f
Ruby
arissetyawan-ruby/ewallet
/app/helpers/application_helper.rb
UTF-8
251
2.65625
3
[]
no_license
module ApplicationHelper def you(a, b) "(you)" if a==b end def error_messages_for(obj) res= "<ul>" obj.errors.each do |k, v| res+= "<li>" + k.to_s.humanize + " " + v.humanize.downcase + "</li>" end res += "</ul>" raw(res) end end
true
fc626c1bed8b9b5a16c03ee58bbe0d2ca1cdaf56
Ruby
maxim/sogger
/lib/sogger/question.rb
UTF-8
810
2.90625
3
[ "MIT" ]
permissive
module Sogger class Question include Comparable attr_accessor :attributes def initialize(attributes = {}) @attributes = attributes end def self.from_xml(xml_element) attributes = { :title => xml_element.css('title').text, :url => xml_element.css('id').text, :tags => xml_element.css('category').map{|c| c['term']}, :published => DateTime.parse(xml_element.css('published').text) } new attributes end def title @attributes[:title] end def url @attributes[:url] end def tags @attributes[:tags] end def published @attributes[:published] end def <=>(other) other.published <=> published end end end
true
18cbdf9ae370bfcf6471eb9c8e4b7d603ad7839f
Ruby
ninoseki/codewars
/5kyu/calculating.rb
UTF-8
702
3.4375
3
[]
no_license
# http://www.codewars.com/kata/calculating-with-functions/train/ruby require 'minitest/spec' require 'minitest/autorun' describe 'static example calculations' do it 'test' do assert_equal seven(times(five())), 35 assert_equal four(plus(nine())), 13 assert_equal eight(minus(three())), 5 assert_equal six(divided_by(two())), 3 end end class Object %w[zero one two three four five six seven eight nine].each.with_index do |name, n| define_method(name) do |args = nil| args ? n.send(*args) : n.to_f end end [['plus', :+], ['minus', :-], ['times', :*], ['divided_by', :/]].each do |name, symbol| define_method(name) do |n| [symbol, n] end end end
true
a34d02ac88765379dee0e6af71f00d9fa0a90a35
Ruby
Pavel-Zyryanov/Lessons
/Lesson 9/passenger_car.rb
UTF-8
242
2.671875
3
[]
no_license
# frozen_string_literal: true class PassengerCar < Car validate :id, :presence validate :id, :format, CAR_ID_FORMAT def initialize(id, place) super(id, place) @type = 'Passenger' end def take_place super(1) end end
true
fcf463c19f3e2f67558de1e5cf27c4762c5f44b2
Ruby
yokotaso/cybozu-launch-menu
/cybozu/launch/menu/service/Client.rb
UTF-8
472
2.546875
3
[]
no_license
require 'nokogiri' require 'open-uri' require 'kconv' class Client SAGANO_URL="http://www.bento-sagano.jp/menu/higawari/index.html" TAMAGOYA_URL="http://www.tamagoya.co.jp/menu.html" def initialize(url) @url = url end def self.sagano() return Client.new(self::SAGANO_URL) end def self.tamagoya() return Client.new(self::TAMAGOYA_URL) end def getDocument() return Nokogiri::HTML.parse(open(@url).read.toutf8, nil, 'UTF-8') end end
true
bdbdeaec94d0f238fd8aa6efdb335325aff8a0ff
Ruby
Jeff-Shap/Projects
/VotingSim/working/voting_4.rb
UTF-8
4,470
2.96875
3
[]
no_license
# $politicians = {"jeb" => "rep", "hil" => "dem"} # $voters = {"voter1" => "soc", "voter2" => "tea", "voter3" => "lib", "voter4" => "con", "voter5" => "nuet"} module Vote def speech_roll speech_num = [0,1].sample if speech_num == 0 $speech = $politician_array[0] else $speech = $politician_array[1] end end def vote_roll rand(0..100) end $dem_votes = 0 $rep_votes = 0 def stump_speech(pol_array) $politician_array = pol_array $voter_array.each do |x| case when x[1] == "soc" speech_roll if $speech[1] == "rep" if vote_roll <= 10 puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided to change my vote" $rep_votes = $rep_votes + 1 else puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided not to change my vote" $dem_votes = $dem_votes + 1 end elsif $speech[1] == "dem" if vote_roll <= 90 puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided not to change my vote" $dem_votes = $dem_votes + 1 else puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided to change my vote" $rep_votes = $rep_votes + 1 end end when x[1] == "lib" speech_roll if $speech[1] == "rep" if vote_roll <= 25 puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided to change my vote" $rep_votes = $rep_votes + 1 else puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided not to change my vote" $dem_votes = $dem_votes + 1 end elsif $speech[1] == "dem" if vote_roll <= 75 puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided not to change my vote" $dem_votes = $dem_votes + 1 else puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided to change my vote" $rep_votes = $rep_votes + 1 end end when x[1] == "nuet" speech_roll if $speech[1] == "rep" if vote_roll <= 50 puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided to change my vote" $dem_votes = $dem_votes + 1 else puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided not to change my vote" $rep_votes = $rep_votes + 1 end elsif $speech[1] == "dem" if vote_roll <= 50 puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided not to change my vote" $dem_votes = $dem_votes + 1 else puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided to change my vote" $rep_votes = $rep_votes + 1 end end when x[1] == "con" speech_roll if $speech[1] == "rep" if vote_roll <= 75 puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided not to change my vote" $rep_votes = $rep_votes + 1 else puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided to change my vote" $dem_votes = $dem_votes + 1 end elsif $speech[1] == "dem" if vote_roll <= 25 puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided to change my vote" $dem_votes = $dem_votes + 1 else puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided not to change my vote" $rep_votes = $rep_votes + 1 end end when x[1] == "tea" speech_roll if $speech[1] == "rep" if vote_roll <= 90 puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided not to change my vote" $rep_votes = $rep_votes + 1 else puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided to change my vote" $dem_votes = $dem_votes + 1 end elsif $speech[1] == "dem" if vote_roll <= 10 puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided to change my vote" $dem_votes = $dem_votes + 1 else puts "#{x[0]}: I have seen #{$speech[0]}'s speech, and have decided not to change my vote" $rep_votes = $rep_votes + 1 end end end end end def vote(pol_hash) $politician_array = pol_hash.collect { |k, v| [k,v] } $voter_array = $voters.collect { |k,v| [k,v] } stump_speech($politician_array) print "REP VOTES =",$rep_votes,"\n" ###REMOVE THESE TWO LINES IF BREAK print "DEM VOTES =",$dem_votes end end include Vote # vote_final($politicians)
true
453eb4a862a73d1aff600520cdabde9223d2a928
Ruby
MagicKey23/Hex_Binary_Conversion
/Binary.rb
UTF-8
2,561
3.5625
4
[]
no_license
class Binary # Divide the number by 2. # Get the integer quotient for the next iteration. # Get the remainder for the binary digit. # Repeat the steps until the quotient is equal to 0. BINARY = {0=>0, 1=>1} def value_of_binary(n) return 2**n end def isNegative?(n) if n < 0 true else false end end def is_binary?(decimal) if BINARY.has_key?(decimal) true else false end end def binary(format, isNegative) isNegative ? format[0] = 1 : format[0]= 0 return "0b" + format.join("") end def convert_to_binary(decimal) if self.is_binary?(decimal) return BINARY[decimal].to_s else return self.binary(self.conversion(decimal), self.isNegative?(decimal)) end end def conversion(n) # Divide the number by 2. # Get the integer quotient for the next iteration. # Get the remainder for the binary digit. # Repeat the steps until the quotient is equal to 0. #base case = [n] when n is 1 or 0 #inductive steps n/16 return [n.abs/2] + [n.abs] if BINARY.include?(n.abs) converted =[] remainder = n.abs % 2 converted += [BINARY[remainder]] return (conversion(n.abs/2) + converted) end def convert_binary_to_decimal(n) if n.to_s.length < 2 return n.to_s end check = n.to_s.split("").all? {|i| self.is_binary?(i.to_i)} if check binary = n.to_s.split("").reverse i = binary.length sum = 0 while i >= 0 if binary[i] == "1" value = self.value_of_binary(i) sum += value end i -= 1 end return sum.to_s else return "Not a binary number" end end end # hard code # def conversion(decimal) # converted = [] # stop = false # until stop # if decimal.abs == 0 # stop = true # converted.unshift(decimal.abs % 2) # else # converted.unshift(decimal.abs % 2) # decimal /= 2 # end # end # ary-Hex-Conversion]$ ruby Machine.rb # Please enter the numb # self.isNegative?(decimal) ? converted[0] = 1 : converted[0] = 0 # return converted.join("") # end
true
9f97f5b8aacdafabc7a7d4f649e0405ee2b30db0
Ruby
Hamish-h/codeclan_pub
/specs/customer_spec.rb
UTF-8
959
3
3
[]
no_license
require("minitest/autorun") require("minitest/rg") require_relative("../pub.rb") require_relative("../customer.rb") require_relative("../drink") class CustomerTest < MiniTest::Test def setup @customer = Customer.new("Hamish", 0) @pub = Pub.new("Joe's Drinking Hole", 100) @drink = Drink.new("Joe's Beer", 1) @customer_money = 10 end def test_get_name assert_equal("Hamish", @customer.name()) end def test_count_contents_of_wallet__when_empty assert_equal(0, @customer.wallet()) end def test_count_contents_of_wallet__when_not_empty @customer.add_money_to_wallet(@customer_money) assert_equal(10, @customer.wallet()) end def test_add_money_to_wallet @customer.add_money_to_wallet(@customer_money) assert_equal(10, @customer.wallet()) end def test_pick_drink__fridge_not_empty @pub.add_drink_to_drink_stock(@drink) assert_equal(@drink, @customer.pick_drink(@pub)) end end
true
c659ea7d02f6e67a07fd386d8783e1269d6d4d97
Ruby
aungaungNMK/ruby_learning_for_gold
/chapter 9 Ruby Platform/arrays.rb
UTF-8
483
3.640625
4
[]
no_license
[1,2,3] #Basic array literal [] #empty array [] #arrays are mutable :but this empty array is different. %w[a b c] #['a','b','c'] Array[1,2,3] empty = Array.new nils = Array.new(3) #[nil,nil,nil] copy = Array.new(nils) zoros = Array.new[4,0] #[0,0,0,0] count = Array.new(3){|i| i + 1} #[1,2,3] print a = Array.new(3,'a') #['a','a','a'] print a[0].upcase! #'A' print a #['A','A','A'] print a = Array.new(3){ 'b'} #["b", "b", "b"] print a[0].upcase! puts print a
true
3ef4545d8dd504dd49aa5e677104b9dce3049b00
Ruby
akxs14/jruby_big_decimal
/lib/big_decimal.rb
UTF-8
754
3.4375
3
[ "MIT" ]
permissive
# encoding: utf-8 require 'java' java_import "java.math.BigDecimal" class BigDecimal def +(y) self.add(y) end def -(y) self.subtract(y) end def *(y) self.multiply(y) end def /(y) self.divide(y) end def **(n) n.class == java.math.BigDecimal ? int_n = n.toString.to_i : int_n = n self.pow(int_n) end def %(n) self.remainder(n).abs end def <=(y) self.compareTo(y) <= 0 end def <(y) self.compareTo(y) < 0 end def >=(y) self.compareTo(y) >= 0 end def >(y) self.compareTo(y) > 0 end def ==(y) self.equals(y) end def !=(y) !self.equals(y) end def <=>(y) return 0 if self == y return 1 if self > y return -1 if self < y end end
true
fcc31d8015a214c8bdf4ab0c1f4674ec32e07226
Ruby
nychinn/article-notes
/online-course/odinproject/ruby/exercise/calc.rb
UTF-8
8,843
3.875
4
[]
no_license
# puts "Hours in one year: #{(24 * 356)}" # puts "Minutes in a decade: #{ ((60 * 24) * 356 * 10) }" # puts "Seconds old: #{ ((((28 * 60) * 60) * 24) * 365) } +" # puts "If I am 1298 million seconds old, how old am I? #{ (((1298000000 / 365) / 24) / 60) / 60 }" # puts 'blink ' * 4 # puts '15'.to_f # puts '99.999'.to_f # puts '99.999'.to_i # puts '' # puts '5 is my favorite number!'.to_i # puts 'Who asked you about 5 or whatever?'.to_i # puts 'Your momma did.'.to_f # puts '' # puts 'stringy'.to_s # puts 3.to_i # puts 'Hello there, and what\'s your name?' # name = gets.chomp # puts 'Your name is ' + name + '? What a lovely name!' # puts 'Pleased to meet you, ' + name + '. :)' # puts '' # puts 'What\'s your first name?' # first_name = gets.chomp # puts 'What\'s your middle name?' # middle_name = gets.chomp # puts 'What\'s your last name?' # last_name = gets.chomp # puts 'Good morning, ' + first_name + ' ' + middle_name + ' ' + last_name + '!' # puts 'What\'s your favourite number?' # fave_number = gets.chomp.to_i # new_number = fave_number+=1 # puts 'I much prefer the number ' + new_number.to_s # puts 'hello '.+ 'world' # puts (10.*9).+ 9 # lineWidth = 50 # puts( 'Old Mother Hubbard'.center(lineWidth)) # puts( 'Sat in her cupboard'.center(lineWidth)) # puts( 'Eating her curds an whey,'.center(lineWidth)) # puts( 'When along came a spider'.center(lineWidth)) # puts( 'Which sat down beside her'.center(lineWidth)) # puts('And scared her poor shoe dog away.'.center(lineWidth)) # puts 'What do you want?' # wanted_thing = gets.chomp.upcase # puts 'WHADDAYA MEAN, ' + wanted_thing + '?!?' # lineWidth = 50 # puts ('Table of Contents').center(lineWidth) # puts ('Chapter 1: Numbers').ljust(lineWidth/2) + ('page 1').rjust(lineWidth/2) # puts ('Chapter 2: Letters').ljust(lineWidth/2) + ('page 72').rjust(lineWidth/2) # puts ('Chapter 3: Variables').ljust(lineWidth/2) + ('page 118').rjust(lineWidth/2) # puts(Math::PI) # puts(Math::E) # puts(Math.cos(Math::PI/3)) # puts(Math.tan(Math::PI/4)) # puts(Math.log(Math::E**2)) # puts((1 + Math.sqrt(5))/2) # puts 'Hello, what\'s your name?' # name = gets.chomp # puts 'Hello, ' + name + '.' # if name == 'Chris' # puts 'What a lovely name!' # end # puts 'I am a fortune-teller. Tell me your name:' # name = gets.chomp # if name == 'Chris' # puts 'I see great things in your future' # else # puts 'Your future is... Oh my! Look at the time!' # puts 'I really have to go, sorry!' # end # command = '' # while command != 'bye' # command = gets.chomp # puts command # end # puts 'Come again soon!' # puts 'Hello, what\'s your name?' # name = gets.chomp # puts 'Hello, ' + name + '.' # if (name == 'Chris' or name == 'Katy') # puts 'What a lovely name!' # end # iAmChris = true # iAmPurple = false # iLikeFood = true # iEatRocks = false # puts (iAmChris and iLikeFood) # puts (iLikeFood and iEatRocks) # puts (iAmPurple and iLikeFood) # DEAF GRANDMA PROGRAM # speak = ''; # bye = '' # while bye != 'BYEBYEBYE' # speak = gets.chomp # if speak != speak.upcase # puts 'HUH?! SPEAK UP, SONNY!' # else # random_year = 1930 + rand(20) # puts 'NO, NOT SINCE ' + random_year.to_s # if speak != 'BYE' # bye = '' # elsif speak == 'BYE' # bye = bye + 'BYE' # end # end # end # puts 'BYE HONEY!' # LEAP YEAR PROGRAM # puts 'Please enter a start year:' # starting_year = gets.chomp.to_i # puts 'Please enter an end year:' # ending_year = gets.chomp.to_i # difference = (ending_year - starting_year) + 1 # difference.times do |i| # year = starting_year + i # if year%4 == 0 and (year%100 != 0 or year%400 == 0) # puts year # end # end # names = ['Ada', 'Belle', 'Chris'] # puts names # puts names[0] # puts names[1] # puts names[2] # puts names[3] # languages = ['English', 'German', 'Ruby'] # languages.each do |lang| # puts 'I love ' + lang + '!' # puts 'Don\'t you?' # end # puts 'And let\'s hear it for C++!' # puts '...' # 3.times do # puts 'Hip-Hip-Hooray!' # end # foods = ['artichoke', 'brioche', 'caramel'] # puts foods # puts # puts foods.to_s # puts # puts foods.join(', ') # puts # puts foods.join(' :) ') + ' 8)' # 200.times do # puts [] # end # favourites = [] # favourites.push 'raindrops on roses' # favourites.push 'whiskey on kittens' # puts favourites[0] # puts favourites.last # puts favourites.length # puts favourites.pop # puts favourites # puts favourites.length # sailor_scouts = ['sailor moon', 'sailor mercury', 'sailor jupiter', 'sailor venus', 'sailor mars'] # puts sailor_scouts.sort # alpha_sailor_scouts = Array.new # sailor_scouts.length.times do |i| # end # puts alpha_sailor_scouts # contents = [ ['Chapter 1: Numbers', 'page 1'], ['Chapter 2: Letters', 'page 72'], ['Chapter 3: Variables', 'page 118'] ] # lineWidth = 50 # puts ('Table of Contents').center(lineWidth) # contents.length.times do |i| # puts (contents[i][0]).ljust(lineWidth/2) + (contents[i][1]).rjust(lineWidth/2) # end # def sayMoo numberOfMoos # puts 'mooooo...' * numberOfMoos # 'yellow submarine' # end # x = sayMoo 3 # puts x # def doubleThis num # numTimes2 = num*2 # puts num.to_s+' doubled is '+numTimes2.to_s # end # doubleThis 44 # def ask question # goodAnswer = false # while (not goodAnswer) # puts question # reply = gets.chomp.downcase # if (reply == 'yes' or reply == 'no') # goodAnswer = true # if reply == 'yes' # answer = true # else # answer = false # end # else # puts 'Please answer "yes" or "no".' # end # end # answer # this is what we return # end # puts 'Hello, and thank you for ...' # puts # ask 'Do you like eating tacos?' # ask 'Do you like eating burritos?' # wetsBed = ask 'Do you wet the bed?' # ask 'Do you like eating chimichangas?' # ask 'Do you like eating sopapillas?' # ask 'Do you like eating tamales?' # puts 'Just a few more questions' # ask 'Do you like drinking horchata?' # ask 'Do you like eating flautas?' # puts # puts 'DEBRIEFING' # puts 'Thank you for ...' # puts # puts wetsBed # time = Time.new # the moment i generated this webpage # time2 = time + 60 # one minute later # puts time # puts time2 # puts Time.mktime(2000,1,1) # y2k # puts Time.mktime(1989,7,28,21,50) # day i was born # puts Time.mktime(1989,7,28,21,50) + 1000000000 # when i will be one billion seconds old # def is_number number # if number != number.to_i # puts 'Please enter a number' # else # return number # end # end # def ask question # good_answer = false # while (not good_answer) # puts question # reply = gets.chomp # if reply != reply.to_i.to_s # puts 'Please enter a number' # else # good_answer = true # end # end # return reply # end # year = ask "What year were you born?" # month = ask "What month were you born?" # day = ask "What day were you born?" # birthdays = (((((Time.new - Time.mktime(year.to_i, month.to_i, day.to_i)) / 60) / 60) / 24) / 365).to_i # birthdays.times do |i| # puts (i+1).to_s + ' SPANK!' # end # colourArray = [] # colourHash = {} # colourArray[0] = 'red' # colourArray[1] = 'green' # colourArray[2] = 'blue' # colourHash['strings'] = 'red' # colourHash['numbers'] = 'green' # colourHash['keywords'] = 'blue' # colourArray.each do |colour| # puts colour # end # colourHash.each do |codeType, colour| # puts codeType + ': ' + colour # end # weirdHash = Hash.new # weirdHash[12] = 'monkeys' # weirdHash[[]] = 'emptiness' # weirdHash[Time.new] = 'no time like the present' # class Die # def roll # 1 + rand(6) # end # end # # make dice # dice = [Die.new, Die.new] # # ... roll them # dice.each do |die| # puts die.roll # end # class Die # def initialize # roll # end # def roll # @numberShowing = 1 + rand(6) # end # def cheat number # if ( number.to_s == number.to_i.to_s ) # if ( number > 0 and number < 7 ) # return number # end # end # end # def showing # @numberShowing # end # end # puts Die.new.showing # toast = Proc.new do # puts 'Cheers!' # end # toast.call # doYouLike = Proc.new do |aGoodThing| # puts 'I *really* like '+aGoodThing+'!' # end # doYouLike.call 'chocolate' # doYouLike.call 'ruby' # def doSelfImportantly someProc # puts 'Everybody just HOLD ON! I have something to do...' # someProc.call # puts 'Ok everyone, I\'m done. Go on with what you were doing.' # end # sayHello = Proc.new do # puts 'hello' # end # sayGoodbye = Proc.new do # puts 'goodbye' # end # doSelfImportantly sayHello # doSelfImportantly sayGoodbye def maybeDo someProc if rand(2) == 0 someProc.call end end def twiceDo someProc someProc.call someProc.call end wink = Proc.new do puts '<wink>' end glance = Proc.new do puts '<glance>' end maybeDo wink
true
c549282e41c5ff94437bd151b49bd49e6533b028
Ruby
vifino/Numatron
/modules/utility/ctcp.rb
UTF-8
1,125
2.65625
3
[ "EFL-2.0" ]
permissive
# CTCP replies and... things. # Made by vifino require 'timeout' def ctcpping(usr) @bot.ctcp(usr,"PING")#+Time.now.to_i.to_s+" 12345") isResponse=false t1=Time.now ret="" begin Timeout::timeout(5) do while true do data= @bot.msgtype(@bot.lastline) type = data[0] nick = data[1] chan = data[2] msg = data[3] username = data[4] hostname = data[5] if type=="notice" and nick=usr then#msg.match(/^\x01PING(.*)$\x01/) ret=msg #if tmestmp=msg.strip.gsub(/^PING( *)/,"").to_i then # ret=Time.now.to_i - tmestmp #else # ret=msg #end break end end #return "Returned: #{ret.strip}. #{(Time.now-t1).to_s} Seconds passed." # ....? return "#{(Time.now-t1).to_s} Seconds passed." end rescue => e return "Timeout." end end def ping(args="",nick="",chan="",rawargs="",pipeargs="") if not args.empty? then if args.include? "\#" then return "Only users allowed, no channels." end ctcpping(args.split(" ").first) else ctcpping(nick) end end addCommand("ping",:ping,"CTCP PINGs the user.") addCommand("p",:ping,"CTCP PINGs the user.")
true
b7ddf170bdcf8ec1c20d64b4c2e0018b1db880a4
Ruby
isabeldiazmi/Sopa-de-Letras
/classBoard.rb
UTF-8
1,914
3.546875
4
[]
no_license
class Board def initialize(arr, str, fil, col) @arr = arr @str = str @fil = fil @col = col @mat = complete_board! end def to_s matriz = @str.each_slice(@fil).to_a end def complete_board! arr = @str.split("") matriz = [] #cambia las x a letras aleatorias arr.each do |x| if x == "X" arr[arr.index(x)] = (65 + rand(25)).chr end end #hace la matriz while !arr.empty? matriz << arr.pop(@col) end matriz.reverse! end def imprime @mat.each do |x| x.each do |y| print y.center(10, " ") + "|" end puts " " puts "----".center(88, "-") end end def revisaFilas(word, arr) letras = word.split("") m = 0 resp = false while m < arr.length && resp == false if (letras - arr[m]).empty? resp = true end m += 1 end resp end def revisaColumnas(word, arr) revisaFilas(word, arr.transpose) end def recorreColumnas(lado, arr) p = 0 r = arr.length - 1 aux = [] if lado == "left" while p < arr.length p.times do arr[p] << "" end r.times do arr[p].unshift("") end aux << arr[p] p += 1 r -= 1 end else while p < arr.length r.times do arr[p] << "" end p.times do arr[p].unshift("") end aux << arr[p] p += 1 r -= 1 end end aux end def revisaDiagonales(word, arr) revisaColumnas(word, recorreColumnas("der", arr)) || revisaColumnas(word, recorreColumnas("izq", arr)) end def include?(word) if revisaDiagonales(word, @mat) == true || revisaColumnas(word, @mat) == true || revisaFilas(word, @mat) == true puts "#{word} is included" else puts "#{word} is not included" end end end
true
e7598ea932cfdcdd605360343a4d4942e2615550
Ruby
skilletfan59/learnruby
/09_timer/timer.rb
UTF-8
609
3.71875
4
[]
no_license
class Timer attr_accessor :time_string, :seconds def initialize @seconds = 0 @number = nil @time_string = "00:00:00" end def seconds=(seconds) @seconds = seconds converter(@seconds) end def converter(seconds) @seconds = seconds.to_i hr = @seconds / 3600 min = (@seconds % 3600) / 60 sec = (@seconds % 3600) % 60 hr = padded(hr) min = padded(min) sec = padded(sec) @time_string = "#{hr}:#{min}:#{sec}" end def padded (input) if input.to_s.length == 1 @number = input.to_s.rjust(2, "0") elsif input.to_s.length == 2 @number = input.to_s end @number end end
true
61028067f0f5310485111847f068a9a12a27e43c
Ruby
beesasoh/ruby-alogarithms
/min_jumps.rb
UTF-8
481
3.453125
3
[]
no_license
@memo = {} def min_jumps(arr) len = arr.length return @memo[len] if @memo.key? len return 0 if len < 2 return 1 if arr[0] >= (len + 1) return Float::INFINITY if arr[0].zero? options = [] i = 0 while i < arr[0] options << min_jumps(arr.drop(i + 1)) i += 1 end results = 1 + options.min @memo[len] = results results end puts min_jumps([2, 5, 8, 9, 2, 6, 7, 6, 1, 2, 5,4,5,3,4,5,6,7,8,9, 8, 9, 2, 6, 7, 6, 8, 9, 1, 1, 6, 8, 9, 1, 1, 1]) puts @memo
true
01f1d9292e2fa3ab4cd8f7341d7d12342b205b34
Ruby
kylewatsonstash/scratch
/homework2.rb
UTF-8
269
4.15625
4
[]
no_license
#For all the numbers between 0 and 1000 check to see if #the number is even and print out "yay" if it is, or "boo" if it isn't start = 0 maximum = 10 while start < (maximum + 1) if start.even? puts "yay" elsif start.odd? puts "boo" end start += 1 end
true
0f4ddc74e5b69b4dada327c581c48f9e8704bc2c
Ruby
dmyronuk/ar-exercises
/exercises/exercise_1.rb
UTF-8
481
3.140625
3
[]
no_license
require_relative '../setup' puts "Exercise 1" puts "----------" # Your code goes below here ... s1 = Store.new s1.name = "Burnaby" s1.annual_revenue = 300_000 s1.mens_apparel = true s1.womens_apparel = true s1.save s2 = Store.new({ name: "Richmond", annual_revenue: 1_260_000, mens_apparel: false, womens_apparel: true, }) s2.save s3 = Store.new({ name: "Gastown", annual_revenue: 190_000, mens_apparel: true, womens_apparel: false, }) s3.save puts Store.count
true
c0795d7dc6ff70d35ca678ddad85e187529ca99d
Ruby
contentful/drupal-exporter.rb
/lib/drupal/vocabulary.rb
UTF-8
1,119
2.53125
3
[ "MIT" ]
permissive
module Contentful module Exporter module Drupal class Vocabulary attr_reader :exporter, :config def initialize(exporter, config) @exporter, @config = exporter, config end def save_vocabularies_as_json exporter.create_directory("#{config.entries_dir}/vocabulary") config.db[:taxonomy_vocabulary].each do |vocabulary_row| extract_data(vocabulary_row) end end private def extract_data(vocabulary_row) puts "Saving vocabulary - id: #{vocabulary_row[:vid]}" db_object = map_fields(vocabulary_row) exporter.write_json_to_file("#{config.entries_dir}/vocabulary/#{db_object[:id]}.json", db_object) end def map_fields(row, result = {}) result[:id] = id(row[:vid]) result[:name] = row[:name] result[:description] = row[:description] result[:machine_name] = row[:machine_name] result end def id(vocabulary_id) "vocabulary_#{vocabulary_id}" end end end end end
true
0f179f92bb7b3d97814737ced46e62abe3025c11
Ruby
rouzbeht/AWE
/hangman.rb
UTF-8
287
3.0625
3
[]
no_license
# Rouzbeh T.Sharifabadi word="bicycle"; wrong="" puts output="-------" 7.times do input=gets for i in 0..word.length-1 if input==word[i].chr+"\n" output[i]=word[i].chr check=true end end if not check wrong=wrong+input[0].chr end puts output+" "+"( "+wrong+" )" end
true
3573e316d1c8e0797c2e2af6c8c7176421207d69
Ruby
mess110/ki
/lib/ki/orm.rb
UTF-8
6,969
2.671875
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'singleton' module Ki module Orm #:nodoc: # This singleton class establishes the database connection and CRUD # operations. # # == Connecting # # Db.instance.establish_connection # # == Queries # # db = Db.instance # db.find 'users', {} # db.find 'users', { name: 'Homer' } # class Db include Singleton attr_reader :config, :connection, :db # Creates the mongo connection. # # It first checks if the env variable "MONGODB_URI" is set. The required # format: http://docs.mongodb.org/manual/reference/connection-string/ # # If the env variable is not set, it will use the information stored in # config.yml. # def establish_connection Mongo::Logger.logger.level = Logger::FATAL # Mongo::Logger.logger = Logger.new('mongo.log') # Mongo::Logger.logger.level = Logger::INFO @config = KiConfig.instance.database @db = if ENV['MONGODB_URI'] Mongo::Client.new else Mongo::Client.new('mongodb://' + connection_string) end self end def connection_string db = KiConfig.instance.database if ENV['MONGODB_URI'] ENV['MONGODB_URI'] else "#{db['host']}:#{db['port']}/#{db['name']}" end end # ==== Returns # # An array of all the collection names in the database. # def collection_names @db.collection_names.delete_if { |name| name =~ /^system/ } end # Insert a hash in the database. # # ==== Attributes # # * +name+ - the mongo collection name # * +hash+ - the hash which will be inserted # # ==== Returns # # The inserted hash. # # * +:conditions+ - An SQL fragment like "administrator = 1" # # ==== Examples # # db = Db.instance # db.insert 'users', { name: 'Homer' } # def insert(name, hash) item = @db[name].insert_one(hash) hash['id'] = item.inserted_id.to_s hash end # Find a hash in the database # # ==== Attributes # # * +name+ - the mongo collection name # # ==== Options # # * +:hash+ - Filter by specific hash attributes # # ==== Returns # # An array of hashes which match the query criteria # # ==== Examples # # db = Db.instance # db.find 'users' # db.find 'users', { id: 'id' } # db.find 'users', { name: 'Homer' } # def find(name, hash = {}) hash = nourish_hash_id hash a = nourish_regex hash hash = a[0] a = nourish_hash_limit hash hash = a[0] limit = a[1] a = nourish_hash_sort hash hash = a[0] sort = a[1] @db[name].find(hash, limit).sort(sort).to_a.stringify_ids end # Update a hash from the database # # The method will update the hash obj with the id specified in the hash # attribute. # # ==== Attributes # # * +name+ - the mongo collection name # * +hash+ - requires at least the id of the hash which needs to be # updated # # ==== Returns # # The updated hash # # ==== Examples # # db = Db.instance # db.update('users', { id: 'id', name: 'Sir Homer' }) # def update(name, hash) hash = nourish_hash_id hash id = hash['_id'].to_s hash.delete('_id') @db[name].update_one({ '_id' => BSON::ObjectId(id) }, hash) hash['id'] = id hash end # Deletes a hash from the database # # ==== Attributes # # * +name+ - the mongo collection name # * +:hash+ - Filter by specific hash attributes. id required # # ==== Returns # # Empty hash # # ==== Examples # # db = Db.instance # db.delete 'users', { id: 'id' } # db.delete 'users', {} # def delete(name, hash) hash = nourish_hash_id hash r = @db[name].delete_many hash { deleted_item_count: r.documents[0]['n'] } end # Count the number of hashes found in a specified collection, filtered # by a hash attribute # # ==== Attributes # # * +name+ - the mongo collection name # # ==== Options # # * +hash+ - used for filtering # # ==== Returns # # The number of objects found. # # ==== Examples # # db = Db.instance # db.count 'users' # db.count 'users', { name: 'Homer' } # def count(name, hash = {}) @db[name].count hash end private def nourish_hash_id(hash) hash = { '_id' => BSON::ObjectId(hash) } if hash.class == String if hash['id'] hash['_id'] = hash['id'] hash.delete('id') end if hash['_id'].class == String hash['_id'] = BSON::ObjectId(hash['_id'].to_s) end hash end # TODO: write tests # http://api.mongodb.com/ruby/current/Mongo/Collection.html#find-instance_method # # really need to work on hash_with_indifferent access # if you change how you access the symbol you will have a bad time def nourish_hash_limit(hash) tmp = {} if hash['__limit'] tmp[:limit] = hash['__limit'].try(:to_i) hash.delete('__limit') end if hash['__skip'] tmp[:skip] = hash['__skip'].try(:to_i) hash.delete('__skip') end [hash, tmp] end def nourish_regex(hash) tmp = {} %w(__regex __regexi).each do |key| if hash[key] hash[key] = [hash[key]] if !hash[key].is_a?(Array) hash[key].each do |target| hash[target] = Regexp.new hash[target], key == '__regexi' ? Regexp::IGNORECASE : nil end hash.delete(key) end end [hash, tmp] end # TODO: write tests def nourish_hash_sort(hash) tmp = {} if hash['__sort'] if hash['__sort'].class != Hash tmp = {} else # TODO: validate for size and number of elements # TODO: validate value # TODO: handle sorting by id hash['__sort'].to_a.each do |e| # asc/desc for some reason don't work on all versions e[1] = -1 if e[1] == '-1' e[1] = 1 if e[1] == '1' tmp[e[0].to_sym] = e[1] end end hash.delete('__sort') end [hash, tmp] end end end end
true
ebdf34ccdfa51f94462106eb9358e497f9e8cdaa
Ruby
midorirestani/validacao-verificacao-software
/Ex7 - FIRST test principles/lib/boleto.rb
UTF-8
1,235
3.28125
3
[]
no_license
require 'active_support/all' require 'cpf_utils' class Boleto attr_accessor :value, :cpf, :name, :expiration_date def initialize(value, name, cpf) @value = value @name = assign_name(name) @cpf = validate_assign(cpf) end def self.next_business_day tomorrow = Time.current.tomorrow.noon next_monday = Time.current.next_week.monday.noon tomorrow.wday.between?(1, 5) ? @expiration_date = tomorrow : @expiration_date = next_monday return @expiration_date end def self.next_month_business_day(expiration_date) next_month = expiration_date.next_month.noon next_month_monday = expiration_date.next_month.next_week.monday.noon next_month.wday.between?(1,5) ? next_month : next_month_monday end def self.validate_and_assign_cpf(cpf) if CpfUtils.valid_cpf?(cpf) @cpf = cpf.to_cpf_format else raise "O CPF é inválido" end end def self.assign_name(name) if !name.nil? or name.length > 0 @name = name else raise "Nome inválido" end end end
true
10db568210b69214e446db828c396d853d68596f
Ruby
nico24687/reunion
/test/activity_test.rb
UTF-8
1,502
3.0625
3
[]
no_license
require 'minitest' require 'minitest/autorun' require 'minitest/pride' require './lib/activity' require 'pry' class ActivityTest < Minitest::Test def test_activity_has_attributes activity = Activity.new("hiking") assert_equal "hiking", activity.name end def test_activity_has_no_participants_by_default activity = Activity.new("hiking") assert_equal({}, activity.participants) end def test_activity_can_add_participant activity = Activity.new("hiking") activity.add_participant("Nico", 10) assert_equal({"Nico" => 10}, activity.participants) end def test_can_add_multiple_participants_to_activity activity = Activity.new("hiking") activity.add_participant("Nico", 10) activity.add_participant("Lorenzo", 20) assert_equal 2, activity.participants.count end def test_can_evaluate_total_cost_of_activity activity = Activity.new("hiking") activity.add_participant("Nico", 10) activity.add_participant("Lorenzo", 20) assert_equal 30, activity.total_cost end def test_can_split_cost_of_activity activity = Activity.new("hiking") activity.add_participant("Nico", 10) activity.add_participant("Lorenzo", 20) assert_equal 15, activity.split end def test_can_calculate_amount_owed activity = Activity.new("hiking") activity.add_participant("Nico", 10) activity.add_participant("Lorenzo", 20) assert_equal({"Nico" => 5, "Lorenzo" => -5}, activity.owe) end end
true
2531923a08dbb4afe926479344d8aaa023b36882
Ruby
tiyd-ror-2016-06/sinatra-todos
/script.rb
UTF-8
1,238
3.171875
3
[]
no_license
require 'httparty' require 'pry' class MyApi attr_reader :headers, :url def initialize url @url = url end def login_as username @headers = { "Authorization" => username } end def list_items make_request :get, "/list" end def add_new_item title make_request :post, "/list", body: { title: title } end def mark_complete title make_request :patch, "/list", query: { title: title } end def make_request verb, endpoint, options={} options[:headers] = headers # TODO: improve? if options[:body].is_a?(Hash) || options[:body].is_a?(Array) options[:body] = options[:body].to_json end r = HTTParty.send verb, "#{url}#{endpoint}", options if r.code >= 400 && r.code < 600 raise "There was an error (#{r.code}) - #{r}" end r end end api = MyApi.new "https://tiy-sinatra-todo.herokuapp.com" # api = MyApi.new "http://localhost:4567" puts "Welcome to the TODO manager" puts "What is your username? > " # username = gets.chomp api.login_as "jdabbs" binding.pry # puts "Your current todo list" # api.list_items.each do |item| # puts "* #{item}" # end # # puts "What would you like to add?" # title = gets.chomp # api.add_new_item title puts "Done"
true
a3bf9a7ea56448dec8c97776f3e96e5f6688ef09
Ruby
Mo7amed178/amex-week_07-day_03-Ruby_Classes
/Answer.rb
UTF-8
455
3.765625
4
[]
no_license
class Masameer attr_reader :location attr_accessor :name def initialize (name, location) @name = name @location = location end def driving_speed puts "180kph" end def destination puts "In #{location}" end def speak puts "ummmmm" end end mouse = Masameer.new("Mouse" , "Ryiadh") mouse.destination mouse.driving_speed mouse.speak mouse.name = "Dog" puts mouse.name
true
a436a4db83e7654386c481d5671331d71f7ee214
Ruby
Mattackai/RB_101
/Exercises/small_problems_RB101-RB109/easy5_7.rb
UTF-8
370
3.375
3
[]
no_license
def word_sizes(string) result = Hash.new(0) string = string.gsub(/[^a-z ]/i, '').squeeze(' ') array = string.split array.each do |word| result[word.size] += 1 end result end print word_sizes('Four score and seven.') print word_sizes('Hey diddle diddle, the cat and the fiddle!') print word_sizes("What's up doc?") print word_sizes('')
true
0607e2b33ef2e3f2fba37530f7c2a69aa76c0ea0
Ruby
masterraf21/GoEat
/lib/GoEat/peta.rb
UTF-8
2,878
3.328125
3
[ "MIT" ]
permissive
module GoEat class Randomize def self.random_coordinate(obj, a, b) # obj is an object that has coordinate attribute. a and b is the interval obj.coordinate.x = rand(a..b) obj.coordinate.y = rand(a..b) end end class Travel def self.distance(loc_a, loc_b) # loc_a and loc_b is object that has coordinate attr # this method works as a distance counter and will return distance from point a to point b # the counting wil use the basic formula of distance of two points # by using the Integer.sqrt method that floor the value to greater-less dist_x = (loc_a.coordinate.x - loc_b.coordinate.x) dist_y = (loc_a.coordinate.y - loc_b.coordinate.y) dist = dist_x ** 2 + dist_y ** 2 return Integer.sqrt(dist) end def self.driver_route(user, driver, store) # This method will generate driver's route # from driver -> store -> user # complete with its steps end def self.route(loc_a, loc_b) # this method will generate step by step route # completing the travel_to method end def self.travel_to(loc_a, loc_b) # this method will generate end end class Position # This class handle positioning guide # such as selecting driver nearest a store def self.select_driver(driver_book, store) # This method is expected to return a driver object # after selecting the nearest one with the store end end class Maps attr_accessor :map_array attr_reader :width attr_reader :height # initialize the map with specified width and height def initialize(width, height) @width = width @height = height end def generate_map # Map will be generated with default value 0 for every region @map_array = Array.new(@width) {Array.new(@height, 0)} end def add_to_map(obj) # add specified value to map according to the type of the object # method will add values # 0 : default. 1 : User, 2 : Driver, 3 : Store x = obj.coordinate.x y = obj.coordinate.y if (obj.class == User) @map_array[x][y] = 1 elsif (obj.class == Driver) @map_array[x][y] = 2 else #obj.class == Store @map_array[x][y] = 3 end end def add_book_to_map(object_book) # This method will ad an array consist of objects # to the current map initialized object_book.each do |val| if (val.class == User) @map_array[val.coordinate.x][val.coordinate.y] = 1 elsif (val.class == Driver) @map_array[val.coordinate.x][val.coordinate.y] = 2 else #obj.class == Store @map_array[val.coordinate.x][val.coordinate.y] = 3 end end end def draw_map # not implemented yet # but the idea is to end end end
true
4cd156bafe0fcb033650b3071d4f9aa74bb15bee
Ruby
hervit0/eclair-ruby
/sudoku/model/sudoku.rb
UTF-8
4,758
2.9375
3
[]
no_license
#Sudoku solver input_example = [ ["x","x","x","x",7,"x","x","x","x"], ["x","x","x","x","x","x",9,"x",1], ["x","x",8,1,"x","x",2,4,3], ["x","x",9,"x","x",5,"x",2,"x"], [2,"x","x","x","x",7,"x","x",8], ["x","x","x",6,4,"x","x",5,"x"], ["x",2,4,"x","x","x","x","x","x"], ["x","x",1,7,"x",4,"x","x",5], ["x",5,6,"x",9,"x","x",1,"x"]] input_blank = Array.new(9, Array.new(9, "x")) def grid_generator(name, feed) input_file = File.open("#{name}.txt", 'w') 9.times do |x| 9.times do |y| input_file.write(feed[x][y]) if y == 2 || y == 5 input_file.write("\t") input_file.write("*") end input_file.write("\t") end if x == 2 || x == 5 input_file.write("\n") input_file.write("*"*82) end input_file.write("\n") end input_file.close end input_name = "input_grid_#{Time.now}" grid_generator(input_name, input_example) p "Grid was generated, see #{input_name}.txt." p "Please indicate x for each blank." p "Press Enter to confirm the solving of the grid." gets p "Grid to solve has been stored in #{input_name}.txt." input_user = File.readlines("#{input_name}.txt").map{|x| x.chomp.split("\t").delete_if{|x| x.include?("*")}}.reject(&:empty?) #Insert here test for grid conformity # 3 primary rules # file blank with "x" input = input_user main_grid = input.map{|i| i.map{|e| (e == "x" ? (1..9).to_a : [e.to_i]) }} # x is the index of row # y is the index of column t = {} 9.times do |x| 9.times do |y| t.store([x, y], main_grid[x][y]) end end def what_subgrid(cell) if cell[0] <= 2 horizontal = [1, 2, 3] elsif cell[0] >= 6 horizontal = [7, 8, 9] else horizontal = [4, 5, 6] end if cell[1] <= 2 vertical = [1, 4, 7] elsif cell[1] >= 6 vertical = [3, 6, 9] else vertical = [2, 5, 8] end (horizontal&vertical)[0] end def subgrid_other_cells(grid, cell) subgrid = what_subgrid(cell) case subgrid when 1 return grid.select{ |k, v| (k != cell)and(k[0].between?(0, 2))and(k[1].between?(0, 2)) } when 2 return grid.select{ |k, v| (k != cell)and(k[0].between?(0, 2))and(k[1].between?(3, 5)) } when 3 return grid.select{ |k, v| (k != cell)and(k[0].between?(0, 2))and(k[1].between?(6, 8)) } when 4 return grid.select{ |k, v| (k != cell)and(k[0].between?(3, 5))and(k[1].between?(0, 2)) } when 5 return grid.select{ |k, v| (k != cell)and(k[0].between?(3, 5))and(k[1].between?(3, 5)) } when 6 return grid.select{ |k, v| (k != cell)and(k[0].between?(3, 5))and(k[1].between?(6, 8)) } when 7 return grid.select{ |k, v| (k != cell)and(k[0].between?(6, 8))and(k[1].between?(0, 2)) } when 8 return grid.select{ |k, v| (k != cell)and(k[0].between?(6, 8))and(k[1].between?(3, 5)) } when 9 return grid.select{ |k, v| (k != cell)and(k[0].between?(6, 8))and(k[1].between?(6, 8)) } end end def row_other_cells(grid, cell) grid.select { |key, value| (key != cell)and(key[0] == cell[0]) } end def column_other_cells(grid, cell) grid.select { |key,value| (key != cell)and(key[1] == cell[1]) } end def figure(hash) hash.select{ |k,v| (v.length == 1)}.values end def epured_cell(grid, cell) if grid[cell].length == 1 return grid[cell] end base = (1..9).to_a authorized_figures_subgrid = base - subgrid_other_cells(grid, cell).values.flatten.uniq.sort authorized_figures_row = base - row_other_cells(grid, cell).values.flatten.uniq.sort authorized_figures_column = base - column_other_cells(grid, cell).values.flatten.uniq.sort if authorized_figures_subgrid.length == 1 authorized_figures_subgrid elsif authorized_figures_row.length == 1 authorized_figures_row elsif authorized_figures_column.length == 1 authorized_figures_column else impossible_figures = (figure(row_other_cells(grid, cell)) + figure(column_other_cells(grid, cell)) + figure(subgrid_other_cells(grid, cell))).flatten grid[cell] - impossible_figures end end n_ini = 0 def solving_sudoku(grid, n) solving_grid = {} 9.times do |x| 9.times do |y| solving_grid.store([x,y], epured_cell(grid, [x, y])) end end n_iter = n + 1 p n p solving_grid.values.flatten.length if n_iter > 20 p "Unsolved after #{n_iter} iterations." exit end unless solving_grid.values.flatten.length == 81 solving_sudoku(solving_grid, n_iter) else [solving_grid, n_iter] end end output = main_grid.clone output_grid = solving_sudoku(t, n_ini) 9.times do |x| 9.times do |y| output[x][y] = output_grid[0][[x,y]][0] end end #Insert here test for grid conformity # 3 primary rules output_name = "output_grid_#{Time.now}" grid_generator(output_name, output) p "Solved after #{output_grid[1]} iterations, see #{output_name}.txt."
true
f55aad6c4f557a13c451e1ddd7ac09f862875fdc
Ruby
waltershub/W1D5-walter-shub-Chris-Hakos
/Knights's_Travails.rb
UTF-8
550
2.953125
3
[]
no_license
require 'byebug' require_relative '00_tree_node.rb' class KnightPasthFinder attr_reader :start_pos attr_accessor :postion :root_node def initialize(postion = []) @start_pos = postion @visted_postions = [start_pos] build_move_tree end def new_move_postion(pos) end def build_move_tree self.root_node = PolyTreeNode.new(start_pos) end private MOVES = [ [-2, -1], [-2, 1], [-1, -2], [-1, 2], [ 1, -2], [ 1, 2], [ 2, -1], [ 2, 1] ] self.valid_moves(pos) end end
true
ae355c1f114881aecb814b4eb5d0c1dada8c1ebd
Ruby
jaw6/fastly_nsq
/lib/fastly_nsq/listener.rb
UTF-8
1,328
2.734375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'fastly_nsq/message' module FastlyNsq class Listener def self.listen_to(**args) new(**args).go end def initialize(topic:, processor:, channel: nil, consumer: nil, **options) @topic = topic @processor = processor @consumer = consumer || FastlyNsq::Consumer.new(topic: topic, channel: channel) @logger = options.fetch :logger, FastlyNsq.logger @preprocessor = options[:preprocessor] end def go(run_once: false) exit_on 'INT' exit_on 'TERM' loop do next_message do |message| log message preprocess message processor.process message end break if run_once end consumer.terminate end private attr_reader :topic, :consumer, :preprocessor, :processor, :logger def log(message) logger.info "[NSQ] Message Received: #{message}" if logger end def next_message message = consumer.pop # TODO: consumer.pop do |message| result = yield FastlyNsq::Message.new(message.body) message.finish if result end def preprocess(message) preprocessor.call(message) if preprocessor end def exit_on(signal) Signal.trap(signal) do consumer.terminate exit end end end end
true
4892d0b0f0859eba18d65869f67c3f3c67d05247
Ruby
spectra-music/mutagen-ruby
/lib/mutagen/id3/id3data.rb
UTF-8
26,689
2.6875
3
[ "MIT" ]
permissive
require 'mutagen/metadata' require 'mutagen/util' module Mutagen module ID3 # A file with an ID3v2 tag. class ID3Data < Mutagen::Metadata include Mutagen::Util::DictProxy V24 = Gem::Version.new '2.4.0' V23 = Gem::Version.new '2.3.0' V22 = Gem::Version.new '2.2.0' V11 = Gem::Version.new '1.1' # @return [Gem::Version] the ID3 tag version attr_reader :version # @return [Fixnum] the total size of the ID3 tag, including the header attr_reader :size # @return [Hash] raw frame data of any unknown frames found attr_reader :unknown_frames # @return [Bool] turn verbose reporting on or off attr_accessor :pedantic def initialize(*args, ** kwargs) @version = V24 @filename, @crc, @unknown_version = nil @size, @flags, @readbytes = 0, 0, 0 @pedantic = true @unknown_frames = [] super(*args, ** kwargs) if block_given? yield self self.save end end def fullread(size) unless @fileobj.nil? raise Mutagen::Util::ValueError, "Requested bytes (#{size}) less than zero" if size < 0 if size > @fileobj.size raise EOFError, ('Requested %#x of %#x (%s)' % [size.to_i, @fileobj.size, @filename]) end end data = @fileobj.read size raise EOFError if not data.nil? and data.size != size @readbytes += size data end # Load tags from a filename # # @param filename [String] filename to load tag data from # @param known_frames [Hash] hash mapping frame IDs to Frame objects # @param translate [Bool] Update all the tags to ID3v2.3/4 internally. If you # intend to save, this must be true or you have to call # update_to_v23 / update_to_v24 manually. # @param v2_version [Fixnum] the minor version number of v2 to use def load(filename, known_frames: nil, translate: true, v2_version: 4) raise ArgumentError, 'Only 3 and 4 possible for v2_version' unless [3, 4].include? v2_version @filename = case filename when Hash; filename[:filename] else filename end @known_frames = known_frames @fileobj = File.open(@filename, 'r') begin load_header rescue EOFError @size = 0 raise ID3NoHeaderError, "#{@filename} too small (#{@fileobj.size} bytes)" rescue ID3NoHeaderError, ID3UnsupportedVersionError => err @size = 0 begin @fileobj.seek(-128, IO::SEEK_END) rescue Errno::EINVAL raise err else frames = Mutagen::ID3.parse_ID3v1(@fileobj.read(128)) if frames.nil? raise err else @version = V11 frames.values.each { |v| add v } end end else frames = @known_frames if frames.nil? if V23 <= @version frames = Frames elsif V22 <= @version frames = Frames_2_2 end end data = fullread(@size - 10) read_frames(data, frames) do |frame| if frame.is_a? ParentFrames::Frame add frame else @unknown_frames << frame end end @unknown_version = @version ensure @fileobj.close @fileobj = nil @filesize = nil if translate (v2_version == 3) ? update_to_v23 : update_to_v24 end end end # Return all frames with a given name (the list may be empty). # # This is best explained by examples:: # # id3.getall('TIT2') == [id3['TIT2']] # id3.getall('TTTT') == [] # id3.getall('TXXX') == [TXXX.new(desc='woo', text='bar'), # TXXX.new(desc='baz', text='quuuux'), ...] # # Since this is based on the frame's hash_key, which is # colon-separated, you can use it to do things like # ``getall('COMM:MusicMatch')`` or ``getall('TXXX:QuodLibet:')``. def get_all(key) if has_key? key [self[key]] else key += ':' each_pair.map { |s, v| v if s.start_with? key }.compact end end # Delete all tags of a given kind; see getall. def delete_all(key) if has_key? key delete key else key += ':' keys.select { |s| s.start_with? key }.each do |k| delete k end end end # Delete frames of the given type and add frames in 'values' def set_all(key, values) delete_all key values.each do |tag| self[tag.hash_key] = tag end end # Return tags in a human-readable format. # # "Human-readable" is used loosely here. The format is intended # to mirror that used for Vorbis or APEv2 output, e.g. # # ``TIT2=My Title`` # # However, ID3 frames can have multiple keys: # # ``POPM=user@example.org=3 128/255`` def pprint # based on Frame.pprint (but we can't call unbound methods) values.map { |v| Frame.pprint(v) }.sort.join("\n") end # @deprecated use the add method def loaded_frame(tag) warn '[DEPRECATION] `loaded_frame` is deprecated. Please use `add` instead.' # turn 2.2 into 2.3/2.4 tags tag = tag.class.superclass.new(tag) if tag.class.to_s.size == 3 self[tag.hash_key] = tag end # add = loaded_frame (and vice versa) break applications that # expect to be able to override loaded_frame (e.q. Quod Libet) # as does making loaded _frame call add # Add a frame to the tag def add(tag) # turn 2.2 into 2.3/2.4 tags if tag.class.name.split('::').last.length == 3 tag = tag.class.superclass.new(tag) end self[tag.hash_key] = tag end def load_header data = fullread(10) id3, vmaj, vrev, flags, size = data.unpack('a3C3a4') @flags = flags @size = BitPaddedInteger.new(size).to_i + 10 @version = Gem::Version.new "2.#{vmaj}.#{vrev}" raise ID3NoHeaderError, "#{@filename} doesn't start with an ID3 tag" unless id3 == "ID3" raise ID3UnsupportedVersionError, "#{@filename} ID3v2.#{vmaj} not supported" unless [2, 3, 4].include? vmaj if pedantic raise Mutagen::Util::ValueError, "Header size not synchsafe" unless BitPaddedInteger.has_valid_padding(size) if V24 <= @version and (flags & 0x0f > 0) raise Mutagen::Util::ValueError, ("#{@filename} has invalid flags %#02x" % [flags]) elsif (V23 <= @version and @version < V24) and (flags & 0x1f > 0) raise Mutagen::Util::ValueError, ("#{@filename} has invalid flags %#02x" % [flags]) end end if f_extended != 0 extsize = fullread 4 if not extsize.nil? and Frames.constants.include? extsize.to_sym # Some tagger sets the extended header flag but # doesn't write an extended header; in this case, the # ID3 data follows immediately. Since no extended # header is going to be long enough to actually match # a frame, and if it's *not* a frame we're going to be # completely lost anyway, this seems to be the most # correct check. # http://code.google.com/p/quodlibet/issues/detail?id=126 @flags ^= 0x40 @extsize = 0 @fileobj.seek(-4, IO::SEEK_CUR) @readbytes -= 4 elsif @version >= V24 # "Where the 'Extended header size' is the size of the whole # extended header, stored as a 32 bit synchsafe integer." @extsize = BitPaddedInteger.new(extsize).to_i - 4 if pedantic unless BitPaddedInteger.has_valid_padding(extsize) raise Mutagen::Util::ValueError, 'Extended header size not synchsafe' end end else # "Where the 'Extended header size', currently 6 or 10 bytes, # excludes itself." @extsize = extsize.unpack('L>')[0] end if not @extsize.nil? and @extsize > 0 @extdata = fullread(@extsize) else @extdata = "" end end end def determine_bpi(data, frames, empty: "\x00" * 10) if @version < V24 return Integer end # have to special case whether to use bitpaddedints here # spec says to use them, but iTunes has it wrong # count number of tags found as BitPaddedInt and how far past o = 0 asbpi = 0 flag = true while o < (data.size - 10) part = data[o...o+10] if part == empty bpioff = -((data.size - o) % 10) flag = false break end name, size, flags = part.unpack('a4L>S>') size = BitPaddedInteger.new size o += 10 + size.to_i if frames.constants.include? name.to_sym asbpi += 1 end end if o >= (data.size - 10) and flag bpioff = o - data.size end # count number of tags found as int and how far past o = 0 asint = 0 flag = true while o < (data.size - 10) part = data[o...o + 10] if part == empty intoff = -((data.size - o) % 10) flag = false break end name, size, flags = part.unpack('a4L>S>') o += 10 + size if frames.constants.include? name.to_sym asint += 1 end end if o >= (data.size - 10) and flag intoff = o - data.size end # if more tags as int, or equal and bpi is past and int is not if asint > asbpi or (asint == asbpi and (bpioff >= 1 and intoff <= 1)) Integer else BitPaddedInteger end end def read_frames(data, frames) return enum_for(:read_frames, data, frames) unless block_given? if @version < V24 and f_unsynch != 0 begin data = Unsynch.decode(data) rescue Mutagen::Util::ValueError # ignore exception end end if V23 <= @version bpi = determine_bpi(data, frames) until data.nil? or data.empty? header = data[0...10] vals = header.unpack('a4L>S>') # not enough header return if vals.include? nil name, size, flags = vals return if Mutagen::Util::strip_arbitrary(name, "\x00").empty? size = if Integer == bpi then size.to_i else bpi.new(size) end framedata = data[10...10+size.to_i] data = data[10+size.to_i..-1] if size == 0 next # drop empty frames end # TODO: turn this into if frames.constants.include? name.to_sym begin tag = frames.const_get(name.to_sym) rescue NameError yield(header + framedata) if ID3::is_valid_frame_id(name) else begin yield load_framedata(tag, flags, framedata) rescue NotImplementedError yield header + framedata rescue ID3JunkFrameError # ignore exception end end end elsif V22 <= @version until data.empty? header = data[0...6] vals = header.unpack('a3a3') # Not enough header. 6 corresponds to the header unpacking string return if vals.inject(:+).bytesize != 6 name, size = vals size, _ = ("\x00" + size).unpack('L>') return if Mutagen::Util::strip_arbitrary(name, "\x00").empty? framedata = data[6...6+size] data = data[6+size..-1] if size == 0 next # drop empty frames end begin tag = frames.const_get(name.to_sym) rescue NameError yield(header + framedata) if ID3::is_valid_frame_id(name) else begin yield load_framedata(tag, 0, framedata) rescue NotImplementedError yield(header + framedata) rescue ID3JunkFrameError # ignore exception end end end end end def load_framedata(tag, flags, framedata) tag.from_data(self, flags, framedata) end def f_unsynch @flags & 0x80 end def f_extended @flags & 0x40 end def f_experimental @flags & 0x20 end def f_footer @flags & 0x10 end # def f_crc # @extflags & 0x8000 # end def prepare_framedata(v2_version, v23_sep) if v2_version == 3 version = V23 elsif v2_version == 4 version = V24 else raise ArgumentError, 'Only 3 or 4 allowed for v2_version' end # Sort frames by 'importance' order = %w(TIT2 TPE1 TRCK TALB TPOS TDRC TCON).each_with_index.to_a order = Hash[order] last = order.size frames = items frames.sort_by! { |a| [order[a[0][0...4]] || last, a[0]] } framedata = frames.map { |_, frame| save_frame(frame, version: version, v23_sep: v23_sep) } # only write unknown frames if they were loaded from the version # we are saving with or upgraded it to if @unknown_version == version framedata.push *@unknown_frames.select { |d| d.size > 10 } end framedata.join end def prepare_id3_header(original_header, framesize, v2_version) if (val = original_header.unpack('a3C3a4')).include? nil id3, insize = '', 0 else id3, vmaj, vrev, flags, insize = val end insize = BitPaddedInteger.new insize if id3 != 'ID3'.b insize = -10 end if insize >= framesize outsize = insize else outsize = (framesize + 1023) & ~0x3FF end framesize = BitPaddedInteger.to_str(outsize, width:4) header = ['ID3'.b, v2_version, 0, 0, framesize].pack('a3C3a4') return header, outsize.to_i, insize.to_i end # Save changes to a file. # # If no filename is given, the one most recently loaded is used. # # Keyword arguments: # v1 -- if 0, ID3v1 tags will be removed # if 1, ID3v1 tags will be updated but not added # if 2, ID3v1 tags will be created and/or updated # v2 -- version of ID3v2 tags (3 or 4). # # By default Mutagen saves ID3v2.4 tags. If you want to save ID3v2.3 # tags, you must call method update_to_v23 before saving the file. # # v23_sep -- the separator used to join multiple text values # if v2_version == 3. Defaults to '/' but if it's None # will be the ID3v2v2.4 null separator. # # The lack of a way to update only an ID3v1 tag is intentional. def save(filename=@filename, v1:1, v2_version:4, v23_sep:'/') framedata = prepare_framedata(v2_version, v23_sep) framesize = framedata.bytesize if framedata.nil? or framedata.empty? begin delete_tags filename rescue SystemCallError => err unless err.is_a? Errno::ENOENT raise err end end return nil end filename= filename.empty? ? @filename : filename begin f = File.open(filename, 'rb+') rescue SystemCallError => err raise err unless err.is_a? Errno::ENOENT File.open(filename, 'ab').close f= File.open(filename, 'rb+') end begin idata = f.read(10) || '' header = prepare_id3_header(idata, framesize, v2_version) header, outsize, insize = header data = header + framedata + ("\x00".b * (outsize - framesize)) if insize < outsize Mutagen::Util::insert_bytes(f, outsize-insize, insize+10) end f.rewind f.write data begin f.seek -128, IO::SEEK_END rescue SystemCallError => err # If the file is too small, that's OK - it just means # we're certain it doesn't have a v1 tag # If we failed to see for some other reason, bail out return unless err.is_a? Errno::EINVAL f.seek 0, IO::SEEK_END end data = f.read 128 idx = data.index('TAG') if idx.nil? offset = 0 has_v1 = false else offset = idx - data.bytesize has_v1 = true end f.seek offset, IO::SEEK_END if v1 == 1 and has_v1 or v1 == 2 f.write ID3::make_ID3v1(self) else f.truncate f.pos end ensure f.close end end # Remove tags from a file. # # If no filename is given, the one most recently loaded is used. # # Keyword arguments: # # * delete_v1 -- delete any ID3v1 tag # * delete_v2 -- delete any ID3v2 tag def delete_tags(filename=@filename, delete_v1:true, delete_v2:true) filename = filename.empty? ? @filename : filename ID3Data::delete(filename, delete_v1:delete_v1, delete_v2:delete_v2) self.clear end def save_frame(frame, name:nil, version:V24, v23_sep:nil) flags = 0 if pedantic and frame.is_a? TextFrame return '' if frame.to_s.empty? end if version == V23 framev23 = frame.get_v23_frame(sep:v23_sep) framedata = framev23.send(:write_data) else framedata = frame.send(:write_data) end # usize = framedata.size # if usize > 2048 # # Disabled as this causes iTunes and other programs # # fail to find these frames, which usually includes # # e.g. APIC. # #framedata = BitPaddedInt.to_str(usize) + framedata.encode('zlib') # #flags |= Frame.FLAG24_COMPRESS | Frame.FLAG24_DATALEN # end if version == V24 bits = 7 elsif version == V23 bits = 8 else raise ArgumentError, "Version is not valid" end datasize = BitPaddedInteger.to_str(framedata.size, width:4, bits:bits) frame_name = frame.class.name.split("::").last.encode('ASCII-8BIT') header = [(name or frame_name), datasize, flags].pack('a4a4S>') header + framedata end # Updates done by both v23 and v24 update def update_common if self.include? 'TCON' # Get rid of "(xx)Foobr" format. self['TCON'].genres = self['TCON'].genres end if @version < V23 # ID3v2.2 PIC frames are slightly different pics = get_all "APIC" mimes= {'PNG'=> 'image/png', 'JPG'=> 'image/jpeg'} delete_all 'APIC' pics.each do |pic| newpic = APIC.new(encoding:pic.encoding, mime:(mimes[pic.mime] or pic.mime), type: pic.type, desc: pic.desc, data: pic.data) add newpic end delete_all 'LINK' end end # Convert older tags into an ID3v2.4 tag. # # This updates old ID3v2 frames to ID3v2.4 ones (e.g. TYER to # TDRC). If you intend to save tags, you must call this function # at some point; it is called by default when loading the tag. def update_to_v24 update_common if @unknown_version == V23 # convert unknown 2.3 frames (flags/size) to 2.4 converted = [] @unknown_frames.each do |frame| if (val = frame[0...10].unpack('a4L>S>')).include? nil next else name, size, flags = val begin frame = ParentFrames::BinaryFrame.from_data(self, flags, frame[10..-1]) rescue Mutagen::Util::ValueError, NotImplementedError next end end converted << save_frame(frame, name:name) end @unknown_frames = converted @unknown_version = Mutagen::ID3::ID3Data::V24 end # TDAT, TYER, and TIME have been turned into TDRC begin unless Mutagen::Util::strip_arbitrary((self['TYER'] or '').to_s, "\x00").empty? date = @dict.delete('TYER').to_s unless Mutagen::Util::strip_arbitrary((self['TDAT'] or '').to_s, "\x00").empty? dat = @dict.delete('TDAT').to_s date = "#{date}-#{dat[2..-1]}-#{dat[0...2]}" unless Mutagen::Util::strip_arbitrary((self['TIME'] or '').to_s, "\x00").empty? time = @dict.delete('TIME').to_s date += "T#{time[0...2]}:#{time[2..-1]}:00" end end unless include? 'TDRC' add(Frames::TDRC.new(encoding:0, text:date)) end end rescue EncodingError # Ignore end # TORY can be the first part of TDOR if include? 'TORY' f = @dict.delete 'TORY' unless include? 'TDOR' begin add Frames::TDOR.new(encoding:0, text:f.to_s) rescue EncodingError # Ignore end end end # IPLC is now TIPL if include? 'IPLS' f = @dict.delete 'IPLS' unless include? "TIPL" add Frames::TIPL.new(encoding:f.encoding, people:f.people) end end # These can't be trivially translated to any ID3v2.4 tags, or # should have been removed already %w(RVAD EQUA TRDA TSIZ TDAT TIME CRM).each do |key| @dict.delete key if has_key? key end end # Convert older (and newer) tags into an ID3v2.3 tag. # # This updates incompatible ID3v2 frames to ID3v2.3 ones. If you # intend to save tags as ID3v2.3, you must call this function # at some point. # # If you want to to go off spec and include some v2.4 frames # in v2.3, remove them before calling this and add them back afterwards. def update_to_v23 update_common # we could downgrade unknown v2.4 frames here, but given that # the main reason to save v2.3 is compatibility and this # might increase the chance of some parser breaking.. better not # TMCL, TIPL -> TIPL if include?('TIPL') or include?('TMCL') people = [] if include? 'TIPL' f = self.delete('TIPL') people.push(*f.people) end if include? 'TMCL' f = self.delete('TMCL') people.push(*f.people) end unless include? 'IPLS' add IPLS.new(encoding: f.encoding, people:people) end end # TDOR -> TORY if include? 'TDOR' f = @dict.delete 'TDOR' unless f.text.empty? d = f.text.first unless d.year.nil? or d.year.zero? or include? "TORY" add Frames::TORY.new(encoding:f.encoding, text: ('%04d' % [d.year])) end end end # TDRC -> TYER, TDAT, TIME if include? 'TDRC' f = @dict.delete 'TDRC' unless f.text.nil? or f.text.empty? d = f.text.first unless d.year.nil? or d.year.zero? or include? 'TYER' add Frames::TYER.new(encoding:f.encoding, text: ('%04d' % [d.year])) end unless d.day.nil? or d.day.zero? or d.month.nil? or d.month.zero? or include? 'TDAT' add Frames::TDAT.new(encoding:f.encoding, text: ('%02d%02d' % [d.day, d.month])) end unless d.hour.nil? or d.minute.zero? or d.month.nil? or d.month.zero? or include? 'TIME' add Frames::TIME.new(encoding:f.encoding, text: ('%02d%02d' % [d.hour, d.minute])) end end end # New frames added in v2.4 v24_frames = %w(ASPI EQU2 RVA2 SEEK SIGN TDEN TDOR TDRC TDRL TDTG TIPL TMCL TMOO TPRO TSOA TSOP TSOT TSST) v24_frames.each { |key| @dict.delete key if include? key } end # Remove tags from a file. # # Keyword arguments: # # * delete_v1 -- delete any ID3v1 tag # * delete_v2 -- delete any ID3v2 tag def self.delete(filename=nil, delete_v1:true, delete_v2:true) File.open(filename, 'rb+') do |f| if delete_v1 begin f.seek -128, IO::SEEK_END rescue IOError, SystemCallError # ignore else if f.read(3) == 'TAG' f.seek -128, IO::SEEK_END f.truncate f.pos end end end # technically an insize=0 tag is invalid, but we delete it anyway # (primarily because we used to write it) if delete_v2 f.rewind idata = f.read 10 begin val = idata.unpack('a3C3a4') if val.include? nil or val.first.bytesize != 3 or val.last.bytesize != 4 id3, insize = '', -1 else id3, vmaj, vrev, flags, insize = val end insize = BitPaddedInteger.new insize if id3 == 'ID3' and insize >= 0 Mutagen::Util::delete_bytes(f, insize.to_i + 10, 0) end end end end end end end end
true
36329de59a9389c38469f75dd48e049183e5ff8b
Ruby
ejaypcanaria/intro_to_git
/hello_world.rb
UTF-8
135
3.390625
3
[]
no_license
def hello_world puts "Hello world from Ruby!" end def greet(salut, name) puts "#{salut}, #{name}!" end hello_world greet("Ejay")
true
ca42233ef12f2a946a1051e5e6c16e43d3ae37ea
Ruby
kartik1982/XirrusMgmtSys_API
/executor/report_status_formatter.rb
UTF-8
955
2.671875
3
[]
no_license
module EXECUTOR class ReportStatusFormatter RSpec::Core::Formatters.register self, :example_passed, :example_pending, :example_failed def initialize(out) @out = out end def example_finished(notification) example = notification.example # @out.puts "finishing up test: #{example.metadata[:description]}" result = example.execution_result $test_count =$test_count + 1 # $execution_time = $execution_time + result.run_time # @out.puts " result #{result.inspect}" stat = result.status.to_s @out.puts " result status #{stat}" if stat == "passed" $pass_count = $pass_count +1 elsif stat == "failed" $fail_count= $fail_count+1 elsif stat == "pending" $pending_count = $pending_count +1 end end alias example_passed example_finished alias example_pending example_finished alias example_failed example_finished end end
true
aa177747836f0ef1ef391f6c27788e24078b54a5
Ruby
Promptus/trixer
/spec/trixer/slotter_spec.rb
UTF-8
19,969
2.703125
3
[ "MIT" ]
permissive
# frozen_string_literal: true include Trixer RSpec.describe Slotter do let(:slots) { (64..73).to_a } # 16:00 - 18:15 let(:limit) { nil } let(:slot_limit) { nil } let(:blocked_slots) { nil } let(:check_limits) { true } let(:matrix) { Slotter.new(slots: slots, places: places, links: links, limit: limit, slot_limit: slot_limit, blocked_slots: blocked_slots) } let(:place1) { Slotter::Place.new(id: 1, capacity: 2) } let(:place2) { Slotter::Place.new(id: 2, capacity: 2) } let(:place3) { Slotter::Place.new(id: 3, capacity: 4) } let(:places) { [place3, place1, place2] } let(:links) { { 1 => [2], 2 => [3] } } context do let(:booking1) { Slotter::Booking.new(id: 1, duration: 4, amount: 4, slot: 66) } # 16:30 - 17:30 let(:booking2) { Slotter::Booking.new(id: 2, duration: 4, amount: 2, slot: 64) } # 16:00 - 17:00 let(:booking3) { Slotter::Booking.new(id: 3, duration: 4, amount: 2, slot: 68) } # 17:00 - 18:00 let(:bookings) { [booking1, booking2, booking3] } before do bookings.each do |booking| matrix.add_booking(booking: booking, check_limits: check_limits) end end # 16:00 17:00 18:00 # 64 65 66 67 68 69 70 71 72 73 # m 6 6 2 2 2 2 6 6 8 8 free capacity # 1/2 2 2 2 2 3 3 3 3 + + # 2/2 + + + + + + + + + + # 3/4 + + 1 1 1 1 + + + + describe 'total_slotcapacity' do subject { matrix.total_slotcapacity } it { is_expected.to eql(8) } context do let(:places) do [ Slotter::Place.new(id: 4, capacity: 6), Slotter::Place.new(id: 1, capacity: 2), Slotter::Place.new(id: 3, capacity: 4), Slotter::Place.new(id: 2, capacity: 2), Slotter::Place.new(id: 5, capacity: 8), ] end it { is_expected.to eql(22) } end end describe 'place_index' do subject { matrix.place_index } it { is_expected.to eql(1 => place1, 2 => place2, 3 => place3) } end describe 'linksize_index' do subject { matrix.linksize_index } it { is_expected.to eql(1 => 1, 2 => 2, 3 => 1) } end describe 'booking_index' do subject { matrix.booking_index } it { is_expected.to eql(1 => booking1, 2 => booking2, 3 => booking3) } end describe 'capacity_index' do subject { matrix.capacity_index } it do is_expected.to eql( 2 => [Set.new([1]), Set.new([2])], 4 => [Set.new([3]), Set.new([1, 2])], 6 => [Set.new([2, 3])], 8 => [Set.new([1, 2, 3])] ) end it { expect(subject.keys).to eql([2, 4, 6, 8]) } it { expect(matrix.max_capacity).to eql(8) } context 'sort by priority' do let(:place1) { Slotter::Place.new(id: 1, capacity: 2, priority: 2) } let(:place2) { Slotter::Place.new(id: 2, capacity: 2, priority: 1) } let(:place3) { Slotter::Place.new(id: 3, capacity: 4, priority: nil) } let(:links) { {} } it do is_expected.to eql( 2 => [Set.new([2]), Set.new([1])], 4 => [Set.new([3])] ) end end context 'sort by less links' do let(:place1) { Slotter::Place.new(id: 1, capacity: 2, priority: 1) } let(:place2) { Slotter::Place.new(id: 2, capacity: 2, priority: 2) } let(:place3) { Slotter::Place.new(id: 3, capacity: 4, priority: 3) } let(:links) { { 1 => [3] } } it do is_expected.to eql( 2 => [Set.new([2]), Set.new([1])], 4 => [Set.new([3])], 6 => [Set.new([1, 3])] ) end end end describe 'max_capacity_for' do let(:place_id) { 1 } subject { matrix.max_capacity_for(place_id: place_id) } it { is_expected.to eql(8) } context do let(:links) { { 1 => [3] } } it { is_expected.to eql(6) } context do let(:place_id) { 2 } it { is_expected.to eql(2) } end end end describe 'occupied_places_index' do subject { matrix.occupied_places_index[slot] } let(:slot) { 64 } it { is_expected.to eql(Set.new([1])) } context do let(:slot) { 67 } it { is_expected.to eql(Set.new([1, 3])) } end context do let(:slot) { 68 } it { is_expected.to eql(Set.new([1, 3])) } end end describe 'free_capacity_index' do subject { matrix.free_capacity_index[slot] } let(:slot) { 64 } it { is_expected.to eql(6) } context do let(:slot) { 67 } it { is_expected.to eql(2) } end context do let(:slot) { 68 } it { is_expected.to eql(2) } end context do let(:slot) { 70 } it { is_expected.to eql(6) } end context do let(:slot) { 72 } it { is_expected.to eql(8) } end end describe 'slot_bookable?' do let(:duration) { 4 } let(:slot) { 64 } subject { matrix.slot_bookable?(slot: slot, duration: duration) } it { is_expected.to be_truthy } context do let(:slot) { 70 } it { is_expected.to be_truthy } end context do let(:slot) { 71 } it { is_expected.to be_falsy } end context do let(:duration) { 3 } let(:slot) { 71 } it { is_expected.to be_truthy } end end describe 'booked_ratio' do let(:check_limits) { false } subject { matrix.booked_ratio } it { is_expected.to eql(0.4) } end describe "free_amount_at" do # 16:00 17:00 18:00 # 64 65 66 67 68 69 70 71 72 73 # m 6 6 2 2 2 2 6 6 8 8 free capacity # 1/2 2 2 2 2 3 3 3 3 + + # 2/2 + + + + + + + + + + # 3/4 + + 1 1 1 1 + + + + let(:slot) { 64 } subject { matrix.free_amount_at(slot: slot) } it { is_expected.to eql(6) } context do let(:slot) { 67 } it { is_expected.to eql(2) } end context 'slot limit' do let(:slot_limit) { 6 } context do let(:slot) { 64 } it { is_expected.to eql(4) } end context do let(:slot) { 67 } it { is_expected.to eql(2) } end context do let(:slot) { 72 } it { is_expected.to eql(6) } end end context 'limit reached' do let(:limit) { 8 } context do let(:slot) { 64 } it { is_expected.to eql(0) } end context do let(:slot) { 72 } it { is_expected.to eql(0) } end end context 'limit reached with 2 amount' do let(:limit) { 10 } context do let(:slot) { 64 } it { is_expected.to eql(2) } end context do let(:slot) { 72 } it { is_expected.to eql(2) } end end end describe 'occupied_places_for' do let(:booking_slots) { [64, 65, 66, 67] } subject { matrix.occupied_places_for(booking_slots: booking_slots).sort } it { is_expected.to eql([1, 3]) } context do let(:booking_slots) { [68, 69, 70, 71] } it { is_expected.to eql([1, 3]) } end context do let(:booking_slots) { [70, 71, 72, 73] } it { is_expected.to eql([1]) } end context do let(:booking_slots) { [72, 73] } it { is_expected.to eql([]) } end end describe 'add_booking' do let(:place_restriction) { nil } let(:check_limits) { true } subject { matrix.add_booking(booking: booking, place_restriction: place_restriction, check_limits: check_limits) } context "adds booking to place 2" do let(:booking) { Slotter::Booking.new(id: 4, duration: 4, amount: 2, slot: 66) } it { is_expected.to be_truthy } it { expect { subject }.to change { booking.places }.from(nil).to(Set.new([2])) } it { expect { subject }.to change { matrix.free_capacity_index[66] }.from(2).to(0) } it { expect { subject }.to change { matrix.occupied_places_index[66] }.from(Set.new([3,1])).to(Set.new([3,1,2])) } it { expect { subject }.to change { matrix.amount_index[66] }.from(4).to(6) } it { expect { subject }.to_not change { matrix.amount_index[67] } } it { expect { subject }.to change { matrix.booked_ratio }.from(0.4).to(0.5) } context "slot limit reached" do let(:slot_limit) { 4 } it { is_expected.to eql(:slot_limit_reached) } it { expect { subject }.to_not change { booking.places } } context 'check_limits false' do let(:check_limits) { false } it { is_expected.to be_truthy } end end context "slot blocked" do let(:blocked_slots) { [66] } it { is_expected.to eql(:slot_unavailable) } end context "slot blocked" do let(:blocked_slots) { [67] } it { is_expected.to be_truthy } end end context "adds booking to place 2 with capacity 1" do let(:booking) { Slotter::Booking.new(id: 4, duration: 4, amount: 1, slot: 66) } it { is_expected.to be_truthy } it { expect { subject }.to change { booking.places }.from(nil).to(Set.new([2])) } it { expect { subject }.to change { matrix.free_capacity_index[66] }.from(2).to(0) } it { expect { subject }.to change { matrix.occupied_places_index[66] }.from(Set.new([3,1])).to(Set.new([3,1,2])) } it { expect { subject }.to change { matrix.booked_ratio }.from(0.4).to(0.45) } end context "adds booking to place 2 with duration 6" do let(:booking) { Slotter::Booking.new(id: 4, duration: 6, amount: 2, slot: 66) } it { is_expected.to be_truthy } it { expect { subject }.to change { booking.places }.from(nil).to(Set.new([2])) } it { expect { subject }.to change { matrix.free_capacity_index[66] }.from(2).to(0) } it { expect { subject }.to change { matrix.free_capacity_index[71] }.from(6).to(4) } it { expect { subject }.to change { matrix.booked_ratio }.from(0.4).to(0.55) } end context "adds (4/2) at 64 to place 3" do let(:booking) { Slotter::Booking.new(id: 4, duration: 2, amount: 4, slot: 64) } it { is_expected.to be_truthy } it { expect { subject }.to change { booking.places }.from(nil).to(Set.new([3])) } it { expect { subject }.to change { matrix.free_capacity_index[64] }.from(6).to(2) } it { expect { subject }.to change { matrix.free_capacity_index[65] }.from(6).to(2) } end context "not enough space for (4/3) at 64" do let(:booking) { Slotter::Booking.new(id: 4, duration: 3, amount: 4, slot: 64) } it { is_expected.to eql(:out_of_capacity) } it { expect { subject }.to_not change { booking.places } } end context "adds (4/2) at 72 to place 3" do let(:booking) { Slotter::Booking.new(id: 4, duration: 2, amount: 4, slot: 72) } it { is_expected.to be_truthy } it { expect { subject }.to change { booking.places }.from(nil).to(Set.new([3])) } it { expect { subject }.to change { matrix.free_capacity_index[72] }.from(8).to(4) } it { expect { subject }.to change { matrix.free_capacity_index[73] }.from(8).to(4) } it { expect { subject }.to change { matrix.amount_index[72] }.from(0).to(4) } it { expect { subject }.to_not change { matrix.amount_index[73] } } context "total limit reached" do let(:limit) { 10 } it { is_expected.to eql(:total_limit_reached) } it { expect { subject }.to_not change { booking.places } } context 'check_limits false' do let(:check_limits) { false } it { is_expected.to be_truthy } end end end context "not enough space for (4/3) at 72" do let(:booking) { Slotter::Booking.new(id: 4, duration: 3, amount: 4, slot: 72) } it { is_expected.to eql(:slot_unavailable) } it { expect { subject }.to_not change { booking.places } } end context "not enough free capacity" do let(:booking) { Slotter::Booking.new(id: 4, duration: 4, amount: 3, slot: 66) } it { is_expected.to eql(:out_of_capacity) } it { expect { subject }.to_not change { booking.places } } it { expect { subject }.to_not change { matrix.free_capacity_index[66] } } it { expect { subject }.to_not change { matrix.occupied_places_index[66] } } end context "too close to closing time" do let(:booking) { Slotter::Booking.new(id: 4, duration: 4, amount: 2, slot: 71) } it { is_expected.to eql(:slot_unavailable) } it { expect { subject }.to_not change { booking.places } } it { expect { subject }.to_not change { matrix.free_capacity_index[71] } } it { expect { subject }.to_not change { matrix.occupied_places_index[71] } } end context "adds (4/2) at 72 to place 1 and 2 if 3 is occupied" do let(:booking4) { Slotter::Booking.new(id: 4, duration: 4, amount: 4, slot: 70) } let(:bookings) { [booking1, booking2, booking3, booking4] } let(:booking) { Slotter::Booking.new(id: 5, duration: 2, amount: 4, slot: 72) } it { is_expected.to be_truthy } it { expect { subject }.to change { booking.places }.from(nil).to(Set.new([1,2])) } it { expect { subject }.to change { matrix.free_capacity_index[72] }.from(4).to(0) } it { expect { subject }.to change { matrix.free_capacity_index[73] }.from(4).to(0) } end context 'invalid slot' do let(:booking_slot) { nil } let(:booking) { Slotter::Booking.new(id: 5, duration: 2, amount: 4, slot: nil) } it { is_expected.to eql(:slot_unavailable) } context do let(:booking_slot) { 'my united states of whatever' } it { is_expected.to eql(:slot_unavailable) } end end context 'capacity exceeded' do let(:booking_amount) { 9 } let(:booking) { Slotter::Booking.new(id: 5, duration: 2, amount: 9, slot: 70) } it { is_expected.to eql(:invalid_capacity) } context do let(:booking_amount) { 'my united states of whatever' } it { is_expected.to eql(:invalid_capacity) } end context do let(:booking_amount) { nil } it { is_expected.to eql(:invalid_capacity) } end end end describe 'open_slots' do let(:amount) { 2 } let(:around_slot) { 70 } let(:duration) { 4 } let(:check_limits) { true } let(:place_restriction) { nil } subject { matrix.open_slots(around_slot: around_slot, amount: amount, duration: duration, result_limit: 4, check_limits: check_limits, place_restriction: place_restriction) } it { is_expected.to eql([70, 69, 68, 67]) } context do before { matrix.add_booking(booking: Slotter::Booking.new(id: 4, duration: 4, amount: 2, slot: 68)) } it { is_expected.to eql([70, 64]) } context do let(:place_restriction) { [1] } it { is_expected.to eql([]) } end context do let(:place_restriction) { [2] } it { is_expected.to eql([64]) } end context do let(:place_restriction) { [3] } it { is_expected.to eql([70]) } end context do let(:blocked_slots) { [70] } it { is_expected.to eql([64]) } end end context do before { matrix.add_booking(booking: Slotter::Booking.new(id: 4, duration: 4, amount: 2, slot: 70)) } it { is_expected.to eql([70, 66, 65, 64]) } end context do let(:amount) { 4 } it { is_expected.to eql([70]) } end context do let(:amount) { 6 } it { is_expected.to eql([70]) } end context do let(:amount) { 10 } it { is_expected.to eql([]) } end context do let(:duration) { 7 } it { is_expected.to eql([67, 66, 65, 64]) } end context do let(:duration) { 2 } before { matrix.add_booking(booking: Slotter::Booking.new(id: 4, duration: 8, amount: 2, slot: 66)) } it { is_expected.to eql([70, 71, 72, 64]) } end context do let(:duration) { 6 } before { matrix.add_booking(booking: Slotter::Booking.new(id: 4, duration: 8, amount: 2, slot: 66)) } it { is_expected.to eql([]) } end context do let(:around_slot) { 66 } let(:slot_limit) { 4 } it { is_expected.to eql([65, 67, 64, 68]) } context do let(:check_limits) { false } it { is_expected.to eql([66, 65, 67, 64]) } end end context 'amount larger than limit' do let(:around_slot) { 66 } let(:amount) { 6 } let(:slot_limit) { 4 } it { is_expected.to eql([]) } end context do let(:places) { [] } let(:links) { {} } it { is_expected.to eql([]) } end end end describe 'add_booking' do let(:place_restriction) { nil } subject { matrix.add_booking(booking: booking, place_restriction: place_restriction) } context "combined places" do let(:booking) { Slotter::Booking.new(id: 1, duration: 4, amount: 6, slot: 66) } it { is_expected.to be_truthy } it { expect { subject }.to change { booking.places }.from(nil).to(Set.new([2,3])) } it { expect { subject }.to change { matrix.free_capacity_index[66] }.from(8).to(2) } it { expect { subject }.to_not change { matrix.free_capacity_index[64] } } it { expect { subject }.to change { matrix.occupied_places_index[66] }.from(Set.new).to(Set.new([2,3])) } end context "special place required" do let(:place_restriction) { [place2.id] } let(:booking) { Slotter::Booking.new(id: 1, duration: 4, amount: 2, slot: 66) } it { is_expected.to be_truthy } it { expect { subject }.to change { booking.places }.from(nil).to(Set.new([2])) } it { expect { subject }.to change { matrix.free_capacity_index[66] }.from(8).to(6) } it { expect { subject }.to_not change { matrix.free_capacity_index[64] } } it { expect { subject }.to change { matrix.occupied_places_index[66] }.from(Set.new).to(Set.new([2])) } end end end # big matrix RSpec.describe Slotter do let(:slots) { (56..80).to_a } # 14:00 - 20:00 let(:places) do (1..100).map do |id| Slotter::Place.new(id: id, capacity: (id/33)*2+2) end end let(:links) do links = {} (1..50).each do |id| links[id] = [100-id] end links end let(:matrix) { Slotter.new(slots: slots, places: places, links: links) } describe 'total_slotcapacity' do subject { matrix.total_slotcapacity } it { is_expected.to eql(410) } end describe 'places' do subject { matrix.place_index.values.map(&:capacity).uniq } it { is_expected.to eql([2,4,6,8]) } end describe 'capacity_index' do subject { matrix.capacity_index[10] } it do is_expected.to eql([Set.new([1, 99]), Set.new([33, 67]), Set.new([34, 66])]) end end context 'performance test' do it do puts "#{places.size} places" puts "#{links.size} links" t0 = Time.now (1..500).each do |id| matrix.add_booking(booking: Slotter::Booking.new(id: id, duration: [2,4,6].sample, amount: [2,4,6,8].sample, slot: slots.sample)) end puts "added #{matrix.booking_index.values.size} bookings in #{(1000*(Time.now-t0)).round}ms" end end end
true
b4f41dc181b2beb12ff463d814fd55da52a02e67
Ruby
Reltre/exercism-challenges
/ruby/word-count/word_count.rb
UTF-8
229
3.265625
3
[]
no_license
class Phrase def initialize(words) @phrase = words end def word_count phrase = @phrase.split(/(?!\')\W+/) phrase.each_with_object(Hash.new(0)) do |word, hash| hash[word.downcase] += 1 end end end
true
ac9d0c18fd3c155abc64a5275ba753891ab3c461
Ruby
zacck-zz/learning_ruby
/inputs.rb
UTF-8
540
4.0625
4
[]
no_license
#give a prompt to accept a number puts "please enter the first number" first_number = gets.chomp puts "please enter second number " #this accepts inputs from the keyboard second_number = gets.chomp #ruby inputs are always regarded as strings in order to do calculations on them we need to convert them to numbers first = first_number.to_i second = second_number.to_i #this is how to concatnate strings puts "multiplication is #{first * second}" puts "division is #{first/second}" puts "modulus or remainder is #{first % second}"
true
d690c0ecae9c39e8d5cb7baf661c249b471598d3
Ruby
FKnottenbelt/Practicing_Ruby
/ruby_practice/reshuffle_int.rb
UTF-8
527
4
4
[]
no_license
# Given a number, return the highest number that could be # formed from the input number's digits. puts max_number(213) == 321 puts max_number(7389) == 9873 puts max_number(63792) == 97632 puts max_number(566797) == 977665 puts max_number(1000000) == 1000000 #################333 =begin I: int o: resuffeld int to highest number f: break it apart, sort desc, make back to int make int to digits sort and reverse join make int =end def max_number(int) int.digits.sort.reverse.join.to_i end
true
d9b809712f407b17f3fd2f95ebb2007764c8f848
Ruby
thecodepixi/OneLineADay
/app/models/day.rb
UTF-8
684
2.609375
3
[ "MIT" ]
permissive
class Day < ApplicationRecord # join table between users and their journals, and users, their journals and their moods belongs_to :user belongs_to :mood belongs_to :journal validates :description, length: { maximum: 250, message: "Journal descriptions can only be 250 characters long." }, presence: true validates :mood_id, presence: true # helper method to show the day 'title' which is just the formatted 'created_at' date def title_date created_at.strftime("%A, %B %d, %Y") end def self.find_by_user(user) where('user_id = ?', user.id) end def self.find_by_mood(mood) where('mood_id = ?', mood.id).order('created_at desc') end end
true
672fcfd7d129b884d3216fb9515c70299b7744ea
Ruby
mongodb/mongo-ruby-driver
/lib/mongo/address/unix.rb
UTF-8
2,254
2.53125
3
[ "Apache-2.0" ]
permissive
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2014-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo class Address # Sets up socket addresses. # # @since 2.0.0 class Unix # @return [ String ] host The host. attr_reader :host # @return [ nil ] port Will always be nil. attr_reader :port # The regular expression to use to match a socket path. # # @since 2.0.0 MATCH = Regexp.new('\.sock').freeze # Parse a socket path. # # @example Parse the address. # Unix.parse("/path/to/socket.sock") # # @param [ String ] address The address to parse. # # @return [ Array<String> ] A list with the host (socket path). # # @since 2.0.0 def self.parse(address) [ address ] end # Initialize the socket resolver. # # @example Initialize the resolver. # Unix.new("/path/to/socket.sock", "/path/to/socket.sock") # # @param [ String ] host The host. # # @since 2.0.0 def initialize(host, port=nil, host_name=nil) @host = host end # Get a socket for the provided address type, given the options. # # @example Get a Unix socket. # address.socket(5) # # @param [ Float ] socket_timeout The socket timeout. # @param [ Hash ] options The options. # # @option options [ Float ] :connect_timeout Connect timeout. # # @return [ Mongo::Socket::Unix ] The socket. # # @since 2.0.0 # @api private def socket(socket_timeout, options = {}) Socket::Unix.new(host, socket_timeout, options) end end end end
true
07192bde96d2d99d0461ae7885ab89091dfd61f2
Ruby
marzily/sales_engine
/test/item_test.rb
UTF-8
1,325
2.5625
3
[]
no_license
require_relative 'test_helper' class ItemTest < Minitest::Test attr_reader :item, :item_from_repo def setup data = { id: "1", name: "Test Item", created_at: "2012-03-27 14:54:00 UTC", updated_at: "2012-03-27 14:54:00 UTC", description: "this is the ideal item", unit_price: "75107", merchant_id: "3" } @item = Item.new(data, nil) engine = SalesEngine.new('./test/fixtures/') engine.startup @item_from_repo = engine.item_repository.collection.first end def test_item_has_a_default_id assert_equal 1, item.id end def test_item_has_a_name assert_equal "Test Item", item.name end def test_item_has_description assert_equal "this is the ideal item", item.description end def test_item_has_unit_price assert_equal BigDecimal.new(75107) / 100, item.unit_price end def test_item_has_merchant_id assert_equal 3, item.merchant_id end def test_invoice_items_returns_all_invoice_items_for_item assert_equal 0, item_from_repo.invoice_items.count end def test_merchant_returns_a_merchant_for_item assert_equal 1, item_from_repo.merchant.id end def test_it_finds_the_best_day_for_sales assert_nil item_from_repo.best_day end end
true
4fad0f028777ffe4a3461ea3b49d7a529e0fcc71
Ruby
nruth/fingar
/produce_pdf_graphs.rb
UTF-8
675
2.53125
3
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
#!/usr/bin/env ruby -wKU raise ArgumentError unless sourcefilename = ARGV[0] raise ArgumentError unless runs = ARGV[1] raise ArgumentError unless dataname = ARGV[2] raise ArgumentError unless dir = ARGV[3] puts "Making Graphs with MATLAB" cmd = "plot_graphs('#{dir}', #{runs}, '#{dataname}', '#{sourcefilename}') exit" puts cmd puts `echo "#{cmd}" | matlab` #the files are already there now so no need for this. # puts "Moving the files into a sorted location" # dir = "#{dataname}" # raise Exception unless `mkdir #{dir}` # raise Exception unless `mv #{dataname}*.eps #{dir}` #Convert the graph eps to pdf for pdftex compatibility puts `cd #{dir} && ../epsconvert.rb`
true
6e20e3079ab848bd73b868a2fb5e456371261b98
Ruby
a6ftcruton/mastermind
/test/hi_scores_test.rb
UTF-8
509
2.59375
3
[]
no_license
gem 'minitest' require 'minitest/autorun' require 'minitest/pride' require_relative '../lib/hi_scores' class HiScoresTest < Minitest::Test def test_it_has_filename hiscores = HiScores.new('first-hi-scores.txt', 'a+') assert_equal hiscores.filename, 'first-hi-scores.txt' end def test_it_puts_text_into_file file = Minitest::Mock.new hiscores = HiScores.new(file, 'a+') file.expect(:open).with("filename", "w").and_yield(file) file.should_receive(:write).with("text") end end
true
ee2413b34e458bca66e364c371697d5ee129c462
Ruby
harley/weblish
/config/initializers/time_formats.rb
UTF-8
763
2.671875
3
[]
no_license
# Add commonly used time format here. Usage: time_object.to_s(:am_pm) or :short_name, or etc. -H my_formats = { am_pm: "%l:%M %p", am_pm_long: "%b %e %Y, %l:%M %p", am_pm_long_tz: "%b %e %Y, %l:%M %p %Z", am_pm_noyear: "%b %e, %l:%M %p", am_pm_long_no_comma: "%I:%M %p %b %d (%Y)", twelve_hour: "%I:%M", just_time: "%H:%M:%S", short_name: "%a, %b %d, %I:%M %p", just_date: "%a, %b %d", just_date_long: "%A, %B %d", date_year: "%B %d, %Y", date_year_long: "%a, %B %d, %Y", db_date: "%Y-%m-%d", day: "%a", Day: "%A", gg: "%a %m/%d", sql: "%Y-%m-%d %H:%M:%S", no_colon: '%Y-%m-%d %H-%M-%S', dt_short: "%b %e %Y, %l:%M %p", microformat: "%FT%T%:z" } Date::DATE_FORMATS.merge!(my_formats) Time::DATE_FORMATS.merge!(my_formats)
true
4e47e3fe94a59eb4e5e9badcde12514c9452423e
Ruby
annebea/Hadenn
/app/models/product.rb
UTF-8
1,085
2.953125
3
[]
no_license
class Product < ApplicationRecord has_many :product_lots has_many :order_lines has_many :orders, through: :order_lines #allows to find all orders for a given product has_one_attached :photo def total_remaining_quantity total_remaining_quantity = 0 product_lots.each do |product_lot| total_remaining_quantity += product_lot.remaining_quantity end return total_remaining_quantity end # les méthodes ci-dessous permettent de mapper pour chaque produit son product_type. Les doublons sont ensuite éliminés grâce au .uniq. # &:product_type est un raccourci syntaxtique qui correspond à : Product.all.map do |product| product.fruit_product # LEFT TO DO: GERER LE CAPITALIZE POUR AVOIR LES CHAMPS CAPITALIZES EN VISU map(&:capitalize) def self.types Product.all.map(&:product_type).uniq.sort_by { |word| word.downcase } end def self.categories Product.all.map(&:product_category).uniq.sort_by { |word| word.downcase } end def self.fruits Product.all.map(&:product_fruit).uniq.sort_by { |word| word.downcase } end end
true
17d9f0bd23d5544ddbbb139aeb90f3f4f13970b9
Ruby
SydneyTestersBootcamp/sydneyTestersBootcamp
/01_TestingFramework/lib/carQuote.rb
UTF-8
588
2.921875
3
[ "Apache-2.0" ]
permissive
require 'quote' require 'carPremiumCalculator' class CarQuote < Quote attr_reader :year, :make, :premium @@makes = {"audi" => "Audi", "alfa" => "Alfa Romeo", "bmw" => "BMW", "lexus" => "Lexus", "toyota" => "Toyota", "vw" => "Volkswagen"} def initialize(age, email, state, make, gender, year) @age = age.to_i @email = email @state = state @make = make @gender = gender @year = year super("car", @age, @email, @state, @gender) @premium = CarPremiumCalculator.new.getPremiumForQuote(self) end def namedMake @@makes[@make] end end
true
bd957b29149d295b1152b382907a53ed1bf6304d
Ruby
Graciexia/w2-day1-homework-basics
/profile-info.rb
UTF-8
1,053
3.890625
4
[]
no_license
info_hash = {name: "Wei Xia", age: 32, username: "Graciexia", city: "Austin", country: "USA"} food_arr = ["sushi", "BBQ", "taco", "spicy fish", "pho"] def print_profile(info_hash,food_arr) puts "my name: #{info_hash[:name]}" puts "my age: #{info_hash[:age]}" puts "my user name: #{info_hash[:username]}" puts "my city: #{info_hash[:city]}" puts "my country: #{info_hash[:country]}" print "my favoriate food:" food_arr.each {|values| print "#{values} "} print "\n" end puts "Welcome to Gracie's profile!" puts "Now I will give you my simple info." prompt = ">" print "if you would like to read my profile info, pls says 'yes'. if you don't, pls say 'no' : #{prompt} " begin user_input = gets.chomp user_input.upcase! case user_input when "YES" puts "I am so glad you want to know me more." print_profile(info_hash,food_arr) when "NO" puts 'Thanks for your time. See you!' else print "Sorry, you typed wrong words. Pls choose 'yes' or 'no' : #{prompt} " end end until user_input=="YES" || user_input=="NO"
true
5f0da705eea2622dd31f2aee8d97172b46c5f961
Ruby
muffatruffa/RB130---Ruby-Foundations-More-Topics
/easy2/each_with_index.rb
UTF-8
770
4.25
4
[]
no_license
# Write a method called each_with_index that behaves similarly for Arrays. # It should take an Array as an argument, and a block. # It should yield each element and an index number to the block. # each_with_index should return a reference to the original Array. # def each_with_index(ar) # index = 0 # while index < ar.size # yield(ar[index], index) # index += 1 # end # ar # end def each_with_index(ar) e_w_i_rec = -> (yielded, index) do if yielded.empty? ar else yield(yielded[0], index) e_w_i_rec.(yielded[1..-1], index + 1) end end e_w_i_rec.(ar, 0) end result = each_with_index([1, 3, 6]) do |value, index| puts "#{index} -> #{value**index}" end puts result == [1, 3, 6] # 0 -> 1 # 1 -> 3 # 2 -> 36 # true
true
cb83cb0e124ec910e572c25548af5f70f4c45ce8
Ruby
mark-ulrich/AdventOfCode2020
/ruby/Day10/adapter_array_two.rb
UTF-8
1,178
3.625
4
[]
no_license
#!/usr/bin/env ruby # Build a tree with a '0' root. Recursively add children to each node for # adapters which are valid (1-3 more joltage). Count the terminating nodes in # the tree to determine total number of valid combinations. # NOTE: Using memoization to complete in this universe's lifetime. Node = Struct.new(:joltage, :children) def build_tree(adapters, memo = {}) adapter = adapters[0] return memo[adapter] if memo.include? adapter node = Node.new(adapter, []) adapters.select { |a| a > node.joltage && a <= node.joltage + 3 }.each_with_index do |a, i| memo[a] = build_tree(adapters[i + 1..-1], memo) node.children << memo[a] end node end def count_paths(node, memo = {}) return memo[node.joltage] unless memo[node.joltage].nil? return 1 if node.children.empty? count = node.children.map { |child| count_paths(child, memo) }.sum memo[node.joltage] = count count end puts '[+] Reading adapters...' adapters = STDIN.readlines.map(&:to_i).sort adapters.unshift(0) adapters << adapters.max + 3 puts '[+] Building tree...' tree = build_tree(adapters) puts '[+] Counting paths...' count = count_paths(tree) puts "Combinations: #{count}"
true
8c18161d563dbcc6ba2e50716822a44b1a25f518
Ruby
elaguerta/word_guessing_game
/play_game.rb
UTF-8
499
3.453125
3
[]
no_license
require_relative "game" require_relative "player" player_1 = Player.new("Player_1") puts "Welcome to the Word Guessing Game, where if you lose, you get an ASCII Flower." difficulty = player_1.get_difficulty #The Game class takes a difficulty level and an optional secret word. #If you don't provide the secret word, a random one will be chosen from the dictionary. word_game = Game.new(player_1, difficulty) while !word_game.game_over? word_game.play_round end #word_game.clear_leaderboard
true
56dd2af5ba1928b423aa1cd2eb5c979720ab1135
Ruby
LauraFlux/lrthw
/ex4.rb
UTF-8
1,720
3.828125
4
[]
no_license
#On enregistre des variables pour pouvoir les reutiliser cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90 #On enregistre des calculs de variables # les voiture non utilisees sont egales au nb de voiture moins le nb de chauffeurs cars_not_driven = cars - drivers #Les voitures utilises sont au meme nb que le nb de chauffeurs cars_driven = drivers #la capacite d'accueil dans les voitures est egal au nb de voiture utilises multiplié par le nb de place par voiture carpool_capacity = cars_driven * space_in_a_car #le nb de passagers par voiture est egale au nb de passagers divisé par le nb de voiture utilise average_passengers_per_car = passengers / cars_driven #on donne le nb de voitures disponibles puts "There are #{cars} cars available." # et le nb de conducteurs puts "There are only #{drivers} drivers available." #on donne le résultat de l'operation pour afficher le nb de voiture pas conduites puts "There will be #{cars_not_driven} empty cars today." #On dit combien de place il reste dans les voitures pour le covoiturage puts "We can transport #{carpool_capacity} people today." puts "We have #{passengers} to carpool today." puts "We need to put about #{average_passengers_per_car} in each car." #exercice : la variable carpool_capacity n'avait pas été déclarée au début du code donc Ruby ne la connaissait pas et ne pouvait pas l'executer #Si on n'utilisait pas le 4.0 mais juste 4 on aurait obtenu un nb entier or concernant des places dans une voiture on ne peut pas diviser, il vaut mieux donc savoir s'il y a 3.8 places (= de la place pour trois) que le chiffre 4 qui aurait été faux. On aurait prévu 4 personnes mais elles n'auraient pas tenu dans la voiture !
true
1fdc8f568fe218b82087917f1029ac0575e9c1a3
Ruby
etdev/algorithms
/0_code_wars/insert_dashes_.rb
UTF-8
186
2.75
3
[ "MIT" ]
permissive
# http://www.codewars.com/kata/55c3026406402936bc000026 # --- iteration 1 --- def insert_dash2(num) num.to_s.gsub(/([13579](?=[13579]))/, '\1-').gsub(/([2468](?=[2468]))/, '\1*') end
true
78130e5397ee9b21c6de8467169819a4077408b3
Ruby
awksedgreep/runo
/lib/dealer.rb
UTF-8
6,058
3.453125
3
[]
no_license
# frozen_string_literal: true require_relative 'player' require_relative 'human_player' require_relative 'deck' require_relative 'card' require_relative 'colorize' require 'logger' require 'pry' # to play # game = Dealer.new(log: log, players: ['Mark', 'Wesley', 'Josh', 'Mingjia']) class Dealer # deck array attr_accessor :deck # player array attr_accessor :players # card play current direction attr_accessor :direction # who's turn is it attr_accessor :turn # who is the current player attr_accessor :current_player # logger object attr_accessor :log # how many players in the current game attr_accessor :total_players # how many total points at end of game attr_accessor :total_points # time the game started attr_accessor :game_start # time the game finished attr_accessor :game_finish # top discard card attr_accessor :top_card # Create dealer, deck, add players def initialize(log:, players:, human_players:) game_init(log, players, human_players) end # Create a game, deck, shuffle, and deal cards # noinspection RubyMismatchedVariableType def game_init(log, players, human_players) @log = log create_deck((players.length + human_players.length) / 8) create_players(players, human_players) deal_cards set_defaults @top_card = @deck.draw_card @current_player = 0 @player = @players[@current_player] end # Set some instance defaults for one game def set_defaults @game_start = Time.now @winner = false @direction = 1 # start with forward direction @direction_name = 'Forward' @total_players = @players.length end # Create the card deck and shuffle it def create_deck(card_decks) card_decks = 1 if card_decks < 1 @deck = Deck.new(@log, card_decks) @log.info { "Shuffling Deck: #{@deck.length} cards" } @deck.shuffle end # Create the player objects def create_players(players, human_players) @players = [] players.each do |player| @players << Player.new(log: @log, name: player, dealer: self) end human_players.each do |player| @players << HumanPlayer.new(log: @log, name: player, dealer: self) end end # Deal cards to the players def deal_cards @log.info { 'Dealing Cards' } 7.times do @players.each(&:draw_card) end end # Play one game of uno def play_game initial_card_rules until @winner before_turn lay_down = @player.play_card(@top_card) @top_card = lay_down unless lay_down.nil? log_after_turn(lay_down) break if winner after_turn end end # Log some initial pre turn data def log_before_turn @log.info { "It's #{@player.name}'s Turn: Direction = #{@direction_name}" } @log.info { "Before turn: #{@player}" } @log.info { "Top card #{@top_card}" } end # Log status after player's turn def log_after_turn(lay_down) @log.info { "Player #{@player.name} could not lay down" } if lay_down.nil? @log.info { "Player #{@player.name} played #{lay_down}" } unless lay_down.nil? @log.info { "Player #{@player.name} now has #{@player.cards.length} cards" } @log.info { "After turn: #{@player}" } end # before we start our turn, do we need to handle any special cards def before_turn log_before_turn return if @top_card.penalized.nil? draw_four if @top_card.internal_value == 14 # Draw Four draw_two if @top_card.internal_value == 12 # Draw Two end # Draw four has been played def draw_four @log.info { "Player #{@player.name} drawing 4 cards" } @player.draw_card(4) @top_card.penalized = true increment_player end # Draw two has been played def draw_two @log.info { "Player #{@player.name} drawing 2 cards" } @player.draw_card(2) @top_card.penalized = true increment_player end # Reverse has been played def reverse @log.info { 'Reverse played, inverting direction' } change_direction @top_card.penalized = true end # Skip card has been played def skip @log.info { 'Skip played, skipping one player' } increment_player @top_card.penalized = true end # After lay down complete, we need to see if special cards need to be addressed def after_turn if @top_card.penalized.nil? reverse if @top_card.internal_value == 10 # Reverse skip if @top_card.internal_value == 11 # Skip end increment_player end # Published rules for what to do if top card is reverse, skip, wild, etc def initial_card_rules # if reverse or skip handle first card change_direction if @top_card.internal_value == 10 # 10 = Reverse increment_player if @top_card.internal_value == 11 # 11 = Skip # if wild card have first player pick color @top_card.color = @player.preferred_color if @top_card.color == 4 end # draw one card from the deck and return it def draw_card @deck.draw_card end # next player in the current direction def increment_player @current_player += @direction @current_player = (@total_players - 1) if @current_player.negative? @current_player = 0 if @current_player >= @total_players @player = @players[@current_player] @current_player end # reverse direction def change_direction @log.info { 'Reversing Direction' } if @direction == 1 @direction = -1 @direction_name = 'Reverse' else @direction = 1 @direction_name = 'Forward' end end # points in the remaining players hands def points @total_points = 0 @players.collect { |player| @total_points += player.points } @total_points end # return winner of the game def winner return if @player.cards.length.positive? @log.warn { "Player #{@player.name} Won!" } @players.each do |player| @log.warn { "Player #{player.name} had #{player.points} points." } end @log.warn { "Total Points: #{points}" } @winner = true @game_end = Time.now @log.warn { "Game took #{@game_end - @game_start} seconds." } end end
true
338bcb9be06e6168dfa5be0eddcc4afeac9734c3
Ruby
LiamClark14/ActualizeWork
/js_exercises/practice.rb
UTF-8
2,312
4.65625
5
[]
no_license
# Exercise: (work in pairs) # Solve the following problems first in Ruby, then convert the solution to JavaScript. # 1. Write a function that takes in an array of numbers and returns its sum. # 2. Write a function that takes in an array of strings and returns the smallest string. # def smallest_string(array) # smallest = array[0] # array.each do |string| # if string.length < smallest.length # smallest = string # end # end # smallest # end # p smallest_string(["cat", "blizzard", "hotdog"]) # 3. Write a function that takes in an array of numbers and returns a new array with the numbers in reverse order. # 4. Write a function that takes in an array of words and returns the number of words that begin with the letter “a”. # def starts_with_A(array) # count = 0 # array.each do |word| # if word.downcase.start_with?("a") # count += 1 # end # end # count # end # p starts_with_A(["Apple", "app", "Aardvark", "bat"]) # 5. Write a function that takes in an array of strings and joins them together to make a single string separated by commas. # 6. Write a function that takes in an array of numbers and returns the product of all the numbers (each number multiplied by each other). def product(array) product = 1 array.each do |multiplier| product *= multiplier end product end p product([1, 2, 3, 4]) # 7. Write a function that takes in an array of numbers and returns the two smallest numbers. # 8. Write a function that takes in an array of numbers and returns a count of how many zeros are in the array. # 9. Write a function that takes in an array of numbers and returns true if all the numbers are bigger than 10, otherwise returns false. # 10. Write a function that takes in an array of words and returns the number of times the letter “a” appeared in total. # BONUS PROBLEMS # Write a function that accepts a string and returns whether it’s a palindrome. # Write a function to generate/print/store the first "n" prime numbers. # Given a tic-tac-toe board (matrix of 3 x 3), write a function that can check to see whether X or O won. # DOUBLE BONUS: # Use the Ruby .map/.select/.reduce shortcuts to rewrite some of the Ruby problems! # Use the JavaScript .map/.filter/.reduce shortcuts to rewrite some of the JavaScript problems!
true
37e86e58547d27d4b0fb0f89f96979f8d7e0cddc
Ruby
amandeep1420/ruby-basics-exercises
/5_loops_2_rev2/9_first_to_five.rb
UTF-8
330
4.34375
4
[]
no_license
# my answer: number_a = 0 number_b = 0 loop do number_a += rand(2) number_b += rand(2) if number_a == 5 || number_b == 5 puts "5 was reached!" break end end # correct, though the book uses "next unless" instead of the if statement. # this is similiar to my answer the first time, but slightly more succinct.
true
c67ec94902fe8172dc16cebc6b613354ac03f9ca
Ruby
codelation/motion-tickspot
/spec/tick/timer_spec.rb
UTF-8
3,629
2.734375
3
[ "MIT" ]
permissive
describe "Tick::Timer" do it "should be defined" do Tick::Timer.is_a?(Class).should.equal true end it "should start a new timer with a task" do task = Tick::Task.new task.id = 1 @timer = Tick::Timer.start_with_task(task) @timer.task.id.should.equal 1 end it "should start the previously created timer if it exists for the task" do @timer.pause @timer.running?.should.equal false task = Tick::Task.new task.id = 1 previous_timer = Tick::Timer.start_with_task(task) @timer.should.equal previous_timer @timer.running?.should.equal true end it "should return whether or not the timer is running" do @timer.is_running.should.equal true @timer.is_paused.should.equal false @timer.stop @timer.is_running.should.equal false @timer.is_paused.should.equal true @timer.start @timer.is_running.should.equal true @timer.is_paused.should.equal false end it "should return the current running timer" do Tick::Timer.current.should.equal @timer end it "should list all started timers" do timers = Tick::Timer.list timers.is_a?(Array).should.equal true timers.length.should.equal 1 timers.first.should.equal @timer end it "should pause all other timers when a new timer is started" do task = Tick::Task.new task.id = 2 new_timer = Tick::Timer.start_with_task(task) Tick::Timer.current.should.equal new_timer timers = Tick::Timer.list timers.length.should.equal 2 timers.each do |timer| if timer.task.id == 2 timer.is_running.should.equal true timer.is_paused.should.equal false else timer.is_running.should.equal false timer.is_paused.should.equal true end end task = Tick::Task.new task.id = 3 another_timer = Tick::Timer.start_with_task(task) Tick::Timer.current.should.equal another_timer timers = Tick::Timer.list timers.length.should.equal 3 timers.each do |timer| if timer.task.id == 3 timer.is_running.should.equal true timer.is_paused.should.equal false else timer.is_running.should.equal false timer.is_paused.should.equal true end end end it "should have a time span for each start and stop" do task = Tick::Task.new task.id = 4 timer = Tick::Timer.start_with_task(task) timer.stop timer.time_spans.length.should.equal 1 timer.start timer.stop timer.time_spans.length.should.equal 2 end it "should calculate the time in seconds and hours based on recorded time spans" do timer = Tick::Timer.new timer.time_spans = [7200, 5400, 3600] # 2 hours, 1.5 hours, 1 hour timer.time_elapsed_in_seconds.to_i.should.equal 16200 timer.time_elapsed_in_hours.round(1).should.equal 4.5 end it "should have the displayed time as hours and minutes: '04:30'" do timer = Tick::Timer.new timer.time_spans = [7200, 5400, 3600] # 2 hours, 1.5 hours, 1 hour timer.displayed_time.should.equal "04:30" end it "should be removed from list of timers when cleared" do Tick::Timer.list.length.should.equal 6 timer = Tick::Timer.list.select{|timer| timer.is_paused }.first timer.clear Tick::Timer.list.length.should.equal 5 end it "should be removed from list of timers when the time is submitted" do Tick::Timer.list.length.should.equal 5 timer = Tick::Timer.list.select{|timer| timer.is_paused }.first timer.submit! do |result| resume end wait do Tick::Timer.list.length.should.equal 4 end end end
true
312aae738fee061b88a6e62424e1c0eb9014d8ec
Ruby
BKMZ90/ThinkNetica
/task2/glasnie.rb
UTF-8
468
3.328125
3
[]
no_license
=begin Заполнить хеш гласными буквами, где значением будет являтся порядковый номер буквы в алфавите (a - 1). =end letter = ("a" .. "z").to_a number = (1..26).to_a vowels = ["a", "e", "i", "o", "u", "y"] all = Hash[letter.zip number] #if Hash[letter].include(vowels) == true h_vowels = {} all.each {|letter, number| h_vowels[letter] = number if vowels.include?(letter)} puts h_vowels
true
3320efc3b67c83d6d4fde3bc37e5d018b5f1a0d4
Ruby
MustafaHaddara/advent-of-code-2019
/ruby/day6-2.rb
UTF-8
921
3.484375
3
[]
no_license
#!/usr/bin/env ruby def add_orbit(existing_orbits, new_orbit) s = new_orbit.split(")") center = s[0] orbiter = s[1] existing_orbits[orbiter] = center end def find_path(orbits) you = "YOU" santa = "SAN" santa_path = [] santa_parent = orbits[santa] while santa_parent != nil santa_path.push(santa_parent) santa_parent = orbits[santa_parent] end your_parent = orbits[you] steps = 0 while your_parent != nil idx = santa_path.index(your_parent) if idx == nil your_parent = orbits[your_parent] steps += 1 else steps += idx break end end return steps end if __FILE__ == $0 orbits = {} File.open(ARGV[0], "r") do |file_handle| file_handle.each_line do |line| add_orbit(orbits, line.chomp) end end puts find_path(orbits) end
true
fea63510b62ccac96a383acfa0b60ae58583274c
Ruby
npatel111/prime-ruby-001-prework-web
/prime.rb
UTF-8
250
3.21875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Add code here! def prime?(x) if x == 0 || x == 1 return false else (2...x).each do |n| if x % n == 0 return false end end return true end end
true
3b09df355dddd873fcb9f9e7f9c5746936d333ac
Ruby
octanner/spectre
/app/models/test_filters.rb
UTF-8
863
2.640625
3
[ "MIT" ]
permissive
# frozen_string_literal: true class TestFilters def initialize(tests, filter_by_status = false, params) @tests = tests @params = params @filter_by_status = filter_by_status end def names @tests.map(&:name).uniq.sort_by(&:downcase) end def browsers @tests.map(&:browser).uniq.sort_by(&:downcase) end def sizes @tests.map(&:size).uniq.sort_by(&:to_i) end attr_reader :filter_by_status def tests @tests = @tests.where(name: @params[:name]) unless @params[:name].blank? unless @params[:browser].blank? @tests = @tests.where(browser: @params[:browser]) end @tests = @tests.where(size: @params[:size]) unless @params[:size].blank? if filter_by_status unless @params[:status].blank? @tests = @tests.where(pass: (@params[:status] == 'pass')) end end @tests end end
true
2a925dc3c2f60a3ec5797e232b8837ffdd8bc9e8
Ruby
eberleant/learn_ruby
/05_book_titles/book.rb
UTF-8
452
4.09375
4
[]
no_license
#write your code here class Book def title= t @title = titleize t end def title return @title end def titleize str little_words = ["the", "and", "over", "in", "of", "a", "an"] str = str.downcase arr = str.split(" ") arr.each_index do |i| if i == 0 or (not little_words.include?(arr[i].downcase)) arr[i] = arr[i].capitalize end end new_str = "" arr.each do |word| new_str = new_str + word + " " end return new_str.strip end end
true
25a0e19b5c0ed9e27b58031cb454aae4a67be3aa
Ruby
totor34/totorminus
/app/models/booking.rb
UTF-8
930
2.765625
3
[]
no_license
# == Schema Information # # Table name: bookings # # id :integer not null, primary key # ride_id :integer # user_id :integer # passenger_number :integer # created_at :datetime not null # updated_at :datetime not null # class Booking < ApplicationRecord belongs_to :ride belongs_to :user validates :passenger_number, presence: true, inclusion: { in: (0..10), message: "Must be a number between 0 and 10"} # enables to call end_point on @booking and returns @booking.ride.end_point delegate :end_point, :start_point, to: :ride enum state: [:pending , :paid ] monetize :amount_cents def calculate_amount self.ride.price * self.passenger_number end # other possibility to avoid doing a belongs_to:end_point through :ride is : # def end_point # ride.end_point # end # def start_point # ride.start_point # end end
true
b25a81676ec4ec8bd8e6eed8ff7a13a9e60e5bba
Ruby
preetishukla/oyster_card_problem
/lib/oyster_card.rb
UTF-8
1,604
3.390625
3
[]
no_license
require_relative 'oyster_card/card' require_relative 'oyster_card/fare' require_relative 'oyster_card/journey' require_relative 'oyster_card/zone' # Add money £30 to card card = Card.new card.top_up(30) puts "Current balance of card ******** #{card.balance}***************" # Taking Transport Tube: from Holborn to Earl’s Court card.tap_in({transport: :tube, stop: "Holborn"}) puts "****************** Travelled by TUBE *******************" puts "Tapped in at Holborn(zone 1) \n Now Current balance of card ********* #{card.balance}************" card.tap_out({transport: :tube, stop: "Earl’s Court"}) puts "Tapped out at Earl’s Court(zone 1/2) \n Now Current balance of card ********** #{card.balance} \n *********" # Taking BUS: 328 from Earl’s Court to Chelsea(where there is no zone or station for Chelsea) card.tap_in({transport: :bus, stop: "Earl’s Court"}) puts "*********Travelled by BUS**************" puts "Tapped in at Earl’s Court (zone 1/2) \n Now Current balance of card ************* #{card.balance} \n **************" # Taking Transport Tube: from Earl’s court to Hammersmith card.tap_in({transport: :tube, stop: "Earl’s Court"}) puts "****************** Travelled by TUBE *******************" puts "Tapped in at Earl’s Court (zone 1/2) \n Now Current balance of card ********* #{card.balance}************" card.tap_out({transport: :tube, stop: "Hammersmith"}) puts "Tapped out at Hammersmith (zone 2) \n Now Current balance of card ************* #{card.balance} \n **************" #Final Balance puts "Final balance in card ********** #{card.balance}*************"
true
b215248b2ae7274a3418d0ebf93bb8e3c1ad29ba
Ruby
Spencer197/finance-tracker
/app/controllers/users_controller.rb
UTF-8
1,895
2.6875
3
[]
no_license
class UsersController < ApplicationController def my_portfolio @user = current_user #Ensures user is logged in. @user_stocks = current_user.stocks #Returns all of the user's stocks. end def my_friends @friendships = current_user.friends end def search #The next two lines were replaced with the code below them in Section 8, Lecture 196. #@users = User.search(params[:search_param])#The .search() method must be created(defined) in the users.rb model file. #render json: @users #This code copied from stock_controller.rb, search method & adjusted. if params[:search_param].blank? #Checks if search_param is blank flash.now[:danger] = "You have entered an empty search string." #blank error message. else @users = User.search(params[:search_param] )#Takes in @users instance variable params @users = current_user.except_current_user(@users) #current_user calls except_current_user method, which passes in an instance of @users. Prevents current_user from being included in friends search. flash.now[:danger] = "No users match this search criteria." if @users.blank? #Checks that it isn't an unmatched search param. end #This do block differs from Rails 4 code. respond_to do |format| format.js {render partial: 'friends/result' } #Render the /users_result partial in all three cases. end end def add_friend @friend = User.find(params[:friend]) current_user.friendships.build(friend_id: @friend.id) #Builds an association between current_user & friend_id. if current_user.save flash[:notice] = "Friend was successfully added" else flash[:danger] = "There was something wrong with the friend request" end redirect_to my_friends_path end def show @user = User.find(params[:id]) #Grabs the user object. @user_stocks = @user.stocks end end
true
ed71f9196d1e41b28f1f1d9736121aabc9ad0eb6
Ruby
Bhanupriya-S/oakland_nursery_page_object_2021
/features/support/pages/oak_plant_search_page.rb
UTF-8
2,803
2.515625
3
[]
no_license
class OakPlantSearchPage include PageObject # page_url 'https://plants.oaklandnursery.com/12130001' page_url $app_url text_field(:search_plant_edit_box, id: 'NetPS-KeywordInput') button(:submit, id: 'NetPSSubmit') links(:plant_names, class: /NetPS-ResultsP(2|)?Link$/) checkbox :choose_first_result, id: 'CheckmP1' link(:select_wish_list, text: 'View My Wish List') div(:wish_list_header, id: 'NetPS-mPTitle') div :search_results, class: 'NetPS-ResultsData' div(:plant_details, class: 'NetPS-ResultsDataSub') ## in general to accessa method need to create an obj for the class instead of that Self taking place def search_plant plant_name # self method becomes a class mehtod # @browser.text_field(id: 'NetPS-KeywordInput').set plant_name # (old one using watir) # search_plant_edit_box_element.set plant_name # OR (Using Pageobject) self.search_plant_edit_box = plant_name # Defined as pageobject #@browser.button(id: 'NetPSSubmit').click # (Using watir) submit_element.click # Defined as Pageobject # wait_until { search_results_element.present? } end def get_all_plant_names wait_until { search_results_element.present? } plant_names_elements.map(&:text) # map mehtod does all the looping things and creates array also # wait_until { search_results_element.present? } end def verify_plant_search_is_correct plant_name wait_until { search_results_element.present? } get_all_plant_names.each do |each_name| # p "verifying the plant - #{each_name} has correct value - #{plant_name}" fail "Plant Name #{each_name} is not related to #{plant_name}" unless each_name.include? plant_name end end def verify_no_of_plant_search_results exp_count fail "No of results are more than #{exp_count}" unless plant_names_elements.count == exp_count end def add_plant_to_wishlist unless choose_first_result_element.checked? choose_first_result_element.when_present(60).set end select_wish_list_element.click fail "You are not on the wishlist page" unless wish_list_header_element.text.eql? 'My Wish List' end def verify_wishlist_has_plant first_plant_name_from_search_page wait_until { search_results_element.present? } first_plant_name_from_wishlist_page = get_all_plant_names.first fail "Wishlist doesnt has the correct plant" unless first_plant_name_from_search_page == first_plant_name_from_wishlist_page end def get_plant_info plant_info_hash = {} plant_details_element.text.split("\n").each do |plant_detail_info| plant_info_hash[plant_detail_info.split(": ")[0]] = plant_detail_info.split(": ")[1].strip end # wait_until { search_results_element.present? } plant_info_hash end end
true
dfb6ad555cc9438f590d2510c18a7e8c1fdd77e1
Ruby
ChaelCodes/Advent-of-Code-2020
/spec/solutions/day_one_spec.rb
UTF-8
982
2.828125
3
[]
no_license
require 'spec_helper' require './solutions/day_one' RSpec.describe DayOne do describe '.run' do subject { DayOne.run(part) } context 'when part 1' do let(:part) { 1 } it 'calls process on an array of numbers' do is_expected.to eq 605364 end end context 'when part two' do let(:part) { 2 } it 'finds 3 numbers that sum to 2020' do is_expected.to eq 128397680 end end end describe '#process' do subject { DayOne.new(input, set).process } context 'sample one' do let(:input) { [1721, 979, 366, 299, 675, 1456] } let(:set) { 2 } it { is_expected.to eq 514579 } end context 'sample two' do let(:input) { [1721, 979, 366, 299, 675, 1456] } let(:set) { 3 } it { is_expected.to eq 241861950 } end end end
true
a6226c92a8ac056905351da2cdc5625d2693ff65
Ruby
sanmedina/libro_rails
/cap05/Estudiante.rb
UTF-8
489
3.5
4
[]
no_license
require "./Matematicas" require_relative "Persona" class Estudiante < Persona include Matematicas attr_accessor :curso def initialize(nombre = "", apellidos = "", curso = -1) super(nombre, apellidos) initialize_math @curso = curso end def decirPI "PI es igual a #{Matematicas::PI}" end def decir2Elevado(n) "2 elevado a la #{n} es igual a #{pow2(n)}" end def to_s super_s = super super_s += " Estoy en #{@curso}." end end
true
9204359c2eb7af5af18fb66384dab491aa9b074f
Ruby
seejohnrun/enforced_interface
/spec/examples/enforced_interface_spec.rb
UTF-8
2,317
2.609375
3
[]
no_license
require 'spec_helper' describe EnforcedInterface do module TestInterface def add(one, two) # Interface method - to be implemented end end context 'when matching method perfectly' do shared_examples_for 'a working interface' do it 'should allow method calls' do expect(klass.new.add(1, 2)).to eq(3) end it 'should include the module' do expect(klass.new).to be_a(TestInterface) end it 'should not pollute' do expect { Class.new.new }.not_to raise_error expect { Class.new.tap { |c| c.send(:include, Module.new) }.new }.not_to raise_error end end 2.times do # follow-up usage for caching context 'when using the interface properly' do let(:klass) do Class.new do def add(one, two) 3 end include EnforcedInterface[TestInterface] end end it_should_behave_like 'a working interface' end end end context 'when matching but with wrong arity' do let(:klass) do Class.new do def add(one) end include EnforcedInterface[TestInterface] end end it 'should error and show wrong arity' do expect { klass }.to raise_error(EnforcedInterface::NotImplementedError) do |err| expect(err.message).to end_with('supports public instance method add with incorrect arity') end end end context 'when matching but with wrong access' do let(:klass) do Class.new do private def add(one) end include EnforcedInterface[TestInterface] end end it 'should error and show not implemented' do expect { klass }.to raise_error(EnforcedInterface::NotImplementedError) do |err| expect(err.message).to end_with('does not support public instance method add') end end end context 'when not implemented' do let(:klass) do Class.new do include EnforcedInterface[TestInterface] end end it 'should error and show not implemented' do expect { klass }.to raise_error(EnforcedInterface::NotImplementedError) do |err| expect(err.message).to end_with('does not support public instance method add') end end end end
true
f2d8e4db81d53adc6e646cdf3fc19e7030219df0
Ruby
StefanoPruna/caffeApp
/spec/ruby_caffe_spec.rb
UTF-8
2,717
3.046875
3
[]
no_license
#testing require_relative "../menu_item" require_relative "../menu" require_relative "../order" require_relative "../caffe" describe MenuItem do it "Should return the price of the item" do name = "caffelatte" price = 2.00 menu_item = MenuItem.new(name, price) expect(menu_item.price).to eq(price) end it "Should return the name of the item" do name = "caffelatte" price = 2.00 menu_item = MenuItem.new(name, price) expect(menu_item.name).to eq(name) end end describe Menu do it "should be able to get an item price" do name = "caffelatte" price = 2.00 menu = Menu.new menu.add_item(name, price) expect(menu.getPrice(name)).to eq(price) end it "should be able to add an item" do name = "caffelatte" price = 2.00 menu = Menu.new menu.add_item(name, price) expect(menu.get_items().length).to be(1) end end describe Order do it "should add an item to the order" do order = Order.new name = "caffelatte" quantity = 2 order.add_item(name, quantity) expect(order.get_items().length).to be(1) end it "should update an item quantity" do order = Order.new name = "caffelatte" quantity = 2 quantityAdded = 3 order.add_item(name, quantity) order.add_item(name, quantityAdded) expect(order.get_items()[name]).to be(quantity+quantityAdded) end end describe Bar do it "should create a bar with a name" do name = "Loske's bar" menu_items = {} bar = Bar.new(name, menu_items) expect(bar.name).to eq(name) end it "should create a bar with a menu" do name = "Loske's bar" menu_items = {caffelatte: 2.00, espresso: 1.00} bar = Bar.new(name, menu_items) expect(bar.menu.get_items.length).to be(2) end it "should add an item to the order" do name = "Loske's bar" menuItems = {caffelatte: 2.00, espresso: 1.00} bar = Bar.new(name, menuItems) item = "caffelatte" quantity = 1 bar.addToOrder(item, quantity) expect(bar.getOrder().get_items().length).to be(1) end it "should define a welcome method" do name = "Loske's bar" menuItems = {caffelatte: 2.00, espresso: 1.00} bar = Bar.new(name, menuItems) expect(bar.welcome).to eq(nil) end it "should define a print menu method" do name = "Loske's bar" menuItems = {caffelatte: 2.00, espresso: 1.00} bar = Bar.new(name, menuItems) expect(bar.printMenu).to eq(nil) end end
true
bed126e6feb63c39acba7f5479ee9a50c9b03e16
Ruby
toxis/piko
/app/models/month.rb
UTF-8
1,123
2.671875
3
[ "MIT" ]
permissive
class Month < ActiveRecord::Base belongs_to :point_times def self.compute_month now = DateTime.now end_time = DateTime.new(now.year, now.month, now.day, now.hour, 0) start_time = end_time - 8.hours average = {} nb = 0 inverters = Inverter.all inverters.each do |inverter| average[inverter.id] = 0.0 end times = PointTime.joins(:weeks, :point_datas).where(time: start_time..end_time).includes(:weeks, :point_datas) times.each do |time| # get data (for each inverter) time.point_datas.each do |data| average[data.inverter_id] = average[data.inverter_id] + data.value end nb = nb + 1 end average.each do |key, value| average[key] = value / nb end point_time = PointTime.create( time: end_time - 4.hours ) average.each do |key, value| point_data = PointData.create( inverter_id: key, point_time_id: point_time.id, value: value, unit: 'W' ) end Month.create( point_time_id: point_time.id ) end end
true
f4700ff73a81b407a6073592acef3ea182f7155d
Ruby
camila-santos-ferreira/game-adivinhar-numero
/adivinhar_numero/lib/sortear_numero.rb
UTF-8
838
3.34375
3
[]
no_license
class SortearNumero # método de classe, o self será utilizado para que a classe não precise ser instanciada def self.sortear # criando um array vazio array = [] # abrindo o arquivo para leitura # o File.expand_path serve para criar um caminho a partir de um local # __FILE__ -> começa a partir de sortear_numero # iremos voltar uma pasta '../' -> lib # iremos voltar mais uma pasta '../' -> adivinhar_numero # e assim poderemos acessar o arquivo numeros.txt File.open(File.expand_path('../../numeros.txt', __FILE__),'r') do |arquivo| # as linhas serão lidas while line = arquivo.gets # os números serão puxados para dentro do array array.push(line.to_i) end end # o sample irá escolher um dos valores do array e "sortear" array.sample end end
true
1f0ba4967f9eaa894b57d7267fd98a7b1e9911c1
Ruby
syaifulrmdhn/sql-crowdfunding-lab-cb-gh-000
/lib/sql_queries.rb
UTF-8
1,718
3.140625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your sql queries in this file in the appropriate method like the example below: # # def select_category_from_projects # "SELECT category FROM projects;" # end # Make sure each ruby method returns a string containing a valid SQL statement. def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name "SELECT title, SUM(amount) FROM projects JOIN pledges ON projects.id=pledges.project_id GROUP BY projects.title ORDER BY projects.title ASC;" end def selects_the_user_name_age_and_pledge_amount_for_all_pledges_alphabetized_by_name "SELECT name, age, SUM(amount) FROM users JOIN pledges ON users.id=pledges.user_id GROUP BY users.name ORDER BY users.name ASC;" end def selects_the_titles_and_amount_over_goal_of_all_projects_that_have_met_their_funding_goal "SELECT title, (SUM(pledges.amount) - funding_goal) AS amount_over_goal FROM projects JOIN pledges ON projects.id=pledges.project_id GROUP BY projects.title HAVING amount_over_goal>=0" end def selects_user_names_and_amounts_of_all_pledges_grouped_by_name_then_orders_them_by_the_amount_and_users_name "SELECT name, SUM(pledges.amount) AS user_amount FROM users JOIN pledges ON users.id = pledges.user_id GROUP BY users.name ORDER BY user_amount ASC, users.name ASC;" end def selects_the_category_names_and_pledge_amounts_of_all_pledges_in_the_music_category "SELECT category, pledges.amount FROM projects JOIN pledges ON projects.id = pledges.project_id WHERE category = 'music';" end def selects_the_category_name_and_the_sum_total_of_the_all_its_pledges_for_the_books_category "SELECT category, SUM(pledges.amount) FROM projects JOIN pledges ON projects.id = pledges.project_id WHERE category = 'books';" end
true
bea34da478313d0072bd809109542b860f81e6a2
Ruby
sagararathi/chess
/spec/chess_spec.rb
UTF-8
1,379
3.21875
3
[]
no_license
require 'chess' RSpec.describe Chess do let(:knight) { described_class.new('Knight', 'd2') } describe '#get_positions' do context 'available moves for Knight' do it 'returns possible moves for Knight from position d2' do expect(knight.get_positions).to eq "f3, c4, e4, b1, f1, b3" end end context 'available moves for Rook' do let(:rook) { described_class.new('rook', 'd2')} it 'returns possible moves for Rook from position d2' do expect(rook.get_positions).to eq 'd1, d3, d4, d5, d6, d7, d8, c2, b2, a2, e2, f2, g2, h2' end end context 'available moves for Queen' do let(:queen) { described_class.new('queen', 'd2')} it 'returns possible moves for Queen from positions d2' do expect(queen.get_positions).to eq 'd1, d3, d4, d5, d6, d7, d8, c2, b2, a2, e2, f2, g2, h2, c3, b4, a5, e1, e3, f4, g5, h6, c1' end end end describe '#get_coordinates' do it 'should return cordinate positions of piece on baord' do expect(knight.send(:get_coordinates)).to eq [6,3] end it 'should return empty array for invalid position entered' do knight.position_string = 'd12' expect(knight.send(:get_coordinates)).to eq [] end end describe '#klass' do it 'should return class' do expect(knight.send(:klass)).to eq Knight end end end
true
3f0fb17c19734ebf8f5b4fcc906f14d029b88105
Ruby
DaisukeKataoka/ruby_ex
/ex3/ex3_2.rb
UTF-8
205
3.265625
3
[]
no_license
class A def m puts "OK" end protected:m def call_m(a) puts "protected" a.m # オブジェクトaのメソッドを呼び出す end end a = A.new a.m #しかし、インスタンス
true
3bc7de74b28d5ede69c31df62074431b50cfc00f
Ruby
ricardo75777/Project7
/Game/Data/Scripts/source/CMouse.rb
UTF-8
1,523
2.53125
3
[]
no_license
#============================================================================== # ■ Mouse #============================================================================== module CMouse CursorFile = "Graphics/System/Cursor.cur" # 光标文件名(最好包含后缀) EmptyCursor = "Graphics/System/Empty.cur" #空光标 AttackCursor = "Graphics/System/Attack.cur" # 攻击光标 LKEY = 1 RKEY = 2 MKEY = 4 module_function #-------------------------------------------------------------------------- # ## 获取坐标 #-------------------------------------------------------------------------- def pos return [self.x, self.y] end #-------------------------------------------------------------------------- # ## 在区域内? #-------------------------------------------------------------------------- def area?(x, y, width, height) pos = [self.x, self.y] return false if pos.nil? return false unless pos[0].between?(x, x+width) return false unless pos[1].between?(y, y+height) return true end #-------------------------------------------------------------------------- # ## 在区域内? #-------------------------------------------------------------------------- def rect?(rect) pos = [self.x, self.y] return false if pos.nil? return false unless pos[0].between?(rect.x, rect.x+rect.width) return false unless pos[1].between?(rect.y, rect.y+rect.height) return true end set_cursor(CursorFile) end Mouse=CMouse
true
fb2e7fa79b665f28012d19463e16e047f3da526d
Ruby
dtime/hal_presenters
/lib/hal_presenters/helpers/rels.rb
UTF-8
3,579
2.640625
3
[ "MIT" ]
permissive
module HalPresenters module Helpers module Rels def self.included(klass) klass.extend(ClassMethods) klass.instance_eval do include(InstanceMethods) end end module ClassMethods # Define a rel and the href that goes with it def rel(name, opts = {}, &block) name = "#{self.rel_name}#{name}" if name =~ /^:/ opts = HalPresenters.normalize_options(opts) stored_rels[name] = [opts, block] end # What this object will be linked as. def rel_name(name = nil) @rel_name = name if name @rel_name end # List of rels defined with #rel # Rels are stored as keys, with procs for each rel def stored_rels @stored_rels ||= {} @stored_rels end # List of rel keys optionally filtered by presentation def rels(presentation = nil) if presentation stored_rels.reject{|k, (v,p)| HalPresenters.exclude_presentation?(v, presentation) }.keys else stored_rels.keys end end end module InstanceMethods # Filter to add link hash based on class level rels def linkify(obj, presentation = :full, *args) obj["_links"] = self.link_hash_for(presentation) selfify(obj, presentation, *args) end # Set self if overridden def selfify(obj, presentation = :full, *args) obj["_links"]["self"] = prep_link(options[:self], "self") if options[:self] && options[:override_self] obj end # Builds a hash of class rels defined, filtered by presentation def link_hash_for(presentation = :full) self.class.rels(presentation).inject({}) do |hash, rel| link = self.link_for_rel(rel, presentation) hash[rel] = link unless link.nil? hash end end # Prepares an individual rel, # calling the defined rel block and calling # prep link on the returned value to prepare for return def link_for_rel(rel, presentation_type = nil) opts, link_proc = self.class.stored_rels[rel] ret = instance_exec(self, opts, presentation_type, &link_proc) if ret.is_a?(Array) if ret.size > 1 ret = ret.map{|l| prep_link(l, rel)}.compact else ret = prep_link(ret.compact.first, rel) end else ret = prep_link(ret, rel) end ret end # Prep link takes a return value, which may be a hash or # string, and turns it into a hash with the rel set. # prep_link("foo", "bar") => {href: "foo", rel: "bar"} # prep_link({href: "banana", test: "foo"}, "bar") => # {test: "foo", href: "banana", rel: "bar"} def prep_link(ret, rel) ret = {href: ret} unless ret.respond_to?(:fetch) return nil unless ret[:href] ret[:href] = "#{self.options[:root]}#{ret[:href]}" if self.options[:root] && ret[:href] =~ /^\// ret[:templated] = true if ret[:href] =~ /\{.*\}/ if ret[:templated] && ret[:'href-vars'].nil? vars = Addressable::Template.new(ret[:href]).variables # Assume all variables are string type ret[:'href-vars'] = vars.inject({}){|acc, var| acc[var] = "string"; acc } end ret[:rel] = rel ret end end end end end
true