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
9c4ba6065738f87d1ef554c221a02540db58f653
Ruby
lawrend/project-euler-even-fibonacci-q-000
/lib/even_fibonacci.rb
UTF-8
219
3.171875
3
[]
no_license
def even_fibonacci_sum(limit) allFib = [1,1] while allFib[-1]<limit && (allFib[-1]+allFib[-2]) <limit allFib.push(allFib[-1]+allFib[-2]) end evenFib = allFib.delete_if &:odd? return evenFib.inject(:+) end
true
b15136e89b9274dad9009e1c69614bdf0f801aab
Ruby
fuchsto/aurita
/lib/aurita/base/bits/hash.rb
UTF-8
225
2.84375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Hash def to_get_params string = '' self.each_pair { |k,v| string << k.to_s << '=' << v.to_s << '&' } string[0..-2] end def dup d = {} each_pair { |k,e| d[k] = e } d end end
true
c01bc2f7199b2a4caac7a0dc3f905c5c3df4c264
Ruby
hyphenized/exercism
/ruby/difference-of-squares/difference_of_squares.rb
UTF-8
335
3.453125
3
[]
no_license
class Squares def initialize num @num=num end def square_of_sum (1..@num).sum ** 2 end def sum_of_squares (1..@num).map{|x|x**2}.sum end def difference square_of_sum - sum_of_squares end end # Find the difference between the square of the sum and the sum of the squares of the first N natural numbers.
true
6824fb3fd2007dc3146d92fcf33c70e8d3fcc26b
Ruby
trixiegoff/word-processor
/anagram.rb
UTF-8
2,104
3.359375
3
[]
no_license
class String def histogram out = {} out.default = 0 self.gsub(/[^a-z]/i, '').upcase.each_char {|c| out[c] += 1} out end def is_anagram (s) needle = self.histogram haystack = s.histogram needle.keys.each {|c| haystack[c] -= needle[c] } result = not(haystack.values.any?{|v| v < 0 }) remainder = "" haystack.each_pair{|c, q| remainder += result ? c*q : q < 0 ? c*q.abs : "" } return result, remainder end end def prompt () print "> " _s = gets.strip if _s[0] =~ /[[:alpha:]]/ then return false, _s else return _s.slice!(0), _s.upcase end end def filter_words (wordlist, haystack) cnt, grafiks = 0, "|/-\\".split('') results = [] wordlist.each do |line| word = (line.class == Array) ? line[0] : line # puts ">>> checking to see if #{word} is an anagram of #{haystack}" word.gsub!(/[^a-z]/i, '') result, remainder = word.is_anagram haystack if result then results << [line, remainder] print "#{grafiks[(cnt+=1)%grafiks.length]}\033[1D" end end results end def print_results (res) res.sort_by{|e| e[0].length}.each do |word| puts("#{word[0]} \t[#{word[1]}]") end end wordlist = File.readlines('words.txt').map{|line| line.strip } # of = "MY ALGORITHM ISNT VERY EFFICIENT" quit = false stack = [] results = [] of = "" while not quit do cmd, thing = prompt case cmd when '`' quit = true when '+' can, remainder = thing.is_anagram of if can then results.select!{|e| e.is_anagram remainder } print_results(results) of = remainder else puts "NEED#{"S" unless remainder.length == 1} #{remainder}" end when '-' puts thing of = of + thing results = filter_words(wordlist, of) print_results(results) when '!' stack = [] of = thing results = filter_words(wordlist, thing) print_results(results) when "?" # results.map{|e| puts(e[0]) } puts(thing.histogram) when ">" File.write("_anagrams.log", results.join("\n")) else of = thing results = filter_words(wordlist, thing) print_results(results) end if results.first.is_a?(Array) then results.map!{|e| e[0]} end end # planck length
true
8c39a1485220176433acc5a6c206908ccfd78f93
Ruby
boomer/tealeaf
/course1/lesson1/blackjack.rb
UTF-8
4,977
3.40625
3
[]
no_license
# blackjack.rb # Michael Boomershine # Edited 11/16/14 require 'pry' def create_deck deck = [{"2H" => 2}, {"2C" => 2}, {"2S" => 2}, {"2D" => 2}, {"3H" => 3}, {"3C" => 3}, {"3S" => 3}, {"3D" => 3}, {"4H" => 4}, {"4C" => 4}, {"4S" => 4}, {"4D" => 4}, {"5H" => 5}, {"5C" => 5}, {"5S" => 5}, {"5D" => 5}, {"6H" => 6}, {"6C" => 6}, {"6S" => 6}, {"6D" => 6}, {"7H" => 7}, {"7C" => 7}, {"7S" => 7}, {"7D" => 7}, {"8H" => 8}, {"8C" => 8}, {"8S" => 8}, {"8D" => 8}, {"9H" => 9}, {"9C" => 9}, {"9S" => 9}, {"9D" => 9}, {"10H" => 10}, {"10C" => 10}, {"10S" => 10}, {"10D" => 10}, {"JH" => 10}, {"JC" => 10}, {"JS" => 10}, {"JD" => 10}, {"QH" => 10}, {"QC" => 10}, {"QS" => 10}, {"QD" => 10}, {"KH" => 10}, {"KC" => 10}, {"KS" => 10}, {"KD" => 10}, {"AH" => 1}, {"AC" => 1}, {"AS" => 1}, {"AD" => 1}] end def show_table(deck, player_name, player_hand, player_total, player_cards, dealer_hand, dealer_total, dealer_cards, prompt) puts "\e[H\e[2J" puts "* * * * * * * * * * * * * * * * * BLACKJACK * * * * * * * * * * * * * * * * *" puts "* * * *" puts "*#{player_name.upcase.center(24)} * * DEALER *" puts "* * * *" puts "*#{player_cards.join(", ").center(24)} *#{prompt.to_s.center(23)}*#{dealer_cards.join(", ").center(24)} *" puts "* * * *" puts "*#{player_total.to_s.center(24)} * *#{dealer_total.to_s.center(24)} *" puts "* * * *" puts "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *" puts "" puts ">> #{prompt.to_s}" end def get_player_name puts "Welcome to Blackjack. What's your name?" player_name = gets.chomp end def say(msg) puts msg sleep(0.25) 3.times do puts "." sleep(0.25) end end def deal_first_cards(deck, player_hand, dealer_hand) 2.times do card = deck.sample player_hand << card deck.delete(card) card = deck.sample dealer_hand << card deck.delete(card) end end def deal_cards(deck, hand) card = deck.sample hand << card deck.delete(card) end def update_cards(cards) temp_array = [] cards.each do |cards| temp_array << cards.keys end cards = temp_array.flatten end def update_total(cards) temp_array = [] cards.each do |cards| temp_array << cards.values temp_array.flatten! end if temp_array.include?(1) temp_array.delete(1) total = temp_array.inject(0) {|sum, i| sum + i } if total < 10 total = total + 1 else total = total + 11 end else total = temp_array.inject(0) {|sum, i| sum + i } end end def get_player_choice player_choice = gets.chomp.upcase # add error checking for user input end def calculate_win(player_name, player_choice, player_total, dealer_total) # binding.pry if (player_total == 21) & (dealer_total == 21) return "Standoff." elsif dealer_total > 21 return "Dealer busts!" elsif player_total == 21 return "#{player_name.upcase} gets Blackjack!" elsif dealer_total == 21 return "Dealer gets Blackjack!" elsif player_total > 21 return "#{player_name.upcase} busts!" elsif (player_choice == "STAY") & (player_total < dealer_total) return "You deserve to lose." else return nil end end deck = create_deck player_hand, dealer_hand, player_cards, dealer_cards, player_total, dealer_total, player_choice = [], [], [], [], 0, 0, " " prompt = "Hit or stay?" player_name = get_player_name say("Hi #{player_name}. Dealing your first two cards.") begin if player_hand.empty? deal_first_cards(deck, player_hand, dealer_hand) elsif (player_choice == "STAY") & (dealer_total < 17) deal_cards(deck, dealer_hand) prompt = "Dealer hits again." sleep(0.25) 3.times do puts "." sleep(0.25) end else player_choice = get_player_choice case when player_choice == "HIT" deal_cards(deck, player_hand) prompt = "Hit or stay?" when player_choice == "STAY" deal_cards(deck, dealer_hand) prompt = "Dealer hits." end end player_total, dealer_total = update_total(player_hand), update_total(dealer_hand) player_cards, dealer_cards = update_cards(player_hand), update_cards(dealer_hand) show_table(deck, player_name, player_hand, player_total, player_cards, dealer_hand, dealer_total, dealer_cards, prompt) win_or_bust = calculate_win(player_name, player_choice, player_total, dealer_total) end until win_or_bust prompt = win_or_bust show_table(deck, player_name, player_hand, player_total, player_cards, dealer_hand, dealer_total, dealer_cards, prompt) # puts "Would you like to play another hand (Y/N)?" # replay = gets.chomp
true
6a480d66e18a4b2db2e76a6c355b9c2aa7c5ec73
Ruby
inclooder/math_expr
/lib/math_expression/parser.rb
UTF-8
1,442
3.203125
3
[ "MIT" ]
permissive
# frozen_string_literal: true require_relative './postfix_evaluator' require_relative './tokenizer' class MathExpression::Parser def initialize(expression) @expression = expression end def to_tokens MathExpression::Tokenizer.new(expression).call end def to_postfix output_queue = [] operator_stack = [] tokens = to_tokens tokens.each do |token| type, value = token[:type], token[:value] case type when :number output_queue << value when :operator loop do break if operator_stack.empty? break if operator_stack.last && operator_stack.last[:value] == '(' break if operator_stack.last && operator_stack.last[:precedence] <= token[:precedence] output_queue << operator_stack.pop[:value] end operator_stack.push(token) when :parenthesis if token[:value] == '(' operator_stack.push(token) else while operator_stack.last && operator_stack.last[:value] != '(' output_queue << operator_stack.pop[:value] end if operator_stack.last && operator_stack.last[:value] == '(' operator_stack.pop end end end end (output_queue + operator_stack.reverse.map { |x| x[:value] }) end def evaluate MathExpression::PostfixEvaluator.new(to_postfix).call end private attr_reader :expression end
true
97a82015bc0fd5ad0c93883a3bc240fece5f2164
Ruby
W-Mills/ruby-exercises
/Code Challenges/Easy/beer_song.rb
UTF-8
2,312
4.71875
5
[]
no_license
# Beer Song # Write a program that can generate the lyrics of the 99 Bottles of Beer song. See the test suite for the entire song. # Write a program to generate the lyrics of the 99 bottles of beer song. # Verse 99: # => "99 bottles of beer on the wall, 99 bottles of beer." # => "Take one down and pass it around, 98 bottles of beer on the wall." #Verse 2: # => "2 bottles of beer on the wall, 2 bottles of beer." # => "Take one down and pass it around, 1 bottle of beer on the wall." #Verse 1: # => "1 bottle of beer on the wall, 1 bottle of beer." # => "Take one down and pass it around, no more bottles of beer on the wall." #Verse 0: # => "No more bottles of beer on the wall, no more bottles of beer." # => "Go to the store and buy some more, 99 bottles of beer on the wall." # Problem: # => iterate through the verses from 99 down to 0, returning (outputting?) each verse # => verses 99..3 are all the same except for the number of bottles decreasing by 1 each time # => verse 2 has to lose the "s" plural when it becomes 1 bottle # => verse 1 has to lose the "s" plural, and also finally say "no more bottles" # => verse 0 is very different, has fully different second half of verse # Approach: # => Create a string with interpolation for the verses with different numbers of beer bottles # => Create a unique string for verses 0-2 class BeerSong attr_accessor :num def verse_pt_1 "#{num} bottles of beer on the wall, #{num} bottles of beer.\n" end def verse_pt_2 "Take one down and pass it around, #{num} bottles of beer on the wall.\n" end def last_verse "No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n" end def verse(verse_num) self.num = verse_num return last_verse if num == 0 pt_1 = verse_pt_1 pt_1.gsub! /bottles/, 'bottle' if num == 1 self.num -= 1 if num > 0 pt_2 = verse_pt_2 if num == 1 pt_2.gsub! /bottles/, 'bottle' elsif num == 0 pt_2.gsub! /0/, 'no more' pt_2.gsub! /one/, 'it' end pt_1 + pt_2 end def verses(first, last) first.downto(last).map { |verse_num| verse(verse_num) }.join("\n") end def lyrics verses(99, 0) end end puts BeerSong.new.verse(1)
true
30ece26986e812ebf6852f93300644d7a31282f0
Ruby
nadeka/ratebeer
/spec/features/beers_spec.rb
UTF-8
2,217
2.5625
3
[]
no_license
require 'rails_helper' describe "Beer" do it "should have zero beers at first" do visit beers_path expect(page).to have_content 'Beers' expect(page).to have_content '0 beers' end describe "when beers exists" do before :each do @beers = ["Karhu", "Tuplahumala", "Lite"] @beers.each do |beer_name| FactoryGirl.create(:beer, name: beer_name) end visit beers_path end it "lists existing beers and their total number" do expect(page).to have_content "#{@beers.count} beers" @beers.each do |beer_name| expect(page).to have_content beer_name end end it "allows user to navigate to a page of a beer" do click_link "Karhu" expect(page).to have_content "Karhu" expect(page).to have_content "Style: lager" end end describe "when created" do before :each do FactoryGirl.create(:user) log_in(username: 'Kate', password: 'Secret1') visit beers_path end it "is saved if the name is valid" do FactoryGirl.create(:brewery, name:"Koff", year:1938) FactoryGirl.create(:style) visit new_beer_path fill_in('beer_name', with:'Lite') select('lager', from:'beer[style_id]') select('Koff', from:'beer[brewery_id]') expect{ click_button "Create Beer" }.to change{Beer.count}.from(0).to(1) expect(page).to have_content "Beer was successfully created." end it "is not saved if the name is invalid" do FactoryGirl.create(:brewery, name:"Koff", year:1938) FactoryGirl.create(:style) visit new_beer_path select('lager', from:'beer[style_id]') select('Koff', from:'beer[brewery_id]') click_button "Create Beer" expect(Beer.count).to eq(0) expect(page).to have_content "error" expect(page).to have_content "Name is too short (minimum is 1 character)" end end end
true
df971618d1dfd3a020754e198ac557bfb12498ae
Ruby
lukaswet/My-Ruby-first-steps
/myapp_05_16/whatnumber.rb
UTF-8
461
3.546875
4
[]
no_license
whatnumber = rand(0..100) time_att = 10 1.upto(time_att) do |attempt| print "Я загадав число. Вгадай яке? Спроба: #{attempt}. Осталось #{time_att - attempt} попыток. " answer = gets.to_i if answer == whatnumber puts "Вгадав" exit elsif answer > whatnumber puts "Нет. Ваше число больше." elsif answer < whatnumber puts "Нет. Ваше число меньше." end end
true
b715844be58af6f2ce4f9175d3acc97e5329e02d
Ruby
Edardgtz/practice_ruby
/inheritance_example.rb
UTF-8
753
3.640625
4
[]
no_license
class Vehicle def initialize @speed = 0 @direction = 'north' end def current_direction @direction end def brake @speed = 0 end def accelerate @speed += 10 end def current_speed @speed end def turn(new_direction) @direction = new_direction end end class Car < Vehicle def honk_horn puts "Beeeeeeep!" end end class Bike < Vehicle def ring_bell puts "Ring ring!" end end car = Car.new bike = Bike.new car.accelerate bike.accelerate bike.ring_bell car.honk_horn p bike.current_direction p car.current_direction car.turn("south") bike.turn("south") p bike.current_direction p car.current_direction p bike.current_speed p car.current_speed car.accelerate p car.current_speed
true
5afec8a622803d50e289ee24a14edbfafea05581
Ruby
paploo/warriorbots-core
/backend/lib/child_process.rb
UTF-8
3,821
3.03125
3
[]
no_license
# # A library for managing child processes. # Only compatible with UNIX based systems. # class ChildProcess @@child_processes = [] # Create a child process either by running a shell command or by supplying a # block to run. # # When running a shell command that is going to exit on its own, it is often # best to call wait, which blocks execution until the command has exited. # The second argument to new, if 'true', will call wait for you. def initialize(command=nil, wait=false, &block) if block.nil? @pid = fork { exec(command) } else @pid = fork &block end Process::detach(@pid) @status = nil wait() if wait end # Return the pid of the related process. attr_reader :pid # Gets the status of the pid by calling ps. Returns the recieved values as a # Hash. If the process has already completed, the hash contains the Proces::Status # object and any keys pre-filled that it can.. # The optional argument supplies an array of fields to parse. The default # fields work on OS X 10.5 and Ubuntu 7. There are few instances where # changing them is useful. def status(fields=['pid','ppid','stat','xstat','%cpu','%mem','rss','etime','ruser','command']) return {'Process::Status' => @status, 'PID' => @status.pid, 'XSTAT' => @status.exitstatus} if @status result = `ps -p #{@pid} -o #{fields.join(',')}` lines = result.split("\n") if lines[1] header = lines[0].strip.split(/\s+/) values = lines[1].strip.split(/\s+/,header.length) return Hash[ *(header.zip(values).flatten) ] else return {} end end # Checks to see if hte process is still running. It firsts looks to see if # the process is already known to be terminated. After that, it confirms it # is running using ps. # Note that zombies are reported as not running. (Zombies can hang around for # a wee bit before being reaped, unless one uses wait.) def running? return false if( @status ) result = `ps -o pid,stat -p #{@pid} | grep #{@pid}`.chomp if( result && result.length > 0 ) stat = result.strip.split(/\s+/)[1] if stat=~/Z/ wait() return false else return true end else return false end end # Asks to quit the process by sending a signal to the process (default SIGTERM), # waits for it to exit, and then returns the cleanup information as an array. # # Note that if the child process is your own ruby script, you should call # something like: # Signal.trap('SIGTERM') { exit(0) } # so that it quits cleanly. def quit(signal='SIGTERM') kill(signal) @status = wait() return @status end # Send any signal to the process. By default it sends a SIGTERM, just like # UNIX's kill command. It does not wait for the process to run the signal, # therefore, if giving a signal that results in termination, it is better to # use :quit. def kill(signal='SIGTERM') return false if @status begin result = Process::kill(signal, @pid) return result rescue Errno::ESRCH => e return false end end alias_method :signal, :kill # Causes the current thread to block until the process has exited and its status # has been reaped. def wait() return @status if @status begin pid, @status = Process.wait2(@pid) rescue Exception => e pid, @status = [nil, nil] end return @status end # Output a human readable form. def to_s exited_s = @status.nil? ? 'false' : "true(#{@status.exitstatus})}" return "#<#{self.class.name}:0x#{object_id.to_s(16)} pid=#{@pid}, exited=#{exited_s}>" end # Output a human readable detailed form. def inspect return to_s end end
true
f6d8d21a838879bf3471de266258a13ff7479b1c
Ruby
BenR1312/rails-template
/app/models/fleet.rb
UTF-8
1,283
2.65625
3
[]
no_license
class Fleet < ActiveRecord::Base acts_as_paranoid has_many :fleet_trucks, inverse_of: :fleet has_many :trucks, through: :fleet_trucks accepts_nested_attributes_for :fleet_trucks, allow_destroy: true validates_associated :fleet_trucks validates :fleet_name, presence: true # We need to manually ensure the uniqueness of Truck ids because when a Fleet is being # created it will not have an id for the FleetTruck object to validate against # # This call must be under the validates_associated(:fleet_trucks), because that validation # will remove any errors we manually add to the FleetTruck objects validate :unique_truck_ids private def has_duplicate_truck_ids? truck_ids = fleet_trucks.map(&:truck_id) truck_ids != truck_ids.uniq end def unique_truck_ids if has_duplicate_truck_ids? # Ensure error message will be visible of Fleet form fleet_trucks.each do |fleet_truck| fleet_truck.errors.add(:truck, "You cannot assign the same Truck multiple times") end # Since validates_associated will be called before this validation, we need to force # this Fleet to be invalid by setting and error errors.add(:fleet_trucks, "You cannot assign the same Truck multiple times") end end end
true
42eb123b17a0287b3b475b6ceb9f3625ecea5646
Ruby
vertis/nomad
/features/step_definitions/when_i_wait_steps.rb
UTF-8
73
2.53125
3
[ "MIT" ]
permissive
When /^I wait for (\d+) seconds?$/ do |seconds| sleep(seconds.to_i) end
true
5cbaa42b39fe325535665432c742e8fd16122389
Ruby
Radik73/convert_util
/lib/parsers/atom_parser.rb
UTF-8
978
2.90625
3
[]
no_license
require_relative 'parser' require 'nokogiri' require 'active_support/core_ext/hash/conversions' class AtomParser < Parser def self.can_parse?(xml) begin xml.xpath('//xmlns:entry').text true rescue Nokogiri::XML::XPath::SyntaxError false end end def transform_hash(hash) content_storage = Array.new result_storage = Hash.new hash['feed']['entry'].each do |entry| list = Array.new list.append(entry["title"]) list.append(scrap_link(entry["link"])) list.append(entry["updated"]) list.append(entry["summary"]) content_storage.append(list) end result_storage[:title] = hash['feed']['title'] result_storage[:link] = scrap_link(hash['feed']['link']) result_storage[:content] = content_storage result_storage end protected def scrap_link(links) if links.class.to_s.eql?( 'Array') link = links[0]['href'] else link = links['href'] end end end
true
d051042fe6773796f4637d4d4b108dfb6f35e7bf
Ruby
christianlarwood/ruby_small_problems
/live_coding_exercises/product_search.rb
UTF-8
1,432
4.1875
4
[]
no_license
=begin Write a method that will return the products given the criteria in query and query2 input: hash output: an array of hashes algorithm: - initialize a result variable and assign to an empty array - iterate over PRODUCTS - iterate over each hash - if the price is between min & max and name includes value in q then select or add to new array - =end PRODUCTS = [ { name: "Thinkpad x210", price: 220}, { name: "Thinkpad x230", price: 250}, { name: "Thinkpad x250", price: 979}, { name: "Thinkpad x230", price: 300}, { name: "Thinkpad x230", price: 330}, { name: "Thinkpad x230", price: 350}, { name: "Thinkpad x240", price: 700}, { name: "Macbook Leopard", price: 300}, { name: "Macbook Air", price: 700}, { name: "Macbook Pro", price: 600}, { name: "Macbook", price: 1449}, { name: "Dell Latitude", price: 200}, { name: "Dell Latitude", price: 650}, { name: "Dell Inspiron", price: 300}, { name: "Dell Inspiron", price: 450} ] query = { price_min: 240, price_max: 280, q: "thinkpad" } query2 = { price_min: 300, price_max: 450, q: 'dell' } def search(query) PRODUCTS.select do |hash| hash[:price].between?(query[:price_min], query[:price_max]) && hash[:name].downcase.include?(query[:q]) end end puts search(query) == [ { name: "Thinkpad x230", price: 250} ] puts search(query2) == [ { name: "Dell Inspiron", price: 300}, { name: "Dell Inspiron", price: 450} ]
true
eb8050579b7020e591c46936e77ac480292c7960
Ruby
byendan/poker_on_rails
/spec/models/table_spec.rb
UTF-8
2,272
3
3
[]
no_license
require 'rails_helper' RSpec.describe Table, type: :model do describe "initialize the table" do it "sets up a table with a user" do table = Table.new(user: "Brendan") expect(table.user).to eq("Brendan") end it "sets up ai players" do table = Table.new(ai_count: 5) expect(table.players.length).to eq(6) end it "puts the user in the players array" do user_name = "Brendan" table = Table.new(user: user_name, ai_count: 5) user_found = false table.players_ary.each {|player| user_found = true if player.name == user_name} expect(user_found).to be_truthy end it "deals cards" do table = Table.new(ai_count: 3) expect(table.players_ary.length).to eq(4) table.players_ary.each {|player| expect(player.cards.length).to eq(2)} end end describe "table game functions" do let(:table) {Table.new(ai_count: 3)} it "deals a flop to the table" do table.flop expect(table.community_cards.length).to eq(3) end it "deals a single card to the table" do table.flip expect(table.community_cards.length).to eq(1) table.flip expect(table.community_cards.length).to eq(2) end it "deals all cards to the table, then dealing is complete" do t = Table.new(ai_count: 1) table.flop table.flip table.flip expect(table.community_cards.length).to eq(5) expect(table.dealing_finished).to be true end it "clears the community cards on demand" do t = Table.new(ai_count: 1) table.flop 2.times {table.flip} expect(table.dealing_finished).to be true table.clear_community_cards expect(table.dealing_finished).to be false end it "clears the players cards" do t = Table.new(ai_count: 2) t.clear_player_cards t.players_ary.each {|player| expect(player.cards.length).to eq(0)} expect(t.dealer.master_deck.length).to eq(52 * 6) end it "clears all cards on the table" do t = Table.new(ai_count: 2) t.flop 2.times {t.flip} t.clear_all_cards t.players_ary.each {|player| expect(player.cards.length).to eq(0)} expect(t.dealer.master_deck.length).to eq(52 * 6) end end end
true
0867b4a0a7548de40c774ef8b18c0dc36d14dcf2
Ruby
relev/skud
/test/models/visit_test.rb
UTF-8
730
2.796875
3
[]
no_license
require 'test_helper' class VisitTest < ActiveSupport::TestCase def create_visit(duration) visit = Visit.new visit.created_at = Time.at(Time.now.to_i - duration*60) visit end test "плата за 10 минут = 15р" do visit = create_visit(10) assert visit.to_state[:price] == 15 end test "плата за 61 минуту = 91р" do visit = create_visit(61) assert visit.to_state[:price] == 91 end test "плата за 119 минуту = #{90+59}р" do visit = create_visit(119) assert visit.to_state[:price] == 90+59 end test "плата за 120 минуту = #{90+60-20}р" do visit = create_visit(120) assert visit.to_state[:price] == 90+60-20 end end
true
48bfe2a9c351ebe0d2b9b989b40c294ea7d993c7
Ruby
gwenh11/LS_core
/100/exercises/exercise_2.rb
UTF-8
153
4
4
[]
no_license
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Method 1 arr.each do |num| if num > 5 puts num end end # Method 2 arr.each {|num| puts num if num > 5}
true
aef706f61076e616b7566c08ba266eb1cb8efc1f
Ruby
ozybrennan/chess
/w2d3/pawn.rb
UTF-8
743
3.5
4
[]
no_license
require_relative 'piece.rb' class Pawn < Piece attr_accessor :pos attr_reader :board, :color, :symbol, :value def initialize(board, pos, color) super(board, pos, color) @symbol = ( color == :black ? "\u2659" : "\u265F" ) @value = 1 end def moves dx = ( color == :black ? 1 : -1 ) x, y = pos forward_moves = [[x + dx, y]] if (x == 1 && color == :black) || (x == 6 && color == :white) forward_moves << [x + dx * 2, y] end forward_moves.select! { |move| check_board_at(move) == :nil } diagonal_moves = [[x + dx, y - 1], [x + dx, y + 1]].select do |move| check_board_at(move) == :opponent end (forward_moves + diagonal_moves).reject { |move| off_board?(move) } end end
true
bde9ab8ecaf5f7d37187bf10bd99e77bd1fd61c4
Ruby
tuned-up/algorithms-playground
/chapter2/erastofen_table/erastofen_table_oop.rb
UTF-8
1,281
3.53125
4
[]
no_license
require 'forwardable' class ErastofenTable class IntegerWithInfo extend Forwardable attr_reader :number attr_accessor :is_composite def_delegators :@number, :<=>, :+, :-, :* def initialize(number) @number = number @is_composite = false end alias is_composite? is_composite def mark_as_composite! @is_composite = true end def to_int @number end end FIRST_PRIME_NUMBER = 2 attr_reader :number, :range, :upper_limit def initialize(number) @number = number @range = (1..number).map { |number| IntegerWithInfo.new(number) } @upper_limit = Math.sqrt(number) end def call return if number < FIRST_PRIME_NUMBER current_number = FIRST_PRIME_NUMBER while current_number <= upper_limit (current_number * 2 .. number).step(current_number).each do |number| range[number - 1].mark_as_composite! end current_number = get_next_number(current_number) end range[1..-1].reject { |number| number.is_composite || number == 1 }.map(&:to_int) end private def get_next_number(current_number) range.each do |number| next if number.is_composite? || number <= current_number.to_int return number end end end
true
14f7af120abf0cf04cf2177aacf62474c7506b5c
Ruby
KasperKen/anagram-detector-online-web-ft-110419
/lib/anagram.rb
UTF-8
195
3.5625
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Anagram attr_accessor :word def initialize(input) @word = input end def match(string) string.select {|is_anagram| is_anagram.chars.sort == @word.chars.sort} end end
true
844135aa8987545e14e11a6b79fcd666b84d5d80
Ruby
kyojo/LDA
/lda.rb
UTF-8
2,859
2.734375
3
[]
no_license
corpus = Array.new(){[]} #corpus[doc_index][token_index] = word wd = [] allwd = [] k = 10 iterate = 100 alpha = beta = 1.0 #Load File File.open("kakaku_filtered.txt") do |f| while l = f.gets wd = l.split(" ") for w in wd do w.slice!(/_.*/) end wd.delete_if{|item| (item.length == 1 && !item=~/[\W_]/) || item=~/[!-~]|[A-Z]|[a-z]|[0-9]|!|?/} #delete stopword corpus << wd end end #Initialization lendoc = corpus.length topic = Marshal.load(Marshal.dump(corpus)) #topic[doc_index][token_index] = topic_index n_wz = Array.new(k){{}} #n_wz[z]["word"]:the number of times topic z is assigned to word w n_dz = Array.new(lendoc){Array.new(k, 0)} #n_dz[doc_index][topix_index]:the number of tokens with topic z in document d n_z = Array.new(k, 0) #n_z[z] = ∑n_z,w n_d = Array.new(lendoc, 0) #n_d[doc_index] = ∑n_d,z for m in 0..lendoc-1 for i in 0..corpus[m].length-1 z = rand(k) topic[m][i] = z if n_wz[z].key?(corpus[m][i]) n_wz[z][corpus[m][i]] += 1 else n_wz[z][corpus[m][i]] = 1 end n_dz[m][z] += 1 n_d[m] += 1 n_z[z] += 1 allwd << corpus[m][i] end end allwd.uniq! v = allwd.length #v:the number of word types p_z = Array.new(k) #Main Algorithm for n in 0..iterate for m in 0..lendoc-1 for i in 0..corpus[m].length-1 z = topic[m][i] n_wz[z][corpus[m][i]] -= 1 n_dz[m][z] -= 1 n_d[m] -= 1 n_z[z] -= 1 temp = 0.0 for j in 0..k-1 if n_wz[j].key?(corpus[m][i]) p_z_molecule = (n_wz[j][corpus[m][i]] + beta) * (n_dz[m][j] + alpha).to_f else p_z_molecule = beta * (n_dz[m][j] + alpha).to_f end p_z_denominator = (n_z[j] + beta*v) * (n_d[m] + alpha*k).to_f p_z[j] = p_z_molecule / p_z_denominator temp += p_z[j] end for j in 0..k-1 p_z[j] = p_z[j] / temp end roulette = rand if roulette < p_z[0] z = 0 else for j in 1..k-1 p_z[j] += p_z[j-1] if roulette < p_z[j] z = j break end end end topic[m][i] = z if n_wz[z].key?(corpus[m][i]) n_wz[z][corpus[m][i]] += 1 else n_wz[z][corpus[m][i]] = 1 end n_dz[m][z] += 1 n_d[m] += 1 n_z[z] += 1 end end end #Output resultary = Array.new(10) for z in 0..k-1 result = {} puts "------------------------------------------------\nz=#{z}" for m in 0..lendoc-1 for i in 0..corpus[m].length-1 if topic[m][i] == z e = (n_wz[z][corpus[m][i]] + beta) / (n_z[z] + beta*v).to_f result[corpus[m][i]] = e end end end resultary = result.sort{|(k1, v1), (k2, v2)| v2 <=> v1}[0..9] for res in resultary puts res end end
true
0a74d3aa40a95f0031d697ef27c0ba077fd207df
Ruby
MayankKashyap/Ruby
/9.rb
UTF-8
395
3.390625
3
[]
no_license
#def test(a = "hey" , b = "amn") #puts "#{a}" # puts "#{b}" #end #test "Mayank", "Kashyap" #test def test i = 100 j = 200 k = 300 return i, j, k end var = test puts var def sample (*test) puts "The number of parameters is #{test.length}" for i in 0...test.length puts "The parameters are #{test[i]}" end end sample "Zara", "6", "F" sample "Mac", "36", "M", "MCA"
true
898135e07b03eb2c90ac0894f8ad89b970a69723
Ruby
campbill01/stuff
/cipher.rb
UTF-8
5,683
3.609375
4
[]
no_license
class Deck_of_cards def initialize #define cards @cards=[] suits=['clubs','diamonds','hearts','spades'] suits.each do |suit| @cards.push("#{suit}.ace") (2..10).each do |num| @cards.push("#{suit}.#{num}") end @cards.push("#{suit}.jack") @cards.push("#{suit}.queen") @cards.push("#{suit}.king") end @cards.push("joker.A") @cards.push("joker.B") end # end initialize def shuffle # actually prepare the deck for encryption move_joker('joker.A') move_joker('joker.B') triple_cut count_cut end def count_cut size=get_value(@cards[53],'card') [email protected]!(53,53) [email protected]!(0,size) @cards=@cards + count_array + lower end def find_output shuffle #puts "finding output letter value" count=get_value(@cards[0],'card') letter_card=@cards[count] pre_number=get_value(letter_card,'card') if pre_number < 27 output=get_return(pre_number) else output=get_return(pre_number -26) end if output != nil return "#{output.upcase}" else find_output end end # def get_return(value,type="letter") alphabet=[nil,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] if type == 'letter' return alphabet[value] else #puts alphabet.index(value) return alphabet.index(value) end end def get_number(value) # end def get_value(card,type) #define values values={'clubs'=>0,'diamonds'=>13,'hearts'=>26,'spades'=>39,'ace'=>1,'jack'=>11,'queen'=>12,'king'=>13,'joker'=>53,'A'=>0,'B'=>0} facecards=['jack','queen','king','ace','joker'] if type=='card' # suit,number=card.split('.') if facecards.include? number value=values[number] else value=number.to_i end value +=values[suit] else # if card < 14 suit='clubs' number=card elsif card < 27 suit='diamonds' number=card -13 elsif card < 40 suit='hearts' number=card -26 else suit='spades' number=card -39 end if values.key(number) value="#{suit}.#{values.key(number)}" else value="#{suit}.#{number}" end end return value end def move_joker(jokerAB) [email protected](jokerAB) if jokerAB =='joker.A' new_position=old_position + 1 else new_position=old_position +2 end if new_position == 54 new_position=1 elsif new_position == 55 new_position=2 end @cards.delete_at(old_position) @cards[new_position, 0] = jokerAB end # def swap_two(one,two) @cards[one],@cards[two] = @cards[two],@cards[one] end # def triple_cut #puts "triple_cut" topjoker,bottomjoker = [@cards.index('joker.A'),@cards.index('joker.B')].sort [email protected]!((bottomjoker +1)..-1) [email protected]!(0, topjoker) @cards= upper + @cards +lower end # def pick_a_card puts @cards.sample(1) end def print_deck @cards.each do |card| puts card end end end #end class # # def sanitize(string) # take string and uppercase, remove non alpha characters, and split in to five character segments (padded with XX) string.gsub!(/[^a-z]/i,'') return string.upcase end # def generate_keystream(size) # take string, count characters and return keystring of same size keystream=[] size.times do keystream.push($hoyle.find_output().chomp) end keystream.delete(nil) return keystream end # def crypt_message(string,action) #take message and encrypt # sanitize, convert to numbers, get keystream, convert keystream to numbers, add keystream subtract if > 26, convert to letters(in 5 char blocks(!!-- maybe do not split, leave that just for output??)) sanitized=sanitize(string) letters=[] nospaces=[] numbers=[] numbersk=[] sanitized.each_char {|c| numbers.push($hoyle.get_return(c,'number') )} keystream=generate_keystream(sanitized.size) #puts sanitized, keystream keystream.each {|k| numbersk.push ($hoyle.get_return(k,'number') )} if action == 'encrypt' numbers.size.times do |num| #encrypt if numbers[num] + numbersk[num] > 26 value=(numbers[num] + numbersk[num] - 26) else value=(numbers[num] + numbersk[num]) end letters.push(value) end else numbers.size.times do |num| #decrypt if numbers[num] <= numbersk[num] value=((numbers[num] + 26) - numbersk[num] ) else value=(numbers[num] - numbersk[num]) end letters.push(value) end end letters.each {|l| nospaces.push($hoyle.get_return(l))} segments=(nospaces.size) / 5 partial=(nospaces.size) % 5 message=String.new segments.times do 5.times do message.concat(nospaces.shift) end message.concat(' ') end if partial > 0 pad= 5 - partial partial.times do message.concat(nospaces.shift) end pad.times do message.concat('X') end end return message end # # # $hoyle=Deck_of_cards.new #puts crypt_message('GLNCQ MJAFF FVOMB JIYCB', 'decrypt') #puts crypt_message('CODEI NRUBY LIVEL ONGER','encrypt') # take input from command line puts "Enter some text" text=gets.chomp puts "Do you want to encrypt or decrypt?" action=gets.chomp #puts action while !(action == 'encrypt') and !(action == 'decrypt') puts "Please choose either encrypt or decrypt" action=gets.chomp end puts crypt_message(text,action)
true
38a990ebb0c72470ef988b129d7debe8053b4467
Ruby
youpy/scissor
/lib/scissor/tape.rb
UTF-8
4,769
2.71875
3
[ "MIT" ]
permissive
require 'open-uri' require 'tempfile' module Scissor class Tape class Error < StandardError; end class EmptyFragment < Error; end attr_reader :fragments def initialize(filename = nil) @fragments = [] if filename filename = Pathname(filename).expand_path @fragments << Fragment.new( filename, 0, SoundFile.new_from_filename(filename).length) end end def self.new_from_url(url) file = nil content_types = { 'audio/wav' => 'wav', 'audio/x-wav' => 'wav', 'audio/wave' => 'wav', 'audio/x-pn-wav' => 'wav', 'audio/mpeg' => 'mp3', 'audio/x-mpeg' => 'mp3', 'audio/mp3' => 'mp3', 'audio/x-mp3' => 'mp3', 'audio/mpeg3' => 'mp3', 'audio/x-mpeg3' => 'mp3', 'audio/mpg' => 'mp3', 'audio/x-mpg' => 'mp3', 'audio/x-mpegaudio' => 'mp3', } open(url) do |f| ext = content_types[f.content_type.downcase] file = Tempfile.new(['audio', '.' + ext]) file.write(f.read) file.flush end tape = new(file.path) # reference tempfile to prevent GC tape.instance_variable_set('@__tempfile', file) tape end def add_fragment(fragment) @fragments << fragment end def add_fragments(fragments) fragments.each do |fragment| add_fragment(fragment) end end def duration @fragments.inject(0) do |memo, fragment| memo += fragment.duration end end def slice(start, length) if start + length > duration length = duration - start end new_instance = self.class.new remaining_start = start.to_f remaining_length = length.to_f @fragments.each do |fragment| new_fragment, remaining_start, remaining_length = fragment.create(remaining_start, remaining_length) if new_fragment new_instance.add_fragment(new_fragment) end if remaining_length == 0 break end end new_instance end alias [] slice def concat(other) add_fragments(other.fragments) self end alias << concat def +(other) new_instance = Scissor() new_instance.add_fragments(@fragments + other.fragments) new_instance end def loop(count) orig_fragments = @fragments.clone new_instance = Scissor() count.times do new_instance.add_fragments(orig_fragments) end new_instance end alias * loop def split(count) splitted_duration = duration / count.to_f results = [] count.times do |i| results << slice(i * splitted_duration, splitted_duration) end results end alias / split def fill(filled_duration) if duration.zero? raise EmptyFragment end loop_count = (filled_duration / duration).to_i remain = filled_duration % duration loop(loop_count) + slice(0, remain) end def replace(start, length, replaced) new_instance = self.class.new offset = start + length new_instance += slice(0, start) if new_instance.duration < start new_instance + Scissor.silence(start - new_instance.duration) end new_instance += replaced if duration > offset new_instance += slice(offset, duration - offset) end new_instance end def reverse new_instance = self.class.new @fragments.reverse.each do |fragment| new_instance.add_fragment(fragment.clone do |attributes| attributes[:reverse] = !fragment.reversed? end) end new_instance end def pitch(pitch, stretch = false) new_instance = self.class.new @fragments.each do |fragment| new_instance.add_fragment(fragment.clone do |attributes| attributes[:pitch] = fragment.pitch * (pitch.to_f / 100) attributes[:stretch] = stretch end) end new_instance end def stretch(factor) factor_for_pitch = 1 / (factor.to_f / 100) * 100 pitch(factor_for_pitch, true) end def pan(right_percent) new_instance = self.class.new @fragments.each do |fragment| new_instance.add_fragment(fragment.clone do |attributes| attributes[:pan] = right_percent end) end new_instance end def to_file(filename, options = {}) Scissor.mix([self], filename, options) end alias > to_file def >>(filename) to_file(filename, :overwrite => true) end def silence Scissor.silence(duration) end end end
true
9e99034cd5bb4de8e05afce1880144afca8698b3
Ruby
fbrute/lovy
/data/pm10/madininair_import.rb
UTF-8
727
3.046875
3
[]
no_license
#!/usr/bin/env ruby datetimes = [] pm10 = [] File.open("export_mesure_fixe.csv").each_with_index do |line,idx| values = line.split ";" #values = values.slice(1,values.length) # remove first element values.shift puts values.length datetimes = values if (idx == 1) pm10 = values if (idx == 2) end lines = [] datetimes.each_index do |idx| lines << datetimes[idx].gsub(/"/,'') + ";" + pm10[idx].to_s end File.open("madininair.csv","a") do |file| lines.each do |line| file.puts line end end #puts datetimes.slice(0,10) #puts pm10.length #puts lines.slice(0,10) puts datetimes.last puts pm10.last puts lines.first puts lines.first.length puts lines.last puts lines.last.length
true
1f8c8d8f9ffc142d1a0413233847539d8f327526
Ruby
tingleshao/rablo2d
/rablo2d.rb
UTF-8
21,676
2.78125
3
[]
no_license
# rablo2d.rb # This is the main program of the 2D objects in context protypeing system. # It contains a class Field that abstracts the canvas of the main window that displays the s-reps. # It contains a class InterpolationControl that abstracts a subwindow for user # to select which s-rep's spokes to interpolate. # The last part: Shoes.app runs the program. # # Author: Chong Shao ([email protected]) # ---------------------------------------------------------------- load 'lib/srep_toolbox.rb' load 'lib/color.rb' $points_file_path = "data/interpolated_points_" $radius_file_path = "data/interpolated_rs_" $logrk_file_path = 'data/interpolated_logrkm1s_' $dilate_ratio = 1.05 $a_big_number = 100 $end_disk_spoke_number = 20 class Field # this is the Field class that draws everything about s-rep on the main UI attr_accessor :sreps, :shifts def initialize(app, points, sreps, shifts) @app = app # set window size @width, @height= 800, 600 @sreps = sreps @shifts = shifts end def setSrep(srep, index) @sreps[index] = srep end def addSrep(srep) @sreps << srep end # methods for rendering points def render_point_big(x, y, color) @app.stroke color @app.strokewidth 2 @app.nofill @app.oval x-1,y-1, 2 end def render_point_small(x, y, color, bg_color) @app.stroke color @app.line x, y, x, y+1 @app.stroke bg_color @app.line x, y+1, x+1, y+1 end # methods for rendering disks def render_circle(cx, cy, d, color) @app.stroke color @app.nofill @app.oval cx, cy, d end # methods for rendering spokes def render_spokes(cx, cy, type, spoke_length, spoke_direction, color) @app.stroke color u_p1 = spoke_direction[0] u_m1 = spoke_direction[1] @app.stroke color spoke_end_x_up1 = cx + spoke_length[0] * u_p1[0] spoke_end_y_up1 = cy - spoke_length[0] * u_p1[1] @app.line(cx, cy, spoke_end_x_up1, spoke_end_y_up1) spoke_end_x_up2 = cx + spoke_length[1] * u_m1[0] spoke_end_y_up2 = cy - spoke_length[1] * u_m1[1] @app.line(cx, cy, spoke_end_x_up2, spoke_end_y_up2) if type == 'end' u_0 = spoke_direction[2] spoke_end_x_u0 = cx + spoke_length[2] * u_0[0] spoke_end_y_u0 = cy - spoke_length[2] * u_0[1] @app.line(cx, cy, spoke_end_x_u0, spoke_end_y_u0) end end # the method for rendering s-reps def render_srep(*args) srep = args[0] shiftx = args[1] shifty = args[2] scale = args[3] show_sphere = args[4] srep.atoms.each_with_index do |atom| render_atom(atom.x + shiftx, atom.y + shifty, atom.color) if show_sphere center_x = atom.x + shiftx - atom.spoke_length[0] center_y = atom.y + shifty - atom.spoke_length[0] d = atom.spoke_length[0] * 2 render_circle(center_x, center_y, d, srep.color) end if srep.show_extend_disk center_x = atom.x + shiftx - atom.expand_spoke_length[0] center_y = atom.y + shifty - atom.expand_spoke_length[0] d = atom.expand_spoke_length[0] * 2 render_circle(center_x, center_y, d, srep.color) end atom_x = atom.x+shiftx atom_y = atom.y+shifty render_spokes(atom_x, atom_y, atom.type, atom.spoke_length, atom.spoke_direction, srep.color) end if srep.interpolated_spokes_begin.length > 0 and srep.show_interpolated_spokes spoke_begin = srep.interpolated_spokes_begin spoke_end = srep.interpolated_spokes_end render_interp_spokes(shiftx, shifty, Color.white, spoke_begin, spoke_end) end if (srep.getExtendInterpolatedSpokesEnd()).length > 0 and srep.show_extend_spokes spoke_begin = srep.interpolated_spokes_end spoke_end = srep.getExtendInterpolatedSpokesEnd() render_extend_interp_spokes(shiftx, shifty, Color.red, spoke_begin, spoke_end) end if srep.show_curve # display the interpolated curve points render_curve($sreps, srep.index, srep, shiftx, shifty) end end def render_curve(sreps, index, srep, shiftx, shifty) file_name = $points_file_path + index.to_s if File::exists?(file_name) gamma_file = File.open(file_name, "r") else alert('file does not exist, interpolate it now') xt = srep.atoms.collect{|atom| atom.x} yt = srep.atoms.collect{|atom| atom.y} step_size = 0.01 interpolateSkeletalCurveGamma(xt,yt,step_size,srep.index) gamma_file = File.open(file_name, "r") end xs = gamma_file.gets.split(" ").collect{|x| x.to_f} ys = gamma_file.gets.split(" ").collect{|y| y.to_f} if (srep.interpolate_finished) xs.each_with_index do |x,i| spoke_ind = i*2 atom_type = srep.getExtendInterpolatedSpokesEnd()[spoke_ind][4] back_atom_type = srep.getExtendInterpolatedSpokesEnd()[spoke_ind+1][4] if atom_type != 'end' and back_atom_type != 'end' linkingIndex = srep.getExtendInterpolatedSpokesEnd()[spoke_ind][2] if linkingIndex == -1 color1 = srep.color else color1 = sreps[linkingIndex].color end linkingIndex = srep.getExtendInterpolatedSpokesEnd()[spoke_ind+1][2] if linkingIndex == -1 color2 = srep.color else color2 = sreps[linkingIndex].color end else color1 = srep.color color2 = srep.color end render_atom(x+shiftx,ys[i]+shifty, color1) render_atom(x+shiftx+3*srep.orientation[0], ys[i]+shifty+3*srep.orientation[1], color2) end else xs.each_with_index do |x,i| render_atom(x+shiftx,ys[i]+shifty, srep.color) render_atom(x+shiftx+3*srep.orientation[0], ys[i]+shifty+3*srep.orientation[1], srep.color) end end end # method for rendering interpolated spokes def render_interp_spokes(shiftx, shifty, color, ibegin, iend) @app.stroke color ibegin.each_with_index do |p, i| @app.line(p[0]+shiftx, p[1]+shifty, iend[i][0]+shiftx, iend[i][1]+shifty) end end # method for rendering extended part of spokes def render_extend_interp_spokes(shiftx, shifty, color, ibegin, iend) @app.stroke color iend.each_with_index do |p, i| @app.line(ibegin[i][0]+shiftx, ibegin[i][1]+shifty, p[0]+shiftx, p[1]+shifty) end end # method for rendering atoms def render_atom(x, y, color) render_point_big(x, y, color) end # method for rendering linking structure def render_linking_structure(shifts) shift = shifts[0] $linkingPts.each do |pt| if pt != [] render_atom(pt[0]+shift, pt[1]+shift, Color.black) end end end # this method calls the render_srep() and render_linking_structure() method def paint @app.nostroke checkSrepIntersection $sreps.each.with_index do |srep, i| render_srep(srep, @shifts[i] , @shifts[i] , 1.5, true) end if $show_linking_structure render_linking_structure(@shifts) end end # this method interates the sreps and let them check the spoke intersection def checkSrepIntersection (0..$sreps.length-1).each do |j| (0..$sreps.length-1).each do |i| if i != j $sreps[j].checkIntersection($sreps[i]) end end end end def [](*args) x, y = args raise "Cell #{x}:#{y} does not exist!" unless cell_exists?(x, y) @field[y][x] end def []=(*args) x, y, v = args cell_exists?(x, y) ? @field[y][x] = v : false end end # a class for the subwindow for choosing the srep to compute interpolation class InterpolateControl attr_accessor :app, :index, :msg def initialize(app) @app = app refresh end def paint() @app.clear @app.flow :margin => 3 do @app.button("Check") { if checkIndexEmpty() @msg.text = "empty index!" else file_name = $radius_file_path + @index.text @msg.text = "file exists: "+ File::exists?(file_name).to_s end } @app.button("Interpolate") { # interpolate radius index = @index.text srep = $sreps[index.to_i] xt = srep.atoms.collect{|atom| atom.x} yt = srep.atoms.collect{|atom| atom.y} rt = srep.atoms.collect{|atom| atom.spoke_length[0].to_s} step_size = 0.01 rs = interpolateRadius(xt,yt,rt,step_size,index) rr = rs.strip.split(' ').collect{|r| r.to_f} # interpolate kappa # read interpolated file step_size = 0.01 # rt and kt are the r's and k's on the base points # calculate kappa at base positions using the curvature formula f = File.new($points_file_path+ index, 'r') xs = f.gets.strip.split(' ') ys = f.gets.strip.split(' ') xt = [] xs.each do |x| xt << x.to_f end yt = [] ys.each do |y| yt << y.to_f end h = step_size f.close ff = File.new($radius_file_path+index, 'r') rs = ff.gets.strip.split(' ') indices= srep.base_index foo = computeBaseKappa(xt,yt, indices, h, rr) kappa = foo[0] rt = srep.atoms.collect{|atom| atom.spoke_length[0]} interpolateKappa(rt, kappa, step_size, index) } end @app.stack :margin => 3 do @app.para "enter the index of the srep" @index = @app.edit_line :width => 50 @msg = @app.para "" end @app.nofill end def refresh paint end def checkIndexEmpty() return @index.text.strip() == "" end end # this is the driver for the main program Shoes.app :width => 1000, :height => 800, :title => '2d multi object' do def render_field clear do background rgb(50, 50, 90, 0.7) flow :margin => 6 do # code for buttons button("Dilate") { $sreps.each do |srep| srep.atoms.each do |atom| atom.dilate($dilate_ratio) end # dilate interpolated spokes # and check intersection # user can specify first serval count to speed up dilate if $dilateCount > 6 sublinkingPts = srep.extendInterpolatedSpokes($dilate_ratio, $sreps, true) sublinkingPts.each do |p| $linkingPts << p end else srep.extendInterpolatedSpokes($dilate_ratio, $sreps, false) end end $linkingPts = $linkingPts.uniq $dilateCount = $dilateCount + 1 refresh @points, $sreps, @shifts } button("Reset") { @dontGrowLst= [] initialConfig } button("Check r-k File") { window :title => "draw srep", :width => 402, :height => 375 do dp = InterpolateControl.new(self) end } button("Interpolate All Spokes") { $sreps.each_with_index do |srep, srep_index| $a_big_number.times do # interpolate one side indices = srep.base_index base_index = $current_base_index distance_to_next_base = ( indices[base_index+1] - indices[base_index] ) - $step_go_so_far if distance_to_next_base == 0 # <= reached another base point $step_go_so_far = 0 $current_base_index = $current_base_index +1 distance_to_next_base = ( indices[base_index+1] - indices[base_index] ) - $step_go_so_far spoke_index = $current_base_index end curr_index = indices[base_index] + $step_go_so_far + 1 d1t = 0.01 * $step_go_so_far d2t = distance_to_next_base * 0.01 # calculate parameters # read all points, rs, logrkm1s from the file file = File.open($points_file_path + srep_index.to_s, 'r') xt = file.gets.split(' ').collect{|x| x.to_f} yt = file.gets.split(' ').collect{|y| y.to_f} file = File.open($radius_file_path + srep_index.to_s, 'r') rt = file.gets.split(' ').collect{|r| r.to_f} file = File.open($logrk_file_path + srep_index.to_s, 'r') logrkm1 = file.gets.split(' ').collect{|logrkm1| logrkm1.to_f} if curr_index < xt.length-1 v1t = [xt[curr_index] - xt[indices[base_index]], yt[curr_index] - yt[indices[base_index]]] if curr_index == indices[base_index+1] v2t = [xt[indices[base_index+1]+1] - xt[curr_index], yt[indices[base_index+1]+1] - yt[curr_index]] else v2t = [xt[indices[base_index+1]] - xt[curr_index], yt[indices[base_index+1]] - yt[curr_index]] end puts "v1t: " + v1t.to_s size_v1t = v1t[0]**2 + v1t[1]**2 norm_v1t = v1t.collect{|v| v / size_v1t} size_v2t = v2t[0]**2 + v2t[1]**2 puts "size_v2t: " + size_v2t.to_s norm_v2t = v2t.collect{|v| v / size_v2t} k1t = ( 1 + ( -1 * Math.exp(logrkm1[indices[base_index]] ) ) ) / rt[indices[base_index]] k2t = ( 1 + ( -1 * Math.exp(logrkm1[indices[base_index+1]] ) ) ) / rt[indices[base_index+1]] u1t = srep.atoms[base_index].spoke_direction[0] u2t = srep.atoms[base_index+1].spoke_direction[0] ui = interpolateSpokeAtPos(u1t, norm_v1t, k1t, d1t, u2t, norm_v2t, k2t, d2t) puts "ui: " + ui.to_s srep.interpolated_spokes_begin << [xt[curr_index],yt[curr_index],-1] puts "rt: " + rt[curr_index-1].to_s srep.interpolated_spokes_end << [xt[curr_index]+ui[0]*rt[curr_index],yt[curr_index]-ui[1]*rt[curr_index],-1,[],'regular'] # interpolate another side u1t = $sreps[srep_index].atoms[base_index].spoke_direction[1] u2t = $sreps[srep_index].atoms[base_index+1].spoke_direction[1] ui = interpolateSpokeAtPos(u1t, norm_v1t, k1t, d1t, u2t, norm_v2t, k2t, d2t) puts "ui: " + ui.to_s spoke_index = indices[base_index]+$step_go_so_far+1 spoke_begin_x = xt[spoke_index] spoke_begin_y = yt[spoke_index ] $sreps[srep_index].interpolated_spokes_begin << [spoke_begin_x,spoke_begin_y,-1,[],'regular'] puts "rt: " + rt[indices[base_index]+$step_go_so_far].to_s spoke_end_x = spoke_begin_x + ui[0]*rt[spoke_index] spoke_end_y = spoke_begin_y - ui[1]*rt[spoke_index] $sreps[srep_index].interpolated_spokes_end << [spoke_end_x,spoke_end_y,-1,[],'regular'] else # add spoke interpolation for end disks # get atom for end disks end_atom_one = srep.atoms[0] end_atom_two = srep.atoms[-1] end_atoms = [end_atom_one, end_atom_two] # get upper and lower and middle spokes end_atoms.each_with_index do |atom, i| atom_spoke_dir_plus1 = atom.spoke_direction[0] atom_spoke_dir_minus1 = atom.spoke_direction[1] atom_spoke_dir_zero = atom.spoke_direction[2] x_diff_1 = atom_spoke_dir_zero[0] - atom_spoke_dir_plus1[0] x_diff_2 = atom_spoke_dir_zero[0] - atom_spoke_dir_minus1[0] y_diff_1 = atom_spoke_dir_zero[1] - atom_spoke_dir_plus1[1] y_diff_2 = atom_spoke_dir_zero[1] - atom_spoke_dir_minus1[1] x_step_size_1 = x_diff_1.to_f / 15 y_step_size_1 = y_diff_1.to_f / 15 x_step_size_2 = x_diff_2.to_f / 15 y_step_size_2 = y_diff_2.to_f / 15 previous_x = atom_spoke_dir_plus1[0] previous_y = atom_spoke_dir_plus1[1] $end_disk_spoke_number.times do new_spoke_dir_x = previous_x + x_step_size_1 new_spoke_dir_y = previous_y + y_step_size_1 # normalize length_new_spoke = Math.sqrt(new_spoke_dir_x**2 + new_spoke_dir_y**2) new_spoke_dir_x = new_spoke_dir_x / length_new_spoke new_spoke_dir_y = new_spoke_dir_y / length_new_spoke previous_x = new_spoke_dir_x previous_y = new_spoke_dir_y # calculate interpolated spoke end new_spoke_vector_x = atom.spoke_length[0]*new_spoke_dir_x new_spoke_vector_y = atom.spoke_length[0]*new_spoke_dir_y new_spoke_end = [atom.x + new_spoke_vector_x, atom.y - new_spoke_vector_y,-1,[],'end'] $sreps[srep_index].interpolated_spokes_begin << [atom.x, atom.y] $sreps[srep_index].interpolated_spokes_end << new_spoke_end end previous_x = atom_spoke_dir_minus1[0] previous_y = atom_spoke_dir_minus1[1] $end_disk_spoke_number.times do new_spoke_dir_x = previous_x + x_step_size_2 new_spoke_dir_y = previous_y + y_step_size_2 # normalize length_new_spoke = Math.sqrt(new_spoke_dir_x**2 + new_spoke_dir_y**2) new_spoke_dir_x = new_spoke_dir_x / length_new_spoke new_spoke_dir_y = new_spoke_dir_y / length_new_spoke previous_x = new_spoke_dir_x previous_y = new_spoke_dir_y # calculate interpolated spoke end new_spoke_vector_x = atom.spoke_length[0]*new_spoke_dir_x new_spoke_vector_y = atom.spoke_length[0]*new_spoke_dir_y new_spoke_end = [atom.x + new_spoke_vector_x, atom.y - new_spoke_vector_y,-1,[],'end'] $sreps[srep_index].interpolated_spokes_begin << [atom.x, atom.y] $sreps[srep_index].interpolated_spokes_end << new_spoke_end $sreps[srep_index].interpolate_finished = true end end $info = "interpolation finished" end $step_go_so_far = $step_go_so_far + 1 puts "count: "+ $step_go_so_far.to_s refresh @points, $sreps, @shifts end $step_go_so_far = 1 $current_base_index = 0 end } end # code for the check list @list = ['Medial Curve', 'Interpolated Spokes', 'Extended Spokes', 'Extended Disks', 'Linking Structure'] stack do @list.map! do |name| flow { @c = check; para name } [@c, name] end if $sreps[0].show_curve @list[0][0].checked = true end if $sreps[0].show_interpolated_spokes @list[1][0].checked = true end if $sreps[0].show_extend_spokes @list[2][0].checked = true end if $sreps[0].show_extend_disk @list[3][0].checked = true end if $show_linking_structure @list[4][0].checked = true end button "Refresh" do $sreps.each do |srep| srep.show_curve = @list[0][0].checked? srep.show_interpolated_spokes = @list[1][0].checked? srep.show_extend_spokes = @list[2][0].checked? srep.show_extend_disk = @list[3][0].checked? end $show_linking_structure = @list[4][0].checked? if @list[4][0].checked? $sreps.each do |srep| srep.extend_interpolated_spokes_end.each_with_index do |spoke_end, i| if spoke_end[2] != -1 $linkingPts << [spoke_end[0], spoke_end[1]] end end end end refresh @points, $sreps, @shifts if @list[4][0].checked? # linkLinkingStructurePoints($sreps, self, 300) end end end stack do @status = para :stroke => black end @field.paint para $info end end # refresh the UI def refresh points, sreps, shifts self.nofill @field = Field.new self, points, sreps, shifts render_field end # initialization def initialConfig $step_go_so_far = 0 @shifts = [300,300,300] $current_base_index = 0 $info = "" $dilateCount = 0 $linkingPts = [] $show_linking_structure = false points0 = [[110,100],[160,75],[210,50],[260,60],[310,80]] l0 = [[35,35,35],[40,40],[50,50],[40,40],[35,35,35]] u0 = [[[-1,3],[-0.1,-4],[-9,1]],[[-1,4],[1.1,-3]],[[-1,4],[0.2,-6]],[[1,9],[0.05,-8]],[[1,2],[1,-5],[6,1]]] srep0 = generate2DDiscreteSrep(points0,l0,u0,0.01,0) srep0.orientation = [0,1] $sreps = [srep0] points1 = [[200,190],[250,190],[300,200],[350,180],[400,160]] l1 = [[35,35,35],[40,40],[45,45],[40,40],[35,35,35]] u1 = [[[-1,6],[0.5,-3],[-9,1]],[[-1,4],[-1,-3]],[[-1,4],[-0.1,-6]],[[1,9],[1,-1.5]],[[1,2],[2,-5],[6,1]]] srep1 = generate2DDiscreteSrep(points1,l1,u1,0.01,1) srep1.color = Color.green srep1.orientation = [0,1] $sreps << srep1 points2 = [[30,50],[10,100],[9,150],[20,200],[50,240],[110,290]] l2 = [[35,35,35],[35,35],[40,40],[35,35],[40,40],[40,40,40]] u2 = [[[6,1],[6,-0.5],[-9,1]],[[-1,4],[3,-0.5]],[[-1,4],[5,-0.5]],[[1,9],[5,1]],[[1,9],[5,3]],[[1,2],[3,5],[6,1]]] srep2 = generate2DDiscreteSrep(points2,l2,u2,0.01,2) srep2.color = Color.purple srep2.orientation = [1,0] $sreps << srep2 refresh @points, $sreps, @shifts end initialConfig end
true
e102491e73c5fcf3f3dde6b2687ff094b95f53b6
Ruby
Epigene/2021_codingame_spring
/codingame.rb
UTF-8
5,361
3.015625
3
[ "MIT" ]
permissive
class Decider attr_reader :world, :timeline LAST_DAY = 5 # for wood1, will change def initialize(world:) @world = world @timeline = [] end # Takes in all data known at daybreak. # Updates internal state and returns all moves we can reasonably make today. # # GROW cellIdx | SEED sourceIdx targetIdx | COMPLETE cellIdx | WAIT <message> # Growing: # - size1 -> 2: costs 3 + size 2 trees already owned. # - size2 -> 3: costs 7 + size 3 trees already owned. # - size3 -> harvest: 4 points # # @return [Array<String>] def move(params) # day:, # nutrients:, # sun:, # score:, # opp_sun:, # opp_score:, # opp_waiting:, # trees:, # actions: params.each_pair do |k, v| debug("#{ k }: #{ v },") end timeline << params if begin_harvest? actions. select { |action| action.start_with?("COMPLETE") }. min_by { |action| action.split(" ").last.to_i } || "WAIT hump, nothing to harvest" elsif grow? grow = nil if can_afford?(:two_to3) && my_harvestable_trees.size < 2 inter = my_size2_trees.keys.sort.map { |i| "GROW #{ i }" }.to_set & actions grow = inter.sort_by { |a| a.split(" ").last.to_i }.first end if can_afford?(:one_to2) && my_size2_trees.size < 2 inter = my_size1_trees.keys.sort.map { |i| "GROW #{ i }" }.to_set & actions grow = inter.sort_by { |a| a.split(" ").last.to_i }.first end grow || "WAIT" else "WAIT" end end def current_move timeline.last end private def begin_harvest? current_move[:day] >= LAST_DAY || my_harvestable_trees.size >= 2 && sun >= 8 end def grow? my_harvestable_trees.size < 2 # && my_size2_trees.size < 2 end def can_afford?(mode) # :harvest case mode when :harvest sun >= 4 when :two_to3 sun >= (7 + my_harvestable_trees.size) when :one_to2 sun >= (3 + my_size2_trees.size) else raise("mode '#{ mode }' not supported") end end def sun current_move[:sun] end # @return [Hash] {1 => {:size=>1, :mine=>true, :dormant=>false}} def my_trees current_move[:trees].select { |i, t| t[:mine] }.to_h end # @return [Hash] {1 => {:size=>1, :mine=>true, :dormant=>false}} def my_harvestable_trees my_trees.select { |i, t| t[:size] >= 3 }.to_h end def my_size2_trees my_trees.select { |i, t| t[:size] == 2 }.to_h end def my_size1_trees my_trees.select { |i, t| t[:size] == 1 }.to_h end def my_seeds my_trees.select { |i, t| t[:size] == 0 }.to_h end def actions current_move[:actions] end end require "set" require "benchmark" STDOUT.sync = true # DO NOT REMOVE def debug(message) STDERR.puts(message) end number_of_cells = gets.to_i # 37 world = {} number_of_cells.times do # index: 0 is the center cell, the next cells spiral outwards # richness: 0 if the cell is unusable, 1-3 for usable cells # neigh_0: the index of the neighbouring cell for each direction line = gets # debug(line) index, richness, neigh_0, neigh_1, neigh_2, neigh_3, neigh_4, neigh_5 = line.split(" ").map(&:to_i) world[index] = { r: richness # TODO, handle neighbours binding.pry } end decider = Decider.new(world: world) timeline = {} loop do day = gets.to_i # the game lasts 24 days: 0-23 nutrients = gets.to_i # the base score you gain from the next COMPLETE action # sun: your sun points # score: your current score sun, score = gets.split(" ").map(&:to_i) # opp_sun: opponent's sun points # opp_score: opponent's score # opp_is_waiting: whether your opponent is asleep until the next day opp_sun, opp_score, opp_waiting = gets.split(" ") opp_sun = opp_sun.to_i opp_score = opp_score.to_i opp_waiting = opp_waiting.to_i == 1 number_of_trees = gets.to_i # the current amount of trees trees = {} number_of_trees.times do # cell_index: location of this tree # size: size of this tree: 0-3 # is_mine: 1 if this is your tree # is_dormant: 1 if this tree is dormant cell_index, size, is_mine, is_dormant = gets.split(" ") cell_index = cell_index.to_i size = size.to_i is_mine = is_mine.to_i == 1 is_dormant = is_dormant.to_i == 1 trees[cell_index] = {size: size, mine: is_mine, dormant: is_dormant} end number_of_possible_actions = gets.to_i # all legal actions actions = Set.new number_of_possible_actions.times do actions << gets.chomp # try printing something from here to start with end # debug("day: #{ day }") # debug("nutrients: #{ nutrients }") # debug("my sun and score: #{ [sun, score] }") # debug("opp sun, score and waiting: #{ [opp_sun, opp_score, opp_waiting] }") # debug("trees: #{ number_of_trees }") # trees.each_pair do |index, data| # debug("tree##{ index }: #{ data }") # end # debug("actions: #{ number_of_possible_actions }") # actions.each do |action| # debug(action) # end params = { day: day, # the game lasts 24 days: 0-23 nutrients: nutrients, sun: sun, score: score, opp_sun: opp_sun, opp_score: opp_score, opp_waiting: opp_waiting, trees: trees, actions: actions } puts decider.move(params) end
true
2e527910a4e34a3272ad2f717e92f7a2596f56a8
Ruby
kirangan/class_kolla
/hari_2/exercise.rb
UTF-8
122
3.46875
3
[]
no_license
def create_sentence(words) str = " " for word in words str += word end end puts create_sentence(["hello, world"])
true
5cbdc5e69b857bfa50e9607253ea1c8006046bcb
Ruby
tayjames/rales_engine
/lib/tasks/import.rake
UTF-8
682
2.640625
3
[]
no_license
require 'csv' namespace :import do desc "imports all data from csv" task seeds: :environment do data = { "Merchant" => ["db/csv/merchants.csv", Merchant], "Customer" => ["db/csv/customers.csv", Customer], "Items" => ["db/csv/items.csv", Item], "Invoice" => ["db/csv/invoices.csv", Invoice], "Transactions" => ["db/csv/transactions.csv", Transaction], "InvoiceItem" => ["db/csv/invoice_items.csv", InvoiceItem]} data.each do |key, array| CSV.foreach(array[0], headers: true) do |row| array[1].create(row.to_h) end puts "There are #{array[1].count} #{key} in the database" end end end
true
3524d567df61dd9b35d5c54d033772a20e973d07
Ruby
christianlarwood/ruby_small_problems
/1.fundamentals_exercises/easy_5/after_midnight_1.rb
UTF-8
1,509
4.3125
4
[]
no_license
=begin Write a method that takes a time using this minute-based format and returns the time of day in 24 hour format (hh:mm). Your method should work with any integer input. You may not use ruby's Date and Time classes. 23:30 What's the expected input(s): - an integer What's the expected output(s): - hh:mm representing the integer What are the rules (explicit & implicit requirements)?: - cannot use Date and Time classes - - Clarifying Questions: - - Describe your mental model (interpretation) of the problem: - Write a method that takes an integer representing time in minues and returns the time of day in hh:mm format Data Structure: Which data structures will work with each step of your mental model? - minutes var - hours var Algorithm: What are the exact steps that will transform the input(s) to the desired output(s)? Use your mental model and data structure. - define a method with one parameter - minutes in a day = 1440 - find the hours - number / 60 - find the minutes - number % 60 - return the time of day in hh:mm format =end # Code: def time_of_day(number) hour, minutes = number.divmod(60) hour = format('%02g', hour % 24) minutes = format('%02g', minutes % 60) "#{hour}:#{minutes}" end # Test Cases: puts time_of_day(0) == "00:00" puts time_of_day(-3) == "23:57" puts time_of_day(35) == "00:35" puts time_of_day(-1437) == "00:03" puts time_of_day(3000) == "02:00" puts time_of_day(800) == "13:20" puts time_of_day(-4231) == "01:29"
true
0e65979c5df4ecf008c9e54251836397fbb3422e
Ruby
ivaanrl/FinalRubyProject
/pawn.rb
UTF-8
1,999
3.96875
4
[]
no_license
require_relative 'piece' class Pawn < Piece attr_accessor :piece def initialize(color) color == 'white' ? @piece = "\u2659 " : @piece = "\u265F " @position = [] end def self.move(initial_square, target_square, taken, turn) if turn == 'white' if taken[0] if turn != taken[1] if initial_square[0] + 1 == target_square[0] && initial_square[1] + 1 == target_square[1] return true else puts "There's another piece there. Pawns can only eat in diagonal." end else puts "There's another #{turn} piece there. Choose another move" end else if (initial_square[0] == 2 && turn == 'white') if initial_square[0] + 1 == target_square[0] || initial_square[0] + 2 == target_square[0] @position = target_square return true end elsif initial_square[0] + 1 == target_square[0] @position = target_square return true else puts "That's not a valid Pawn move. Choose your coordinates again." end end else if taken[0] if turn != taken[1] if initial_square[0] - 1 == target_square[0] && initial_square[1] - 1 == target_square[1] return true else puts "There's another piece there. Pawns can only eat in diagonal." end else puts "There's another #{turn} piece there. Choose another move" end else if (initial_square[0] == 7 && turn == 'black') if initial_square[0] - 1 == target_square[0] || initial_square[0] - 2 == target_square[0] @position = target_square return true end elsif initial_square[0] - 1 == target_square[0] @position = target_square return true else puts "That's not a valid Pawn move. Choose your coordinates again." end end end end end
true
07d1fd7cd0576153aa55c88cecaeadff1e250d99
Ruby
Buraisx/Ruby-OOP-exercises
/player/player.rb
UTF-8
710
3.546875
4
[]
no_license
class Player def initialize @gold_coins = 0 @health_points = 10 @lives = 5 end def display_stats return "Gold: #{@gold_coins}/ Health: #{@health_points}/ Lives: #{@lives}" end def level_up @lives = @lives +1 end def collect_treasure @gold_coins = @gold_coins +1 if @gold_coins % 10 == 0 level_up end end def do_battle(damage) # take damage @health_points = @health_points - damage # if healthpoints are less than 1, lose a life and reset health if @health_points < 1 @lives = @lives - 1 # if no more lives, restart game if @lives < 1 restart end @health_points = 10 end end def restart @gold_coins = 0 @health_points = 10 @lives = 5 end end
true
1d39c1deb0daa95167637c1ad09c2a1d7848f616
Ruby
Andyreyesgo/reposting
/aumento_precios.rb
UTF-8
761
3.609375
4
[]
no_license
def augment () puts "Escribe el nombre del documento con su extensión (.txt)" STDOUT.flush d=gets.chomp data1 = open(d).read.chomp.split(',') array=[] puts "el documento contiene el siguiente arreglo" print data1 data1.each do |x| array.push x.to_i end new_prices=[] print "\n" puts "Ingresa el factor de multiplicación de tus datos " n=gets.chomp.to_i array.each do |i| new_prices.push(i*n) end puts "Los valores aumentados son" print new_prices puts "\n" print "ingrese el nombre de documento" puts "\n" name=gets File.write("#{name}.txt",new_prices) end augment()
true
3e22eb5ddf96aa1a682e134bba49c519b7802e5e
Ruby
Felipeandres11/desafioruby1
/DESAFIO1/escape.rb
UTF-8
70
2.5625
3
[]
no_license
g=ARGV r=ARGV ve = Math.sqrt(2*ARGV[0].to_f*ARGV[1].to_f); puts ve
true
00c9664fad2a8f106531503d8d875756cc95025f
Ruby
Sidarth20/ted_lasso_2103
/lib/team.rb
UTF-8
893
3.40625
3
[]
no_license
require 'pry' class Team attr_reader :name, :coach, :players def initialize(name, coach, players) @name = name @coach = coach @players = players end def total_salary sum = 0 # binding.pry players.each do |player| sum = @players[0].salary + @players[1].salary end sum end # this method passes the test but doesn't account for highest salary # def captain # @players.find_all do |player| # # binding.pry # if player.name == "Roy Kent" # return player.name # end # end # end def captain salaries = [] @players.each do |player| salaries << player.salary end salaries.max @players.find do |player| if salaries.max == player.salary return player.name end end end def positions_filled @players.map do |player| player.position end end end
true
23cb1a6037d55319cef8c3f590f1bc2a2e279e4c
Ruby
plonk/100knock
/q30.rb
UTF-8
2,833
3.8125
4
[]
no_license
=begin 30. 形態素解析結果の読み込み 形態素解析結果(neko.txt.mecab)を読み込むプログラムを実装せよ.ただし, 各形態素は表層形(surface),基本形(base),品詞(pos),品詞細分類 1(pos1)をキーとするマッピング型に格納し,1文を形態素(マッピング型) のリストとして表現せよ.第4章の残りの問題では,ここで作ったプログラムを 活用せよ. =end module Enumerable def split(pattern) Enumerator.new do |yielder| chunk = [] self.each do |elt| if pattern === elt yielder << chunk chunk = [] else chunk << elt end end yielder << chunk unless chunk.empty? end.tap do |enumerator| enumerator.each do |chunk| yield(chunk) end if block_given? end end end module Enumerable def intersperse(pad) flat_map { |elt| [pad,elt] } . drop(1) end def proc_map(&block) if block map { |elt| -> { block.call(elt) } } else Enumerator.new do |yielder| each do |elt| yielder << -> { block.call(elt) } end end end end end class Proc def +(other) -> { self.(); other.() } end end class Symbol def call(*args, &block) -> obj { obj.send(self, *args, &block) } end end # 表層形\t品詞,品詞細分類1,品詞細分類2,品詞細分類3,活用形,活用型,原形,読み,発音 # String^10 -> Morpheme(={:surface,:pos,:pos1,:base}) def morpheme(surface, pos, pos1, _品詞細分類2, _品詞細分類3, _活用形, _活用型, base, _読み, _発音) { surface: surface, pos: pos, pos1: pos1, base: base } end # String -> Morpheme def parse_morpheme(line) surface, params = line.split("\t") morpheme(surface, *params.chomp.split(',')) end # [String, ...] -> Sentence (=[Morpheme, ...]) def parse_sentence(lines) lines.map do |line| parse_morpheme(line) end end # String -> [Sentence, ...] def parse_text(str) str.each_line.split("EOS\n").map do |lines| parse_sentence(lines) end end # () -> [Sentence, ...] def analyzed_text File.open 'neko.txt.mecab' do |f| parse_text(f.read) end end def to_type(occur) ret = occur.dup ret.delete(:surface) ret end # [Sentence, ...] -> () def dump_text(text) print '[' text.proc_map { |s| print '[' s.proc_map { |morph| print morph.inspect } .intersperse(-> { print "\n " }) .each(&:call) print ']' }.intersperse(-> { print ",\n " }).each(&:call) puts ']' end def morphemes(text) text.flatten(1) end def main dump_text(analyzed_text) end if __FILE__ == $0 main end
true
cfc2dd3613ad4d5229574912493c3a4952c02c33
Ruby
KazukiHozumi/yukicoder
/725.rb
UTF-8
43
2.75
3
[]
no_license
s = gets puts s.gsub(/treeone/, "forest")
true
1ba80a01ab7775140d98694e06d286dbe2ecdc93
Ruby
orest-kostiuk/OnApp-Search
/start.rb
UTF-8
179
3.0625
3
[]
no_license
require './simple_json_search' loop do puts('Input your search') query = gets.chomp break if query == 'exit' puts('result:') puts(SimpleJsonSearch.new(query).call) puts end
true
4284979b9615245d19fefa58d20d2dd8533464b8
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/cs169/combine_anagrams_latest/6672.rb
UTF-8
354
3.703125
4
[]
no_license
def combine_anagrams(words) anagrams = Hash.new() words.each do |word| if anagrams.has_key?(word.downcase.chars.sort.join) anagrams[word.downcase.chars.sort.join].push(word) else anagrams[word.downcase.chars.sort.join] = [word] end end return anagrams.values() end print combine_anagrams(["hello", "HeLLo"])
true
a1b14c78cbbcbab9922abd0a866f681b25389f99
Ruby
dlyn1110/happy_hour
/lib/happy_hour/cli.rb
UTF-8
1,340
3.4375
3
[ "MIT" ]
permissive
class HappyHour::CLI def call puts "*************************************" puts "" puts "Welcome! Let's get your Happy on!!!" puts "-------------------------------------" puts "-------------------------------------" HappyHour::Bar.scrape_bars bar_list more_info goodbye end def bar_list HappyHour::Bar.all.each.with_index(1) do |bar, i| puts "#{i}. #{bar.name}" #binding.pry end end def more_info input = nil while input != 'exit' puts "" puts "Enter number for details of bar of choice:" puts "" input = gets.strip.downcase if input.to_i > 0 && input.to_i <= HappyHour::Bar.all.length bar = HappyHour::Bar.all[input.to_i - 1] puts "" puts "#{bar.name}" puts "************************" puts "#{bar.description}" puts "************************" puts "" puts "For main list of bars, type 'list'. To leave, type 'exit'." elsif input == 'list' bar_list elsif input == 'exit' else puts "" puts "Oops! Think you pressed the wrong number." #binding.pry end end end def goodbye puts "" puts "Thanks for visiting! Come back soon!!!" puts "" end end
true
d4d1de11525d9ed25fc896a58e3504355154dfa1
Ruby
Seva-Sh/RB101
/codewars/ex46.rb
UTF-8
490
4
4
[]
no_license
=begin Problem: - - - - - Input: int Output: int Algorithm: - Break the given integer into an array of numbers - Reassign the integer to the sum of all the numbers in the array if the result integer has only one digit -> return it if not, repeat the process - =end def digital_root(int) loop do return int if int.to_s.size == 1 int = int.digits.sum end end p digital_root(16) == 7 p digital_root(942) == 6 p digital_root(132189) == 6 p digital_root(493193) == 2
true
af767aecb4452b1c4730b314664911aa118048d9
Ruby
CarolinaAntolin/Range_fundamentals
/desafio_range.rb
UTF-8
367
3.78125
4
[]
no_license
x=Array (1..7) print x puts "Class Name: #{x.class}" num_a=x[0] puts num_a if x.include? num_a puts "incluye el" + num_a.to_s else puts "El numero no esta en la cadena" end puts "El ultimo numero de la cadena es :" + x.last.to_s puts "El minimo valor de la cadena es :" + x.min.to_s puts "El maximo valor de la cadena es :" + x.max.to_s
true
39c2396e4a1bc2cea609db528232da11b78109b0
Ruby
Aquaj/rosetta
/spec/rosetta/serializers/csv_serializer_spec.rb
UTF-8
1,221
2.578125
3
[ "MIT" ]
permissive
require 'rosetta/element' require 'rosetta/serializers/csv' RSpec.describe Rosetta::Serializers::CSV do it 'takes in Elements and returns csv' do elements = [ Rosetta::Element.new('a' => 1), Rosetta::Element.new('a' => 2) ] serialized = Rosetta::Serializers::CSV.serialize(elements) expect(serialized).to eq <<~CSV a 1 2 CSV end it 'serializes nested structures as a flat structure with point-separated keys' do elements = [ Rosetta::Element.new('a' => { 'b' => 'c' }), ] serialized = Rosetta::Serializers::CSV.serialize(elements) expect(serialized).to eq <<~CSV a.b c CSV end it 'serializes array values as comma-separated values in a string' do elements = [ Rosetta::Element.new('a' => [:a, :b]), ] serialized = Rosetta::Serializers::CSV.serialize(elements) expect(serialized).to eq <<~CSV a "a,b" CSV end it 'does not serialize Element with different structures' do elements = [ Rosetta::Element.new('a' => 1), Rosetta::Element.new('b' => 2) ] expect { Rosetta::Serializers::CSV.serialize(elements) }.to( raise_error(Rosetta::ConversionError)) end end
true
49129ca14ee14f0182272bf7d06138a109bbbd1c
Ruby
Hollywilkerson/learning_by_doing
/arrays/array_practice.rb
UTF-8
1,111
4
4
[]
no_license
#!/usr/bin/env ruby starting_array = (1..10).to_a puts "#{starting_array.join('...')}..." puts "T-#{starting_array.reverse.join(', ')}... BLASTOFF!" puts "The last element is #{starting_array.last}" puts "The first element is #{starting_array.first}" puts "The third element is #{starting_array[2]}" puts "The element with an index of 3 is #{starting_array[3]}" puts "The second from last element is #{starting_array[-2]}" puts "The first four elements are '#{starting_array.first(4).join(', ')}'" starting_array.delete_if { |digit| [5, 6, 7].include?(digit) } print 'If we delete 5, 6 and 7 from the array,' puts " we're left with [#{starting_array.join(',')}]" starting_array.unshift(5) print 'If we add 5 at the beginning of the array,' puts " we're left with [#{starting_array.join(',')}] " starting_array.push(6) print 'If we add 6 at the end of the array,' puts " we're left with [#{starting_array.join(',')}]" puts "Only the elements #{starting_array.select { |digit| digit > 8 }} are > 8." print 'If we remove all the elements,' puts " then the length of the array is #{starting_array.clear.length}"
true
76b9b405257db786e46fe868881474506c161666
Ruby
tomdionysus/json2ruby
/lib/json2ruby/cli.rb
UTF-8
6,006
2.9375
3
[ "MIT" ]
permissive
require 'digest/md5' require 'json' require 'optparse' module JSON2Ruby # The CLI (Command Line Interface) functionality class for the json2ruby executable class CLI # Run the json2ruby command, using arguments in ARGV. def self.run puts "json2ruby v#{VERSION}\n" # Do the cmdline options options = get_cli_options # Ensure Output Directory options[:outputdir] = File.expand_path(options[:outputdir], File.dirname(__FILE__)) ensure_output_dir(options) # Parse Files rootclasses = parse_files(options) # Write out Ruby (see what I'm doing here?) writer = JSON2Ruby::RubyWriter # Write Output write_files(rootclasses, writer, options) end # Create the output directory with the options[:outputdir] if it does not exist. def self.ensure_output_dir(options) puts "Output Directory: #{options[:outputdir]}" if options[:verbose] unless Dir.exists?(options[:outputdir]) puts "Creating Output Directory..." if options[:verbose] Dir.mkdir(options[:outputdir]) end end # Process ARGV for command line switches and return the options hash. def self.get_cli_options options = {} OptionParser.new do |opts| opts.banner = "Usage: #{$0} [options] <file.json> [<file.json>....]" opts.on("-o", "--outputdir OUTPUTDIR", "Output directory") do |v| options[:outputdir] = v end opts.on("-n", "--namespace MODULENAME", "Module namespace path") do |v| options[:namespace] = v end opts.on("-s", "--superclass SUPERCLASS", "Class ancestor") do |v| options[:superclass_name] = v end opts.on("-r", "--require REQUIRE", "Require module in file") do |v| options[:require] ||= [] options[:require] << v end opts.on("-i", "--include INCLUDE", "Include Class/Module in file") do |v| options[:include] ||= [] options[:include] << v end opts.on("-e", "--extend EXTEND", "Extend from Class/Module in file") do |v| options[:extend] ||= [] options[:extend] << v end opts.on("-M", "--modules", "Create Modules, not classes") do |v| options[:modules] = true end opts.on("-a", "--attributemethod METHODNAME", "Use attribute method instead of attr_accessor") do |v| options[:attributemethod] = v end opts.on("-c", "--collectionmethod METHODNAME", "Use collection method instead of attr_accessor") do |v| options[:collectionmethod] = v end opts.on("-t", "--types", "Include type in attribute definition call") do |v| options[:includetypes] = true end opts.on("-b", "--baseless", "Don't generate classes/modules for the root JSON in each file") do |v| options[:baseless] = true end opts.on("-f", "--forceoverwrite", "Overwrite Existing files") do |v| options[:forceoverwrite] = v end opts.on("-N", "--forcenumeric", "Use Numeric instead of Integer/Float") do |v| options[:forcenumeric] = v end opts.on("-v", "--verbose", "Verbose") do |v| options[:verbose] = v end end.parse! # Defaults options[:outputdir] ||= File.expand_path("./classes") options[:namespace] ||= "" options[:attributemethod] ||= "attr_accessor" options[:collectionmethod] ||= "attr_accessor" options[:includetypes] ||= false options[:baseless] ||= false options[:forceoverwrite] ||= false options[:verbose] ||= false options[:modulenames] = options[:namespace].split("::") options end # Parse all JSON files in ARGV and build the Entity cache, using the supplied options Hash. def self.parse_files(options) # Reset the object cache Entity.reset_parse # Load and parse each JSON file puts "Parsing Files..." if options[:verbose] rootclasses = [] ARGV.each do |filename| filename = File.expand_path(filename) puts "Processing: #{filename}" if options[:verbose] file = File.read(filename) data_hash = JSON.parse(file) rootclasses << Entity.parse_from(File.basename(filename,'.*'), data_hash, options) end rootclasses end # Write out all types in the Entity cache, except primitives and those contained in the # rootclasses array, to the provided writer with the supplied options Hash. def self.write_files(rootclasses, writer, options) files = 0 Entity.entities.each do |k,v| next if options[:baseless] and rootclasses.include?(v) display_entity(k,v) if options[:verbose] && !v.is_a?(Primitive) if v.is_a?(Entity) indent = 0 out = "" options[:modulenames].each do |v| out += (' '*indent)+"module #{v}\r\n" indent += 2 end out += writer.to_code(v, indent,options) while indent>0 indent -= 2 out += (' '*indent)+"end\r\n" end filename = options[:outputdir]+"/#{v.name}.rb" if File.exists?(filename) && !options[:forceoverwrite] $stderr.puts "File #{filename} exists. Use -f to overwrite." else File.write(filename, out) files += 1 end end end # Done puts "Done, Generated #{files} file#{files==1 ? '' : 's'}" end # Display the Entity supplied in ent with the supplied hash value hsh to STDOUT def self.display_entity(hsh, ent) puts "- #{ent.name} (#{ent.class.short_name} - #{hsh})" if ent.is_a?(Entity) ent.attributes.each { |ak,av| puts " #{ak}: #{av.name}" } elsif ent.is_a?(Collection) puts " (Types): #{ent.ruby_types.map { |h,ent| ent.name }.join(',')}" end end end end
true
d4e44c9a23088ff1beab66ed39bf0f8f58f62b46
Ruby
opendoor-labs/nomenclature
/app/models/term.rb
UTF-8
419
2.640625
3
[]
no_license
class Term < ApplicationRecord belongs_to :team validates :name, presence: true validates :description, presence: true def self.from_text(text) separator = if text.include?(':') ':' else ' ' end name, description = text.split(separator, 2).map(&:strip) term = find_or_initialize_by(name: name) term.assign_attributes(name: name, description: description) term end end
true
3ecdce614ac9df8434c9ab86cd9dce46f7addf1d
Ruby
jacquelynoelle/hotel
/lib/bookingdates.rb
UTF-8
643
3.078125
3
[]
no_license
module Hotel class BookingDates class InvalidBookingDatesError < StandardError end attr_reader :checkin, :checkout def initialize(checkin, checkout) unless checkout > checkin raise InvalidBookingDatesError, "Checkin must be before checkout." end @checkin = checkin @checkout = checkout end def nights return checkout - checkin end def overlaps?(other_booking) return !(other_booking.checkout <= self.checkin || other_booking.checkin >= self.checkout) end def contains?(date) return date >= self.checkin && date < self.checkout end end end
true
df9106baddd48b965756495d329fa2cae8cfbd7e
Ruby
PhilippePerret/Icare_AD_2018
/_lib/_required/User/instance/options.rb
UTF-8
4,056
2.671875
3
[]
no_license
# encoding: UTF-8 =begin Les bits d'options de 0 à 15 sont réservés à l'administration et les bits de 16 à 31 sont réservés à l'application elle-même. C'est ici qu'on définit ces options propres à l'application. Exemple de réglage forcé des options ------------------------------------ options = '0'*26 options[0] = '0' # > 0 si administrateur options[1] = '0' # Grade de l'user options[2] = '1' # 0 si le mail n'a pas été confirmé options[3] = '1' # 1 si a été détruit options[4] = '9' # Type de contact (voir aussi ci-dessous) # 9 => aucun mail options[16] = '4' # État de l'icarien # 4 => inactif # Si 1, pas reçu, si 2 actif, 3 en pause options[17] = '1' # jamais de mails options[18] = '0' # Direction après identification options[19] = '8' # Type de contact pour les autres icariens options[20] = '0' # pour cacher l'header options[21] = '1' # pour partager son historique options[22] = '1' # Notifier si reçoit message options[23] = '8' # Type de contact pour le reste du monde =end class User # Définir la valeur d'une option # +index+ Offset de l'option (0-start, de 0 à 31) ou un # symbol défini dans la méthode ci-dessus # +value+ Valeur à lui donner, de 0 à 35 (sera toujours transformé) # en un caractère unique. def set_option key_option, value index, instance_var = option_index_and_inst_name(key_option) opts = options.dup || "0"*(index+1) # || ("0"*32) raise "La valeur à donner à une option ne peut être supérieur à 35" if value.to_i > 35 opts[index] = value.to_s(36) # debug "NOUVELLES OPTIONS : #{opts}" set( options: opts ) # On renseigne la variable d'instance si elle existe instance_variable_set(instance_var, value) unless instance_var.nil? end def get_option key_option index, instance_var = option_index_and_inst_name(key_option) (options||"")[index].to_s.to_i(36) end # Bit 16 # État de l'icarien def bit_state options[16].to_i end # Bit 17 et suivant, cf. le fichier # ./ruby/_objets/User/model/Preferences/preferences.rb dans # l'atelier Icare_AD # Le bit 17 (18e) peut prendre les valeurs : # 0: rapport quotidien si actif # 1: jamais de mails # 2: résumé hebdomadaire # 3: quotidien et rapport hebdomadaire def pref_mails_activites ; options[17].to_i end # bit 17 (= 18e) # Une valeur de 0 à 9 (voir plus) définissant où l'user # doit être redirigé après son login. Ces valeurs peuvent être # définies par l'application, dans REDIRECTIONS_AFTER_LOGIN # dans la fichier config/site.rb # avec en clé le nombre du bit 18 : # site.redirections_after_login = { # '1' => {hname: "<nom pour menu>", route: 'route/4/show'}, # '2' => etc. # } def pref_goto_after_login; options[18].to_i end # bit 18 (= 19e) # = Type de contact = # Pour les autres icariens # 0: Par mail et par message (frigo) # 1: Par mail seulement # 2: Par message seulement # 8: Aucun contact def pref_type_contact; options[19].to_i end # Pour le reste du monde (non icariens) # 0: Par mail et par message (frigo) # 1: Par mail seulement # 2: Par message seulement # 8: Aucun contact def pref_type_contact_world; options[23].to_i end def pref_cache_header? ; pref? 3 end # bit 20 def pref_share_historique? ; pref? 4 end # bit 21 def pref_notify_when_message? ; pref? 5 end # bit 22 def pref? relbit realbit = 17 + relbit options[realbit].to_i == 1 end # BIT 24 (25e) def bit_reality options[24].to_i end # BIT 25 (26e) # Bit d'avertissement d'échéance de paiement dépassée # C'est un nombre de 0 à 9 pour savoir quel mail a été envoyé # suite à une échéance de paiment dépassé # 1: simple avertissement jusqu'à 9: menace de rejet # Note : les mails sont gérés par le CRON def bit_echeance_paiement options[25].to_i end end
true
ef4f2e7738d086b4d915627efc8aa93c5ef9c772
Ruby
yura-poj/TaskForCurs2
/lesson3/cargo_train.rb
UTF-8
210
2.59375
3
[]
no_license
require_relative 'train' require_relative 'cargo_carriage' class CargoTrain < Train def type :cargo end def add_carriage_with_own_type(number) add_carriage!(CargoCarriage.new(number)) end end
true
20f8df0274a61dc0595808ef39a11338aa9dc048
Ruby
bigtiger/vurl
/app/models/vurl.rb
UTF-8
3,628
2.65625
3
[]
no_license
class Vurl < ActiveRecord::Base require 'open-uri' require 'nokogiri' belongs_to :user has_many :clicks validates_presence_of :url, :user validates_format_of :url, :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix validate :appropriateness_of_url before_validation :format_url before_save :fetch_url_data named_scope :most_popular, lambda {|*args| { :order => 'clicks_count desc', :limit => args.first || 5 } } named_scope :since, lambda {|*args| { :conditions => ["created_at >= ?", args.first || 7.days.ago] } } def last_sixty_minutes(start_time=Time.now) minutes = [] 60.times do |i| new_time = i.minutes.ago(start_time) minutes << new_time.change(:hour => new_time.hour, :min => new_time.min) end minutes.reverse end def last_twenty_four_hours(start_time=Time.now) hours = [] 24.times do |i| new_time = i.hours.ago(start_time) hours << new_time.change(:hour => new_time.hour) end hours.reverse end def last_seven_days(start_date=Time.now) dates = [] 7.times do |i| new_date = i.days.ago(start_date) dates << new_date.change(:hour => 0) end dates.reverse end def clicks_for_last period case period when 'hour' clicks.since(1.hour.ago).all(:select => 'clicks.*, MINUTE(clicks.created_at) AS minute').group_by(&:minute) when 'day' clicks.since(1.day.ago).all(:select => 'clicks.*, HOUR(clicks.created_at) AS hour').group_by(&:hour) when 'week' clicks.since(1.week.ago).all(:select => 'clicks.*, DAY(clicks.created_at) AS day').group_by(&:day) end end def units_for_last period case period when 'hour' last_sixty_minutes when 'day' last_twenty_four_hours when 'week' last_seven_days end end def last_click clicks.last end def self.random find(:first, :offset => (Vurl.count * rand).to_i) end def before_create if vurl = Vurl.find(:first, :order => 'id DESC') self.slug = vurl.slug.succ else self.slug = 'AA' end end def self.tweet_most_popular_of_the_day require 'twitter' vurl = find(:first, :order => 'clicks_count desc', :conditions => ['created_at >= ?', 1.day.ago]) return if vurl.nil? intro = 'Most popular vurl today? ' link = ' http://vurl.me/' + vurl.slug description_length = 140 - intro.length - link.length description = vurl.title.first(description_length) unless vurl.title.blank? httpauth = Twitter::HTTPAuth.new(APP_CONFIG[:twitter][:login], APP_CONFIG[:twitter][:password], :ssl => true) base = Twitter::Base.new(httpauth) base.update("#{intro}#{description}#{link}") end def fetch_url_data begin document = Nokogiri::HTML(open(construct_url)) self.title = document.at('title').text self.keywords = document.at("meta[@name*=eywords]/@content").to_s self.description = document.at("meta[@name*=escription]/@content").to_s truncate_metadata rescue logger.warn "Could not fetch data for #{construct_url}." end end def construct_url url end private def format_url self.url = url.strip unless url.nil? end def truncate_metadata self.title = title.first(255) if title.length > 255 self.description = description.first(255) if description.length > 255 self.keywords = keywords.first(255) if keywords.length > 255 end def appropriateness_of_url if url =~ /https*:\/\/[a-zA-Z-]*\.*vurl\.me/i errors.add(:url, "shouldn't point back to vurl.me") end end end
true
f3736216a9f2cab9b1693efb63057c5fc72713dc
Ruby
swatichauhan16997/orm
/app/services/master_order_handler.rb
UTF-8
1,495
2.578125
3
[]
no_license
# Service for handling MasterOrders class MasterOrderHandler attr_accessor :params def initialize(params, session, current_user,id) @params = params @session = session @current_user = current_user @restaurant = Restaurant.find(id) end def manage_master_order search_session_order create_master_order update_master_order end private def search_session_order @order = [] order_key = @session[:order].compact.keys order_key.each do |i| @order << Order.find_by(id: i) unless Order.find_by(id: i).nil? end end def update_master_order total @master_order.update_attributes( total: $sum, order_status: 'placed', payment_status: 'pending', user_id: @current_user.id, restaurant_id: @restaurant.id ) return @master_order end def create_master_order @master_order = MasterOrder.create(master_order_params) $sum = 0 orders = Order.where(restaurant_id: @restaurant.id) orders.where(id: @session[:order].compact.keys).each do |o| OrderHistory.create(master_order_id: @master_order.id,order_id: o.id) $sum += o.price.to_i @session[:order].delete(o.id.to_s) end end def total; end def master_order_params params.require(:master_order).permit(:total, :order_type, :payment_type, :order_status, :payment_status, :transaction_id, :user_id) end end
true
e74d8aff5aeb0d887bf40d71bf7dbbb285515cc8
Ruby
josornoc/josornoc.github.io
/course/week2Day4/oc5.rb
UTF-8
3,894
3.46875
3
[]
no_license
# OC4. IronhackMDB # Trumpets are playing, a choir is singing, and a really handsome TV presenter is introducing all you to… THE BIG EXERCISE! # But don’t be scared. It’s just a bigger exercise than normal, using all the useful stuff we learned this week: testing with RSpec, #the TDD methodology, Sinatra, ERB and ActiveRecord. Quite a lot for being just the second week! # So let’s get hands on it! We decide we love TV shows so much that checking them on IMDB is not enough. We want to implement a web # app where we can keep track of the TV shows we love or hate, writing there our own rating and comments. # We want our web app, which will be called IronhackMDB, to match the following: # • The Model # ◦ We have a TVShow model (a skeleton of the class is available in Slack, together with an empty database) # ◦ The TVShow has three parameters: the name (so we can look it up at IMDB), our own comments, and our own rating. # ◦ The name field should be present, and unique across all our TV shows. # ◦ The our_rating field should be present and between 0 and 10 (both included) # ◦ The our_comments field should be present, with more than 100 characters but less than 10000 # ◦ Add tests to match what we want for each one of the three fields # ◦ Also add methods to the TVShow model to fetch IMDB rating, numbers of seasons, link, and picture # • Web features # ◦ In the top of the main page of our site, which will be called IronhackMDB (be sure to add an h1 title that says it!), we will have a # form that will create a new TVShow. # ◦ Just below that creation form, we will have links to the main route (‘/‘), the "our ranking" route (‘/our-ranking’) and the “imdb # ranking” route (‘/imdb-ranking’) # ◦ Both form and links should be always displayed, in any route (use a template for that!) # ◦ The main route (‘/‘) will list, for each one of the TV shows that we have in our database, their name, our own rating, the IMDB # rating, and a link to another route (‘/tv_shows/:tv_show_id’) # ◦ The page for a specific TV show (‘/tv_shows/:tv_show_id’) will load the TV show from the database and show a lot of information for # it: the name, our rating and comments, the IMDB rating, number of seasons, picture, and a HTML link to the IMDB page for that tv show. # ◦ The ‘/our-ranking’ route will just show a list, of tv shows, like the main route (even the link to the own TV show page), but # ordered, from best to worst, by our own rating # ◦ The ‘/imdb-ranking’ should do the same as ‘/our-ranking’ but following IMDB criteria # Note: the class fields are “name”, “own_rating” and “own_comments”. # OC4, reloaded. IronhackMDB Premium # If you finish this before time (I dare you!), we will add a complexity layer to it. The web app that we just wrote is really nice and # allows us to keep track of TV shows that we love or hate. # But the lists of TV shows are quite slow, because we have to go fetch the new information in IMDB every time for every TV show. What # could we do to improve it? # Exactly: save the IMDB information in the database. This way we only have to fetch it from IMDB when we are going to create the record; # afterwards the information will be fetched from our database, which is way quicker than going to the Internet. # You have a new empty database with the additional TVShow fields in slack. Use the .rb file you have build until now, except that you have # to connect to the “ironhackmdb_premium.sqlite” database. # Note: first read about Active Record callbacks in http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html # Note: the class fields are “name”, “own_rating”, “own_comments”, “imdb_rating”, “imdb_number_of_seasons”, “imdb_link”, “imdb_picture".
true
b6d8628b6ed7f65643b8721595d006ab4e0d0e4d
Ruby
airblade/quo_vadis
/app/models/quo_vadis/recovery_code.rb
UTF-8
703
2.515625
3
[ "MIT" ]
permissive
# frozen_string_literal: true module QuoVadis class RecoveryCode < ActiveRecord::Base belongs_to :account has_secure_password :code before_validation { send("code=", self.class.generate_code) unless code } # Returns true and destroys this instance if the plaintext code is authentic, false otherwise. def authenticate_code(plaintext_code) !!(destroy if super) end private CODE_LENGTH = 11 # odd number # Returns a string of length CODE_LENGTH, with two hexadecimal groups # separated by a hyphen. def self.generate_code group_length = (CODE_LENGTH - 1) / 2 SecureRandom.hex(group_length).insert(group_length, '-') end end end
true
fd6983dc6ea6f7255f3786e0e97545cd1b3e3763
Ruby
sbower/rbnd-toycity-part3
/lib/transaction.rb
UTF-8
1,364
3.078125
3
[ "MIT" ]
permissive
class Transaction attr_reader :id, :product, :customer @@id = 1 @@transactions = [] def initialize(customer, product) @customer = customer @product = product @id = @@id @@id += 1 if @product.in_stock? @product.decrement_stock else raise OutOfStockError, "'#{@product.title}' is out of stock." end add_to_transactions end def self.return(customer, transaction_id) transaction = find(transaction_id) raise TransactionNotFound, "There is no transtion #{transaction_id} for #{customer.name}" if transaction.nil? || transaction.customer.name != customer.name @@transactions.delete_at(Transaction.all.find_index {|t| t.id == transaction.id}) transaction.product.increment_stock end def self.all @@transactions end def self.find(id) @@transactions.find {|t| t.id == id} end def self.find_by_product(product_title) @@transactions.find_all {|t| t.product == product_title} end def self.find_by_zip(zip_code) @@transactions.find_all {|t| t.customer.zip_code == zip_code} end def self.find_by_age(age) @@transactions.find_all {|t| t.customer.age == age} end def self.find_by_customer(customer_name) @@transactions.find_all {|t| t.customer.name == customer_name} end private def add_to_transactions @@transactions << self end end
true
f265dd44f04b841f67e9c87064b60503ba17a1b4
Ruby
getadeo/code-snippets
/ruby-snippets/mixins.rb
UTF-8
994
3.078125
3
[]
no_license
module Login def login username, password @username == username and @password == password and p "Succesfully logged in as #@username" end def logout end def sign_up end end class Student include Login def initialize name, born_at, gender, username, password @name = name @born_at = born_at @gender = gender @username = username @password = password end def age age Time.today.year - @born_at.year age -= 1 if Time.today < birthday + age.years end end class Teacher include Login def initialize name, proficiency, list_of_grades, username, password @name = name @proficiency = proficiency @list_of_grades = list_of_grades @username = username @password = password end end student = Student.new "Ronald", Time.new("1970-04-12"), "M", "ronald", "j9" teacher = Teacher.new "Mutya", Time.new("1970-12-12"), "F", "mutya", "jef" student.login "ronald", "j9" teacher.login "mutya", "bes"
true
bd33d271ac72a6f0cb86badfbd598b15bff7f290
Ruby
multilang-depends/depends
/src/test/resources/ruby-code-examples/extends.rb
UTF-8
117
2.953125
3
[ "MIT" ]
permissive
class Animal def breathe end end class Cat < Animal def speak puts "Miao~~" end end
true
2f1799c4a2a42e0e28d0eac7cddbd3b4777f7a04
Ruby
counterbeing/mars-rover-challenge
/classes/format_validator.rb
UTF-8
492
3
3
[]
no_license
class FormatValidator def self.plateau_dimensions(string) unless string =~ /^\d+ \d+$/ raise "Your plateau dimensions should be something like '5 5'" end end def self.rover_location(string) unless string =~ /^\d+ \d+ (N|S|E|W)$/ raise "Your rover location should be something like '5 4 E'" end end def self.rover_command(string) unless string =~ /^(M|L|R)+$/ raise "Your rover command should be something like 'MRMLRM'" end end end
true
d2accda42fb19601ae319c039d7ac7d9cba9a69a
Ruby
decal/zap-attack
/lib/zap_attack/api/core/action/delete_alerts.rb
UTF-8
925
2.515625
3
[ "Apache-2.0" ]
permissive
# coding: utf-8 module ZapAttack::API RMALRTS_JSON = 'http://zap:8080/JSON/core/action/deleteAllAlerts' DELETE_ALERTS_JSON = RMALRTS_JSON # # Clear all current vulnerability alerts from the ZAP API. # # @return [String] Value of the JSON "Result" key received from the ZAP API JSON # @example urlarray = ZapAttack::API.DeleteAllAlerts.new # @see http://zap:8080/JSON/core/action/deleteAllAlerts # class DeleteAllAlerts < String attr_reader :json, :text, :rmall def initialize @rmall, @json, @text = '', [], '' open(RMALRTS_JSON, OPEN_URI_OPTS) do |x| if x.content_type.include?('/json') and x.status.first.to_i.eql?(200) x.each_line do |l| @text << l end end end @json = JSON.parse(@text) return '' if [email protected]?('Result') @rmall = @json['Result'] super(@rmall.clone) self end end end
true
7d4be591e7196466f5cab1f7147f027426c44343
Ruby
shioju/jsonar
/lib/jsonar/indexer.rb
UTF-8
1,009
2.890625
3
[ "MIT" ]
permissive
require 'json' require 'set' module Jsonar class Indexer def self.from_files(files = []) raise ArgumentError if files.empty? index = {} files.each do |file| index = Jsonar::Indexer.from_string(File.read(file), index) end index end private_class_method def self.from_string(json, index = {}) input = JSON.parse(json) # assume the json input is always an array at the top level input.each do |item| index_fields(item, item, index) end index end def self.index_fields(root, input, index) if input.is_a? Array input.each do |item| index_fields(root, item, index) end elsif input.is_a? Hash input.each_value do |v| index_fields(root, v, index) end else input = input.to_s input = 'null' if input.empty? index[input] = index[input] || Set.new index[input] << root end index end end end
true
4927c6a4ab5ba38c1b97ec96d4029c9cc3f278f1
Ruby
nayow/tictactoe_game
/lib/show.rb
UTF-8
6,672
2.96875
3
[]
no_license
class Show attr_accessor :tab def self.header @tab = ["","1","2","3","4","5","6","7","8","9"] system "clear" puts "","",""," ███╗ ███╗ ██████╗ ██████╗ ██████╗ ██╗ ██████╗ ███╗ ██╗██╗ ████╗ ████║██╔═══██╗██╔══██╗██╔══██╗██║██╔═══██╗████╗ ██║██║ ██╔████╔██║██║ ██║██████╔╝██████╔╝██║██║ ██║██╔██╗ ██║██║ ██║╚██╔╝██║██║ ██║██╔══██╗██╔═══╝ ██║██║ ██║██║╚██╗██║╚═╝ ██║ ╚═╝ ██║╚██████╔╝██║ ██║██║ ██║╚██████╔╝██║ ╚████║██╗ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ".colorize(:light_white),"","","_"*75 puts "","","" end def self.empty_grid puts "","","" puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " "+"1".colorize(:light_red)+" | "+"2".colorize(:light_red)+" | "+"3".colorize(:light_red)+" ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " -----------------------------------------------".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " "+"4".colorize(:light_red)+" | "+"5".colorize(:light_red)+" | "+"6".colorize(:light_red)+" ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " -----------------------------------------------".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " "+"7".colorize(:light_red)+" | "+"8".colorize(:light_red)+" | "+"9".colorize(:light_red)+" ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts "","","" end def self.grid(player, position) @tab[position] = player.sign # remplace le numéro de case par le signe du joueur qui l'a choisi puts " ","","" puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " "+@tab[1].to_s.colorize(:light_red)+" | "+@tab[2].to_s.colorize(:light_red)+" | "+@tab[3].to_s.colorize(:light_red)+" ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " -----------------------------------------------".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " "+@tab[4].to_s.colorize(:light_red)+" | "+@tab[5].to_s.colorize(:light_red)+" | "+@tab[6].to_s.colorize(:light_red)+" ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " -----------------------------------------------".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " "+@tab[7].to_s.colorize(:light_red)+" | "+@tab[8].to_s.colorize(:light_red)+" | "+@tab[9].to_s.colorize(:light_red)+" ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts " | | ".colorize(:light_white) puts "","","" end end
true
d880862dcd762293e25fca97b0c9d47788b1affc
Ruby
shannongamby/boris-bikes2
/lib/van.rb
UTF-8
289
2.75
3
[]
no_license
require_relative 'docking_station' require_relative 'bike' require_relative 'garage' class Van attr_reader :stored_bikes def initialize @stored_bikes = [] end def take_broken_bikes(station) @stored_bikes = station.docked_bikes.reject { |bike| bike.working? } end end
true
baa8ffe01536d2b3d63a065f3225f17e811a5ec2
Ruby
rocky-jaiswal/smshelper
/lib/smshelper.rb
UTF-8
281
2.890625
3
[]
no_license
require_relative "smshelper/version" require_relative "smshelper/solver" module Smshelper puts "Enter text you want to send :" puts "Helper will ignore case and space denotes pause" text = gets.chomp solver = Smshelper::Solver.new puts solver.solve(text).inspect end
true
4f6e73a62fe9fa9ea6a81f3f1c8c9e18d9d0bd19
Ruby
moofmayeda/stanford-algorithms-part-1
/week_1_practice.rb
UTF-8
1,162
3.734375
4
[]
no_license
def merge_sort(array) puts array.to_s length = array.count if length > 1 half = length / 2 left = merge_sort array[0..half-1] right = merge_sort array[half..length-1] merge(left, right) else array end end def merge(left, right) if left.empty? result = right elsif right.empty? result = left elsif left[0] < right[0] result = [left[0]] + merge(left[1..left.count-1], right) else result = [right[0]] + merge(left, right[1..right.count-1]) end result end def add(big_array) k = big_array.count n = big_array[0].count merged = big_array[0] (k - 1).times do |i| merged = merge(merged, big_array[i+1]) end merged end def multiply(x, y) # get number of digits in x/y n = x != 0 ? Math.log10(x).to_i + 1 : 1 if n > 1 half = 10**(n/2) a = x/half b = x%half c = y/half d = y%half # without Gauss # (half**2) * multiply(a, c) + half * (multiply(a, d) + multiply(b, c)) + multiply(b, d) # with Gauss ac = multiply(a, c) bd = multiply(b, d) abcd = multiply(a + b, c + d) (half**2) * ac + half * (abcd - ac - bd) + bd else x * y end end
true
1326da6475bc2876f6ec28b0c419522ee1a9b2f3
Ruby
eregon/Classes
/extension.rb
UTF-8
867
3.359375
3
[]
no_license
=begin July 2009 Code taken from the Ruby Extension Project http://rubyforge.org/projects/extensions http://extensions.rubyforge.org/ =end module Enumerable # # Like <tt>#map</tt>/<tt>#collect</tt>, but it generates a Hash. The block # is expected to return two values: the key and the value for the new hash. # numbers = (1..3) # squares = numbers.build_hash { |n| [n, n*n] } # 1=>1, 2=>4, 3=>9 # sq_roots = numbers.build_hash { |n| [n*n, n] } # 1=>1, 4=>2, 9=>3 # def build_hash result = {} self.each do |e| key, value = yield e result[key] = value end result end # # Added by Eregon # Same as Enumerable#build_hash, with indexes # def build_hash_with_index result = {} self.each_with_index do |e, i| key, value = yield(e, i) result[key]= value end result end end
true
a3ba4aa3eb0336fe0fc7b59e518b664029b1c0a0
Ruby
Denisglb/TickTacToe
/lib/player.rb
UTF-8
113
2.921875
3
[]
no_license
class Player attr_reader :piece def initialize @piece = 'x' end end player1 = Player.new p player1.piece
true
2d55bc5c21f5bdd433b4a94ec31f4e58cdc871f0
Ruby
iwaseasahi/design_pattern_with_ruby
/iterator/main.rb
UTF-8
339
3.359375
3
[]
no_license
require_relative 'book' require_relative 'book_shelf' class Main book_shelf = BookShelf.new book_shelf.append_book(Book.new('本1')) book_shelf.append_book(Book.new('本2')) book_shelf.append_book(Book.new('本3')) iterator = book_shelf.iterator while iterator.has_next? book = iterator.next puts book.name end end
true
6b4ee358453f61f4ad849044fece598dc9ea28b5
Ruby
iAmXquisite/ttt-8-turn-cb-gh-000
/lib/turn.rb
UTF-8
1,286
4.46875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Prints the Board def display_board(board) puts " #{board[0]} | #{board[1]} | #{board[2]} " puts "-----------" puts " #{board[3]} | #{board[4]} | #{board[5]} " puts "-----------" puts " #{board[6]} | #{board[7]} | #{board[8]} " end # Takes the number user enters and subtracts 1 to match array index def input_to_index(index) return index.to_i - 1 end # Adds the players move to the board def move(board, index, char="X") board[index] = char end # Gets user input and checks to see if its not taken def valid_move?(board, position) index = position.to_i if position_taken?(board, index) == false && index.between?(0, 8) return true else return false end end # re-define your #position_taken? method here, so that you can use it in the #valid_move? method above. def position_taken?(board, index) if board[index] == " " or board[index] == "" or board[index] == nil return false elsif board[index] == "X" or board[index] == "O" return true end end def turn(board) puts "Please enter 1-9:" display_board(board) input = gets.strip input = input_to_index(input) while !valid_move?(board, input) puts "Please enter 1-9:" input = gets.strip input = input_to_index(input) end move(board, input) return display_board(board) end
true
5af2901d314b8f1f62bda865701c263a073adaa0
Ruby
InflectProject/inflections
/lib/services/holliday_service.rb
UTF-8
1,321
2.984375
3
[ "MIT" ]
permissive
require 'net/http' class HollidayService < Inflect::AbstractService # A WORDS Array constant with the key words of the Service. # @example Array for New York Times service # words = %W[ NEWS TODAY NEW\ YORK\ TIMES] # In case there are modules that provide similar contents the # one with most PRIORITY is picked. # Float::Infinity is the lowest priority. def initialize @priority = 1 @words = %W[FERIADOS PROXIMOS] @title = 'Proximo Feriado' @base_url = 'nolaborables.com.ar'.freeze end # This is method is the only one needed for Inflect to work. # Implements how the service responds at the translated words. # Returns a Inflect::Response with retrieved data, . def default response = Net::HTTP.get(@base_url, '/API/v1/proximo') body = JSON.parse(response) content = { 'title': @title, 'body': body } respond content end def proximos response = Net::HTTP.get(@base_url, '/API/v1/actual') body = JSON.parse(response) days = reject_past_dates body content = { body: days.first(5) } respond content, {type: 'list'} end private def reject_past_dates(days) today = Date.today days.select { |day| Date.new(today.year, day["mes"], day["dia"]).between? today, Date.new(today.year, 12, 31) } end end
true
c771e72cd98e075b64dc9e1ea9e99cde0097c26a
Ruby
keram/refinerycms-inquiries2
/app/models/refinery/inquiries/inquiry.rb
UTF-8
1,070
2.578125
3
[ "MIT" ]
permissive
require 'refinery/core/base_model' require 'filters_spam' module Refinery module Inquiries class Inquiry < Refinery::Core::BaseModel self.table_name = 'refinery_inquiries' default_scope -> { order(id: :desc) } scope :fresh, -> { where(archived: false) } scope :archived, -> { where(archived: true) } scope :ham, -> { where(spam: false) } scope :spam, -> { where(spam: true) } alias_attribute :title, :name validates :name, presence: true validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i } validates :message, presence: true # filters_spam message_field: :message, # email_field: :email, # author_field: :name, # other_fields: [:phone], # extra_spam_words: %w() def self.latest(number = 7, include_spam = false) include_spam ? limit(number) : ham.limit(number) end def ham? !spam? end def fresh? !archived? end end end end
true
9e673746293729c3993cc71ff2f8ba2e992ab361
Ruby
rdavid1099/poke-api-v2
/lib/poke_api/common/name.rb
UTF-8
302
2.59375
3
[ "MIT" ]
permissive
module PokeApi module Common # Name object handling lists of names and languages class Name attr_reader :name, :language def initialize(data) @name = data[:name] @language = Utility::Language.new(data[:language]) end end end end
true
1a2162efcb20446dccad003eb5c6822a736ca6e1
Ruby
tbfisher/puppet-php
/lib/puppet/parser/functions/to_php.rb
UTF-8
978
2.90625
3
[]
no_license
def var_export(val) if val.class == String val = val.gsub(/'/, '\\\\\0') "'#{val}'" elsif val.class == Array val = val.collect{|v| var_export(v) }.join(', ') "array(#{val})" elsif val.class == Hash val = val.collect{|k,v| var_export(k) + ' => ' + var_export(v) }.join(', ') "array(#{val})" # checking whether foo is a boolean elsif !!val == val val ? "TRUE" : "FALSE" elsif val.is_a? Numeric val.to_s() elsif val == :undef "NULL" else raise(Puppet::ParseError, 'to_php(): Could not convert value:' + val.inspect) end end module Puppet::Parser::Functions newfunction(:to_php, :type => :rvalue, :doc => <<-EOS Converts a value to a PHP literal. EOS ) do |args| raise(Puppet::ParseError, 'to_php(): Wrong number of arguments ' + "given (#{args.size} for 1)") if args.size != 1 var_export(args[0]) end end
true
657d8cdb8b710cf21f7dc12c150acda66fdebe7d
Ruby
lawhump/CS-Air
/tests/graph_stats_test.rb
UTF-8
694
2.71875
3
[]
no_license
require 'minitest/autorun' require 'json' require '../app/graph' # I don't really know how I'm expected to verify my answers. # Reading through the JSON and comparing things by hand is not gonna happen. class GraphStatsTest < Minitest::Test # Called before every test method runs. Can be used # to set up fixture information. def setup # Do nothing end # Called after every test method runs. Can be used to tear # down fixture information. def teardown # Do nothing end # Basic test to see if I can make and access my object in a # predictable manner def test_graph graph = Graph.new("../app/map_data.json") # Graph stats gs = graph.gs end end
true
a3a9b0829721a111a0bec8d1bc42cf1c0ef4e095
Ruby
AshRhazaly/alphacamp
/Power_of_two.rb
UTF-8
146
3.40625
3
[]
no_license
def is_power_of_two(n) if Math.sqrt(n) % 1 == 0 return true else return false end end puts is_power_of_two(25) puts "hello world"
true
e2966e31ce53d36b11db4acdeb951a49ac52d680
Ruby
szareey/ministryDocs
/spec/ministry_docs/math_2007_doc/specific_parser_spec.rb
UTF-8
1,034
2.5625
3
[]
no_license
require 'spec_helper' describe MinistryDocs::Math2007Doc::SpecificParser do subject(:parser) { MinistryDocs::Math2007Doc::SpecificParser.new } let(:specific) { get_txt 'specific_parser/specific' } describe '#parse' do let(:parsed) { parser.parse(specific, '1').first } let(:part) { '1.1' } let(:description) { "explain the meaning of the term function, and distinguish a function from a relation that is not a function, through investigation of linear and quadratic relations using a variety of representations (i.e., tables of values, mapping diagrams, graphs, function machines, equations) and strategies (e.g., identifying a one-to-one or many-to-one mapping; using the vertical-line test) \nSample problem: Investigate, using numeric and graphical representations, whether the relation x = y2 is a function, and justify your reasoning." } it 'parse part' do expect(parsed.part).to eq part end it 'parse description' do expect(parsed.description).to eq description end end end
true
bb07905019071a7fc809374bfc9ab011b7a82ace
Ruby
richardpattinson/oystercard-1
/lib/journey.rb
UTF-8
318
3.21875
3
[]
no_license
class Journey MIN_FARE = 1 PENALTY_FARE = 6 def initialize(entry_station, exit_station) @entry_station = entry_station @exit_station = exit_station end def complete? return false if @exit_station || @entry_station == nil end def fare self.complete? ? MIN_FARE : PENALTY_FARE end end
true
2a79982b3d4b3c555de3bb4ab0c6711cb8899155
Ruby
chackerian/Ruby
/formatfail.rb
UTF-8
328
3.203125
3
[]
no_license
days = "Mon Tue Wed Thur Fri Sat Sun" months = "Jan\nFeb\nMar\nApr\nMay\nJune\nJuly\nAug" puts "Here are some days: ", days puts "Here are some months ", months puts <<PARAGRAPH There's something going on here With the PARAGRAPH thing We'll be able to type as much as we like Even 4 lines if we want or five or six. PARAGRAPH
true
7bc0e6e28c86fe3a9238a1392836f801275d6608
Ruby
EricRicketts/RubyBooks
/MasteringRubyClosures/exercises/chapter_2_blocks/exercise_4_test.rb
UTF-8
1,421
3.515625
4
[]
no_license
module​ Redis ​  ​class​ Server ​  ​# ... more code ...​ ​  ​  ​def​ run ​  ​loop​ ​do​ ​  session = @server.accept ​  ​  ​begin​ ​  ​return​ ​if​ ​yield​(session) == ​:exit​ ​  ​ensure​ ​  session.close ​  ​end​ ​  ​end​ ​  ​rescue​ => ex ​  $stderr.puts ​"Error running server: ​​#{​ex.message​}​​"​ ​  $stderr.puts ex.backtrace ​  ​ensure​ ​  @server.close ​  ​end​ ​  ​  ​# ... more code ...​ ​  ​end​ ​  ​end​ =begin 1. Does Redis::Server#run require a block to be passed in? Yes, as the yield keyword is used. Since there is no block_given? check, a LocalJumpError would result if no block was passed in. 2. How is the return result of this block used? If the return value from the block is :exit then #run exits. Otherwise, the session local variable is passed to the block. Note that even though the conditional is checking for an exit condition, yield(session) still means a session is still beeing passed to an accompanying block. 3. How could this code be called? Redis::Server.new.run do |session| # do something with the session end The session return value is discarded unless it returns :exit =end
true
97d65c3dcfa42e8ea40b38e1942682d0b6bdb4bc
Ruby
mytestbed/omf_web
/lib/omf-web/rack/multi_file.rb
UTF-8
1,839
2.609375
3
[]
no_license
require 'rack/file' module OMF::Web::Rack # Rack::MultiFile serves files which it looks for below an array # of +roots+ directories given, according to the # path info of the Rack request. # # Handlers can detect if bodies are a Rack::File, and use mechanisms # like sendfile on the +path+. # class MultiFile < ::Rack::File def initialize(roots, opts = {}) super nil, opts[:cache_control] @roots = roots if opts[:sub_path] @sub_path = opts[:sub_path].split ::Rack::Utils::PATH_SEPS end if @version = opts[:version] # read VERSION_MAP.yaml files @version_map = {} require 'yaml' yml = File.join((@sub_path || []), 'VERSION_MAP.yaml') @roots.reverse.each do |dir| fn = File.join(dir, yml) #puts "Checking for #{fn}" if File.readable?(fn) mh = YAML.load_file(fn) #puts "VERSIONS: #{mh.inspect}" @version_map.merge!(mh) end end end end def _call(env) @path_info = ::Rack::Utils.unescape(env["PATH_INFO"]) parts = @path_info.split ::Rack::Utils::PATH_SEPS if @version_map if pkg_name = @version_map[parts[1]] parts[1] = pkg_name # replace with version end end if @sub_path parts = @sub_path + parts end return fail(403, "Forbidden") if parts.include? ".." @roots.each do |root| @path = F.join(root, *parts) #puts ">>>> CHECKING #{@path}" available = begin F.file?(@path) && F.readable?(@path) rescue SystemCallError false end if available return serving(env) end end fail(404, "File not found: #{@path_info}") end # _call end # MultiFile end # module
true
ef0936f1f9a2d0572d08048f46c14da3b102487b
Ruby
alpiepho/rpn-calc-chrome-extension
/test_html/test_enter_drop.rb
UTF-8
1,314
2.859375
3
[]
no_license
# # Copyright (C) 2017 ThatNameGroup, LLC. and Al Piepho # All Rights Reserved # ########################################################### # TEST - enter and drop ########################################################### def test_EnterEachNumberThenDrop puts "SUITE: test_EnterEachNumberThenDrop" puts " TEST: (hex) Each number with 'enter'" for i in 1..15 do click("button%X" % i) #puts inputValueStr() click("buttonEnter") assertResultVal("line0", i) end puts " TEST: (hex) drop previous numbers from stack" for i in 0..14 do assertResultVal("line0", 15-i) click("buttonDrop") assertResultVal("line0", 15-i-1) if i < 14 assertResultEmp("line0") if i == 14 end puts " TEST: toggle format to %d" $fmtHex = false click("buttonFormat") puts " TEST: (dec) Each number with 'enter'" for i in 1..9 do click("button%X" % i) #puts inputValueStr() click("buttonEnter") assertResultVal("line0", i) end puts " TEST: (dec) drop previous numbers from stack" for i in 0..8 do assertResultVal("line0", 9-i) click("buttonDrop") assertResultVal("line0", 9-i-1) if i < 8 assertResultEmp("line0") if i == 8 end puts " TEST: toggle format to %x" $fmtHex = true click("buttonFormat") end
true
c32d00dc9df237863eadb1d4a4b4cfb4793d3e15
Ruby
RND-SOFT/lusnoc
/lib/lusnoc/mutex.rb
UTF-8
3,381
2.6875
3
[ "MIT" ]
permissive
require 'socket' require 'lusnoc/session' module Lusnoc class Mutex include Helper attr_reader :key, :value, :owner def initialize(key, value: Socket.gethostname, ttl: 20) @key = key @value = value @ttl = ttl end def locked? !!owner end def owned? owner == Thread.current end def session_id @session&.id end [:time_to_expiration, :need_renew?, :ttl, :expired?, :alive?, :alive!, :renew].each do |m| define_method(m) { @session&.public_send(m) } end def on_mutex_lost(&block) @on_mutex_lost = block end def synchronize(timeout: 0, &block) t = Timeouter::Timer.new(timeout, eclass: TimeoutError, message: 'mutex acquisition expired') Session.new("mutex_session/#{key}", ttl: @ttl) do |session| @session = session session.on_session_die do @owner = nil @on_mutex_lost&.call(self) end return acquisition_loop! key, session, value, t, &block ensure release(key, session.id, timeout: 2) rescue nil logger.info("Mutex[#{key}] released for Session[#{session.name}:#{session.id}]") @owner = nil @session = nil end end private def acquire(key, session, value) resp = Lusnoc.http_put(build_url("/v1/kv/#{key}?acquire=#{session.id}"), value, timeout: 1) return false if resp.body.chomp != 'true' @owner = Thread.current logger.info("Mutex[#{key}] acquired for Session[#{session.name}:#{session.id}]") renew true end def release(key, session) Lusnoc.http_put(build_url("/v1/kv/#{key}?release=#{session.id}"), timeout: 1) end def acquisition_loop!(key, session, value, t) if acquire(key, session, value) prepare_guard(session, key).run do return yield(self) end end logger.debug("Mutex[#{key}] run acquisition loop for Session[#{session.name}:#{session.id}]") t.loop! do session.alive!(TimeoutError) wait_for_key_released(key, t.left) if acquire(key, session, value) prepare_guard(session, key).run do return yield(self) end end logger.debug("Mutex[#{key}] acquisition failed for Session[#{session.name}:#{session.id}]") sleep 0.4 end end def prepare_guard(session, key) Lusnoc::Guard.new(build_url("/v1/kv/#{key}")) do |guard| guard.condition do |body| JSON.parse(body).first['Session'] == session.id rescue false end guard.then do @owner = nil logger.info("Mutex[#{key}] LOST for Session[#{session.name}:#{session.id}]") @on_mutex_lost&.call(self) end end end def wait_for_key_released(key, timeout = nil) logger.debug("Mutex[#{key}] start waiting of key releasing...") Lusnoc::Watcher.new(build_url("/v1/kv/#{key}"), timeout: timeout, eclass: TimeoutError, emessage: 'mutex acquisition expired').run do |body| result = JSON.parse(body.empty? ? '[{}]' : body) return true if result.first['Session'].nil? end end end end
true
4595a67ead4058efbb6b99d3c1dfdc900bed4311
Ruby
Zernov/projecteuler
/20-29/Problem 21.rb
UTF-8
398
3.78125
4
[]
no_license
def divisors_of(number) divisors = [] n = 1 while n <= number**0.5 if number % n == 0 divisors << n divisors << number / n unless number / n == n or n == 1 end n += 1 end divisors.sort end result = [] (1..10000).each { |i| result << i if divisors_of(divisors_of(i).inject(:+)).inject(:+) == i } p result.select { |e| e != divisors_of(e).inject(:+) }.inject(:+)
true
aad70236f50f63e8bf9839ed61f911fa69a43d5d
Ruby
heedspin/m2mhub
/app/models/quality/customer_otd_report.rb
UTF-8
2,228
2.765625
3
[ "MIT" ]
permissive
class Quality::CustomerOtdReport class Month attr_accessor :date, :num_releases, :late_releases def initialize(date) @date = date @num_releases = 0 @late_releases = [] end def add_late_release(release) @late_releases.push release end def num_late_releases @late_releases.size end def percent_late if (self.num_releases <= 0) or (self.num_releases < self.num_late_releases) 100 else (self.num_late_releases.to_f / self.num_releases) * 100 end end end def initialize(args=nil) args ||= {} @start_date = args[:start_date] ||= Date.current.beginning_of_year @end_date = args[:end_date] || @start_date.advance(:years => 1) if @end_date > Date.current @end_date = Date.current.advance(:days => 1) end @months = {} end def run results = M2m::SalesOrderRelease.connection.select_rows <<-SQL select sorels.fduedate, count(*) from sorels where sorels.fduedate >= '#{@start_date.to_s(:db)}' and sorels.fduedate < '#{@end_date.to_s(:db)}' group by sorels.fduedate order by sorels.fduedate SQL results.each do |result_row| due_date, count = result_row month_for(due_date).num_releases += count end late_releases = M2m::SalesOrderRelease.shipped_late.due(@start_date, @end_date) M2m::SalesOrderItem.attach_to_releases(late_releases) late_releases.each do |late_release| month_for(late_release.due_date).add_late_release(late_release) end true end def ordered_months @months.values.sort_by(&:date) end def month_for(date) month_date = Date.new(date.year, date.month, 1) @months[month_date] ||= Month.new(month_date) end def all_late_releases @months.values.map(&:late_releases).flatten end def num_releases @num_releases ||= @months.values.sum(&:num_releases) end def num_late_releases @num_late_releases ||= @months.values.sum(&:num_late_releases) end def percent_late if (self.num_releases <= 0) or (self.num_releases < self.num_late_releases) 100 else (self.num_late_releases.to_f / self.num_releases) * 100 end end end
true
51524a79b48e8b9951867a974bbe6e894f396aef
Ruby
nettan20/qae
/app/pdf_generators/qae_pdf_forms/custom_questions/by_year.rb
UTF-8
2,403
2.78125
3
[ "MIT" ]
permissive
module QaePdfForms::CustomQuestions::ByYear YEAR_LABELS = %w(day month year) YEAR_LABELS_TABLE_HEADERS = [ "Financial year", "Day", "Month", "Year" ] IN_PROGRESS = "in progress..." def render_years_labels_table rows = financial_year_changed_dates_entries rows.map do |e| e[1] = to_month(e[1]) end rows.push(latest_year_label) active_fields.length.times do |i| rows[i].unshift(i + 1) end render_multirows_table(YEAR_LABELS_TABLE_HEADERS, rows) end def render_years_table rows = active_fields.map do |field| entry = year_entry(field) entry.present? ? entry : IN_PROGRESS end render_single_row_table(financial_years_decorated_headers, rows) end def financial_years_decorated_headers headers = financial_year_changed_dates_entries.map do |entry| decorated_label(entry) end headers.push(decorated_label(latest_year_label(false))) end def financial_year_changed_dates_entries financial_year_changed_dates_question.active_fields[0..-2].map do |field| YEAR_LABELS.map do |year_label| fetch_year_label(field, year_label, :financial_year_changed_dates, false) end end end def financial_year_changed_dates_question step.filtered_questions.detect do |q| q.key == :financial_year_changed_dates end end def active_fields question.decorate(answers: form_pdf.filled_answers).active_fields end def fetch_year_label(field, year_label, q_key = nil, with_month_check = true) entry = year_entry(field, year_label, q_key) if entry.present? if with_month_check && year_label == "month" to_month(entry) else entry end else "-" end end def year_entry(field, year_label = nil, q_key = nil) entry = form_pdf.filled_answers.detect do |k, _v| k == "#{q_key || key}_#{field}#{year_label}" end entry[1] if entry.present? end def latest_year_label(with_month_check = true) month = if with_month_check to_month(form_pdf.filled_answers["financial_year_date_month"]) else form_pdf.filled_answers["financial_year_date_month"] end [ "0" + form_pdf.filled_answers["financial_year_date_day"], month, Date.today.year ] end def decorated_label(label) "Year ending in " + label.join("/") end end
true
924f1cbe255412869224d7bee377ab5451bb7182
Ruby
jsha1/cycling
/rides.rb
UTF-8
409
2.8125
3
[]
no_license
require 'nokogiri' require 'open-uri' class Ride def self.getStats(user, early) page = Nokogiri::HTML(open("http://strava.com/athletes/#{user}")) result = [ page.css("h1#athlete-name").text, early - page.css("ul.inline-stats li strong")[3].text.to_i] end end users = {"usmanity" => 211, "hcabalic" => 697, "1320215" => 655, "1689644" => 53} r = Ride.getStats("usmanity", 500) Ride.addToFile(r)
true
648d48eb99a1186278572f843ddf9541fc584749
Ruby
prashantGyeser/urbanzeak-leads-processor
/lib/tasks/check_words.rake
UTF-8
1,779
2.796875
3
[]
no_license
require 'word_counter_processed_tweets' # Usage sample # rake check:word[<word to check. Takes only one word>] # To run it on rake with multiple words # heroku run rake 'check:word["want lunch"]' # Make sure it is quoted properly namespace :check do desc "Check if a list of words exists in the leads and non leads" task :word, [:word] => :environment do |task, args| word_to_check = args.word.to_s.downcase word_counters = WordCounter.where(word: word_to_check) word_counters.destroy_all #Lead.records_containing_word(args.word.to_s) WordCounterProcessedTweets.count_times_word_occurs_in_leads(word_to_check) WordCounterProcessedTweets.count_times_word_occurs_in_non_city_leads(word_to_check) WordCounterProcessedTweets.count_times_word_occurs_in_non_leads(word_to_check) puts "Finished storing tweets with the word" end desc "Get the word count for all the words in the tweet body in the leads table" task lead_word_count: :environment do words = WordCounterProcessedTweets.unique_word_count_in_leads Hash[words.sort_by{|k, v| v}.reverse].each do |word| puts word.inspect end end desc "Get the word count for all the words in the tweet body in the unchecked non leads table" task unchecked_non_lead_word_count: :environment do words = WordCounterProcessedTweets.unique_word_count_in_unchecked_non_leads Hash[words.sort_by{|k, v| v}.reverse].each do |word| puts word.inspect end end desc "Get the word count for all the words in the tweet body in the non leads table" task non_lead_word_count: :environment do words = WordCounterProcessedTweets.unique_word_count_in_non_leads Hash[words.sort_by{|k, v| v}.reverse].each do |word| puts word.inspect end end end
true
83e6fbde2a030f6b01ae73848817d304e40037c5
Ruby
englertjoseph/Fighter
/player.rb
UTF-8
3,587
3.25
3
[]
no_license
require_relative 'animation.rb' module Fighter class Player SCALE = 3 STEP_SIZE = 2 MAX_HEALTH = 100 ATTACKS = { kick: MAX_HEALTH / 10, punch: MAX_HEALTH / 20 } attr_reader :side, :MAX_HEALTH attr_accessor :health def initialize(player_name, window, x, y, side) @tileset = TileSet.new player_name, window @window = window @x, @y = x, y @side = side @health = 100 @cooldown = rand(100..500) @last_attack = 0 end def move_left(other_player) return if blocking? return if @side == :left && outer_x - STEP_SIZE <= 0 return if @side == :right && inner_x - STEP_SIZE <= other_player.inner_x @x -= STEP_SIZE end def move_right(other_player) return if blocking? return if @side == :right && outer_x + STEP_SIZE >= @window.width return if @side == :left && inner_x + STEP_SIZE >= other_player.inner_x @x += STEP_SIZE end def idle @busy = false set_animation :idle end def kick(other_player) return if Gosu::milliseconds-@last_attack < @cooldown @busy = true set_animation(:kick) { attack other_player, :kick; idle } @cooldown = rand(0..1500) @last_attack = Gosu::milliseconds end def punch(other_player) return if Gosu::milliseconds-@last_attack < @cooldown @cooldown = rand(0..1500) @last_attack = Gosu::milliseconds @busy = true set_animation(:punch) { attack other_player, :punch; idle } end def walking set_animation :walking end def block set_animation :block end def hit(damage) return if blocking? @busy = true @health -= damage set_animation(:hit) { idle } end def draw @tileset.animation.draw @x, @y, 0, scale_x, SCALE end def width @tileset.width*SCALE end def busy? @busy end def in_range?(other_player) (inner_x - other_player.inner_x).abs <= STEP_SIZE end def blocking? @tileset.animation == @tileset[:block] end def attack(other_player, move) return unless in_range?(other_player) || other_player.blocking? other_player.hit ATTACKS[move] @window.gameover if other_player.ko? end def ko? @health <= 0 end def freeze @tileset.animation.freeze! end # Returns the x value of the players bounding box closest to the # opposing player def inner_x @side == :left ? @x+width : @x-width end def outer_x @x # Note when flipping @x remains the same hence @x is always the outer value end private def set_animation(animation, &block) @tileset.animation = @tileset[animation] @tileset.animation.play_once(&block) unless block.nil? end def scale_x return SCALE if @side == :left -SCALE if @side == :right end end class TileSet < Hash def initialize(player_name, window) self[:idle] = Animation.new("#{player_name}/idle", window) self[:kick] = Animation.new("#{player_name}/kick", window) self[:punch] = Animation.new("#{player_name}/punch", window) self[:walking] = Animation.new("#{player_name}/walking", window) self[:block] = Animation.new("#{player_name}/block", window) self[:hit] = Animation.new("#{player_name}/hit", window) @animation = self[:walking] @width, @height = @animation.width, @animation.height end attr_accessor :animation attr_reader :width, :height end end
true
6fa22f0c08a3a1766564185d9512a223bc12d055
Ruby
BenRKarl/WDI_work
/w01/d04/Rebecca_Strong/rental_app/spec/person.rb
UTF-8
242
3.71875
4
[]
no_license
class Person attr_accessor :name, :age, :income def initialize(name, age, income) @name = name @age = age @income = income end def to_s "My name is #{name}, I am #{age} and I earn $#{income} per year." end end
true
e75f5f23b986eb0fbb481b9b3f864af36f264a62
Ruby
ravelll/toy-compiler
/compiler.rb
UTF-8
4,517
3.484375
3
[]
no_license
class Compiler class Runner def initialize(source) @source = source @source_index = 0 @tokens = [] @token_index = 0 end def read_number(char) number_chars = [char] loop do char = get_char break unless char if '0' <= char && char <= '9' number_chars << char else unget_char break end end number_chars.join end def get_token if @token_index == @tokens.size return nil end token = @tokens[@token_index] @token_index += 1 token end def tokenize print "# Tokens :" loop do char = get_char break unless char case char when " ", "\t", "\n" next when "0".."9" literal_int = read_number(char) token = Token.new(kind: :literal_int, value: literal_int) @tokens = @tokens << token print " '#{token.value}'" when ";", "+", "-", "*", "/" token = Token.new(kind: :punct, value: char) @tokens = @tokens << token print " '#{token.value}'" else raise StandardError, "Tokenizer: Invalid char: '#{char}'" end end print "\n" end def get_char if @source_index == @source.size return nil end char = @source[@source_index] @source_index += 1 char end def unget_char @source_index -= 1 end def generate_expr(expr) case expr.kind when :literal_int puts " movq $#{expr.intval}, %rax" when :unary case expr.operator when "+" puts " movq $#{expr.operand.intval}, %rax" when "-" puts " movq $-#{expr.operand.intval}, %rax" else raise StandardError, "generator_expr: Unknown unary expr.operator: #{expr.operator}" end when :binary puts " movq $#{expr.left.intval}, %rax" puts " movq $#{expr.right.intval}, %rcx" case expr.operator when "+" puts " addq %rcx, %rax" when "-" puts " subq %rcx, %rax" when "*" puts " imulq %rcx, %rax" when "/" puts " movq $0, %rdx" puts " idiv %rcx" else raise StandardError, "generator_expr: Unknown binary expr.operator: #{expr.operator}" end else raise StandardError, "generator_expr: Unknown expr.kind: #{expr.kind}" end end def generate_code(expr) puts " .global main" puts "main:" generate_expr(expr) puts " ret" end def parse_unary_expr token = get_token case token.kind when :literal_int Expr.new(kind: :literal_int, intval: token.value) when :punct operand = parse_unary_expr Expr.new(kind: :unary, operator: token.value, operand: operand) else nil end end def parse expr = parse_unary_expr loop do token = get_token if token == nil || token.value == ";" return expr end case token.value when "+", "-", "*", "/" left = expr right = parse_unary_expr return Expr.new( kind: :binary, operator: token.value, left: left, right: right ) else return expr end end end def run tokenize expr = parse generate_code(expr) end end class Token attr_accessor :kind, :value def initialize(kind:, value:) if ![:literal_int, :punct].include? kind raise StandardError, "Token#new: Invalid token kind: #{kind}" end @kind = kind @value = value end end class Expr attr_accessor :kind, :intval, :operator, :operand, :left, :right def initialize(kind:, intval: nil, operator: nil, operand: nil, left: nil, right: nil) if ![:literal_int, :unary, :binary].include? kind raise StandardError, "Expr#new: Invalid token kind: #{kind}" end @kind = kind @intval = intval @operator = operator # "+", "-" @operand = operand # for unary expression @left = left # for binary expression @right = right # for binary expression end end end source = ARGV[0] if source.nil? raise StandardError, "Nothing was input" end Compiler::Runner.new(source).run
true
aa51da339ad0a004e31267dac712e6809dcd15a2
Ruby
nikita-ahuja/phase-0-tracks
/ruby/assessment_practice/newsroom.rb
UTF-8
2,547
3.703125
4
[]
no_license
class Newsroom attr_reader :name, :reporters attr_accessor :budget def initialize(name, budget) @name = name @budget = budget @reporters = {} end def add_reporter(reporter_name, skills) if has_budget?(reporter_name) if @reporters.keys.include?(reporter_name) puts "We can't hire another #{reporter_name}!" else @reporters[reporter_name] = skills end else #!has_budget?(reporter_name) puts "We can't afford #{reporter_name}!" end @reporters end def salary_for(reporter_name) reporter_name.length * 10000 end # def total_salaries # total_salaries = 0 # @reporters.keys.each do |name| # total_salaries += salary_for(name) # end # total_salaries # end # more efficient way to write total_salaries def total_salaries @reporters.keys.reduce(0) do |sum, name| sum + salary_for(name) end end #commented out inefficiency... comparison operator automatically returns true or false! def has_budget?(reporter_name) #if total_salaries + salary_for(reporter_name) <= budget # true # else # false # end end def friendly_print puts "Welcome to the #{@name} Newsroom!" puts #new line puts "Your reporting team is:" @reporters.each do |reporter, skills| #skills.join(", ") puts "-#{reporter}, specializing in #{skills.join(", ")}." end puts puts "Thank you for watching! Good night!" end # def find_reporters_with_skill(skill) # reporters_with_skill = [] # @reporters.each do |reporter, skills| # if skills.include?(skill) # reporters_with_skill.push(reporter) # end # end # p reporters_with_skill # end # more efficient way to write skill method def find_reporters_with_skill(skill) reporters_with_skill = @reporters.select do |name, skills| skills.include?(skill) end reporters_with_skill.keys end def new_skill(reporter_name, skill) @reporters[reporter_name] << skill end end p room1 = Newsroom.new("Elysium", 300_000) p room1.name p room1.add_reporter("Anderson Cooper", ["politics", "economics", "grey hair"]) p room1.salary_for("Anderson Cooper") p room1.add_reporter("Wolf Blitzer", ["grey hair"]) # p room1.add_reporter("Jim Acosta") p room1.total_salaries p room1.has_budget?("Rachel Maddow") p room1.add_reporter("Rachel Maddow", ["speaking", "presenting"]) room1.friendly_print p room1.find_reporters_with_skill("grey hair") p room1.reporters room1.new_skill("Anderson Cooper", "painting") p room1.reporters
true
0aa9d074dd0a75e4817548ba4494e53e52f463c1
Ruby
Jenietoc/Ruby_kommit_course
/Arrays III/Remove_Array_Items_that_Exist_in_Another_Array.rb
UTF-8
253
3.578125
4
[]
no_license
a = [1, 1, 2, 2, 2, 3, 3, 4, 5] b = [1, 4, 5] p a - b #Challenge def custom_subtraction(arr1, arr2) new_array = [] arr1.each do |item| new_array << item unless arr2.include?(item) end new_array end p custom_subtraction(a, b)
true
29dd8bd87e00665d5c89735e6703fa269f5d64aa
Ruby
tessa155/Software-Modelling-And-Design-Projects
/Project1/project1_codes/news/csv_formatter.rb
UTF-8
672
2.5625
3
[]
no_license
# This script contains CsvFormatter class, # which has common methods for the three csv formatters. # # # Author:: Tessa(Hyeri) Song ([email protected]) # Student Number:: 597952 # Copyright:: Copyright (c) 2015 The University Of Melbourne module News class CsvFormatter < Formatter # Call super to guarantee that our checks are run def initialize super end # Define extension type def extension "csv" end # Return true for header def header? true end # Return false for footer def footer? false end # Return nothing but needed to prevent any error def header article; end end end
true
f424890dbee318dd754b41ee11aac4e745d2def1
Ruby
casualjim/caricature
/lib/caricature/clr/descriptor.rb
UTF-8
4,946
3.109375
3
[ "BSD-3-Clause" ]
permissive
module Caricature # Contains the logic to collect members from a CLR type module ClrMemberCollector attr_reader :class_events, :events private # collects the instance members for a CLR type. # makes sure it can handle indexers for properties etc. def build_member_collections(context={}, instance_member=true) build_event_collection(context, instance_member) mem = [] mem += build_method_collection(context, instance_member) mem += build_property_collection(context, instance_member) mem end def build_property_collection(context, instance_member) context[:properties].inject([]) do |res, pi| prop_name = property_name_from(pi) res << MemberDescriptor.new(prop_name, pi.property_type, instance_member) res << MemberDescriptor.new("set_Item", nil, instance_member) if prop_name == "get_Item" res << MemberDescriptor.new("#{prop_name}=", nil, instance_member) if pi.can_write and prop_name != "get_Item" res end end def build_method_collection(context, instance_member) context[:methods].inject([]) do |meths, mi| meths << MemberDescriptor.new(mi.name.underscore, mi.return_type, instance_member) unless event?(mi.name, instance_member) meths end end def build_event_collection(context, instance_member) context[:events].inject(evts=[]) { |evc, ei| evc << ClrEventDescriptor.new(ei.name, instance_member) } (instance_member ? @events = evts : @class_events = evts) end # indicates if this member is an event def event?(name, instance_member) ((instance_member ? @events : @class_events)||[]).any? { |en| /^(add|remove)_#{en.event_name}/i =~ name } end # gets the property name from the +PropertyInfo+ # when the property is an indexer it will return +[]+ def property_name_from(property_info) return property_info.name.underscore if property_info.get_index_parameters.empty? "get_Item" end # the binding flags for instance members of a CLR type def instance_flags System::Reflection::BindingFlags.public | System::Reflection::BindingFlags.instance end # the binding flags for class members of a CLR type def class_flags System::Reflection::BindingFlags.public | System::Reflection::BindingFlags.static end def event_flags non_public_flag | instance_flags end def class_event_flags non_public_flag | class_flags end def non_public_flag System::Reflection::BindingFlags.non_public end end class ClrEventDescriptor attr_reader :event_name def initialize(event_name, instance_member=true) @event_name, @instance_member = event_name, instance_member end def instance_member? @instance_member end def add_method_name "add_#{event_name}" end def remove_method_name "remove_#{event_name}" end def to_s "<#{self.class}:#{object_id} @event_name=\"#{event_name}\">" end end # describes clr interfaces. # Because CLR interfaces can't have static members this descriptor does not collect any class members class ClrInterfaceDescriptor < TypeDescriptor include ClrMemberCollector # collects instance members on this interface # it will collect properties, methods and property setters def initialize_instance_members_for(klass) clr_type = klass.to_clr_type context = {} context[:properties] = clr_type.collect_interface_properties context[:methods] = clr_type.collect_interface_methods context[:events] = clr_type.collect_interface_events @instance_members = build_member_collections context end # this method is empty because an interface can't have static members def initialize_class_members_for(klass); end end # Describes a CLR class type. it collects the properties and methods on an instance as well as on a static level class ClrClassDescriptor < TypeDescriptor include ClrMemberCollector # collects all the instance members of the provided CLR class type def initialize_instance_members_for(klass) clr_type = klass.to_clr_type context = {} context[:methods] = clr_type.get_methods(instance_flags) context[:properties] = clr_type.get_properties(instance_flags) context[:events] = clr_type.get_events(event_flags) @instance_members = build_member_collections context end # collects all the static members of the provided CLR class type def initialize_class_members_for(klass) clr_type = klass.to_clr_type context = {} context[:methods] = clr_type.get_methods(class_flags) context[:properties] = clr_type.get_properties(class_flags) context[:events] = clr_type.get_events(class_event_flags) @class_members = build_member_collections context, false end end end
true
b753205a216ace48ab4abf20259db554cff3748b
Ruby
anthonychen1109/boating-school
/app/models/student.rb
UTF-8
589
3.078125
3
[]
no_license
class Student attr_reader :first_name, :last_name @@all = [] def initialize(first_name, last_name) @first_name = first_name @last_name = last_name @@all << self end def self.full_names self.all.map {|student| "#{student.first_name} #{student.last_name}"} end def self.all @@all end def self.find_student(full_name) self.all.find {|student| full_name == "#{student.first_name} #{student.last_name}"} end def add_boating_test(instructor, test_name, test_status) BoatingTest.new(instructor, test_name, test_status, self) end end
true
3e773b4bcad3f56efefd267ca198c94fab998245
Ruby
Ben-CU/Ruby-Basic-TCP-Client
/tcp_server.rb
UTF-8
251
2.96875
3
[]
no_license
require "socket" #Creates a TCP Server on port 9999 server = TCPServer.new(9999) #Listens for Connections and sends "Hello World! to them loop do Thread.start(server.accept) do |client| client.puts "Hello World!" client.close end end
true
c6e32ea67d0fd72366dafd5093126413fc492567
Ruby
fabiocasmar/lenguajes-de-programacion-1
/Proyecto2-Ruby/bfs.rb
UTF-8
8,161
3.578125
4
[]
no_license
=begin Nombre del archivo: bfs.hs Realizado por: Fabio Castro 10-10132 Patricia Reinoso 11-10851 Organización: Universidad Simón Bolívar Proyecto: Programación Orientada a Objetos - Lenguajes de Programación I Versión: v0.9.0 =end =begin El módulo Bfs contiene todas las funciones para la ejecución del bfs. =end module Bfs =begin La función bfs realiza la ejecución del bfs de manera genérica, haciendo uso de la función each de la clase, del objeto. =end protected def bfs(start) q = [] q.push(start) visit = [] pushear_nodo = lambda { |x| q.push(x) } while(q.size != 0) n = q.shift if !visit.include? n n.each pushear_nodo yield n visit.push(n) end end end =begin La función find recibe un nodo desde el cual se ejecutará bfs y un predicado. Se devolverá el primer nodo que cumpla con el predicado. =end public def find(start, predicate) raise "start debe tener modulo bfs." unless start.respond_to? :bfs start.bfs(start) { |n| return n if predicate.call(n) } end =begin La función path recibe un nodo desde el cual se ejecutará bfs y un predicado. Se devolverá el camino desde el nodo start, hasta el primer nodo que cumpla el predicado. =end public def path(start, predicate) raise "start debe tener modulo bfs." unless start.respond_to? :bfs f = { start => nil } start.bfs(start) do |n| f.keys.each do |x| if x == n n = x end end if predicate.call(n) pa = [] while !(n.nil?) do pa.unshift(n) n = f[n] end return pa end n.each lambda { |h| f[h] = n } end end =begin La función walk recibe un nodo desde el cual se ejecutará bfs y un action que se ejecutará sobre cada nodo. Se devolverá una lista con todos los nodos visitado. =end public def walk (start, action) raise "start debe tener modulo bfs." unless start.respond_to? :bfs v = [] start.bfs(start) do |n| action.call(n) v.push(n) end return v end end =begin La clase BinTree, permite representar árboles binaros por un nodo. =end class BinTree include Bfs # Valor almacenado en el nodo attr_accessor :value # BinTree izquierdo attr_accessor :left # BinTree derecho attr_accessor :right =begin La función initialize de BinTree permite crear un árbol binario e inicializarlo. =end def initialize(v,l,r) raise "Solo se puede tener hijos de tipo BinTree o nil" unless (l.is_a? BinTree) or (l.nil?) raise "Solo se puede tener hijos de tipo BinTree o nil" unless (r.is_a? BinTree) or (r.nil?) self.value, self.left, self.right = v, l, r end =begin La función each de BinTree, recibe un bloque que sera utilizado para iterar sobre los hijos del nodo, cuando esten definidos. =end def each(b) b.call(self.left) unless self.left.nil? b.call(self.right) unless self.right.nil? end end =begin La clase GraphNode, permite representar Grafos por el nodo. =end class GraphNode include Bfs # Valor alamacenado en el nodo attr_accessor :value # Arreglo de sucesores GraphNode attr_accessor :children =begin La función initialize de GraphNode permite crear un Grafo representado por un nodo, e inicializarlo. =end def initialize(v,c) raise "Solo se puede inicializar la lista de hijos como vacia o nil." unless (c.is_a? Array) or (c.nil?) c.each { |x| raise "Solo se puede tener hijos de tipo GraphNode" unless (x.is_a? GraphNode ) } unless (c.nil?) self.value, self.children = v, c end =begin La función each de GaphNode, recibe un bloque que sera utilizado para iterar sobre los hijos del nodo, cuando esten definidos. =end def each(b) (self.children.each { |c| b.call(c) }) unless self.children.nil? or self.children.empty? end end =begin La clase LCR tiene todo lo necesario para representar grafo implícitos de expansión, los nodos representan los estado, se hace uso de la clase bfs. =end class LCR include Bfs # En value se encuentra el estado actual, de que lado se encueentra que. attr_accessor :value =begin La función fun_ver verifica si un nodo tiene una configuración válida, por ejemplo, un estado inválido es cuando están la cabra y el lobo del mismo lado, y el bote se encuentra del otro lado. =end protected def fun_ver (s) if (s.value["side"] == :right) side_in = "left" else side_in = "right" end if (s.value[side_in].include?(:lobo) and s.value[side_in].include?(:cabra)) or (s.value[side_in].include?(:cabra) and s.value[side_in].include?(:repollo)) false else true end end =begin La función initialize de LCR permite crear un Grafo implícito, e inicializarlo. =end public def initialize(side,left,right) left.map! { |c| c.to_sym } right.map! { |c| c.to_sym } side = side.to_sym self.value = { "side" => side, "left" => left, "right" => right } left.each { |x| raise "Se introdujo una etiqueta erronea en el lado izquierdo." unless ((x ==:lobo)or(x ==:cabra)or(x ==:repollo)) } right.each { |x| raise "Se introdujo una etiqueta erronea en el lado derecho." unless ((x ==:lobo)or(x ==:cabra)or(x ==:repollo)) } raise "Se introdujo una etiqueta con lado erroneo." unless ((side==:left)or(side==:right)) raise "Se ha introducido una cantidad de elementos incorrecta" unless (left.length + right.length == 3) raise "Ha introducido un elemento dos veces" unless ((left+right).uniq!).nil? end =begin La función each de LCR, recibe un procedimiento que sera utilizado para iterar sobre los hijos del estado, que serán generado al momento de requerirlos. =end public def each(p) if self.value["side"] == :left o = "left" d = "right" else o = "right" d = "left" end self.value[o].each do |x| newo = Array.new(self.value[o]) newo.delete(x) newd = (Array.new(self.value[d])).push(x) if o == "right" ns = LCR.new(d,newd,newo) else ns = LCR.new(d,newo,newd) end p.call(ns) if fun_ver(ns) end ns = LCR.new(d,self.value["left"],self.value["right"]) p.call(ns) if fun_ver(ns) end =begin La función == de LCR, permite saber si dos nodos LCR son iguales. =end protected def ==(comp) if comp.is_a?LCR ((self.value["side"] == comp.value["side"])) and ((self.value["right"]).sort() == (comp.value["right"]).sort()) and ((self.value["left"]).sort() == (comp.value["left"]).sort()) else false end end =begin La función solve de LCR hace uso de la función path del módulo Bfs para resolver el grafo implícito y devolver la serie de estados por los que pasar para llegar al estado objetivo. =end public def solve raise "El estado que ha introducido es invalido" unless self.fun_ver(self) o = LCR.new(:right,[],[:repollo,:cabra,:lobo]) p = lambda { |x| x == o } self.path(self,p).each { |m| puts m.value } return true end end
true
c565ecf8865410315cd55045c77ad42bab5cc5d2
Ruby
annakim93/restricted-arrays
/lib/using_restricted_array.rb
UTF-8
6,205
3.734375
4
[]
no_license
require_relative 'restricted_array.rb' # RestrictedArray can be created using a specified size, or a random size in # the range of 1-20 will be chosen for you. # All values are integers in the range of 1-221. # RestrictedArray cannot be resized. # Get that nice colorized output Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new ##################################################################### # Calculates the length of the restricted array. All values are integers. # The restricted_array is terminated by 'nil' i.e. array[length] = nil # Complexity assessment: # Note: where n = length of the input array # Time complexity: O(n); linear; at most will parse through each array elem once # Space complexity: O(1); constant; excluding the input space, # the variables included in the function are all constants def length(array) # raise NotImplementedError array_length = 0 if array[0] == nil return nil else index = 0 until array[index] == nil array_length += 1 index += 1 end end return array_length end # Prints each integer values in the array # Complexity assessment: # Note: where n = length of the input array # Time complexity: O(n); linear; prints each elem of array # Space complexity: O(1); constant; space for index (int) def print_array(array) # raise NotImplementedError index = 0 until array[index] == nil p array[index] index += 1 end end # For an unsorted array, searches for 'value_to_find'. # Returns true if found, false otherwise. # Complexity assessment: # Note: where n = length of the input array # Time complexity: O(n); linear; worst case goes through array from beginning to end to find value # Space complexity: O(1); constant; doesn't require more space than input array and index constant def search(array, length, value_to_find) index = 0 until index == length if array[index] == value_to_find return true end index += 1 end return false # raise NotImplementedError end # Finds and returns the largest integer value the array # Assumes that the array is not sorted. # Complexity assessment: # Note: where n = length of the input array # Time complexity: O(n); linear; worst case will parse through array from beginning to end to find max # Space complexity: O(1); constant; does not require new vars aside from index (int) and max value (int) def find_largest(array, length) max_value = array[0] index = 1 until index == length if array[index] > max_value max_value = array[index] end index += 1 end return max_value # raise NotImplementedError end # Finds and returns the smallest integer value in the array # Assumes that the array is not sorted. # Complexity assessment: # Note: where n = length of the input array # Time complexity: O(n); linear; worst case will parse through array from beginning to end to find min # Space complexity: O(1); constant; does not require new vars aside from index (int) and min value (int) def find_smallest(array, length) min_value = array[0] index = 1 until index == length if array[index] < min_value min_value = array[index] end index += 1 end return min_value # raise NotImplementedError end # Reverses the values in the integer array in place # Complexity assessment: # Note: where n = length of the input array # Time complexity: O(n); linear; traverse through half of array O(n/2) --> O(n) # Space complexity: O(1); constant; does not require new vars aside from index (int) and reverse_ind (int) def reverse(array, length) ind = 0 reverse_ind = length - 1 until ind > reverse_ind temp = array[reverse_ind] array[reverse_ind] = array[ind] array[ind] = temp ind += 1 reverse_ind -= 1 end return array # raise NotImplementedError end # For an array sorted in ascending order, searches for 'value_to_find'. # Returns true if found, false otherwise. # Complexity assessment: # Note: where n = length of the input array # Time complexity: O(log n); logarithmic; half of array is eliminated with each search: # doubling size of array only increases search count by 1 # Space complexity: O(1); constant; does not require new vars aside from begin_ind (int), end_ind (int), and midpoint (int) def binary_search(array, length, value_to_find) begin_ind = 0 end_ind = length - 1 while begin_ind <= end_ind midpoint = (begin_ind + end_ind) / 2 if array[midpoint] == value_to_find return true elsif array[midpoint] > value_to_find end_ind = midpoint - 1 else begin_ind = midpoint + 1 end end return false # raise NotImplementedError end # Helper method provided to sort the array in ascending order # Implements selection sort # Time complexity = O(n^2), where n is the number of elements in the array. # To find the correct value for index 0, a total of (n-1) comparisons are needed. # To find the correct value for index 1, a total of (n-2) comparisons are needed. # To find the correct value for index 2, a total of (n-3) comparisons are needed. # and so on ... # To find the correct value for index (n-2), a total of 1 comparisons is needed. # To find the correct value for the last index, a total of 0 comparisons are needed. # Total number of comparisons = (n-1) + (n-2) + ... 3 + 2 + 1 # = (n * (n-1))/2 # This is O(n^2) in Big O terms. # Space complexity = constant or O(1) since the additional storage needed, # does not depend on input array size. def sort(array, length) length.times do |index| # outer loop - n elements min_index = index # assume index is where the next minimally value is temp_index = index+1 # compare with values at index+1 to length-1 while temp_index < length # inner loop - n-1 elements if array[temp_index] < array[min_index] # found a new minimum, update min_index min_index = temp_index end temp_index += 1 # move to next index end if min_index != index # next minimum value is not at current index, swap temp = array[min_index] array[min_index] = array[index] array[index] = temp end end end ## --- END OF METHODS ---
true
6253d1aa0f4f4da708bd6183aaa2a213bece597f
Ruby
nelgau/xe
/lib/xe/enumerator/launchers.rb
UTF-8
1,166
2.78125
3
[]
no_license
module Xe class Enumerator # Convenience methods for invoking the enumeration strategies, or choosing # to short-circuit in favor of the standard enumerable methods when the # context is disabled. module Launchers # Runs a computation, returning a value, within a single fiber. If the # fiber blocks on a realization, a proxy is returned instead. def run_evaluator(&blk) Strategy::Evaluator.(context, options, &blk) end # Runs an enumeration, returning a value, with a succession of fibers, # that folds a block starting with the given initial value. If some fiber # blocks on a realization, a proxy is substituted for that value and # passed into the next iteration. def run_injector(initial, &blk) Strategy::Injector.(context, enum, initial, options, &blk) end # Runs an enumeration, returning an array of independent values, within a # succession of fibers. If some fiber blocks on a realization, a proxy is # substituted for that value. def run_mapper(&blk) Strategy::Mapper.(context, enum, options, &blk) end end end end
true
46fabc01b70cadd86f306c24a58c81c48e414618
Ruby
EPrenzlin/ruby-collaborating-objects-lab-onl01-seng-pt-030220
/lib/song.rb
UTF-8
611
3.078125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Song attr_accessor :name, :artist, :import @@all = [] def self.new_by_filename(import) title = import.split("-")[1].strip artist_from_file = import.split("-")[0].strip song = self.new(title) song.artist = Artist.find_or_create_by_name(artist_from_file) song.artist.add_song(song) song # binding.pry end def self.all @@all end def initialize(name) @name = name @@all << self end def artist_name=(import) self.artist = Artist.find_or_create_by_name(import) end end
true
bdd35de20f5735e6d828d28e8cbcf3824e6a30a4
Ruby
oceanep/UGHHHH
/app/models/girl.rb
UTF-8
790
2.59375
3
[]
no_license
class Girl < ApplicationRecord def rank(user) ranking = Ranking.where(user: user, girl: self).first if !ranking 0 else ranking.rank end end def total_rank # Ranking.where(:girl_id => self.id).pluck(:rank).inject(:+) end def highest_rank # highest_ranking_girl = Girl.all.sort_by{|i| i.total_rank}.first end def Girl.vote_count Girl.find_by_sql ['SELECT id, name, upvote_count, downvote_count, ((upvote_count + 1.9208) / (upvote_count + downvote_count) - 1.96 * SQRT((upvote_count * downvote_count) / (upvote_count + downvote_count) + 0.9604) / (upvote_count + downvote_count)) / (1 + 3.8416 / (upvote_count + downvote_count)) AS ci_lower_bound FROM girls WHERE upvote_count + downvote_count > 0 ORDER BY ci_lower_bound DESC'] end end
true