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
02332f02554fed69ca10fd761da805bd5c22c22c
Ruby
sarakhandaker/ruby-enumerables-cartoon-collections-lab-seattle-web-030920
/cartoon_collections.rb
UTF-8
899
3.65625
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'pry' def roll_call_dwarves(array)# code an argument here # Your code here array.each_with_index{ | item, index| puts "#{index+1} #{item}" } end def summon_captain_planet(array)# code an argument here # Your code here array.map! {|name| name.capitalize } array.map! {|name| name+= "!" } end def long_planeteer_calls(array)# code an argument here # Your code here n=false array.map{|word| n=true if word.size>4} n end def find_the_cheese(array)# code an argument here # the array below is here to help cheese_types = ["cheddar", "gouda", "camembert"] if array.include?(cheese_types[0]) || array.include?(cheese_types[1])|| array.include?(cheese_types[2]) x=[] x[0]=array.index("gouda") x[1]=array.index( "camembert") x[2]=array.index("cheddar") x.map!do|item| if item==nil item=4 else item=item end end n=x.min array[n] else n=nil end end
true
2378cced05fc779fd89e6a1a6ce6c49981eba08f
Ruby
renatosousafilho/ror-senac
/revisao-trabalho/pessoa_crud.rb
UTF-8
370
3.0625
3
[]
no_license
require_relative './pessoa' class PessoaCrud def initialize @pessoas = [] end def cadastrar(nome, idade, endereco, telefone) pessoa = Pessoa.new(nome, idade, endereco, telefone) @pessoas << pessoa end def listar @pessoas end def pesquisar_por_nome(nome) @pessoas.each do |pessoa| return pessoa if pessoa.nome == nome end return nil end end
true
05abda5f1bce6f0cfd15601d8ac73e09b315cf72
Ruby
this-is-simon/cc_w1d5_weekend_homework
/start_point/pet_shop_simons_answers.rb
UTF-8
1,686
3.203125
3
[]
no_license
def pet_shop_name(pet_shop) pet_shop[:name] end def total_cash(pet_shop) pet_shop[:admin][:total_cash] end def add_or_remove_cash(pet_shop, added_or_removed_cash) pet_shop[:admin][:total_cash] += added_or_removed_cash end def pets_sold(pet_shop) return pet_shop[:admin][:pets_sold] end def increase_pets_sold(pet_shop, pet_increase) pet_shop[:admin][:pets_sold] += pet_increase end def stock_count(pet_shop) pet_shop[:pets].count end def pets_by_breed(pet_shop, animal_breed) animal_count = [] for animals in pet_shop[:pets] if animals[:breed] == animal_breed animal_count.push(animals) end end return animal_count end def find_pet_by_name(pet_shop, pet_name) animal_cage = {} for animals in pet_shop[:pets] if animals[:name] == pet_name animal_cage[:name] = pet_name end end return animal_cage unless animal_cage.empty? end def add_pet_to_stock(pet_shop, new_pet) pet_shop[:pets] << new_pet return pet_shop[:pets].length end def customer_pet_count(customer) return customer[:pets].count end def add_pet_to_customer(customer, new_pet) customer[:pets] << new_pet customer[:pets].count end def customer_can_afford_pet(customer, new_pet) if customer[:cash] < new_pet[:price] return false else return true end end #2. Check if we can find the pet #3. Check can customer afford pet #4. Move pet hash to customer pets #5. Increase admin sales / pets sold #6. Increase shop cash def sell_pet_to_customer(pet_shop, pet, customer) #1. Search pet shop for pet name if find_pet_by_name && customer_can_afford_pet == true add_pet_to_customer increase_pets_sold add_or_remove_cash end end
true
2ea7e7a043de833c54a304fe6e8fbb06984a2433
Ruby
aspsa/blocipedia
/app/helpers/wikis_helper.rb
UTF-8
925
2.546875
3
[]
no_license
module WikisHelper def wiki_collaboration_link(wiki, user) return unless wiki.id # If this wiki entry does not have a user id in the collaborators table, then this user is a potential collaborator. unless wiki.collaborator?(user) #link_to "Collaborate", add_collaborator_wiki_path(wiki: wiki, user: user.id) link_to "Collaborate", add_collaborator_wiki_path(wiki: wiki, user: user) # If this wiki entry has a user id in the collaborators table, then this user is a candidate for removal as a collaborator. else #link_to "Remove Collaboration", delete_collaborator_wiki_path(wiki: wiki, user: user.id) link_to "Remove Collaboration", delete_collaborator_wiki_path(wiki: wiki, user: user) end end def standard_users(users) standard_users = [] users.each do |u| standard_users << u if u.role == 'standard' end standard_users end end
true
2acfd24266e85b11d1be39e6dfb2b23a0ba94387
Ruby
eyeseast/pillbox
/pillbox_resource_noko.rb
UTF-8
1,380
2.578125
3
[]
no_license
require 'nokogiri' require 'open-uri' class PillboxResourceNoko attr_accessor :attrs def PillboxResourceNoko::find_first_with_img_by_ingredient(ingredient) prs = PillboxResourceNoko.find_all_by_ingredient(ingredient) pill = nil prs.each do |pr| pill = pr if pr.has_image? end pill end def PillboxResourceNoko::find_all_by_ingredient(ingredient) doc = Nokogiri::XML(open("http://pillbox.nlm.nih.gov/PHP/pillboxAPIService.php?key=12345&ingredient=#{ingredient}")) prs = [] doc.xpath('//Pills/pill').each do |pill| pr = PillboxResourceNoko.new pr.attrs = {} pill.children.each do |child| next if child.nil? or child.name == "text" pr.attrs[child.name] = child.inner_html end prs << pr end prs end def shape; attrs['SPLSHAPE'] end def color; attrs['SPLCOLOR'] end def description; attrs['RXSTRING'] end def product_code; attrs['PRODUCT_CODE'] end def has_image?; attrs['HAS_IMAGE'] == '1' end def ingredients; attrs['INGREDIENTS'].split(";") end def size; attrs['SPLSIZE'].to_i end def image_id; attrs['image_id'] end def image_url; image_id ? "http://pillbox.nlm.nih.gov/assets/super_small/#{image_id}ss.png" : nil end #def image_url; image_id ? "http://pillbox.nlm.nih.gov/assets/small/#{image_id}sm.jpg" : nil end def imprint; attrs['splimprint'] end end
true
9f14be62e3aa8246d39276c533833d41aec9cdc0
Ruby
duykhoa/haythat
/test/test_field.rb
UTF-8
1,076
2.5625
3
[]
no_license
require 'helper' class TestField < Minitest::Test def setup @wheat = Wheat.new @field = Field.new end def test_wheat_harvest_time assert_equal(120, @wheat.harvest_time) end def test_grow_wheat @field.grow(@wheat) assert_equal(@wheat, @field.growing_crop) assert_equal(true, @field.occupied?) end def test_grow_set_occupied_at current_time = Time.now @field.grow(@wheat, current_time) assert_equal(current_time, @field.occupied_at) end def test_grow_occupied_field_raise_error @field.grow(@wheat) assert_raises FieldIsOccupiedException do @field.grow(@wheat) end end def test_harvest_blank_field assert_nil @field.harvest end def test_harvest_occupied_field_collectable # TODO: write `minute` helper grow_time = Time.now - 3*60 @field.grow(@wheat, grow_time) assert_equal(HarvestItem, @field.harvest.class) end def test_harvest_occupied_field_before_available grow_time = Time.now @field.grow(@wheat, grow_time) assert_nil @field.harvest end end
true
682db7ad087d746e35e97efdd9dfc2d4faa4f62d
Ruby
adam-patel/stock-trading-ledger
/spec/ledger_spec.rb
UTF-8
1,731
3.375
3
[]
no_license
require 'ledger' # 100 shares bought for 10000 # 50 shares sold for 6000 # 200 shares bought for 11000 describe StockTracker do it 'can add a trade to the trades array' do account = StockTracker.new trade = Trade.new("ULVR", 300, 3948.39) account.trades << trade expect(account.trades.length).to eq(1) end it 'has a #buy method' do expect(StockTracker.new).to respond_to(:buy) end it 'does not have a #test method' do expect(StockTracker.new).not_to respond_to(:test) end it 'calling the #buy method creates a Trade.new' do account = StockTracker.new account.buy("ULVR", 300, 3948.39) expect(account.trades.length).to eq(1) expect(account.trades[0].quantity).to eq(300) end it 'has a #sell method' do expect(StockTracker.new).to respond_to(:sell) end it 'has a #check_current_holdings method' do expect(StockTracker.new).to respond_to(:check_current_holdings_of) end # it 'can tell whether a particular stock is already owned or not' do # account = StockTracker.new # account.buy("ULVR", 300, 4949.43) # expect(account.check_current_holdings_of("ULVR")).to eq(true) # expect() # end it 'has a #create_trade_record' do expect(StockTracker.new).to respond_to(:create_trade_record) end it '#create_trade_record creates a hash' do account = StockTracker.new account.create_trade_record("ULVR", 300, 4040.40) expect(account.current_holdings[0]["market"]).to eq("ULVR") end end describe Trade do it 'can record a trade' do trade = Trade.new("ULVR", 300, 4564.43) expect(trade.market).to eq("ULVR") expect(trade.quantity).to eq(300) expect(trade.book_cost).to eq(4564.43) end end
true
857ff411c8527da276e2d2f6d2cfc89d06acb400
Ruby
Kimtaro/ve
/lib/misc.rb
UTF-8
106
2.8125
3
[ "MIT" ]
permissive
class Enumerator def more? begin self.peek true rescue false end end end
true
391ef38d1d8bd1368d5adebaac866bc97940e860
Ruby
eliyooy/tic-tac-toe-rb-q-000
/lib/tic_tac_toe.rb
UTF-8
3,003
4.0625
4
[]
no_license
WIN_COMBINATIONS = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ] def display_board(board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]) seperator = "-----------" puts " #{board[0]} | #{board[1]} | #{board[2]} " puts seperator puts " #{board[3]} | #{board[4]} | #{board[5]} " puts seperator puts " #{board[6]} | #{board[7]} | #{board[8]} " end def move(array, input, char = "X") array[input.to_i - 1] = char end def position_taken?(board, position) if position < 0 || position > 9 return nil elsif board[position] == "" || board[position] == " " || board[position] == " " return false elsif board[position] == "X" || board[position] = "O" return true end end def valid_move?(board, position) realPosition = position.to_i - 1 if position_taken?(board, realPosition) == true || position_taken?(board, realPosition) == nil return false else return true end end def turn(board) input = gets.strip until valid_move?(board, input) puts "Invalid entry." display_board(board) input = gets.strip end move(board, input, current_player(board)) end def turn_count(board) turnCount = 0 board.each do |spot| if spot == "X" || spot == "O" turnCount += 1 end end return turnCount end def current_player(board) turnCount = turn_count(board) if turnCount % 2 == 0 return "X" else return "O" end end def won?(board) if WIN_COMBINATIONS.none? do |streak| (board[streak[0]] == "X" && board[streak[1]] == "X" && board[streak[2]] == "X") || (board[streak[0]] == "O" && board[streak[1]] == "O" && board[streak[2]] == "O") end return false else WIN_COMBINATIONS.each do |streak| if (board[streak[0]] == "X" && board[streak[1]] == "X" && board[streak[2]] == "X") || (board[streak[0]] == "O" && board[streak[1]] == "O" && board[streak[2]] == "O") return streak end end end end def full?(board) if board.all? do |spot| spot == "X" || spot == "O" end return true else return false end end def draw?(board) if won?(board) == false && full?(board) == true return true else return false end end def over?(board) if won?(board) != false || full?(board) == true || draw?(board) == true return true else return false end end def winner(board) if won?(board) == false return nil else WIN_COMBINATIONS.each do |streak| if (board[streak[0]] == "X" && board[streak[1]] == "X" && board[streak[2]] == "X") return "X" elsif (board[streak[0]] == "O" && board[streak[1]] == "O" && board[streak[2]] == "O") return "O" end end end end def play(board) until over?(board) == true display_board(board) turn(board) end display_board(board) puts "Thank you for playing!" if won?(board) != false puts "Congratulations #{winner(board)}!" else puts "Cats Game!" end end
true
3187d26af055df7175ba8935cbd0bb0140c435e9
Ruby
jlblumberg/bank-tech-test
/lib/statement.rb
UTF-8
674
3.328125
3
[]
no_license
class Statement HEADER = "date || credit || debit || balance\n" def initialize(account) @transactions = account.transactions end def print_statement format_statement print @transactions end private def add_header @transactions = HEADER + @transactions end def reverse_transactions @transactions = @transactions.each_slice(4).to_a.reverse end def add_pipes_and_newlines @transactions.map! { |transaction| transaction.join(" || ") } @transactions = @transactions.join("\n") end def format_statement reverse_transactions add_pipes_and_newlines add_header @transactions.gsub!(" ", " ") end end
true
5598fb2f8b2b82ef56d90ef5756dd940ef74e28c
Ruby
codekunoichi/learning-ruby
/method_example.rb
UTF-8
795
4.5625
5
[ "CC0-1.0" ]
permissive
def prime(n) puts "That's not an integer." unless n.is_a? Integer is_prime = true for i in 2..n-1 if n % i == 0 is_prime = false end end if is_prime puts "#{n} is prime!" else puts "#{n} is not prime." end end prime(2) prime(9) prime(11) prime(51) prime(97) def greeter(name) return name end def by_three?(number) if number % 3 == 0 return true else return false end end # The block, {|i| puts i}, is passed the current # array item each time it is evaluated. This block # prints the item. [1, 2, 3, 4, 5].each { |i| puts i } # This block prints the number 5 for each item. # (It chooses to ignore the passed item, which is allowed.) [1, 2, 3, 4, 5].each { |i| puts i*5 } my_array = [1, 2, 3, 4, 5] my_array.each do |n| puts n*n end
true
0820952f31bd0eeb61f0db87357bbd77644215b1
Ruby
bmordan/ruby-cli-journal
/lib/journal.rb
UTF-8
869
2.78125
3
[ "MIT" ]
permissive
require "journal/version" module Journal class Instruct def initialize puts "Welcome to journal use the --help flag for instructions" end end class Input def initialize (args) date, entry = args entry = entry ? entry : date case date when "today" date = Time.now when "yesterday" date = Time.now - (60 * 60 * 24) when /-/ date = Time.new(date) else date = Time.now end date = date.strftime("%a %-d %b %h:%m") Journal::Entry.new("#{date} | #{entry}") end end class Entry def initialize(entry) dest = "#{Dir.home}/.cli-journal" if File.exist?(dest) File.open(dest, "a+") {|file| file.puts entry} else file = File.new(dest, "a+") file.puts entry file.close() end end end end
true
5bb8a5f12414e8fb67592cab0491fe5bb48df592
Ruby
anitacanita/bananas_airport
/lib/plane.rb
UTF-8
209
2.765625
3
[]
no_license
class Plane def initialize @airborne = true end def land! @airborne = false end def take_off! @airborne = true end def flying_status @airborne ? 'flying' : 'landed' end end
true
3f1dcaf2551ef5e521cb350123a7bfa165429886
Ruby
trouni/batch-656
/livecodes/animals/spec/meerkat_spec.rb
UTF-8
578
3.03125
3
[]
no_license
require_relative '../meerkat' describe Meerkat do describe '#initialize' do it 'returns an instance of Meerkat' do meerkat = Meerkat.new('Napoleon') expect(meerkat).to be_a(Meerkat) end end describe '#name' do it 'returns the name of the meerkat' do meerkat = Meerkat.new('Napoleon') expect(meerkat.name).to eq('Napoleon') end end describe '#talk' do it 'returns the sound the meerkat makes' do meerkat = Meerkat.new('Napoleon') expected = 'Napoleon barks' expect(meerkat.talk).to eq(expected) end end end
true
5fda0cb565aa2ce7d05aa5f9bd5767b17532960b
Ruby
micahbales/Launch-Academy
/challenges/phase-2/online_souq/part1.rb
UTF-8
955
3.515625
4
[]
no_license
puts "Howdy shopper? What's your name?" name = gets.chomp items = ["old paperback book", "potato", "red onion", "dried lemon", "frankincense", "medicinal herbs", "saffron", "glass spice jar", "red fabric", "orange fabric", "handicrafts", "small Persian rug", "medium Persian rug", "large Persian rug", "extra large Persian rug"] puts "Welcome, #{name}! We offer the following items: \n \n" items.each do |item| puts "* #{item}" end puts "\n" user_items = [] puts "So what would you like to buy?" puts "Type 'FINISHED' when you've told me everything" input = "" while input != "FINISHED" do input = gets.chomp if items.include?(input) user_items.push(input) puts "\nGreat, #{input} is one of my favorites." puts "What else? \n \n" else puts "\nSorry, we don't have #{input}. What else can I get you? \n \n" end end puts "Very well! You have selected: \n \n" user_items.each do |item| puts "* #{item}" end puts "\n"
true
dbd3e3f6a461584a853515267abab3c115116697
Ruby
ijikeman/Study
/RUBY/EVENTMACHINE/HELLO/timer2.rb
UTF-8
276
2.546875
3
[]
no_license
require 'eventmachine' EM.run do p = EM::PeriodicTimer.new(1) do puts 'Tick...' end EM::Timer.new(3) do puts 'BOOM' end EM::Timer.new(2) do puts 'Tack...' end EM::Timer.new(5) do puts 'BOOM2' end EM::Timer.new(10) do EM.stop end end
true
66e958c04de37c77d43723887719e747b120f769
Ruby
CatalanoWebDevelopment/ttt-8-turn-v-000
/bin/turn
UTF-8
296
3.59375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
#!/usr/bin/env ruby # REQUIRE #turn.rb FILE require_relative '../lib/turn.rb' # SET AN EMPTY BOARD AT START board = [" ", " ", " ", " ", " ", " ", " ", " ", " "] # OUTPUT A GREETING puts "Welcome to Tic Tac Toe!" # DISPLAY THE EMPTY BOARD display_board(board) # BEGIN TURN METHOD turn(board)
true
8ef72b7299e6e4db379ee0bce57e86c1f3c5ab90
Ruby
justonemorecommit/puppet
/lib/puppet/functions/round.rb
UTF-8
488
3.609375
4
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
# Returns an `Integer` value rounded to the nearest value. # Takes a single `Numeric` value as an argument. # # @example 'rounding a value' # # ```puppet # notice(round(2.9)) # would notice 3 # notice(round(2.1)) # would notice 2 # notice(round(-2.9)) # would notice -3 # ``` # Puppet::Functions.create_function(:round) do dispatch :on_numeric do param 'Numeric', :val end def on_numeric(x) if x > 0 Integer(x + 0.5) else Integer(x - 0.5) end end end
true
841362b7bbc76b17a0fc71177d193cf63324f7d3
Ruby
M-Munk/programming_with_ruby
/hashes/challenge.rb
UTF-8
881
4.03125
4
[]
no_license
# problem: determine words that have the same letters and return and array of # those words # should return a different array for each set of words with the same letters # chars method returns an array of characters from a string # sort orders an array words = ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live', 'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide', 'flow', 'neon'] # arrange words into sorted array for comparison # iterate through words # arrange word into a key based on alphabetical sorting of the word # if the key does not exist, add the key and add word to value array # if the key already exists, just add the value # print values anagrams = {} words.each do |word| key = word.chars.sort.join unless anagrams.has_key?(key) anagrams[key] = [word] else anagrams[key].push(word) end end anagrams.each { |key, value| p value}
true
fe782ad64c9059e1d63e7e834e7c15d6a4bceeee
Ruby
metchadou/Chess-game
/piece.rb
UTF-8
673
3.234375
3
[]
no_license
require "byebug" class Piece attr_accessor :board attr_reader :color, :position def initialize(color, board, position) @color, @board, @position = color, board, position end def to_s " #{symbol} " end def empty? color.nil? end def position=(val) @position = val end def symbol end def inspect {symbol: symbol, color: color, pos: position}.inspect end def valid_moves moves.reject {|pos| move_into_check?(pos)} end def move_into_check?(end_pos) board_dup = @board.deep_dup board_dup.update_board_ref_of_pieces board_dup.move_piece!(@position, end_pos) board_dup.in_check?(@color) end end
true
debedf325504c49c0f67a379fcea10aa68bab350
Ruby
sergioschuler/tealeaf-ruby-book-01-basics
/01.basics/01.03_movie_year.rb
UTF-8
163
2.875
3
[]
no_license
movies = {:matrix => 1999, :blade_runner => 1982, :another_random_movie => 2015} puts movies[:matrix] puts movies[:blade_runner] puts movies[:another_random_movie]
true
84060834f85bc00719980696058ef6b8e2769dbd
Ruby
GalaxyAstronaut/deli-counter-onl01-seng-ft-012120
/deli_counter.rb
UTF-8
655
3.96875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your code here. katz_deli = [] def line(numinline) line_method_arr = [] if numinline.length == 0 puts "The line is currently empty." else numinline.each_with_index do |name,index| line_method_arr.push("#{index + 1}. #{name}") end puts "The line is currently: #{line_method_arr.join(" ")}" end end def take_a_number(katz_deli,name) katz_deli.push(name) puts "Welcome, #{name}. You are number #{katz_deli.length} in line." end def now_serving(nextperson) if nextperson.empty? puts "There is nobody waiting to be served!" else puts "Currently serving #{nextperson[0]}." nextperson.shift end end
true
4293aa412f50e20070df2474118b8207054ecf56
Ruby
gaohongwei/cs
/offer/oral_offer.rb
UTF-8
763
2.734375
3
[]
no_license
### Response to oral offer ### Never negotiate a verbal offer. Wow! Thank you for the offer, and I look forward to going over the details in the written offer before I can give my formal acceptance. When do you expect a response? ### if HR still asks for oral acceptance, say this As of this time, I see no reason not to accept this position— I just feel more comfortable having a written offer in hand ### If HR ask your feedback about the oral offer 1. Try above first 2. If HR insist on requiring a feedback If you want to negotiate, start out with a friendly comment to keep things non-adversarial. Say I really appreciate this job offer and I’ve got to tell you I’d love to work here. Then make a counter offer.
true
aac7c1ac4bbe2843cdf6f73ccfa7dd27fd62e1d4
Ruby
TheLosingEdge/head-first-ruby-exercises
/Exercises/Chp2/dog.rb
UTF-8
524
4.15625
4
[]
no_license
class Dog attr_accessor :name, :age def name=(value) if value == "" raise "Name can't be blank idiot" end @name = value end def move(destination) puts "#{@name} runs to the #{destination} and goes to sleep" end def talk puts "#{@name} says Bark!" end def report_age puts "#{@name} is #{@age} years old" end end dog = Dog.new dog.name = "Butters" dog.age = 9 dog.report_age dog.talk dog.move("bed")
true
24e08cd2a02b76942e412abcf8a3735e442e4523
Ruby
akuhn/euler
/problem_14.rb
UTF-8
1,232
3.734375
4
[]
no_license
require_relative 'euler' # The following iterative sequence is defined for the set of positive integers: # n = n/2 (n is even) # n = 3n + 1 (n is odd) # Using the rule above and starting with 13, we generate the following sequence: # 13 40 20 10 5 16 8 4 2 1 # It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. # Which starting number, under one million, produces the longest chain? # NOTE: Once the chain starts the terms are allowed to go above one million. class Numeric def even? self % 2 == 0 end def next_turtle return nil if self < 2 self.even? ? self/2 : 3*self+1 end @@T = Array.new(10.million) def length_of_chain return 1 if self < 2 return 1 + self.next_turtle.length_of_chain unless self < @@T.size return @@T[self] unless @@T[self].nil? @@T[self] = 1 + self.next_turtle.length_of_chain end end class Range def element_with_longest_chain self.collect{|n|[n,n.length_of_chain]}.sort_by{|a|a.last}.last.first end end 13.length_of_chain.should == 10 (1...1.million).element_with_longest_chain.should == 837799
true
25992227664afb2e055aac0aad09188776510ee6
Ruby
JenniferGrudi/CCAC_TTT
/app.rb
UTF-8
3,242
2.84375
3
[]
no_license
require 'sinatra' require_relative 'sequentialAI.rb' require_relative 'randomAI.rb' require_relative 'console_game.rb' require_relative 'human.rb' enable :sessions set :session_secret, 'This is a secret key' get '/wiki_rules' do @title = 'Wiki' erb :wiki_rules end get '/how_to' do @title = 'How To Play' erb :how_to end get '/' do #this is my homepage, Let's Play TTT @title = 'Welcome to Tic Tac Toe' session[:board] = params[:board] session[:board] = @ttt_board erb :welcome_page, :locals => {:board => session[:board], :current_player => session[:current_player], :message => " ", :welcome_message => "WELCOME!!", :enter => "Let's Play!"} end post '/player_one' do #player name enter @title = 'Player Name' session[:p1_name] = params[:p1_name] session[:p1] = Human.new("X") session[:current_player] = session[:p1] session[:current_player_name] = session[:p1_name] erb :player_name, :locals => {:board => session[:board], :p1_name => session[:p1_name]} end post '/player_2_choice' do #select player mode page. @title = 'Game Mode' session[:p2] = params[:p2] erb :choose_game, :locals => {:board => session[:board], :p2 => session[:p2]} end post '/rival' do #once selected mode should go to game @title = 'Rival' p2_name = params[:p2_name] if session[:p2] == "Human" p2 = Human.new("O") erb :player_name, :locals => {:board => session[:board], :p2_name => session[:p2_name], :p2 => session[:p2]} end end # if session[:p2] == "SequentialAI" # p2 = SequentialAI.new("O") # session[:CPU] = "Tom Riddle" # redirect '/make_move' # elsif session[:p2] == "RandomAI" # p2 = RandomAI.new("O") # session[:CPU] = "Tom Riddle" # redirect '/make_move' # else session[:p2] == "Human" # p2 = Human.new("O") # erb :player_name, :locals => {:board => session[:board], :p2_name => session[:p2_name], # :p2 => session[:p2]} # end # session[:current_player] = p2 # end # get '/make_move' do # session[:move] = params[:move].to_i # session[:board] = update_board(session[:board], session[:move].to_i, session[:current_player][:marker]) # if game_won?(session[:board], session[:current_player].marker) == true # erb :win, :locals => {:board => session[:board], :p1_marker => p1_marker, :p1_name => session[:p1_name], # :p2_marker => p2_marker, :p2_name => session[:name_player_2]} # else # game_ends_in_tie? == true # erb :tie, :locals => {:board => session[:board], :p1_marker => p1_marker, :p1_name => session[:p1_name], # :p2_marker => p2_marker, :p2_name => session[:name_player_2]} # end # if session[:current_player].marker == "X" # session[:current_player] = session[:p2] # session[:current_player_name] = session[:p2_name] # else # session[:current_player] = session[:p1] # session[:current_player_name] = session[:p1_name] # end # erb :get_move, :locals => { :board => session[:board], :current_player => session[:current_player], # :p1 => session[:p1], :p1_marker => p1_marker, :p1_name => session[:p1_name], # :p2 => session[:p2], :p2_marker => p2_marker, :p2_name => session[:name_player_2]} # end
true
1a5a60b0b2171816a7f5a423e5b46a6afbb9d8ca
Ruby
jocelynthode/SocialMovies
/app/models/movie.rb
UTF-8
1,527
2.625
3
[]
no_license
class Movie < ActiveRecord::Base has_many :movielists has_many :lists, through: :movielists attr_accessor :title, :release_date, :actors, :imdb # Retrieve movie model from datastore and add entry in local DB def self.retrieve(mid) q = %Q( SELECT ?id ?title ?releaseDate ?imdb ?actorName WHERE { ?movies rdf:type movie:film . ?movies movie:filmid "#{mid}"^^xsd:int . ?movies rdfs:label ?title . ?movies movie:initial_release_date ?releaseDate . ?movies foaf:page ?imdb . FILTER regex(str(?imdb), '^http://www.imdb.com/title/') OPTIONAL { ?movies movie:filmid "#{mid}"^^xsd:int . ?movies movie:actor ?a . ?a rdf:type movie:actor . ?a movie:actor_name ?actorName } } ) res = RemoteData.linkedmdb_query(q) bindings = res[:results][:bindings] return nil if bindings.empty? movie = Movie.find_or_create_by(id: mid) movie.title = bindings[0][:title][:value] movie.release_date = bindings[0][:releaseDate][:value] movie.imdb = bindings[0][:imdb][:value].split('/').last movie.actors = bindings.map{|x| x[:actorName]}.compact.map{|x| x[:value]} movie end # Populate current instance with info from datastore def retrieve! raise %q('id' cannot be null) if not self.id res = self.class.retrieve(self.id) self.title = res.title self.release_date = res.release_date self.actors = res.actors self.imdb = res.imdb self end end
true
d0417b4537cc718fbf87cb91365322ee9a47010f
Ruby
demullane/katy-perry-hash
/06_favorite_food.rb
UTF-8
301
3.1875
3
[]
no_license
require_relative "person" # Print Katy's favorite foods. It should read "Katy's favorite foods are sushi, hamburgers, and pho." puts "Katy's favorite foods are " + KATY_PERRY[:favorite_foods].first.to_s + ", " + KATY_PERRY[:favorite_foods][1] + ", and " + KATY_PERRY[:favorite_foods].last.to_s + "."
true
528d8c696b4d4f31e3d7665ae970363ef4dcda2a
Ruby
susd/liberty-sis
/lib/tasks/name_stats.rake
UTF-8
1,399
2.796875
3
[]
no_license
namespace :stats do task students: :environment do fname_size = 3 regex = /(\s|-|\'|\")/ while fname_size < 24 puts "Trying #{fname_size}" hsh = Hash.new(0) Aeries::Student.active.pluck(:fn, :fna, :mn, :ln, :gr).each do |fn, fna, mn, ln, gr| middle = (mn.blank? ? '' : mn[0]) # if fna.blank? # fname = fn[0..fname_size].gsub(regex, '') # else # fname = fna.gsub(regex, '') # end fname = fn[0..fname_size].gsub(regex, '') lname = ln.gsub(regex, '') grad = (12 - gr) + Time.now.year hsh["#{fname}#{middle}#{lname}#{grad.to_s[-2, 2]}"] += 1 end dup_count = hsh.keep_if{|k,v| v > 1} # binding.pry if dup_count.size == 0 # binding.pry puts "Stopped at #{fname_size}" break else fname_size += 1 end end end task teachers: :environment do fname_size = 5 lname_size = 18 hsh = Hash.new(0) Teacher.find_each do |teacher| name = (teacher.first_name[0...fname_size] + teacher.lastest_name[0...lname_size]).gsub(/(\s|-|\'|\")/, '') hsh[name] += 1 end dups = hsh.dup.keep_if{|k,v| v > 1} shorts = hsh.find_all{|k,v| k.length < 8} longs = hsh.find_all{|k,v| k.length > 14} puts dups puts shorts.map(&:first) puts longs.map(&:first) end end
true
24ed3751ddaf82da517f8695ce4d599ba7dabf6e
Ruby
Jack2ee/specialsession
/practice2.rb
UTF-8
158
3.015625
3
[]
no_license
woonjang = '졸림' if woonjang == '피곤' puts '공부하자!' elsif woonjang == '졸림' puts '더 가르쳐라!' else puts '가자!'
true
8f91bf074f6fefbe29cbf3e7d315c658898941d1
Ruby
lucaswilric/frsss
/mongo_cache.rb
UTF-8
907
2.640625
3
[]
no_license
require 'mongo_connector' module Cache class NoDataError < Exception; end class MongoCache def initialize(timeout = 600) @timeout = timeout mongo_uri = ENV['MONGO_URI'] || ENV["MONGOHQ_URL"] database = MongoConnector.new(mongo_uri, 'friendly-rss').connection @collection = database['cache'] end def [](url) items = find_entries(url) return nil if items.count == 0 item = items.first keys = item.keys keys.each do |k| item[k.to_sym] = item[k] end item end def []=(url, data) @collection.update({url: url}, data.merge(url: url, updated_at: Time.now), { upsert: true }) data end def valid?(url) items = find_entries(url) items.count > 0 end def find_entries(url) @collection.find(url: url, updated_at: {'$gt' => (Time.now - @timeout)}) end end end
true
d552d124ed94667df4dabfb19b2c0bc0d04900c9
Ruby
dabrorius/dabrorius.github.io
/code_examples/splat-splat-and-double-splat/mix.rb
UTF-8
558
3.3125
3
[]
no_license
# def can_you_do_this?(*positional, **named) # puts positional # puts named # end # can_you_do_this?('first', 'second', name: 'john', surname: 'doe') # def can_you_do_this?(_first, *positional, _second, name:, **named) # puts positional # puts named # puts first # puts second # end # can_you_do_this?('first', 'second', name: 'john', surname: 'doe') def splat_test(*args) puts args.class puts args end puts '----' splat_test('positional', foo: 'bar') puts '----' splat_test('positional', foo: 'bar') puts '----' splat_test(foo: 'bar')
true
f6982870bcbfeaeba08bfd7020c3d267a6fa3b76
Ruby
ngohoaiphuong/ruby-pratices
/examing/15.rb
UTF-8
1,372
3.703125
4
[]
no_license
Move Zeroes Create a function which takes an array arr and moves all zeros to the end, preserving the order of the other elements. Examples move_zeros([1, 0, 1, 2, 0, 1, 3]) ➞ [1, 1, 2, 1, 3, 0, 0] move_zeros([0, 1, nil, 2, false, 1, 0]) ➞ [1, nil, 2, false, 1, 0, 0] move_zeros(['a', 0, 0, 'b', 'c', 'd', 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9]) ➞ ['a', 'b', 'c', 'd', 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ------------- def move_zeros(a) a.select{|b|b != 0} + a.select{|b|b == 0} end -------------- Test.assert_equals(move_zeros([1,2,0,1,0,1,0,3,0,1]), [1,2,1,1,3,1,0,0,0,0]) Test.assert_equals(move_zeros([9,0.0,0,9,1,2,0,1,0,1,0.0,3,0,1,9,0,0,0,0,9]), [9,9,1,2,1,1,3,1,9,9,0,0,0,0,0,0,0,0,0,0]) Test.assert_equals(move_zeros(["a",0,0,"b","c","d",0,1,0,1,0,3,0,1,9,0,0,0,0,9]), ["a","b","c","d",1,1,3,1,9,9,0,0,0,0,0,0,0,0,0,0]) Test.assert_equals(move_zeros(["a",0,0,"b",nil,"c","d",0,1,false,0,1,0,3,[],0,1,9,0,0,0,0,9]), ["a","b",nil,"c","d",1,false,1,3,[],1,9,9,0,0,0,0,0,0,0,0,0,0]) Test.assert_equals(move_zeros([0,1,nil,2,false,1,0]), [1,nil,2,false,1,0,0]) Test.assert_equals(move_zeros(["a","b"]), ["a","b"]) Test.assert_equals(move_zeros(["a"]), ["a"]) Test.assert_equals(move_zeros([0,0]), [0,0]) Test.assert_equals(move_zeros([0]), [0]) Test.assert_equals(move_zeros([false]), [false]) Test.assert_equals(move_zeros([]), []) #Mubashir
true
d01b20ed483fc89a6c814c791d119a676c71b531
Ruby
gorails-screencasts/http-server-from-scratch
/request.rb
UTF-8
607
3.15625
3
[]
no_license
class Request attr_reader :method, :path, :headers, :body, :query def initialize(request) lines = request.lines index = lines.index("\r\n") @method, @path, _ = lines.first.split @path, @query = @path.split("?") @headers = parse_headers(lines[1...index]) @body = lines[(index + 1)..-1].join puts "<- #{@method} #{@path} #{@query}" end def parse_headers(lines) headers = {} lines.each do |line| name, value = line.split(": ") headers[name] = value.chomp end headers end def content_length headers["Content-Length"].to_i end end
true
956e4542ac5d0db5b8ecc830371d7f9689a89cbd
Ruby
hilarysk/daily-feminist-affirmation
/app/models/user.rb
UTF-8
1,743
2.6875
3
[]
no_license
# Class: User # # Creates different users. # # Attributes: # @email - String: User email # @user_name - String: User name # @id - Integer: user ID, primary key for users table # @password - String: user's password # # Public Methods: # #self.user_name_pass_search # #insert # # Private Methods: # #initialize require 'bcrypt' class User < ActiveRecord::Base include FeministInstanceMethods include BCrypt attr_accessible :user_name, :email, :password_hash, :privilege, :created_at, :status validates :email, uniqueness: { case_sensitive: false } validates :email, :password, presence: true has_many :terms has_many :excerpts has_many :people has_many :quotes #bcrypt method def password @password ||= Password.new(password_hash) end #bcrypt method def password=(new_password) @password = Password.create(new_password) self.password_hash = @password end # put user's contributions in descending order def items_array_sorted_descending array = [] self.excerpts.each do |object| array.push object end self.quotes.each do |object| array.push object end self.terms.each do |object| array.push object end self.people.each do |object| array.push object end return array.sort! {|b,a| a.updated_at<=>b.updated_at} end # get array of items belonging to a user in order by type def items_array array = [] self.excerpts.each do |object| array.push object end self.quotes.each do |object| array.push object end self.terms.each do |object| array.push object end self.people.each do |object| array.push object end return array end end
true
fa25d5aef0edc1fa4c3ecfc3200051295eaca4b8
Ruby
macsrok/best-attempt-gem-updater
/best_attempt_gem_updater.rb
UTF-8
3,496
3.234375
3
[]
no_license
class BestAttemptGemUpdater def initialize(gems) @gems = gems @original_commit = "" @skipped_gems = [] @failed_gems = [] @updated_gems = [] end def attempt_gem_update puts 'This is experimental software. Use at your own risk. Any damage to your code base is not my fault!' puts '#######' puts '#######' puts ' Are you sure you want to proceed? Type YES to continue, any other input will exit.' user_input = gets.chomp unless user_input == 'YES' puts 'Did not recieve YES, exiting.' return end unless clean_working_tree? puts 'A clean working tree is required. please commit your changes before you continue.' return end @original_commit = current_commit @gems.each do |gem| update_gem(gem) end puts 'All Done! 😸' puts '' puts '######' puts "#{@updated_gems.count} gems were updated. would you like to display them? Y/N" if gets.chomp.downcase == 'y' @updated_gems.each do |gem| puts gem end puts '' puts '' end puts '######' puts "#{@skipped_gems.count} gems did not require updates. Would you like to display them? Y/N" if gets.chomp.downcase == 'y' @skipped_gems.each do |gem| puts gem end puts '' puts '' end puts '######' puts "#{@failed_gems.count} gems broke rspec. Would you like to display them? Y/N" if gets.chomp.downcase == 'y' @failed_gems.each do |gem| puts gem end puts '' puts '' end puts '' puts '' puts '######' puts 'If this broke your app Please run the following command to get back to where we started.' puts "git reset --hard #{@original_commit}" end def update_gem(gem) fallback_commit = current_commit puts "Updating gem: #{gem}" if update_required?(gem) puts "## update required" if bundler_update(gem) if rspec_green? puts "## Rspec Paased!" commit_changes(gem) @updated_gems << gem else puts "## rspec failed" @failed_gems << gem reset_to_commit(fallback_commit) end else puts "## update failed" @failed_gems << gem reset_to_commit(fallback_commit) end else puts "## update not required" @skipped_gems << gem end end def bundler_update(gem) puts "## attempting update" system("bundle update #{gem}") end def rspec_green? system('rspec --fail-fast') end def current_commit `git rev-parse HEAD`.chomp end def reset_to_commit(commit) `git reset --hard #{commit}` end def update_required?(gem) `bundle outdated #{gem}`.include?('Outdated gems included in the bundle:') end def commit_changes(gem) `git commit -am '#{gem} was updated. Automatic commit.'` end def clean_working_tree? `git status`.include?('nothing to commit, working tree clean') end end
true
38d5c251ab0e79397a0887ac01d62ca65cb307ad
Ruby
pikonori/auto_sftp
/lib/autosftp/cli.rb
UTF-8
2,791
2.984375
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- require 'thor' require 'autosftp/monitor' require 'autosftp/file_access' require 'autosftp/connection' module Autosftp class CLI < Thor desc "start [remote name]", "Automatic monitoring start" option :chmod def start(*word) if false == Autosftp::FileAccess.exist? puts "is not .autosftp \n $ autosftp init" exit end conf = Autosftp::FileAccess.read if !conf[word[0]] puts "is not setting \n $ autosftp set [remote name]" exit elsif setting = conf[word[0]] word.delete_at(0) end if 0 < word.size dir = word.map {|a| a.to_s + "**/*"} else dir = '**/*' end permission = {} if options[:chmod] permission[:dir] = options[:chmod] permission[:file] = options[:chmod] else permission[:dir] = 755 permission[:file] = 644 end Autosftp::Monitor.start setting, dir, permission end desc "set [remote name]", "add information to the '.autosftp'. Please put the name of any [remote name]" def set(word) ssh_hash = {} begin puts "[username@host:port]" ssh_str = STDIN.gets.chomp if false == Autosftp::Connection.check?(ssh_str) puts "is not [username@host:port]" exit end ssh_hash = Autosftp::Connection.explode ssh_str puts "password:" ssh_hash[:password] = STDIN.noecho(&:gets).chomp puts "remote path:" ssh_hash[:remote_path] = STDIN.gets.chomp puts "local path: --If you enter a blank, the current directory is set" ssh_hash[:local_path] = STDIN.gets.chomp if '' == ssh_hash[:local_path] ssh_hash[:local_path] = Dir.pwd puts ssh_hash[:local_path] end Autosftp::FileAccess.save word, ssh_hash rescue Interrupt end end desc "delete [remote name]", "remove the configuration." def delete(word) Autosftp::FileAccess.delete word end desc "list", "setting list" def list() Autosftp::FileAccess.read.each do |key, value| puts <<"EOS" #{key}: host: #{value[:host]} local_path: #{value[:local_path]} remote_path: #{value[:remote_path]} EOS end end desc "init", "Creating the initial file. file called '.autosftp' is created" def init init_file = Autosftp::FileAccess if true == init_file.exist? if yes? "File exists. Overwrite the file? [y/n]" init_file.create puts 'overwite!!! (' + init_file.path + ')' else puts 'cancel' end else init_file.create puts 'create!!! (' + init_file.path + ')' end end end end
true
8ee203583a699f350e32132049a889d056384ff8
Ruby
theotherzach/exercism.io
/assignments/ruby/bob/example.rb
UTF-8
1,090
3.90625
4
[]
no_license
class Bob def hey(something) if silent?(something) 'Fine. Be that way.' elsif question?(something) 'Sure.' elsif shouting?(something) 'Woah, chill out!' else 'Whatever.' end end private def question?(s) s.end_with?('?') end def silent?(s) s.empty? end def shouting?(s) s.upcase == s end end class AnswerSilence def self.handles?(input) input.empty? end def reply 'Fine. Be that way.' end end class AnswerQuestion def self.handles?(input) input.end_with?('?') end def reply 'Sure.' end end class AnswerShout def self.handles?(input) input == input.upcase end def reply 'Woah, chill out!' end end class AnswerDefault def self.handles?(input) true end def reply 'Whatever.' end end class Alice def hey(input) answerer(input).reply end private def answerer(input) handlers.find {|answer| answer.handles?(input)}.new end def handlers [AnswerSilence, AnswerQuestion, AnswerShout, AnswerDefault] end end
true
0e8d34f046a57d65142619efe7720640efa614a0
Ruby
hgodinot/hgodinot-Launch_School
/RB130/lesson/car.rb
UTF-8
213
3.34375
3
[]
no_license
class Vehicle ; end class Car < Vehicle attr_accessor :wheels, :name, :colour def initialize(name) @wheels = 4 @name = name end def ==(other) other.is_a?(Car) && name == other.name end end
true
d10fe92e7091277005e8777fa51dfb6a6a281119
Ruby
Reactician/RubyBuby
/2uzd/2uzd.rb
UTF-8
244
2.84375
3
[]
no_license
# frozen_string_literal: true puts 'Įveskite egzamino bala' a = gets.to_i if a >= 5 && a < 11 puts 'Egzaminas išlaikytas' elsif a < 5 && a.positive? puts 'Egzaminas neišlaikytas' else puts 'tokio pazymio negali buti' end
true
1047467140fc7ce6877a09563233cf071746f78d
Ruby
dmdinh22/PreCourse
/exercises_methods.rb
UTF-8
310
4.15625
4
[]
no_license
#1 def greeting(name) puts "Hello " + name = "." end puts greeting("David") #2 x = 2 puts x = 2 p name = "Joe" four = "four" print something = "nothing" #3 def multiply(x, y) x * y end puts multiply(3, 5) #4, 5 def scream(words) words = words + "!!!!" puts words "Hi there" end scream("Yippeee")
true
9c744308821014f1fbd48f0f262d156b32d670e3
Ruby
tianbymy/relative_time
/lib/relative_time/in_words.rb
UTF-8
1,092
3.1875
3
[ "MIT" ]
permissive
module RelativeTime class InWords def call(date_to, date_from) diff = date_from.to_time - date_to.to_time return '1分钟前' if diff.abs.round <= 59 date_string = verb_agreement(resolution(diff.abs.round)) diff >= 0 ? "#{date_string} 前" : "#{date_string}" end private MINUTE = 60 HOUR = 60 * MINUTE DAY = 24 * HOUR WEEK = 7 * DAY MONTH = 4 * WEEK YEAR = 12 * MONTH def resolution(diff) if diff >= YEAR [(diff / YEAR).round, '年'] elsif diff >= MONTH [(diff / MONTH).round, '月'] elsif diff >= WEEK [(diff / WEEK).round, '周'] elsif diff >= DAY [(diff / DAY).round, '天'] elsif diff >= HOUR [(diff / HOUR).round, '小时'] else [(diff / MINUTE).round, '分钟'] end end def verb_agreement(resolution) if resolution[0] == 1 && resolution.last == '小时' '小时' elsif resolution[0] == 1 resolution.last[0...-1] else resolution.join(' ') end end end end
true
70f7fedcdf58e95f67e628501ae94860b558579b
Ruby
heythor/Estudos
/ForWhile/resta5.rb
UTF-8
135
3.0625
3
[]
no_license
valor = 1001 while valor != 2000 if valor % 11 == 5 puts valor valor += 1 else valor += 1 end end
true
3fe05dcf06669494525a4bc9b77369330a706642
Ruby
lucianoq/codejam
/17/round_1C/A_ample-syrup/main.rb
UTF-8
1,233
3.34375
3
[]
no_license
#!/usr/bin/env ruby class Pancake attr_reader :r attr_reader :h attr_reader :lsurf attr_reader :area attr_reader :syrup def initialize(r, h) @r, @h = r.to_f, h.to_f @lsurf = @h * (2*Math::PI*@r) @area = @r**2 * Math::PI @syrup = @lsurf + @area end end def area_gain(new, min, last) (new.area - last.area) + (new.lsurf - min.lsurf) end def solve(k, pp) set = (pp.sort_by { |x| -x.lsurf })[0...k].sort_by { |x| -x.r } bases = (pp-set).select { |x| x.r>=set[0].r } if bases.size != 0 min_lsurf_stack = set.min_by { |x| x.lsurf } max_gain_base = bases.max_by { |x| area_gain(x, min_lsurf_stack, set[0]) } if area_gain(max_gain_base, min_lsurf_stack, set[0]) > 0 set[set.index(min_lsurf_stack)] = max_gain_base set = set.sort_by { |x| -x.r } end end area = set[0].area lateral = set.map { |x| x.lsurf }.inject(:+) area + lateral end def main $stdin.readline.to_i.times do |i| n, k = $stdin.readline.strip.split(' ').map(&:to_i) pp = [] n.times do ri, hi = $stdin.readline.strip.split(' ').map(&:to_i) pp << Pancake.new(ri, hi) end result = solve(k, pp) puts "Case ##{i+1}: " + '%.9f' % result.round(9) end end main
true
a6e9d66e97dc62af5073b5e36da90088278abe93
Ruby
davemerritt/learn_ruby
/02_calculator/calculator.rb
UTF-8
185
3.484375
3
[]
no_license
def add(a,b) return a + b end def subtract(a,b) return a - b end def sum(number) sum = 0 number.each { |x| sum += x } return sum end def multiply(*num) return num * num end
true
34798cecb1d77ce3c09dd70f560b8f76675f7152
Ruby
tradener/cardinality-br
/lib/brazilian_cardinality/number.rb
UTF-8
4,325
3.59375
4
[ "MIT" ]
permissive
module BrazilianCardinality module Number NumberTooBigError = Class.new(StandardError) ONES = { 0 => 'zero', 1 => 'um', 2 => 'dois', 3 => 'três', 4 => 'quatro', 5 => 'cinco', 6 => 'seis', 7 => 'sete', 8 => 'oito', 9 => 'nove' }.freeze TENS = { 10 => 'dez', 11 => 'onze', 12 => 'doze', 13 => 'treze', 14 => 'quatorze', 15 => 'quinze', 16 => 'dezesseis', 17 => 'dezessete', 18 => 'dezoito', 19 => 'dezenove', 20 => 'vinte', 30 => 'trinta', 40 => 'quarenta', 50 => 'cinquenta', 60 => 'sessenta', 70 => 'setenta', 80 => 'oitenta', 90 => 'noventa' }.freeze HUNDREDS = { 100 => 'cento', 200 => 'duzentos', 300 => 'trezentos', 400 => 'quatrocentos', 500 => 'quinhentos', 600 => 'seiscentos', 700 => 'setecentos', 800 => 'oitocentos', 900 => 'novecentos' }.freeze class << self def number_cardinal(number) negative = number.negative? ? 'menos ' : '' abs_value = number.abs decimals = abs_value.to_s.split('.')[1].to_s[0, 2] integer = abs_value.to_i expression = raw_cardinal_expression(integer, decimals) "#{negative}#{expression}" end private def raw_cardinal_expression(integer, decimals) integer_expression = cardinal_number_integer_part(integer) cents_expression = cardinal_decimals(decimals) [integer_expression, cents_expression].compact.join(' vírgula ') end def cardinal_number_integer_part(value) case value when 0..999 then cardinal_for_0_up_to_999(value) when 1000..999_999_999_999_999 then cardinal_for_thousands_to_trillions(value) else raise NumberTooBigError, "#{value} is too big" end end def cardinal_decimals(decimals) return if decimals.to_i.zero? if decimals[0].to_i.zero? decimal_prefix = 'zero' end decimals = decimals.to_i [decimal_prefix, Number.number_cardinal(decimals)].compact.join(' ') end def cardinal_for_0_up_to_999(number) case number when 0..9 then ONES[number] when 10..19 then TENS[number] when 20..99 then cardinal_for_tens_and_hundreds(number, 10) when 100 then 'cem' when 101..999 then cardinal_for_tens_and_hundreds(number, 100) end end def cardinal_for_thousands_to_trillions(number) case number when 1000..999_999 cardinal_for_scale_of_thousands(number, 1_000, 'mil', 'mil') when 1_000_000..999_999_999 cardinal_for_scale_of_thousands(number, 1_000_000, 'milhão', 'milhões') when 1_000_000_000..999_999_999_999 cardinal_for_scale_of_thousands(number, 1_000_000_000, 'bilhão', 'bilhões') when 1_000_000_000_000..999_999_999_999_999 cardinal_for_scale_of_thousands(number, 1_000_000_000_000, 'trilhão', 'trilhões') end end def cardinal_for_tens_and_hundreds(number, scale) remainder = number % scale words_map = scale == 10 ? TENS : HUNDREDS return words_map[number] if remainder.zero? "#{words_map[number - remainder]} e #{number_cardinal(remainder)}" end def cardinal_for_scale_of_thousands(number, scale, singular, plural) quocient = number / scale remainder = number % scale word = quocient > 1 ? plural : singular high_order_units = "#{number_cardinal(quocient)} #{word}" return high_order_units if remainder.zero? "#{high_order_units} e #{number_cardinal(remainder)}" end def cardinal_for_fraction(fraction) return '' unless fraction fraction = (fraction * 10).to_i fraction_expression = case fraction when 0..999 then cardinal_for_0_up_to_999(fraction) when 1000..999_999_999_999_999 then cardinal_for_thousands_to_trillions(fraction) else raise NumberTooBigError, "#{fraction} is too big" end ' vírgula ' + fraction_expression end end end end
true
d9e50c3828f8b0ac47fb24a3530e8c7f5d4b0269
Ruby
savyounts/Netflix_Bestflix
/lib/netflix_bestflix/movie.rb
UTF-8
1,150
2.71875
3
[ "MIT" ]
permissive
class NetflixBestflix::Movie attr_accessor :title, :position, :url, :genre, :rt_score, :viewer_score, :description, :rating @@all = [] def initialize(title = nil, position = nil, url = nil) @title = title @position = position @url = url @@all << self end def self.new_from_scrape(s) self.new( s.css("h2 a").text, s.css(".countdown-index").text.gsub('#',''), s.css("h2 a").attr("href").value ) end def self.find_by_position(position) self.all.find {|movie| movie.position == position} end def genre @genre ||= doc.css(".panel-body ul li:nth-child(2) .meta-value").text.strip end def rating @rating ||= doc.css(".panel-body ul li:nth-child(1) .meta-value").text end def rt_score @rt_score ||= doc.css(".critic-score .meter-value").text.gsub(/%(.*)/, "%") end def viewer_score @viewer_score ||= doc.css(".audience-score .meter-value span").text end def description @description ||= doc.css("#movieSynopsis").text.strip end def self.all @@all end def doc @doc ||= Nokogiri::HTML(open(self.url)).css("#mainColumn") end end
true
0ec5f7582ee30399ef1137db0aaaa74e4bc2d585
Ruby
arrayfire/arrayfire-rb
/test/blas_test.rb
UTF-8
928
2.703125
3
[ "BSD-3-Clause" ]
permissive
require 'test_helper' class ArrayFire::BLASTest < Minitest::Test def setup @matrix_left = ArrayFire::Af_Array.new 2, [2,2],[ 12, 21,-61, 48] @matrix_right = ArrayFire::Af_Array.new 2, [2,2],[-15, 41, 30 , 7 ] @vector_left = ArrayFire::Af_Array.new 2, [4,1],[-15, 41, 30 , 7 ] @vector_right = ArrayFire::Af_Array.new 2, [4,1],[ 25, 141, 17 , 7 ] end def test_matmul result = ArrayFire::Af_Array.new 2, [2,2],[-2681.0, 1653.0, -67.0, 966.0] assert_equal result, ArrayFire::BLAS.matmul(@matrix_left, @matrix_right, :AF_MAT_NONE, :AF_MAT_NONE) end def test_dot result = ArrayFire::Af_Array.new 1,[1],[5965.0] assert_equal result, ArrayFire::BLAS.dot(@vector_left, @vector_right, :AF_MAT_NONE, :AF_MAT_NONE) end def test_transpose result = ArrayFire::Af_Array.new 2, [2,2], [12.0, -61.0, 21.0, 48.0] assert_equal result, ArrayFire::BLAS.transpose(@matrix_left) end end
true
c706e3d466f530b1a5ad55609e94e76789c01680
Ruby
dgarate/arreglos
/smartwatch1.rb
UTF-8
622
3.109375
3
[]
no_license
def clear_steps (pasos) pasos_sin_letras = pasos.select do |paso| if paso.class == Integer # added this "if" to ensure that program would work if the array contains Integer and String paso else orig_length = paso.length new_length = paso.to_i.to_s.length orig_length == new_length end end n = pasos_sin_letras.count pasos_validos = [] n.times do |i| if pasos_sin_letras[i].to_i >= 200 && pasos_sin_letras[i].to_i < 100000 pasos_validos.push pasos_sin_letras[i].to_i end end print pasos_validos end clear_steps([300, '100', '21', '231as', '2031', '1052000', '213b', 'b123'])
true
05866548e4e558ce978394fc88a4294825e6cddb
Ruby
rchavesc/ruby_introduction
/05_printing.rb
UTF-8
119
3.1875
3
[]
no_license
puts 'soy un texto en la terminal' print 'hola' print 'soy un texto en print' #print no crea un salto de linea, puts si
true
cacd9517fa75cc63a7630a8b40db7f4f6d8388b0
Ruby
mknicos/coursewareofthefuture
/features/step_definitions/time_steps.rb
UTF-8
325
2.578125
3
[ "MIT" ]
permissive
Given(/^that it is (\d+)\/(\d+)\/(\d+)$/) do |year, month, day| t = Time.new(year.to_i, month.to_i, day.to_i) Timecop.travel(t) end Given(/^that it is (\d+)\/(\d+)\/(\d+) (\d+):(\d+)AM$/) do |year, month, day, hour, minute| t = Time.new(year.to_i, month.to_i, day.to_i, hour.to_i, minute.to_i) Timecop.travel(t) end
true
5f4cad3f07250b1a317c840b317ce22e9fb67f67
Ruby
pomartel/auto_html-contrib
/lib/auto_html/gist.rb
UTF-8
421
2.546875
3
[ "MIT" ]
permissive
require 'tag_helper' module AutoHtml # Gist filter class Gist include TagHelper def call(text) regex = %r{https?://gist\.github\.com/(\w+/)?(\d+)} text.gsub(regex) do gist_id = Regexp.last_match(2) tag(:script, type: 'text/javascript', src: gist_url(gist_id)) { '' } end end private def gist_url(id) "https://gist.github.com/#{id}.js" end end end
true
559e11fa897fdfff1fcaa59f6fa14968c042d86d
Ruby
jdwolk/form_io
/spec/output/form_spec.rb
UTF-8
1,548
2.71875
3
[ "MIT" ]
permissive
require 'spec_helper' describe FormIO::Output::Form do class PhoneReader < Struct.new(:phone) def value=(model_value) @value = model_value end def value phone = @value.split('') area_code = phone.take(3).join first_three = phone.drop(3).take(3).join last_four = phone.drop(6).join "(#{area_code}) #{first_three}-#{last_four}" end end class UserDetailsForm < FormIO::Output::Form field :name field :phone, transformer: PhoneReader end describe 'fields' do it 'normalizes field values according to assigned transfomers' do user = OpenStruct.new(phone: '9098876543') subject = UserDetailsForm.new(user) normalized_phone = '(909) 887-6543' expect(subject.phone).to eq normalized_phone end it 'delegates to model attributes when no transformer is assigned' do expected_name = 'John Doe' user = OpenStruct.new(phone: '1234567890', name: expected_name) subject = UserDetailsForm.new(user) expect(subject.name).to eq expected_name end it 'only has fields for fields slots its own field slots' do class OtherForm < FormIO::Output::Form field :other_field end user = OpenStruct.new(phone: '1234567890', name: 'John Doe') subject = UserDetailsForm.new(user) expect(subject).not_to respond_to :other_field other_model = OpenStruct.new(other_field: '') other_subject = OtherForm.new(other_model) expect(other_subject).to respond_to :other_field end end end
true
b489fc0453fd25f77535e24ed6139b1ba39c2619
Ruby
Redcozmo/gobike
/app/services/closest_stations.rb
UTF-8
998
3.5
4
[]
no_license
# frozen_string_literal: true class ClosestStations # # Description : # => Use the ClosestStations class to calculate the closest stations # to a position with two lon/lat coordinate pairs. # # Output : # => array with <num> closest stations from input coordinate point # # Example usage : # => ClosestStations.new(coord, num).closest_stations attr_accessor :longitude, :latitude, :num def initialize(coord, num) @latitude, @longitude = coord @num = num end def closest_stations @stations = Station.all distances = {} selection = {} @stations.map do |station| distances[station.station_id] = Haversine.new( [station.latitude, station.longitude], [@latitude, @longitude] ).distance end distances.values.min(@num).each { |distance| selection[distances.key(distance)] = distance } [@stations.select { |station| selection.keys.find { |id| id == station.station_id } }, distances] end end
true
1adb9833579641cd6a831a40f53c5a17da52065a
Ruby
anibha88/Pine
/simple_block_call.rb
UTF-8
214
2.8125
3
[]
no_license
def profile &block block.call end profile do p "hi" end # def profile &block # block.call # end # profile do # p "hi" # 10.times do # p "HSVJ" # end # profile do # p "Test" # end # end
true
3e16271f4341295c8b1f4e4262f702926c9148e0
Ruby
taw/paradox-tools
/eu4_trade_graph/trade_graph.rb
UTF-8
2,490
2.671875
3
[ "MIT" ]
permissive
require_relative "../lib/paradox_mod_file_serializer" require "rgl/adjacency" require "rgl/connected_components" require "rgl/topsort" class TradeGraph attr_reader :node def initialize(node) @node = node end def nodes @node.keys end def edges result = [] @node.each do |from, trade_node| trade_node.find_all("outgoing").each do |link| to = link["name"] result << [from, to] end end result end def find_link(from, to) @node[from].find_all("outgoing").find{|n| n["name"] == to} end def build_link(from, to) direct = find_link(from, to) backwards = find_link(to, from) if direct direct elsif backwards PropertyList[ "name", to, "path", backwards["path"].reverse, "control", backwards["control"].each_slice(2).to_a.reverse.flatten, ] else # warn "No link from #{a} to #{b} or backwards" PropertyList[ "name", to, "path", [], "control", [], ] end end def rewrite(updated_edge_list) edge_graph = RGL::DirectedAdjacencyGraph[*updated_edge_list.flatten] unless valid?(edge_graph) raise "Trade Graph is not valid, can't rebuild" end output = PropertyList[] edge_graph.topsort_iterator.each do |node_name| orig_node = @node[node_name] raise "Unknown keys: #{orig_node.keys}" unless ( orig_node.keys.to_set - Set["location", "color", "outgoing", "members", "inland", "end", "ai_will_propagate_through_trade"] ).empty? node = PropertyList[] node.add! "location", orig_node["location"] copy_attr(node, orig_node, "inland") copy_attr(node, orig_node, "color") edge_graph.each_adjacent(node_name) do |target_node_name| node.add! "outgoing", build_link(node_name, target_node_name) end node.add! "members", orig_node["members"] copy_attr(node, orig_node, "ai_will_propagate_through_trade") if edge_graph.each_adjacent(node_name).to_a.empty? node.add! "end", true end output.add! node_name, node end output end private def valid?(edge_graph) inv_comp_map = {} edge_graph.strongly_connected_components.comp_map.each do |v, n| (inv_comp_map[n] ||= []) << v end inv_comp_map.values.delete_if { |scc| scc.size == 1 }.empty? end def copy_attr(target, source, attr) if source[attr] target.add! attr, source[attr] end end end
true
9f13b722a2aec1394bf5fd6f7c78492184d96462
Ruby
shixiongjing/D4
/helper.rb
UTF-8
586
3.109375
3
[]
no_license
def insert_sort(arr, char) idx = arr.length temp = arr.dup temp << char until idx.zero? || (temp[idx - 1] <= char) idx -= 1 temp[idx + 1], temp[idx] = temp[idx], temp[idx + 1] end # puts 'adding: ' + char # puts 'orinigal: ' + arr # puts 'sorted:' + temp temp end def check_args(argv) if argv.count != 1 puts( 'Usage: ', 'ruby word_finder.rb *graph_file*' ) return false end unless File.exist?(argv[0]) puts 'Could not access file' return false end true end def read_dictionary File.readlines('wordlist.txt') end
true
772f5430c88399246569d1ce9246cfb27609be49
Ruby
learn-co-students/seattle-web-031119
/44-jwt/rainbow.rb
UTF-8
154
2.796875
3
[]
no_license
require 'bcrypt' passphrase = "a" while true hash = BCrypt::Password.create(passphrase) puts "#{passphrase} #{hash}" passphrase = passphrase.next end
true
169270dd2e2d2ba1c233c6d7f227b4ac4de05cb0
Ruby
bubdm/all-the-structures
/ruby/src/stack/stack.rb
UTF-8
225
3.546875
4
[]
no_license
#!/usr/bin/env ruby class Stack def initialize() @values = [] end def push(val) @values << val end def pop() @values.pop end def size @values.length end end
true
bcaf73cbfc85c1d4218c289bc6b91f4d51dba332
Ruby
unrar/midb
/lib/midb/hooks.rb
UTF-8
1,405
2.96875
3
[]
no_license
# ADDED in midb-2.0.0a by unrar # # # The "hooks" part of the MIDB::API module allows programmers to customize their API. # Hooks are methods that are run in the API; overriding them allows you to run a custom API. # # This hooking technology has been developed in its-hookable. # module MIDB module API class Hooks attr_accessor :hooks def initialize() @hooks = Hash.new @hooks["after_get_all_entries"] = [] @hooks["format_field"] = [] end # This method adds a method _reference_ (:whatever) to the hash defined above. def register(hook, method) @hooks[hook].push method end # These are the methods that are ran when the hook is called from the main class. # The code can be slightly modified depending on the arguments that each hook takes, # but that's up to the original developer - not the one who does the customization. def after_get_all_entries(n_entries) @hooks["after_get_all_entries"].each do |f| # Just run :f whenever this method is called, no arguments. Object.send(f, n_entries) end end def format_field(field, what) if @hooks["format_field"] == [] return what else @hooks["format_field"].each do |f| return Object.send(f, field, what) end end end end end end
true
79b9d3404a880368c853372cea279a7d657b81f5
Ruby
paulinasalem/my-collect-v-000
/lib/my_collect.rb
UTF-8
138
3.265625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def my_collect(argument) i=0 collection=[] while i<argument.length collection<<yield(argument[i]) i+=1 end collection end
true
9101c68a90ef3b8c6521340f697968f3e0351f8c
Ruby
KernelDeimos/tmp-setmonkey
/app/controllers/sets_controller.rb
UTF-8
2,535
2.71875
3
[]
no_license
# vim: ts=2 sw=2 expandtab class SetsController < ApplicationController def definition end def view # Choose correct behaviour based on which button was pressed case params[:commit] when "union" union when "intersection" intersection when "difference" difference when "subset" subset end end def union # Initialize empty set setUnion = Hash.new # Convert user input (lists) to sets lisa = params[:seta] lisb = params[:setb] lisa.each do |k| setUnion[k] = true end lisb.each do |k| setUnion[k] = true end @output = setUnion.keys end def intersection # Initialize empty set for result setIntersection = Hash.new # Collect user input lists lisa = params[:seta] lisb = params[:setb] # Add set A items to intermediate hashmap hasha = Hash.new lisa.each do |k| hasha[k] = true end # Iterate over set B, adding any key found # in hash A to the final result lisb.each do |k| if hasha.key?(k) setIntersection[k] = true end end @output = setIntersection.keys end def difference # Initialize empty set for result setDifference = Hash.new # Initialize empty set for union setIntersection = Hash.new # Collect user input lists lisa = params[:seta] lisb = params[:setb] # Add set A items to intermediate hashmap hasha = Hash.new lisa.each do |k| hasha[k] = true end # Iterate over set B, adding any key found # in hash A to the final result lisb.each do |k| if hasha.key?(k) setIntersection[k] = true end end # Add set items which aren't in intersection to difference (lisa + lisb).each do |k| if not setIntersection.key?(k) setDifference[k] = true end end @output = setDifference.keys end def subset # Collect user input lists lisa = params[:seta] lisb = params[:setb] # Add set B items to intermediate hashmap hashb = Hash.new lisb.each do |k| hashb[k] = true end # Optimism: assume A is a subset aIsSubsetOfB = true lisa.each do |k| if not hashb.key?(k) aIsSubsetOfB = false break end end @output = aIsSubsetOfB ? ["true"] : ["false"] end # Route to dump results for manual testing def temp puts YAML::dump params[:seta] puts YAML::dump params[:setb] render plain: params[:seta].inspect end end
true
8967900be263671f95e3437d3c67cbc8e62a0999
Ruby
mnain/learn-ruby
/servlet.rb
UTF-8
1,783
2.625
3
[]
no_license
#!/opt/third-party/bin/ruby # # $Id: servlet.rb,v 1.1 2005/07/23 00:41:37 madan Exp madan $ # # SERVLET_RB # require 'webrick' include WEBrick s = HTTPServer.new( :Port => 8085 ) # HTTPServer#mount(path, servletclass) # When a request referring "/hello" is received, # the HTTPServer get an instance of servletclass # and then call a method named do_"a HTTP method". class HelloServlet < HTTPServlet::AbstractServlet def do_GET(req, res) res.body = "<HTML>" res.body += "<head>" res.body += '<link rel="shortcut icon" href="favicon.ico" >' res.body += "</head>" res.body += "hello, world.</HTML>" res['Content-Type'] = "text/html" end end s.mount("/", HTTPServlet::FileHandler, "c:\\learn\\ruby\\index.html", true) s.mount("/hello", HelloServlet) # HTTPServer#mount_proc(path){|req, res| ...} # You can mount also a block by `mount_proc'. # This block is called when GET or POST. s.mount_proc("/hello/again") {|req, res| res.body = "<HTML>hello (again)</HTML>" res['Content-Type'] = "text/html" } s.mount_proc("/hello/madan") { |req,res| res.body = "<html>" res.body += "<head><title>Hello Madan</title></head>" res.body += 'Welcome to http://mnain.dyndns.org:8085/' res.body += "<table border=1>" res.body += "<tr><td>Hello world</td></tr>" res.body += "</table>" res.body += "<br>" res['Content-Type'] = 'text/html' } s.mount_proc("/now") { |req,res| currentTime = Time.now res.body = "<HTML>" res.body += "#{currentTime} (PST)" res.body += "<br>" res.body += "#{currentTime.gmtime} (GMT)" res.body += "<br>" res.body += "</html>" res['Content-Type'] = "text/html" } trap("INT"){ s.shutdown } s.start
true
b95a742bc90db6847ea69ff7113ddcef16c91e22
Ruby
TheNaoX/tic_tac_toe
/lib/game.rb
UTF-8
265
2.640625
3
[ "MIT" ]
permissive
module Game @@games = {} class << self def store(session) @@games.merge!(session => Game::Environment.new) end def get_instance(session) @@games[session] end def finish(session) @@games.delete(session) end end end
true
9241c794cca33a0914028657313bc57ec81b646d
Ruby
superff/hello-gitlearn
/ruby/Part1-1.rb
UTF-8
780
4.09375
4
[]
no_license
def palindrome?(string) # your code here g = string.downcase.gsub(/[^a-z]/, '') b = g.reverse return g == b end def count_words(string) # your code here str_hash = Hash.new a = (string.downcase).gsub(/[^a-z\s]/, '').split(/[\b\s]/) #puts g a.each do |key| if key != '' if !str_hash.has_key?(key) str_hash[key] = 0 end str_hash[key] +=1 end end return str_hash end puts count_words("A man, a plan, a canal -- Panama") # => {'a' => 3, 'man' => 1, 'canal' => 1, 'panama' => 1, 'plan' => 1} puts count_words "Doo bee doo bee doo" # => {'doo' => 3, 'bee' => 2} puts puts palindrome?("A man, a plan, a canal -- Panama") #=> true puts palindrome?("Madam, I'm Adam!") # => true puts palindrome?("Abracadabra") # => false (nil is also ok)
true
a68fa8ef7a5bf9fc8421db4e8e9cfa466f1e7381
Ruby
timsalazar/week-02-exercise-timsalazar
/spec/exercise-spec.rb
UTF-8
532
3.640625
4
[]
no_license
describe "Strings" do context "when calling strip" do it "should remove all whitespace from the beginning and the end of the string" do lyrics = " Hello, is it me you're looking for I can see it in your eyes " lyrics.strip.should eq "Hello, is it me you're looking for I can see it in your eyes" end end end describe "Addition" do context "when calling addition" do it "should add these integers together" do x = 17 y = 4 z = x + y z.should eq 21 end end end
true
941f6e77d3e9d5c07a7af0b3bd0a135921ca5488
Ruby
tdg5/tco_method
/test/unit/tco_method_test.rb
UTF-8
1,860
2.71875
3
[ "MIT" ]
permissive
require "test_helper" module TCOMethod class TCOMethodTest < TCOMethod::TestCase include TCOMethod::TestHelpers::Assertions Subject = TCOMethod # Grab source before it's recompiled for use later InstanceFibYielderSource = TestClass.instance_method(:instance_fib_yielder).source subject { Subject } context Subject.name do should "be defined" do assert defined?(subject), "Expected #{subject.name} to be defined!" end end context "::tco_eval" do should "raise ArgumentError unless code is a String" do bad_code = [ :bad_code, 5, proc { puts "hello" }, ] bad_code.each do |non_code| assert_raises(ArgumentError) do subject.tco_eval(non_code) end end end should "compile the given code with tail call optimization" do EvalDummy = dummy_class = Class.new subject.tco_eval(<<-CODE) class #{dummy_class.name} #{InstanceFibYielderSource} end CODE fib_yielder = dummy_class.new.method(:instance_fib_yielder) assert tail_call_optimized?(fib_yielder, 5) end end context "::with_tco" do should "raise ArgumentError if a block is not given" do exception = assert_raises(ArgumentError) { subject.with_tco } assert_match(/block required/i, exception.message) end should "compile the given code with tail call optimization" do subject.with_tco do class WithTCODummy def countdown(count, &block) yield count count.zero? ? 0 : countdown(count - 1, &block) end end end meth = WithTCODummy.new.method(:countdown) assert tail_call_optimized?(meth, 5) end end end end
true
0d3e62515e0e487abeeed44ee969b3aaed6dd948
Ruby
eudaimonious/cyo-revenge
/revenge.rb
UTF-8
10,083
3.1875
3
[]
no_license
# -*- coding: UTF-8 -*- from sys import exit import re import json import urllib2 import random h = { "self_destruct" => { :text => "\nIt's 2002 and you are now an 18 year old billionaire with major issues.\nYou're partying like you just got out of juvie and maybe getting into a few bar fights.\nThen pesky, pesky Nolan shows up again to bail you out.\nHe comments on your self-destruction and asks if you've read the journals.\nWhat do you do?\n\n1) Say \"hell no, I don't care what they say. My father was a terrorist.\"\n2) Consider that maybe this is not what you should be doing and maybe\n looking into your and your father's history would be worth your time.", :options => { "1" => "destruct()", "2" => "loopin_through(anditbegins)" }, :else => "dead('Looks like the guy you were fighting with in the bar came back out and stabbed you.')" }, "start" => { :text => "Date: June 2002. You're Amanda Clarke.\nYour father is David Clarke, convicted of helping launder money\nfor the domestic terrorists who blew up Flight 197 on June 4, 1993.\nYou've just been released from Allenwood Juvenile Detention Facility after two years.\nPicking you up is Nolan Ross.\n \nNolan hands you a box and tells you that your father is not who you think he is.\nHe also tells you that there is a key in the box that unlocks a safe in Switzerland\nwith billions of dollars, the earnings from your father investing in his company.\nWhat do you do?\n \n1) Ignore the contents of the box. You already know what your father did.\n But definitely take the money. There is some sweet partying to be done.\n2) You're intrigued. You go through the contents of the box.\n And take the money. It is yours, after all.", :options => { "1" => "loopin_through(self_destruct)", "2" => "loopin_through(anditbegins)" }, :else => "dead('Looks like you drank too much tequila in Allenwood and forgot how to talk without slurring your words. \nYou couldn\'t figure out how to get the money and end up homeless.')" }, "anditbegins" => { :text => "Your father’s journals reveal that he isn’t the man that you thought he was.\nHe was framed. Someone will have to pay for this.\nReading your father's journals, you find out who betrayed him.\n \n1. Victoria Grayson: Queen of the Hamptons. Your father’s lover before he was framed.\n2. Conrad Grayson: CEO of Grayson Global. He is directly responsible for what happened to your father.\n3. Bill Harmon: Your father's best friend. Testified against your father to save his job.\n4. Dr. Michelle Banks: Put you in an institution in order to further her career.\n5. Mason Treadwell: Originally told you he would puts the truth, but his book about your father was full of LIES!\n6. Senator Tom Kingsly: Ignored evidence that would have saved your father and proven him not guilty.\n \nWhat do you do now? Do you:\n1. Take time to plan it out. These assholes must be taken down appropriately.\n2. Who needs time when you have guns?", :options => { "1" => "loopin_through(changetoemily)", "2" => "gunsablazin(3)" }, :else => "cthulhu(loopin_through(anditbegins))" } } def loopin_through(name) puts h[name][:text] whereto_stop = raw_input("> ") if h[name][:options].has_key?(whereto_stop) result = h[name][:options][whereto_stop] else result = h[name][:else] end send(result) end # Start of Amanda's journey into self-destruction def funtime(doots) puts "funny " + doots end #Amanda is destructing. def destruct() puts " " puts "It's New Year's 2003 and you pick the wrong bar to party at." # #pick out a song at random that is from 2003 or ealier that is both "hot" and danceable (likely to be played at a bar) # a = 'http://developer.echonest.com/api/v4/song/search?api_key=19EL7JSMTLLWIHPS0&format=json&results=1&artist_end_year_before=2004&min_danceability=0.{dance}&song_min_hotttnesss=0.{hotness}'.format(dance = random.randint(5,9), hotness = random.randint(5,9)) # f = urllib2.urlopen(a) # songdata = json.load(f)['response'] # #if a song isn't picked, play Creed. Yuck. # if not songdata['songs'] # puts "The song playing on the jukebox is 'Higher' by Creed. It makes you a bit stabby." # else # #puts the song that's playing # puts "The song playing on the jukebox is {song} by {artist}".format(song = songdata['songs'][0]['title'], artist = songdata['songs'][0]['artist_name']) # end puts "You start a fight with these two punks." puts "One is a larger woman who seems to have a knife." puts "The other is a skinny man who doesn't appear to have a weapon." puts "Who do you attack first?" puts " " puts "1) Disarm the woman!" puts "2) Take out scrawny." whereto = raw_input("> ") #this all goes poorly and all roads lead to death if whereto == "1" dead("Too bad, scrawny also had a knife! He stabs you in the back and you die.") elsif whereto == "2" dead("Not quick enough! The woman stabs you as soon as you go for the man. You die.") else dead("Too slow! The woman stabs you while the man punches you in the face. You die.") end end def changetoemily() puts " " puts "It’s revenge time. But everyone knows your name." puts "You go back to Allenwood with a plan:" puts "convince your old cell mate to switch names with you." puts "You earned her trust on the inside, but you still have" puts "to convince her that you are still her best friend." #(insert options on becoming emily’s bestie)" revengesensei() end def revengesensei() puts " " puts "You are now Emily Thorne." puts "The warden at Allenwood put you in contact" puts "with a revenge sensei in Japan (shhhh those exist)." puts "Do you decide to travel to Japan to begin your training?" puts "Or do you go to the Hamptons guns blazing but *slightly* underprepared?" whereto = raw_input("> ").downcase # if "hamptons" in whereto # #call gunsablazin with "smarts" variable. you are pretty smart now. # gunsablazin(0) # elsif "japan" in whereto # goingtojapan() # else # cthulhu(revengesensei) # end end def gunsablazin(exp) puts " " puts "You’re right, who needs preparation?" puts "These assholes just need a good old fashioned killing," puts "just like what happened to your dad. You go down to Jersey" puts "to pick up a few automatics and some ammo from the corner store." puts "Who do you go after first?" puts " " puts "1. Victoria Grayson" puts "2. Conrad Grayson" puts "3. Bill Harmon" puts "4. Dr. Michelle Banks" puts "5. Mason Treadwell" puts "6. Senator Tom Kingsly" puts " " tally = exp # give each person a variable that says whether they are alive. can't kill them twice! # also gives emily a variable that allows her to kill 2 people only while tally <= 4 whereto = raw_input("> ") if whereto == "1" and victoria == True puts "You killed Victoria!" victoria = False tally +=1 elsif whereto == "1" and victoria == False puts "You looped around and tried to kill Victoria again. That was dumb." tally += 1 elsif whereto == "2" and conrad == True puts "You killed Conrad!" conrad = False tally += 1 elsif whereto == "2" and conrad == False puts "You looped around and tried to kill Conrad again. That was dumb." tally +=1 elsif whereto == "3" and bill == True puts "You killed Bill!" bill = False tally += 1 elsif whereto == "3" and bill == False puts "You looped around and tried to kill Bill again. That was dumb." tally +=1 elsif whereto == "4" and michelle == True puts "You killed Dr. Banks!" michelle = False tally += 1 elsif whereto == "4" and michelle == False puts "You looped around and tried to kill Dr. Banks again. That was dumb." tally +=1 elsif whereto == "5" and mason == True puts "You killed Mason!" mason = False tally += 1 elsif whereto == "5" and mason == False puts "You looped around and tried to kill Mason again. That was dumb." tally +=1 elsif whereto == "6" and tom == True puts "You killed Senator Kingsley!" tom = False tally += 1 elsif whereto == "6" and tom == False puts "You looped around and tried to kill Senator Kingsley again. That was dumb." tally +=1 else cthulhu(gunsablazin) end end puts " " puts "You hear the cops coming. Two choices:" puts "1. You are not going down without a fight. Shootout!" puts "2. Surrender and go to jail. Maybe you can escape?" whereto2 = raw_input("> ") if whereto2 == "1" dead("Shooting at cops is not the best idea. You get gunned downed by cops.") elsif whereto2 == "2" dead("You are arrested and sent to jail for life.") else dead("You tried to run, but the feds found you in Tennessee.") end end # sends player to fight cthulhu when they press the wrong button. sends you back to originating function if you defeat cthulhu def cthulhu(wherefrom) puts " " puts "Hmm. You seem to have wondered over to the ocean." puts "Rising out of the ocean is Cthulhu." puts "He, it, whatever stares at you and you go insane." puts "Can you kill Cthulhu before he drives you insane?" puts "You have two choices. Do you pick the axe or the rifle?" #cthulhu starts at zero each time cthulhu_life = 0 while cthulhu_life < 10 and emily_sanity < 10 whereto = raw_input("> ") #sets input to lower case whereto = raw_input("> ").downcase # if "axe" in whereto # cthulhu_life += 5 # emily_sanity +=1 # puts "Nice hit! Axe or rifle?" # elsif "rifle" in whereto # cthulhu_life +=4 # emily_sanity +=1 # puts "Good shot! Axe or rifle?" # else # emily_sanity +=2 # puts "You are going insane. Axe or rifle?" # end end if cthulhu_life >= 10 puts "You have killed Cthulhu." #try to send it back from whence it came wherefrom() else dead("You have gone insane. ") end end def dead(why) puts " " puts why, "Sorry." exit end def start() # initializes emily's sanity and life variables emily_sanity=0 victoria = True conrad = True bill = True michelle = True mason = True tom = True #makes variables global # global emily_sanity, victoria, conrad, bill, michelle, mason, tom puts h[:start][:text] puts "oh HEYYYYY" end def raw_input(prompt) puts prompt gets end puts "hiiii" start()
true
b40d075499de9f95f65d243ea37052ad3ad6b1dc
Ruby
tskupinski/marcus
/lib/treasury.rb
UTF-8
924
3.453125
3
[]
no_license
require_relative './coin' require_relative './errors/unsupported_coin_error' class Treasury STARTING_COINS = [ Coin.new('1p', 1, 10), Coin.new('2p', 2, 10), Coin.new('5p', 5, 10), Coin.new('10p', 10, 10), Coin.new('20p', 20, 10), Coin.new('50p', 50, 10), Coin.new('1£', 100, 10), Coin.new('2£', 200, 10) ].freeze def initialize(coins = STARTING_COINS) @coins = coins end attr_accessor :coins def restock_coins(denomination, amount) coin = coins.find { |c| c.denomination == denomination } || raise_error coin.increase_quantity(amount) end def subtract_coins(denominations) denominations.each do |denomination| coin = coins.find { |c| c.denomination == denomination } coin.decrease_quantity(1) end end private def raise_error raise UnsupportedCoinError, 'Unsupported coin, please use one of supported denominations' end end
true
750eb286bce2e93e6ead64926d82b9c34cb60a6c
Ruby
jeesong/compsciwork
/word_complete_redo.rb
UTF-8
1,349
3.578125
4
[]
no_license
require 'pry' class AutoCompleteNode attr_accessor :value, :children, :is_complete_word def initialize(value) @value = value @children = [] @is_complete_word = false end def learn(input) length = input.length i = 1 parent = self while i <= length if parent.children.any? { |node| node.value == input[0..i] } parent = children.find { |node| node.value == input[0..i] } else newNode = AutoCompleteNode.new(input[0,i]) parent.children << newNode parent = newNode end i += 1 end parent.is_complete_word = true end def completionsFor(input) matches = [] # if completionsFor(input) @children.each do |subtree| if subtree.value.start_with?(input) && subtree.is_complete_word matches << subtree.value end matches += subtree.completionsFor(input) end matches end end root = AutoCompleteNode.new('') root.learn 'apple' root.learn 'ape' # root.learn 'app' # root.learn 'appear' # root.learn 'approve' # root.learn 'appease' # root.learn 'boo' # root.learn 'book' # root.learn 'books' # root.learn 'bored' # root.learn 'candle' binding.pry # while true # puts 'Input a word' # input = gets.chomp() # # root.learn(input) # root.completionsFor(input) # # puts root.inspect # # binding.pry # end
true
30d1d4b17d0f2d6ccde2ec4186337e4d1cee6047
Ruby
take-cheeze/mruby-pack
/test/pack.rb
UTF-8
2,089
3.125
3
[ "MIT" ]
permissive
# pack & unpack 'm' (base64) assert('[""].pack("m")') do ary = "" str = "" [ary].pack("m") == str and str.unpack("m") == [ary] end assert('["\0"].pack("m")') do ary = "\0" str = "AA==\n" [ary].pack("m") == str and str.unpack("m") == [ary] end assert('["\0\0"].pack("m")') do ary = "\0\0" str = "AAA=\n" [ary].pack("m") == str and str.unpack("m") == [ary] end assert('["\0\0\0"].pack("m")') do ary = "\0\0\0" str = "AAAA\n" [ary].pack("m") == str and str.unpack("m") == [ary] end assert('["abc..xyzABC..XYZ"].pack("m")') do ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"].pack("m") == "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJT\nVFVWV1hZWg==\n" end assert('"YWJ...".unpack("m") should "abc..xyzABC..XYZ"') do str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJT\nVFVWV1hZWg==\n".unpack("m") == [str] and "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWg==\n".unpack("m") == [str] end # pack & unpack 'H' assert('["3031"].pack("H*")') do ary = "3031" str = "01" [ary].pack("H*") == str and str.unpack("H*") == [ary] end assert('["10"].pack("H*")') do ary = "10" str = "\020" [ary].pack("H*") == str and str.unpack("H*") == [ary] end assert('[0,1,127,128,255].pack("C*")') do ary = [ 0, 1, 127, 128, 255 ] str = "\x00\x01\x7F\x80\xFF" ary.pack("C*") == str and str.unpack("C*") == ary end # pack "a" assert('["abc"].pack("a")') do ["abc"].pack("a") == "a" and ["abc"].pack("a*") == "abc" and ["abc"].pack("a4") == "abc\0" end # upack "a" assert('["abc"].pack("a")') do "abc\0".unpack("a4") == ["abc\0"] and "abc ".unpack("a4") == ["abc "] end # pack "A" assert('["abc"].pack("A")') do ["abc"].pack("A") == "a" and ["abc"].pack("A*") == "abc" and ["abc"].pack("A4") == "abc " end # upack "A" assert('["abc"].pack("A")') do "abc\0".unpack("A4") == ["abc"] and "abc ".unpack("A4") == ["abc"] end # regression tests assert('issue #1') do [1, 2].pack("nn") == "\000\001\000\002" end
true
a23d61a1fe68f35d60baa48ab5e714ce336e8297
Ruby
ALEKUTTY/ruby-challenges-final
/always3_method.rb
UTF-8
266
3.296875
3
[]
no_license
def method_3 #ask user for a number puts "Give me a number" #define variable to hold number first_number = gets.to_i #do maths to get 3 and display result puts "Always" + (((first_number + 5)*2-4)/2 - first_number).to_s end method_3
true
c6fbb33ac275919878eab11b8cbde5e350500f3b
Ruby
mooreds/ruby-lambdas
/lambda_pipeline.rb
UTF-8
243
3.046875
3
[]
no_license
double_it = lambda { |num| num * 2 } triple_it = lambda { |num| num * 3 } half_it = lambda { |num| num / 2 } value = 5 lambda_pipeline = [double_it, triple_it, half_it] lambda_pipeline.each do |lmb| value = lmb.call(value) end puts value
true
de96727637bd856b40a13aa8152aa6d815f8f4fa
Ruby
mdumke/tealeaf_exercises
/course 0 - prep course/intro_programming_1_workbook/quiz1_2/07.rb
UTF-8
186
3
3
[]
no_license
# See if the name "Dino" appears in the string below advice = "Few things in life are as important as house training your pet dinosaur." p !!advice.match('Dino') p !!(advice =~ /Dino/)
true
0dcda60dd7bd02c7c25d603db729d9ec9991a256
Ruby
davidtadams/advent-of-code
/2019/day14/part1and2.rb
UTF-8
2,063
3.6875
4
[]
no_license
# frozen_string_literal: true reactions_input = File.read('input.txt').split("\n") class Chemical attr_accessor :name, :result, :inputs def initialize(name, result, inputs = []) @name = name @result = result @inputs = inputs end end class Reaction attr_accessor :name, :cost def initialize(name, cost) @name = name @cost = cost end end def parse_reaction(reaction) (inputs, output) = reaction.split(' => ') (output_result, output_name) = output.split input_nodes = inputs.split(', ').map do |input| (input_cost, input_name) = input.split Reaction.new(input_name, input_cost.to_i) end Chemical.new(output_name, output_result.to_i, input_nodes) end def build_nodes(reactions_input) reactions = {} reactions_input.each do |reaction| parent_node = parse_reaction(reaction) reactions[parent_node.name] = parent_node end reactions end def calculate_costs(reaction_name, reaction_amount, reactions, total_costs = {}, wasted_costs = {}) reaction = reactions[reaction_name] wasted_costs[reaction_name] ||= 0 total_costs[reaction_name] ||= 0 if reaction_amount < wasted_costs[reaction_name] wasted_costs[reaction_name] -= reaction_amount else multiplier = ((reaction_amount - wasted_costs[reaction_name]) / reaction.result.to_f).ceil total_costs[reaction_name] -= wasted_costs[reaction_name] wasted_costs[reaction_name] += (multiplier * reaction.result) - reaction_amount reaction.inputs.each do |input| total_costs[input.name] ||= 0 quantity_needed = input.cost * multiplier total_costs[input.name] += quantity_needed calculate_costs(input.name, quantity_needed, reactions, total_costs, wasted_costs) if input.name != 'ORE' end end total_costs['ORE'] end reactions = build_nodes(reactions_input) total_ore_cost = calculate_costs('FUEL', 1, reactions) answer = (1..1_000_000_000_000).bsearch { |n| calculate_costs('FUEL', n, reactions) > 1_000_000_000_000 } - 1 puts "ANSWER #1: #{total_ore_cost}" puts "ANSWER #2: #{answer}"
true
ff9e987e36c85d003e24be06b8261aa24e094b21
Ruby
dmillzilla/trello_archiver
/trello_archiver.rb
UTF-8
1,198
2.765625
3
[]
no_license
require 'trello' require 'yaml' require 'date' config = YAML::load_file(File.join(File.dirname(File.realpath(__FILE__)), ".config")) @trello_config = config["trello_config"] trello_board_arr = [] Trello.configure do |c| c.developer_public_key = @trello_config["APP_KEY"] c.member_token = @trello_config["TOKEN"] end trello_boards = Trello::Board.all trello_boards.each do |board| trello_board_arr << {:id => board.id, :name => board.name} end def board_archive_prompt(trello_board_hash) puts "Would you like to archive old cards from \"#{trello_board_hash[:name]}\"? (y/n)" print "> " @board_archive_choice = $stdin.gets.chomp unless ['y','yes','n','no'].include?(@board_archive_choice) puts 'That is not a valid input.' board_archive_prompt(trello_board_hash) end end trello_board_arr.each do |trello_board_hash| board_archive_prompt(trello_board_hash) next unless ['y','yes'].include?(@board_archive_choice) trello_board = Trello::Board.find(trello_board_hash[:id]) trello_board.cards.each do |card| if card.due && card.due < (Date.today - 90).to_s Trello::Card.find(card.id).close! puts "closing #{card.name}" end end end
true
4e5c4e9d9c776f072758c5d26c4ba204bedbb6b6
Ruby
cokesnort/readme
/app/services/base64_to_image.rb
UTF-8
266
2.703125
3
[]
no_license
class Base64ToImage def initialize(base64) @base64 = base64 end def call(path = nil) image = path.present? ? File.new(path, 'wb') : Tempfile.new('image') image.binmode image.write(Base64.decode64(@base64)) image.flush image end end
true
0f5e085f332c7ada585ac475e9a24b73fc52adf1
Ruby
whistler/whistler.github.com
/_plugins/random.rb
UTF-8
304
2.921875
3
[]
no_license
# Jekyll Liquid Filter to select one from an array # Eg. display a random post title # {% assign post = site.posts | random %} # {{ post.title }} module Jekyll module RandomFilter def random(input) input.sample end end end Liquid::Template.register_filter(Jekyll::RandomFilter)
true
73aea157fdf160352750d5341ab8463a87e916aa
Ruby
shadowmonkey95/AstarForPgrouting
/lib/algorithm/hungarian.rb
UTF-8
6,862
2.640625
3
[]
no_license
class Hungarian def initialize @C = [] @M = [] @rowCover = [] @colCover = [] @C_orig = [] @path = [] @pathChild = [] @nrow = 0; @ncol = 0; @step = 1; @path_row_0 = 0; @path_col_0 = 0; @path_count = 0; @asgn = 0; @debug = false; end def show @M end def setUpData(costMatrix) iSize = costMatrix.count @nrow = iSize @ncol = iSize @C = costMatrix @M = Array.new(iSize){Array.new(iSize, 0)} @rowCover = Array.new(iSize, 0) @colCover = Array.new(iSize, 0) @C_orig = [] @path = [] @step = 1 @path_row_0 = 0 @path_col_0 = 0 @path_count = 0 @asgn = 0 end def runMunkres done = false while !done do case @step when 1 step_one when 2 step_two when 3 step_three when 4 step_four when 5 step_five when 6 step_six when 7 step_seven done = true end end end private def step_one min_in_row = 10000 (0..@nrow - 1).each do |r| min_in_row = @C[r][0] (0..@ncol - 1).each do |c| if @C[r][c] < min_in_row min_in_row = @C[r][c] end end (0..@ncol - 1).each do |c| @C[r][c] -= min_in_row end end @step = 2 end def step_two (0..@nrow - 1).each do |r| (0..@ncol - 1).each do |c| if @C[r][c] == 0 && @rowCover[r] == 0 && @colCover[c] == 0 @M[r][c] = 1 @rowCover[r] = 1 @colCover[c] = 1 end end end (0..@nrow - 1).each do |r| @rowCover[r] = 0 end (0..@ncol - 1).each do |c| @colCover[c] = 0 end @step = 3 end def step_three byebug colCount = 0 (0..@nrow - 1).each do |r| (0..@ncol - 1).each do |c| if @M[r][c] == 1 @colCover[c] = 1 end end end (0..@ncol - 1).each do |c| if @colCover[c] == 1 colCount += 1 end end if colCount >= @ncol || colCount >= @nrow @step = 7 else @step = 4 end end def find_a_zero(coordinates) r = 0; c = 0; done = false; coordinates[0] = -1; coordinates[1] = -1; while !done do c = 0 while true do if @C[r][c] == 0 && @rowCover[r] == 0 && @colCover[c] == 0 coordinates[0] = r coordinates[1] = c done = true end c += 1 break if c >= @ncol || done end r += 1 if r >= @nrow done = true end end coordinates end def star_in_row(row) tmp = false; (0.. @ncol - 1).each do |c| if @M[row][c] == 1 tmp = true end end tmp end def find_star_in_row(row) col = -1; (0..@ncol - 1).each do |c| if @M[row][c] == 1 col = c end end col end def step_four byebug row = -1 col = -1 done = false coordinates = [] coordinates << row coordinates << col while !done do coordinates = find_a_zero(coordinates) if coordinates[0] == -1 done = true @step = 6 else @M[coordinates[0]][coordinates[1]] = 2 if star_in_row(coordinates[0]) coordinates[1] = find_star_in_row(coordinates[0]) @rowCover[coordinates[0]] = 1 @colCover[coordinates[1]] = 0 else done = true @step = 5 @path_row_0 = coordinates[0] @path_col_0 = coordinates[1] end end end end def find_star_in_col(col) r = -1; (0..@nrow - 1).each do |i| if @M[i][col] == 1 r = i end end r end def find_prime_in_row(r) c = -1; (0.. @ncol - 1).each do |i| if @M[r][i] == 2 c = i end end c end def augment_path (0..@path_count - 1).each do |i| if @M[@path[i][0]][@path[i][1]] == 1 @M[@path[i][0]][@path[i][1]] = 0 else @M[@path[i][0]][@path[i][1]] = 1 end end end def clear_covers (0.. @nrow - 1).each do |r| @rowCover[r] = 0 end (0.. @ncol - 1).each do |c| @colCover[c] = 0 end end def erase_primes (0.. @nrow - 1).each do |r| (0.. @ncol - 1).each do |c| if @M[r][c] == 2 @M[r][c] = 0 end end end end def step_five byebug done = false r = -1 c = -1 @path_count = 1 @pathChild = [] @pathChild << @path_row_0 @pathChild << @path_col_0 @path << @pathChild while !done do r = find_star_in_col(@path[@path_count - 1][1]) if r > -1 @path_count += 1 @pathChild = [] @pathChild << r @pathChild << @path[@path_count - 2][1] @path << @pathChild else done = true end if done c = find_prime_in_row(@path[@path_count - 1][0]) @path_count += 1 @pathChild = [] @pathChild << @path[@path_count - 2][0] @pathChild << c @path << @pathChild end end augment_path clear_covers erase_primes @step = 3 end def find_smallest(minval) (0.. @nrow - 1).each do |r| (0.. @ncol - 1).each do |c| if @rowCover[r] == 0 && @colCover[c] == 0 if minval > @C[r][c] minval = @C[r][c] end end end end minval end def step_six byebug minval = 1000000 minval = find_smallest(minval) (0.. @nrow - 1).each do |r| (0.. @ncol - 1).each do |c| if @rowCover[r] == 1 @C[r][c] += minval end if @colCover[c] == 0 @C[r][c] -= minval end end end @step = 4 end def step_seven end end
true
d87459a3cd5ae8565a198743f568c954ecb031a2
Ruby
ArunMichaelDsouza/ruby-foundations
/scripts/basics.rb
UTF-8
1,000
4.53125
5
[ "MIT" ]
permissive
# Variables, user input/output val = 2 puts "Value : #{val}" # Interpolation float = 0.99 puts "Float : #{float}" puts "Enter value" new_val = gets puts "New value : #{new_val}" # Type casting puts "Enter number" num = gets.to_i # Convert to integer puts "Double is : #{num * 2}" int = 3 puts "This is a number : " + int.to_s # Convert to string =begin Multiline comment =end # Constants CONST = 3 puts "Constant : #{CONST}" CONST = 2 puts "New Constant : #{CONST}" # Arithmetic operators puts "2 + 3 : #{2+3}" puts "6 - 1 : #{6-1}" puts "5 * 1 : #{5*1}" puts "5 / 1 : #{5/1}" puts "25 % 20 : #{25%20}" puts "5 ** 2 : #{5**2}" # String methods puts "hello.capitalize : #{"hello".capitalize}" puts "hello.upcase : #{"hello".upcase}" puts "Hello.downcase : #{"Hello".downcase}" name = "Arun" puts "name.include?('run') : #{name.include?("run")}" # Substring in string # Symbols :symbol puts "Symbol : #{:symbol}" # Arrays array = Array.new array = [1,2,3,4] puts array puts array.length
true
ce028477d8a60f30f656e29d3323a9a53a2b74c8
Ruby
elma635/ruby-objects-has-many-through-lab-nyc-web-051319
/lib/doctor.rb
UTF-8
762
3.359375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class Doctor attr_accessor :name @@all = [] def initialize(name) @name = name @@all << self end #instance #confused on That Appointment should know that it belongs to the doctor def new_appointment(patient, date) Appointment.new(patient, self, date) #binding.pry end def appointments Appointment.all.select do |appointment| appointment.doctor end end #confused on The Doctor class needs an instance method, #patients, that iterates over that doctor's Appointments and collects the patient that belongs to each Appointments. def patients Appointment.all.map do |appointment| #binding.pry appointment.patient end end #class def self.all @@all end end
true
3ceec5a5ea34f5f23f3be3c3acca2c97da8c097b
Ruby
codemilan/old_stuff
/active_point1/RubyExt/module.rb
UTF-8
2,296
2.5625
3
[]
no_license
class Module def namespace if @module_namespace_defined @module_namespace else @module_namespace_defined = true @module_namespace = Module.namespace_for name end end def each_namespace &block current = namespace while current do block.call current current = current.namespace end end def each_ancestor include_standard = false, &block if include_standard ancestors.each{|a| block.call a unless a == self} else exclude = [self, Object, Kernel] ancestors.each do |a| block.call a unless exclude.include? a end end end def self_ancestors_and_namespaces &b b.call self each_ancestor &b each_namespace &b end def self.namespace_for class_name list = class_name.split("::") if list.size > 1 list.pop return eval list.join("::"), TOPLEVEL_BINDING, __FILE__, __LINE__ else return nil end end def wrap_method( sym, prefix = "old_", &blk ) old_method = "#{prefix}_#{sym}".to_sym alias_method old_method, sym define_method(sym) do |*args| instance_exec(old_method, *args, &blk) end end def is?(base) ancestors.include?(base) end def resource_exist? resource_name self_ancestors_and_namespaces do |klass| return true if RubyExt::Resource.resource_exist? klass, resource_name end return false end def [] resource_name self_ancestors_and_namespaces do |klass| if RubyExt::Resource.resource_exist? klass, resource_name return RubyExt::Resource.resource_get(klass, resource_name) end end raise RubyExt::Resource::NotExist, "Resource '#{resource_name}' for Class '#{self.name}' doesn't exist!", caller end def []= resource_name, value RubyExt::Resource.resource_set self.name, resource_name, value end def inherit *modules modules.each do |amodule| include amodule processed = [] amodule.ancestors.each do |a| if a.const_defined? :ClassMethods class_methods = a.const_get :ClassMethods next if processed.include? class_methods processed << class_methods extend class_methods end end end end end
true
98419b357ebe21c215b3dc43151d6405bc463630
Ruby
IlyaMur/ruby_learning
/RubyRush_school/Lesson7/max.rb
UTF-8
169
3.109375
3
[]
no_license
puts 'Какой длины будет массив случайных чисел?' num = gets.to_i arr = Array.new(num) {rand 1..100} puts arr.to_s puts arr.max
true
2b05a1aa49ea65c352de2db7d9b839b9b10eee6b
Ruby
facenord-sud/myl
/lib/parser/tree_parser.rb
UTF-8
700
2.640625
3
[ "MIT" ]
permissive
class TreeParser require 'treetop' Treetop.load(File.expand_path(File.join(File.dirname(__FILE__), 'myl_parser.treetop'))) @@parser = MylReferenceParserParser.new def self.parse(data) tree = @@parser.parse(data) if(tree.nil?) raise ParseError, "Parse error at offset: #{@@parser.index}" end # clean up the tree by removing all nodes of default type 'SyntaxNode' self.clean_tree(tree) return tree end private def self.clean_tree(root_node) return if(root_node.elements.nil?) root_node.elements.delete_if{|node| node.class.name == "Treetop::Runtime::SyntaxNode" } root_node.elements.each {|node| self.clean_tree(node) } end end
true
c1f2f77b09653359082b85593337686401627136
Ruby
tbierwirth/monster_shop
/app/models/item.rb
UTF-8
1,026
2.5625
3
[]
no_license
class Item < ApplicationRecord belongs_to :merchant has_many :order_items has_many :orders, through: :order_items has_many :reviews, dependent: :destroy validates_presence_of :name, :description, :image, :price, :inventory def sorted_reviews(limit = nil, order = :asc) reviews.order(rating: order).limit(limit) end def average_rating reviews.average(:rating) end def self.all_active where(active: true) end def self.popular_items(limit, order = 'DESC') joins(:order_items) .select('items.*, sum(order_items.quantity) AS qty') .group('items.id') .order("qty #{order}") .order("items.name") .limit(limit) end def get_order_item(order_id) order_items.where(order_id: order_id).first end def fulfilled?(order_id) order_items.where(order_id: order_id).first.status == 'fulfilled' end def fulfillable?(qty) inventory >= qty end end
true
f29e7bdd59a18b1d47514c50030b5af393f38004
Ruby
ept/cotweet-export
/lib/cotweet/download_queue.rb
UTF-8
832
2.796875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module CoTweet class DownloadQueue MAX_CONCURRENCY = 10 def initialize(&block) @operation = block @items_seen = Set.new @active = {} @queued = [] end def <<(item) return if @items_seen.include? item @items_seen << item if has_capacity? start(item) else @queued << item end end def finish return DG.success if idle? @finishing ||= DG.blank end private def idle? @active.empty? end def has_capacity? @active.size < MAX_CONCURRENCY end def start(item) @active[item] = @operation.call(item).bothback do @active.delete item start(@queued.shift) if has_capacity? && !@queued.empty? @finishing.succeed if @finishing && idle? end end end end
true
8792a7f14da2ea2a23e9769d394d6a061455cede
Ruby
damoguyan8844/rumoji
/lib/rumoji/emoji/nature.rb
UTF-8
5,590
2.65625
3
[ "MIT" ]
permissive
# -*- encoding: utf-8 -*- require 'rumoji/emoji' require 'set' module Rumoji class Emoji NATURE = Set[ self.new("2600" , [:sunny], "BLACK SUN WITH RAYS"), self.new("2614" , [:umbrella], "UMBRELLA WITH RAIN DROPS"), self.new("2601" , [:cloud]), self.new("2744" , [:snowflake]), self.new("26C4" , [:snowman], "SNOWMAN WITHOUT SNOW"), self.new("26A1" , [:zap], "HIGH VOLTAGE SIGN"), self.new("1F300", [:cyclone]), # "typhoon, hurricane self.new("1F301", [:foggy]), self.new("1F30A", [:ocean], "WATER WAVE"), # Animals self.new("1F431", [:cat], "CAT FACE"), self.new("1F436", [:dog], "DOG FACE"), self.new("1F42D", [:mouse], "MOUSE FACE"), self.new("1F439", [:hamster], "HAMSTER FACE"), self.new("1F430", [:rabbit], "RABBIT FACE"), self.new("1F43A", [:wolf], "WOLF FACE"), self.new("1F438", [:frog], "FROG FACE"), self.new("1F42F", [:tiger], "TIGER FACE"), self.new("1F428", [:koala]), self.new("1F43B", [:bear], "BEAR FACE"), self.new("1F437", [:pig], "PIG FACE"), self.new("1F43D", [:pig_nose]), self.new("1F42E", [:cow], "COW FACE"), self.new("1F417", [:boar]), self.new("1F435", [:monkey_face]), self.new("1F412", [:monkey]), self.new("1F434", [:horse], "HORSE FACE"), self.new("1F40E", [:racehorse], "HORSE"), self.new("1F42B", [:camel], "BACTRIAN CAMEL"), # "has two humps" self.new("1F411", [:sheep]), self.new("1F418", [:elephant]), self.new("1F43C", [:panda_face]), self.new("1F40D", [:snake]), self.new("1F426", [:bird]), self.new("1F424", [:baby_chick]), self.new("1F425", [:hatched_chick], "FRONT-FACING BABY CHICK"), self.new("1F423", [:hatching_chick]), self.new("1F414", [:chicken]), self.new("1F427", [:penguin]), self.new("1F422", [:turtle]), self.new("1F41B", [:bug]), self.new("1F41D", [:honeybee]), self.new("1F41C", [:ant]), self.new("1F41E", [:beetle], "LADY BEETLE"), # "ladybird, ladybug, coccinellids" self.new("1F40C", [:snail]), self.new("1F419", [:octopus]), self.new("1F420", [:tropical_fish]), self.new("1F41F", [:fish]), self.new("1F433", [:whale], "SPOUTING WHALE"), self.new("1F40B", [:whale2], "WHALE"), self.new("1F42C", [:dolphin]), self.new("1F404", [:cow2], "COW"), self.new("1F40F", [:ram]), self.new("1F400", [:rat]), self.new("1F403", [:water_buffalo]), self.new("1F405", [:tiger2], "TIGER"), self.new("1F407", [:rabbit2], "RABBIT"), self.new("1F409", [:dragon]), self.new("1F410", [:goat]), self.new("1F413", [:rooster]), self.new("1F415", [:dog2], "DOG"), self.new("1F416", [:pig2], "PIG"), self.new("1F401", [:mouse2], "MOUSE"), self.new("1F402", [:ox]), self.new("1F432", [:dragon_face]), self.new("1F421", [:blowfish]), self.new("1F40A", [:crocodile]), self.new("1F42A", [:dromedary_camel]), # "has a single hump" self.new("1F406", [:leopard]), self.new("1F408", [:cat2], "CAT"), self.new("1F429", [:poodle]), self.new("1F43E", [:paw_prints]), # Flowers self.new("1F490", [:bouquet]), self.new("1F338", [:cherry_blossom]), self.new("1F337", [:tulip]), self.new("1F340", [:four_leaf_clover]), self.new("1F339", [:rose]), self.new("1F33B", [:sunflower]), self.new("1F33A", [:hibiscus]), self.new("1F341", [:maple_leaf]), self.new("1F343", [:leaves], "LEAF FLUTTERING IN WIND"), self.new("1F342", [:fallen_leaf]), self.new("1F33F", [:herb]), self.new("1F344", [:mushroom]), self.new("1F335", [:cactus]), self.new("1F334", [:palm_tree]), self.new("1F332", [:evergreen_tree]), self.new("1F333", [:deciduous_tree]), self.new("1F330", [:chestnut]), self.new("1F331", [:seedling]), self.new("1F33C", [:blossom]), # "daisy" self.new("1F33E", [:ear_of_rice]), self.new("1F41A", [:shell], "SPIRAL SHELL"), self.new("1F310", [:globe_with_meridians]), # "used to indicate international input source, world clocks with time zones, etc." # Moon self.new("1F31E", [:sun_with_face]), self.new("1F31D", [:full_moon_with_face]), self.new("1F31A", [:new_moon_with_face]), self.new("1F311", [:new_moon], "NEW MOON SYMBOL"), self.new("1F312", [:waxing_crescent_moon], "WAXING CRESCENT MOON SYMBOL"), self.new("1F313", [:first_quarter_moon], "FIRST QUARTER MOON SYMBOL"), # "half moon" self.new("1F314", [:waxing_gibbous_moon], "WAXING GIBBOUS MOON SYMBOL"), # "waxing moon" self.new("1F315", [:full_moon], "FULL MOON SYMBOL"), self.new("1F316", [:waning_gibbous_moon], "WAINING GIBBOUS MOON SYMBOL"), self.new("1F317", [:last_quarter_moon], "LAST QUARTER MOON SYMBOL"), self.new("1F318", [:waning_crescent_moon], "WANING CRESCENT MOON SYMBOL"), self.new("1F31C", [:last_quarter_moon_with_face]), self.new("1F31B", [:first_quarter_moon_with_face]), self.new("1F319", [:moon], "CRESCENT MOON"), # "may indicate either the first or last quarter moon" self.new("1F30D", [:earth_africa], "EARTH GLOBE EUROPE-AFRICA"), self.new("1F30E", [:earth_americas], "EARTH GLOBE AMERICAS"), self.new("1F30F", [:earth_asia], "EARTH GLOBE ASIA-AUSTRALIA"), self.new("1F30B", [:volcano]), self.new("1F30C", [:milky_way]), self.new("26C5" , [:partly_sunny], "SUN BEHIND CLOUD") ] end end
true
a382405c7ff4e3eb4e004c1c75bf4eccd8368ae3
Ruby
timpalpant/bioruby-genomic-file
/spec/utils/parallelizer_spec.rb
UTF-8
1,565
2.75
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# # parallelizer_spec.rb # bioruby-genomic-file # # Created by Timothy Palpant on 6/28/11. # Copyright 2011 UNC. All rights reserved. # require 'spec_helper' require 'utils/parallelizer' describe Enumerable do before do @test = [1, 2, 3, 4, 5, 6, 7, 8] end context "#p_each" do it "should iterate over all entries once" do output_file = File.expand_path(File.dirname(__FILE__) + '/../fixtures/iteration-test.txt') begin @test.p_each do |entry| File.open(output_file, 'a+') do |f| f.puts entry end end result = File.readlines(output_file) result.length.should == 8 result.each { |line| @test.delete(line.chomp.to_i) } @test.length.should == 0 ensure File.delete(output_file) if File.exist?(output_file) end end it "should allow the number of threads to be set" do @test.p_each(:in_threads => 4) { |e| e } end it "should allow the number of processes to be set" do @test.p_each(:in_processes => 2) { |e| e } end end context "#p_map" do it "should return all entries" do result = @test.p_map { |e| e } result.length.should == @test.length result.each { |e| @test.delete(e) } @test.length.should == 0 end it "should allow the number of threads to be set" do @test.p_map(:in_threads => 4) { |e| e } end it "should allow the number of processes to be set" do @test.p_map(:in_processes => 2) { |e| e } end end end
true
6edb3b8d22d1ac679f20ed0c65b9be1458e2ac81
Ruby
dan-waters/advent_of_code_2020
/day1/main.rb
UTF-8
254
2.703125
3
[]
no_license
require_relative 'expenses_reader' require_relative 'expenses_calculator' expenses = ExpensesReader.new.expenses_from_file('inputs.csv') puts ExpensesCalculator.new.product_of_2(expenses, 2020) puts ExpensesCalculator.new.product_of_3(expenses, 2020)
true
157638e0afc494806c180518c9eef9ace20d642e
Ruby
felipemfp/programacao-de-computadores
/listas/lista-02/exercicio-18.rb
UTF-8
958
2.859375
3
[]
no_license
test1, work1 = gets.to_f, gets.to_f w_test1, w_work1 = gets.to_i, gets.to_i test2, work2 = gets.to_f, gets.to_f w_test2, w_work2 = gets.to_i, gets.to_i grade1 = (test1 * w_test1 + work1 * w_work1) / (w_test1 + w_work1) grade2 = (test2 * w_test2 + work2 * w_work2) / (w_test2 + w_work2) partial_grade = (grade1 * 2 + grade2 * 3) / 5 final_test = nil final_grade = partial_grade if partial_grade >= 2 and partial_grade < 6 final_test = gets.to_f final_grade1 = ((partial_grade + final_test) / 2) final_grade2 = ((2*grade1 + 3*final_test) / 5) final_grade3 = ((3*grade2 + 2*final_test) / 5) final_grade = (final_grade1 > final_grade2 and final_grade2 > final_grade3) ? final_grade1 : (final_grade2 > final_grade3 ? final_grade2 : final_grade3) end final_test_report = final_test ? '%.1f' % final_test : '-' report = (final_grade >= 6) ? 'APROVADO' : 'REPROVADO' puts '%.1f:%.1f:%s:%.1f:%s' % [grade1, grade2, final_test_report, final_grade, report]
true
985841a36990147753e971698bea88548ccb7204
Ruby
secorjeretweaz/als_typograf
/lib/als_typograf/request.rb
UTF-8
2,033
2.609375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# -*- encoding: utf-8 -*- require 'net/http' module AlsTypograf # The request class module Request SERVICE_URL = URI.parse('http://typograf.artlebedev.ru/webservices/typograf.asmx') SOAP_ACTION = '"http://typograf.artlebedev.ru/webservices/ProcessText"' RESULT_REGEXP = /<ProcessTextResult>\s*((.|\n)*?)\s*<\/ProcessTextResult>/ # Process text with remote web-service # @param [String] text text to process # @param [Hash] options options for web-service # @return [String] def self.process_text(text, options = {}) text = text.encode(options[:encoding]) body = <<-END_SOAP <?xml version="1.0" encoding="#{options[:encoding]}" ?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <ProcessText xmlns="http://typograf.artlebedev.ru/webservices/"> <text>#{text.gsub(/&/, '&amp;').gsub(/</, '&lt;').gsub(/>/, '&gt;')}</text> <entityType>#{options[:entity_type]}</entityType> <useBr>#{options[:use_br]}</useBr> <useP>#{options[:use_p]}</useP> <maxNobr>#{options[:max_nobr]}</maxNobr> </ProcessText> </soap:Body> </soap:Envelope> END_SOAP make_request(body, options) || text rescue StandardError => e AlsTypograf.log_exception(e) text end def self.make_request(text, options) request = Net::HTTP::Post.new(SERVICE_URL.path, 'Content-Type' => 'text/xml', 'SOAPAction' => SOAP_ACTION) request.body = text response = Net::HTTP.new(SERVICE_URL.host, SERVICE_URL.port).start { |http| http.request(request) } return nil unless response.is_a?(Net::HTTPSuccess) result = response.body result.force_encoding(options[:encoding]) if result.respond_to?(:force_encoding) result = Regexp.last_match[1].gsub(/&gt;/, '>').gsub(/&lt;/, '<').gsub(/&amp;/, '&').gsub(/(\t|\n)$/, '') if RESULT_REGEXP =~ result result.encode(options[:encoding]) end end end
true
fb7d91006274870e86ce66b1acbd823d557ac488
Ruby
lkriffell/whats-in-my-food
/app/facades/food_facade.rb
UTF-8
358
2.734375
3
[]
no_license
class FoodFacade def self.dishes_with_ingredient(ingredient) dishes = FoodService.dishes_with_ingredient(ingredient)[:foods] @dishes = dishes[0..9].map do |dish_data| Dish.new(dish_data) end end def self.total_dishes_with_ingredient(ingredient) total_dishes = FoodService.dishes_with_ingredient(ingredient)[:totalHits] end end
true
f5ff4be36d7612cf9865b94c164ed410f8fa937a
Ruby
Benjam-BB/Petbnb-Rails-BDD
/db/seeds.rb
UTF-8
1,038
2.640625
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # require 'faker' Dog.destroy_all Dogsitter.destroy_all Stroll.destroy_all City.destroy_all puts "tout a été détruit" 4.times do City.create!(city_name: Faker::Address.city) end puts "villes créées" 20.times do Dog.create!(name: Faker::FunnyName.name, city_id: City.all.sample.id) Dogsitter.create!(first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, city_id: City.all.sample.id) end puts "chiens et dogsitters créés" City.all.each do |city| i = city.id 2.times do #les where sont utilisés pour qu'une promenade ne puisse pas avoir lieu pour un chien et un dogsitter qui ne sont pas dans la meme ville Stroll.create!(date: Faker::Date.in_date_period, dog_id: Dog.where(city_id: i).sample.id, dogsitter_id: Dogsitter.where(city_id: i).sample.id) end end puts "promenades créées"
true
d610a9bcb4a7bf2ef08a57e912030e149201f033
Ruby
Sugai-Ayano/Bookers2-debug-5
/app/models/book.rb
UTF-8
465
2.640625
3
[]
no_license
class Book < ApplicationRecord belongs_to :user validates :title, presence: true validates :body, presence: true, length: {maximum: 200} def self.search_for(content,method) if method == 'perfet' Book.where(title: content) elsif method == 'foword' Book.where('title Like ?', content + '%') elsif method == 'backword' Book.method('title Like ?', '%' + content) else Book.where('title Like ?', '%' + content + '%') end end end
true
101cd58bc87abb62f3fc66b12a711fa2a10ca886
Ruby
anilktechie/rb2py
/pyfixes/find.rb
UTF-8
315
2.53125
3
[ "Zlib" ]
permissive
# array.find {|item| code} # ==> # def _block_XXXX(item): # code # rb2py.find(_block_XXXX, array) class FindNode def pyfix_find block_def, block_name_node = prepare_new_block call = make_rb2py_call 'find', block_name_node, target insert_new_block block_def, call return call end end
true
caa3bd93a667d9fb77e53c5306a03772bd229452
Ruby
TheGuth/launch_school
/launch_school_review/course_120/lesson_4/hard_1.rb
UTF-8
1,120
3.359375
3
[]
no_license
# Exercises: Hard 1 # Question 1. Alyssa has been assigned a task of modifying a class that was # initially created to keep track of secret information. The new requirement # calls for adding logging, when clients of the class attempt to access the # secret data. Here is the class in its current form: class SecretFile def initialize(secret_data, security_log) @data = secret_data @security_log = SecurityLogger.new end def data @security_log.create_log_entry @data end end # She needs to modify it so that any access to data must result in a log entry # being generated. That is, any call to the class which will result in data being # returned must first call a logging class. The logging class has been supplied to # Alyssa and looks like the following class SecurityLogger def create_log_entry # ... implementation omitted ... end end # Hint: Assume that you can modify the initialize method in SecretFile to have an # instance of SecurityLogger be passed in as an additional argument. # It may be helpful to review the lecture on collaborator objects for this exercise.
true
48476e8b79fae0027400442f3edd35068112a228
Ruby
ammar/cf_script
/lib/cf_script/command/cf/routes/routes.rb
UTF-8
814
2.5625
3
[ "MIT" ]
permissive
module CfScript::Command class Routes::RoutesCommand < CfScript::Command::Base ROUTES_TABLE = ['space', 'host', 'domain', 'apps'] def initialize super(:routes, :routes) end def run(*args, &block) run_cf self do |output| return unless good_run?(output) if rows = output.table(ROUTES_TABLE) routes = build_route_info(rows) block_given? ? yield(routes) : routes else error "Routes table was not found" end end end private def build_route_info(rows) routes = [] rows.each do |row| routes << CfScript::RouteInfo.new( row[:space].value, row[:host].value, row[:domain].value, row[:apps].to_a ) end routes end end end
true
e5d58a16a85dc115b081d0900a54b598e0a1d818
Ruby
microsoftgraph/msgraph-sdk-ruby
/lib/models/workbook_worksheet.rb
UTF-8
8,934
2.65625
3
[ "MIT" ]
permissive
require 'microsoft_kiota_abstractions' require_relative '../microsoft_graph' require_relative './models' module MicrosoftGraph module Models class WorkbookWorksheet < MicrosoftGraph::Models::Entity include MicrosoftKiotaAbstractions::Parsable ## # Returns collection of charts that are part of the worksheet. Read-only. @charts ## # The display name of the worksheet. @name ## # Returns collection of names that are associated with the worksheet. Read-only. @names ## # Collection of PivotTables that are part of the worksheet. @pivot_tables ## # The zero-based position of the worksheet within the workbook. @position ## # Returns sheet protection object for a worksheet. Read-only. @protection ## # Collection of tables that are part of the worksheet. Read-only. @tables ## # The Visibility of the worksheet. The possible values are: Visible, Hidden, VeryHidden. @visibility ## ## Gets the charts property value. Returns collection of charts that are part of the worksheet. Read-only. ## @return a workbook_chart ## def charts return @charts end ## ## Sets the charts property value. Returns collection of charts that are part of the worksheet. Read-only. ## @param value Value to set for the charts property. ## @return a void ## def charts=(value) @charts = value end ## ## Instantiates a new workbookWorksheet and sets the default values. ## @return a void ## def initialize() super end ## ## Creates a new instance of the appropriate class based on discriminator value ## @param parse_node The parse node to use to read the discriminator value and create the object ## @return a workbook_worksheet ## def self.create_from_discriminator_value(parse_node) raise StandardError, 'parse_node cannot be null' if parse_node.nil? return WorkbookWorksheet.new end ## ## The deserialization information for the current model ## @return a i_dictionary ## def get_field_deserializers() return super.merge({ "charts" => lambda {|n| @charts = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::WorkbookChart.create_from_discriminator_value(pn) }) }, "name" => lambda {|n| @name = n.get_string_value() }, "names" => lambda {|n| @names = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::WorkbookNamedItem.create_from_discriminator_value(pn) }) }, "pivotTables" => lambda {|n| @pivot_tables = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::WorkbookPivotTable.create_from_discriminator_value(pn) }) }, "position" => lambda {|n| @position = n.get_number_value() }, "protection" => lambda {|n| @protection = n.get_object_value(lambda {|pn| MicrosoftGraph::Models::WorkbookWorksheetProtection.create_from_discriminator_value(pn) }) }, "tables" => lambda {|n| @tables = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::WorkbookTable.create_from_discriminator_value(pn) }) }, "visibility" => lambda {|n| @visibility = n.get_string_value() }, }) end ## ## Gets the name property value. The display name of the worksheet. ## @return a string ## def name return @name end ## ## Sets the name property value. The display name of the worksheet. ## @param value Value to set for the name property. ## @return a void ## def name=(value) @name = value end ## ## Gets the names property value. Returns collection of names that are associated with the worksheet. Read-only. ## @return a workbook_named_item ## def names return @names end ## ## Sets the names property value. Returns collection of names that are associated with the worksheet. Read-only. ## @param value Value to set for the names property. ## @return a void ## def names=(value) @names = value end ## ## Gets the pivotTables property value. Collection of PivotTables that are part of the worksheet. ## @return a workbook_pivot_table ## def pivot_tables return @pivot_tables end ## ## Sets the pivotTables property value. Collection of PivotTables that are part of the worksheet. ## @param value Value to set for the pivotTables property. ## @return a void ## def pivot_tables=(value) @pivot_tables = value end ## ## Gets the position property value. The zero-based position of the worksheet within the workbook. ## @return a integer ## def position return @position end ## ## Sets the position property value. The zero-based position of the worksheet within the workbook. ## @param value Value to set for the position property. ## @return a void ## def position=(value) @position = value end ## ## Gets the protection property value. Returns sheet protection object for a worksheet. Read-only. ## @return a workbook_worksheet_protection ## def protection return @protection end ## ## Sets the protection property value. Returns sheet protection object for a worksheet. Read-only. ## @param value Value to set for the protection property. ## @return a void ## def protection=(value) @protection = value end ## ## Serializes information the current object ## @param writer Serialization writer to use to serialize this model ## @return a void ## def serialize(writer) raise StandardError, 'writer cannot be null' if writer.nil? super writer.write_collection_of_object_values("charts", @charts) writer.write_string_value("name", @name) writer.write_collection_of_object_values("names", @names) writer.write_collection_of_object_values("pivotTables", @pivot_tables) writer.write_number_value("position", @position) writer.write_object_value("protection", @protection) writer.write_collection_of_object_values("tables", @tables) writer.write_string_value("visibility", @visibility) end ## ## Gets the tables property value. Collection of tables that are part of the worksheet. Read-only. ## @return a workbook_table ## def tables return @tables end ## ## Sets the tables property value. Collection of tables that are part of the worksheet. Read-only. ## @param value Value to set for the tables property. ## @return a void ## def tables=(value) @tables = value end ## ## Gets the visibility property value. The Visibility of the worksheet. The possible values are: Visible, Hidden, VeryHidden. ## @return a string ## def visibility return @visibility end ## ## Sets the visibility property value. The Visibility of the worksheet. The possible values are: Visible, Hidden, VeryHidden. ## @param value Value to set for the visibility property. ## @return a void ## def visibility=(value) @visibility = value end end end end
true
c782682238319bbaf675d1507512f16d20ff7d33
Ruby
rgylling/countdown-to-midnight-v-000
/countdown.rb
UTF-8
171
3.578125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def countdown(integer) while integer > 0 puts "#{integer} SECOND(S)!" integer -=1 end "HAPPY NEW YEAR!" end def countdown_with_sleep(integer) sleep(integer) end
true
843ab70307bdaad76a98df7769d58cc7b4faa9e7
Ruby
Yoni-Satat/ruby_project
/controllers/artist_controller.rb
UTF-8
685
2.609375
3
[]
no_license
require_relative('../models/album.rb') require_relative('../models/artist.rb') require_relative('../models/genre.rb') get '/artist' do @artist = Artist.all() erb(:"artist/index") end get '/artist/new' do erb :"artist/create_artist" end post '/artist' do artist = Artist.new(params) artist.save() redirect to ('/artist') end post '/artist/:id/delete' do if Artist.delete(params["id"]) == true redirect to ('/artist') else erb :"artist/warning" end end get '/artist/:id/update' do @artist = Artist.find(params["id"]) erb :"artist/update_artist" end post '/artist/:id' do @artist = Artist.new(params) @artist.update redirect to ('/artist') end
true