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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
fd73235f4a1fc7d34d877dd7ed01527f33a038f8
|
Ruby
|
s2k/ATDD-demo
|
/src/user.rb
|
UTF-8
| 311
| 3.140625
| 3
|
[] |
no_license
|
class User
attr :name
attr :pwd
attr :status
def initialize(name, user_data)
@name = name
@pwd = user_data[:pwd]
@status = user_data[:status]
end
def logged_in?
return @status == :online
end
def password_equals(password)
return password == @pwd
end
end
| true
|
14804b66961b02883faa7d4d1e0a596275c54f1a
|
Ruby
|
feymartynov/task_mgr
|
/db/seeds.rb
|
UTF-8
| 1,336
| 2.578125
| 3
|
[] |
no_license
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
users = %w(joe mike robert).map do |name|
User.create!(email: "#{name}@example.com", password: 'qwerty123')
end
tasks = YAML.load(<<-YAML)
- name: Make a Rails app
description: Use Rails and Bootstrap
state: finished
- name: Create models
description: Task (name, description, state, user), User (email, password)
state: finished
- name: Write some seeds
description: Add some fake users & tasks
state: started
- name: Create Welcome page
description: Just like that
state: new
- name: Add authorization
description: Allow users to access the private area
state: new
- name: Make a tasks list page
description: Show all tasks in the system and their owners
state: new
- name: Allow users to change the task state
description: One can change the state only of his own tasks, not the others'
state: new
- name: Deploy on Heroku
description: Use capistrano. Also set up travis ci.
state: new
YAML
tasks.each do |attrs|
Task.create!(attrs.merge(user: users.sample))
end
| true
|
383237feff9a56f2949fd274913289786c62cca4
|
Ruby
|
thehimalayanleo/thehimalayanleo.github.io
|
/vendor/bundle/ruby/3.1.0/gems/bibtex-ruby-4.0.16/test/bibtex/test_string.rb
|
UTF-8
| 3,863
| 2.8125
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later",
"GPL-3.0-only"
] |
permissive
|
require 'helper.rb'
module BibTeX
class StringTest < Minitest::Spec
describe 'when parsing a simple string' do
before do
@bib = BibTeX.parse('@string{ foo = "bar" }')
end
it 'should should not be empty' do
assert_equal 1, @bib.length
end
it 'should have a symbol as key' do
assert_equal :foo, @bib[0].key
end
it 'should have a value string' do
assert_equal 'bar', @bib[0].value.to_s
end
it 'should have been registered' do
refute @bib.strings[:foo].nil?
end
end
#
# def test_replacement
# bib = BibTeX::Bibliography.open(Test.fixtures(:string_replacement), :debug => false)
# refute_nil(bib)
# assert(bib.kind_of?(BibTeX::Bibliography))
# refute(bib.empty?)
# assert_equal(7,bib.length)
# assert_equal([BibTeX::String,BibTeX::Preamble,BibTeX::Entry], bib.data.map(&:class).uniq)
# assert_equal(["foo"], bib.strings[:foo])
# assert_equal(["bar"], bib.strings[:bar])
# assert_equal([:foo, "bar"], bib.strings[:foobar])
# assert_equal([:foobar, :foo], bib.strings[:foobarfoo])
# assert_equal([:bar, "foo", :bar], bib.strings[:barfoobar])
# assert_equal('"foo" # foo # foobarfoo # "bar"', bib.preambles[0].content)
# assert_equal('"foo" # barfoobar', bib[:'manual:1'].title)
#
# bib.replace_strings({ :filter => [:preamble]})
# assert_equal(["foo"], bib.strings[:foo])
# assert_equal(["bar"], bib.strings[:bar])
# assert_equal([:foo, "bar"], bib.strings[:foobar])
# assert_equal([:foobar, :foo], bib.strings[:foobarfoo])
# assert_equal([:bar, "foo", :bar], bib.strings[:barfoobar])
# assert_equal('"foo" # "foo" # foobar # foo # "bar"', bib.preambles[0].content)
# assert_equal('"foo" # barfoobar', bib[:'manual:1'].title)
#
# bib.replace_strings({ :filter => [:string]})
# assert_equal(['foo','bar'], bib.strings[:foobar])
# assert_equal(['foo', 'bar','foo'], bib.strings[:foobarfoo])
# assert_equal(['bar','foo','bar'], bib.strings[:barfoobar])
# assert_equal('"foo" # "foo" # foobar # foo # "bar"', bib.preambles[0].content)
# assert_equal('"foo" # barfoobar', bib[:'manual:1'].title)
#
# bib.replace_strings({ :filter => [:preamble,:entry]})
# assert_equal('"foo" # "foo" # "foo" # "bar" # "foo" # "bar"', bib.preambles[0].content)
# assert_equal('"foo" # "bar" # "foo" # "bar"', bib[:'manual:1'].title)
# end
#
# def test_roundtrip
# bib = BibTeX::Bibliography.open(Test.fixtures(:string_replacement), :debug => false)
# refute_nil(bib)
# assert_equal('@string{ foo = "foo" }', bib.data[0].to_s)
# assert_equal('@string{ bar = "bar" }', bib.data[1].to_s)
# assert_equal('@string{ foobar = foo # "bar" }', bib.data[2].to_s)
# assert_equal('@string{ foobarfoo = foobar # foo }', bib.data[3].to_s)
# assert_equal('@string{ barfoobar = bar # "foo" # bar }', bib.data[4].to_s)
# bib.replace_strings
# assert_equal('@string{ foo = "foo" }', bib.data[0].to_s)
# assert_equal('@string{ bar = "bar" }', bib.data[1].to_s)
# assert_equal('@string{ foobar = "foo" # "bar" }', bib.data[2].to_s)
# assert_equal('@string{ foobarfoo = "foo" # "bar" # "foo" }', bib.data[3].to_s)
# assert_equal('@string{ barfoobar = "bar" # "foo" # "bar" }', bib.data[4].to_s)
# bib.join_strings
# assert_equal('@string{ foo = "foo" }', bib.data[0].to_s)
# assert_equal('@string{ bar = "bar" }', bib.data[1].to_s)
# assert_equal('@string{ foobar = "foobar" }', bib.data[2].to_s)
# assert_equal('@string{ foobarfoo = "foobarfoo" }', bib.data[3].to_s)
# assert_equal('@string{ barfoobar = "barfoobar" }', bib.data[4].to_s)
# end
end
end
| true
|
5486822643feadbdba1d688112132dbd3dcd5e99
|
Ruby
|
jeffryang24/learning-star
|
/ruby/integer_class.rb
|
UTF-8
| 290
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
a = 123
puts a
puts a.class
a = 574654694576854796746495
puts a
puts a.class
a = 473574389579593457347539759375934759837593759759375395
puts a
puts a.class
=begin
as ruby >= 2.4,
the fixnum and bignum class is unified into integer class.
So, all of above command will print Integer
=end
| true
|
10fcfd7cd43c95a382a2bb10910d037e0a8df4b3
|
Ruby
|
anayib/work
|
/object_oriented_programing/twenty_one_solution.rb
|
UTF-8
| 5,453
| 3.890625
| 4
|
[] |
no_license
|
class Participant
attr_accessor :name, :cards
attr_writer :total
def initialize
@name = name
@cards = []
@total = 0
end
def hit(new_card)
cards << new_card
end
def stay
puts "#{name} stays!"
end
def busted?
total > 21
end
def total
total = 0
cards.each do |card|
if card.ace?
total += 11
elsif card.jack? || card.queen? || card.king?
total += 10
else
total += card.value.to_i
end
end
cards.select(&:ace?).count.times do
break if total <= 21
total -= 10
end
total
end
end
class Player < Participant
end
class Dealer < Participant
end
class Deck
attr_accessor :cards
def initialize
@cards = []
Card::SUITS.each do |suit|
Card::VALUES.each do |value|
@cards << Card.new(suit, value)
end
end
mix_cards!
end
def mix_cards!
cards.shuffle!
end
def update_deck
cards.pop
end
end
class Card
SUITS = ["H", "D", "S", "C"]
VALUES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
def initialize(suit, value)
@suit = suit
@value = value
end
def to_s
"The #{value} of #{suit}"
end
def value
case @value
when 'J' then 'Jack'
when 'Q' then 'Queen'
when 'K' then 'King'
when 'A' then 'Ace'
else
@value
end
end
def suit
case @suit
when 'H' then 'Hearts'
when 'D' then 'Diamonds'
when 'S' then 'Spades'
when 'C' then 'Clubs'
end
end
def ace?
value == 'Ace'
end
def king?
value == 'King'
end
def queen?
value == 'Queen'
end
def jack?
value == 'Jack'
end
end
module Hand
def deal_cards
2.times do
player.cards << deck.update_deck
dealer.cards << deck.update_deck
end
end
def show_initial_cards
puts "#{dealer.name} has: #{dealer.cards.first}"
puts "#{player.name} has: #{player.cards.first} and #{player.cards.last} "
end
def player_turn
loop do
puts "Your total is: #{player.total}"
puts "#{player.name}, do you want to hit or stay (h/s)?"
answer = nil
loop do
answer = gets.chomp.downcase
break if %w(h s).include? answer
puts "Please hit(h),or stay (s)"
end
if answer == 's'
player.stay
break
elsif player.busted?
break
else
player.hit(deck.update_deck)
show_player_card
break if player.busted?
end
end
end
def dealer_turn
loop do
if dealer.total >= 17
dealer.stay
elsif dealer.total < 17
dealer.hit(deck.update_deck)
end
break if dealer.total >= 17
end
end
def show_player_card
puts "You got: #{player.cards.last}"
end
def show_result
if player.total > dealer.total
puts "#{player.name} wins!"
elsif player.total < dealer.total
puts "#{dealer.name} wins!"
else
puts "It's a tie!"
end
end
def show_busted
if player.busted?
puts "#{dealer.name} wins. You busted with a total of: #{player.total}"
elsif dealer.busted?
puts "#{player.name} wins.#{dealer.name} busted! with a total of: #{dealer.total}"
end
end
def show_total_score
puts "#{dealer.name} total: #{dealer.total}"
puts "#{player.name} total: #{player.total}"
end
def is_a_tie?
player.total == dealer.total
end
end
class Game
include Hand
attr_accessor :player, :dealer, :deck
def initialize
@player = Player.new
@dealer = Dealer.new
@deck = Deck.new
end
def start
set_dealer_name
display_welcome_message
set_player_name
start_hand
good_bye_message
end
def start_hand
loop do
clear
deal_cards
show_initial_cards
player_turn
if player.busted?
show_busted
if play_again?
reset
next_hand_message
sleep(2)
next
else
break
end
end
dealer_turn
if dealer.busted?
show_busted
if play_again?
reset
next_hand_message
sleep(2)
next
else
break
end
end
show_result
show_total_score
play_again? ? reset : break
next_hand_message
sleep(2)
end
end
private
def clear
system 'clear'
end
def display_welcome_message
puts "Welcome to 21 game. My name is #{dealer.name}"
end
def set_dealer_name
dealers = %w(R2D2 RUBOP SOBY)
dealer.name = dealers.sample
end
def set_player_name
puts "What is your name?"
answer = nil
loop do
answer = gets.chomp
break unless answer.empty?
puts "Please type your name:"
end
puts "Let's start #{answer}"
player.name = answer
end
def play_again?
answer = nil
puts "Do you want to play again? y/n"
loop do
answer = gets.chomp.downcase
break if %w(y n).include? answer
puts "Please type y or n"
end
return true if answer == 'y'
return false if answer == 'n'
end
def next_hand_message
puts "*****************************"
puts "Let's play another hand then!"
puts "*****************************"
end
def reset
player.cards = []
dealer.cards = []
self.deck = Deck.new
end
def good_bye_message
puts "Thanks for playing"
end
end
Game.new.start
| true
|
656f23c8ece3518f15b3f4afc174802514b9490a
|
Ruby
|
MASisserson/launch_school
|
/intro_programming_ruby/hashes/2.rb
|
UTF-8
| 277
| 3.3125
| 3
|
[] |
no_license
|
# Hashes Exercise 2
palau = { peter: 'uncle', rdiall: 'cousin' }
america = { abigail: 'girlfriend', mark: 'friend', steve: 'friend' }
england = { anna: 'friend' }
puts palau
puts america
puts england
puts palau.merge(america)
puts palau
puts palau.merge!(england)
puts palau
| true
|
90d0ca074c08d89acf35861c2553de7056e372c2
|
Ruby
|
Joicyg/joicy1
|
/AssignmentDay5/inheritance.rb
|
UTF-8
| 242
| 3.703125
| 4
|
[] |
no_license
|
class Animal
def display_msg
puts "Some animals gives birth"
end
end
class Dog < Animal
def display_msg
super()
puts "Dogs give birth to babydogs"
end
def barks
puts "Dogs barks"
end
end
d = Dog.new
d.display_msg
d.barks
| true
|
b9ee071e176d8331901f420fa91e818ed654a71a
|
Ruby
|
dwhenry/co-engine
|
/spec/co-engine/loaders/json_loader_spec.rb
|
UTF-8
| 5,338
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
require 'co_engine'
RSpec.describe CoEngine::Loaders::JsonLoader do
let(:game_type) { nil }
describe '#load' do
subject { described_class.new(game_data.merge(game_type: game_type)) }
context 'loading a game without players' do
it 'when no player data it raises an error' do
expect { described_class.new({}).load }.to raise_error(CoEngine::InvalidPlayerData, 'must be passed an array of player details')
end
it 'when empty player data it raises an error' do
expect { described_class.new({player: []}).load }.to raise_error(CoEngine::InvalidPlayerData, 'must be passed an array of player details')
end
end
context 'newly created game' do
let(:game_data) { { players: [nil, nil] } }
it 'does not raise any errors' do
expect { subject }.not_to raise_error
end
it 'has a state of "waiting for players"' do
expect(subject.state).to eq(CoEngine::WaitingForPlayers)
end
it 'does not have a player' do
expect(subject.current_player).to be_nil
end
end
context 'game with players' do
let(:game_data) { { players: [{id: 345}, {id: 567}] } }
it 'has a state of "initial tile selection"' do
expect(subject.state).to eq(CoEngine::InitialTileSelection)
end
context ', all finalized initial selection' do
let(:game_data) { { players: [{id: 345}, {id: 567}], turns: turns } }
context ', last turn has a state of CoEngine::TileSelection' do
let(:turns) { [{type: CoEngine::HAND_FINALIZED}, {type: CoEngine::HAND_FINALIZED}, {state: CoEngine::TileSelection.to_s}] }
it 'has a state of "tile selection"' do
expect(subject.state).to eq(CoEngine::TileSelection)
end
it 'has a current player set to the first player' do
player = CoEngine::Player.new(id: 345)
expect(subject.current_player).to eq(player)
end
end
context ', last turn has a state of CoEngine::GuessTile' do
let(:turns) { [{type: CoEngine::HAND_FINALIZED}, {type: CoEngine::HAND_FINALIZED}, {state: CoEngine::GuessTile.to_s}] }
it 'has a state of "tile selection"' do
expect(subject.state).to eq(CoEngine::GuessTile)
end
it 'has a current player set to the first player' do
player = CoEngine::Player.new(id: 345)
expect(subject.current_player).to eq(player)
end
end
context ', last turn has an invalid state' do
let(:turns) { [{type: CoEngine::HAND_FINALIZED}, {type: CoEngine::HAND_FINALIZED}, {state: 'OtherState'}] }
it 'has a state of "tile selection"' do
expect { subject.state }.to raise_error(CoEngine::CorruptGame, "invalid game state detected: 'OtherState'")
end
end
end
it 'has a no current player' do
expect(subject.current_player).to be nil
end
end
context 'game with two players' do
let(:game_data) { { players: [{id: 345}, {id: 567}], turns: [{type: CoEngine::HAND_FINALIZED}, {type: CoEngine::HAND_FINALIZED}] } }
let(:player_1) { CoEngine::Player.new(id: 345) }
let(:player_2) { CoEngine::Player.new(id: 567) }
it 'when one turn as been completed' do
game_data[:turns] << {state: CoEngine::Completed.to_s} << {state: CoEngine::TileSelection.to_s}
game = described_class.new(game_data)
expect(game.current_player).to eq(player_2)
end
it 'when two turn as been completed' do
game_data[:turns] << {state: CoEngine::Completed.to_s} << {state: CoEngine::Completed.to_s} << {state: CoEngine::TileSelection.to_s}
game = described_class.new(game_data)
expect(game.current_player).to eq(player_1)
end
end
context 'game with tiles' do
let(:game_data) { { players: [{id: 345}, {id: 567}], tiles: [{color: 'black', value: 1}, {color: 'black', value: 5}] } }
it 'reads the tile data from the array' do
expect(subject.tiles).to eq([
CoEngine::Tile.new(color: 'black', value: 1),
CoEngine::Tile.new(color: 'black', value: 5),
])
end
end
context 'tile initialization' do
let(:game_data) { { players: [{id: 345}, {id: 567}] } }
context 'when game_type is not set' do
it 'only has numbered tiles' do
expect(subject.tiles.select { |t| t.value.nil? }).to eq([])
end
end
context 'when game_type is -1' do
let(:game_type) { -1 }
it 'only has numbered tiles' do
expect(subject.tiles.select { |t| t.value.nil? }).to eq([])
end
end
context 'when game_type is 0' do
let(:game_type) { 0 }
it 'expects a black blank tile' do
expect(subject.tiles.select { |t| t.value.nil? }).to eq([CoEngine::Tile.new(color: 'black', value: nil)])
end
end
context 'when game_type is 1' do
let(:game_type) { 1 }
it 'expects white and black blank tiles' do
expect(subject.tiles.select { |t| t.value.nil? }).to match_array([
CoEngine::Tile.new(color: 'white', value: nil),
CoEngine::Tile.new(color: 'black', value: nil),
])
end
end
end
end
end
| true
|
ffba8b7ddd4a25050ee66fe7f823970460f0ae84
|
Ruby
|
codehaus/damagecontrol
|
/rscm/lib/rscm/command_line.rb
|
UTF-8
| 2,609
| 2.75
| 3
|
[] |
no_license
|
module RSCM
# Utility for running a +cmd+ in a +dir+ with a specified +env+.
# If a block is passed, the standard out stream is passed to that block (and returns)
# the result from the block. Otherwise, if a block is not passed, standard output
# is redirected to +stdout_file+. The standard error stream is always redirected
# to +stderr_file+. Note that both +stdout_file+ and +stderr_file+ must always
# be specified with non-nil values, as both of them will always have the command lines
# written to them.
module CommandLine
class OptionError < StandardError; end
class ExecutionError < StandardError
attr_reader :cmd, :dir, :exitstatus, :stderr
def initialize(cmd, dir, exitstatus, stderr); @cmd, @dir, @exitstatus, @stderr = cmd, dir, exitstatus, stderr; end
def to_s
"\ndir : #{@dir}\n" +
"command : #{@cmd}\n" +
"exitstatus: #{@exitstatus}\n" +
"stderr : #{@stderr}\n"
end
end
def execute(cmd, options={}, &proc)
options = {
:dir => Dir.pwd,
:env => {},
:exitstatus => 0
}.merge(options)
raise OptionError.new(":stdout can't be nil") if options[:stdout].nil?
raise OptionError.new(":stderr can't be nil") if options[:stderr].nil?
options[:stdout] = File.expand_path(options[:stdout])
options[:stderr] = File.expand_path(options[:stderr])
commands = cmd.split("&&").collect{|c| c.strip}
Dir.chdir(options[:dir]) do
redirected_cmd = commands.collect do |c|
redirection = block_given? ? "#{c} 2>> #{options[:stderr]}" : "#{c} >> #{options[:stdout]} 2>> #{options[:stderr]}"
"echo #{RSCM::Platform.prompt} #{c} >> #{options[:stdout]} && " +
"echo #{RSCM::Platform.prompt} #{c} >> #{options[:stderr]} && " +
redirection
end.join(" && ")
options[:env].each{|k,v| ENV[k]=v}
begin
IO.popen(redirected_cmd) do |io|
if(block_given?)
return(proc.call(io))
else
io.read
end
end
rescue Errno::ENOENT => e
File.open(options[:stderr], "a") {|io| io.write(e.message)}
ensure
if($?.exitstatus != options[:exitstatus])
error_message = File.exist?(options[:stderr]) ? File.read(options[:stderr]) : "#{options[:stderr]} doesn't exist"
raise ExecutionError.new(cmd, options[:dir], $?.exitstatus, error_message)
end
end
end
$?.exitstatus
end
module_function :execute
end
end
| true
|
941b3319488cd5c2bb0edf894d5dcb08c4977232
|
Ruby
|
NeilVeira/asdfghjkretb5
|
/app/helpers/people_helper.rb
|
UTF-8
| 2,206
| 2.734375
| 3
|
[] |
no_license
|
module PeopleHelper
private
def get_all_sponsors (person)
Sponsor.where(person_id: person.id)
end
def get_all_players (person)
Player.where(person_id: person.id)
end
def get_all_tournament_organizers (person)
TournamentOrganizer.where(person_id: person.id)
end
def get_all_golf_course_organizers (person)
GolfCourseOrganizer.where(person_id: person.id)
end
def get_all_tickets (person)
Ticket.where(person_id: person.id)
end
def find_tournaments_for (listOfPeople)
@tournamentIds = []
listOfPeople.each do |person|
@tournamentIds << person.tournament.id
end
Tournament.where(id: @tournamentIds).order(sort_column + " " + sort_direction)
end
def find_golf_courses_for (listOfPeople)
golfCourseIds = []
listOfPeople.each do |person|
golfCourseIds << person.golf_course.id
end
GolfCourse.where(id: @golfCourseIds).order(sort_column + " " + sort_direction)
end
public
# returns tournament objects
def get_all_tournaments_as (peopleType, personToFind = current_person) #default arg
case peopleType
when "sponsor"
return find_tournaments_for (get_all_sponsors personToFind)
when "player"
return find_tournaments_for (get_all_players personToFind)
when "tournament_organizer", "organizer"
return find_tournaments_for (get_all_tournament_organizers personToFind)
end
end
# returns golf course objects
def get_all_golf_courses_as (peopleType, personToFind = current_person) #default arg
case peopleType
when "organizer", "golf_course_organizer"
return find_golf_courses_for (get_all_golf_course_organizers personToFind)
end
end
def get_user_tickets (personToFind = current_person)
return get_all_tickets(current_person)
end
def check_Tournaments (tournaments)
c_date = Time.now.to_date
tournaments_displayed = 0
tournaments.each do |t|
t_date = t.date.to_date
days_away = (t_date - c_date).to_i
if days_away >= 0
tournaments_displayed += 1
end
end
if tournaments_displayed >= 1
return true
else
return false
end
end
end
| true
|
1c01b85bc3defe14ea0290bc83c66e06d1c1478d
|
Ruby
|
billiegoatin/LearnRubyWithCodecademy
|
/PlayinWithMethods.rb
|
UTF-8
| 237
| 3.828125
| 4
|
[] |
no_license
|
def greeter(name)
return "hello, " + name
end
#So there is a ? here, why? Billie, look this shit up
def by_three?(number)
if number % 3 == 0
return true
else
return false
end
end
puts greeter("Austin")
puts by_three(9)
| true
|
f1c9306feeb9c51aee232086d0499821551a0ab3
|
Ruby
|
yangsooyeon/code
|
/script.rb
|
UTF-8
| 1,303
| 2.703125
| 3
|
[] |
no_license
|
require 'httparty'
require 'nokogiri'
# 1. naver์ ์ํ๋ ์ ๋ณด๊ฐ ๋ด๊ธด ํ์ด์ง๋ฅผ ์์ฒญ
# 2. naver์๊ฒ ๋ฐ์ ๋ฌธ์ ์์ ์๋ ์ํ๋ ์ ๋ณด๋ฅผ ๋ถ๋ฌ ์จ๋ค.
# 3. ๋ถ๋ฌ์จ ์ ๋ณด๋ฅผ ์ถ๋ ฅ ํ๋ค.
# res = HTTParty.get("http://finance.naver.com/sise/")
# val = Nokogiri::HTML(res).css("#KOSPI_now")
# puts "ํ์ฌ ์ฝ์คํผ ์ง์๋ " + val.text + " ์
๋๋ค."
headers = {
'User-Agent': 'Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; ko-KR))'
}
# res = HTTParty.get("http://www.dcinside.com/")
# val = Nokogiri::HTML(res).css("#rank1 > li:nth-child(1) > a > span.title")
# puts "ํ์ฌ ์ค๊ฒ1์๋ " + val.text + " ์
๋๋ค."
# res = HTTParty.get("https://search.daum.net/search?w=tot&DA=YZR&t__nil_searchbox=btn&sug=&sugo=&q=%EB%B9%84%ED%8A%B8%EC%BD%94%EC%9D%B8", headers: headers)
# val = Nokogiri::HTML(res).css("#speCurrencyColl > div.coll_cont > div > div.wrap_quote > div.graph_quote > div.graph_rate.stock_up > em.currency_value")
# puts val
res = HTTParty.get("https://search.daum.net/search?nil_suggest=btn&nil_ch=&rtupcoll=&w=tot&m=&f=&lpp=&DA=SBC&sug=&sq=&o=&sugo=&q=%ED%99%98%EC%9C%A8", headers: headers)
val = Nokogiri::HTML(res).css("#exchangeColl > div.coll_cont > div > div.wrap_info > div.info_price > div.stock_down.inner_price > em")
puts val
| true
|
cf325e23cab835e5bfd4a5f6f5b0a57c76637096
|
Ruby
|
leticiarina/bandejao-bot
|
/bot/bot_papoco.rb
|
UTF-8
| 914
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
require './utils/constants'
class Bot
class Papoco
def initialize(bot)
@bandejao = bot.bandejao
@bot = bot
end
def start(chat, exists = false)
prng = Random.new( Time.now().to_i )
shots = 11
boom = "POOOW"
if prng.rand(100) >= 90
boom = "..."
end
while shots > 0 do
num = prng.rand(1..shots)
if num > shots
num = shots
end
shots -= num
send_message(
chat,
"pra " * num
)
end
send_message(
chat,
boom
)
end
private # Private methods =================================================
def send_message(chat, text, markup = nil, parse = CONST::PARSE_MODE)
@bot.bot.api.send_message(
chat_id: chat.id,
text: text,
parse_mode: parse,
reply_markup: markup
)
end
end
end
| true
|
481f5c601247630063da576532781a3df7adac9c
|
Ruby
|
sassafracas/SmarterChild
|
/src/modules/events/mention.rb
|
UTF-8
| 305
| 2.609375
| 3
|
[] |
no_license
|
module Bot::DiscordEvents
# This pms a user when bot is mentioned (will replace with something more useful)
module Mention
extend Discordrb::EventContainer
mention do |event|
event.user.pm("Hey #{event.user.name}, don't tell anyone we talked.")
end
end
end
| true
|
4616beb9c42f587ed5b924257d154c3e7532dcd1
|
Ruby
|
ViSual-BBS/identity-idp
|
/lib/tasks/reset_user_passwords.rake
|
UTF-8
| 736
| 2.515625
| 3
|
[
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
namespace :adhoc do
USAGE_WARNING = <<~EMAIL.freeze
WARNING: Running this task without EMAILS argument is a noop
Usage: rake adhoc:reset_passwords_and_notify_users EMAILS=user1@asdf.com,user2@asdf.com
To include an additional message:
rake adhoc:reset_passwords_and_notify_users EMAILS=user1@asdf.com,user2@asdf.com MESSAGE='Your password may have been compromised by a keylogger'
EMAIL
desc 'Reset the passwords for a comma separated list of users'
task reset_passwords_and_notify_users: :environment do
emails_input = ENV['EMAILS']
next warn(USAGE_WARNING) if emails_input.blank?
emails = emails_input.split(',')
emails.each do |email|
ResetPasswordAndNotifyUser.new(email, ENV['MESSAGE']).call
end
end
end
| true
|
598d7b8bd86627b31245128f3bf251c62a54864d
|
Ruby
|
adudley78/ruby-intro-to-arrays-lab-online-web-prework
|
/lib/intro_to_arrays.rb
|
UTF-8
| 511
| 3.53125
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def instantiate_new_array
@my_new_array = [ ]
end
def array_with_two_elements
@my_new_array = ["Element_One", "Element_Two"]
end
def first_element(my_new_array)
my_new_array[0]
end
def third_element(my_new_array)
my_new_array[2]
end
def last_element(my_new_array)
my_new_array[-1]
end
def first_element_with_array_methods(my_new_array)
my_new_array.first
end
def last_element_with_array_methods(my_new_array)
my_new_array.last
end
def length_of_array(my_new_array)
my_new_array.count
end
| true
|
a1234d2803e907d51d23901e60fec4ce63155b33
|
Ruby
|
mageshkumarbe/ruby
|
/ex8.rb
|
UTF-8
| 949
| 4.0625
| 4
|
[] |
no_license
|
formatter = "%{first} %{second} %{third} %{fourth}" #Initialized multiple format string using %{} to formatter
puts formatter % {first: 1, second: 2, third: 3, fourth: 4} #Here format strings are took integer values by it's own name,also it prints the format string values
puts formatter % {first: "one", second: "two",third: "three", fourth: "four"} #Here format strings are took string values,and prints the exact quoted values.,
puts formatter % {first: true, second: false, third: true, fourth: false} #Format strings took boolean values here.
puts formatter % {first: formatter, second: formatter, third: formatter, fourth: formatter} #It has printed format string
#Formatter takes multiline quotes and prints the string.also %{} is used same format multiple time.
puts formatter % {
first: "I had this thing.",
second: "That you type up right.",
third: "But it didn't sing.",
fourth: "So i said goodnight."
}
| true
|
cb08dea9bffe387f353edbba33687b37540299a9
|
Ruby
|
MariaTerzieva/Tic-Tac-Toe
|
/app/controllers/players_controller.rb
|
UTF-8
| 1,113
| 3.5
| 4
|
[] |
no_license
|
##
# This class represents the Players Controller which is responsible
# for saving or updating a player and their number of wins in the
# database, printing out the leaderboard and loading an appropriate
# page when there is no winner.
class PlayersController < ApplicationController
##
# Searches for the player by name in the database. If there already
# exists such player in the database, it increments the player's
# number of wins. Otherwise it creates a new player in the database
# with the given name and with number of wins equal to 1.
def save
player = Player.find_by(name: params[:winner])
if player
player.update(number_of_wins: player.number_of_wins.succ)
else
player = Player.new(name: params[:winner], number_of_wins: 1)
player.save
end
end
##
# Prints out all the players and their number of wins that exist in
# the database in a descensding order.
def leaderboard
@players = Player.order(number_of_wins: :desc)
end
##
# Loads an appropriate page with message indicating that there is no
# winner.
def draw
end
end
| true
|
35e799a75ea13eac1d58e81627d9aa1e0625adcf
|
Ruby
|
sethbass14/Gigster
|
/app/models/user.rb
|
UTF-8
| 925
| 2.640625
| 3
|
[] |
no_license
|
class User < ApplicationRecord
has_secure_password
belongs_to :city
has_many :musician_instruments, :foreign_key => "musician_id"
has_many :instruments, through: :musician_instruments
has_many :bookings, :class_name => "Gig", :foreign_key => "leader_id"
has_many :musician_gigs, :foreign_key => "musician_id"
has_many :gigs, through: :musician_gigs
validates :first_name, :last_name, :bio, :age, presence: true
def to_s
self.first_name + " " +self.last_name
end
def leader_dates #as a leader
self.bookings.collect { |booking| booking.date }
end
def gig_dates
self.gigs.collect { |gig| gig.date}
end
def booked_dates
leader_dates.concat(gig_dates)
end
def available(date)
!booked_dates.include?(date)
end
def ordered_bookings
self.bookings.sort_by { | booking| booking.date }
end
def ordered_gigs
self.gigs.sort_by { | gig | gig.date }
end
end
| true
|
d8214721ec56487371aa4eacd244f53755bec309
|
Ruby
|
supersquashman/character-generator
|
/Resources/Books/PHB/Feats/two-weapon_fighting_feats.rb
|
UTF-8
| 2,554
| 2.953125
| 3
|
[] |
no_license
|
#require "FeatList"
# require 'pathname'
# require Pathname(__FILE__).ascend{|d| h=d+'FeatList.rb'; break h if h.file?}
class TwoWeaponFighting < FeatModel
@bonus_classes = ["Fighter", "Ranger(Melee)"]
def initialize
super
@title = "Two-Weapon Fighting"
@description = "You can fight with a weapon in each hand. You can make one extra attack each round with the second weapon."
@page = "PHB??"
@link = ""
end
def self.available?(char)
return !feat_taken(char) && char.stats["dex"] >= 15
end
def self.is_bonus_feat?(class_type)
return @bonus_classes.include?(class_type)
end
end
class TwoWeaponDefense < FeatModel
@bonus_classes = ["Fighter", "Ranger(Melee)"]
def initialize
super
@title = "Two-Weapon Defense"
@description = "+1 Shield bonus when fighting with a double weapon or a weapon in each hand. (+2 when fighting defensively or using total defense.)"
@page = "PHB??"
@link = ""
end
def self.available?(char)
return !feat_taken(char) && char.stats["dex"] >= 15 && TwoWeaponFighting.feat_taken(char)
end
def self.is_bonus_feat?(class_type)
return @bonus_classes.include?(class_type)
end
end
class ImprovedTwoWeaponFighting < FeatModel
@bonus_classes = ["Fighter", "Ranger(Melee)"]
def initialize
super
@title = "Two-Weapon Fighting (Improved)"
@description = "In addition to the standard single extra attack you get with an off-hand weapon, you get a second attack with it, albeit at a -5 penalty."
@page = "PHB??"
@link = ""
end
def self.available?(char)
return !feat_taken(char) && char.stats["dex"] >= 17 && TwoWeaponFighting.feat_taken(char) && char.BAB >= 6
end
def self.is_bonus_feat?(class_type)
return @bonus_classes.include?(class_type)
end
end
class GreaterTwoWeaponFighting < FeatModel
@bonus_classes = ["Fighter", "Ranger(Melee)"]
def initialize
super
@title = "Two-Weapon Fighting (Greater)"
@description = "You get a third attack with your off-hand weapon, albeit at a -10 penalty."
@page = "PHB??"
@link = ""
end
def self.available?(char)
return !feat_taken(char) && char.stats["dex"] >= 19 && TwoWeaponFighting.feat_taken(char) && ImprovedTwoWeaponFighting.feat_taken(char) && char.BAB >= 11
end
def self.is_bonus_feat?(class_type)
return @bonus_classes.include?(class_type)
end
end
FeatList.push(TwoWeaponDefense)
FeatList.push(TwoWeaponFighting)
FeatList.push(ImprovedTwoWeaponFighting)
FeatList.push(GreaterTwoWeaponFighting)
| true
|
bff62e639ea493f5112c19cf5474387a8843183c
|
Ruby
|
KamalMicheal/flower_shop
|
/spec/app/flower_shop_spec.rb
|
UTF-8
| 2,137
| 2.84375
| 3
|
[] |
no_license
|
require 'spec_helper'
describe FlowerShop do
let(:flowers) do
[
{
name: 'Roses',
code: 'R12',
bundles: [
{ quantity: 5, price: 6.99 },
{ quantity: 10, price: 12.99 }
]
},
{
name: 'Lilies',
code: 'L09',
bundles: [
{ quantity: 3, price: 9.95 },
{ quantity: 6, price: 16.95 },
{ quantity: 9, price: 24.95 }
]
},
{
name: 'Tulips',
code: 'T58',
bundles: [
{ quantity: 3, price: 5.95 },
{ quantity: 5, price: 9.95 },
{ quantity: 9, price: 16.99 }
]
}
]
end
let(:flower_shop) { FlowerShop.new(flowers) }
context 'when invalid order arrives' do
let(:invalid_order_items) do
[{ code: 'R1', quantity: 5 }]
end
it 'should raise an error' do
expect { flower_shop.order(invalid_order_items) }.to raise_error(ArgumentError)
end
end
context 'when the order items are valid' do
let(:valid_order_items) do
[
{ quantity: 10, code: 'R12' },
{ quantity: 15, code: 'L09' },
{ quantity: 13, code: 'T58' }
]
end
let(:expected_output) do
[
{
flower: 'R12',
quantity: 10,
bundles: [{ quantity: 1, size: 10, price: 12.99 }],
total_price: 12.99
},
{
flower: 'L09',
quantity: 15,
bundles: [
{ quantity: 1, size: 9, price: 24.95 },
{ quantity: 1, size: 6, price: 16.95 }
],
total_price: 41.90
},
{
flower: 'T58',
quantity: 13,
bundles: [
{ quantity: 2, size: 5, price: 9.95 },
{ quantity: 1, size: 3, price: 5.95 }
],
total_price: 25.85
}
]
end
it 'should not raise errors' do
expect { flower_shop.order(valid_order_items) }.not_to raise_error
end
it 'should return the required output' do
expect(flower_shop.order(valid_order_items)).to eq expected_output
end
end
end
| true
|
8757765f6cd41ce7d2d19e45ea97760a8929e9ae
|
Ruby
|
alizawren/game
|
/main.rb
|
UTF-8
| 494
| 2.671875
| 3
|
[] |
no_license
|
require "gosu"
require_relative "./SceneManager.rb"
require_relative "./scenes/TitleScene.rb"
class Main < Gosu::Window
def initialize
super 1280, 720
self.caption = "Game?"
SceneManager.run
end
def update
SceneManager.update(mouse_x, mouse_y)
end
def draw
SceneManager.draw
end
def button_down(id)
SceneManager.button_down(id, method(:close))
if id == Gosu::KB_ESCAPE
SceneManager.run
else
super
end
end
end
Main.new.show
| true
|
6dd8d5fb49626179f024fb1e7dd03e2ce4222317
|
Ruby
|
dombarnes/firelog
|
/config/initializers/time_formats.rb
|
UTF-8
| 245
| 2.515625
| 3
|
[] |
no_license
|
Time::DATE_FORMATS[:default] = "%H:%M"
Date::DATE_FORMATS[:default] = "%e %b %Y"
DateTime::DATE_FORMATS[:default] = "%e %b %Y"
DEFAULT_DATETIME_FORMAT = "%a %-d %b %H:%M"
class DateTime
def to_s
strftime DEFAULT_DATETIME_FORMAT
end
end
| true
|
49297c2039b4281bdf3059ef9ce817447a7945bb
|
Ruby
|
klavinslab/nursery
|
/auto/rehearse/69.rb
|
UTF-8
| 399
| 2.640625
| 3
|
[] |
no_license
|
class Protocol
def main
o = op input
o.input.all.take
# Todo: Figure out how many gels to pour based on the number of threads (o.threads.length)
show {
title "#{o.name} Inputs"
note "Detailed instructions for pouring a gel go here"
}
o.output.all.produce
o.input.all.release
o.output.all.release
return o.result
end
end
| true
|
6b956c534fab88f0a4bd5066749952b301bb7caf
|
Ruby
|
synthresin/jfk
|
/app/models/user.rb
|
UTF-8
| 1,467
| 2.640625
| 3
|
[] |
no_license
|
# encoding: utf-8
require 'bcrypt'
class User < ActiveRecord::Base
attr_accessor :password, :password_confirmation
attr_accessible :email, :password, :password_confirmation
before_save :encrypt_password
include BCrypt
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :password, :presence => {:message => '๋น๋ฐ๋ฒํธ๋ฅผ ์
๋ ฅํด์ฃผ์ธ์.'},
:confirmation => {:message => '๋์ผํ ๋น๋ฐ๋ฒํธ๋ฅผ ๋๋ฒ ์
๋ ฅํด์ฃผ์ธ์.'},
:on => :create
validates :password_confirmation, :presence => true,
:on => :create
validates :email, :format => { :with => email_regex, :message => '์๋ชป๋ ์ด๋ฉ์ผ ํ์์
๋๋ค.' },
:presence => {:message => '์ด๋ฉ์ผ ์ฃผ์๋ฅผ ์
๋ ฅํด์ฃผ์ธ์.'},
:uniqueness => true
# def password
# @password ||= Password.new(encrypted_password)
# end
# def password=(new_password)
# @password = Password.create(new_password)
# self.encrypted_password = @password
# end
def is_admin?
self.admin
end
def has_password?(submitted_password)
Password.new(self.encrypted_password) == submitted_password
end
def self.authenticate(email, submitted_password)
user = find_by_email(email)
return nil if user.nil?
return user if user.has_password?(submitted_password)
end
private
def encrypt_password
self.encrypted_password = Password.create(password)
end
end
| true
|
5c63c32a09a03b5b492a2652db2a79352d779d19
|
Ruby
|
Jose-N/Launch-Academy-Week-1
|
/blackjack/spec/lib/deck_spec.rb
|
UTF-8
| 1,897
| 3.21875
| 3
|
[] |
no_license
|
require "spec_helper"
require_relative "../../lib/deck.rb"
RSpec.describe Deck do
describe "#initialize" do
let (:test_deck) {Deck.new}
context "should create a new deck of cards" do
it "it should have 52 cards total" do
expect(test_deck.deck.size).to eq(52)
end
it "it should have 13 cards of heart suit" do
heart = []
test_deck.deck.each do |card|
if card.suit == "Heart"
heart << card
end
end
expect(heart.size).to eq(13)
end
it "it should have 13 cards of spade suit" do
spade = []
test_deck.deck.each do |card|
if card.suit == "Spade"
spade << card
end
end
expect(spade.size).to eq(13)
end
it "it should have 13 cards of club suit" do
club = []
test_deck.deck.each do |card|
if card.suit == "Club"
club << card
end
end
expect(club.size).to eq(13)
end
it "it should have 13 cards of diamond" do
diamond = []
test_deck.deck.each do |card|
if card.suit == "Diamond"
diamond << card
end
end
expect(diamond.size).to eq(13)
end
end
end
describe "#shuffle!" do
let (:test_deck) {Deck.new}
let (:compare_deck) {Deck.new}
context "should shuffle the deck" do
it "shuffled deck should not equal the original deck" do
test_deck.shuffle!
expect(test_deck).not_to eq(compare_deck)
end
end
end
describe "#deal" do
let (:test_deck) {Deck.new}
let (:compare_deck) {Deck.new}
context "should deal a card" do
it "it should return the last card in the deck, and remove it from the deck" do
expect(test_deck.deal.name).to eq(compare_deck.deck[-1].name)
end
end
end
end
| true
|
7a97bb235075fac3f4ee946adcaccdd8b5249a70
|
Ruby
|
AgileVentures/shf-project
|
/app/services/memberships/renew_membership_actions.rb
|
UTF-8
| 909
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
#--------------------------
#
# @class Memberships::RenewMembershipActions
#
# @desc Responsibility: Do all the things that need to be done when a membership is renewed.
#
#
# @author Ashley Engelund (ashley.engelund@gmail.com weedySeaDragon @ github)
# @date 2022-05=21
#
# TODO: what if they are a current_member and the last day > the date?
# end the current membership on (date - 1 day) and start the new one on the date?
#--------------------------------------------------------------------------------------------------
module Memberships
class RenewMembershipActions < NewRenewMembershipActions
LOGMSG_MEMBERSHIP_RENEWED = 'Membership renewed' unless defined? LOGMSG_MEMBERSHIP_RENEWED
def self.mailer_class
MemberMailer
end
def self.mailer_method
:membership_renewed
end
def self.log_message_success
LOGMSG_MEMBERSHIP_RENEWED
end
end
end
| true
|
d81a4dbc8b1e19a429ad49d2b410d9a2dd39ed52
|
Ruby
|
patty-cc/Day-01_classes_homework
|
/cohort_student.rb
|
UTF-8
| 511
| 3.265625
| 3
|
[] |
no_license
|
class CohortStudent
def initialize ( student_name, cohort_number)
@cohort_number = cohort_number
@student_name = student_name
end
def student_name
return @student_name
end
def cohort_number
return @cohort_number
end
def student_speech
return "I can talk"
end
def prog_lang(language)
return "I Love #{language}"
end
def set_student_name(name)
return @student_name = name
end
def set_cohort_number(number)
return @cohort_number = number
end
end
| true
|
711c0f1032395039851dcbde58a3c2e2ffdfdbe5
|
Ruby
|
hope-andrew/app-academy
|
/w2d5/poker/lib/hand.rb
|
UTF-8
| 2,011
| 3.4375
| 3
|
[] |
no_license
|
require 'card'
require 'byebug'
class Hand
attr_reader :cards
def categories
[ :straight_flush,
:four_of_a_kind,
:full_house,
:flush,
:straight,
:three_of_a_kind,
:two_pair,
:one_pair,
:high_card
]
end
def initialize(cards)
@cards = cards
end
def best_hand
categories.each do |category|
result = self.send("#{category}?")
return [category, result] if result
end
# if flush = straight_flush?
# [:straight_flush, flush]
# elsif four = four_of_a_kind?
# [:four_of_a_kind, four]
# elsif full_house = full_house?
# [:full_house, full_house]
# elsif flush = flush?
# [:flush, flush]
# elsif straight = straight?
# [:straight, straight]
# elsif three = three_of_a_kind?
# [:three_of_a_kind, three]
# elsif two_pair = two_pair?
# [:two_pair, two_pair]
# elsif one_pair = one_pair?
# [:one_pair, one_pair]
# else
# [:high_card, [sort.first]]
# end
end
def beats?(other_hand)
end
private
def sort
cards.sort_by(&:value).reverse
end
def straight_flush?
(straight? && flush?) ? sort : false
end
def full_house?
of_a_kind?(3) && of_a_kind?(2)
end
def straight?
sorted_cards = sort
straight = (0...cards.length-1).all? do |i|
sorted_cards[i].value - sorted_cards[i+1].value == 1
end
straight ? sort : false
end
def flush?
cards.all? { |card| card.suit == cards.first.suit } ? sort : false
end
def of_a_kind?(n)
counts = Hash.new(0)
cards.each { |card| counts[card.name] += 1 }
if name = counts.key(n)
cards.select { |card| card.name == name }
else
false
end
end
def four_of_a_kind?
of_a_kind?(4)
end
def three_of_a_kind?
of_a_kind?(3)
end
def one_pair?
of_a_kind?(2)
end
def two_pair?
# fix later
cards.map(&:name).uniq.count == 3
end
def high_card?
[sort.first]
end
end
| true
|
7e1938cc85b5983537b2e7ad8411b214ad1388a4
|
Ruby
|
trizen/sidef
|
/scripts/RosettaCode/multifactorial.sf
|
UTF-8
| 223
| 3.234375
| 3
|
[
"Artistic-2.0"
] |
permissive
|
#!/usr/bin/ruby
#
## http://rosettacode.org/wiki/Multifactorial
#
func mfact(s, n) {
n > 0ย ? (n * mfact(s, n-s))ย : 1;
}
ย
for s in range(1, 10) {
say "step=#{s}: #{1..10 -> map {|n| mfact(s, n)}.join(' ')}";
}
| true
|
24617a693a9ab0ae94076735a384904c997bbfe7
|
Ruby
|
JevanWu/huali
|
/app/values/discount.rb
|
UTF-8
| 472
| 3.34375
| 3
|
[] |
no_license
|
class Discount
attr_reader :operator, :number
def initialize(adjustment)
unless adjustment =~ %r{\A[+-x*%/][\s\d.]+\z}
raise "Invalid adjustment string"
end
adjust = adjustment.to_s.squeeze(' ').sub('x', '*').sub('%', '/')
@operator = adjust.first.to_sym
@number = adjust[1..-1].to_f
end
def calculate(amount)
amount.send(operator, number)
end
def ==(other)
operator == other.operator && number == other.number
end
end
| true
|
cafd186c4021e8a5343ee0b550f2052da47290f2
|
Ruby
|
Aymane11/30-Days-of-Code
|
/Solutions/Day6/solution.rb
|
UTF-8
| 303
| 3.640625
| 4
|
[] |
no_license
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
t = gets.to_i
t.times{
txt = gets.chomp
ev = ""
od = ""
(0...txt.size).each{ |i|
if i%2==0
ev << txt[i]
else
od << txt[i]
end
}
puts "#{ev} #{od}"
}
| true
|
353a84d74e6c2eaaa12c7cc114cd75c802876ac2
|
Ruby
|
patch0/feature_flag
|
/spec/feature_flag/lookup_spec.rb
|
UTF-8
| 1,159
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
describe Lookup do
context '#check_flag' do
it 'should return true when ENV variable enabled' do
ENV["FEATURE"] = "true"
Lookup.check_flag('FEATURE').should be_true
end
it 'should return false when no ENV variable found' do
Lookup.check_flag('xxMISINGxx').should be_false
end
it 'should return false when ENV variable empty' do
ENV["FEATURE"] = ""
Lookup.check_flag('FEATURE').should be_false
end
it 'should return false when ENV variable nil' do
ENV["FEATURE"] = nil
Lookup.check_flag('FEATURE').should be_false
end
end
context '#enabled' do
it 'should match true values' do
%w(true t yes y enabled 1).each do |value|
Lookup.enabled(value).should == true
end
end
it 'should not have false positive matches to non-true values' do
%w(untrue not eyes silly unenabled 101).each do |value|
Lookup.enabled(value).should == false
end
end
it 'should match false values' do
%w(false f no n disabled 0).each do |value|
Lookup.enabled(value).should == false
end
end
end
end
| true
|
d503e9f5207f176f230124ec8d2e7ed5cc3a8338
|
Ruby
|
masa-1013/100Questions
|
/28.rb
|
UTF-8
| 435
| 3.03125
| 3
|
[] |
no_license
|
n = gets.to_i
graph = Array.new(n)
n.times do |i|
input = gets.split().map(&:to_i)
tmp = []
input[1].times do |j|
tmp << input[j+2]-1
end
graph[i] = tmp
end
dist = Array.new(n, -1)
queue = []
dist[0] = 0
queue << 0
while !queue.empty?
v = queue.shift
graph[v].each do |i|
next if dist[i] != -1
dist[i] = dist[v] + 1
queue << i
end
end
dist.each_with_index do |i, index|
puts "#{index+1} #{i}"
end
| true
|
5df4d6b5fc0f9dbe8d55b064ee9274fe24738663
|
Ruby
|
joan2kus/ChartDirector
|
/railsdemo/app/controllers/stepline_controller.rb
|
UTF-8
| 3,123
| 2.5625
| 3
|
[
"IJG"
] |
permissive
|
require("chartdirector")
class SteplineController < ApplicationController
def index()
@title = "Step Line Chart"
@ctrl_file = File.expand_path(__FILE__)
@noOfCharts = 1
render :template => "templates/chartview"
end
#
# Render and deliver the chart
#
def getchart()
# The data for the chart
dataY0 = [4, 4.5, 5, 5.25, 5.75, 5.25, 5, 4.5, 4, 3, 2.5, 2.5]
dataX0 = [Time.mktime(1997, 1, 1), Time.mktime(1998, 6, 25), Time.mktime(1999, 9,
6), Time.mktime(2000, 2, 6), Time.mktime(2000, 9, 21), Time.mktime(2001, 3, 4
), Time.mktime(2001, 6, 8), Time.mktime(2002, 2, 4), Time.mktime(2002, 5, 19),
Time.mktime(2002, 8, 16), Time.mktime(2002, 12, 1), Time.mktime(2003, 1, 1)]
dataY1 = [7, 6.5, 6, 5, 6.5, 7, 6, 5.5, 5, 4, 3.5, 3.5]
dataX1 = [Time.mktime(1997, 1, 1), Time.mktime(1997, 7, 1), Time.mktime(1997, 12,
1), Time.mktime(1999, 1, 15), Time.mktime(1999, 6, 9), Time.mktime(2000, 3, 3
), Time.mktime(2000, 8, 13), Time.mktime(2001, 5, 5), Time.mktime(2001, 9, 16
), Time.mktime(2002, 3, 16), Time.mktime(2002, 6, 1), Time.mktime(2003, 1, 1)]
# Create a XYChart object of size 500 x 270 pixels, with a pale blue (e0e0ff)
# background, black border, 1 pixel 3D border effect and rounded corners
c = ChartDirector::XYChart.new(600, 300, 0xe0e0ff, 0x000000, 1)
c.setRoundedFrame()
# Set the plotarea at (55, 60) and of size 520 x 200 pixels, with white (ffffff)
# background. Set horizontal and vertical grid lines to grey (cccccc).
c.setPlotArea(50, 60, 525, 200, 0xffffff, -1, -1, 0xcccccc, 0xcccccc)
# Add a legend box at (55, 32) (top of the chart) with horizontal layout. Use 9
# pts Arial Bold font. Set the background and border color to Transparent.
c.addLegend(55, 32, false, "arialbd.ttf", 9).setBackground(
ChartDirector::Transparent)
# Add a title box to the chart using 15 pts Times Bold Italic font. The text is
# white (ffffff) on a deep blue (000088) background, with soft lighting effect
# from the right side.
c.addTitle("Long Term Interest Rates", "timesbi.ttf", 15, 0xffffff).setBackground(
0x000088, -1, ChartDirector::softLighting(ChartDirector::Right))
# Set the y axis label format to display a percentage sign
c.yAxis().setLabelFormat("{value}%")
# Add a red (ff0000) step line layer to the chart and set the line width to 2
# pixels
layer0 = c.addStepLineLayer(dataY0, 0xff0000, "Country AAA")
layer0.setXData(dataX0)
layer0.setLineWidth(2)
# Add a blue (0000ff) step line layer to the chart and set the line width to 2
# pixels
layer1 = c.addStepLineLayer(dataY1, 0x0000ff, "Country BBB")
layer1.setXData(dataX1)
layer1.setLineWidth(2)
# Output the chart
send_data(c.makeChart2(ChartDirector::PNG), :type => "image/png",
:disposition => "inline")
end
end
| true
|
372c47cf7fc1ecbd16599dfc816daafcf7a86dc4
|
Ruby
|
trollsk1n/test_ruby
|
/animal.rb
|
UTF-8
| 966
| 4.21875
| 4
|
[] |
no_license
|
# frozen_string_literal: true
# Animal superclass
class Animal
attr_reader :name, :age
def name=(value)
raise "Name can't be blank!" if value == ''
@name = value
end
def age=(value)
raise "An age of #{value} isn't valid" if value.negative?
@age = value
end
def talk
puts "#{@name} says Bark!"
end
def move(destination)
puts "#{@name} runs to #{destination}"
end
def report_age
puts "#{@name} is #{age} years old"
end
end
# Dog class extends Animal
class Dog < Animal
# to_s for write object as string
def to_s
puts "#{@name} the dog, age #{@age}"
end
end
# Cat class extends Animal
class Cat < Animal
def talk
puts "#{@name} says Meow!"
end
end
# Bird class extends Animal
class Bird < Animal
def talk
puts "#{@name} says Chirp! Chirp!"
end
end
# Armadillo class extends Animal
class Armadillo < Animal
def move(destination)
puts "#{@name} unrolls!"
super
end
end
| true
|
4382c0d35649e7fb807e94190e5876b94bbcabae
|
Ruby
|
AaronC81/quickspcr
|
/src/quickspcr/prompt.rb
|
UTF-8
| 526
| 2.515625
| 3
|
[] |
no_license
|
require_relative 'spcr'
require 'shellwords'
# Handles displaying a prompt and launching the browser if necessary.
class Prompt
def self.show(app_id, app_name)
message = %W[
Looks like you've been playing #{app_name}. Would you like to
compose a report for it on SPCR?
].join(' ')
system(%W[
zenity --question --width 600 --title QuickSPCR
--text "#{Shellwords.escape(message)}"
].join(' '))
return unless $?.exitstatus.zero?
Spcr.open_contribution_page(app_id)
end
end
| true
|
e558651e3e7367f8d4293c3363e21f5a54e37b93
|
Ruby
|
Christof/SimpleGnuplot
|
/Gnuplot.rb
|
UTF-8
| 4,495
| 2.53125
| 3
|
[] |
no_license
|
require 'narray'
require './NArray_Extensions.rb'
class Gnuplot
attr_accessor :synchronize
attr_accessor :debug
attr_accessor :replot
def initialize(gnuplot_path = "pgnuplot", dump_file = nil)
@gnuplot_path = gnuplot_path
if dump_file
@stream = File.new(dump_file, "w")
@is_process = false
else
@stream = IO.popen(@gnuplot_path, "w")
@is_process = true
@stream.sync = true
end
@temp_files = []
sleep 0.5
end
def Gnuplot.open(gnuplot_path = "gnuplot", &lambda)
g = Gnuplot.new(gnuplot_path)
if block_given?
lambda.call(g)
g.close
end
g
end
def Gnuplot.open_interactive(gnuplot_path = "pgnuplot", &lambda)
g = Gnuplot.new(gnuplot_path)
if block_given?
lambda.call(g)
g.close
end
g
end
def Gnuplot.dump_script_to(filename, &lambda)
g = Gnuplot.new(nil, filename)
if block_given?
lambda.call(g)
g.close
end
g
end
def load(script)
send(%Q{l "#{script}"})
end
def terminal=(args)
if args.length == 2
send("se t #{args[0]} #{args[1]}")
else
send("se t #{args}")
end
@replot_not_first_plot = false
end
def output=(filename)
send(%Q{se out "#{filename}"})
@replot_not_first_plot = false
end
def xlabel=(text)
send(%Q{se xl "#{text}"})
end
def ylabel=(text)
send(%Q{se yl "#{text}"})
end
def y2label=(text)
send(%Q{se y2l "#{text}"})
end
def ytics=(args)
send("se yti #{args[0]}, #{args[1]}")
end
def y2tics=(args)
send("se y2ti #{args[0]}, #{args[1]}")
send("se yti nomi")
end
def xrange=(args)
send "se xr [#{args[0]}:#{args[1]}]"
end
def yrange=(args)
send "se yr [#{args[0]}:#{args[1]}]"
end
def y2range=(args)
send "se y2r [#{args[0]}:#{args[1]}]"
end
def set_log(text)
send("se log #{text}")
end
def unset_log(text = "")
send("uns log #{text}")
end
def set(arg)
send("se #{arg}")
end
def unset(arg)
send("uns #{arg}")
end
def title=(t)
send(%Q{se tit "#{t}"})
end
def pause(l = -1)
send("pa #{l}")
end
def unset_output
send("uns out")
@stream.flush
@replot_not_first_plot = false
end
alias :flush :unset_output
def reset
send("reset")
end
def with_file(in_file)
@in_file = in_file
self
end
def with_data(data)
s = ""
if data.is_a?(NArray)
if data.dim == 1
data.each do |x|
s << x.to_s << "\n"
end
else
s = data.to_gplot
end
else
s = data.to_s
end
@temp_data = s
self
end
def prepare_plot_command(args)
local_args = args.clone
if local_args.has_key? :title
local_args[:title] = %Q{"#{args[:title]}"}
end
if local_args.has_key? :f
local_args.delete :f
end
a = local_args.inject("") { |res, elem| res << elem[0].to_s << " " << elem[1].to_s << " " }
a.gsub('title ""', 'notitle')
end
private :prepare_plot_command
def _plot_command
if @replot
cmd = @replot_not_first_plot ? 'rep' : 'p'
@replot_not_first_plot = true
cmd
else
'p'
end
end
def plot(args)
a = prepare_plot_command(args)
if args.has_key? :f
send(%Q{#{_plot_command} #{args[:f]} #{a}})
else
send(%Q{#{_plot_command} "#{@temp_data ? '-' : @in_file}" #{a}})
end
if @temp_data
send(%Q{#{@temp_data}\ne\n})
@temp_data = nil
end
end
def multiplot(arr)
a = arr.collect do |args|
prepare_plot_command args
end
a = a.join(', "" ')
send(%Q{#{_plot_command} "#{@temp_data ? '-' : @in_file}" #{a}})
arr.length.times do
if @temp_data
send(%Q{#{@temp_data}\ne\n})
end
end
@temp_data = nil
end
def splot(args)
a = prepare_plot_command(args)
send(%Q{sp "#{@temp_data ? '-' : @in_file}" #{a}})
if @is_process and @synchronize
send("pr 1")
tmp = @stream.readpartial(1)
puts tmp
end
end
def multisplot(arr)
a = arr.collect do |args|
prepare_plot_command args
end
a = a.join(%Q{, "#{@temp_data ? '-' : @in_file}" })
send(%Q{sp "#{@temp_data ? '-' : @in_file}" #{a}})
arr.length.times do
if @temp_data
send(%Q{#{@temp_data}\ne\n})
end
end
@temp_data = nil
end
def replot
send("re")
end
def send(command)
@stream << (command << "\n")
end
private :send
def hold
send "pa mouse"
end
def close
send("exit")
@stream.close
end
end
| true
|
7996b51513d88aa43ff7767b9acfee064edb84b0
|
Ruby
|
malachaifrazier/Beatstream
|
/app/services/media_reader.rb
|
UTF-8
| 1,220
| 2.640625
| 3
|
[
"LicenseRef-scancode-other-permissive"
] |
permissive
|
require 'find'
class MediaReader
MUSIC_PATH = Rails.application.config.music_paths.to_s
SONGS_JSON_FILE = Rails.root.join('data', 'songs.json').to_s
def self.MUSIC_PATH
MUSIC_PATH
end
def self.SONGS_JSON_FILE
SONGS_JSON_FILE
end
def self.all
songs_file.read
end
def self.create_song(path, index)
begin
Song.new_from_mp3_file(path, index + 1)
rescue Exception => e
Rails.logger.info "Failed to load media: #{path}"
Rails.logger.info e
end
end
def self.files(path)
Dir.chdir(path)
return Dir['**/*.{mp3,MP3}']
end
def self.refresh
songs = files(MUSIC_PATH).each_with_index.map {|f,i| create_song(f, i)}
.select {|s| s.is_a?(Song)}
.sort_by &:to_natural_sort_string
songs_file('w').write(songs.to_json)
end
def self.songs_file(mode = 'r')
begin
file = File.open(SONGS_JSON_FILE, mode)
Rails.logger.info "Songs JSON last modified on #{file.mtime.to_s}"
rescue Errno::ENOENT => e
# File not found
FileUtils.touch(SONGS_JSON_FILE)
file = File.open(SONGS_JSON_FILE, mode)
Rails.logger.info "Songs JSON last modified on #{file.mtime.to_s}"
end
return file
end
end
| true
|
da584252a1f9b4e0a0f676ed3f6ac9d6ee2891d4
|
Ruby
|
RubyCamp/rc2018sp_g5
|
/practice15/Scene/Lib/Enemy.rb
|
UTF-8
| 588
| 2.71875
| 3
|
[] |
no_license
|
#encoding :Shift_JIS
class Enemy < Sprite
def initialize(x,y)
super
self.x = x
self.y = y
self.image = Image.load('Scene/images/enemy.png')
@y_move = 5
end
def update
self.draw
self.x -= 10
self.y += @y_move
if self.x < 0
self.vanish
end
end
def hit
self.vanish
end
def shot
self.vanish
end
def shot_tile
@y_move -= rand(5) + 1
end
def shot_sky
@y_move += rand(5) + 1
end
end
| true
|
1931bf3c3ed43f71833ada1070a98f836b208dab
|
Ruby
|
toddt67878/Build_a-File_Type_Hash_Mapper_in_Ruby
|
/Build_a File_Type_Hash_Mapper_in_Ruby.rb
|
UTF-8
| 898
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
require 'rspec'
class Array
def file_type_mapper
each_with_object(Hash.new { |h, k| h[k] = [] }) do |file, hash|
file_ext = File.extname(file)[1..-1]
hash[file_ext] = hash[file_ext].push(file.chomp!('.' + file_ext))
end
end
end
describe 'File selector' do
it 'converts an array of file names into a hash where each file type is the key and the name(s) are in an array for the value' do
file_names = %w{file1.rb file2.html file3.rb file4.rb file5.js}
expect(file_names.file_type_mapper).to eq({
'rb' => ['file1', 'file3', 'file4'],
'html' => ['file2'],
'js' => ['file5']
})
end
end
file_names = %w{file1.rb file2.html file3.rb file4.rb file5.js}
p file_names.file_type_mapper
| true
|
ecc4af1261bae31bfb077f5a024d9f42e247c7e6
|
Ruby
|
amaxwellblair/module_3_assessment
|
/spec/requests/api/v1/items_spec.rb
|
UTF-8
| 2,050
| 2.546875
| 3
|
[] |
no_license
|
require "rails_helper"
describe "item api" do
it "returns all of the items" do
Item.create(name: "bacon", description: "best kind of bacon", image_url: "www.whocares.com")
Item.create(name: "not bacon", description: "why eat it", image_url: "www.whocares.com")
get "/api/v1/items.json"
expect(response).to be_success
items = JSON.parse(response.body)
expect(items.length).to eq(2)
expect(items.first["name"]).to eq("bacon")
# expect(items.first["created_at"]).to eq(nil)
# expect(items.first["updated_at"]).to eq(nil)
end
it "returns a specific item" do
item = Item.create(name: "bacon", description: "best kind of bacon", image_url: "www.whocares.com")
Item.create(name: "not bacon", description: "why eat it", image_url: "www.whocares.com")
get "/api/v1/items/#{item.id}.json"
expect(response).to be_success
item = JSON.parse(response.body)
expect(item["name"]).to eq("bacon")
# expect(item["created_at"]).to eq(nil)
# expect(item["updated_at"]).to eq(nil)
end
it "deletes a specific item" do
item = Item.create(name: "bacon", description: "best kind of bacon", image_url: "www.whocares.com")
Item.create(name: "not bacon", description: "why eat it", image_url: "www.whocares.com")
delete "/api/v1/items/#{item.id}.json"
expect(response.status).to eq(204)
items = Item.all
expect(items.length).to eq(1)
end
it "creates an item" do
item = Item.create(name: "bacon", description: "best kind of bacon", image_url: "www.whocares.com")
Item.create(name: "not bacon", description: "why eat it", image_url: "www.whocares.com")
post "/api/v1/items.json", parameters: {name: "MeSeeks", description: "AndDestroy", image_url: "www.whocares.com"}
expect(response.status).to eq(201)
item = JSON.parse(response.body)
items = Item.all
expect(items.length).to eq(3)
expect(item["name"]).to eq("MeSeeks")
# expect(item["created_at"]).to eq(nil)
# expect(item["updated_at"]).to eq(nil)
end
end
| true
|
6bb4f697013f553fdb10cb943a2aca693fb3c844
|
Ruby
|
isabella232/cutlass
|
/lib/cutlass/docker_diff.rb
|
UTF-8
| 1,090
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module Cutlass
# Diffs docker images
#
# diff = DockerDiff.new
#
# diff.call.changed? # => false
#
# BashResult.run("docker build .")
#
# diff.call.changed? # => true
class DockerDiff
def initialize(before_ids: nil, get_image_ids_proc: -> { Docker::Image.all.map(&:id) })
@before_ids = before_ids || get_image_ids_proc.call
@get_image_ids_proc = get_image_ids_proc
end
def call
DiffValue.new(
before_ids: @before_ids,
now_ids: @get_image_ids_proc.call
)
end
class DiffValue
attr_reader :diff_ids
def initialize(before_ids:, now_ids:)
@diff_ids = now_ids - before_ids
end
def changed?
@diff_ids.any?
end
def same?
!changed?
end
def leaked_images
diff_ids.map do |id|
Docker::Image.get(id)
end
end
def to_s
leaked_images.map do |image|
" tags: #{image.info["RepoTags"]}, id: #{image.id}"
end.join($/)
end
end
end
end
| true
|
27b9c3c2ef9623940d2ef71302d379c40d541084
|
Ruby
|
ndrluis/mbank
|
/app/models/account.rb
|
UTF-8
| 1,736
| 2.84375
| 3
|
[] |
no_license
|
# frozen_string_literal: true
class Account < ApplicationRecord
has_many :debit_transfers,
-> { Transaction.transfer },
foreign_key: 'source_account_id',
class_name: 'Transaction'
has_many :credit_transfers,
-> { Transaction.transfer },
foreign_key: 'destination_account_id',
class_name: 'Transaction'
has_many :deposits,
-> { Transaction.deposit },
foreign_key: 'source_account_id',
class_name: 'Transaction'
belongs_to :user
def statements
current_balance = 0
transactions.map do |transaction|
amount = transaction.amount
amount = -amount if transaction.debit_for?(self)
current_balance += amount
build_statement(amount, transaction, current_balance)
end
end
def balance
deposits_balance +
credit_transfers_balance -
debit_transfers_balance
end
def enough_balance_to_transfer?(amount)
return unless balance.positive?
!(balance - amount).negative?
end
def formatted_balance
ActiveSupport::NumberHelper.number_to_currency(
balance, locale: :'pt-BR'
)
end
private
def build_statement(amount, transaction, current_balance)
{
amount: amount.to_f,
kind: transaction.kind,
balance: current_balance.to_f,
source: transaction.source_account,
destination: transaction.destination_account
}
end
def transactions
debit_transfers
.or(credit_transfers)
.or(deposits)
end
def credit_transfers_balance
credit_transfers.sum(:amount)
end
def debit_transfers_balance
debit_transfers.sum(:amount)
end
def deposits_balance
deposits.sum(:amount)
end
end
| true
|
a2ada17f8d3b90a3c5437576412d67488c8d0d68
|
Ruby
|
chenyukang/rubytt
|
/tests/cases/gcd.rb
|
UTF-8
| 104
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
def gcd x, y
return x if x == y
if x >= y && y > 0
gcd y, x % y
else
gcd y, x
end
end
| true
|
a025210d806122c47b1ecb8e42767d00983f234a
|
Ruby
|
errm/scraping_ebay
|
/scraper.rb
|
UTF-8
| 1,155
| 3.21875
| 3
|
[] |
no_license
|
require 'wombat'
require 'monetize'
require 'pry'
Monetize.assume_from_symbol = true
class EbayPhone
def initialize(data)
self.name = data['name'].gsub("New listing\r\n\t\t",'')
self.price = Monetize.parse(data['price'])
end
def to_s
"#{name} - #{price.symbol}#{price}"
end
attr_reader :name, :price
protected
attr_writer :name, :price
end
class EbayPhonesScraper
def self.get_phones(search)
new(search).phones
end
def initialize(search)
self.search = search
end
def phones
data.fetch('phones', [])
.map { |d| EbayPhone.new(d) }
.select { |phone| phone.name.match(/#{search}/i) }
.sort_by { |phone| phone.price }
end
protected
attr_accessor :search
private
def data
Wombat.crawl do
base_url "http://www.ebay.co.uk"
path "/sch/Mobile-Smart-Phones-/9355/i.html?_nkw=#{search}"
phones "css=.lvresult", :iterator do
name "css=.lvtitle"
price "css=.lvprice"
end
end
end
end
phones = EbayPhonesScraper.get_phones(ARGV[0])
puts "The Cheepest #{ARGV[0]}"
puts phones.first
puts "The Dearest #{ARGV[0]}"
puts phones.last
| true
|
08f45e4670fd87af7ba03f6c9112435df46fa780
|
Ruby
|
johnsonch/RubyQuizes
|
/fizzbuzz.rb
|
UTF-8
| 1,096
| 4
| 4
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
class Game
def self.fizzbuzz
Array(1..100).map{|x| output(x) }
end
def self.output(statement)
puts is_fizz_buzz?(statement) || is_fizz?(statement) || is_buzz?(statement) || statement
end
def self.is_fizz_buzz?(statement)
is_fizz?(statement) && is_buzz?(statement) ? "fizzbuzz" : false
end
def self.is_fizz?(number)
number.to_i % 3 == 0 ? "fizz" : false
end
def self.is_buzz?(number)
number.to_i % 5 == 0 ? "buzz" : false
end
end
describe "game" do
it 'has a fizzbuzz method' do
Game.fizzbuzz
end
it 'counts to 100' do
Game.should_receive(:output).exactly(100).times
Game.fizzbuzz
end
it 'prints out fizz if number is divisible by 3' do
Game.is_fizz?(3).should == "fizz"
end
it 'does not print out fizz if a number is not divisible by 3' do
Game.is_fizz?(5).should_not == "fizz"
end
it 'prints out buzz if number is divisible by 5' do
Game.is_buzz?(5).should == "buzz"
end
it "prints out fizzbuzz if number is divisible by 3 and 5" do
Game.is_fizz_buzz?(15).should == "fizzbuzz"
end
end
| true
|
d913914c6f9648988546e9fb8dbdd443c82a34c0
|
Ruby
|
kasumi8pon/atcoder_practice
|
/abc/072/d.rb
|
UTF-8
| 201
| 3.046875
| 3
|
[] |
no_license
|
n = gets.to_i
ps = gets.split.map(&:to_i)
answer = 0
(0...n).each do |i|
next if ps[i] != i + 1
answer += 1
ps[i], ps[i + 1] = ps[i + 1], ps[i]
end
answer += 1 if ps[n - 1] == n
puts answer
| true
|
89201cb43656f844aeaff836d86030f168f4e51b
|
Ruby
|
EosLightmedia/whyte_avalanche
|
/lib/http_sender.rb
|
UTF-8
| 732
| 2.515625
| 3
|
[] |
no_license
|
class HTTPSender
attr_accessor :port, :domain, :log_http, :log_body
def initialize(params)
@port = params[:port] || 80
@domain = params[:domain]
@page = params[:page]
@url = "http://#{@domain}/"
mp @url
@client = AFMotion::Client.build(@url)
end
def get(param_key, param_value)
page_and_params = "#{@page}/#{param_key}=#{param_value}"
mp "#{@url}#{page_and_params}" if @log_http
@client.get(page_and_params) do |result|
mp result.body if @log_body
end
nil
end
def simple_get(ip, port, to_send) #this is specific to cueserver and works
AFMotion::HTTP.get("http://#{ip}:#{port}/exe.cgi?cmd=#{to_send}") do |result|
p result.body.to_s
end
end
end
| true
|
6a9506081d61896e7905234ff36402d376c451a9
|
Ruby
|
vanegg/Rubylearning
|
/S2D5/examen_final_fase0.rb
|
UTF-8
| 6,727
| 4.09375
| 4
|
[] |
no_license
|
#Examen Final Fase 0
#Removiendo vocales
#Crea el mรฉtodo vowels que recibe una lista de palabras words y remueve las vocales de cada string. Haz pasar la prueba correspondiente.
def vowels(array)
array.map {|word| word.delete "aeiouAEIOU"}
end
p vowels(["banana", "carrot", "pineapple", "strawberry"]) == ["bnn", "crrt", "pnppl", "strwbrry"]
# Suma de nรบmeros
# Dados dos nรบmeros, que pueden ser positivos y negativos, encuentra
#la suma de todos los nรบmeros entre ellos, incluyendo esos nรบmeros
#tambiรฉn. Si los dos nรบmeros son iguales, regresa alguno de los dos
def get_sum(num1, num2)
menor = num1 < num2 ? num1 : num2
mayor = menor == num1 ? num2 : num1
(menor..mayor).reduce(:+)
end
p get_sum(1, 0) == 1
p get_sum(1, 2) == 3
p get_sum(0, 1) == 1
p get_sum(1, 1) == 1
p get_sum(-1, 0) == -1
p get_sum(-1, 2) == 2
# Palabras y caracteres
# Crea un mรฉtodo que reciba una oraciรณn y regrese un string seรฑalรกndonos el nรบmero de palabras y caracteres que contiene, sin contar los espacios en blanco, tu mรฉtodo deberรก pasar las siguientes pruebas:
def char_word_counter(string)
chars =0
words = string.split.length
string.split.each { |word| chars += word.length }
"This sentence has #{words} words & #{chars} characters"
end
p char_word_counter("This is a sentence") == "This sentence has 4 words & 15 characters"
p char_word_counter("This easy") == "This sentence has 2 words & 8 characters"
p char_word_counter("This is a very complex line of code to test our program") == "This sentence has 12 words & 44 characters"
p char_word_counter("And when she needs a shelter from reality she takes a dip in my daydreams") == "This sentence has 15 words & 59 characters"
# Buscando en hashes
# Ahora vamos a aprovechar los Hashes como herramienta de organizaciรณn para distinguir alimentos por grupo alimenticio. Para esto deberรกs generar un mรฉtodo que tome como parรกmetro un string que contenga una comida, y buscarlo en el siguiente hash, regresando su key como valor de retorno, si no encuentra la comida deberรก regresar "comida no encontrada".
def food_group(string)
food_groups = {
"grano" => ['Arroz','Trigo', 'Avena', 'Cebada', 'Harina'],
"vegetal" => ['Zanahoria', 'Maรญz', 'Elote', 'Calabaza', 'Papa'],
"fruta" => ['Manzana', 'Mango', 'Fresa', 'Durazno', 'Piรฑa'],
"carne" => ['Res', 'Pollo', 'Salmรณn', 'Pescado', 'Cerdo'],
"lรกcteo" => ['Leche', 'Yogur', 'Queso', 'Crema']
}
food_groups.each do |key,array|
array.each { |food| return key if food == string }
end
return "comida no encontrada"
end
# Deberรกs utilizar este Hash como base de tu programa
# Driver code
p food_group('Crema') == "lรกcteo"
p food_group('Res') == "carne"
p food_group('Piรฑa') == "fruta"
p food_group('Caรฑa') == "comida no encontrada"
# Dado
# Define la clase Die. Todos los objetos de esta clase (dados) son creados con un nรบmero de lados definido por el usuario. Ademรกs define un mรฉtodo roll que sea capaz de lanzar el dado y que regrese un nรบmero entre uno y el nรบmero de lados del dado. Ten en cuenta que un dado no puede tener un solo lado, notifรญcale al usuario. Define getters y setters para los lados del dado, y รบsalos. No puedes usar los attr_* que nos da Ruby.
class Die
def initialize(lados)
if lados == 1
p "Un dado no puede tener un sรณlo lado. Tu dado cambio a 2 lados"
@lados = 2
else
@lados = lados
end
end
def lados
@lados
end
def lados=(new_lados)
@lados = new_lados
end
def roll
num = Random.new
num.rand(1..@lados)
end
end
dado1 = Die.new(1)
p dado1.lados == 2
dado1.lados = 4
p dado1.roll <=4
dado2 = Die.new(6)
p dado2.roll <= 6
dado2.lados = 10
p dado2. lados == 10
# Driving
# Crea una clase llamada MyCar. Cuando inicializas un nuevo objeto de la clase se permite al usuario definir las variables de instancia que nos dicen el aรฑo, color y modelo del carro. Crea mรฉtodos de instancia que permiten al carro acelerar, frenar y apagar el carro. Haz pasar todas las pruebas correspondientes.
class MyCar
def initialize(aรฑo,color,modelo)
@aรฑo = aรฑo
@color = color
@modelo = modelo
@speed ||= 0
end
def speed_up(speed)
@speed += speed
"You push the gas and accelerate #{speed} kph."
end
def brake(speed)
@speed -= speed
"You push the brake and decelerate #{speed} kph."
end
def current_speed
"You are now going #{@speed} kph."
end
def shut_down
@speed = 0
"Let's shut down to #{@speed}!"
end
end
carro_prueba = MyCar.new(2000, 'negro', 'Toyota')
# Driver code
p carro_prueba.speed_up(20) == "You push the gas and accelerate 20 kph."
p carro_prueba.current_speed == "You are now going 20 kph."
p carro_prueba.speed_up(20) == "You push the gas and accelerate 20 kph."
p carro_prueba.current_speed == "You are now going 40 kph."
p carro_prueba.brake(20) == "You push the brake and decelerate 20 kph."
p carro_prueba.current_speed == "You are now going 20 kph."
p carro_prueba.brake(20) == "You push the brake and decelerate 20 kph."
p carro_prueba.current_speed == "You are now going 0 kph."
p carro_prueba.shut_down == "Let's shut down to 0!"
p carro_prueba.current_speed == "You are now going 0 kph."
# Playlist
# Crea la clase Playlist que para inicializarla recibe 2 argumentos: name (nombre del playlist) y songs (lista de canciones).
# Crea una forma para poder leer el nombre del Playlist.
# Crea el mรฉtodo number_of_songs que regresa el nรบmero de canciones que contiene el Playlist.
# Crea el mรฉtodo add_song que agrega una canciรณn a la lista.
# Crea el mรฉtodo next_song que regresa la siguiente canciรณn del Playlist. Para esto necesitarรกs llevar control de cuรกl es la canciรณn actual. Si el playlist se encuentra en la รบltima canciรณn debe de volver a iniciar.
# Al crear una nueva instancia de Playlist la canciรณn actual por default deberรญa ser la primera canciรณn de la lista que le pasen.
class Playlist
attr_reader :name
@number_song ||= 0
def initialize (name, songs)
@name = name
@songs = songs
end
def number_of_songs
@songs.length
end
def add_song(song)
@songs << song
end
def next_song
@number_song ||= 0
@number_song
@number_song < @songs.length - 1 ? @number_song += 1 : @number_song = 0
@songs[@number_song]
end
end
lista = Playlist.new("DaftPunk", ["Beyond", "Within", "Touch"])
p lista.name == "DaftPunk"
p lista.number_of_songs == 3
p lista.add_song("Motherboard")
p lista.number_of_songs == 4
p lista.next_song == "Within"
p lista.next_song == "Touch"
p lista.next_song == "Motherboard"
p lista.next_song == "Beyond"
p lista.next_song == "Within"
| true
|
71d56380132b9f8cd488d859582a0446870c5b62
|
Ruby
|
tchin8/W4D3
|
/display.rb
|
UTF-8
| 1,670
| 3.40625
| 3
|
[] |
no_license
|
require 'colorize'
# require 'colorized_string'
require_relative "board.rb"
require_relative "cursor.rb"
class Display
attr_reader :cursor, :board
def initialize(board)
@board = board
@cursor = Cursor.new([0, 0], board)
end
def render
board.grid.each_with_index do |row, i|
printed_row = []
row.each_with_index do |ele, j|
if (i + j).odd?
# ele.to_s.colorize(:background => :grey)
printed_row << ele.to_s.colorize(:color => :light_blue, :background => :grey)
else
if [i,j] == @cursor.cursor_pos
printed_row << ele.to_s.colorize(:color => :light_blue, :background => :red)
else
# ele.to_s.colorize(:background => :white)
printed_row << ele.to_s.colorize(:color => :light_blue, :background => :white)
end
end
# printed_row << ele.to_s.colorize(:color => :light_blue)
end
puts printed_row.join
end
# x,y =
# @grid@cursor.cursor_pos.colorize(:background => :red)
# iterates over board & prints out all rows ;; use to_s
# then colorize diff pieces depending on their symb
# colorize wherever the cursor is
# cursor.colorize(:color => :light_blue, :background => :red)
#can't colorize bc it's not a str
end
end
# p d1
if $PROGRAM_NAME == __FILE__
d1 = Display.new(Board.new)
while true
d1.render
# ENDLESS LOOP
end
end
| true
|
534c5f420834d20db25ca0be4747ef120802b7fa
|
Ruby
|
DavidMah/Euler-Code
|
/010 - 019/Fourteen.rb
|
UTF-8
| 405
| 3.125
| 3
|
[] |
no_license
|
$results = Hash.new
def sequence(n)
if n == 1
return 1
elsif $results[n] != nil
return $results[n]
elsif n % 2 == 0
res = 1 + sequence(n / 2)
$results[n] = res
else
res = 1 + sequence(3 * n + 1)
$results[n] = res
end
end
greatest = 0
best = 0
for i in 1..999999
res = sequence(i)
$results[i] = res
best = i and greatest = res if res > greatest
puts i if i % 10000 == 0
end
puts best
| true
|
5581aa5fb5b4c81447e3ffd01a6ba20cb22908ee
|
Ruby
|
norelevance/ivr
|
/app/controllers/twilio_controller.rb
|
UTF-8
| 2,205
| 2.765625
| 3
|
[] |
no_license
|
require 'twilio-ruby'
require 'sanitize'
class TwilioController < ApplicationController
def initialize
@vr = Twilio::TwiML::VoiceResponse.new
end
def index
render text: "Dial Me."
end
def ivr_welcome
response = Twilio::TwiML::VoiceResponse.new
gather = Twilio::TwiML::Gather.new(input: 'dtmf', num_digits: '1', action: menu_path)
gather.say(message: "IVR Welcome - please press 1 to reach a live person or press 2 to leave a message........", loop: 1)
response.append(gather)
render xml: response.to_s
end
# GET ivr/menu_selection
# menu_path
def menu_selection
user_selection = params[:Digits]
case user_selection
when "1"
#@selection = Twilio::TwiML::VoiceResponse.new
@vr.say(message: "Placing you into the queue. This call will be recorded. Please stand by.")
@vr.enqueue(name: 'support')
when "2"
@vr.say(message: 'Please record your message now.')
@vr.record(timeout: 10, method: 'GET', max_length: 20, finish_on_key: '*')
when "*"
@vr.say(message: "Your message has been saved. Goodbye.")
@vr.hangup
when "9"
#@vr.say(message: "Connecting you to the caller. Please stand by.")
@vr.dial do |dial|
dial.queue('support', url: agent_path)
end
puts "@vr = #{@vr}"
else
@vr.say("Returning to the main menu.")
@vr.redirect(welcome_path)
end
render xml: @vr.to_s
end
def agent
@vr.dial do |dial|
dial.conference('support')
end
puts @vr
render xml: @vr.to_s
end
def connect
@vr.say(message: 'You will now be connected to an agent.')
puts @vr
render xml: @vr.to_s
end
def twiml_say(phrase, exit = false)
# Respond with some TwiML and say something.
# Should we hangup or go back to the main menu?
response = Twilio::TwiML::VoiceResponse.new do |r|
r.say(phrase, voice: 'alice', language: 'en-GB')
if exit
r.say("Thank you for calling the ET Phone Home Service - the
adventurous alien's first choice in intergalactic travel.")
r.hangup
else
r.redirect(welcome_path)
end
end
render xml: response.to_s
end
end
| true
|
477f3a62b113906debb319571b813cf0afe001c6
|
Ruby
|
mopuriiswaryalakshmi/Rspec
|
/matchers_spec.rb
|
UTF-8
| 1,185
| 3.640625
| 4
|
[] |
no_license
|
describe "Matchers"do
it "asserts on equality" do
number = 3
expect(number).to eq 3
end
it "asserts on mathematical operators" do
number = 5
expect(number)to be >= 2
end
it "asserts on matching a regular expression" do
email = "jose@tutsplus.com"
regular_expression = /^\w+@\w+\.[a-z]{2,4}$/
expect(email).to match regular_expression
end
it "asserts on types and classes" do
object = Numaric.new
expect(object).to be_an_instance_of Numeric
end
it "asserts on truthiness" do
bool = true
falsy_bool = false
nil_value = nil
object = Class.new
expect(object).to be_truthy
end
it "experts errors" do
expect do
raise ArgumentError
end.to raise_error TypeError
end
it "experts throws" do
expect {
throw :hooray
}.to throw_symbol
end
it "asserts on predicates" do
class A
def good?
A
end
end
expect(A.new).to be_good
end
it "asserts on collections" do
list = [
:one,
:two,
:three,
:four
]
expect(list).to include :four
expect(list).to start_with [ :one, :two ]
expect(list).to end_with [:three, :four ]
end
it "negates asserts" do
expect(3).not_to be 3
end
end
| true
|
761c57fa06af5388ab7e6d3fae21849054feca7c
|
Ruby
|
karthikeyan7585/adva_cms
|
/vendor/gems/rubyzip-0.9.1/lib/quiz1/t/solutions/Carlos/solitaire.rb
|
UTF-8
| 1,991
| 3.578125
| 4
|
[
"Ruby",
"BSD-2-Clause",
"MIT"
] |
permissive
|
class Numeric
def value
self
end
def to_letter
((self-1)%26 + ?A).chr
end
end
class String
# returns an array with the code of the letters,
# padded with the code of X
def to_numbers
res=upcase.unpack("C*").collect { |b|
if b.between? ?A, ?Z
b - ?A + 1
else
nil
end
}.compact
# 24 == X
res.fill 24, res.length, (5 - res.length % 5) % 5
end
def crypt (deck, decrypt=false)
numbers = to_numbers
keystream = deck.generate_keystream numbers.length
result = ""
numbers.zip(keystream) do |n, k|
k = -k if decrypt
result << (n+k).to_letter
end
result
end
def encrypt (deck)
crypt deck, false
end
def decrypt (deck)
crypt deck, true
end
end
class Joker
def value
53
end
end
A = Joker.new
B = Joker.new
class Array
def wrap_down pos
pos %= length
if pos == 0
pos = length
end
pos
end
def next_key
# step 2: move A joker down 1 card
pos = index A
slice! pos
pos = wrap_down(pos + 1)
self[pos, 0] = A
# step 3: move B joker down 2 cards
pos = index B
slice! pos
pos = wrap_down(pos + 2)
self[pos, 0] = B
# step 4: triple cut
first_joker, second_joker = [index(A), index(B)].sort
cards_above = slice! 0...first_joker
second_joker -= cards_above.length
cards_below = slice! second_joker+1..-1
push *cards_above
unshift *cards_below
# step 5: count cut using the value of the bottom card.
# reinsert above the last card
cut = slice! 0, last.value
self[-1,0] = cut
# step 6: find the letter
card = self[first.value]
return Joker===card ? nil : card.value
end
def generate_keystream len
(1..len).collect {|i| next_key or redo }
end
end
def new_deck
(1..52).to_a + [A, B]
end
res = if ARGV[0] == "-d"
ARGV[1..-1].join("").decrypt(new_deck)
else
ARGV.join("").encrypt(new_deck)
end
puts res.scan(/.{5}/).join(" ")
| true
|
ce4cef0bdb7afdb89b3dc13b0de630d9077d9fd7
|
Ruby
|
okke/jparsr
|
/spec/grammar/statements.rb
|
UTF-8
| 16,822
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
#
# Copyright (c) 2015, Okke van 't Verlaat
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be includedi
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
shared_examples :statements do
it "should accept a return statement" do
parse(%q{return;},:statement) do |tree|
expect(tree.has_key?(:return)).to be true
end
end
it "should accept a return expression statement" do
parse(%q{return "hot";},:statement) do |tree|
expect(tree[:return][:expression][:string]).to eq "\"hot\""
end
end
it "should accept a throw expression statement" do
parse(%q{throw new SoupToHotException();},:statement) do |tree|
expect(tree[:throw][:expression].has_key?(:new)).to be true
end
end
it "should accept a synchronized statement" do
parse(%q{synchronized(soup) {}},:statement) do |tree|
expect(tree[:synchronized][:expression][:id]).to eq "soup"
end
end
it "should accept a synchronized statement within a synchronized statement" do
parse(%q{synchronized("hot") {
synchronized("soep") {
}
}},:statement) do |tree|
expect(tree[:synchronized][:block][0][:statement].has_key?(:synchronized)).to be true
end
end
it "should accept an assignment as statement" do
parse(%q{until = max_temperature;},:statement) do |tree|
expect(tree[:expression][:o].has_key?(:assign_to)).to be true
end
end
it "should accept a pre increment as statement" do
parse(%q{++temperature;},:statement) do |tree|
expect(tree[:expression][:o].has_key?(:add_add)).to be true
end
end
it "should accept a pre decrement as statement" do
parse(%q{--temperature;},:statement) do |tree|
expect(tree[:expression][:o].has_key?(:minus_minus)).to be true
end
end
it "should accept a post increment as statement" do
parse(%q{temperature++;},:statement) do |tree|
expect(tree[:expression][:o].has_key?(:add_add)).to be true
end
end
it "should accept a post decrement as statement" do
parse(%q{temperature--;},:statement) do |tree|
expect(tree[:expression][:o].has_key?(:minus_minus)).to be true
end
end
it "should accept a method invocation as statement" do
parse(%q{andWaitFor(180);},:statement) do |tree|
expect(tree[:expression][:id]).to eq "andWaitFor"
end
end
it "should accept a instance creation as statement" do
parse(%q{new Stove();},:statement) do |tree|
expect(tree[:expression].has_key?(:new)).to be true
end
end
it "should accept a try catch as statement" do
parse(%q{try {
} catch(SoupToHotException e) {
}
},:statement) do |tree|
expect(tree[:try].has_key?(:block)).to be true
expect(tree[:try][:catch][0].has_key?(:block)).to be true
end
end
it "should accept a try catch with multiple catches as statement" do
parse(%q{try {
} catch(SoupToHotException e) {
return false;
}
catch(StoveOutOfOrderException e) {
}
},:statement) do |tree|
expect(tree[:try].has_key?(:block)).to be true
expect(tree[:try][:catch][0].has_key?(:block)).to be true
expect(tree[:try][:catch][1].has_key?(:block)).to be true
end
end
it "should accept a try with a finally clause as statement" do
parse(%q{try {
} finally {
}
},:statement) do |tree|
expect(tree[:try].has_key?(:block)).to be true
expect(tree[:try][:finally].has_key?(:block)).to be true
end
end
it "should accept a try-catch with a finally clause as statement" do
parse(%q{try {
} catch(SoupToHotException e) {
} finally {
}
},:statement) do |tree|
expect(tree[:try].has_key?(:block)).to be true
expect(tree[:try][:catch][0].has_key?(:block)).to be true
expect(tree[:try][:finally].has_key?(:block)).to be true
end
end
it "should accept a try catch finally with multiple catches as statement" do
parse(%q{try {
} catch(SoupToHotException e) {
}
catch(StoveOutOfOrderException e) {
} finally {
}
},:statement) do |tree|
expect(tree[:try].has_key?(:block)).to be true
expect(tree[:try][:catch][0].has_key?(:block)).to be true
expect(tree[:try][:catch][1].has_key?(:block)).to be true
expect(tree[:try][:finally].has_key?(:block)).to be true
end
end
it "should accept an empty statement" do
parse(%q{;},:statement) do |tree|
expect(tree.has_key?(:empty)).to be true
end
end
it "should accept a labeled statement" do
parse(%q{start: temperature = 30;},:statement) do |tree|
expect(tree[:label]).to eq "start"
end
end
it "should accept a break statement" do
parse(%q{break;},:statement) do |tree|
expect(tree.has_key?(:break)).to be true
end
end
it "should accept a labeled break statement" do
parse(%q{break start;},:statement) do |tree|
expect(tree[:break][:label]).to eq "start"
end
end
it "should accept a continue statement" do
parse(%q{continue;},:statement) do |tree|
expect(tree.has_key?(:continue)).to be true
end
end
it "should accept a labeled continue statement" do
parse(%q{continue start;},:statement) do |tree|
expect(tree[:continue][:label]).to eq "start"
end
end
it "should accept a do while statement" do
parse(%q{do i--; while (i > 0);},:statement) do |tree|
expect(tree[:do].has_key?(:statement)).to be true
expect(tree[:do].has_key?(:expression)).to be true
end
end
it "should accept a do while statement with a block" do
parse(%q{do {
} while (i > 0);
},:statement) do |tree|
expect(tree[:do][:statement].has_key?(:block)).to be true
expect(tree[:do].has_key?(:expression)).to be true
end
end
it "should accept a while statement without any statement" do
parse(%q{while(true);},:statement) do |tree|
expect(tree[:while].has_key?(:expression)).to be true
expect(tree[:while][:statement].has_key?(:empty)).to be true
end
end
it "should accept a while statement with a statement" do
parse(%q{while(true) break;},:statement) do |tree|
expect(tree[:while].has_key?(:expression)).to be true
expect(tree[:while][:statement].has_key?(:break)).to be true
end
end
it "should accept a while statement with an empty block" do
parse(%q{while(true) {}},:statement) do |tree|
expect(tree[:while].has_key?(:expression)).to be true
expect(tree[:while][:statement].has_key?(:block)).to be true
end
end
it "should accept a while statement with a block of statements" do
parse(%q{while(true) {a = 3; b = 5; }},:statement) do |tree|
expect(tree[:while].has_key?(:expression)).to be true
expect(tree[:while][:statement][:block][0].has_key?(:statement)).to be true
expect(tree[:while][:statement][:block][1].has_key?(:statement)).to be true
end
end
it "should accept a for statement without init, condition and update" do
parse(%q{for(;;) {}},:statement) do |tree|
expect(tree.has_key?(:for)).to be true
expect(tree[:for][:statement].has_key?(:block)).to be true
end
end
it "should accept a for statement without init and update" do
parse(%q{for(;true;) {}},:statement) do |tree|
expect(tree[:for].has_key?(:expression)).to be true
expect(tree[:for][:statement].has_key?(:block)).to be true
end
end
it "should accept a for statement without init or expression but with single update" do
parse(%q{for(;;a++) {}},:statement) do |tree|
expect(tree[:for].has_key?(:update)).to be true
expect(tree[:for][:statement].has_key?(:block)).to be true
end
end
it "should accept a for statement without init or expression but with multiple updates" do
parse(%q{for(;;a++,b++) {}},:statement) do |tree|
expect(tree[:for][:update][0].has_key?(:o)).to be true
expect(tree[:for][:update][1].has_key?(:o)).to be true
expect(tree[:for][:statement].has_key?(:block)).to be true
end
end
it "should accept a for statement with a single init and no expression nor update" do
parse(%q{for(a=3;;) {}},:statement) do |tree|
expect(tree[:for].has_key?(:init)).to be true
expect(tree[:for][:statement].has_key?(:block)).to be true
end
end
it "should accept a for statement with a multiple inits and no expression nor update" do
parse(%q{for(a=3,b=4;;) {}},:statement) do |tree|
expect(tree[:for][:init][0].has_key?(:o)).to be true
expect(tree[:for][:init][1].has_key?(:o)).to be true
expect(tree[:for][:statement].has_key?(:block)).to be true
end
end
it "should accept a for statement with a local var init and no expression nor update" do
parse(%q{for(int a=3;;) {}},:statement) do |tree|
expect(tree[:for][:init].has_key?(:class)).to be true
expect(tree[:for][:statement].has_key?(:block)).to be true
end
end
it "should accept an iterator style for statement" do
parse(%q{for(Soup s : Soups) {}},:statement) do |tree|
expect(tree[:for][:statement].has_key?(:block)).to be true
expect(tree[:for][:iterable][:id]).to eq "Soups"
end
end
it "should accept the most well known for statement" do
parse(%q{for(int i=0;i<100;i++) {}},:statement) do |tree|
expect(tree[:for].has_key?(:init)).to be true
expect(tree[:for].has_key?(:expression)).to be true
expect(tree[:for].has_key?(:update)).to be true
end
end
it "should accept a for in a while" do
parse(%q{while(true) for(;;) {}},:statement) do |tree|
expect(tree[:while][:statement].has_key?(:for)).to be true
end
end
it "should accept a while in a for" do
parse(%q{for(;;) while(true) {}},:statement) do |tree|
expect(tree[:for][:statement].has_key?(:while)).to be true
end
end
it "should accept a for in a while" do
parse(%q{while(true) for(;;) {}},:statement) do |tree|
expect(tree[:while][:statement].has_key?(:for)).to be true
end
end
it "should accept an if without stament" do
parse(%q{if(true);},:statement) do |tree|
expect(tree[:if].has_key?(:expression)).to be true
expect(tree[:if][:true].has_key?(:empty)).to be true
end
end
it "should accept an if with a statement" do
parse(%q{if(true) return;},:statement) do |tree|
expect(tree[:if].has_key?(:expression)).to be true
expect(tree[:if][:true].has_key?(:return)).to be true
end
end
it "should accept an if with a block" do
parse(%q{if(true) {}},:statement) do |tree|
expect(tree[:if].has_key?(:expression)).to be true
expect(tree[:if][:true].has_key?(:block)).to be true
end
end
it "should accept an if without stament and an else without statement" do
parse(%q{if(true); else;},:statement) do |tree|
expect(tree[:if][:true].has_key?(:empty)).to be true
expect(tree[:if][:false].has_key?(:empty)).to be true
end
end
it "should accept an if with a block and an else without statement" do
parse(%q{if(true) {} else;},:statement) do |tree|
expect(tree[:if][:true].has_key?(:block)).to be true
expect(tree[:if][:false].has_key?(:empty)).to be true
end
end
it "should accept an if withouth statement and an else with a block" do
parse(%q{if(true); else {}},:statement) do |tree|
expect(tree[:if][:true].has_key?(:empty)).to be true
expect(tree[:if][:false].has_key?(:block)).to be true
end
end
it "should accept an if with a block and an else with a block" do
parse(%q{if(true) {} else {}},:statement) do |tree|
expect(tree[:if][:true].has_key?(:block)).to be true
expect(tree[:if][:false].has_key?(:block)).to be true
end
end
it "should accept an if with an if" do
parse(%q{if(true) if(false);},:statement) do |tree|
expect(tree[:if][:true][:if][:true].has_key?(:empty)).to be true
end
end
it "should accept an if with an if and an else" do
parse(%q{if(true) if(false); else;},:statement) do |tree|
expect(tree[:if][:true][:if][:true].has_key?(:empty)).to be true
expect(tree[:if].has_key?(:false)).to be false
expect(tree[:if][:true][:if][:false].has_key?(:empty)).to be true
end
end
it "should accept an if with an if and an else" do
parse(%q{if(true) ; else if(false);},:statement) do |tree|
expect(tree[:if][:true].has_key?(:empty)).to be true
expect(tree[:if][:false][:if][:true].has_key?(:empty)).to be true
end
end
it "should accept a switch with a single empty case" do
parse(%q{switch(soup) {
case hot:
}},:statement) do |tree|
expect(tree[:switch].has_key?(:expression)).to be true
expect(tree[:switch][:labels][0].has_key?(:expression)).to be true
end
end
it "should accept a switch with a multiple empty cases" do
parse(%q{switch(soup) {
case hot:
case cold:
}},:statement) do |tree|
expect(tree[:switch].has_key?(:expression)).to be true
expect(tree[:switch][:labels][0].has_key?(:expression)).to be true
expect(tree[:switch][:labels][1].has_key?(:expression)).to be true
end
end
it "should accept a switch with an empty default" do
parse(%q{switch(soup) {
default:
}},:statement) do |tree|
expect(tree[:switch].has_key?(:expression)).to be true
expect(tree[:switch][:labels][0].has_key?(:default)).to be true
end
end
it "should accept a switch with an empty case and an empty default" do
parse(%q{switch(soup) {
case hot:
default:
}},:statement) do |tree|
expect(tree[:switch].has_key?(:expression)).to be true
expect(tree[:switch][:labels][0].has_key?(:expression)).to be true
expect(tree[:switch][:labels][1].has_key?(:default)).to be true
end
end
it "should accept a switch with a case with a single statement" do
parse(%q{switch(soup) {
case hot: freeze(20);
}},:statement) do |tree|
expect(tree[:switch].has_key?(:expression)).to be true
expect(tree[:switch][:labels][0].has_key?(:expression)).to be true
expect(tree[:switch][:labels][0][:statements][0].has_key?(:expression)).to be true
end
end
it "should accept a switch with a case with a multiple statements" do
parse(%q{switch(soup) {
case hot: freeze(20); break;
}},:statement) do |tree|
expect(tree[:switch].has_key?(:expression)).to be true
expect(tree[:switch][:labels][0].has_key?(:expression)).to be true
expect(tree[:switch][:labels][0][:statements][0].has_key?(:expression)).to be true
expect(tree[:switch][:labels][0][:statements][1].has_key?(:break)).to be true
end
end
it "should accept a switch with a default with a multiple statements" do
parse(%q{switch(soup) {
default: freeze(20); break;
}},:statement) do |tree|
expect(tree[:switch].has_key?(:expression)).to be true
expect(tree[:switch][:labels][0].has_key?(:default)).to be true
expect(tree[:switch][:labels][0][:statements][0].has_key?(:expression)).to be true
expect(tree[:switch][:labels][0][:statements][1].has_key?(:break)).to be true
end
end
it "should accept a switch with a case followed by a block" do
parse(%q{switch(soup) {
case cold: {boil(20); break;}
}},:statement) do |tree|
expect(tree[:switch].has_key?(:expression)).to be true
expect(tree[:switch][:labels][0].has_key?(:expression)).to be true
expect(tree[:switch][:labels][0][:statements][0].has_key?(:block)).to be true
end
end
end
| true
|
ac3d400aba80511e957e287ed97ed1fe4b5dad25
|
Ruby
|
tanaken0515/atcoder
|
/virtual-contests/pepabo/001/A.rb
|
UTF-8
| 92
| 2.796875
| 3
|
[] |
no_license
|
sorted_nums = gets.chomp.split(" ").map(&:to_i).sort
print sorted_nums[0] + sorted_nums[1]
| true
|
1ed277814b8e71622dc44c324e764afdd06f9a56
|
Ruby
|
andrewdwooten/enigma
|
/test/Key_test.rb
|
UTF-8
| 546
| 2.9375
| 3
|
[] |
no_license
|
require_relative 'test_helper.rb'
require './lib/Key.rb'
class KeyTest < MiniTest::Test
def test_is_the_key_a_key
house_key = Key.new
assert_equal Key, house_key.class
end
def test_is_the_key_five_digits
house_key = Key.new
assert_equal 5, house_key.key.count
end
def test_is_the_key_an_array
house_key = Key.new
assert_equal Array, house_key.key.class
end
def test_keys_are_differently_cut
house_key = Key.new
closet_key = Key.new
assert true, house_key.key != closet_key.key
end
end
| true
|
b591242e8c419a0d4586528ce657269310d4a768
|
Ruby
|
lpzraf/ruby-object-attributes-lab-v-000
|
/lib/person.rb
|
UTF-8
| 287
| 3.25
| 3
|
[] |
no_license
|
class Person
def name= (name)
@name = name
end
def name
@name
end
def job= (job)
@job = job
end
def job
@job
end
end
beyonce = Person.new
beyonce.name = "Beyonce"
puts beyonce.name
singer = Person.new
singer.job = "Singer"
puts singer.job
| true
|
c0848163a60690546a3a38a59bc751c5436e937f
|
Ruby
|
JennicaStiehl/personal_site
|
/test/features/user_sees_a_homepage_test.rb
|
UTF-8
| 703
| 2.6875
| 3
|
[] |
no_license
|
require './test/test_helper'
class HomepageTest < CapybaraTestCase
def test_user_can_see_the_homepage
visit '/'
# save_and_open_page
assert page.has_content?("Welcome!")
assert_equal 200, page.status_code
end
def test_user_can_see_the_error_message
visit '/error'
assert page.has_content?("Page not found.")
assert_equal 404, page.status_code
end
end
# When we assert that the page.has_content?("Welcome!"), we are checking that Welcome! is in the body of our response. When we assert that the status code is 200, we're checking to see that's what our server sent back.
#
# If you want a full list of methods that you can call on page, you can run page.methods.
| true
|
7af5b2f21c72a24501e33182bdff4b0a76414bb1
|
Ruby
|
hlindberg/tahu
|
/lib/puppet/functions/tahu/ppyaml_key.rb
|
UTF-8
| 4,862
| 2.75
| 3
|
[
"Apache-2.0"
] |
permissive
|
# This hiera5 lookup_key kind of backend function reads a yaml file and performs Puppet Language evaluation.
#
# It requires a 'path' pointing to a data file, and it can optionally perform a hiera interpolation before evaluating
# the read data structure as Puppet Source code. The 'path' is provided by hiera 5 framework from one of the inputs
# `path`, `paths`, `glob` or `globs`.
#
# All values that are strings are then evaluated as Puppet Source code. That means that strings are Puppet Language, and
# if they are to be interpreted as strings must either be quoted as `"'single quoted string'"` or `'"double quoted string"'` in
# the yaml source since the Puppet evaluation requires quotes around strings.
#
# All values inside of Array and Hash values (keys are excluded) will be recursively visisted and all strings will be replaced
# with the result of evaluating that string.
#
Puppet::Functions.create_function(:'tahu::ppyaml_key') do
dispatch :yaml_data do
param 'Variant[String, Numeric]', :key
param 'Struct[{path=>String[1], Optional[hiera_interpolation]=>Boolean}]', :options
param 'Puppet::LookupContext', :context
end
argument_mismatch :missing_path do
param 'Variant[String, Numeric]', :key
param 'Hash', :options
param 'Puppet::LookupContext', :context
end
require 'yaml'
def yaml_data(key, options, context)
# Recursion detection is tricky since evaluation of puppet logic can call the `lookup` function and start a
# new invocation. The protection here is not perfect but will detect if recursion occurs for the very same key
# when hitting the logic here. This is done by picking up an invocation from an earlier call in the puppet context,
# and using this invocation to check for recursion on the same key.
#
context_key = :'tahu::ppyaml'
invocation, level = Puppet.lookup(context_key) { [context.invocation, 0] }
next_level = invocation.equal?(context.invocation) ? level : level + 1
Puppet.override({context_key => [invocation, next_level]}, "Protect against recursive lookup/eval of same key") do
recursion_check(invocation, level, next_level, key) do
path = options['path']
hiera_interpolation = !!options['hiera_interpolation']
data = context.cached_file_data(path) do |content|
begin
data = Puppet::Util::Yaml.safe_load(content, [Symbol], path)
if data.is_a?(Hash)
Puppet::Pops::Lookup::HieraConfig.symkeys_to_string(data)
else
msg = _("%{path}: file does not contain a valid yaml hash" % { path: path })
raise Puppet::DataBinding::LookupError, msg if Puppet[:strict] == :error && data != false
Puppet.warning(msg)
{}
end
rescue Puppet::Util::Yaml::YamlLoadError => ex
# YamlLoadErrors include the absolute path to the file, so no need to add that
raise Puppet::DataBinding::LookupError, _("Unable to parse %{message}") % { message: ex.message }
end
end
value = data[key]
if value.nil?
if !data.include?(key)
context.not_found()
else
return nil # nothing to process further - just return the nil value
end
end
# First perform any hiera interpolation if that is wanted
value = context.interpolate(value) if hiera_interpolation
do_pp_interpolation(value)
end
end
end
# Recursively evaluate strings inside hash and array values, pp evaluate all strings
# and return all other (basically numerics) verbatim.
#
def do_pp_interpolation(value)
case value
when Array
value.map {|v| do_pp_interpolation(v)}
when Hash
result = {}
value.each_pair {|k,v| result[k] = do_pp_interpolation(v) }
result
when String
call_function('tahu::eval', value)
else
value
end
end
# If a call comes from the initial level (0) it is already checked at that level
# Subsequent recursive calls via the "lookup" function will bump the level
# and make a check against the initial Invocation that is passed on in the
# puppet context, with increasing level count - there is no need to decrease it
# since the level disappears when the level override goes out of scope.
#
def recursion_check(invocation, level, next_level, key, &block)
if level == next_level # within the same level
yield
else
invocation.check(key, &block)
end
end
def missing_path(options, context)
if !options['path']
"one of 'path', 'paths' 'glob', 'globs' or 'mapped_paths' must be declared in hiera.yaml when using this lookup_key function"
else
"supported options are String 'path', and Boolean 'hiera_interpolation' got: '#{options}'"
end
end
end
| true
|
aa0414a808c0e6ac6dba9376b0c3c24e5096ff1b
|
Ruby
|
tm1819/Code--github-
|
/Development/NYU Classes Health/nyuClassesHealth0.1.rb
|
UTF-8
| 5,403
| 2.75
| 3
|
[] |
no_license
|
# ###########################################################################
# Title: NYU Classes Health Check
# Author: Tom Martin
# Date: 2/25/2013
#
# This script checks the status of an NYU Classes Server, and sends an email
# message in the event of a status change.
# ###########################################################################
# ###########################################################################
# Ruby Required Libraries
# ###########################################################################
require 'net/http'
require 'net/https'
require 'net/smtp'
require 'open-uri'
require 'uri'
# ###########################################################################
# Script Parameters
# ###########################################################################
scriptName = "NYU Classes Health Check" # the name of the script
downTitle = "NYU Classes App Server Down" # title for notification email
downMessage = "NYU Classes is unavailable." # body text for notification email
statusMsgAddress = "********@maildomain.com" # source address for notification email
statusMsgPassword = "******************" # password for notification email
baseServer = "http://newclasses.nyu.edu" # the base site url
loginPath = "portal/relogin" # the login page
userName = "*****" # the login username
password = "*****" # the login password
serverFilter = /sakaiCopyrightInfo[^<]*[^>]*>[\s]*([^\s]*)/ # regex for app server name
recipientList = [ # addresses that will receive status messages
"*************@maildomain.com",
"*************@maildomain.edu"
]
# ---------------------------------------------------------------------------
# Name: httpsRequest
# Desc: Sends an HTTPS request, which requires different code from HTTP
# ---------------------------------------------------------------------------
def httpsRequest (url)
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
return response
end
# ---------------------------------------------------------------------------
# Name: httpRequest
# Desc: Sends an HTTP request, which requires different code from HTTPS
# ---------------------------------------------------------------------------
def httpRequest (url)
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
response = http.request(Net::HTTP::Get.new(uri.request_uri))
end
# ---------------------------------------------------------------------------
# Name: webRequest
# Desc: Sends a generic web request (either HTTP or HTTPS)
# ---------------------------------------------------------------------------
def webRequest (url)
if url =~ /(https)/
return httpsRequest(url)
else
return httpRequest(url)
end
end
# ---------------------------------------------------------------------------
# Name: autoRedirectWebRequest
# Desc: Submits a generic web request and automatically follows redirects.
# Returns: A struct containing the eventual url, and an http response.
# ---------------------------------------------------------------------------
Redirect = Struct.new(:newURL, :response)
def autoRedirectWebRequest (url)
response = webRequest(url)
if response.code == "301" or response.code == "302" or response.code == "307"
location = response["location"]
return autoRedirectWebRequest(location)
else
redirectResponse = Redirect.new(url,response)
return redirectResponse
end
end
# ---------------------------------------------------------------------------
# Name: notifyRecipients
# Desc: Sends email notification to recipient list
# ---------------------------------------------------------------------------
def notifyRecipients (statusMsgAddress, statusMsgPassword, recipientList, downTitle, downMessage)
recipientList.length.times do |i|
msg = "Subject: #{downTitle}\n\n#{downMessage}"
smtp = Net::SMTP.new 'smtp.gmail.com', 587
smtp.enable_starttls
smtp.start("gmail", statusMsgAddress, statusMsgPassword, :login) do
smtp.send_message(msg, statusMsgAddress, recipientList[i])
end
end
end
# ###########################################################################
# Script Action
# ###########################################################################
# Simulate Login. Notify Recipients in the event of an error
begin
redirectResponse = autoRedirectWebRequest(baseServer)
redirectResponse = autoRedirectWebRequest(redirectResponse.newURL + loginPath + "&eid=" + userName + "&pw=" + password + "&submit=Login")
rescue Exception=>e
errMsg = "\nERROR: " + scriptName + ": Can't resolve URL"
notifyRecipients(statusMsgAddress, statusMsgPassword, recipientList, downTitle, downMessage+errMsg)
end
# Assertion for App server text. If not found, notify recipients
if redirectResponse.response.body =~ serverFilter
#puts "MESSAGE: " + scriptName + ": Server '" + $1 + "' is up and running."
else
errMsg = "\nERROR: " + scriptName + ": Can't find server name. May be down."
notifyRecipients(statusMsgAddress, statusMsgPassword, recipientList, downTitle, downMessage+errMsg)
end
| true
|
94cac24f69da21ca0bf4ffef983b89167b5b67bc
|
Ruby
|
Lafatra351/TicTacToe.THP
|
/TicTacToe2.rb
|
UTF-8
| 4,482
| 3.734375
| 4
|
[
"MIT"
] |
permissive
|
# classe cases :
class BoardCase
#la classe a deux attr_accessor : sa valeur ("X", "_", ou vide), et son numรฉro de case.
attr_accessor :value, :case_number
def initialize(case_number)
@value = ""
@case_number = case_number
end
def to_s
# renvoie la valeur au format string
self.value = @value
end
end
##################################################
##################################################
# Le tableau de jeu
class Board
include Enumerable
attr_accessor :board
def initialize
#Quand la classe s'initialize, elle crรฉe 9 instances BoardCases
#Ces instances sont rangรฉes dans une array qui est l'attr_accessor de la classe
@board = [*0..8].map { |i| BoardCase.new(i).case_number }
end
def to_s
# affiche le plateau
puts "#{@board[0..2].join(" | ")}"
puts "--|---|--"
puts "#{@board[3..5].join(" | ")}"
puts "--|---|--"
puts "#{@board[6..8].join(" | ")}"
end
def play(symbol)
# change la case jouรฉe en fonction de ce qu'a jouรฉ le joueur (X, ou _)
case_number = gets.chomp().to_i
@board = @board.each_index.map { |e| e == case_number && @board[e] != "X" && @board[e] != "_" ? @board[e] = symbol : @board[e] }
end
def victory?
# qui gagne : on teste si les rangรฉes ou diagonales contiennent des symboles identiques
if (@board[0] == @board[1] && @board[0] == @board[2]) || (@board[3] == @board[4] && @board[3] == @board[5]) || (@board[6] == @board[7] && @board[6] == @board[8] ) || (@board[0] == @board[3] && @board[0] == @board[6]) || (@board[1] == @board[4] && @board[1] == @board[7]) || (@board[2] == @board[5] && @board[2] == @board[8]) ||( @board[0] == @board[4] && @board[0] == @board[8]) || (@board[2] == @board[4] && @board[2] == @board[6])
return true
else
return false
end
end
end
##################################################
##################################################
class Player
# La classe a deux attr_accessor : son nom, et son symbole (X ou O).
attr_accessor :name, :symbol
def initialize(name, symbol)
# nom du joueur, symbole avec lequel il joue
@name = name
@symbol = symbol
end
end
##################################################
##################################################
class Game
attr_accessor :symbol
def initialize
# On efface l'รฉcran du terminal
system "clear"
puts "Bienvenue au jeu du morpion!"
puts "Attention, si tu choisis une case dรฉjร occupรฉe, tu perds ton tour!"
puts
puts "Joueur 1, ton symbole sera X, choisis un nom: "
print ">"
name_1 = gets.chomp
# crรฉe le joueur 1
@player1 = Player.new(name_1, "X")
puts
puts "Joueur 2, ton symbole sera underscore _ , choisis un nom: "
print ">"
name_2 = gets.chomp
# crรฉe le joueur 2
@player2 = Player.new(name_2, "_")
@current_player = @player1
# crรฉe le plateau de jeu
@board = Board.new
end
def go
# lance la partie
while @board.victory? == false
self.turn
end
end
# Passe d'un joueur ร l'autre
def switch_players
if @current_player == @player1
@current_player = @player2
else
@current_player = @player1
end
end
#ร chaque tour on exรฉcute turn (lancรฉ par la mรฉthode go)
def turn
# On boucle tant qu'il n'y a pas de victoire
loop do
system "clear"
puts "============="
puts "Voici l'รฉtat du jeu:"
# Affiche le plateau :
@board.to_s
puts ""
puts "C'est le tour de #{@current_player.name} avec les #{@current_player.symbol}"
puts "Choisis une case"
print ">"
# On appelle la mรฉthode play de la classe board sur le joueur en cours (current). Elle demande au joueur quelle case il joue, puis affiche son symbole dans la case
@board.play(@current_player.symbol)
# On arrรชte la boucle en cas de victoire
if @board.victory? == true
system "clear"
puts "============="
puts "Voici l'รฉtat du jeu:"
@board.to_s
puts ""
puts "#{@current_player.name} a gagnรฉ !!!"
puts
break
end
# Il n'y a pas de victoire : on passe au joueur suivant et on boucle (tour suivant)
switch_players
end
end
end
##################################################
##################################################
# On crรฉe un nouveau jeu et on appelle la mรฉthode Go qui lance le jeu
Game.new.go
| true
|
1a6d70e78daeddbe7921fca7ba458ce79bbd9a52
|
Ruby
|
koshavaghela/platform-code-test
|
/award.rb
|
UTF-8
| 1,198
| 3.25
| 3
|
[] |
no_license
|
class Award
attr_accessor :name, :expires_in, :quality
def initialize(name, expires_in, quality)
@name = name
@expires_in = expires_in
@quality = quality
end
def update_award_quality
case name
when 'Blue Distinction Plus'
@quality = 80
when 'NORMAL ITEM'
self.normal_item
when 'Blue First'
self.blue_first
when 'Blue Compare'
self.blue_compare
when 'Blue Star'
self.blue_star
end
@expires_in -= 1 if name != 'Blue Distinction Plus'
end
private
def normal_item
if @quality.positive?
self.has_expired? ? @quality -= 2 : @quality -= 1
end
end
def blue_star
self.has_expired? ? @quality -= 4 : @quality -= 2
@quality = 0 if @quality.negative?
end
def blue_first
self.has_expired? ? @quality += 2 : @quality += 1
@quality = 50 if @quality > 50
end
def blue_compare
if self.has_expired?
@quality = 0
elsif @expires_in <= 5
@quality += 3
elsif (6..10).include?(@expires_in)
@quality += 2
elsif @expires_in > 10
@quality += 1
end
@quality = 50 if @quality > 50
end
def has_expired?
@expires_in <= 0
end
end
| true
|
208842244c03f758cd0acc25c865f242456c2b5e
|
Ruby
|
Cheltonne/THP-Jour-17-Chelton-Ajax
|
/lib/game.rb
|
UTF-8
| 3,328
| 3.453125
| 3
|
[] |
no_license
|
require 'pry'
require_relative 'player'
class Game
attr_accessor :human_player, :players_left, :ennemies_in_sight
def initialize(player_name)
@players_left = 10
@human_player = HumanPlayer.new(player_name)
self.ennemies_in_sight = []
4.times do |i|
@ennemies_in_sight << Player.new("cpu_#{i}")
end
end
def kill_player(victim)
@ennemies_in_sight = @ennemies_in_sight - [victim]
end
def is_still_ongoing?
if human_player.life_points > 0 && @ennemies_in_sight != [] #Ceci signifie "Tant que le joueur est vivant ET que la liste des ennemis n'est pas un tableau vide"
return true
else
return false
end
end
def show_players
puts "Il te reste #{human_player.life_points} points de vie, et tu possedes une arme de niveau #{human_player.weapon_level}. Il reste #{ennemies_in_sight.length} ennemis en jeu.\n\n"
end
def menu
puts "Voici les differents choix possibles, entre la lettre ou le chiffre correspondant a ton choix :"
puts "a - Chercher une meilleure arme"
puts "s - Chercher ร se soigner\n\n"
puts "Attaquer un joueur en vue :"
i = 0
@ennemies_in_sight.each do |ennemy| #On verifie pour chaque ennemi qu'il lui reste bien des PV, si c'est le cas, on les affiche, et on lui affecte un numero correspondant a sa place dans l'array @ennemies.
if ennemy.life_points > 0
puts "#{i} - Ennemi #{ennemy.name} a #{ennemy.life_points} points de vie."
i += 1
end
end
puts ""
puts "Quel est ton choix ?"
print "> "
return player_action = gets.chomp
end
def menu_choice(player_action)
if @ennemies_in_sight == []
return false
end
if player_action == 'a'
human_player.search_weapon
elsif player_action == 's'
human_player.search_health_pack
elsif ennemies_in_sight[player_action.to_i] != nil #Si le choix du joueur est un chiffre, je regarde si un ennemi se trouve a l'index correspondant dans l'array des ennemis a portee, si c'est le cas, j'attaque cet ennemi
human_player.attacks(ennemies_in_sight[player_action.to_i])
else
puts "โ ๏ธ Ce choix n'existe pas. Tu as perdu un tour pour rien ! โ ๏ธ\n\n"
end
@ennemies_in_sight.each do |i|
if i.life_points <= 0
kill_player(i)
end
end
ennemies_attack
end
def ennemies_attack
@ennemies_in_sight.each do |ennemy|
ennemy.attacks(human_player)
if human_player.life_points < 1
return false
end
end
end
def end_game
if human_player.life_points >= 1
puts "Winner winner, chicken dinner"
else
puts "Game over..."
end
end
def new_players_in_sight
if players_left == ennemies_in_sight.length
puts "Tous les joueurs sont dรฉjร en vue.\n\n"
end
dice = rand(1..6)
case dice
when 1
puts "Aucun nouveau joueur adverse n'arrive.\n\n"
when [2.. 4]
ennemies_in_sight << Player.new("joueur_#{rand(1..50)}")
puts "Un nouvel ennemi apparait !\n\n"
when 5 || 6
2.times do |new_player_in_sight|
ennemies_in_sight << Player.new("joueur_#{rand(1..50)}")
puts "Deux nouveaux ennemis apparaissent !\n\n"
end
end
end
end #Fin de la definition de classe Game
| true
|
5ec9529743e8fe62b3a71c87142962528718c779
|
Ruby
|
miketierney/seacrest
|
/bin/csscrubber
|
UTF-8
| 1,981
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require 'rubygems'
require "lib/seacrest"
# puts "Scrub scrub scrub scrub scrub scrub scrub"
output = Seacrest::CSScrubber.run(ARGV)
if output.dup_selectors.size >= 1
puts "\n#############################"
puts "### Duplicate Selectors ###"
puts "#############################\n\n"
puts "You have #{output.dup_selectors.size} duplicate selector#{'s' unless output.dup_selectors.size == 1 }.\n\n"
output.dup_selectors.each do |key, value|
puts "#{key}\n"
puts " Found in the following files:\n"
value.each do |file|
puts " | #{file}"
end
puts "\n"
end
end
if output.unused_selectors.size >= 1
output.unused_selectors.sort!
puts "\n##############################"
puts "##### Unused Selectors #####"
puts "##############################\n\n"
output.unused_selectors.uniq!.sort!
puts "You have #{output.unused_selectors.size} unused selector#{'s' unless output.unused_selectors.size == 1 }.\n\n"
# p output.all_selectors
# p output.dup_selectors
output.unused_selectors.each do |selector|
puts "#{selector}"
p output.dup_selectors.has_key?(selector) ? output.dup_selectors[selector] : output.unique_selectors[selector]
# puts " Found in the following files:\n"
# files = output.unique_selectors[selector][:files]
# p files
# files.each do |file|
# puts " | #{file}"
# end
puts "\n\n"
end
end
# if output.unique_selectors.size >= 1
#
# puts "\n##############################"
# puts "##### Unique Selectors #####"
# puts "##############################\n\n"
#
# puts "You have #{output.unique_selectors.size} selector#{'s' unless output.unique_selectors.size == 1 } in all of your css files.\n\n"
#
# output.unique_selectors.each do |key, value|
# puts "#{key}"
# puts " Found in the following files:\n"
# value[:files].each do |file|
# puts " | #{file}"
# end
# puts "\n"
# end
# end
| true
|
7e6058b07d842cfe407ab00a0028e525547880fe
|
Ruby
|
HJRandolph/learn_ruby
|
/ruby_challenges/attr_settersANDgetters.rb
|
UTF-8
| 771
| 3.671875
| 4
|
[] |
no_license
|
class Pet
# attr_writer:name, :owner_name
# attr_reader:name, :owner_name
attr_accessor:name, :owner_name
end
class Ferret < Pet
def squeal
return "squeeeeee"
end
end
class Chincilla < Pet
def squeek
return "eeeep"
end
end
class Parrot < Pet
def tweet
return "caw"
end
end
my_ferret = Ferret.new
my_ferret.name = "Fredo"
ferret_name = my_ferret.name
my_parrot = Parrot.new
my_parrot.name = "Budgie"
parrot_name = my_parrot.name
my_chincilla = Chincilla.new
my_chincilla.name = "Dali"
chincilla_name = my_chincilla.name
puts "#{ferret_name} says #{my_ferret.squeal},
#{parrot_name} says #{my_parrot.tweet},
and #{chincilla_name} says #{my_chincilla.squeek}."
#puts my_ferret.inspect
#puts my_parrot.inspect
#puts my_chincilla.inspect
| true
|
b0534ec12fc99f2e3ddc44e32d276d0fcc6956b4
|
Ruby
|
edgelaboratories/sensu-plugins-edgelab
|
/bin/check-apt-expired-keys.rb
|
UTF-8
| 2,366
| 2.609375
| 3
|
[] |
no_license
|
#! /usr/bin/env ruby
# frozen_string_literal: true
#
# check-apt-expired-keys
#
# DESCRIPTION:
# This plugin reports expired GPG key used for APT signing.
#
# OUTPUT:
# plain text
#
# PLATFORMS:
# Debian
#
# DEPENDENCIES:
# gem: sensu-plugin
#
# USAGE:
# example commands
#
# NOTES:
# Does it behave differently on specific platforms, specific use cases, etc
#
# LICENSE:
# Copyright 2015 EdgeLaboratories.
# Released under the same terms as Sensu (the MIT license); see LICENSE
# for details.
#
require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'sensu-plugin/check/cli'
class APTKey < Sensu::Plugin::Check::CLI
def run
# Must be executed as root in order to access APT keys list
if Process.uid != 0
return unknown 'Must be executed as root user'
end
expired = expired_keys
if expired.count.positive?
if expired.count == 1
verb = 'is'
noun = 'key'
else
verb = 'are'
noun = 'keys'
end
warning "There #{verb} #{expired.count} expired APT #{noun}: #{expired.join('; ')}"
else
ok 'No APT expired keys'
end
end
def expired_keys
expired = []
IO.popen('apt-key list') do |cmd|
current_key_id = nil
current_key_name = nil
# We try to parse output like this:
# pub 2048R/B999A372 2010-08-12 [expired: 2015-08-13]
# uid Riptano Package Repository <paul@riptano.com>
cmd.each do |line|
# Parse and extract the expired public key ID
match = /^pub[ ]+[^\/]+\/(.*) .* \[expired: /.match(line)
unless match.nil?
current_key_id = match.captures[0]
end
# Try to get the more user-friendly name. Sometimes, it doesn't
# contain enough information to be useful, but it still
# slightly better than the key ID.
match = /^uid[ ]+(.*)$/.match(line)
unless match.nil?
current_key_name = match.captures[0]
end
# If we reach an empty line and we parsed expired key, save
# them and reset everything for the next keys after.
if line =~ /^$/
if current_key_id
expired.push "#{current_key_name || 'unknown key uid'} (#{current_key_id})"
end
current_key_id = nil
current_key_name = nil
end
end
end
expired
end
end
| true
|
87637b9913fae92029792588ab258ba92f40babf
|
Ruby
|
Vandegrift/rex12
|
/spec/rex12/segment_spec.rb
|
UTF-8
| 1,546
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
describe REX12::Segment do
subject { described_class.new elements, 1}
let (:elements) {
[REX12::Element.new("a", 1), REX12::Element.new("b", 2)]
}
describe "position" do
it "returns the position given in the constructor" do
expect(subject.position).to eq 1
end
it "freezes position" do
expect(subject.position).to be_frozen
end
end
describe "segment_type" do
it "returns the first element's value as the segment type" do
expect(subject.segment_type).to eq "a"
end
context "with no elements" do
subject { described_class.new [], 1}
it "returns nil" do
expect(subject.segment_type).to be_nil
end
end
end
describe "element" do
it "returns the element at the given index" do
expect(subject.element 1).to eq elements[1]
end
it "returns nil for invalid index" do
expect(subject.element 100).to be_nil
end
end
describe "elements" do
it "returns an enum of all elements" do
els = subject.elements
expect(els.next).to eq elements[0]
expect(els.next).to eq elements[1]
expect{ els.next }.to raise_error StopIteration
end
it "yields elements" do
expect { |b| subject.elements(&b) }.to yield_successive_args(elements[0], elements[1])
end
end
describe "[]" do
it "returns an elements value at index" do
expect(subject[1]).to eq elements[1].value
end
it "returns nil for invalid index" do
expect(subject[100]).to be_nil
end
end
end
| true
|
9559aedaa17a9f6de7871b2f75347b310be31843
|
Ruby
|
joshua31101/ruby_practice
|
/searching_algorithms/binary_search.rb
|
UTF-8
| 442
| 3.5625
| 4
|
[] |
no_license
|
def binary_search(arr, target, first, last)
mid = (first+last) / 2
return true if arr[mid] == target
return false if first > last
if target < arr[mid]
binary_search(arr, target, first, mid-1)
else
binary_search(arr, target, mid+1, last)
end
end
arr = (1..10000000).to_a
t1 = Time.now
p binary_search(arr, 10000000, 0, arr.length-1)
t2 = Time.now
puts "The elapsed time of binary search for ten milion items is #{t2-t1}"
| true
|
8cb6f11138c7b8246ba1c0cedfbd74107faef3c5
|
Ruby
|
nicooga/project-euler
|
/0009.rb
|
UTF-8
| 748
| 3.765625
| 4
|
[] |
no_license
|
# A Pythagorean triplet is a set of three natural numbers, a b c, for which,
# a2 + b2 = c2
# For example, 32 + 42 = 9 + 16 = 25 = 52.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
def pitagoric_triplet?(a,b,c)
(a**2 + b**2) == c**2
end
def solution
triplet = []
997.downto(334) do |c|
range = (1..(1000-c)).to_a
a_values = range.size.even? ? range[0...(range.size/2-1)] : range[0...(range.size/2)]
b_values = range[(range.size/2)...(range.max-1)].reverse
ab_pairs = a_values.zip(b_values)
triplet = ab_pairs.select { |a,b| pitagoric_triplet?(a,b,c) }.map{ |a,b| [a,b,c] }
break if triplet.any?
end
triplet.first.reduce(:*)
end
puts "Solution: #{solution}"
| true
|
b09f334e1f2473304791538d9e6774ca2af17840
|
Ruby
|
sahidur-prosku/gs1
|
/lib/gs1/validations.rb
|
UTF-8
| 1,014
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
require 'gs1/validations/check_digit_validation'
require 'gs1/validations/date_validation'
require 'gs1/validations/length_validation'
module GS1
# Module for handling validations.
#
module Validations
def self.included(base)
base.extend ClassMethods
base.send :include, InstanceMethods
base.send :include, CheckDigitValidation
base.send :include, DateValidation
base.send :include, LengthValidation
end
# Adding validation class methods.
#
module ClassMethods
def valid_data?(data)
new(data).valid?
end
end
# Adding validation instance methods.
#
module InstanceMethods
def valid?
errors.clear
validate
errors.empty?
end
def errors
@errors ||= []
end
def validate
self.class.definitions.each_key do |definition|
next if definition == :separator
public_send("validate_#{definition}")
end
end
end
end
end
| true
|
206eebd90c6e1b1b74f9cb168ac65aaf712ce601
|
Ruby
|
tanmle/lf_testing
|
/lib/tasks/db_seed_dump.rake
|
UTF-8
| 4,276
| 2.703125
| 3
|
[] |
no_license
|
require 'active_support/core_ext/string/strip'
namespace :db do
namespace :seed do
task dump: [:environment, :load_config] do
desc 'LF - Create a db/seeds.rb file from the database'
# get information from config/database.yml file
erb = ERB.new(File.read('config/database.yml'))
config = YAML.load(erb.result)[ENV['RAILS_ENV']]
database = config['database']
username = config['username']
password = config['password']
puts "Using '#{database}' database"
seeds_path = File.join('db', 'seeds.rb').gsub(File::SEPARATOR, File::ALT_SEPARATOR || File::SEPARATOR)
command = "mysqldump #{database} -u #{username} -p#{password} --host #{config['host']} --port #{config['port']} --no-create-info --no-create-db --ignore-table=#{database}.schema_migrations --ignore-table=#{database}.stations"
output = `#{command}`
ActiveRecord::Base.establish_connection(config)
version = ActiveRecord::Base.connection.exec_query('select * from schema_migrations order by version desc limit 1').first.first[1]
tables = output.scan(/(insert into `([^`]+).*)/i)
puts " generated #{output.lines.size} lines for #{tables.size} tables"
File.open(seeds_path, 'w') do |file|
file.puts <<-INTERPOLATED_HEREDOC.strip_heredoc
# encoding: UTF-8
# This file is auto-generated from the current state of the database.
#
# #{version} database version used
# #{tables.size} tables had data
puts 'Seeding #{tables.size} tables for database version #{version}'
INTERPOLATED_HEREDOC
file.puts <<-'HEREDOC'.strip_heredoc
@connection = ActiveRecord::Base.connection
def insert_data(number, table_name, insert_sql)
before = @connection.exec_query("select count(1) from #{table_name}").first.first[1].to_i
@connection.execute insert_sql
after = @connection.exec_query("select count(1) from #{table_name}").first.first[1].to_i
puts "#{number}.\t#{after - before}\t#{after}\t#{table_name}"
end
puts "#\tadded\ttotal\ttable"
HEREDOC
tables.each_with_index do |table, index|
names = ''
selected_columns = []
array_length = []
columns_name = ActiveRecord::Base.connection.exec_query("show columns from #{table[1]}").rows
columns_name.delete_if { |x| x[0].end_with? '_at' }
columns_name.each do |x|
selected_columns.push "`#{x[0]}`"
record_values = ActiveRecord::Base.connection.exec_query("select `#{x[0]}` from #{table[1]}").rows.flatten.compact.max_by(&:length)
max_length = record_values.nil? ? 1 : record_values.length
if x[0].to_s.length >= max_length
names += x[0] + ', '
array_length.push x[0].to_s.length
else
names += x[0] + ', ' + ' ' * (max_length - x[0].length)
array_length.push max_length
end
end
names.slice! names.rindex(',')
names.gsub! 'order', '`order`'
value_data = ActiveRecord::Base.connection.exec_query("select #{selected_columns.join(',')} from #{table[1]}").rows
array_data = []
value_data.each do |e|
text = ''
e.each_with_index do |item, ind|
if item.nil?
text << 'NULL' + ', ' + ' ' * (array_length[ind] - 4)
else
text << "'" + item.to_s.gsub("'", "\\\\'") + "'" + ', ' + ' ' * (array_length[ind] - item.to_s.length)
end
end
text.slice! text.rindex(',')
array_data.push text.chop
end
print_data = ''
array_data.each { |element| print_data += '(' + element.to_s.gsub("\n", '\\n') + "),\n " }
file.puts <<-INTERPOLATED_HEREDOC.strip_heredoc
insert_data #{index + 1}, '#{table[1]}', <<-'HEREDOC'
INSERT INTO `#{table[1]}`
(#{names.chop}) VALUES
#{print_data.strip.chop + ';'}
HEREDOC
INTERPOLATED_HEREDOC
end
file.puts "puts 'done!'"
end
end
end
end
| true
|
5c69f34d96c82e3fbd49619f483180cdd358f0f8
|
Ruby
|
Ghuti/semaine14
|
/ex.rb
|
UTF-8
| 143
| 3.59375
| 4
|
[] |
no_license
|
1.upto(100) do |i|
if i % 5 == 0 and i % 3 == 0
puts "FizzBuzz"
elsif i % 5 == 0
puts "Buzz"
elsif i % 3 == 0
puts "Fizz"
else
puts i
end
end
| true
|
9bd6dcb5059e08b419d821c5f11c62825d106d4f
|
Ruby
|
niiicolai/P2-API
|
/app.rb
|
UTF-8
| 2,606
| 2.75
| 3
|
[] |
no_license
|
# Require the necessary libraries and models
require 'sinatra'
require 'sinatra/activerecord'
require './models/participant'
require './models/completed_activity'
require './models/failed_activity'
require './models/interaction'
require './models/rating'
require 'rack'
require 'rack/contrib'
# set the path to the database configuration
# for active record
use Rack::JSONBodyParser
set :database_file, "database.yml"
# A before filter that is called
# before any of routes below
before do
# Set the content type of the response body to json
# https://www.rubydoc.info/gems/sinatra/Sinatra%2FHelpers:content_type
content_type :json
end
get '/participants_delete' do
# delete everything
Participant.delete_all
CompletedActivity.delete_all
FailedActivity.delete_all
Interaction.delete_all
Rating.delete_all
{message: "OK"}.to_json
end
# Just for example
# Returns all participants
get '/participants' do
# Get all participants
participants = Participant.all
data = []
# Return the participants as json
participants.each_with_index do |participant, index|
data[index] = {
participant: participant.to_json,
failed_activities: participant.failed_activities.to_json,
completed_activities: participant.completed_activities.to_json,
interactions: participant.interactions.to_json,
ratings: participant.ratings.to_json
}
end
data.to_json
end
# Creates a new participant
post "/participant" do
# Create an instance of a new participant
# and instantly save it to the database
# by using .create instead of .new
participant = Participant.create(date_created: DateTime.now)
# return the new participant as json
participant.to_json
end
post "/failed_activity" do
participant = Participant.find(params["id"])
participant.failed_activities.create(activity_id: params["activity_id"])
{message: "OK"}.to_json
end
post "/completed_activity" do
participant = Participant.find(params["id"])
participant.completed_activities.create(activity_id: params["activity_id"])
{message: "OK"}.to_json
end
post "/interaction" do
participant = Participant.find(params["id"])
interaction = participant.interactions.create(
date_created: params["dateCreated"],
method: params["method"],
message: params["message"]
)
{message: "OK"}.to_json
end
post "/ratings" do
participant = Participant.find(params[:id])
params["ratings"].each do |r|
participant.ratings.create(
date_created: r["dateCreated"],
question: r["question"],
rate: r["rate"]
)
end
{message: "OK"}.to_json
end
| true
|
a47b129145b4d91e87a784984f45d4ffc5050df2
|
Ruby
|
dlains/rpl
|
/spec/rpl/parser_spec.rb
|
UTF-8
| 4,485
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
require 'parslet/convenience'
module Rpl
describe Parser do
it 'can parse a sentence with parentheses' do
result = Parser.new.parse_with_debug('PA implies (PB or PC)')
expect(result[:implies][:left][:symbol]).to eq('PA')
expect(result[:implies][:right][:or][:left][:symbol]).to eq('PB')
expect(result[:implies][:right][:or][:right][:symbol]).to eq('PC')
end
it 'can parse a sentence with nested parentheses' do
result = Parser.new.parse_with_debug('(PA implies (PB or PC)) and ((PD or PE) implies PF)')
expect(result[:and][:left][:implies][:left][:symbol]).to eq('PA')
expect(result[:and][:left][:implies][:right][:or][:left][:symbol]).to eq('PB')
expect(result[:and][:left][:implies][:right][:or][:right][:symbol]).to eq('PC')
expect(result[:and][:right][:implies][:left][:or][:left][:symbol]).to eq('PD')
expect(result[:and][:right][:implies][:left][:or][:right][:symbol]).to eq('PE')
expect(result[:and][:right][:implies][:right][:symbol]).to eq('PF')
end
it 'can parse a negated symbol' do
result = Parser.new.parse_with_debug('not PA')
expect(result.has_key?(:not)).to be_truthy
expect(result[:not][:right][:symbol]).to eq('PA')
end
it 'can parse a conjunction sentence' do
result = Parser.new.parse_with_debug('PA and PB')
expect(result.has_key?(:and)).to be_truthy
expect(result[:and][:left][:symbol]).to eq('PA')
expect(result[:and][:right][:symbol]).to eq('PB')
end
it 'can parse a disjunction sentence' do
result = Parser.new.parse_with_debug('PA or PB')
expect(result.has_key?(:or)).to be_truthy
expect(result[:or][:left][:symbol]).to eq('PA')
expect(result[:or][:right][:symbol]).to eq('PB')
end
it 'can parse an implies sentence' do
result = Parser.new.parse_with_debug('(PA and PB) implies not PC')
expect(result.has_key?(:implies)).to be_truthy
expect(result[:implies][:left][:and][:left][:symbol]).to eq('PA')
expect(result[:implies][:left][:and][:right][:symbol]).to eq('PB')
expect(result[:implies][:right][:not][:right][:symbol]).to eq('PC')
end
it 'can parse an iif sentence' do
result = Parser.new.parse_with_debug('PA iif not PB')
expect(result.has_key?(:iif)).to be_truthy
expect(result[:iif][:left][:symbol]).to eq('PA')
expect(result[:iif][:right][:not][:right][:symbol]).to eq('PB')
end
it 'can be the true constant' do
result = Parser.new.parse_with_debug('True')
expect(result.has_key?(:true)).to be_truthy
expect(result[:true]).to eq('True')
end
it 'can be the false constant' do
result = Parser.new.parse_with_debug('False')
expect(result.has_key?(:false)).to be_truthy
expect(result[:false]).to eq('False')
end
it 'can be a symbol' do
result = Parser.new.parse_with_debug('I90')
expect(result.has_key?(:symbol)).to be_truthy
expect(result[:symbol]).to eq('I90')
end
describe 'symbol' do
def parse_symbol(input)
return Parser.new.symbol.parse(input)
end
it 'starts with an upper case character' do
result = parse_symbol('Tree')
expect(result.has_key?(:symbol)).to be_truthy
expect(result[:symbol]).to eq('Tree')
end
it 'can have additional upper case characters' do
result = parse_symbol('TreeTop')
expect(result.has_key?(:symbol)).to be_truthy
expect(result[:symbol]).to eq('TreeTop')
end
it 'is delimeted by spaces' do
result = parse_symbol('Tree ')
expect(result.has_key?(:symbol)).to be_truthy
expect(result[:symbol]).to eq('Tree')
end
it 'can be a single character' do
result = parse_symbol('X')
expect(result.has_key?(:symbol)).to be_truthy
expect(result[:symbol]).to eq('X')
end
it 'can include numbers' do
result = parse_symbol('Tree10')
expect(result.has_key?(:symbol)).to be_truthy
expect(result[:symbol]).to eq('Tree10')
end
it 'can not start with a number' do
expect { parse_symbol('7Tree') }.to raise_error(Parslet::ParseFailed)
end
it 'can not start with a lower case character' do
expect { parse_symbol('tree') }.to raise_error(Parslet::ParseFailed)
end
end
end
end
| true
|
6fd28bcf9305affde2a0e9443028a0ba766c0b37
|
Ruby
|
Niikwartey/ttt-with-ai-project-wdf-000
|
/lib/players/computer.rb
|
UTF-8
| 1,211
| 3.40625
| 3
|
[] |
no_license
|
require 'pry'
module Players
class Computer < Player
attr_accessor :win_combinations, :board
WIN_COMBINATIONS = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [6,4,2]]
def initialize(token)
@token = token
@win_combinations = WIN_COMBINATIONS
end
def move(board)
@board = board
def play_or_nil(input)
!board.taken?(input) ? input : nil
end
def op_pos_count(combo)
combo.select do |position|
board.cells[position] != " " && board.cells[position] != @token
end.size
end
def best_op_combo
win_combos = @win_combinations.delete_if do |combo|
combo.any? {|position| board.cells[position] == @token} # || board.cells[position] != " "
end
win_combos.sort_by {|combo| op_pos_count(combo)}.last
end
def pick_move
best_op_combo ? best_op_combo.sample || [0,2,6,8].detect{|p|play_or_nil(p)} : rand(1..9) # play_or_nil([0,2,6,8].sample) ||
end
# board = board ? board : board
# binding.pry
play_or_nil("5") || (pick_move + 1).to_s || ["1","3","7","9"].detect{|p| play_or_nil(p)} || rand(1..9).to_s
end
end
end
| true
|
e391ae3db76e9c6cce714e559327c4418c997b09
|
Ruby
|
matrharr/data_structures-algorithms
|
/binary_tree_prac.rb
|
UTF-8
| 999
| 3.8125
| 4
|
[] |
no_license
|
class Node
attr_accessor :value, :right_child, :left_child
def initialize(val)
@value = val
@right_child = nil
@left_child = nil
end
end
class BinaryTree
attr_accessor :root
def initialize
@root = nil
end
def bt_insert(val)
@new_node = Node.new(val)
if @root == nil
@root = @new_node
else
def insert(current_node)
if current_node.value < @new_node.value
if current_node.right_child == nil
current_node.right_child = @new_node
else
insert(current_node.right_child)
end
elsif current_node.value > @new_node.value
if current_node.left_child == nil
current_node.left_child = @new_node
p current_node.left_child
else
insert(current_node.left_child)
end
end
end
return insert(@root)
end
end
end
b = BinaryTree.new
b.bt_insert(5)
b.bt_insert(4)
b.bt_insert(7)
b.bt_insert(3)
p b
| true
|
11ad644add55d2bc50c3675d1a5931343b52adc0
|
Ruby
|
christinebeaubrun/books
|
/ex16.rb
|
UTF-8
| 1,087
| 4.03125
| 4
|
[] |
no_license
|
filename = ARGV.first
# filename is a variable that test.txt is assigned to
script = $0
# this is the name of the program or test.txt
# the program worked fine even when I #ed it out
puts "For exercise #{script} We're going to erase #{filename}."
puts "If you dont want that, hit CTRL-C (^C)."
# CTRL-C will cancel the program
puts "If you do want that, hit RETURN."
print "?"
STDIN.gets
# I hit the enter key, next stage
puts "Opening the file . . . "
target = File.open(filename, 'w')
# w means write
puts "Truncating the file. Goodbye!"
target.truncate(target.size)
# truncate clears but what is target.size?
puts "Now I'm going to ask you for three lines."
print "line 1: "; line1 = STDIN.gets.chomp()
print "line 2: "; line2 = STDIN.gets.chomp()
print "line 3: "; line3 = STDIN.gets.chomp()
puts "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
puts "Let's read our text now: "
puts "#{line1}\\#{line2}\\#{line3}"
puts "Finally, we close our text."
target.close()
| true
|
e2b25eea021cb1081730094767782310ac72e13c
|
Ruby
|
rwalters/emcee
|
/lib/emcee/library.rb
|
UTF-8
| 2,052
| 3.296875
| 3
|
[] |
no_license
|
module Emcee
class Library
attr_reader :library
def initialize(library = {})
@library = library
end
def add(title, artist)
raise Emcee::DuplicateTitleError.new(title) unless library[title].nil?
library[title] = { artist: artist, played: false }
message = %Q[Added "#{title}" by #{artist}]
{message: message, library: self}
end
def play(title)
raise Emcee::TitleNotFoundError.new(title) if library[title].nil?
library[title][:played] = true
{ message: %Q[You're listening to "#{title}"], library: self }
end
def show_all
msg =
library.each.map do |elem|
title = elem.first
artist = elem.last[:artist]
played = elem.last[:played] ? "played" : "unplayed"
%Q["#{title}" by #{artist} (#{played})]
end.join("\n")
{ message: msg, library: self }
end
def show_unplayed
msg =
unplayed(library).each.map do |elem|
title = elem.first
artist = elem.last[:artist]
%Q["#{title}" by #{artist}]
end.join("\n")
{ message: msg, library: self }
end
def show_all_by(artist)
msg =
by_artist(artist, library)
.each
.map do |elem|
title = elem.first
artist = elem.last[:artist]
played = elem.last[:played] ? "played" : "unplayed"
%Q["#{title}" by #{artist} (#{played})]
end.join("\n")
{ message: msg, library: self }
end
def show_unplayed_by(artist)
msg =
by_artist(artist, unplayed(library))
.each
.map do |elem|
title = elem.first
artist = elem.last[:artist]
%Q["#{title}" by #{artist}]
end.join("\n")
{ message: msg, library: self }
end
private
def unplayed(lib)
lib.each.reject{|elem| elem.last[:played] }.to_h
end
def by_artist(artist, lib)
lib.each.select{|elem| elem.last[:artist] == artist }.to_h
end
end
end
| true
|
7310f280201ca9175b059ffc001860867382407a
|
Ruby
|
stefannibrasil/algoritmosii
|
/number_generator.rb
|
UTF-8
| 601
| 3.640625
| 4
|
[] |
no_license
|
def generate_numbers(n)
(1..n).to_a
end
def write_file(filename, arr)
File.open(filename, 'w') do |file|
arr.each do |n|
file.write(n)
file.write(' ')
end
end
end
# cem mil
numbers_100k = generate_numbers(10 ** 5)
write_file('100k_ordered.txt', numbers_100k)
write_file('100k_reverse.txt', numbers_100k.reverse)
write_file('100k_random_order.txt', numbers_100k.shuffle)
# 1 milhรฃo
numbers_1kk = generate_numbers(10 ** 6)
write_file('1kk_ordered.txt', numbers_1kk)
write_file('1kk_reverse.txt', numbers_1kk.reverse)
write_file('1kk_random_order.txt', numbers_1kk.shuffle)
| true
|
46be8656709eee3c81b01928cf9e71fd381e4dc7
|
Ruby
|
JeffWaltzer/tastydoc
|
/app/text_view.rb
|
UTF-8
| 1,540
| 3
| 3
|
[] |
no_license
|
require_relative "rendering_context"
require_relative "string_wrapper"
class TextView
def initialize(style_sheet)
@accumulator = ''
@last_level= nil
@display_indent= 0
@indented_sections= style_sheet[:indented_sections] || []
@bulleted_sections = style_sheet[:bulleted_sections] || []
@seperated_sections= style_sheet[:seperated_sections] || []
@nobreak_sections= style_sheet[:nobreak_sections] || []
end
def self.wrap_page(body)
body
end
def render(document)
@accumulator = ''
context= RenderingContext.new(self, :document, document, 0)
context.render_document
@accumulator
end
def indent(level)
end
def link(document_text, document_link, level, style)
if document_text == document_link
string("#{document_link}", level, style)
else
string("#{document_text} (#{document_link})", level, style)
end
end
def begin_paragraph(style)
if @indented_sections.include?(style)
@display_indent += 1
end
end
def end_paragraph(style)
if @indented_sections.include?(style)
@display_indent -= 1
end
if @seperated_sections.include?(style)
@accumulator += "\n"
end
end
def paragraph(style, level)
begin_paragraph(style)
yield(level)
end_paragraph(style)
end
def string(s, level, style)
line_prefix = ' ' * @display_indent
bullet= @bulleted_sections.include?(style)
@accumulator += StringWrapper.new(line_prefix, bullet).wrap(s, @nobreak_sections.include?(style))
end
end
| true
|
4e2ca3681b9817cb3cc1c9df4babc09681e45a6e
|
Ruby
|
zonika/jukebox-cli-web-0715-public
|
/lib/jukebox.rb
|
UTF-8
| 1,425
| 3.546875
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
songs = [
"Phoenix - 1901",
"Tokyo Police Club - Wait Up",
"Sufjan Stevens - Too Much",
"The Naked and the Famous - Young Blood",
"(Far From) Home - Tiga",
"The Cults - Abducted",
"Phoenix - Consolation Prizes",
"Harry Chapin - Cats in the Cradle",
"Amos Lee - Keep It Loose, Keep It Tight"
]
def say_hello(name)
"Hi #{name}!"
end
def help
puts "help: displays this message\n
list: displays a list of songs you can play\n
play: lets you choose a song to play\n
exit: exits this program\n"
end
def play(songs)
list(songs)
puts "Select a song by entering its number or full title: "
input=gets.chomp
nums=["1","2","3","4","5","6","7","8"]
flag=true
songs.each do |song|
if song==input
puts "Playing #{song}"
flag=false
end
end
nums.each do |num|
if num==input
puts "Playing #{songs[num.to_i-1]}"
flag=false
end
end
if flag==true
puts "Invalid input, please try again"
end
end
def list(songs)
songs.each_with_index do |song, index|
puts "#{index+1}. #{song}"
end
end
def get_input
puts "Please enter a command:\n"
input=gets.chomp
end
def exit_jukebox
puts "Goodbye"
end
def run(songs)
input=get_input
while input.downcase != "exit"
case input.downcase
when "help"
help
when "play"
play(songs)
when "list"
list(songs)
end
input=get_input
end
exit_jukebox
end
| true
|
ad52691633e70770dcf870b7e93b61a32616f1e7
|
Ruby
|
kjdchapman/aoc-1
|
/run_find_repeat_frequency.rb
|
UTF-8
| 140
| 2.546875
| 3
|
[] |
no_license
|
require './lib/find_repeat_frequency'
calculator = FindRepeatFrequency.new
input = File.read("./input.txt")
puts calculator.execute(input)
| true
|
dcb5b6d0a3b4305448c171ae1dc8ccdc614ffd5c
|
Ruby
|
itiswhatitisio/rb101
|
/lesson_5/pp_15.rb
|
UTF-8
| 562
| 3.921875
| 4
|
[] |
no_license
|
=begin
# Problem:
return an array which contains only the hashes
where all the integers are even
Input: array with hashes
Output: array
# Requirements
- hashes should contain only even numbers
# Examples:
arr = [{e: [8], f: [6, 10]}]
# Data structure/Algorithm
- since the returned value should be array,
need to use select method
=end
arr = [{a: [1, 2, 3]}, {b: [2, 4, 6],
c: [3, 6], d: [4]}, {e: [8], f: [6, 10]}]
result = arr.select do |hsh|
hsh.all? do |key, val|
val.all? do |num|
num.even?
end
end
end
p result
| true
|
fa5e82d1d598ce8360605457fef3261c76e05ba4
|
Ruby
|
dubroe/twitter-doghouse
|
/app/models/request_from_twitter.rb
|
UTF-8
| 2,332
| 2.828125
| 3
|
[] |
no_license
|
# This table is for incoming requests from Twitter to add people to Doghouse
class RequestFromTwitter < ActiveRecord::Base
MINUTES_CHAR = 'm'
HOURS_CHAR = 'h'
DAYS_CHAR = 'd'
DURATION_TYPES = [MINUTES_CHAR, HOURS_CHAR, DAYS_CHAR]
DURATION_MINUTES_MULTIPLIER_MAP = {"#{MINUTES_CHAR}" => 1, "#{HOURS_CHAR}" => MINUTES_IN_HOUR, "#{DAYS_CHAR}" => MINUTES_IN_DAY}
belongs_to :user
attr_accessible :tweet_id, :text
# This is called periodically to see if any new add to doghouse requests have been created
# Tweet must be of the form: @TwitDoghouse username timeframe tweet
def self.handle_incoming_requests
# Find all tweets since last processed request that include @TwitDoghouse
requests = Twitter.search SEARCH_QUERY, result_type: 'recent', since_id: RequestFromTwitter.last.try(:tweet_id)
# Loop through each tweet from earliest to most recent
requests.reverse_each do |request|
user = User.find_by_nickname request.from_user
next unless user # The tweeter must be a user in our system
text_split = request.text.split ' '
next if text_split.length < 3 # There must be at least three 'words' in the tweet
next unless text_split[0] == SEARCH_QUERY # Must start with @TwitDoghouse
duration = text_split[2].chop #Should be of form 29m. This removes the last char.
duration_type = text_split[2][-1] #Last char
next unless duration.to_i > 0 # Duration must be a positive integer
next unless DURATION_TYPES.include?(duration_type) # Duration type must be 'm', 'h', or 'd'
duration_minutes = DURATION_MINUTES_MULTIPLIER_MAP[duration_type] * duration.to_i # Calculate the duration_minutes
next unless Twitter.friendship(request.from_user, text_split[1]).source.following # screen_name to add to doghouse. Must be currently following.
enter_tweet = text_split[3..-1].join ' ' # Enter tweet is anything after the third 'word'
request_from_twitter = user.request_from_twitters.create(tweet_id: request.id, text: request.text) # Create the request from twitter entry
# Create the DogHouse entry based on the request
user.doghouses.create({screen_name: text_split[1], duration_minutes: duration_minutes, enter_tweet: enter_tweet, request_from_twitter_id: request_from_twitter.id}, as: :safe_code)
end
end
end
| true
|
366ba76eafe3d8b7f100e6d6fef4e67d5dd2fa78
|
Ruby
|
MichaelXavier/hollaback_admin
|
/spec/hollaback_inbound/helpers_spec.rb
|
UTF-8
| 1,902
| 2.515625
| 3
|
[] |
no_license
|
require 'hollaback_inbound/helpers'
module HollabackInbound
describe Helpers do
class HelpersTest; include HollabackInbound::Helpers; end
subject { HelpersTest.new }
describe "#calculate_offset" do
it "returns 0 for GMT" do
subject.calculate_offset("Fri, 17 Feb 2012 20:19:46 -0000").
should == 0
end
it "returns the proper time for pacific time" do
subject.calculate_offset("Fri, 17 Feb 2012 20:19:46 -0800").
should == -28800
end
end
describe "payload handling" do
let(:payload) do
{
"Date" => "Fri, 17 Feb 2012 20:19:46 -0800",
"From" => "joe@example.com",
"To" => "3h@hollaback.example.com",
"Subject" => "holla back!",
"TextBody" => "woop woop"
}
end
describe "#simplify_payload" do
it "parses out the relevant data" do
subject.simplify_payload(payload).should == {
'from' => "joe@example.com",
'to' => "3h@hollaback.example.com",
'subject' => "holla back!",
'body' => "woop woop",
'offset_seconds' => -28800
}
end
end
describe "#store" do
let(:redis) { mock("Redis", :rpush => 1) }
before(:each) do
subject.stub(:redis).and_return(redis)
end
it "pushes the simplified payload to the end of the message queue" do
redis.should_receive(:rpush).with do |key, json|
key == "messages" &&
JSON.parse(json) == {
'from' => "joe@example.com",
'to' => "3h@hollaback.example.com",
'subject' => "holla back!",
'body' => "woop woop",
'offset_seconds' => -28800
}
end
subject.store(payload)
end
end
end
end
end
| true
|
1b77f16ef6337faacee3ed2cd5ac3fc489771a96
|
Ruby
|
onosi/aoj
|
/Introduciton_to_programming/Finding_Missing_Cards.rb
|
UTF-8
| 624
| 3.40625
| 3
|
[] |
no_license
|
S = Array.new(13,false)
H = Array.new(13,false)
C = Array.new(13,false)
D = Array.new(13,false)
numbers = gets.to_i
numbers.times do | n |
a,b = gets.split(' ')
b = b.to_i
case a
when "S"
S[b-1] = true
when "D"
D[b-1] = true
when "C"
C[b-1] = true
when "H"
H[b-1] = true
end
end
S.each_with_index do |n, i|
puts "S #{i + 1}" if n == false
end
H.each_with_index do |n, i|
puts "H #{i + 1}" if n == false
end
C.each_with_index do |n, i|
puts "C #{i + 1}" if n == false
end
D.each_with_index do |n, i|
puts "D #{i + 1}" if n == false
end
| true
|
7705b200ef3cfd21812aa387c022fffbaa23d951
|
Ruby
|
katsuster/nqueens_ruby
|
/nqueens.rb
|
UTF-8
| 1,723
| 3.65625
| 4
|
[
"Apache-2.0"
] |
permissive
|
require_relative 'solver.rb'
def main(argv)
if argv.length < 2
puts 'usage: \n' +
'NQueens queens(1 ... 30) parallel(true or false)'
return -1
end
#get the arguments
n = argv[0].to_i
if n < 0 || 30 < n
n = 0
end
puts 'queens : ' + n.to_s()
parallel = false
if argv.length >= 2
case argv[1].class == String ? argv[1].downcase : argv[1]
when 'true', 'True'
parallel = true
when 'false', 'False'
parallel = false
end
end
puts 'parallel: ' + parallel.to_s()
#start
start = Time.now()
#solve
center = n >> 1
solvers = []
solver_threads = []
answer = 0
for x in 0..center - 1
#left half
row = 1 << x
left = row << 1
right = row >> 1
s = Solver.new(row, left, right, n, 1, 0)
if parallel
t = Thread.new(s) do |r|
r.run()
end
solver_threads.push(t)
else
s.run()
end
solvers.push(s)
end
if n % 2 == 1
#center(if N is odd)
row = 1 << center
left = row << 1
right = row >> 1
solver_remain = Solver.new(row, left, right, n, 1, 0)
if parallel
solver_remain_thread = Thread.new(solver_remain) do |r|
r.run()
end
else
solver_remain.run()
end
end
#join
for x in 0..center - 1
if parallel
solver_threads[x].join()
end
answer += solvers[x].get_new_answer()
end
answer *= 2
if n % 2 == 1
if parallel
solver_remain_thread.join()
end
answer += solver_remain.get_new_answer()
end
#finished
elapse = Time.now() - start
#solved
puts 'answers : ' + answer.to_s()
puts 'time : ' + elapse.to_s() + '[s]'
end
if __FILE__ == $0
main(ARGV)
end
| true
|
0c99768eae0136df557bc6ce01f00b9cdf2fb69c
|
Ruby
|
christophe48/bot_tw
|
/lib/bot_qui_like.rb
|
UTF-8
| 710
| 2.53125
| 3
|
[] |
no_license
|
# ligne trรจs importante qui appelle la gem.
require 'twitter'
require 'dotenv'# n'oublie pas les lignes pour Dotenv iciโฆ
Dotenv.load('.env')
# quelques lignes qui appellent les clรฉs d'API de ton fichier .env
client = Twitter::REST::Client.new do |config|
config.consumer_key = ENV["TWITTER_CONSUMER_KEY"]
config.consumer_secret = ENV["TWITTER_CONSUMER_SECRET"]
config.access_token = ENV["TWITTER_ACCESS_TOKEN"]
config.access_token_secret = ENV["TWITTER_ACCESS_TOKEN_SECRET"]
end
#je collect les info que je cherche avec client search
like_this = client.search("#bonjour_monde", recent_type: "recent").take(25)
#je like ma recherche avec client.favorite
client.favorite(like_this)
| true
|
45dff0d404c6c60974e48d368bd5fc81301ee715
|
Ruby
|
joshdales/08-11-Reinforcing-exercise-API-Calls
|
/exercise.rb
|
UTF-8
| 216
| 2.921875
| 3
|
[] |
no_license
|
require 'HTTParty'
response = HTTParty.get('http://setgetgo.com/randomword/get.php')
words = []
k = 1
10.times do |k, v|
words[k] = HTTParty.get('http://setgetgo.com/randomword/get.php')
k += 1
end
puts words
| true
|
bda831bdb461806f715d4819b3218b451278246a
|
Ruby
|
John-Odom/bringing-it-all-together-atlanta-web-071519
|
/lib/dog.rb
|
UTF-8
| 2,526
| 3.171875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Dog
attr_accessor :id, :name, :breed
def initialize (props = {})
@id = props[:id]
@name = props[:name]
@breed = props[:breed]
end
def self.create_table
sql = <<-SQL
CREATE TABLE dogs (
id INTEGER PRIMARY KEY,
name TEXT,
breed TEXT
);
SQL
DB[:conn].execute(sql)
end
def self.drop_table
sql = <<-SQL
DROP TABLE
IF EXISTS dogs
SQL
DB[:conn].execute(sql)
end
def save
sql = <<-SQL
INSERT INTO dogs
(name, breed)
VALUES (?, ?)
SQL
DB[:conn].execute(sql, self.name, self.breed)
self.id = DB[:conn].execute("SELECT last_insert_rowid() FROM dogs")[0][0]
self
end
def self.create (props)
dog = Dog.new (props)
dog.save
dog
end
def self.new_from_db (props)
dog = Dog.new
dog.id = props[0]
dog.name = props[1]
dog.breed = props[2]
dog
end
def self.find_by_id (id)
dog = Dog.new
sql = <<-SQL
SELECT *
FROM dogs
WHERE id = ?
SQL
row = DB[:conn].execute(sql, id).flatten
dog.id = row[0]
dog.name = row[1]
dog.breed = row[2]
dog
end
def self.find_by_name(name)
sql = <<-SQL
SELECT *
FROM dogs
WHERE name = ?
SQL
row = DB[:conn].execute(sql, name).flatten
self.new_from_db(row)
end
def self.find_or_create_by(props)
# if props doeesn't have an id, we need to create and return it.
# Otherwise we need to find it.
sql = <<-SQL
SELECT *
FROM dogs
WHERE name = ?
AND breed = ?
SQL
row = DB[:conn].execute(sql, props[:name], props[:breed]).flatten
if !row.empty?
dog = Dog.new
dog.id = row[0]
dog.name = row[1]
dog.breed = row[2]
dog
else
dog = self.create(props)
end
end
def update
sql = <<-SQL
UPDATE dogs
SET name = ?
WHERE id = ?
SQL
DB[:conn].execute(sql, self.name, self.id)
end
end
| true
|
7f37fa31e4ff45071b403bd795c57f210452519e
|
Ruby
|
thinkwell/yolk-client
|
/lib/yolk-client/client/enrollments.rb
|
UTF-8
| 1,986
| 2.546875
| 3
|
[] |
no_license
|
require 'time'
module Yolk
class Client
# Defines all api calls related to enrollments
module Enrollments
def enrollments options = {}
format_search_options options
response = get('enrollments', options)
prepare_enrollments response
end
def enrollments_by_entity entity, options = {}
format_search_options options
options.merge! "search[limit_results]" => 0 unless options["search[limit_results]"]
response = get("entities/#{entity}/enrollments", options)
prepare_enrollments response
end
def enrollments_by_owner owner, options = {}
format_search_options options
options.merge! "search[limit_results]" => 0 unless options["search[limit_results]"]
options.merge! "search[owner]" => owner
enrollments(options)
end
def enrollments_by_assignee assignee, options = {}
format_search_options options
options.merge! "search[limit_results]" => 0 unless options["search[limit_results]"]
options.merge! "search[assigned_to]" => assignee
enrollments(options)
end
def enrollment uuid
response = get("enrollments/#{uuid}")
prepare_enrollment(response)
end
def enrollment_create enrollment
response = post('enrollments', {:enrollment => enrollment})
prepare_enrollment(response)
end
def enrollment_update uuid, enrollment
put("enrollments/#{uuid}", {:enrollment => enrollment})
end
def enrollment_destroy uuid
delete("enrollments/#{uuid}")
end
private
def prepare_enrollments enrollments
enrollments.each {|e| prepare_enrollment e }
enrollments
end
def prepare_enrollment enrollment
# Parse dates
enrollment.select{|k, v| v && k =~ /_(date|at)$/}.
each{|k, v| enrollment.send(:"#{k}=", Time.parse(v))}
enrollment
end
end
end
end
| true
|
61ad1d54cdc1bdf0c01cdea24e84dd725da823d5
|
Ruby
|
tomykaira/dropnico
|
/lib/youtube/url.rb
|
UTF-8
| 1,884
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
require 'cgi'
module Youtube
class Url
def self.parse_map(encoded_stream_map)
encoded_stream_map.split(',').map { |part| self.new(part) }
end
def initialize(encoded_stream)
@encoded_stream = encoded_stream
end
def download_url
url = param('url')
if sig = param('sig')
url + "&signature=" + sig
elsif s = param('s')
sig = s[6, 1] + s[1, 2] + s[62, 1] + s[7,36] +
s[0,1] + s[56,1] + s[45,11] + s[43,1] + s[57,5] +
s[3,1] + s[63,21];
url + "&signature=" + sig
else
raise "No signature in #{@encoded_stream}"
end
end
def itag
itag = param('itag')
if itag
itag.to_i
else
raise "No itag in #{@encoded_stream}"
end
end
# http://en.wikipedia.org/wiki/YouTube
def video_resolution
res = {
5 => 240,
6 => 270,
13 => 0,
17 => 144,
18 => 360,
22 => 720,
34 => 360,
35 => 480,
36 => 240,
37 => 1080,
38 => 3072,
43 => 360,
44 => 480,
45 => 720,
46 => 1080,
82 => 360,
83 => 240,
84 => 720,
85 => 520,
100 => 360,
101 => 360,
102 => 720,
120 => 720,
}[itag]
if res
res
else
raise "Unknown itag #{itag} in #{@encoded_stream}"
end
end
def ext
case itag
when 5, 6, 34, 36, 120
'flv'
when 13, 17, 36
'3gp'
when 18, 22, 37, 38, 82, 83, 84, 85
'mp4'
when 43, 44, 45, 46, 100, 101, 102
'webm'
else
raise "Unknown itag #{itag} in #{@encoded_stream}"
end
end
def param(name)
params[name].first
end
def params
CGI.parse(@encoded_stream)
end
end
end
| true
|
ffaa4fbb204d32b330b2bd89c94589ecdfaa9e1d
|
Ruby
|
sleeperbus/Ordin
|
/beginning_ruby/unittest.rb
|
UTF-8
| 469
| 3.109375
| 3
|
[] |
no_license
|
class String
def titlelize
self.gsub(/(\A|\s)\w/) { |letter| letter.upcase }
end
end
require 'minitest/autorun'
#require 'test/unit'
#class TestTitlelize < Test::Unit::TestCase
class TestTitlelize < Minitest::Test
def test_basic
assert_equal("This Is A Test", "this is a test".titlelize)
assert_equal("Another Test 1234", "another test 1234".titlelize)
assert_equal("We're Testing", "We're testing".titlelize)
end
end
| true
|
de9c3ad85284c0fc1a9fd1890a317830f1fa8ab6
|
Ruby
|
donjar/counting-stream
|
/app/counter_systems/median_counter_system.rb
|
UTF-8
| 357
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require_relative 'counter_system'
require_relative '../helpers/array_averages'
Array.include ArrayAverages
# The query method in this class finds the median of all corresponding boxes.
class MedianCounterSystem < CounterSystem
def query(num)
@hash_functions.map { |hf| @counters[hf.id][hf.hash(num)] }.median
end
end
| true
|
d6265a4b43fd51b652c2813ebbaff864f5bf318a
|
Ruby
|
wildkain/BlackJack
|
/interface.rb
|
UTF-8
| 1,434
| 3.578125
| 4
|
[] |
no_license
|
class Interface
def welcome_message
line
p 'Welcome to BlackJack game!'
p 'We hope you are Lucky Guy!'
line
end
def ask_name
p 'What is your name? Please enter:'
gets.chomp.to_s
end
def get_action
p "What you to do? Enter |'1' - Hit!|, |'2' - Stand|, |'3' - show cards|"
gets.chomp.to_i
end
def greeting(player_name)
p "Exellent, #{player_name}! Lets start our adventures!"
line
end
def show_info(user)
p "#{user.name} Cards #{user.hand}. Scores: #{user.scores}. Cash: #{user.cash}"
end
def prepare_deck
p 'Now we prepare deck and shuffle'
p 'You and the dealer get 2 cards'
end
def line
p '------------------------------------------'
end
def show_cards(user)
p "<==== #{user.name} cards: #{user.hand.each { |card| print card.show }} Scores: #{user.scores}"
end
def show_dealer_cards(user)
p "Dealer have #{user.hand.size} cards. Cash: #{user.cash} "
end
def show_last_card(user)
p "#{user.name} are take card: #{user.hand[2].show}"
end
def new_game_answer
p 'Want to play else? 1 - Yes, 2 - NO'
gets.chomp.to_i
end
def goodbye
'This is GOOD GAME, Bro! See you later.'
end
def no_money_no_honey
p "So sorry. We can't play else("
end
def show_winner(user)
p "#{user.name} WIN!!! Scores: #{user.scores} Cash: #{user.cash}"
end
def nobody_wins
p ' Nobody wins('
end
end
| true
|
865e163ac91cbbe639ddc643f0c9b998af4bbcab
|
Ruby
|
danielmachado/kermitpfc-core
|
/lib/business/converter/twitter_converter.rb
|
UTF-8
| 3,253
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
require 'json'
require_relative './converter'
require_relative '../../model/USMF/USMF'
require_relative '../../model/USMF/link'
require_relative '../../model/USMF/to_user'
require_relative '../../model/USMF/user'
require_relative '../../logging'
# @author Daniel Machado Fernandez
# @version 1.0
#
# Twitter Specification from Converter
class TwitterConverter < Converter
include Logging
# Field to field parsing to become a tweet into a USMF message
#
# @param status [String] the tweet previously retrieved
# @return [USMF] the resultant message
def to_usmf status
usmf = USMF.new
user = User.new
status = JSON.parse(status)
if status.has_key? 'Error'
logger.error("tweet malformed")
raise "status malformed"
end
#Retrieving a status from Twitter
usmf.service = "Twitter"
usmf.id = status["id_str"]
x = status["coordinates"]
unless x==nil
usmf.geo = x["coordinates"]
end
usmf.application = status["source"]
x = status["place"]
unless x == nil
usmf.location = x["full_name"] + " , " + x["country"]
end
usmf.date = status["created_at"]
usmf.text = status["text"]
usmf.description = status["in_reply_to_status_id_str"]
usmf.likes = status["retweet_count"]
#Retrieving user
x = status["user"]
unless x == nil
user.name = x["screen_name"]
user.real_name = x["name"]
user.id = x["id_str"]
user.language = x["lang"]
unless x["time_zone"] == nil and x["utc_offset"] == nil
user.utc = x["time_zone"].to_s + " + " + x["utc_offset"].to_s
end
user.description = x["description"]
user.avatar = x["profile_image_url_https"]
user.location = x["location"]
user.subscribers = x["followers_count"]
user.subscriptions = x["friends_count"]
user.postings = x["statuses_count"]
user.profile = "https://twitter.com/#!/#{user.name}"
user.website = x["url"]
usmf.user = user
usmf.source = "https://twitter.com/#{usmf.user.name}/status/#{usmf.id}"
end
usmf.to_users = []
usmf.links = []
#Retrieving entities
entities = status["entities"]
unless entities == nil
#Retrieving URLs
x = entities["urls"]
unless x == nil
x.each do |item|
l = Link.new
l.href = item["url"]
usmf.links << l
end
end
#Retrieving all media content
x = entities["media"]
unless x == nil
x.each do |item|
l = Link.new
l.title = item["type"]
l.thumbnail = item["media_url"]
l.href = item["url"]
usmf.links << l
end
end
#Retrieving hashtags
x = entities["hashtags"]
unless x == nil
usmf.keywords = ""
x.each do |h|
usmf.keywords += h["text"] + ", "
end
end
#Retrieving mentions
x = entities["user_mentions"]
unless x == nil
x.each do |item|
tu = ToUser.new
tu.name = item["screen_name"]
tu.id = item["id_str"]
if item["id_str"] == status["in_reply_to_user_id_str"]
tu.service = "reply"
else
tu.service = "mention"
end
unless status["in_reply_to_status_id_str"] == nil
tu.title = status["in_reply_to_status_id_str"]
tu.href = "https://twitter.com/#{tu.name}/status/#{tu.title}"
end
usmf.to_users << tu
end
end
end
usmf
end
end
| true
|
3df09beef9fd6c37bf8e27c89e89d6894c2c9a3d
|
Ruby
|
chsweet/viewing_party
|
/app/poros/actor.rb
|
UTF-8
| 186
| 2.59375
| 3
|
[] |
no_license
|
class Actor
attr_reader :name,
:role
def initialize(data)
@name = data[:name]
@role = data[:character]
@department = data[:known_for_department]
end
end
| true
|
dfac4db411c3d6e799efcae1eb4a4e55cb3aef4c
|
Ruby
|
lhoj4228/coderbyte
|
/simplesymbols.rb
|
UTF-8
| 366
| 3.109375
| 3
|
[] |
no_license
|
def SimpleSymbols(str)
i = 0
while i < str.length
if str[i].ord > 96 && str[i].ord < 123
if (i == 0 || (i == str.length-1))
return "false"
end
if (str[i-1].ord != 43) || (str[i+1].ord != 43)
return "false"
end
end
i+=1
end
return "true"
end
SimpleSymbols(STDIN.gets)
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.