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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
cd1f491c9e54da990a61ccd054e517bb388dc315 | Ruby | ndrewpacheco/RB130 | /ruby_challenges/easy1/sieve.rb | UTF-8 | 1,589 | 4.28125 | 4 | [] | no_license | # Write a program that uses the Sieve of Eratosthenes to find all the primes from 2
# up to a given number.
# The Sieve of Eratosthenes is a simple, ancient algorithm for
# finding all prime numbers up to any given limit.
#
# It does so by iteratively marking as composite (i.e. not prime)
#the multiples of each prime, starting with the multiples of 2.
# Create your range, starting at two and continuing up to and including the given limit.
# (i.e. [2, limit]).
# The algorithm consists of repeating the following over and over:
# take the next available unmarked number in your list (it is prime)
# mark all the multiples of that number (they are not prime)
# Repeat until you have processed each number in your range.
# When the algorithm terminates,
#all the numbers in the list that have not been marked are prime.
#The wikipedia article has a useful graphic that explains the algorithm.
# Notice that this is a very specific algorithm,
# and the tests don't check that you've implemented the algorithm,
# only that you've come up with the correct list of primes.
class Sieve
UNMARKED = :unmarked
MARKED = :marked
def initialize(last_num)
@last_num = last_num
@multiples = (2..last_num).to_a
@collection = Hash[(2..last_num).map { |num| [num, UNMARKED] }]
end
def primes
@multiples.each do |multiple|
@collection.each do |item, _|
next if @collection[item] == MARKED
@collection[item] = MARKED if item % multiple == 0 && item != multiple
end
end
@collection.select {|_, marker| marker == UNMARKED}.keys
end
end | true |
4fa19b2ffa82cf3e8d5767b449529ee26111d7f4 | Ruby | loveshell/asciinema.org | /spec/models/terminal_spec.rb | UTF-8 | 3,513 | 2.6875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | # encoding: utf-8
require 'spec_helper'
describe Terminal do
let(:terminal) { Terminal.new(6, 3) }
let(:first_line_text) { subject.as_json.first.map(&:first).join.strip }
before do
data.each do |chunk|
terminal.feed(chunk)
end
end
after do
terminal.release
end
describe '#snapshot' do
subject { terminal.snapshot }
let(:data) { ["fo\e[31mo\e[42mba\n", "\rr\e[0mb\e[1;4;5;7maz"] }
it 'returns an instance of Snapshot' do
expect(subject).to be_kind_of(Snapshot)
end
it "returns screen cells groupped by the character attributes" do
expect(subject.as_json).to eq([
[
['fo', {}],
['o', fg: 1],
['ba', fg: 1, bg: 2],
[' ', {}],
],
[
['r', fg: 1, bg: 2],
['b', {}],
['az', bold: true, underline: true, inverse: true, blink: true],
[' ', inverse: true], # <- cursor here
[' ', {}]
],
[
[' ', {}]
]
])
end
describe 'utf-8 characters handling' do
let(:terminal) { Terminal.new(20, 1) }
context "when polish national characters given" do
let(:data) { ['żółć'] }
it 'returns proper utf-8 string' do
expect(first_line_text).to eq('żółć')
end
end
context "when chinese national characters given" do
let(:data) { ['雞機基積'] }
it 'returns proper utf-8 string' do
expect(first_line_text).to eq('雞機基積')
end
end
end
context "when invalid utf-8 character is yielded by tsm_screen" do
let(:terminal) { Terminal.new(3, 1) }
let(:data) { ["A\xc3\xff\xaaZ"] }
it 'gets replaced with "�"' do
expect(first_line_text).to eq('A�Z')
end
end
context "when double quote character ...." do
let(:terminal) { Terminal.new(6, 1) }
let(:data) { ['"a"b"'] }
it 'works' do
expect(first_line_text).to eq('"a"b"')
end
end
context "when backslash character..." do
let(:terminal) { Terminal.new(6, 1) }
let(:data) { ['a\\b'] }
it 'works' do
expect(first_line_text).to eq('a\\b')
end
end
describe 'with a 256-color mode foreground color' do
subject { terminal.snapshot.as_json.first.first.last[:fg] }
let(:data) { ["\x1b[38;5;#{color_code}mX"] }
(1..255).each do |n|
context "of value #{n}" do
let(:color_code) { n }
it { should eq(n) }
end
end
end
describe 'with a 256-color mode background color' do
subject { terminal.snapshot.as_json.first.first.last[:bg] }
let(:data) { ["\x1b[48;5;#{color_code}mX"] }
(1..255).each do |n|
context "of value #{n}" do
let(:color_code) { n }
it { should eq(n) }
end
end
end
end
describe '#cursor' do
subject { terminal.cursor }
let(:data) { ["foo\n\rba"] }
it 'gets its x position from the screen' do
expect(subject.x).to eq(2)
end
it 'gets its y position from the screen' do
expect(subject.y).to eq(1)
end
it 'gets its visibility from the screen' do
expect(subject.visible).to eq(true)
end
context "when cursor was hidden" do
before do
terminal.feed("\e[?25l")
end
it 'gets its visibility from the screen' do
expect(subject.visible).to eq(false)
end
end
end
end
| true |
ad89f43917da6c47162e2429d9327a337f883b95 | Ruby | afast/chess-rate | /lib/board/pawn.rb | UTF-8 | 1,892 | 2.90625 | 3 | [] | no_license | module Board
class Pawn < Piece
def can_move_to? position
return InvalidPositionError.new unless position.valid?
rank_dis = @position.rank_distance(position) # rank distance
file_dis = @position.file_distance(position) # file distance
can_move = (position.rank - @position.rank) == (side == :black ? -1 : 1)
can_move = can_move && rank_dis == 1 && (file_dis == 0 && @board.square_empty?(position) ||
file_dis == 1 && (!@board.square_empty?(position) || @board.en_passant.to_s == position.to_s)) # can move forward
can_move = can_move || rank_dis == 2 && file_dis == 0 && # en passant
@board.empty_ranks_between?(@position, position) && (position.rank - @position.rank) == (side == :black ? -2 : 2)
can_move
end
def move_to position
raise NoPositionError.new unless @position && position
from = @position.to_s
@board.set_piece(nil, @position.file_to_i, rank) # empty from coords
if position.to_s == @board.en_passant.to_s
pos = Position.new(position.file, position.rank + (side == :black ? 1 : -1))
@board.eliminate @board.piece_at(pos) # eliminate piece if there was one
@board.set_piece(nil, pos.file_to_i, pos.rank) # empty from coords
else
@board.eliminate @board.piece_at(position) # eliminate piece if there was one
end
if @position.rank_distance(position) == 2
@board.en_passant = Position.new(position.file, position.rank + (side == :black ? 1 : -1))
else
@board.en_passant = nil
end
@position = position
@board.set_piece(self, position.file_to_i, rank) # place piece in new coords
from # return algebraic old source
end
def board_print
side == :black ? 'p' : 'P'
end
end
class InvalidPositionError < StandardError; end
end
| true |
c173d8636be593b6075939aac24ba4112e6de5a5 | Ruby | djwonk/method_trails | /test/helpers/subject_s_exp.rb | UTF-8 | 846 | 2.5625 | 3 | [
"MIT"
] | permissive | require 'require_relative'
require_relative '/../../lib/classes/s_exp'
SUBJECT_S_EXP =
[:program,
[
[:class,
[:const_ref, [:@const, "VerySimple", [1, 6]]],
nil,
[:body_stmt,
[
[:def,
[:@ident, "method_one", [2, 6]],
[:params, nil, nil, nil, nil, nil],
[:body_stmt,
[
[:var_ref, [:@ident, "method_two", [3, 4]]]
],
nil,
nil,
nil
]
],
[:def,
[:@ident, "method_two", [5, 6]],
[:params, nil, nil, nil, nil, nil],
[:body_stmt,
[
[:binary,
[
:binary, [:@int, "1", [6, 4]],
:+,
[:@int, "2", [6, 8]]
],
:+,
[:@int, "3", [6, 12]]
]
],
nil,
nil,
nil
]
]
],
nil,
nil,
nil
]
]
]
].to_s_exp
| true |
ba73c86690a13e5a3a1146a37ec9fe521179e181 | Ruby | mlovic/mtb-scrape-scraper | /lib/scraper.rb | UTF-8 | 1,281 | 2.796875 | 3 | [] | no_license | require 'uri'
require 'mechanize'
require_relative 'scraper/spider'
require_relative 'logging'
class Scraper
Thread.abort_on_exception = true
include Logging
def initialize(processor)
@url_q = Queue.new
@pages_q = Queue.new
@processor = processor
end
def start(options = {})
#offset = options[:start_page] || 1
# TODO handle errors in spider thread
return false if started?
@spider = Spider.new(Mechanize.new) # get rid of hardcoded limit
logger.info "Starting spider..."
@spider.crawl_async(url_q, pages_q) # Async. Starts thread and returns immediately.
logger.info "Starting processor..."
@processor.process_async(pages_q, url_q)
# TODO handle potential deadlock error. Sleep and retry?
#url_q.empty? &&
#!@spider.waiting_for_response?
return true
end
def enq(url, handler)
url_q << [url, handler]
end
def done?
url_q.empty? &&
pages_q.empty? &&
@processor.waiting? &&
@spider.waiting?
end
def stop
return false unless started?
logger.info "Killing spider and processor threads..."
@spider.kill
@processor_thread.kill
end
def started?
@processor_thread&.alive?
end
private
attr_accessor :url_q, :pages_q, :processor
end
| true |
5b1e9e00c2896888a8c4e8cc2cae6e77c486b519 | Ruby | freerobby/convergence | /lib/convergent_object.rb | UTF-8 | 281 | 2.515625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'celluloid'
class ConvergentObject
include Celluloid
attr_accessor :key, :subscribers
def initialize(_key, _data = nil)
key = _key
subscribers = []
@data = _data
end
def data=(_val)
@data = _val
query
end
def query
data
end
end
| true |
b9d06f4dc3bb641f2abcce40ecee203bfe3c8152 | Ruby | bdmac/strong_password | /lib/active_model/validations/password_strength_validator.rb | UTF-8 | 1,539 | 2.515625 | 3 | [
"MIT"
] | permissive | require 'strong_password'
module ActiveModel
module Validations
class PasswordStrengthValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
ps = ::StrongPassword::StrengthChecker.new(**strength_options(options, object))
unless ps.is_strong?(value.to_s)
object.errors.add(attribute, :'password.password_strength', **(options.merge(:value => value.to_s)))
end
end
def strength_options(options, object)
strength_options = options.dup
strength_options[:extra_dictionary_words] = extra_words_for_object(strength_options[:extra_dictionary_words], object)
strength_options.slice(:min_entropy, :use_dictionary, :min_word_length, :extra_dictionary_words)
end
def extra_words_for_object(extra_words, object)
return [] unless extra_words.present?
if object
if extra_words.respond_to?(:call)
extra_words = extra_words.call(object)
elsif extra_words.kind_of? Symbol
extra_words = object.send(extra_words)
end
end
extra_words || []
end
end
module HelperMethods
# class User < ActiveRecord::Base
# validates_password_strength :password
# validates_password_strength :password, extra_dictionary_words: :extra_words
# end
#
def validates_password_strength(*attr_names)
validates_with PasswordStrengthValidator, _merge_attributes(attr_names)
end
end
end
end
| true |
550eac4432ff0f8adea7755cc7d452b8a62f2794 | Ruby | akcedro/ruby-fall-part-time | /birthplace.rb | UTF-8 | 145 | 2.78125 | 3 | [] | no_license | user1= {:firstname=> "Johnny", :lastname=> "Begood", :gender=> "male", :dob=> "08/21/1981", :birthplace=> "Seattle,WA"}
puts user1[:birthplace]
| true |
aaa3acf70ee883c307e93d3825e349f9c05b781b | Ruby | BlairWhite/phase-0 | /week-4/largest-integer/my_solution.rb | UTF-8 | 128 | 3.4375 | 3 | [
"MIT"
] | permissive | def largest_integer(list_of_nums)
largest = list_of_nums[0]
list_of_nums.each {|i| largest = i if i > largest}
largest
end | true |
cac5000cb73bf639f5c27d04f42c635fbc98732e | Ruby | anrosol/consolitaire | /pile.rb | UTF-8 | 365 | 3.1875 | 3 | [] | no_license | require_relative 'card'
class Pile
attr_reader :cards
def initialize
@cards = []
end
def length
@cards.length
end
def clear
@cards.clear
end
def empty?
@cards.length == 0
end
def current_card
@cards.empty? ? nil : @cards.last
end
def add(card)
@cards.push(card)
end
def remove
@cards.pop
end
end
| true |
8c86a539ec6f402676a8586e43343c3b89d8b43f | Ruby | adamki/m1w1 | /sfb.rb | UTF-8 | 366 | 3.625 | 4 | [] | no_license | (1..1001).each do |x|
if x%3==0&&x%5==0&&x%7==0
puts "SuperFizzBuzz"
elsif x%3==0&&x%7==0
puts "SuperFizz"
elsif x%5==0&&x%7==0
puts "SuperBuzz"
elsif x%3==0 &&x%5==0
puts "#{x}"
elsif x%3==0
puts "Fizz"
elsif x%5==0
puts "Buzz"
elsif x%7==0
puts "Super"
else
puts "#{x}"
end
end
| true |
7875ca7a0e394e54e676c6e433365105179baebb | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/proverb/ca7880ee096640dd93b5320ddbf23fc5.rb | UTF-8 | 347 | 3.109375 | 3 | [] | no_license | class Proverb
def initialize *chain, qualifier: nil
@chain = chain
@qualifier = qualifier
end
def to_s
chain.each_cons(2).map do |a, b|
"For want of a #{a} the #{b} was lost.\n"
end.join + "And all for the want of a #{[qualifier, chain.first].compact.join(' ')}."
end
private
attr_reader :chain, :qualifier
end
| true |
b40da55f9f3a75ecd960e09118181b68225edbae | Ruby | frederikhappel/puppetlabs-stdlib | /lib/puppet/parser/functions/validate_puppet_resource.rb | UTF-8 | 755 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | module Puppet::Parser::Functions
newfunction(:validate_puppet_resource, :doc => <<-'ENDHEREDOC') do |args|
Validate that all passed values are puppet resources. Abort catalog
compilation if any value fails this check.
ENDHEREDOC
unless args.length > 0 then
raise Puppet::ParseError, ("validate_puppet_resource(): wrong number of arguments (#{args.length}; must be > 0)")
end
# load required functions
Puppet::Parser::Functions.autoloader.load(:is_puppet_resource) unless Puppet::Parser::Functions.autoloader.loaded?(:is_puppet_resource)
args.each do |arg|
unless function_is_puppet_resource([arg])
raise Puppet::ParseError, ("'#{arg}' is not a valid puppet resource.")
end
end
end
end
| true |
f15031a7147d2d724ccb6988bf09dbdfc0577415 | Ruby | interestinall/anagram-detector-v-000 | /lib/anagram.rb | UTF-8 | 370 | 3.828125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Your code goes here!
class Anagram
attr_accessor :word
def initialize(word)
@word = word
end
def match(array)
sorted_word = @word.split("").sort.join
final_array = []
array.each do |word|
array_word = word.split("").sort.join
if sorted_word == array_word
final_array << word
end
end
final_array
end
end | true |
ae458dc219f1788eccf42cc686f0011f42ce51a6 | Ruby | learn-co-curriculum/chicago-se-120720 | /rails-forms-and-validations/test.rb | UTF-8 | 312 | 2.90625 | 3 | [] | no_license | # ternary operator
# condition ? result if true : result if false
class recipes
belongs_to :category
def category=(category_name)
category = Categroy.find_or_create_by(name: category_name)
recipe.category = category
end
def category_name
self.category ? self.category.name : nil
end
end | true |
ea11c6c850ee65b82eab99716ce13e6443eb942f | Ruby | kavinderd/data_structures | /lib/data_structures/linked_list.rb | UTF-8 | 1,345 | 3.40625 | 3 | [] | no_license | module DataStructures
class Link
attr_reader :data
attr_accessor :next
def initialize(data, link=nil)
@data = data
@next = link
end
end
class LinkedList
def initialize(start=nil)
@start = start
reset_current
end
def <<(item)
@start = Link.new(item, @start)
reset_current
end
def remove(item)
link = search(item)
if link
pred = predecessor(@start, link)
if pred
pred.next = link.next
else
@start = link.next
end
end
end
def search(item)
return @start if @start.data == item
link = @start
while link.next
if link.data == item
return link
else
link = link.next
end
end
end
def predecessor(link, item)
return nil unless next?(link)
if link.next == item
link
else
predecessor(link.next, item)
end
end
def next
return nil unless next?(@current)
@current = @current.next
@current.data
end
def current
@current.data if @current
end
private
def reset_current
@current = @start
end
def next?(link)
link && link.next
end
def step
@current = @current.next
end
end
end
| true |
5b1f3daf4bba723e89260c7cbcc170a929415a07 | Ruby | csbpku/csce606 | /app/controllers/planning_route.rb | UTF-8 | 576 | 2.640625 | 3 | [] | no_license | class PlanningRoute
attr_accessor:hash_value
def init(hash_value=nil)#hash_value should be a hash object
@hash_value=hash_value
end
def summary_update()
#recalculate all the duration and distance of the whole route
end
def reset()
@hash_value.clear
end
def add(comment_not_used,route)
steps_1=@hash_value[:legs]
steps_2=route[:legs]
@hash_value[:legs]=steps_1.merge(steps_2){ |key,oldval,newval| oldval | newval }#suppose this is right
summary_update()
end
end | true |
29336a72331dbf8e19a86f31d0d1930d71c7b6ae | Ruby | luishong07/immersive-module-one-mini-mock-challenge | /author.rb | UTF-8 | 974 | 3.46875 | 3 | [] | no_license | class Author
attr_accessor :name
@@all = []
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
def all_books_authors
BookAuthor.all.select do |bookauthor|
bookauthor.author == self
end
end
def books
self.all_books_authors.map do |book_author|
book_author.book
end
end
def write_book(title, word_count)
book = Book.new(title,word_count)
BookAuthor.new(book,self)
end
def total_words
#should return the total number of words that author has written across all of their authored books.
total = 0
self.books.each do |book|
total += book.word_count
# total = total + book.word_count
end
total
end
def self.most_words
self.all.max_by do |author|
author.total_words
end
end
end | true |
4b5267d90bbce71aa79c84060ccca3062bc621aa | Ruby | Sirdmu/imageblur | /imageblur2.rb | UTF-8 | 1,121 | 3.984375 | 4 | [] | no_license | class Image
def initialize (image)
@image = image
end
def get_coordinates
coordinates = []
@image.each_with_index do |row, y|
row.each_with_index do |value, x|
if value == 1
coordinates<<[y, x]
end
end
end
return coordinates
end
def blur!
coordinates = get_coordinates
@image.each_with_index do |row, y|
row.each_with_index do |value, x|
coordinates.each do |found_y, found_x|
if y == found_y && x == found_x
@image[y -1][x] = 1 unless y == 0 #up
@image[y +1][x] = 1 unless y >= 3 #down
@image[y][x -1] = 1 unless x == 0 #left
@image[y][x +1] = 1 unless x >= 3 #right
end
end
end
end
end
def output_image
@image.each do |data|
puts data.join
end
end
end
image = Image.new([
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]
])
image.output_image
puts
image.blur!
image.output_image | true |
865e26c5f3a836341da4f798bfa1d6f86552e476 | Ruby | jdashton/glowing-succotash | /daniel/AoC/advent15.rb | UTF-8 | 397 | 3.1875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require_relative 'lib/advent09'
require_relative 'lib/advent15'
input =
IO
.read('input/advent15.txt')
.split(?,)
.map(&:to_i)
adv15 = Advent15.new
Advent09.new.run input, adv15, adv15
puts "Oxygen system found at #{ adv15.oxygen_coords } " \
"in #{ adv15.oxygen_num_moves } moves."
puts "Oxygen filled the room in #{ adv15.fill_o2 } minutes."
| true |
8669de999f495390bb31f6f44fd011e76c71a9b4 | Ruby | shabbirsaifee92/rspec-course | /spec/array_2_spec.rb | UTF-8 | 250 | 2.65625 | 3 | [] | no_license | RSpec.describe Array do
subject(:sally) { [1,2] }
it 'can add remove elements' do
expect(sally.length).to eq 2
sally.pop
expect(sally.length).to eq 1
end
it 'has defualt length of 2' do
expect(sally.length).to eq 2
end
end | true |
b8336cdefc767ac40d54fe09e4855e031d76bde6 | Ruby | SinkLineP/RubyOnRails-18.08.2021 | /Ruby on rails/coalla-cosmetology-ddcbe64f3200/app/services/phone_sanitizer.rb | UTF-8 | 273 | 3.328125 | 3 | [] | no_license | class PhoneSanitizer
PHONE_REGEXP = /\A\d{10,11}\z/
def self.sanitize(phone)
sanitized = phone.try(:gsub, /[\-\+\(\)\s\.\Q]/, '')
if sanitized =~ PHONE_REGEXP && sanitized.start_with?('7', '8')
sanitized[1..-1]
else
sanitized
end
end
end | true |
fd796a65d8a65beb9181fbc354693557aab41546 | Ruby | markfranciose/drops_of_knowledge | /practice/ruby/ruby_yield.rb | UTF-8 | 356 | 4.25 | 4 | [
"MIT"
] | permissive | # basics of yield
# Using the ¶meter
def hello
# nothing is here, yo.
end
hello do
puts "hello!"
end
# executing the method on line 5 won't throw an error, but it won't print out "hello!" to the terminal.
# line 5-7 is the same as:
hello {puts "hello!"}
def hello
yield if block_given?
end
hello {puts "hello!"}
| true |
c351c47832ff2203197c961d0ec5a73487a71175 | Ruby | mwean/mac_setup | /lib/mac_setup/shell.rb | UTF-8 | 844 | 2.75 | 3 | [
"MIT"
] | permissive | require "shellwords"
require "io/console"
require "open3"
module MacSetup
class Shell
class << self
def result(*command)
run(*command).output
end
def run(*command)
Result.new(*Open3.capture3(*command))
end
def raw(command)
system(command)
end
def ask(question)
puts question
STDIN.gets.strip
end
def password
puts "Enter Password"
STDIN.noecho(&:gets).strip
end
def success?(command)
run(command).success?
end
def command_present?(command)
success?("command -v #{command} >/dev/null 2>&1")
end
def sanitize_command(command)
if command.respond_to?(:each)
Shellwords.join(command)
else
command
end
end
end
end
end
| true |
84562febcbd3576636adcb294ab30d5beb9a1c81 | Ruby | mindplace/reddit_comments_gem | /spec/reddit_comments_spec.rb | UTF-8 | 2,823 | 2.5625 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
require 'pry'
describe RedditComments do
it 'has a version number' do
expect(RedditComments::VERSION).not_to be nil
end
describe 'link_tested' do
it 'raises error if given a non-Reddit link' do
url = 'http://www.example.com'
reddit_comments = RedditComments::GetComments.new(url)
expect{ reddit_comments.link_tested }.to raise_error(RedditComments::IncorrectLinkFormat)
end
it 'raises error for Reddit link if not correct format' do
url = 'https://www.reddit.com/r/worldnews/comments/were_living_worse_than_in_a_war_venezuelas/'
reddit_comments = RedditComments::GetComments.new(url)
expect{ reddit_comments.link_tested }.to raise_error(RedditComments::IncorrectLinkFormat)
end
it 'passes an acceptabe Reddit link' do
url = 'https://www.reddit.com/r/worldnews/comments/4p4orb/were_living_worse_than_in_a_war_venezuelas/'
reddit_comments = RedditComments::GetComments.new(url)
expect{ reddit_comments.link_tested }.not_to raise_error
end
end
describe 'append_json' do
it 'appends .json to the link if not present' do
url = 'https://www.reddit.com/r/worldnews/comments/4p4orb/were_living_worse_than_in_a_war_venezuelas/'
updated = url + '.json'
reddit_comments = RedditComments::GetComments.new(url)
reddit_comments.append_json
expect(reddit_comments.url).to eq(updated)
end
it 'does not append if present' do
url = 'https://www.reddit.com/r/worldnews/comments/4p4orb/were_living_worse_than_in_a_war_venezuelas/.json'
reddit_comments = RedditComments::GetComments.new(url)
reddit_comments.append_json
expect(reddit_comments.url).to eq(url)
end
end
describe 'parse_post' do
it 'takes a url and returns JSON object of url content' do
url = 'https://www.reddit.com/r/worldnews/comments/4p4orb/were_living_worse_than_in_a_war_venezuelas/.json'
reddit_comments = RedditComments::GetComments.new(url)
reddit_comments.parse_post
expect(reddit_comments.post).to be_an_instance_of(Array)
expect(reddit_comments.post[0]).to be_an_instance_of(Hash)
end
end
describe 'get_comments' do
let(:url) { "https://www.reddit.com/r/worldnews/comments/4p71mu/migrant_protests_calais_france_tried_to_force_way/.json" }
let(:comments) { RedditComments::GetComments.new(url).retrieve }
it 'returns an array of comment hashes' do
expect(comments).to be_an_instance_of(Array)
comments.each do |comment|
expect(comment).to be_an_instance_of(Hash)
end
end
it 'includes expected comment text' do
comment = comments.select{|c| c["body"] == "That moment you realize brexit does nothing to stop this."}
expect(comment).not_to be_empty
end
end
end
| true |
8a89635117fb4c1dc24dbbb1416a2ac876e65ac3 | Ruby | Localvox/vivialconnect-ruby | /spec/resource_spec.rb | UTF-8 | 11,501 | 2.5625 | 3 | [
"MIT"
] | permissive | require_relative "./spec_helper"
require_relative "./stubbed_response"
require 'json'
RSpec.describe Resource do
context ".path_builder" do
it "builds correct paths for base actions" do
path = Resource.path_builder(:create)
expect(path).to eq('/resources.json')
path = Resource.path_builder(:all)
expect(path).to eq('/resources.json')
path = Resource.path_builder(:find, 1)
expect(path).to eq('/resources/1.json')
path = Resource.path_builder(:update, 1)
expect(path).to eq('/resources/1.json')
path = Resource.path_builder(:delete, 1)
expect(path).to eq('/resources/1.json')
path = Resource.path_builder(:count)
expect(path).to eq('/resources/count.json')
end
end
context ".class_to_json_root" do
it "builds no CamelCase root correctly" do
class Tester < Resource ; end
expect(Tester.class_to_json_root).to eq('tester')
end
it "builds one Camel root correctly" do
class TestTest < Resource ; end
expect(TestTest.class_to_json_root).to eq('test_test')
end
it "builds two Camel root correctly" do
class TestTestTest < Resource ; end
expect(TestTestTest.class_to_json_root).to eq('test_test_test')
end
end
context ".build_hash_root_and_add_user_hash" do
it "works normally for non-Number resources" do
class Message < Resource ; end
root = Message.build_hash_root_and_add_user_hash({hello: 'world'})
expect(root.keys[0]).to eq('message')
end
it "makes correct change for Number resources" do
class Number < Resource ; end
root = Number.build_hash_root_and_add_user_hash({hello: 'world'})
expect(root.keys[0]).to eq('phone_number')
end
end
context ".class_to_path" do
it 'builds Account path correctly' do
expect(VivialConnect::Account.class_to_path).to eq('accounts')
end
it 'builds Attachment path correctly' do
expect(VivialConnect::Attachment.class_to_path).to eq('/attachments')
end
it 'builds Log path correctly' do
expect(VivialConnect::Log.class_to_path).to eq('/logs')
end
it 'builds Message path correctly' do
expect(VivialConnect::Message.class_to_path).to eq('/messages')
end
it 'builds Number path correctly' do
expect(VivialConnect::Number.class_to_path).to eq('/numbers')
end
it 'builds User path correctly' do
expect(VivialConnect::User.class_to_path).to eq('/users')
end
end
context ".pluralize" do
it "adds s" do
expect(Resource.pluralize('cat')).to eq('cats')
end
end
context "#add_methods" do
it "adds the methods passed as hash to the object" do
resource = Resource.new
resource.add_methods({dog_one: "pug", dog_two: "great dane" })
expect(resource.dog_one).to eq("pug")
expect(resource.dog_two).to eq("great dane")
expect(resource.some_undefined_method).to be(nil)
end
end
context "#save / #delete" do
it "responds to #save" do
a = VivialConnect::Account.new
expect(a).to respond_to(:save)
end
it "completes object on #save (with no id) and updates object on save (with id)" do
client = VivialConnect::Client.instance
@stubs = Faraday::Adapter::Test::Stubs.new
@conn = Faraday.new do |builder|
builder.adapter :test, @stubs
end
message = VivialConnect::Message.new
message.to_number = "+18005551111"
message.from_number = "+19194332323"
message.body = "Test message"
#before the post there should be no id
expect(message.id).to be(nil)
uri = "/messages.json"
data = "{\"message\":{\"to_number\":\"+18005551111\",\"from_number\":\"+19194332323\",\"body\":\"Test message\"}}"
@stubs.post('https://api.vivialconnect.net/api/v1.0/messages.json') { [200, {'Content-Type' => 'application/json'}, message_post_response] }
resp = @conn.post('https://api.vivialconnect.net/api/v1.0/messages.json')
url = Addressable::URI.parse('https://api.vivialconnect.net/api/v1.0/messages.json')
post_request_resp = client.process_api_response(resp, url, :post)
allow(client).to receive(:make_request).with('POST', uri, data).and_return(post_request_resp)
message.save
expect(message.class).to be(VivialConnect::Message)
expect(message.to_number).to eq("+18005551111")
expect(message.from_number).to eq("+19194332323")
expect(message.body).to eq("Test message")
expect(message.id).to eq(231323)
@stubs.put('https://api.vivialconnect.net/api/v1.0/messages/231323.json') { [200, {'Content-Type' => 'application/json'}, message_put_response] }
resp = @conn.put('https://api.vivialconnect.net/api/v1.0/messages/231323.json')
put_request_resp = client.process_api_response(resp, url, :post)
message.body = ""
uri = "/messages/231323.json"
allow(client).to receive(:make_request).with('PUT', uri, anything).and_return(put_request_resp)
expect(client).to receive(:make_request).with('PUT', "/messages/231323.json", anything)
message.save
end
it "respond_to #delete" do
a = VivialConnect::Account.new
expect(a).to respond_to(:delete)
end
it "should make a delete request with the right args" do
expect(VivialConnect::Client.instance).to receive(:make_request).with("DELETE", "/messages/1.json", "{\"id\":1}")
message = VivialConnect::Message.new
message.to_number = "+18005551111"
message.from_number = "+19194332323"
message.body = "Test message"
message.id = 1
message.delete
end
end
context "it responds to all the base methods the other resource classes are expecting and forumates the correct responses" do
it "responds to .create" do
expect(Resource).to respond_to(:create)
end
it ".create formulates the correct request" do
client = VivialConnect::Client.instance
expect(client).to receive(:make_request).with('POST', "/messages.json", "{\"message\":{\"from_number\":\"+1608421999\",\"to_number\":\"+16128887777\",\"body\":\"test\"}}")
VivialConnect::Message.send(from_number: "+1608421999", to_number: "+16128887777", body: "test")
end
it "responds to .all" do
expect(Resource).to respond_to(:all)
end
it ".all formulates the correct request" do
client = VivialConnect::Client.instance
expect(client).to receive(:make_request).with('POST', "/messages.json", "{\"message\":{\"from_number\":\"+1608421999\",\"to_number\":\"+16128887777\",\"body\":\"test\"}}")
VivialConnect::Message.send(from_number: "+1608421999", to_number: "+16128887777", body: "test")
end
it "responds to .find" do
expect(Resource).to respond_to(:find)
end
it ".find formulates the correct request" do
client = VivialConnect::Client.instance
expect(client).to receive(:make_request).with("GET", "/messages/1.json")
VivialConnect::Message.find(1)
end
it "responds to .count" do
expect(Resource).to respond_to(:count)
end
it ".count formulates the correct request" do
client = VivialConnect::Client.instance
expect(client).to receive(:make_request).with("GET", "/messages/count.json")
VivialConnect::Message.count
end
it "responds to .update" do
expect(Resource).to respond_to(:update)
end
it ".update formulates the correct request" do
client = VivialConnect::Client.instance
expect(client).to receive(:make_request).with("PUT", "accounts/1.json", "{\"account\":{\"name\":\"Bob\",\"id\":1}}")
VivialConnect::Account.update(1, name: "Bob")
end
it "responds to .delete" do
expect(Resource).to respond_to(:delete)
end
it ".delete formulates the correct request" do
client = VivialConnect::Client.instance
expect(client).to receive(:make_request).with("DELETE", "/contacts/1.json", "{\"id\":1}")
VivialConnect::Contact.delete(1)
end
end
context ".update_final_array" do
it "adds new array into final array and flattens into one" do
array = Resource.update_final_array([1, 2, 3], [4, 5, 6])
expect(array.class).to be(Array)
expect(array.count).to eq(6)
expect(array[3]).to eq(1)
expect(array[2]).to eq(6)
expect(array[0]).to eq(4)
array2 = Resource.update_final_array([100], array)
expect(array2.count).to eq(7)
expect(array2[-1]).to eq(100)
end
end
context ".build_template_uri" do
it "returns uri with expect query params" do
uri = Resource.build_template_uri(path: '/accounts.json', start: 100, batch_size: 5)
expect(uri).to eq('/accounts.json?page=100&limit=5')
end
end
context ".find_each" do
it "returns an enum if no block is given" do
allow(VivialConnect::Client.instance).to receive(:make_request).with("GET", anything)
result = VivialConnect::Account.find_each
expect(result.class).to be(Enumerator)
end
it "iterates through individual records in collection if block is given" do
client = VivialConnect::Client.instance
@stubs = Faraday::Adapter::Test::Stubs.new
@conn = Faraday.new do |builder|
builder.adapter :test, @stubs
end
url = Addressable::URI.parse('https://api.vivialconnect.net/api/v1.0/accounts.json')
@stubs.get('https://api.vivialconnect.net/api/v1.0/accounts.json') { [200, {'Content-Type' => 'application/json'}, account_all] }
resp = @conn.get('https://api.vivialconnect.net/api/v1.0/accounts.json')
get_request_resp = client.process_api_response(resp, url, :get)
allow(client).to receive(:make_request).with("GET", "accounts.json?page=1&limit=150").and_return(get_request_resp)
new_array = []
iteration_count = 0
VivialConnect::Account.find_each {|record| new_array << record; iteration_count +=1 }
expect(new_array.count).to eq(5)
expect(iteration_count).to eq(5)
new_array.each {|account| expect(account).to be_a(VivialConnect::Account)}
end
end
context ".find_in_batches" do
it "returns an enum if no block is given" do
allow(VivialConnect::Client.instance).to receive(:make_request).with("GET", anything)
result = VivialConnect::Account.find_in_batches
expect(result.class).to be(Enumerator)
end
it "iterates through batches in collection if block is given" do
client = VivialConnect::Client.instance
@stubs = Faraday::Adapter::Test::Stubs.new
@conn = Faraday.new do |builder|
builder.adapter :test, @stubs
end
url = Addressable::URI.parse('https://api.vivialconnect.net/api/v1.0/accounts.json')
@stubs.get('https://api.vivialconnect.net/api/v1.0/accounts.json') { [200, {'Content-Type' => 'application/json'}, account_all] }
resp = @conn.get('https://api.vivialconnect.net/api/v1.0/accounts.json')
get_request_resp = client.process_api_response(resp, url, :get)
allow(client).to receive(:make_request).with("GET", "accounts.json?page=1&limit=1").and_return(get_request_resp)
new_array = []
iteration_count = 0
VivialConnect::Account.find_in_batches(start: 1, finish: 1, batch_size: 1) {|record| new_array << record; iteration_count +=1 }
expect(new_array.count).to eq(1)
expect(iteration_count).to eq(1)
new_array.each {|account| expect(account).to be_an(Array)}
end
end
end | true |
b08eeab2a6868131e808bc2142cdc81b5630f9cb | Ruby | yurufuwarb/library | /app/controllers/book_controller.rb | UTF-8 | 1,969 | 2.734375 | 3 | [] | no_license | class BookController < ApplicationController
before_action :check_params
def check_params
case action_name
when 'create'
render_error(-1, 1, "typeパラメータを指定してください。") and return unless params.include?(:type)
render_error(-1, 1, "nameパラメータを指定してください。") and return unless params.include?(:name)
render_error(-1, 1, "outlineパラメータを指定してください。") and return unless params.include?(:outline)
when 'destroy'
end
end
# GET /books
def index
p "-----"
p params[:type]
p "-----"
render json: {test: "test"}
end
# POST /books
def create
type = params[:type]
name = params[:name]
outline = params[:outline]
# フォーマットチェック
render_error(-1, 2, "typeは 0 または 1 で指定してください。") and return unless (0..1).include?(type.to_i)
render_error(-1, 3, "nameは30文字以内で指定してください。") and return if is_exceeded(name, 30)
render_error(-1, 4, "outlineは50文字以内で指定してください。") and return if is_exceeded(outline, 50)
# 登録・更新データ
book = Book.where(id: params[:id]).first_or_initialize
book.type = type
book.name = name
book.outline = outline
# true:新規登録、false:既存更新
is_created = book.new_record?
# 登録・更新
book.save!
# 実行結果
render json: {
result: 0,
is_created: is_created,
book: book.attributes
}
end
# DELETE /books/:id
def destroy
p "-----"
p params[:id]
p "-----"
render json: {test: "test"}
end
def is_exceeded(data, max_length)
data.length > max_length
end
def render_error(result, error_code, error_message = nil)
render json: {
result: result,
error: {
error_code: error_code,
error_message: error_message
}
}
end
end
| true |
80c953acbbc155c97ab6a2254a7056b4e54398c5 | Ruby | Austio/learning | /Projects/Mission/evented/lib/flight_simulator.rb | UTF-8 | 3,004 | 2.671875 | 3 | [] | no_license | class FlightSimulator
include Wisper::Publisher
def initialize(mission, rocket)
@mission = mission
@rocket = rocket
@total_time = Unit.new("0 sec")
@total_distance_traveled = Unit.new("0 km")
end
def run!
return status_aborted if !@rocket.launched?
return status_exploded if @rocket&.doomed?
time_increment = Unit.new("120 sec")
loop do
status = @rocket.fly(time_increment)
@total_time = @total_time + time_increment
distance_traveled = status.velocity * time_increment
@total_distance_traveled = @total_distance_traveled + distance_traveled
distance_remaining = @mission.distance - @total_distance_traveled
remaining_time = distance_remaining / status.velocity
status_update(fuel_burn_rate: status.fuel_burn_rate,
velocity: status.velocity,
remaining_time: remaining_time)
if @total_distance_traveled >= @mission.distance
status_completed
break
end
sleep 1
end
end
private
def final_status_update_stats
{ mission_uuid: @mission.uuid,
rocket_uuid: @rocket.uuid,
total_time_in_seconds: @total_time.scalar,
total_distance_in_km: @total_distance_traveled.scalar,
total_fuel_burned_in_liters: @rocket.fuel_used.scalar }
end
def status_completed
broadcast(:flight_simulator_complete_successful, final_status_update_stats)
end
def status_aborted
broadcast(:flight_simulator_complete_aborted, final_status_update_stats)
end
def status_exploded
# Criteria. Select a random spot on explosions
total_distance_traveled = @mission.random_point
total_time = (total_distance_traveled / @rocket.average_speed).round(0)
total_fuel = @rocket.burn_rate * total_time
random_stats = final_status_update_stats
.merge(total_time_in_seconds: total_time.scalar,
total_distance_in_km: total_distance_traveled.scalar,
total_fuel_burned_in_liters: total_fuel.scalar)
broadcast(:flight_simulator_complete_exploded, random_stats)
end
def status_update(fuel_burn_rate:, velocity:, remaining_time:)
time_to_destination = remaining_time.round(0).scalar
progress = [
{ key: "Current fuel burn rate",
value: FormatHelpers.unit_with_commas(fuel_burn_rate.convert_to('liters/min')) },
{ key: "Current speed",
value: FormatHelpers.unit_with_commas(velocity.convert_to("km/h")) },
{ key: "Current distance traveled",
value: FormatHelpers.unit_with_commas(@total_distance_traveled) },
{ key: "Elapsed time",
value: FormatHelpers.unit_with_commas(@total_time) },
{ key: "Time to destination", value: FormatHelpers.clock_display(time_to_destination) },
]
broadcast(:flight_simulator_progressed, { mission_uuid: @mission.uuid,
rocket_uuid: @rocket.uuid,
plan: progress })
end
end
| true |
18fe7e6c975a0f7d2e1d33a18808f7f5809fe0cf | Ruby | JuPlutonic/Flashcards | /app/services/card_comparator.rb | UTF-8 | 1,838 | 3.09375 | 3 | [] | no_license | class CardComparator
# here we use a SuperMemo2 algorithm
# to read more about it, follow the link https://www.supermemo.com/english/ol/sm2.htm
def initialize(params)
@card = params[:card]
@compared_text = params[:compared_text]
end
def self.call(params)
Result.new(new(params).qualify)
end
def qualify
difference = DamerauLevenshtein.distance(@card.original_text.downcase.strip, @compared_text.downcase.strip, 1, 2)
length = @card.original_text.strip.length
q = get_quality(difference, length).to_i
@card.update(review_date_calc(q))
return q
end
def review_date_calc(q)
if q < 3
{
repeate: 1,
review_date: 1.day.from_now,
interval: 1
}
else
efactor = efactor_calc(q, @card.e_factor) if @card.repeate >= 3
efactor = @card.e_factor if @card.repeate < 3
interval = interval_calc(@card.interval, efactor, @card.repeate)
{
e_factor: efactor,
interval: interval,
repeate: @card.repeate+1,
review_date: @card.interval.days.from_now
}
end
end
def interval_calc(interval, e_factor, repeate)
return 1 if repeate == 1
return 6 if repeate == 2
interval*e_factor
end
def efactor_calc(q, efactor)
new_efactor = efactor-0.8+0.28*q-0.02*q*q
new_efactor < 1.3 ? 1.3 : new_efactor
end
def get_quality(diff, length)
percent = ((diff.to_f / length) * 100)
if percent == 0 # until we have no jQuery timer, we think all answer "perfectly correct"
5
elsif percent.between?(1, 10) # incorrect answer with a little error
2
elsif percent.between?(11, 20) # incorrect answer with rather significant error
1
elsif percent < 21 # absolytely incorrect answer
return 0
end
end
end | true |
b94b03e8bf236a2f6ad27ea8da96396e9c2a4be1 | Ruby | sleepless-p03t/Amazer | /maze | UTF-8 | 25,250 | 3.046875 | 3 | [
"MIT"
] | permissive | #!/bin/ruby
require 'io/console'
load('./internals.rb')
load('./portals.rb')
trap("INT", "SIG_IGN")
class Maze # Maze Generator from: https://rosettacode.org/wiki/Maze_generation#Ruby
DIRECTIONS = [ [1, 0], [-1, 0], [0, 1], [0, -1] ]
def initialize(width, height)
@width = width
@height = height
@start_x = rand(width)
@start_y = 0
@end_x = rand(width)
@end_y = height - 1
@vertical_walls = Array.new(width) { Array.new(height, true) }
@horizontal_walls = Array.new(width) { Array.new(height, true) }
@path = Array.new(width) { Array.new(height) }
@horizontal_walls[@end_x][@end_y] = false
generate
end
def print
mz = File.new(".maze", "w")
mz.puts @width.times.inject("+") {|str, x| str << (x == @start_x ? " +" : "---+")}
@height.times do |y|
line = @width.times.inject("|") do |str, x|
str << (@path[x][y] ? " * " : " ") << (@vertical_walls[x][y] ? "|" : " ")
end
mz.puts line
mz.puts @width.times.inject("+") {|str, x| str << (@horizontal_walls[x][y] ? "---+" : " +")}
end
mz.close
end
private
def reset_visiting_state
@visited = Array.new(@width) { Array.new(@height) }
end
def move_valid?(x, y)
(0...@width).cover?(x) && (0...@height).cover?(y) && !@visited[x][y]
end
def generate
reset_visiting_state
generate_visit_cell(@start_x, @start_y)
end
def generate_visit_cell(x, y)
@visited[x][y] = true
coordinates = DIRECTIONS.shuffle.map { |dx, dy| [x + dx, y + dy] }
for new_x, new_y in coordinates
next unless move_valid?(new_x, new_y)
connect_cells(x, y, new_x, new_y)
generate_visit_cell(new_x, new_y)
end
end
def connect_cells(x1, y1, x2, y2)
if x1 == x2
@horizontal_walls[x1][ [y1, y2].min ] = false
else
@vertical_walls[ [x1, x2].min ][y1] = false
end
end
end
class Game
def initialize
width = (`tput cols`.to_i) / 5
height = (`tput lines`.to_i / 2) - 1
maze = Maze.new(width, height)
maze.print
board = File.readlines('.maze').join(",").gsub(",", "").split("\n")
@maze_board = []
board.each do |line|
@maze_board.push line.split(//)
end
File.delete('.maze')
@char = 'x'
@chrcolor = "default"
@show_path = false
@path_color = "default"
@path_char = "\u2219".encode("UTF-8")
@portals = false
@portal_instance = nil
@cr = 1
@cc = 0
i = 1
n = 0
@maze_board[0].each do |c|
if c == " "
@cc = i
@maze_board[0][n] = ':'
@maze_board[0][n + 1] = ':'
@maze_board[0][n + 2] = ':'
break
end
i += 1
n += 1
end
@finished = false
i = 0
@maze_board[@maze_board.length - 1].each do |c|
if c == " "
@maze_board[@maze_board.length - 1][i] = '#'
@maze_board[@maze_board.length - 1][i + 1] = '#'
@maze_board[@maze_board.length - 1][i + 2] = '#'
break
end
i += 1
end
end
def get_maze_board
return @maze_board
end
def get_cr
return @cr
end
def get_cc
return @cc
end
def is_finished?
return @finished
end
def set_char(c)
@char = c
end
def get_char
return @char
end
# set show_path
def set_show_path(bool)
@show_path = bool
end
def set_path_color(color)
@path_color = color
end
def set_char_color(color)
@chrcolor = color
end
def get_char_color
return @chrcolor
end
def set_portals(bool)
@portals = bool
end
def set_portal_instance(portal)
@portal_instance = portal
end
def move_up(y, x)
if test_move_up(y, x) == 1
if @portals
if @portal_instance.test_portal_up(y, x) == 0
npos = @portal_instance.teleport(y - 1, x)
@cr = npos[0]
@cc = npos[1]
clsp(y, x)
output_char
return
end
end
@cr -= 1
clsp(y, x)
output_char
end
end
def move_down(y, x)
if test_move_down(y, x) == 1
if @portals
if @portal_instance.test_portal_down(y, x) == 0
npos = @portal_instance.teleport(y + 1, x)
@cr = npos[0]
@cc = npos[1]
clsp(y, x)
output_char
return
end
end
@cr += 1
clsp(y, x)
output_char
end
end
def move_left(y, x)
if test_move_left(y, x) == 1
if @portals
if @portal_instance.test_portal_left(y, x) == 0
npos = @portal_instance.teleport(y, x - 1)
@cr = npos[0]
@cc = npos[1]
clsp(y, x)
output_char
return
end
end
@cc -= 1
clsp(y, x)
output_char
end
end
def move_right(y, x)
if test_move_right(y, x) == 1
if @portals
if @portal_instance.test_portal_right(y, x) == 0
npos = @portal_instance.teleport(y, x + 1)
@cr = npos[0]
@cc = npos[1]
clsp(y, x)
output_char
return
end
end
@cc += 1
clsp(y, x)
output_char
end
end
private
def clsp(y, x)
system("tput cup #{y} #{x}")
system("tput ech 1")
if @show_path
if @path_color == "default"
print @path_char
elsif @path_color == "lg" || @path_color == "light_green"
print "\e[1;32m#{@path_char}\e[0m"
elsif @path_color == "lr" || @path_color == "light_red"
print "\e[1;31m#{@path_char}\e[0m"
elsif @path_color == "ly" || @path_color == "light_yellow"
print "\e[1;33m#{@path_char}\e[0m"
elsif @path_color == "lb" || @path_color == "light_blue"
print "\e[1;34m#{@path_char}\e[0m"
elsif @path_color == "lp" || @path_color == "light_purple"
print "\e[1;35m#{@path_char}\e[0m"
elsif @path_color == "lc" || @path_color == "light_cyan"
print "\e[1;36m#{@path_char}\e[0m"
elsif @path_color == "lw" || @path_color == "light_white"
print "\e[1;37m#{@path_char}\e[0m"
end
end
end
def output_char
system("tput cup #{@cr} #{@cc}")
if @chrcolor == "default"
print @char
elsif @chrcolor == "lg" || @chrcolor == "light_green"
print "\e[1;32m#{@char}\e[0m"
elsif @chrcolor == "lr" || @chrcolor == "light_red"
print "\e[1;31m#{@char}\e[0m"
elsif @chrcolor == "ly" || @chrcolor == "light_yellow"
print "\e[1;33m#{@char}\e[0m"
elsif @chrcolor == "lb" || @chrcolor == "light_blue"
print "\e[1;34m#{@char}\e[0m"
elsif @chrcolor == "lp" || @chrcolor == "light_purple"
print "\e[1;35m#{@char}\e[0m"
elsif @chrcolor == "lc" || @chrcolor == "light_cyan"
print "\e[1;36m#{@char}\e[0m"
elsif @chrcolor == "lw" || @chrcolor == "light_white"
print "\e[1;37m#{@char}\e[0m"
end
end
def test_move_up(y, x)
dy = y - 1
dx1 = x - 1
dx2 = x + 1
if dy == 0 || @maze_board[dy][x] != " "
return 0
else
if @maze_board[dy][dx1] != " " || @maze_board[dy][dx2] != " "
return 0
end
return 1
end
end
def test_move_down(y, x)
dy = y + 1
dx1 = x - 1
dx2 = x + 1
if @maze_board[dy][x] == '#'
@finished = true
return 0
end
if dy == @maze_board.length - 1 || @maze_board[dy][x] != " "
return 0
else
if @maze_board[dy][dx1] != " " || @maze_board[dy][dx2] != " "
return 0
end
return 1
end
end
def test_move_left(y, x)
dx = x - 2
if dx == 0 || @maze_board[y][dx] != " "
return 0
else
return 1
end
end
def test_move_right(y, x)
dx = x + 2
if dx == @maze_board[0].length - 1 || @maze_board[y][dx] != " "
return 0
else
return 1
end
end
end
class Runner
def initialize(configs)
@game = Game.new
@maze = @game.get_maze_board
@mz_color = "default"
@flag_color = "default"
@mz_solid = false
@portals = false
@portal_instance = nil
@banner = [
["#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#"],
["#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#"],
["#", "#", "Y", "b", "#", "#", "d", "P", "#", "#", "d", "P", "\"", "Y", "b", "#", "#", "8", "8", "#", "#", "#", "8", "8", "#", "#", "#", "#", "Y", "b", "#", "#", "#", "#", "#", "#", "#", "#", "d", "P", "#", "#", "d", "P", "\"", "Y", "b", "#", "#", "8", "8", "b", "#", "8", "8", "#", "#"],
["#", "#", "#", "Y", "b", "d", "P", "#", "#", "d", "P", "#", "#", "#", "Y", "b", "#", "8", "8", "#", "#", "#", "8", "8", "#", "#", "#", "#", "#", "Y", "b", "#", "#", "d", "b", "#", "#", "d", "P", "#", "#", "d", "P", "#", "#", "#", "Y", "b", "#", "8", "8", "Y", "b", "8", "8", "#", "#"],
["#", "#", "#", "#", "8", "P", "#", "#", "#", "Y", "b", "#", "#", "#", "d", "P", "#", "Y", "8", "#", "#", "#", "8", "P", "#", "#", "#", "#", "#", "#", "Y", "b", "d", "P", "Y", "b", "d", "P", "#", "#", "#", "Y", "b", "#", "#", "#", "d", "P", "#", "8", "8", "#", "Y", "8", "8", "#", "#"],
["#", "#", "#", "d", "P", "#", "#", "#", "#", "#", "Y", "b", "o", "d", "P", "#", "#", "`", "Y", "b", "o", "d", "P", "'", "#", "#", "#", "#", "#", "#", "#", "Y", "P", "#", "#", "Y", "P", "#", "#", "#", "#", "#", "Y", "b", "o", "d", "P", "#", "#", "8", "8", "#", "#", "Y", "8", "#", "#"],
["#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#"],
["#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#", "#"]
]
@banner_show = true
if configs
load_configs
end
end
def start
print `printf '\033c'`
system("tput cup 0 0")
system("tput civis")
system("stty -echo")
output_maze
cr = @game.get_cr
cc = @game.get_cc
system("tput cup #{cr} #{cc}")
chr = @game.get_char
chr_color = @game.get_char_color
if chr_color == "default"
print chr
elsif chr_color == "lr" || chr_color == "light_red"
print("\e[1;31m#{chr}\e[0m")
elsif chr_color == "lg" || chr_color == "light_green"
print("\e[1;32m#{chr}\e[0m")
elsif chr_color == "ly" || chr_color == "light_yellow"
print("\e[1;33m#{chr}\e[0m")
elsif chr_color == "lb" || chr_color == "light_blue"
print("\e[1;34m#{chr}\e[0m")
elsif chr_color == "lp" || chr_color == "light_purple"
print("\e[1;35m#{chr}\e[0m")
elsif chr_color == "lc" || chr_color == "light_cyan"
print("\e[1;36m#{chr}\e[0m")
elsif chr_color == "lw" || chr_color == "light_white"
print("\e[1;37m#{chr}\e[0m")
end
keep_playing = 1
while keep_playing == 1
cr = @game.get_cr
cc = @game.get_cc
c = Handler.read_char
case c
when Handler.UP_ARROW
@game.move_up(cr, cc)
when Handler.DOWN_ARROW
@game.move_down(cr, cc)
if @game.is_finished?
keep_playing = 2
end
when Handler.LEFT_ARROW
@game.move_left(cr, cc)
when Handler.RIGHT_ARROW
@game.move_right(cr, cc)
when Handler.DEL
keep_playing = 0
end
end
if keep_playing == 2
system("tput cup 0 0")
system("stty -echo")
system("tput civis")
if @banner_show
show_won
end
Handler.read_char
end
system("tput cnorm")
system("stty echo")
print `printf '\033c'`
end
private
def load_configs
colors = [ "lr", "light_red", "lg", "light_green", "ly", "light_yellow", "lb", "light_blue", "lp", "light_purple", "lc", "light_cyan", "lw", "light_white" ]
if File.file?('.mazecfg')
cfgs = File.readlines('.mazecfg').join(",").gsub(",", "").split("\n")
cfgs.each do |cfg|
cfg.gsub!(" ", "")
if cfg.start_with?("char=")
char = cfg.split('=')[1]
@game.set_char("#{char}")
elsif cfg.start_with?("chr_color=")
color = cfg.split('=')[1]
if colors.include?(color)
@game.set_char_color(color)
else
@game.set_char_color("default")
end
elsif cfg.start_with?("mz_color=")
mzcolor = cfg.split('=')[1]
if colors.include?(mzcolor)
@mz_color = mzcolor
else
@mz_color = "default"
end
elsif cfg.start_with?("mz_solid")
mzsolid = cfg.split('=')[1]
if mzsolid == "true"
@mz_solid = true
else
@mz_solid = false
end
elsif cfg.start_with?("fl_color=")
flcolor = cfg.split('=')[1]
if colors.include?(flcolor)
@flag_color = flcolor
else
@flag_color = "default"
end
elsif cfg.start_with?("path_color=")
pcolor = cfg.split('=')[1]
if colors.include?(pcolor)
@game.set_path_color(pcolor)
else
@game.set_path_color("default")
end
elsif cfg.start_with?("show_path")
showp = cfg.split('=')[1]
if showp == "true"
@game.set_show_path(true)
else
@game.set_show_path(false)
end
elsif cfg.start_with?("portals")
portal = cfg.split('=')[1]
if portal == "true"
load('./portals.rb')
@portal_instance = Portal.new(@maze, rand(3..8), @game.get_cr, @game.get_cc)
@portals = true
@game.set_portals(true)
@game.set_portal_instance(@portal_instance)
else
@portals = false
@game.set_portals(false)
@game.set_portal_instance(nil)
end
elsif cfg.start_with?("banner=")
banner_bool = cfg.split('=')[1]
if banner_bool == "true"
@banner_show = true
else
@banner_show = false
end
end
end
end
end
def output_maze
for i in 0..@maze.length - 1 do
for j in 0..@maze[i].length - 1 do
c = @maze[i][j]
if c == ':' || c == '#'
if @flag_color == "default"
print c
elsif @flag_color == "lg" || @flag_color == "light_green"
print "\e[1;32m#{c}\e[0m"
elsif @flag_color == "lr" || @flag_color == "light_red"
print "\e[1;31m#{c}\e[0m"
elsif @flag_color == "ly" || @flag_color == "light_yellow"
print "\e[1;33m#{c}\e[0m"
elsif @flag_color == "lb" || @flag_color == "light_blue"
print "\e[1;34m#{c}\e[0m"
elsif @flag_color == "lp" || @flag_color == "light_purple"
print "\e[1;35m#{c}\e[0m"
elsif @flag_color == "lc" || @flag_color == "light_cyan"
print "\e[1;36m#{c}\e[0m"
elsif @flag_color == "lw" || @flag_color == "light_white"
print "\e[1;37m#{c}\e[0m"
end
else
if @mz_color == "default"
if @mz_solid
c = set_wall_char(i, j)
if @maze[i][j] == " "
c = " "
end
end
print c
elsif @mz_color == "lg" || @mz_color == "light_green"
if @mz_solid
c = set_wall_char(i, j)
if @maze[i][j] == " "
c = " "
end
end
print "\e[1;32m#{c}\e[0m"
elsif @mz_color == "lr" || @mz_color == "light_red"
if @mz_solid
c = set_wall_char(i, j)
if @maze[i][j] == " "
c = " "
end
end
print "\e[1;31m#{c}\e[0m"
elsif @mz_color == "ly" || @mz_color == "light_yellow"
if @mz_solid
c = set_wall_char(i, j)
if @maze[i][j] == " "
c = " "
end
end
print "\e[1;33m#{c}\e[0m"
elsif @mz_color == "lb" || @mz_color == "light_blue"
if @mz_solid
c = set_wall_char(i, j)
if @maze[i][j] == " "
c = " "
end
end
print "\e[1;34m#{c}\e[0m"
elsif @mz_color == "lp" || @mz_color == "light_purple"
if @mz_solid
c = set_wall_char(i, j)
if @maze[i][j] == " "
c = " "
end
end
print "\e[1;35m#{c}\e[0m"
elsif @mz_color == "lc" || @mz_color == "light_cyan"
if @mz_solid
c = set_wall_char(i, j)
if @maze[i][j] == " "
c = " "
end
end
print "\e[1;36m#{c}\e[0m"
elsif @mz_color == "lw" || @mz_color == "light_white"
if @mz_solid
c = set_wall_char(i, j)
if @maze[i][j] == " "
c = " "
end
end
print "\e[1;37m#{c}\e[0m"
end
end
end
puts
end
if @portals
@portal_instance.show_portals
end
end
def set_wall_char(r, c)
drp = r + 1
drn = r - 1
dcp = c + 1
dcn = c - 1
wall_left = c > 0 ? @maze[r][dcn] == "-" : false
wall_right = c < @maze[r].length - 1 ? @maze[r][dcp] == "-" : false
wall_up = r > 0 ? @maze[drn][c] == "|" : false
wall_down = r < @maze.length - 1 ? @maze[drp][c] == "|" : false
cs = wall_left && wall_right && wall_up && wall_down
tr = !wall_left && wall_right && wall_up && wall_down
tl = wall_left && !wall_right && wall_up && wall_down
tu = wall_left && wall_right && wall_up && !wall_down
td = wall_left && wall_right && !wall_up && wall_down
vl = !wall_left && !wall_right && (wall_up || wall_down)
hl = wall_left && wall_right && !wall_up && !wall_down
cbr = wall_left && !wall_right && wall_up && !wall_down
cbl = !wall_left && wall_right && wall_up && !wall_down
ctr = wall_left && !wall_right && !wall_up && wall_down
ctl = !wall_left && wall_right && !wall_up && wall_down
tlc = r == 0 && c == 0
trc = r == 0 && c == @maze[r].length - 1
blc = r == @maze.length - 1 && c == 0
brc = r == @maze.length - 1 && c == @maze[r].length - 1
if tlc
return UTF8.TOP_LEFT_CORNER
elsif blc
return UTF8.BOTTOM_LEFT_CORNER
elsif trc
return UTF8.TOP_RIGHT_CORNER
elsif brc
return UTF8.BOTTOM_RIGHT_CORNER
elsif r == 0 && wall_down
return UTF8.T_DOWN
elsif r == 0 && !wall_down
return UTF8.HORI_WALL
elsif c == 0 && wall_right
return UTF8.T_RIGHT
elsif c == 0 && !wall_right
return UTF8.VERT_WALL
elsif r == @maze.length - 1 && wall_up
return UTF8.T_UP
elsif r == @maze.length - 1 && !wall_up
return UTF8.HORI_WALL
elsif c == @maze[r].length - 1 && wall_left
return UTF8.T_LEFT
elsif c == @maze[r].length - 1 && !wall_left
return UTF8.VERT_WALL
elsif cs
return UTF8.CROSS
elsif tr
return UTF8.T_RIGHT
elsif tl
return UTF8.T_LEFT
elsif tu
return UTF8.T_UP
elsif td
return UTF8.T_DOWN
elsif vl
return UTF8.VERT_WALL
elsif hl
return UTF8.HORI_WALL
elsif cbr
return UTF8.BOTTOM_RIGHT_CORNER
elsif cbl
return UTF8.BOTTOM_LEFT_CORNER
elsif ctr
return UTF8.TOP_RIGHT_CORNER
elsif ctl
return UTF8.TOP_LEFT_CORNER
elsif @maze[r][c] == "+" && (wall_right || wall_left)
return UTF8.HORI_WALL
elsif @maze[r][c] == "+" && (wall_up || wall_down)
return UTF8.VERT_WALL
elsif @maze[r][c] == "|"
return UTF8.VERT_WALL
elsif @maze[r][c] == "-"
return UTF8.HORI_WALL
else
return @maze[r][c]
end
end
def full?
has_empty = false
for r in 0..@banner.length - 1 do
for c in 0..@banner[r].length - 1 do
if @banner[r][c] != '~'
has_empty = true
end
end
end
if has_empty
return false
else
return true
end
end
def valid_pos?(r, c)
if @banner[r][c] == '~'
return false
else
return true
end
end
def show_won
lines = `tput lines`.to_i / 2
cols = `tput cols`.to_i / 2
start_x = cols - (@banner[0].length / 2) - 2
start_y = lines - (@banner.length / 2)
height = @banner.length - 1
width = @banner[0].length - 1
while !full? do
r = rand(0..height)
c = rand(0..width)
if valid_pos?(r, c)
system("tput cup #{r + start_y} #{c + start_x}")
if @banner[r][c] == "#"
print "\e[1;30m#{@banner[r][c]}\e[0m"
@banner[r][c] = '~'
elsif @banner[r][c] != "~"
print "\e[1;31m#{@banner[r][c]}\e[0m"
@banner[r][c] = '~'
end
end
end
end
end
class Main
def initialize
is_done = 0
while is_done == 0
option = show_menu
if option == "help"
show_help
elsif option == "start"
configs = ARGV[0]
instance = nil
if configs == "--no-config"
instance = Runner.new(false)
else
instance = Runner.new(true)
end
instance.start
elsif option == "exit"
is_done = 1
system("stty echo")
system("tput cnorm")
print `printf '\033c'`
end
end
end
private
def show_help
system("stty -echo")
system("tput civis")
print `printf '\033c'`
system( <<-EOF
pager <<EOH
A-MAZE-R Help
In Game:
Movement: Arrow keys
Quit: q
Config File:
File name: .mazecf
Variables:
char set character
chr_color set character color
mz_color set maze color
mz_solid set true or false
fl_color set start/end flag color
show_path set true or false
path_color set path color
Available Colors:
lr | light_red
lg | light_green
ly | light_yellow
lb | light_blue
lp | light_purple
lc | light_cyan
lw | light_white
default
Example config file:
char=@
chr_color=lg
mz_color=lw
show_path=false
path_color=default
EOH
EOF
)
end
def show_menu
icon = [
["+", "-", "-", "-", "+", "-", "-", "-", "+", "-", "-", "-", "+", " ", " ", " ", "+", "-", "-", "-", "+"],
["|", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "|", " ", " ", " ", "|"],
["+", " ", " ", " ", "+", "-", "-", "-", "+", "-", "-", "-", "+", "-", "-", "-", "+", " ", " ", " ", "+"],
["|", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "|", " ", " ", " ", " ", " ", " ", " ", "|"],
["+", "-", "-", "-", "+", "-", "-", "-", "+", " ", " ", " ", "+", " ", " ", " ", "+", " ", " ", " ", "+"],
["|", " ", " ", " ", "|", " ", " ", " ", " ", " ", " ", " ", "|", " ", " ", " ", "|", " ", " ", " ", "|"],
["+", " ", " ", " ", "+", " ", " ", " ", "+", "-", "-", "-", "+", "-", "-", "-", "+", " ", " ", " ", "+"],
["|", " ", " ", " ", "|", " ", " ", " ", "|", " ", " ", " ", " ", " ", " ", " ", "|", " ", " ", " ", "|"],
["+", " ", " ", " ", "+", " ", " ", " ", "+", " ", " ", " ", "+", " ", " ", " ", "+", " ", " ", " ", "+"],
["|", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "|", " ", " ", " ", " ", " ", " ", " ", "|"],
["+", "-", "-", "-", "+", " ", " ", " ", "+", "-", "-", "-", "+", "-", "-", "-", "+", "-", "-", "-", "+"]
]
print `printf '\033c'`
tl_cols = `tput cols`.to_i / 2
icon_cols = icon[0].length
icon_mid = icon_cols / 2
icon_x = tl_cols - icon_mid
icon_dx = icon_x
icon_y = 0
lines = (`tput lines`.to_i / 2) - 2
if icon.length + 6 <= `tput lines`.to_i
for r in 0..icon.length - 1 do
for c in 0..icon[r].length - 1 do
system("tput cup #{icon_y} #{icon_dx}")
print("\e[1;37m#{icon[r][c]}\e[0m")
icon_dx += 1
end
icon_dx = icon_x
icon_y += 1
puts
end
lines = icon_y + 1
end
sel = "\u25B6".encode("UTF-8")
title = "A-MAZE-R"
cols = `tput cols`.to_i / 2
start = cols - (title.length / 2)
i_start_x = start + 2
i_start_y = lines + 2
system("stty -echo")
system("tput civis")
system("tput cup #{lines} #{start}")
print("\e[1;31m#{title}\e[0m")
system("tput cup #{i_start_y} #{i_start_x}")
system("tput bold")
print("Start")
system("tput sgr0")
system("tput cup #{i_start_y+1} #{i_start_x}")
system("tput bold")
print("Help")
system("tput sgr0")
system("tput cup #{i_start_y+2} #{i_start_x}")
system("tput bold")
print("Exit")
system("tput sgr0")
c_i_x = i_start_x - 2
c_i_y = i_start_y
cpos = c_i_y
pos_track = 1
system("tput cup #{c_i_y} #{c_i_x}")
print(sel)
md = true
while md do
ch = Handler.read_char
case ch
when Handler.DOWN_ARROW
system("tput cup #{cpos} #{c_i_x}")
system("tput ech 1")
cpos += 1
pos_track += 1
if pos_track > 3
cpos = c_i_y
pos_track = 1
end
system("tput cup #{cpos} #{c_i_x}")
print(sel)
when Handler.UP_ARROW
system("tput cup #{cpos} #{c_i_x}")
system("tput ech 1")
cpos -= 1
pos_track -= 1
if pos_track < 1
cpos = c_i_y + 2
pos_track = 3
end
system("tput cup #{cpos} #{c_i_x}")
print(sel)
when Handler.RIGHT_ARROW
md = false
end
end
if pos_track == 1
return "start"
elsif pos_track == 2
return "help"
elsif pos_track == 3
return "exit"
end
end
end
def add_cfg(cfg)
var = cfg.split('=')[0]
if File.readlines(".mazecfg").grep(var).size == 0
File.open(".mazecfg", "a") { |f| f.puts cfg }
end
end
if !ARGV.empty?
system("cp .mazecfg .mazecfg.org")
system("sed -i 's/ = /=/g' .mazecfg")
system("sed -i 's/ =/=/g' .mazecfg")
system("sed -i 's/= /=/g' .mazecfg")
text = File.read(".mazecfg")
ARGV.each do |a|
nc = ""
if a == "--no-portals" || a == "-P"
add_cfg("portals=false")
nc = text.gsub(/portals=true/, "portals=false")
elsif a == "--portals" || a == "-p"
add_cfg("portals=true")
nc = text.gsub(/portals=false/, "portals=true")
elsif a == "--no-solid" || a == "-S"
add_cfg("mz_solid=false")
nc = text.gsub(/mz_solid=true/, "mz_solid=false")
elsif a == "solid" || a == "-s"
add_cfg("mz_solid=true")
nc = text.gsub(/mz_solid=false/, "mz_solid=true")
elsif a == "--no-path" || a == "-T"
add_cfg("show_path=false")
nc = text.gsub(/show_path=true/, "show_path=false")
elsif a == "--path" || a == "-t"
add_cfg("show_path=true")
nc = text.gsub(/show_path=false/, "show_path=true")
else
puts "Unknown flag #{a}. Aborting."
exit
end
if nc != ""
File.open(".mazecfg", "w") { |f| f.puts nc }
end
end
end
at_exit {
if File.file?(".mazecfg.org")
system("mv .mazecfg.org .mazecfg")
end
}
Main.new
| true |
e63f07367aac278372bd2bb3f4f5d10d47fff79b | Ruby | lilwillifo/week1 | /flashcards/test/round_test.rb | UTF-8 | 1,867 | 3.46875 | 3 | [] | no_license | require 'minitest'
require 'minitest/autorun'
require 'minitest/pride'
require './lib/card.rb'
require './lib/guess.rb'
require './lib/deck.rb'
require './lib/round.rb'
class RoundTest < Minitest::Test
def setup
@card_1 = Card.new("What is the capital of Virginia", "Richmond")
@card_2 = Card.new("What is Margaret's middle name?", "Eleanor")
@card_3 = Card.new("Who was 7th president of USA?", "Andrew Jackson")
@card_array = [@card_1, @card_2, @card_3]
@deck1 = Deck.new(@card_array)
@round = Round.new(@deck1)
end
def test_round_exists_and_deck_method
assert_instance_of Round, @round
end
def test_deck_method
assert_equal @round.deck, @deck1
end
def test_guesses_before_user_input
assert_equal @round.guesses, []
end
def test_current_card_at_game_beginning
assert_equal @round.current_card, @card_1
end
def test_record_guess_returns_instance_of_guess_class
assert_instance_of Guess, @round.record_guess("Richmond")
end
def test_record_guess_shovels_into_guesses_array
@round.record_guess("Richmond")
assert_equal @round.guesses[0].response, "Richmond"
end
def test_record_guess_has_same_card_argument
assert_equal @round.record_guess("Richmond").card, @card_1
end
def test_number_correct_accurate_tally
tally = @round.guesses.count do |guess|
guess.correct?
end
assert_equal @round.number_correct, tally
end
def test_current_card_progresses_to_next_card
assert_equal @round.current_card, @deck1.cards[@round.guesses.length]
#The length of the array of guesses (total number of guesses)
#will match the index of cards array
end
def test_percent_correct
tally = @round.guesses.count do |guess|
guess.correct?
end
assert_equal @round.percent_correct, tally / @round.guesses.count * 100 unless tally == 0
end
end
| true |
cec57208b35620ae03f3d91fddc26eb5502c8045 | Ruby | didy400/exos-ruby | /exo_20.rb | UTF-8 | 247 | 3.125 | 3 | [] | no_license | print "Hey! tu veux voir ma grosse pyramide? Dis moi la hauteur que tu veux entre 1 et 25!"
h = Integer(gets.chomp)
pyramid = "#"
if h <25
h.times do
puts pyramid
pyramid = pyramid + "#"
end
else
puts "Vous me surestimez très chère!"
end | true |
34f8e6e8e6bcc2477b675c57e0aa5c9ac3bac474 | Ruby | postazure/Ruby-Practice | /CH8/joinMethod.rb | UTF-8 | 276 | 3.359375 | 3 | [] | no_license | foods = ['artichoke','brioche','caramel']
puts foods
puts #just an empty line
puts foods.to_s
puts
puts foods.join(', ')
puts
puts foods.join(' :) ') + ' 8) '
#the following array does not contain anything
200.times do #this does not repeat 200 times
puts [[1,0],0]
end
| true |
3cdd6de9f58001e5beb597461cc0db602aa8bd95 | Ruby | CorySpitzer/leap_years | /leap_years_spec.rb | UTF-8 | 1,333 | 3.765625 | 4 | [] | no_license | require 'rspec'
require './leap_years'
# We add a Leap Day on February 29, almost every four years. The leap day is an
# extra, or intercalary, day and we add it to the shortest month of the year,
# February.
#
# In the Gregorian calendar three criteria must be taken into account to
# identify leap years:
#
# The year can be evenly divided by 4;
# If the year can be evenly divided by 100, it is NOT a leap year, unless;
# The year is also evenly divisible by 400. Then it is a leap year.
#
# This means that in the Gregorian calendar, the years 2000 and 2400 are leap
# years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years.
describe '#leap_year?' do
it 'identifies a multiple of 4 as a leap year' do
expect(leap_year?(2016)).to eq true
end
it 'identifies an odd year as not a leap year' do
expect(leap_year?(2015)).to eq false
end
it 'identifies a multiple of 100 as not a leap year' do
expect(leap_year?(2100)).to eq false
end
it 'identifies a multiple of 400 as a leap year' do
expect(leap_year?(2400)).to eq true
end
end
describe '#leap_years' do
it 'identifies 2016 as a leap year' do
expect(leap_years(2015, 2017)).to eq [2016]
end
it 'identifies many leap years correctly' do
expect(leap_years(2000, 2016)).to eq [2000, 2004, 2008, 2012, 2016]
end
end
| true |
783697049dc4e2df3f3269b3f0ae5a89a04056b9 | Ruby | DiegoSalazar/kwipper_challenge | /app/models/user.rb | UTF-8 | 665 | 2.515625 | 3 | [
"MIT"
] | permissive | module Kwipper
class User < Model
column "username", :to_s
column "email", :to_s
column "hashed_password", :to_s
column "created_at", :to_s
def self.authenticate(username, password)
user = where(username: username).first
user && user.hashed_password == password && user
end
def favorite?(post)
result = sql("SELECT COUNT(id) FROM post_favorites WHERE user_id = #{id} AND post_id = #{post.id} LIMIT 1").first
result.respond_to?(:[]) && result["count"].to_i > 0
end
def posts
Post.recent "SELECT * FROM posts WHERE user_id = #{id}"
end
# TODO
def admin?
false
end
end
end | true |
889ab4e1f90aab4b391971148f4e151a710ade34 | Ruby | maiyama18/AtCoder | /abc/070/c.rb | UTF-8 | 222 | 3.390625 | 3 | [] | no_license | def gcd(a, b)
return a if b == 0
gcd(b, a % b)
end
def lcm(a, b)
a * b / gcd(a, b)
end
n = gets.to_i
t = n.times.map { gets.to_i }
puts n == 1 ? t[0] : t.each_cons(2).reduce(1) {|r, (t1, t2)| lcm(r, lcm(t1, t2))}
| true |
1830e8c38e4b2e9807202579c73c4ab65c26d760 | Ruby | kirualex/Flamingo | /vendor/bundle/ruby/2.6.0/gems/declarative-option-0.1.0/lib/declarative/options.rb | UTF-8 | 416 | 2.734375 | 3 | [
"MIT"
] | permissive | require "declarative/option"
module Declarative
def self.Options(options, config={})
Options.new.tap do |hsh|
options.each { |k,v| hsh[k] = Option(v, config) }
end
end
class Options < Hash
# Evaluates every element and returns a hash. Accepts context and arbitrary arguments.
def call(context, *args)
Hash[ collect { |k,v| [k,v.(context, *args) ] } ]
end
end
end
| true |
d9fb396310f7dae792485e35b171ad42503f4a09 | Ruby | TimBek2/phase-0 | /week-4/smallest-integer/my_solution.rb | UTF-8 | 541 | 3.921875 | 4 | [
"MIT"
] | permissive | # Smallest Integer
# I worked on this challenge by myself
# smallest_integer is a method that takes an array of integers as its input
# and returns the smallest integer in the array
#
# +list_of_nums+ is an array of integers
# smallest_integer(list_of_nums) should return the smallest integer in
# +list_of_nums+
#
# If +list_of_nums+ is empty the method should return nil
# Your Solution Below
def smallest_integer(list_of_nums)
list_of_nums.sort!
smallest = list_of_nums.shift
p smallest
end
#test = []
#smallest_integer(test) | true |
ec3be35b539027007cc49fd419b35bead61d07a8 | Ruby | isieo/lvl-up-kl-iot-demo | /app.rb | UTF-8 | 3,491 | 2.59375 | 3 | [] | no_license | #!/usr/bin/env ruby
# encoding: utf-8
require 'rubygems'
require 'sinatra'
require 'serialport'
require 'celluloid/autostart'
set :server, %w[thin mongrel webrick]
set :bind, '0.0.0.0'
set :port, 8000
class LightStatus
@@red = 0
@@green = 0
@@blue = 0
@@device = nil
@@shutdown = false
@@ambient = 0
DEVICES = ['/dev/rfcomm0','/dev/rfcomm1']
def self.shutdown?
@@shutdown
end
def self.shutdown!
@@shutdown = true
end
def self.device=(d)
@@device = d
end
def self.red_percent
(@@red/255 * 100).to_i
end
def self.green_percent
(@@green/255 * 100).to_i
end
def self.blue_percent
(@@blue/255 * 100).to_i
end
def self.color_ratio
{
r: 1.to_f,
g: @@green.to_f / @@red,
b: @@blue.to_f / @@red
}
end
def self.brightness(percent)
ratios = LightStatus.color_ratio.sort{|a,b| b[1] <=> a[1]}
return false if ratios.to_a[0][1] * percent > 255 ||
ratios.to_a[1][1] * percent > 255 ||
ratios.to_a[2][1] * percent > 255
ratio = LightStatus.color_ratio
LightStatus.set_color((ratio[:r] * percent).abs,(ratio[:g] * percent).abs,(ratio[:b] * percent).abs)
puts "#{ratio[:r] * percent},#{ratio[:g] * percent},#{ratio[:b] * percent}"
end
def self.set_color(red,green,blue)
@@red = red = red.to_i
@@green = green = green.to_i
@@blue = blue = blue.to_i
red += 1
green += 1
blue += 1
red = 255 if red > 255
green = 255 if green > 255
blue = 255 if blue > 255
red = 1 if red < 1
green = 1 if green < 1
blue = 1 if blue < 1
puts "#{red} #{green} #{blue} L#{red.chr}#{green.chr}#{blue.chr}"
DEVICES.each do |d|
if File.exist?(d)
device_alt = SerialPort.new d, 9600, 8, 1, SerialPort::NONE
device_alt.write("L#{red.chr}#{green.chr}#{blue.chr}")
device_alt.close
end
end
end
def self.cycle
DEVICES.each do |d|
if File.exist?(d)
device = SerialPort.new d, 9600, 8, 1, SerialPort::NONE
device.write "D\r\n"
device.close
end
end
end
def self.fade
DEVICES.each do |d|
if File.exist?(d)
device = SerialPort.new d, 9600, 8, 1, SerialPort::NONE
device.write "F\r\n"
device.close
end
end
end
def self.html_color
return "#{@@red.to_s(16).rjust(2,'0')}#{@@green.to_s(16).rjust(2,'0')}#{@@blue.to_s(16).rjust(2,'0')}"
end
end
class RemoteControl
include Celluloid
attr_reader :serial_device
def initialize(serial_device)
@serial_device = serial_device
end
def start
loop do
if File.exist?(@serial_device)
device = SerialPort.new @serial_device, 9600, 8, 1, SerialPort::NONE
process_command(device.gets.chomp)
device.close
end
end
end
def process_command command
case command
when "CYCLEON"
LightStatus.cycle
when "CYCLEOFF"
LightStatus.set_color(255,0,0)
when "FADE"
LightStatus.fade
when "OFF"
LightStatus.set_color(0,0,0)
end
end
end
get '/lights' do
hex = params[:hex]
red = green = blue = 0
red = hex[0..1].to_i(16)
green = hex[2..3].to_i(16)
blue = hex[4..5].to_i(16)
LightStatus.set_color(red,green,blue)
end
get '/fade_lamp' do
LightStatus.fade
"ok!"
end
get '/cycle' do
LightStatus.cycle
"ok!"
end
get '/' do
@color = '#000000'
erb :index
end
| true |
23bfa183353ff7147c6171d8f6089b45ff5de9fa | Ruby | nilbot/ruby-skippy-sample | /point.rb | UTF-8 | 113 | 3.265625 | 3 | [] | no_license | class Point
attr_reader :x, :y
def initialize(x,y)
@x = x
@y = y
end
def to_s
"[#{@x},#{@y}]"
end
end | true |
465968ba4aa9e6f4a83363d3d79c24a0df79c489 | Ruby | Maquech/MX-ID | /lib/MX/ID/auxiliar.rb | UTF-8 | 1,744 | 2.875 | 3 | [
"MIT"
] | permissive | # encoding: utf-8
module MX::ID::Auxiliar
module ClassMethods
def en_blanco?(cadena)
cadena.nil? or cadena.empty?
end
def fecha_con_formato(fecha)
fecha.strftime("%y%m%d")
end
def obtener_primer_nombre_valido(nombres)
arr_nombres = nombres.split(" ")
if arr_nombres.size <= 1
nombres
else
arr_nombres[0] =~ /(JOSE)|(J\.)|J|(MARIA)|(MA)|(MA\.)/ ? arr_nombres[1] : arr_nombres[0]
end
end
# TODO: Anexar/crear biblioteca para convertir número a palabras y poder hacer esta una clase independiente
def numero_a_palabras(numero_entero)
quitar_acentos(::I18n.with_locale(:es) { numero_entero.to_words }).upcase
end
def quitar_acentos(cadena)
I18n.transliterate(cadena)
end
def fecha_coincide?(dia_str, mes_str, año_str, fecha_coincidente = nil, tipo_fecha = "nacimiento", msg = [])
errores = false
begin
if Date.valid_date?(año_str.to_i, mes_str.to_i, dia_str.to_i)
unless fecha_coincidente.nil?
fn = Date.parse("#{año_str}-#{mes_str}-#{dia_str}")
unless fn.year == fecha_coincidente.year and fn.month == fecha_coincidente.month and fn.day == fecha_coincidente.day
errores = true
msg << "La fecha de #{tipo_fecha} no coincide con la fecha de #{tipo_fecha} proporcionada."
end
end
else
errores = true
msg << "La fecha de #{tipo_fecha} es incorrecta."
end
rescue
errores = true
msg << "La fecha de #{tipo_fecha} está mal formada."
end
return !errores
end
end
def self.included(base)
base.extend ClassMethods
end
end | true |
a43bd32dc264ae4b759b520f7db533b68a38a375 | Ruby | MatthewRiggott/surf-report | /test3.rb | UTF-8 | 535 | 3.9375 | 4 | [] | no_license | def repeat?(int)
int_array = int.to_s.chars
last_index = int_array.size - 1
int_array.each_with_index do |number, index|
if index < last_index
return true if number == int_array[index+1]
end
end
return false
end
def count_Numbers(arr)
arr.each do |sub_array|
min = sub_array[0]
max = sub_array[1]
count = 0
(min..max).each do |value|
if repeat?(value)
count += 1
end
end
puts count
end
end
| true |
a75c29c244dcca4cbdadbdb64f105ad14f9cab14 | Ruby | saumyamehta17/algorithm_and_system_design | /tree/print_bottom_view.rb | UTF-8 | 1,848 | 3.71875 | 4 | [] | no_license | require 'pry'
require 'set'
class Node
attr_accessor :left, :right, :value
def initialize(val)
@value = val
end
end
class QD
attr_accessor :hd, :node
def initialize(hd, node)
@hd = hd
@node = node
end
end
class BinaryTree
attr_accessor :root
@hsh = {}
@@sorted_set = SortedSet.new
def initialize(val)
@root = Node.new(val)
end
def self.sample
root = BinaryTree.new(20).root
root.left = Node.new(8)
root.left.left = Node.new(5)
root.left.right = Node.new(3)
root.left.right.left = Node.new(10)
root.left.right.right = Node.new(14)
root.right = Node.new(22)
root.right.right = Node.new(25)
root
end
def self.bottom_view(node, hd=0)
q = Queue.new
q.enq(QD.new(hd, node))
while(!q.empty?)
qd_node = q.deq
@@sorted_set.add(qd_node.hd)
@hsh[qd_node.hd] = qd_node.node.value
hd = qd_node.hd
node = qd_node.node
q.enq(QD.new(hd-1, node.left)) unless node.left.nil?
q.enq(QD.new(hd+1, node.right)) unless node.right.nil?
end
end
def self.print_in_vertical_order(node, hd = 0)
q = Queue.new
q.enq(QD.new(hd, node))
while(!q.empty?)
qd_node = q.deq
@hsh[qd_node.hd] = @hsh[qd_node.hd].nil? ? [qd_node.node.value] : @hsh[qd_node.hd] + [qd_node.node.value]
hd = qd_node.hd
node = qd_node.node
q.enq(QD.new(hd-1, node.left)) unless node.left.nil?
q.enq(QD.new(hd+1, node.right)) unless node.right.nil?
end
end
def self.print_it
@@sorted_set.each do |ss|
puts @hsh[ss]
end
puts 'dfdf----------------'
@hsh.each do |k,v|
print v
puts "\n"
end
end
end
root = BinaryTree.sample
# BinaryTree.bottom_view(root)
# BinaryTree.print_it
BinaryTree.print_in_vertical_order(root)
BinaryTree.print_it
| true |
84c2b082d1c0c18fd9825245ff1afc9fe46c5dac | Ruby | k-p-jones/simple_playing_cards | /lib/simple_playing_cards/card.rb | UTF-8 | 1,374 | 3.4375 | 3 | [
"MIT"
] | permissive | module SimplePlayingCards
class Card
include Comparable
RANKS = %w[Ace 2 3 4 5 6 7 8 9 10 Jack King Queen]
SUITS = %w[Spades Hearts Diamonds Clubs]
attr_reader :rank, :suit
attr_accessor :value, :options
def initialize(rank, suit, options = {})
validate_inputs(rank, suit)
@options = options
@rank = rank
@suit = suit
@value = assign_value
end
def name
"#{rank} of #{suit}"
end
def <=> (card)
if self.value < card.value
-1
elsif self.value > card.value
1
else
0
end
end
private
def assign_value
if rank.to_i > 0
rank.to_i
else
case rank
when 'Jack'
11
when 'Queen'
12
when 'King'
13
when 'Ace'
options['aces_high'] ? 14 : 1
end
end
end
def validate_inputs(rank, suit)
errors = []
errors << "Invalid argument type. Rank and Suit most both be strings!" unless rank.is_a?(String) && suit.is_a?(String)
errors << "#{rank} is not a valid rank for a playing card!" unless RANKS.include?(rank)
errors << "#{suit} is not a valid suit for a playing card!" unless SUITS.include?(suit)
raise ArgumentError.new(errors.join(" ")) unless errors.empty?
end
end
end
| true |
83c2679b6aaddaf287406c15c9c58ed5bb593e6b | Ruby | maeda5206/mrubyc | /sample_ruby/basic_sample06.rb | UTF-8 | 21 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive |
n = 5
puts "n=#{n}"
| true |
7c494da82fe487669f8b96812955be289788d9ef | Ruby | jimbobhickville/ruby-stormondemand | /lib/Storm/Network/private.rb | UTF-8 | 3,773 | 2.796875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | # Copyright 2013 Liquid Web, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "Storm/Base/model"
require "Storm/Base/sodserver"
require "Storm/server"
require "Storm/Network/zone"
module Storm
module Network
# Helper class for zone in private network
class PrivateZone < Storm::Base::Model
attr_accessor :attached
attr_accessor :id
attr_accessor :name
attr_accessor :region
attr_accessor :unattached
def from_hash(h)
if h[:attached]
@attached = h[:attached].map do |s|
server = Storm::Server.new
server.from_hash s
server
end
end
@id = h[:id]
@name = h[:name]
if h[:region]
@region = Storm::Network::ZoneRegion.new
@region.from_hash h[:region]
end
if h[:unattached]
@unattached = h[:unattached].map do |s|
server = Storm::Server.new
server.from_hash s
server
end
end
end
end
# This class defines APIs methods for attaching and detaching
# a server to a private network, and for querying information about an
# existing private network.
class Private
# Attach a given server to your private network
#
# @param server [Server] the specified server
# @return [String] a result message
def self.attach(server)
data = Storm::Base::SODServer.remote_call '/Network/Private/attach',
:uniq_id => server.uniq_id
data[:attached]
end
# Detach a given server from your private network
#
# @param server [Server] the specified server
# @return [String] a result message
def self.detach(server)
data = Storm::Base::SODServer.remote_call '/Network/Private/detach',
:uniq_id => server.uniq_id
data[:detached]
end
# Get all servers attached to your private network, which zones they are
# in and what IPs they are assigned
#
# @return [Array] an array of PrivateZone objects
def self.get
data = Storm::Base::SODServer.remote_call '/Network/Private/get'
data[:zones].map do |z|
pz = PrivateZone.new
pz.from_hash z
pz
end
end
# Get the current private IP for a particular server, if it has one
#
# @param server [Server] the specified server
# @return [String] the IP address
def self.get_ip(server)
data = Storm::Base::SODServer.remote_call '/Network/Private/getIP',
:uniq_id => server.uniq_id
data[:ip]
end
# Determine whether a given server is currently attached to your private
# network.
#
# @param server [Server] the specific server
# @return [Bool] whether the server is attached
def self.is_attached(server)
data = Storm::Base::SODServer.remote_call '/Network/Private/isAttached',
:uniq_id => server.uniq_id
data[:is_attached].to_i == 0 ? false : true
end
end
end
end
| true |
c033741e5ba406fd8668780f86b93e3e83831955 | Ruby | al002/exercism-ruby | /hamming/hamming.rb | UTF-8 | 257 | 3.609375 | 4 | [] | no_license | class Hamming
def self.compute(a, b)
raise ArgumentError if a.length != b.length
a_arry = a.split("")
b_arry = b.split("")
count = 0
a_arry.each_with_index do |chr, i|
count += 1 if chr != b_arry[i]
end
count
end
end
| true |
d61a5feab5c657eb3e4d8e609167b543996f6fcd | Ruby | yoshikazu-ishitsuka/WebDev-Udemy | /practice/fib2.rb | UTF-8 | 134 | 3.59375 | 4 | [] | no_license | def fib(n)
memo = []
memo[n] ||= n if n == 0 || n == 1
memo[n] ||= fib(n - 2) + fib(n - 1)
end
for i in 0..10
puts fib(i)
end | true |
b7de80389618c75c123d996be1583297e44f7e8c | Ruby | crossfireup/study | /app/ruby/select.rb | UTF-8 | 340 | 2.90625 | 3 | [] | no_license | #!/usr/bin/env ruby
rp, wp = IO.pipe
mesg = "ping "
100.times {
rs, ws = IO.select([rp], [wp])
if r = rs[0]
ret = r.read(5)
print ret
case ret
when /ping/
mesg = "pong\n"
when /pong/
mesg = "ping "
end
end
if w = ws[0]
w.write(mesg)
end
}
| true |
5de256cc3dc90f0ac13a1ecefb0eb1a013b5b603 | Ruby | gregbell/observable | /spec/observable_spec.rb | UTF-8 | 2,338 | 2.546875 | 3 | [] | no_license | require File.dirname(__FILE__) + '/spec_helper'
describe Observable do
after(:each) do
# Reset the observables
Employee.class_eval{ @observables = {} }
end
describe "- Creating Observables" do
it "should create new observables with a name" do
class Employee
include Observable
observable :changed_location
end
Employee.observables.size.should == 1
Employee.observables.first.should == :changed_location
end
it "should create new observables based on the name of an attr_accessor" do
class Employee
include Observable
attr_accessor :salary
observable :salary
end
Employee.observables.size.should == 1
Employee.observables.first.should == :salary
end
it "should create a new anonymous observable with a name" do
Observable.create :system_messages
Observable.all_observables.should include('Observable::AnonymousObservables:system_messages')
end
end
describe "- Registering and receiving notifications" do
before(:each) do
class Employee
include Observable
attr_accessor :salary
observable :salary
end
end
after(:each) do
# Reset the observables
Employee.class_eval{ @observables = {} }
end
it "should register a new observer with a block" do
class HR
include Observable
observe Employee, :salary do |event|
raise "received event notification"
end
end
lambda{ Employee.new.salary = 5000 }.should raise_error("received event notification")
end
it "should register a new observer with a class method as a symbol" do
class HR
include Observable
observe Employee, :salary, :salary_changed
def self.salary_changed(event)
raise "received event notification"
end
end
lambda{ Employee.new.salary = 5000 }.should raise_error("received event notification")
end
it "should register a new observer on an instance of an observable class" do
employee = Employee.new
employee.observe :salary do
raise "received event notification"
end
lambda{ employee.salary = 5000 }.should raise_error("received event notification")
end
end
end | true |
3683f1c80cd17e84ce90e06de06e93ba3871381e | Ruby | njpa/launchschool-rb101 | /lesson_3/3_medium_1/question_05.rb | UTF-8 | 1,327 | 4.40625 | 4 | [] | no_license | # Alyssa asked Ben to write up a basic implementation of a Fibonacci
# calculator, A user passes in two numbers, and the calculator will keep
# computing the sequence until some limit is reached.
# Ben coded up this implementation but complained that as soon as he ran it,
# he got an error. Something about the limit variable. What's wrong with the
# code?
LIMIT = 15
#limit = 15
def fib(first_num, second_num)
while first_num + second_num < LIMIT
#while first_num + second_num < limit
sum = first_num + second_num
first_num = second_num
second_num = sum
end
sum
end
result = fib(0, 1)
puts "result is #{result}"
# How would you fix this so that it works?
# ANSWER
# The method level scope in which we attempt to access `limit`, cannot reach to
# the outer scope in which `limit` was instantiated. This will raise a
# `NameError`. We could instantiate `limit` as a constant. In ruby, constant variables are
# accessible within the method-level scope.
# We can also refactor the method so that it takes in an additional argument
# referencing the limit.
limit = 15
def fib(first_num, second_num, limit)
while first_num + second_num < limit
sum = first_num + second_num
first_num = second_num
second_num = sum
end
sum
end
result = fib(0, 1, limit)
puts "result is #{result}"
| true |
387e12d07b68b70ce44021427bfcc0bb48eb260e | Ruby | umuro/hobodemo1 | /lib/extended_date.rb | UTF-8 | 1,139 | 3.015625 | 3 | [] | no_license | # ExtendedDate is a simple extension to date making it possible to set a start year and end year inside a Hobo
# application. This is necessary for things such as birthdays and events far in the future or past.
class ExtendedDate < Date
# It is necessary to override new, as the behavior of Hobo likes to give it the base object. This will conflict
# with the original civil (and aliased new) method.
def self.new d
if d.is_a? Date
self.civil d.year, d.month, d.day, d.sg
else
return nil if d.empty? || d.nil?
begin
d, _, ex = d.partition('/')
m, _, y = ex.partition('/')
self.civil y.to_i, m.to_i, d.to_i
rescue
self.civil
end
end
end
def validate
if self == Date.civil
"an invalid date has been entered"
else
nil
end
end
# This is necessary for validation. There is nothing to be really validated though, as the date class will take care
# of it.
def length; 20; end
# Register this to use the "date" column type in the database
COLUMN_TYPE = :date
HoboFields.register_type(:extended_date, self)
end
| true |
b790ea08da557f2e4a78f9df35dccb18774135a5 | Ruby | blairanderson/sales_engine_web | /lib/sales_engine_web/models/finder_methods.rb | UTF-8 | 2,062 | 2.71875 | 3 | [] | no_license | module SalesEngineWeb
module FinderMethods
def create(params)
self.new(params).save
end
def add(subject)
table.insert(subject.to_hash)
end
def random
result = table.to_a.sample
self.new(result) if result
end
def find_by_id(id)
result = table.where(:id => id.to_i).first
new(result) if result
end
def verify_finder(params,search)
params.keys.select do |attribute|
self.respond_to?("#{search}#{attribute}")
end.pop
end
def find(params)
attribute = verify_finder(params,"find_by_")
self.send("find_by_#{attribute}", params[attribute])
end
def find_all(params)
attribute = verify_finder(params,"find_all_by_")
self.send("find_all_by_#{attribute}", params[attribute])
end
def belongs_to(relation)
new_class = relation.to_s.split('_').map{|e| e.capitalize}.join
define_method relation do
relation_class = SalesEngineWeb.const_get(new_class)
method_name = "find_by_id"
relation_id = self.send("#{relation}_id".to_sym)
relation_class.send(method_name, relation_id)
end
end
def self.new_class(association)
association[0..-2].split('_').map{|e| e.capitalize}.join
end
def has_many(association)
new_class = FinderMethods.new_class(association)
define_method association do
things_class = SalesEngineWeb.const_get(new_class)
method_name = "find_all_by_#{ self.class.to_s.split('::').last.downcase }_id"
things_class.send(method_name, id)
end
end
def has_many_through(association, through)
new_class = FinderMethods.new_class(association)
define_method association do
assoc_class = SalesEngineWeb.const_get(new_class)
finder_method = "find_all_by_#{ through[0..-2] }_id"
through_objects = self.send(through)
through_objects.map do |object|
assoc_class.send(finder_method, object.id)
end.flatten
end
end
end
end
| true |
7164a64f52cbccf32c6c449388ea65603abd8f73 | Ruby | bingo8670/ruby-programming-2.3 | /5.1.ad2pingcheng.rb | UTF-8 | 110 | 3.09375 | 3 | [] | no_license | # 将公历转换为平成纪年,1989为平成元年
ad = ARGV[0].to_i
pingcheng = ad -1988
puts pingcheng
| true |
c20d83181cfeec2d944745d13fed487fe8d65ac3 | Ruby | chef/win32-security | /lib/win32/security/acl.rb | UTF-8 | 6,733 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | # The Win32 module serves as a namespace only.
module Win32
# The Security class serves as a toplevel class namespace.
class Security
# The ACL class encapsulates an Access Control List.
class ACL
include Windows::Security::Constants
include Windows::Security::Functions
include Windows::Security::Structs
extend Windows::Security::Functions
# The version of the Win32::Security::ACL class.
VERSION = '0.2.1'
# The underlying ACL structure.
attr_reader :acl
# The revision level.
attr_reader :revision
# Creates and returns a new Win32::Security::ACL object. This object
# encapsulates an ACL structure, including a binary representation of
# the ACL itself, and the revision information.
#
def initialize(size = 1024, revision = ACL_REVISION)
acl = ACL_STRUCT.new
unless InitializeAcl(acl, size, revision)
FFI.raise_windows_error('InitializeAcl')
end
@acl = acl
@revision = revision
end
# Returns the number of ACE's in the ACL object.
#
def ace_count
info = ACL_SIZE_INFORMATION.new
unless GetAclInformation(@acl, info, info.size, AclSizeInformation)
FFI.raise_windows_error('GetAclInformation')
end
info[:AceCount]
end
# Returns a two element array that consists of the bytes in use and
# bytes free for the ACL.
#
def byte_info
info = ACL_SIZE_INFORMATION.new
unless GetAclInformation(@acl, info, info.size, AclSizeInformation)
FFI.raise_windows_error('GetAclInformation')
end
[info[:AclBytesInUse], info[:AclBytesFree]]
end
# Adds an access allowed ACE to the given +sid+, which can be a
# Win32::Security::SID object or a plain user or group name. If no
# sid is provided then the owner of the current process is used.
#
# The +mask+ is a bitwise OR'd value of access rights.
#
# The +flags+ argument can be anyone of the following constants.
#
# * OBJECT_INHERIT_ACE
# * CONTAINER_INHERIT_ACE
# * NO_PROPAGATE_INHERIT_ACE
# * INHERIT_ONLY_ACE
# * INHERITED_ACE
#
# Example:
#
# acl = Win32::Security::ACL.new
# acl.add_access_allowed_ace('some_user', GENERIC_READ | GENERIC_WRITE)
#
def add_access_allowed_ace(sid=nil, mask=0, flags=nil)
if sid.is_a?(Win32::Security::SID)
sid = sid.sid
else
sid = Win32::Security::SID.new(sid).sid
end
if flags
unless AddAccessAllowedAceEx(@acl, @revision, flags, mask, sid)
FFI.raise_windows_error('AddAccessAllowedAceEx')
end
else
unless AddAccessAllowedAce(@acl, @revision, mask, sid)
FFI.raise_windows_error('AddAccessAllowedAce')
end
end
sid
end
# Adds an access denied ACE to the given +sid+, which can be a
# Win32::Security::SID object ora plain user or group name. If
# no sid is provided then the owner of the current process is used.
#
# The +mask+ is the bitwise OR'd value of access rights.
#
# The +flags+ argument can be any one of the following constants:
#
# * OBJECT_INHERIT_ACE
# * CONTAINER_INHERIT_ACE
# * NO_PROPAGATE_INHERIT_ACE
# * INHERIT_ONLY_ACE
# * INHERITED_ACE
#
def add_access_denied_ace(sid=nil, mask=0, flags=nil)
if sid.is_a?(Win32::Security::SID)
sid = sid.sid
else
sid = Win32::Security::SID.new(sid).sid
end
if flags
unless AddAccessDeniedAceEx(@acl, @revision, flags, mask, sid)
FFI.raise_windows_error('AddAccessDeniedAceEx')
end
else
unless AddAccessDeniedAce(@acl, @revision, mask, sid)
FFI.raise_windows_error('AddAccessDeniedAce')
end
end
end
# Adds an ACE to the ACL object with the given +revision+ at +index+
# or the end of the chain if no index is specified.
#
# Returns the index if successful.
#--
# This won't work until we implement the ACE class.
#
def add_ace(ace, index=MAXDWORD)
unless AddAce(@acl, @revision, index, ace, ace.length)
FFI.raise_windows_error('AddAce')
end
index
end
# Deletes an ACE from the ACL object at +index+, or from the end of
# the chain if no index is specified.
#
# Returns the index if successful.
#
def delete_ace(index=MAXDWORD)
unless DeleteAce(@acl, index)
FFI.raise_windows_error('DeleteAce')
end
index
end
# Finds and returns an ACE object for the ACL at the given
# +index+. If no index is provided, then it returns an ACE object
# that corresponds to the first free byte of the ACL.
#
# If +raw+ is true, it will return an ACCESS_GENERIC_ACE struct,
# an FFI object that you can then access directly.
#
def find_ace(index = nil, raw = false)
result = nil
FFI::MemoryPointer.new(:pointer) do |pptr|
if index.nil?
unless FindFirstFreeAce(@acl, pptr)
FFI.raise_windows_error('FindFirstFreeAce')
end
else
unless GetAce(@acl, index, pptr)
FFI.raise_windows_error('GetAce')
end
end
# There's no way to know what type of ACE it is at this point as far
# as I know, so we use a generic struct and use the AceType to figure
# it out later, or the users can.
ace = ACCESS_GENERIC_ACE.new(pptr.read_pointer)
if raw
result = ace
else
result = ACE.new(ace[:Mask], ace[:Header][:AceType], ace[:Header][:AceFlags])
end
end
result
end
# Sets the revision information level, where the +revision_level+
# can be ACL_REVISION1, ACL_REVISION2, ACL_REVISION3 or ACL_REVISION4.
#
# Returns the revision level if successful.
#
def revision=(revision_level)
FFI::MemoryPointer.new(:ulong) do |buf|
buf.write_ulong(revision_level)
unless SetAclInformation(@acl, buf, buf.size, AclRevisionInformation)
FFI.raise_windows_error('SetAclInformation')
end
end
@revision = revision_level
revision_level
end
# Returns whether or not the ACL is a valid ACL.
#
def valid?
IsValidAcl(@acl)
end
end
end
end
| true |
c77d2fcf852284b8d4ef17a8ee1657c96c6af7e3 | Ruby | breadbaker/nn-wrap | /breast/breast.rb | UTF-8 | 541 | 2.953125 | 3 | [] | no_license | require '../nn.rb'
# 1000025,5,1,1,1,2,1,3,1,1,2
class Breast < NN
def initialize
@fann_network = true
@match_index = 10
@splitter ||= ','
@file_path ||= './breast-cancer-wisconsin.data.txt'
@epochs ||= 2000
@neuron_setup ||= [5, 10, 5]
@results_path ||= './results'
@special_normalize = {
10 => :good_or_bad
}
super
end
def good_or_bad(data_group, index)
data_group.map do |el|
if el == 2
[0,1]
else
[1,0]
end
end
end
end
a = Breast.new
a.run | true |
3ed0ab0705d0f3d166447e81532b4b5ea3396b9c | Ruby | oscos/launch_school | /rb100/ruby_basics/conditionals/ex07.rb | UTF-8 | 277 | 3.859375 | 4 | [] | no_license | # ex07.rb
# Stoplight (Part 2)
# Answered On: 06/28/2020
# Convert the following case statement to an if statement.
stoplight = ['green', 'yellow', 'red'].sample
if stoplight == 'green'
puts("Go!")
elsif stoplight == 'yellow'
puts("Slow down!")
else
puts("Stop!")
end | true |
e5c43b822f9128d7ba1f37c62cad3d63a4f055b6 | Ruby | ancduncan/WAD_2.Assesment_TestDriven | /wad_dond_gen_01.rb | UTF-8 | 4,256 | 3.3125 | 3 | [] | no_license | # Ruby code file - All your code should be located between the comments provided.
# Main class module
module DOND_Game
# Input and output constants processed by subprocesses. MUST NOT change.
GOES = 5
class Game
attr_reader :sequence, :selectedboxes, :openedboxes, :chosenbox, :selectedbox, :turn, :input, :output, :winner, :played, :wins, :losses, :guess, :values, :amounts
attr_writer :sequence, :selectedboxes, :openedboxes, :chosenbox, :selectedbox, :turn, :input, :output, :winner, :played, :wins, :losses, :guess, :values, :amounts
def initialize(input, output)
@input = input
@output = output
end
def getinput
@input.gets.chomp.upcase
end
def storeguess(guess)
if guess != ""
@selectedboxes = @selectedboxes.to_a.push "#{guess}"
end
end
# Any code/methods aimed at passing the RSpect tests should be added below.
def start()
@output.puts("Welcome to Deal or No Deal!")
@output.puts("Designed by: " + self.created_by())
@output.puts("StudentID: " + self.student_id())
@output.puts("Starting game...")
end
def created_by()
return "Andrej Szalma, Matey Krastev, Antonia Duncan, Cammy Begg, Laura McKenna"
end
def student_id()
return "123456789"
end
def displaymenu()
@output.puts("Menu: (1) Play | (2) New | (3) Analysis | (9) Exit")
end
def resetgame()
@output.puts("New game...")
@sequence = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
@selectedboxes = []
@openedboxes = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
@chosenbox = 0
@selectedbox = 0
@turn= 0
@turnsleft = GOES
@winner = 0
@played = 0
@wins = 0
@losses = 0
@guess = ""
@values = [0.01,0.10,0.50,1.00,5.00,10.00,50.00,100.00,250.00,500.00,750.00,1000.00,3000.00,5000.00,10000.00,15000.00,20000.00,35000.00,50000.00,75000.00,100000.00,250000.00]
@amounts = @values
end
def assignvaluestoboxes()
@sequence = @values
end
def showboxes()
for i in (0..21) do
s = "_"
g = "_"
b = i + 1
if @openedboxes[i] == 0
s = "Closed"
g = "[#{b}]"
else
s = "Opened"
g = "|#{b}|"
end
@output.print("#{g} ")
end
@output.print("*#{@chosenbox}* ")
end
def showamounts()
col1 = 0
col2 = 11
for i in (0..10)
c1 = @amounts[col1 + i]
c2 = @amounts[col2 + i]
@output.puts("#{c1} #{c2}")
end
end
def removeamount(value)
index = @amounts.index(value)
@amounts[index] = " "
end
def setchosenbox(num)
@chosenbox = num
end
def getchosenbox()
return @chosenbox
end
def displaychosenbox()
@output.puts("Chosen box: [#{@chosenbox}]")
end
def displaychosenboxvalue()
@output.puts("Chosen box: [#{@chosenbox}] contains: #{@sequence[@chosenbox - 1]}")
end
def displaychosenboxprompt()
@output.puts("Enter the number of the box you wish to keep.")
end
def displaychosenboxerror()
@output.puts("Error: Box number must be 1 to 22.")
end
def displayanalysis()
@output.puts("Game analysis...")
for i in (0..21) do
s = "_"
g = "_"
b = i + 1
if @openedboxes[i] == 0
s = "Closed"
g = "[#{b}]"
else
s = "Opened"
g = "|#{b}|"
end
@output.puts("#{g} Status: #{s}")
end
end
def boxvalid(num)
num = num.to_i
if (num > 0) && (num < 23)
return 0
else
return 1
end
end
def showselectedboxes()
@output.puts("Log: #{@selectedboxes.inspect}")
end
def displayselectboxprompt()
@output.puts("Enter the number of the box you wish to open. Enter returns to menu.")
end
def openbox(num)
@openedboxes[num-1] = 1
@output.puts("|#{num}| Status: Opened")
end
def bankerphoneswithvalue(value)
@output.puts("Banker offers you for your chosen box: #{value}")
end
def bankercalcsvalue(value)
return value / 2
end
def numberofboxesclosed()
count = 0
for i in (0..@openedboxes.length) do
if @openedboxes[i] == 0
count += 1
end
end
return count
end
def incrementturn()
@turn += 1
@turnsleft -= 1
end
def getturnsleft()
return @turnsleft
end
def finish()
@output.puts("... game finished.")
end
# Any code/methods aimed at passing the RSpect tests should be added above.
end
end
| true |
f2ef2ab7de77d08bfc6da14d566ab7021d7d761e | Ruby | tedlarai/launch_school | /ls-introduction-to-programming/basics_2.rb | UTF-8 | 183 | 3.265625 | 3 | [] | no_license | number = 5792
thousands = number / 1000
puts "#{thousands}"
hundreds = number % 1000 / 100
puts "#{hundreds}"
tens = number % 100 / 10
puts "#{tens}"
ones = number % 10
puts "#{ones}" | true |
f2ac47950a65ebeaa95628f1e457ae9cbd411aef | Ruby | solds-zz/programming-foundations | /lesson5/exercises/exercise16.rb | UTF-8 | 271 | 2.984375 | 3 | [] | no_license | def generate_uuid
hex_chars = "0123456789abcdef".split('')
uuid = ""
uuid_size = 36
hyphen_indices = [8, 13, 18, 23]
uuid_size.times do |i|
if hyphen_indices.include?(i)
uuid << '-'
else
uuid << hex_chars.sample
end
end
uuid
end
| true |
90678f343584a3ff76e135c1a38fc71f1213d084 | Ruby | yaqizhao/projet_THP | /Week1/Day3_Ruby/jeu.rb | UTF-8 | 737 | 3.984375 | 4 | [] | no_license | def askIfRollADice
puts "Please roll a dice"
gets.chomp
end
def rollADice
askIfRollADice
diceResult = 1 + rand(6)
puts "You rolled #{diceResult}."
return diceResult
end
def move(diceResult, whereIwas)
if diceResult == 1
if whereIwas != 0
return whereIwas - 1
else
return whereIwas
end
elsif diceResult == 5 or diceResult == 6
return whereIwas + 1
else # diceResult in {2 3 4}
return whereIwas
end
end
def turn(whereIwas)
whereIam = move(rollADice, whereIwas)
puts "You are now at level #{whereIam}."
return whereIam
end
def gameOver(whereIam)
if whereIam == 10
return true
else
return false
end
end
def game
whereIam = 0
while not gameOver(whereIam)
whereIam = turn(whereIam)
end
end
game | true |
dab47290b210b838a0be5115d3cfc52fd037aa2f | Ruby | tanordheim/ahgoblin | /app/models/recipe_group.rb | UTF-8 | 2,671 | 2.625 | 3 | [
"MIT"
] | permissive | class RecipeGroup < ActiveRecord::Base
DURATION_12H = 12
DURATION_24H = 24
DURATION_48H = 48
# Recipe groups belong to professions.
belongs_to :profession
# Recipe groups belong to users.
belongs_to :user
# Recipe groups are associated with recipes.
has_many :recipes, :dependent => :destroy
# Validate that the recipe group is associated with a profession.
validates :profession, :presence => true
# Validate that the recipe group is associated with a user.
validates :user, :presence => true
# Validate that the recipe group has a name.
validates :name, :presence => true
# Validate that the ah duration field is set, and that is has a valid value.
validates :ah_duration, :presence => true, :inclusion => { :in => [DURATION_12H, DURATION_24H, DURATION_48H] }
# Returns all recipe groups for the specified profession.
scope :for_profession, lambda { |profession| where(:profession_id => profession.id) }
# Returns all recipe groups for the specified user.
scope :for_user, lambda { |user| where(:user_id => user.id) }
# Order the recipe groups by the name of the associated profession.
scope :ordered_by_profession_name, includes(:profession).order('LOWER(professions.name) ASC')
# Order the recipe groups by name.
scope :ordered_by_name, order('LOWER(recipe_groups.name) ASC')
# Include the recipes within the group in the query.
scope :include_recipes, includes(:recipes => :item).includes(:recipes => {
:reagents => {
:reagent => {
# Preload item components and their items.
:item_components => :item,
# Preload reagent components, their reagents and those reagents items.
:reagent_components => { :reagent_reference => :item },
# Preload transformation components, and the full transformation data set.
:transformation_components => {
:transformation => {
:reagents => { :reagent => :item },
:yields => :item
}
}
}
}
})
# Returns the name of this recipe group, prefixed with the associated
# profession name.
def name_with_profession
"#{profession.name}: #{name}"
end
# Returns the AH deposit multiplier to apply to the item vendor value.
#
# This follows the standard Auction House deposit formula:
# Deposit (12hr auction) = 0.15 * MSV
# Deposit (24hr auction) = 2 * Deposit (12hr auction)
# Deposit (48hr auction) = 4 * Deposit (12hr auction)
def ah_deposit_multiplier
case ah_duration
when DURATION_24H then return 2
when DURATION_48H then return 4
else return 1
end
end
end
| true |
7d2d7b10720ddab71cdae04151eb7b57df9ab29c | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/gigasecond/a794094629bc4290b6d63adabfc0611d.rb | UTF-8 | 113 | 2.90625 | 3 | [] | no_license | class Gigasecond
SECONDS_PER_DAY = 60*60*24
def self.from(date)
date + (10**9)/SECONDS_PER_DAY
end
end
| true |
ccd704cb286c81d4871dab172f5c92c000c4cd6a | Ruby | runpaint/numb | /spec/numb/trimorphic_spec.rb | UTF-8 | 762 | 2.875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | describe Integer, "#trimorphic?" do
TRIMORPHIC = [0,1,4,5,6,9,24,25,49,51,75,76,99,125,249,251,375,
376,499,501,624,625,749,751,875,999,1249,3751,
4375,4999,5001,5625,6249,8751,9375,9376,9999,
18751,31249,40625,49999,50001,59375,68751,81249,
90624,90625]
it "returns true for trimorphic numbers" do
TRIMORPHIC.each do |number|
number.should be_trimorphic
end
end
it "returns false for non-trimorphic numbers" do
[2,3,7, 8752, 906266, 33333].each do |number|
number.should_not be_trimorphic
end
end
it "returns false for negative numbers" do
[2,3,4,7,9,8752, 906266, 33333].each do |number|
(-number).should_not be_trimorphic
end
end
end
| true |
3c8d836e066e65de6f565eebc2af138a350d35f9 | Ruby | TopherBlair/programs | /Game_of_life.rb | UTF-8 | 553 | 3.765625 | 4 | [] | no_license |
matrix = [(1..10).to_a,
(11..20).to_a,
(21..30).to_a,
(31..40).to_a,
(41..50).to_a,
(51..60).to_a,
(61..70).to_a,
(71..80).to_a,
(81..90).to_a,
(91..100).to_a,
]
puts "Sample Matrix:"
# prints out the matrix in a nice format
matrix.each do |r|
puts r.map { |p| p }.join(" ")
end
matrix.each_with_index do |row, row_index|
row.each_with_index do |value, col_index|
puts "The value #{value} is in row #{row_index}, column #{col_index}"
end
end
| true |
8dc8f537dccad01abd8580b9d5b1546d3530b05e | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/roman-numerals/89ef38e345b44a8bad2cdc917805e062.rb | UTF-8 | 794 | 3.59375 | 4 | [] | no_license | class Fixnum
def to_roman
romans = {0 => '', 1 => 'I', 4 => 'IV', 5 => 'V', 9 => 'IX', 10 => 'X', 50 => 'L', 100 => 'C', 500 => 'D', 1000 => 'M'}
nb = self
decomposition = []
result = []
if nb <= 5
if nb == 4 or nb == 5
result << romans[nb]
else
decomposition = nb.divmod(5)
result << "I"* decomposition[1]
result.join
end
end
if nb > 5 && nb <= 10
if nb == 9
result << romans[nb]
else
decomposition = nb.divmod(5)
result << "V" + "I"* decomposition[1]
result.join
end
end
if nb > 10 #&& <= 10
decomposition = nb.divmod(10) #[2, 7]
result << "X"* decomposition[0] + "I"* decomposition[1] #il faudrait que 7 soit décomposé !
result.join
end
result[0]
end
end
| true |
ccb6040901ea7418c9118f02c0f6ca84bb1f819c | Ruby | EricLondon/Ruby-Exec-Shell-With-Timeout | /test.rb | UTF-8 | 127 | 2.578125 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'logger'
log = Logger.new('./log.txt')
(1..20).each do |i|
puts i
log.debug i
sleep 1
end
| true |
d52ad60c9bbb20a07e94755465a4d528057031a8 | Ruby | staskjs/swan | /bin/swan | UTF-8 | 1,221 | 2.5625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require 'bundler/setup'
require 'swan'
require 'optparse'
require 'yaml'
require 'open-uri'
options = {
init: false,
init_params: '',
only: [],
config: '.swan.yml',
}
# Parse options
OptionParser.new do |opts|
opts.banner = 'Usage: swan [options]'
opts.on('--init', 'Initialize swan config file') do |v|
options[:init] = true
end
opts.on('-c', '--config config', 'Configuration file to use') do |c|
options[:config] = c
options[:init_params] = " -c #{c}"
end
opts.on('--only only', 'Comma-separated list of files, download only them') do |only|
options[:only] = only.split(',')
end
opts.on('-h', '--help', 'Show this help message') do
puts opts
exit
end
end.parse!
swan = Swan::Downloader.new
if options[:init]
# Create new config file
# Ask user to override if exists
swan.init(options[:config])
else
# Read config file
begin
files = YAML.load_file(options[:config])
rescue
puts "Can not find #{options[:config]} file. Please run `swan --init#{options[:init_params]}` to create it or choose another file."
exit
end
unless files
puts 'Nothing to download.'
exit
end
swan.download(files, options)
end
| true |
1866fd2586453a91ba9a46c0ad6dcd986b580bb9 | Ruby | yasukuro6259/ruby_drill | /ruby_drill_day33.rb | UTF-8 | 1,403 | 4.15625 | 4 | [] | no_license | 問題.1
西暦の年数および月を入力し、その月の日数を求めるプログラムを書きます。
その場合、閏年について考慮する必要があります。
閏年は以下の判断基準で決まります。
①その西暦が4で割り切れたら閏年である
②ただし、例外として100で割り切れる西暦の場合は閏年ではない
③ただし、その例外として400で割り切れる場合は閏年である
つまり、西暦2000年は閏年であり、西暦2100年は閏年ではありません。
これらに対応できるように、出力例と雛形をもとに実装しましょう。
出力例
1990年2月 =>"1990年2月は28日間あります"
2000年2月 =>"2000年2月は29日間あります"
2100年2月 =>"2100年2月は28日間あります"
2000年3月=>"2000年3月は31日間あります"
雛形
def get_days(year, month)
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if month == 2 && year % 4 == 0
end
puts "年を入力してください:"
year = gets.to_i
puts "月を入力してください:"
month = gets.to_i
days = get_days(year, month)
puts "#{year}年#{month}月は#{days}日間あります"
もしmonthが2月かつyearが4で割り切れて、100で割り切れないとき
4で割り切れる and 100で割り切れない
400で割り切れる and 100で割り切れない | true |
8543b4d8db4cad53bee1a75cf017d4ee88fadf3c | Ruby | filip373/design-patterns | /01_factory_method/boat.rb | UTF-8 | 143 | 3.109375 | 3 | [] | no_license | class Boat
def go(package)
puts("Sailing with #{package}...")
sleep(1)
puts("Package #{package} delivered with boat!")
end
end
| true |
295818e2820a78dc4d8dafa64b301ae9b776a8ed | Ruby | tkhrk/poker | /spec/requests/cards_spec.rb | UTF-8 | 3,055 | 2.578125 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe "API::Ver1::Cards", type: :request do
let(:request_header) do
{ 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' }
end
let(:good_cards) do
'{"cards": ["H1 H13 H12 H11 H10", "H9 C9 S9 H2 C12","C13 D12 C11 H8 H7"]}'
end
let(:wrong_cards) do
'{"cards": ["H1 H13 H12 H11 H10", "H9 C9 S95 G2 C12","C13 D12 C11 H8 H7"]}'
end
describe "POST /api/v1/cards/check" do
context "正しいパラメータを送ったとき" do
before do
post "/api/v1/cards/check", params: good_cards, headers: request_header #URLはあってる模様.cards.rbには送られているのを確認済み
end
it "201(create)が返ってくる" do
expect(response).to have_http_status(201)
end
it "Cardレコードが増える" do
expect {
post "/api/v1/cards/check", params: good_cards, headers: request_header
}.to change { Card.count }.by(3)
end
it "役,bestを含むJSONが返ってくる" do
body = JSON.parse(response.body)
expect(body["result"][0]["card"]).to eq "H1 H13 H12 H11 H10"
expect(body["result"][0]["hand"]).to eq "ストレートフラッシュ"
expect(body["result"][0]["best"]).to eq true
expect(body["result"][1]["card"]).to eq "H9 C9 S9 H2 C12"
expect(body["result"][1]["hand"]).to eq "スリー・オブ・ア・カインド"
expect(body["result"][1]["best"]).to eq false
expect(body["result"][2]["card"]).to eq "C13 D12 C11 H8 H7"
expect(body["result"][2]["hand"]).to eq "ハイカード"
expect(body["result"][2]["best"]).to eq false
end
end
context "間違ったパラメータを含むリクエストを送ったとき" do
before do
post "/api/v1/cards/check", params: wrong_cards, headers: request_header
end
it "エラーメッセージを含むJSONが返ってくる" do
body = JSON.parse(response.body)
expect(body["result"][0]["card"]).to eq "H1 H13 H12 H11 H10"
expect(body["result"][0]["hand"]).to eq "ストレートフラッシュ"
expect(body["result"][0]["best"]).to eq true
expect(body["result"][1]["card"]).to eq "C13 D12 C11 H8 H7"
expect(body["result"][1]["hand"]).to eq "ハイカード"
expect(body["result"][1]["best"]).to eq false
expect(body["error"][0]["card"]).to eq "H9 C9 S95 G2 C12"
expect(body["error"][0]["msg"]).to eq ["3番目のカード指定文字が不正です。 (S95)","4番目のカード指定文字が不正です。 (G2)","半角英字大文字のスート(S,H,D,C)と数字(1〜13)の組み合わせでカードを指定してください。"]
end
it "正しいCardセットの数だけCardレコードが増える" do
expect {
post "/api/v1/cards/check", params: wrong_cards, headers: request_header
}.to change { Card.count }.by(2) #2セット:正,1セット:誤
end
end
end
end
| true |
a3509adab4b45a03c118b6e5a3176652e2ff1485 | Ruby | ODINAKACHUKWU/random-room-allocator | /app.rb | UTF-8 | 7,320 | 3.328125 | 3 | [] | no_license | # require_relative "helpers/allocation_helpers"
# require_relative "lib/file_reader"
# require_relative "lib/application"
# require_relative "db/setup"
# require_relative "controllers/application_controller"
# require "pry-byebug"
# require_relative "helpers/response_helpers"
# Steps:
# -> Get all data from files and store the data obtained in arrays of objects (employees, offices, and rooms respectively)
# -> Assign all employees (staff and fellows) to available offices
# -> Assign all fellows (male and female) to available rooms
# -> Send JSON responses to allocations folder
class Applicatio
# include AllocationHelper
# include FileReaderHelper
# include ResponseHelper
# @@employees = []
# @@office_spaces = []
# @@male_rooms = []
# @@female_rooms = []
# This method allocates all employees to available offices
def allocate_employees
loop do
break if unallocated_employees?(@@employees).length == 0 || available_office_space?(@@office_spaces).length == 0
office = @@office_spaces.sample
@@employees.each do |employee|
if employee.office_space.nil? && office["available_space"] >= 1
employee.office_space = (office["office"])
office["available_space"] -= 1
end
end
end
end
# This method allocates all fellows who require accommodation to available rooms
def allocate_fellows
male_fellows = @@employees.select do |employee|
employee.sex == "M" && employee.role == "FELLOW" && employee.accommodation? == "Y"
end
female_fellows = @@employees.select do |employee|
employee.sex == "F" && employee.role == "FELLOW" && employee.accommodation? == "Y"
end
fellows = [male_fellows, female_fellows]
fellows.each do |fellows|
loop do
rooms = [@@male_rooms, @@female_rooms]
break if unallocated_fellows?(fellows).length == 0 || available_room_space?(fellows, rooms).length == 0
fellows.sample.sex == "M" ? room = rooms[0].sample : room = rooms[1].sample
fellows.each do |fellow|
if fellow.room.nil? && room["available_space"] >= 1
fellow.room = (room["room"])
room["available_space"] -= 1
end
end
end
end
end
# This method executes all allocations and returns all required json responses
def self.allocate_all
# files = [["files/employees.txt", @@employees], ["files/offices.txt", @@office_spaces], ["files/male_rooms.txt", @@male_rooms], ["files/female_rooms.txt", @@female_rooms]]
# if read_files(files) == "No file match!"
# puts "Oops! Allocation was not successful. Please ensure that every file has an all-letters capitalized title!"
# else
# puts "Files successfully read!"
# puts "allocating offices to employees..."
# puts ".................................."
# allocate_employees
# puts "allocating rooms to fellows..."
# allocate_fellows
# puts ".................................."
# puts "Allocations successfull!"
# send_office_allocation(@@employees)
# send_male_room_allocation(@@employees)
# send_female_room_allocation(@@employees)
# send_unallocated_employees(@@employees)
# send_unallocated_fellows(@@employees)
# end
end
end
# ======================= Start of the app
class Collection
attr_reader :data
def initialize(data = [])
@data = data
end
end
# require_relative "models/employee"
require_relative "controllers/employee_controller"
require_relative "controllers/space_controller"
# [TODO]: Write code to verify whether a file is empty in order to return a clear response message to the user that the file is empty.
class RandomAllocator
attr_reader :allocations
def initialize(allocations = [])
@allocations = allocations
end
def analyze_file(*files)
files.each do |file|
title = file.split("/").last.split(".").first
begin
case title
when "employees"
# Call the employee controller
collection = Collection.new
File.open(file).each do |line|
data = line.chomp.split
collection.data.push data
end
EmployeeController.call(collection)
when "offices"
# Call the space controller
collection = Collection.new
File.open(file).each do |line|
data = line.chomp.split
data.push "office"
collection.data.push data
end
SpaceController.call(collection)
when "male_rooms"
# Call the space controller
collection = Collection.new
File.open(file).each do |line|
data = line.chomp.split
data.push "room"
data.push "male"
collection.data.push data
end
SpaceController.call(collection)
when "female_rooms"
# Call the space controller
collection = Collection.new
File.open(file).each do |line|
data = line.chomp.split
data.push "room"
data.push "female"
collection.data.push data
end
SpaceController.call(collection)
else
unsuported_file = file.split("/").last
puts "The file '#{unsuported_file}' is not supported!"
end
rescue => exception
puts "An error occured: #{exception.full_message}"
end
end
end
def get_all_employees
EmployeeController.fetch_all
end
def get_all_male_fellows
EmployeeController.fetch_all_male_fellows
end
def get_all_female_fellows
EmployeeController.fetch_all_female_fellows
end
def get_all_spaces
SpaceController.fetch_all
end
def get_male_rooms
SpaceController.fetch_all_male_rooms
end
def get_female_rooms
SpaceController.fetch_all_female_rooms
end
def get_available_offices
SpaceController.get_available_offices
end
def allocate_offices_to_employees
employees = get_all_employees
offices = get_available_offices
allocate(employees, offices)
# p ">>>>>>", employees
end
def allocate_rooms_to_fellows
allocate_rooms_to_male_fellows
# allocate_rooms_to_female_fellows
end
private
def allocate_rooms_to_male_fellows
@male_fellows = get_all_male_fellows
@rooms = get_male_rooms
allocate(@male_fellows, @rooms)
end
def allocate_rooms_to_female_fellows
@male_fellows = get_all_female_fellows
@rooms = get_female_rooms
end
def allocate(employees, spaces)
loop do
if unallocated_employees?(employees) && available_space?(spaces)
employees.each do |employee|
space = spaces.sample
employee.office = space.name
space.available_space -= 1
end
else
break
end
end
end
def unallocated_employees?(employees)
employees.select { |employee| employee.office == nil }.any?
end
def available_space?(spaces)
spaces.select { |space| space.available_space > 0 }.any?
end
end
app = RandomAllocator.new
app.analyze_file("files/employees.txt", "files/offices.txt", "files/male_rooms.txt", "files/female_rooms.txt", "files/file.txt")
app.allocate_offices_to_employees
app.allocate_rooms_to_fellows
p ">>>>>", app.get_all_employees
| true |
36c7059e51e0da8e03dd7d53ca469016cc8fd55b | Ruby | derrelldurrett/AliasMadness | /app/models/initialize_bracket/template_loader.rb | UTF-8 | 2,804 | 2.78125 | 3 | [] | no_license | module InitializeBracket
class TemplateLoader
require 'assets/rgl/directed_adjacency_graph'
# require_relative './template_format_error'
include Singleton
attr_reader :bracket_structure_data,
:spec_comp_regex,
:label_lookup
def initialize
# Construction:
# nNODE_NUM(a(nA_NODE1,nA_NODE2)|tT_TEAM_NUM(T_TEAM_NAME;sT_TEAM_SEED))
@spec_comp_regex =
Regexp.new('\An(?<node_num>\d+)\(
( (?<has_a>a) \( n(?<a_node1>\d+) ; n(?<a_node2>\d+) \)
| (?<has_t>t)(?<team_num>\d+)
\( (?<team_name>[^;]+) ; s(?<team_seed>\d+) \) )
\)\z',
Regexp::EXTENDED | Regexp::MULTILINE)
end
def load_template(file)
data = File.open(file, &:readlines)
@bracket_structure_data = build_and_sort_match_data(data)
end
def build_and_sort_match_data(data)
cells_as_match_data = []
data.each do |line|
cells_as_match_data.concat(
line.chomp.split(',').select { |cell| !cell.nil? && !cell.eql?('') }
.map { |c| @spec_comp_regex.match(c) }
)
end
# rename compare when refactoring...
cells_as_match_data.sort! { |a, b| compare_csv_elements a, b }
cells_as_match_data
end
def build_graph(graph)
@label_lookup = {}
# Edge is two node numbers. Lookup allows us to get from a node
# number to the Game/Team that it represents
edge_list = []
@bracket_structure_data.reverse_each do |d|
build_lookups(d, edge_list)
end
edge_list.reverse_each { |e| graph.add_edge e[0], e[1] }
graph
end
private
def build_lookups(d, edge_list)
if d[:has_a]
build_edge(d, edge_list)
elsif d[:has_t]
get_team(d)
else
raise TemplateFormatError "Bad data-- node #{d} has neither a nor t"
end
end
def build_edge(d, edge_list)
label_lookup.include?(d[:node_num]) or
label_lookup.store(d[:node_num], new_game(d[:node_num]))
edge_list << [d[:node_num], d[:a_node1]]
edge_list << [d[:node_num], d[:a_node2]]
end
def get_team(d)
if label_lookup.include?(d[:node_num])
label_lookup.fetch(d[:node_num])
else
t = { name: d[:team_name],
seed: d[:team_seed].to_i,
label: d[:node_num].to_s }
label_lookup.store(d[:node_num], t)
t
end
end
def new_game(node_num)
{ label: node_num, winner: nil }
end
# (Meaningless) Examples:
# n23(a(n30;n34)),
# n12(t12(Foobar U.;s2)),
# n14(t3(Ancillary St.;s4)),
# n13(t5(Boofoo U.;s15))
def compare_csv_elements(a, b)
a[:node_num].to_i <=> b[:node_num].to_i
end
end
end | true |
f98a6204c042b8659ee57eb4c8d6fcdc23385c8f | Ruby | ymason/ironhack | /Week_10/URL_Shortly/app/models/link.rb | UTF-8 | 297 | 2.8125 | 3 | [
"MIT"
] | permissive | class Link < ActiveRecord::Base
ALPHABET = [('a' .. 'z').to_a, ('A' .. 'Z').to_a].flatten
def self.generate_shortlink(link_length)
ALPHABET.sample(link_length).join
# shortlink =
# link_length.times do
# shortlink += ALPHABET[rand(ALPHABET.length)]
# end
# shortlink
end
end
| true |
91b63ea2d8b35114d309f1a8a512ee344754bdf9 | Ruby | brpadilha/conceitos_ruby | /modulo_02/12_criando_classes.rb | UTF-8 | 186 | 3.78125 | 4 | [] | no_license | class Pessoa
def dizOla(name = 'Bruno')
p "Olá #{name}"
end
def initialize(cont = 5)
cont.times do |i|
puts "Contando... #{i}"
end
end
end
p = Pessoa.new(7)
| true |
f9d21a93af58aee98a719f7d6b78986ce747586e | Ruby | shailaja-enbake/Ruby | /q05moreque.rb | UTF-8 | 783 | 4.03125 | 4 | [] | no_license | puts " Q1 : What is 2 + 2 ?"
var1 = gets.chomp
if var1.to_i == 4
puts "Correct ! "
else
puts "Wrong - the answer was 4 "
end
puts "Q2 : What is 2 + 6 ?"
var2 = gets.chomp
if var2.to_i == 8
puts "Correct ! "
else
puts "Wrong - the answer was 8 "
end
puts "Q3 : What is 2 * 2 ?"
var3 = gets.chomp
if var3.to_i == 4
puts "Correct ! "
else
puts "Wrong - the answer was 4 "
end
puts "Q4 : What is 2 / 2 ?"
var4 = gets.chomp
if var4.to_i == 1
puts "Correct ! "
else
puts "Wrong - the answer was 1 "
end
puts "Q5 : What is 10 - 2 ?"
var5 = gets.chomp
if var5.to_i == 8
puts "Correct ! "
else
puts "Wrong - the answer was 8 "
end
| true |
904b762e84da775ea48a412c9aef37e933806e5f | Ruby | jimbog/cucumbering | /features/step_definitions/list_steps.rb | UTF-8 | 397 | 2.546875 | 3 | [] | no_license | Given(/^I have the following elements$/) do |table|
table.hashes.each { |element| Store.add element }
end
When(/^I find an element with id (\d+)$/) do |id|
@result = Store.find_by_id id
puts "the result is #{@result}"
end
Then("I should get $name") do |name|
expect(@result["name"]).to eq(name)
end
Transform /table:id,name/ do |table|
table.map_column! (:id) { |cell| cell.to_i }
end
| true |
b67052d6eab48f93e7ae9a125c9a2101db36d538 | Ruby | Emik234/formtastic | /lib/formtastic/inputs/country_input.rb | UTF-8 | 3,624 | 2.8125 | 3 | [
"MIT"
] | permissive | module Formtastic
module Inputs
# Outputs a country select input, wrapping around a regular country_select helper.
# Rails doesn't come with a `country_select` helper by default any more, so you'll need to do
# one of the following:
#
# * install the [country_select](https://github.com/stefanpenner/country_select) gem
# * install any other country_select plugin that behaves in a similar way
# * roll your own `country_select` helper with the same args and options as the Rails one
#
# Formtastic supports both 1.x and 2.x of stefanpenner/country_select, but if you're upgrading
# from 1.x, they behave quite differently, so please see their [upgrade instructions](https://github.com/stefanpenner/country_select/blob/master/UPGRADING.md).
#
# By default, Formtastic includes a handful of English-speaking countries as "priority
# countries", which can be set in the `priority_countries` configuration array in the
# formtastic.rb initializer to suit your market and user base (see README for more info on
# configuration). Additionally, it is possible to set the :priority_countries on a per-input
# basis through the `:priority_countries` option. These priority countries will be passed down
# to the `country_select` helper of your choice, and may or may not be used by the helper.
#
# @example Basic example with full form context using `priority_countries` from config
#
# <%= semantic_form_for @user do |f| %>
# <%= f.inputs do %>
# <%= f.input :nationality, :as => :country %>
# <% end %>
# <% end %>
#
# <li class='country'>
# <label for="user_nationality">Country</label>
# <select id="user_nationality" name="user[nationality]">
# <option value="...">...</option>
# # ...
# </li>
#
# @example `:priority_countries` set on a specific input (country_select 1.x)
#
# <%= semantic_form_for @user do |f| %>
# <%= f.inputs do %>
# <%= f.input :nationality, :as => :country, :priority_countries => ["Australia", "New Zealand"] %>
# <% end %>
# <% end %>
#
# <li class='country'>
# <label for="user_nationality">Country</label>
# <select id="user_nationality" name="user[nationality]">
# <option value="...">...</option>
# # ...
# </li>
#
# @example `:priority_countries` set on a specific input (country_select 2.x)
#
# <%= semantic_form_for @user do |f| %>
# <%= f.inputs do %>
# <%= f.input :nationality, :as => :country, :priority_countries => ["AU", "NZ"] %>
# <% end %>
# <% end %>
#
# <li class='country'>
# <label for="user_nationality">Country</label>
# <select id="user_nationality" name="user[nationality]">
# <option value="...">...</option>
# # ...
# </li>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
class CountryInput
include Base
def to_html
raise "To use the :country input, please install a country_select plugin, like this one: https://github.com/stefanpenner/country_select" unless builder.respond_to?(:country_select)
input_wrapping do
label_html <<
builder.country_select(method, priority_countries, input_options, input_html_options)
end
end
def priority_countries
options[:priority_countries] || builder.priority_countries
end
end
end
end
| true |
c91bff646541fe9edaf2e9f8aaa02bf9b56d89da | Ruby | muratatak77/react_rails_appointment_schedule | /db/seeds.rb | UTF-8 | 4,220 | 2.796875 | 3 | [] | no_license | =begin
Name,Timezone,Day of Week,Available at,Available until
Christy Schumm,(GMT-06:00) America/North_Dakota/New_Salem,Monday, 9:00AM, 5:30PM
Christy Schumm,(GMT-06:00) America/North_Dakota/New_Salem,Tuesday, 8:00AM, 4:00PM
Christy Schumm,(GMT-06:00) America/North_Dakota/New_Salem,Thursday, 9:00AM, 4:00PM
Christy Schumm,(GMT-06:00) America/North_Dakota/New_Salem,Friday, 7:00AM, 2:00PM
Natalia Stanton Jr.,(GMT-06:00) Central Time (US & Canada),Tuesday, 8:00AM,10:00AM
Natalia Stanton Jr.,(GMT-06:00) Central Time (US & Canada),Wednesday,11:00AM, 6:00PM
Natalia Stanton Jr.,(GMT-06:00) Central Time (US & Canada),Saturday, 9:00AM, 3:00PM
Natalia Stanton Jr.,(GMT-06:00) Central Time (US & Canada),Sunday, 8:00AM, 3:00PM
Nola Murazik V,(GMT-09:00) America/Yakutat,Monday, 8:00AM,10:00AM
Nola Murazik V,(GMT-09:00) America/Yakutat,Tuesday,11:00AM, 1:00PM
Nola Murazik V,(GMT-09:00) America/Yakutat,Wednesday, 8:00AM,10:00AM
Nola Murazik V,(GMT-09:00) America/Yakutat,Saturday, 8:00AM,11:00AM
Nola Murazik V,(GMT-09:00) America/Yakutat,Sunday, 7:00AM, 9:00AM
Elyssa O'Kon,(GMT-06:00) Central Time (US & Canada),Monday, 9:00AM, 3:00PM
Elyssa O'Kon,(GMT-06:00) Central Time (US & Canada),Tuesday, 6:00AM, 1:00PM
Elyssa O'Kon,(GMT-06:00) Central Time (US & Canada),Wednesday, 6:00AM,11:00AM
Elyssa O'Kon,(GMT-06:00) Central Time (US & Canada),Friday, 8:00AM,12:00PM
Elyssa O'Kon,(GMT-06:00) Central Time (US & Canada),Saturday, 9:00AM, 4:00PM
Elyssa O'Kon,(GMT-06:00) Central Time (US & Canada),Sunday, 8:00AM,10:00AM
Dr. Geovany Keebler,(GMT-06:00) Central Time (US & Canada),Thursday, 7:00AM, 2:00PM
Dr. Geovany Keebler,(GMT-06:00) Central Time (US & Canada),Thursday, 3:00PM, 5:00PM
=end
require 'open-uri'
require 'csv'
require 'constant'
require 'date_util'
# DAYS_OF_WEEK = %w[Sunday Monday Tuesday Wednesday Thursday Friday Saturday].freeze
# DURATION_MINUTES = 30
def self.generate_time_slots(start_time, finish_time)
time_slots = []
start_time = Time.parse(start_time)
finish_time = Time.parse(finish_time)
puts " > start_time : #{start_time}, finish_time : #{finish_time}"
# puts "(finish_time.hour - start_time.hour) : #{(finish_time.hour - start_time.hour) }"
# puts "(60 / Constant::DURATION_MINUTES) : #{(60 / Constant::DURATION_MINUTES)}"
total = (finish_time.hour - start_time.hour) * (60 / Constant::DURATION_MINUTES)
puts " > total : #{total} time slots"
1.upto(total) do
time_slots << DateUtil.convert_to_string(start_time)
start_time += (Constant::DURATION_MINUTES * 60)
end
puts " > We got time_slots : #{time_slots}"
time_slots
end
def self.create_coach(item)
coach = Coach.new()
coach.name = item[:name]
coach.time_zone = item[:time_zone]
if coach.save!
puts "Coach is created : #{coach.id}"
else
puts "Coach is not created : #{coach.errors}"
end
coach
end
def load_data
data_url = "https://gist.githubusercontent.com/wireframe/4a6f196d1b4b24617916d81239eea658/raw/7ca471b2a915c5a6f9a205d68b3fc0cedd527938/data.csv"
coaches_data = []
CSV.new(open(data_url), :headers => :first_row).each do |line|
obj = {}
obj[:name] = line[0]
obj[:time_zone] = line[1]
obj[:day_of_week] = line[2]
obj[:available_at] = line[3]
obj[:available_until] = line[4]
coaches_data << obj
end
coaches_data
end
def start(coaches_data)
ActiveRecord::Base.transaction do
coaches_data.each do |item|
puts "Start Process. Getting coach: #{item}"
coach = Coach.find_by_name(item[:name])
coach = self.create_coach(item) unless coach
day_of_week = Constant::DAYS_OF_WEEK.index(item[:day_of_week])
available_at = item[:available_at].strip
available_until = item[:available_until].strip
if availability = coach.availabilities.create!(day_of_week: day_of_week, available_at: available_at, available_until: available_until)
puts "Availabilities were created!"
end
times_slots = self.generate_time_slots(available_at, available_until)
times_slots.each do |ts|
TimeSlot.create!(availability: availability, start_time: ts )
puts "TimeSlot were created!"
end
end
User.create!(name: "Test User", time_zone: "(GMT-07:00) America/Los_Angeles")
end
end
data = load_data()
start(data)
| true |
006017aa420611ca69086a8d0d495ad0dcffa79e | Ruby | zaashige/ProjectEuler | /problem 1.rb | UTF-8 | 503 | 3.8125 | 4 | [] | no_license | =begin
Project Euler - Problem #1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
=end
require 'benchmark'
time = Benchmark.realtime do
# Begin Solution
multiples = Array.new
(1..999).each do |i|
if i % 3 == 0 or i % 5 == 0
multiples.push(i)
end
end
answer = multiples.inject(0, :+)
puts(answer)
# End Solution
end
puts("Solved in #{time} seconds.") | true |
0aa9c4275ef3c9f84b8da825e75df841cd116e27 | Ruby | pr0biem/passgen-2.0 | /app/helpers/keywords_helper.rb | UTF-8 | 1,613 | 2.90625 | 3 | [] | no_license | module KeywordsHelper
require 'securerandom'
def true_rand(x)
num = SecureRandom.random_number(x)
until num != 0
num = SecureRandom.random_number(x)
end
return num
end
def roll_5_dice
@roll = ""
5.times do
@roll << true_rand(6).to_s
end
@roll.to_i
end
def roll_3_dice
@roll = ""
3.times do
@roll << true_rand(6).to_s
end
@roll.to_i
end
def generate
separator = params[:separator]
pass_length = params[:length_of_password].to_i
if params[:l_or_w] == 'Words'
if separator.length <= 3 && separator.length >= 0
if pass_length <= 13 && pass_length > 0
count = 0
@display = ""
until count == pass_length
roll_5_dice
@display << @keyword.find(@roll).value + separator
count += 1
end
else
@display = "Minumum of 1 and maximum of 13 words allowed."
end
else
@display = "Your separator must be 3 characters or less"
end
elsif params[:l_or_w] == 'Letters'
if separator.length <= 3 && separator.length >= 0
if pass_length <= 25 && pass_length > 0
count = 0
@display = ""
until count == pass_length
roll_3_dice
@display << @keyword.find(@roll).value + separator
count += 1
end
else
@display = "Minumum of 1 and maximum of 25 letters allowed."
end
else
@display = "Your separator must be 3 characters or less"
end
end
return @display
end
end
| true |
8593cbca76eca47f8613393638782ffacb20c697 | Ruby | sarita2129/PractiseCode | /Ruby/lesson7/Inheritance.rb | UTF-8 | 801 | 4.03125 | 4 | [] | no_license | class Employee
attr_reader :name,:salary
def initialize(name,salary)
@name = name
@salary = salary
end
def CalcSalary(rate)
@salary += rate * salary / 100
puts "You are in main class"
end
end
class AccountEmployee < Employee
end
class SalesEmployee < Employee
def CalcSalary(rate,salesperYear)
if salesperYear > 10000
@salary += (rate + 5) * salary / 100
else
@salary += rate * salary / 100
end
puts "You are in child class"
end
end
employee = Employee.new("Richard",20000)
employee.CalcSalary(10)
puts employee.salary
accountemployee = AccountEmployee.new("anna",12000)
accountemployee.CalcSalary(10)
puts accountemployee.salary
salesemployee = SalesEmployee.new("anna",10000)
salesemployee.CalcSalary(10,12000)
puts salesemployee.salary
| true |
d2053c64252291b7bd65fba2c52410adcc15b736 | Ruby | saeedghorbanim/ruby_fundamentals | /ruby_puzzles.rb | UTF-8 | 796 | 3.8125 | 4 | [] | no_license | a = [3,5,1,2,7,9,8,13,25,32]
sum = 0
for j in a
sum += j
end
puts sum
puts a.reject { |number| number < 10 }
people = ["John", "KB", "Oliver", "Cory", "Matthew", "Christopher"]
puts people.shuffle
puts people.select {|people| people.length > 5}
alphabet = ("a".."z").to_a
puts alphabet.shuffle.last
puts alphabet.shuffle.first
mixed = alphabet.shuffle
if ["a","e","i","o","u"].include? mixed.first
puts "#{mixed.first} is a vowel"
end
random = []
10.times { random << rand(55..100) }
puts random
randoms= []
10.times { randoms << rand(55..100) }
puts randoms.sort
puts randoms.max
puts randoms.min
word = ""
5.times { word << (65+rand(26)).chr }
puts word
new_arr = []
10.times do
word = ""
5.times { word << (65+rand(26)).chr }
new_arr << word
end
puts new_arr
| true |
79bc30fc33a372dc758f12456c980f48e261296c | Ruby | cdsandoval/mini-assignment-day4 | /5. insertion_sort.rb | UTF-8 | 422 | 3.859375 | 4 | [] | no_license | def insertionSort1(n, arr)
ele = arr[n - 1]
(n - 2).downto(0) do |index|
if (arr[index] < ele)
arr[index + 1] = ele
puts arr.join(" ")
break
else
arr[index + 1] = arr[index]
puts arr.join(" ")
if (index - 1 < 0)
arr[0] = ele;
puts arr.join(" ")
end
end
end
end
n = 10
arr = "2 3 4 5 6 7 8 9 10 1".split(' ').map(&:to_i)
insertionSort1 n, arr
| true |
bc7af269609e6a61245dc43b99e194f66ec2e087 | Ruby | anickel101/ruby-oo-practice-relationships-domains-nyc01-seng-ft-080320 | /app/models/lyft/driver.rb | UTF-8 | 892 | 3.65625 | 4 | [] | no_license | class Driver
attr_reader :name
@@all = []
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
def new_ride(passenger, distance)
Ride.new(self, passenger, distance)
end
#Selects all the rides that have THIS DRIVER as its driver
def rides
Ride.all.select {|ride| ride.driver == self}
end
#Of all this driver's rides, pull out the unqiue passenger names
def passengers
self.rides.map {|ride| ride.passenger}.uniq
end
#Get all the rides of THIS driver, sum the distances.
def total_distance
self.rides.sum {|ride| ride.distance}
end
#Of ALL drivers, find the ones who have a total distance > given float distance.
def self.mileage_cap(distance)
self.all.find_all {|driver| driver.total_distance.to_f > distance}
end
end
| true |
9e0ad4e01523f6ec88c809cb25fc2ea663e2ccb0 | Ruby | RasPat1/withdrawlolz | /narcs/Tester.rb | UTF-8 | 814 | 2.84375 | 3 | [] | no_license | Dir["./funcs/*.rb"].each { |file| require file}
Dir["./lib/*.rb"].each { |file| require file}
class Tester
def initialize
end
def call
# Run each alg from k = 1 to k = 10 for performance comparison
# Run each for 60 seconds and compare how many solutions were found
k = 40
max_seconds = 60
holder = ResultHolder.new("Alt Timed Run Max: #{max_seconds}s")
funcs = [
[FindNarcs, k, "Standard", max_seconds],
[FastFindNarcs, k, "Fast", max_seconds],
[FasterFindNarcs, k, "Faster", max_seconds],
[FastestFindNarcs, k, "Fastest", max_seconds],
]
funcs.each do |func_array|
klass = func_array[0]
result = klass.new.call(*func_array[1..-1])
holder.add_result(result)
end
holder.print_results
# holder.print_chart
end
end | true |
4f63c2e9cbd4b00f1bce483f08a8f8be5e27a94b | Ruby | bcmdarroch/Calculator | /calculator.rb | UTF-8 | 3,605 | 4.65625 | 5 | [] | no_license | # Build a calculator command line interface (CLI) that allows a user to perform simple arithmetic.
# defines addition, subtraction, multiplication, division,
# exponent, and modulo methods
def add(a, b)
return a + b
end
def subtract(a, b)
return a - b
end
def multiply(a, b)
return a * b
end
# error when dividing by 0
def divide(a, b)
if b != 0
return a / b
else
puts "You can't divide by 0!"
return "impossible"
end
end
# Add support for computing exponents (2^4 = 2 * 2 * 2 * 2 = 16).
def power(a, b)
return a**b
end
# Add support for the modulo operator (10 % 3 = 1).
def mod(a, b)
return a % b
end
operators = ["add", "addition", "plus", "+", "subtract", "subtraction",
"minus", "-", "multiply", "multiplication", "times", "*", "x", "divide",
"division", "divided by", "divide by", "/", "exponent",
"**", "power", "modulo", "mod", "%"]
# asks the user for an operation (string or numeric symbol) and two numbers
# Gracefully handle unexpected user input:
# this section is repetitive - Brenna
print "HEY YOU! Yeah, you. What kind of math operation is your jam right now? "
operator = gets.chomp
while operators.include?(operator) == false
print "Nah, try again with an math operator this time: "
operator = gets.chomp
end
print "Algebraic! What's the first number? "
first_num = gets.chomp
while first_num.to_i.to_s != first_num
print "Nah, try again with a number this time: "
first_num = gets.chomp
end
print "Radical! What's the second number? "
second_num = gets.chomp
while second_num.to_i.to_s != second_num
print "Nah, try again with a number this time: "
second_num = gets.chomp
end
first_num = first_num.to_i
second_num = second_num.to_i
# tried to differentiate between floats and integers
# didn't work since I test for numbers with .to_i above
# if first_num % 1 != 0
# first_num = first_num.to_f
# else
# first_num = first_num.to_i
# end
#
# if second_num % 1 != 0
# second_num = second_num.to_f
# else
# second_num = second_num.to_i
# end
# Print out the formula in addition to the result, i.e. 2 + 2 = 4
puts "Mathematical! Here's the answer: "
case operator
when "add", "addition", "plus", "+"
puts "#{first_num} + #{second_num} = #{add(first_num, second_num)}"
when "subtract", "subtraction", "minus", "-"
puts "#{first_num} - #{second_num} = #{subtract(first_num, second_num)}"
when "multiply", "multiplication", "times", "*"
puts "#{first_num} * #{second_num} = #{multiply(first_num, second_num)}"
when"x", "divide", "division", "divided by", "divide by", "/"
puts "#{first_num} / #{second_num} = #{divide(first_num, second_num)}"
when "exponent", "**", "power"
puts "#{first_num}^#{second_num} = #{power(first_num, second_num)}"
when "modulo", "mod", "%"
puts "#{first_num} % #{second_num} = #{mod(first_num, second_num)}"
# test that all cases are working
else
puts "Woopsie!"
end
# Tested & Verified
# adds numbers with both add and +
# subtracts numbers with both subtract and -
# adds numbers with both multiply and *
# adds numbers with both divide and /
# handles divide when attempting to divide by zero.
# handles erroneous input. For example the user might enter clown when asked to enter a number.
# needs to handle erroneous operators.
# Optional Enhancements - not completed
# What happens if the user input is nil (i.e., the user just pressed enter)?
# What happens if the user tries to add hotdog to elephant?
# Make your program know when it needs to return an integer versus a float.
# Add support for parentheticals, i.e. 10 / (5 + 5) = 1.
| true |
10bf6f2093523baadf9793289a03af89a4d01ab8 | Ruby | RobertRodes/ruby-exercises | /exercises/ex_9.rb | UTF-8 | 86 | 2.65625 | 3 | [] | no_license | h = {a:1, b:2, c:3, d:4}
puts h[:b]
h.store(:e, 5)
h.reject! {|k,v| v < 3.5}
puts h
| true |
fa622bcce46a6d547b89927ec8d16bf7a9d8567a | Ruby | learn-co-students/sfo-web-120919 | /05-ruby-oo-review/tools/console.rb | UTF-8 | 806 | 2.546875 | 3 | [] | no_license | require_relative '../config/environment.rb'
def reload
load 'config/environment.rb'
end
student1 = Student.new("Bob", "Saget")
student2 = Student.new("Coffee", "Dad")
student3 = Student.new("David", "Rosenholz")
classroom1 = Classroom.new("Fox")
classroom2 = Classroom.new("Borg")
classroom3 = Classroom.new("Lovelace")
lecture1 = Lecture.new(student1, classroom2, "Ruby OO Review")
lecture2 = Lecture.new(student2, classroom2, "Intro to JavaScript")
lecture3 = Lecture.new(student3, classroom3, "Ruby OO Relationships")
lecture4 = Lecture.new(student1, classroom1, "Ruby OO Review")
lecture5 = Lecture.new(student3, classroom2, "Intro to JavaScript")
lecture6 = Lecture.new(student3, classroom1, "Ruby OO Relationships")
# Student.find_by_full_name("Bob Saget")
# Do not edit below pry
binding.pry
0
| true |
458ff1a7bb5b3249d01a6bb4912bc5a8efc6ceaa | Ruby | BrianDeWitt/LearnToProgram2ndEd | /Chapter06/chap06_02.rb | UTF-8 | 120 | 2.875 | 3 | [] | no_license | puts 'WHAT DO YOU WANT?!'
whatIWant = gets.chomp
puts 'WHADDAYA MEAN " ' + whatIWant.upcase + '"?!? YOU\'RE FIRED!!'
| true |
2d69414d34dd0129b5a2265bdd10a0de27d034e3 | Ruby | kenharsch/ourvapes | /app/models/my_config.rb | UTF-8 | 783 | 3.046875 | 3 | [] | no_license | class MyConfig
def initialize
@parts = {}
end
# type:: Product::TYPE_... or prod.type on a Product object
def remove(type)
@parts.delete(type)
end
# type:: Product::TYPE_... or prod.type on a Product object
def part(type)
return @parts[type]
end
def add_by_id(id)
prod = Product.find(id)
@parts[prod.type] = prod
end
def size
return @parts.size
end
# use with a block expecting the two variables _type_ and _part_
# type:: Product::TYPE_... or prod.type on a Product object
# part:: a Product object
def each_slot
Kit::PART_TYPES.each {|type| yield(type, @parts[type])}
end
# returns an array of IDs representing the contained parts
def ids
result = []
@parts.values.each {|prod| result << prod.id unless prod.nil?}
return result
end
end | true |
c3eea3bbc3d2badb135f901b2be25f9bdcbebd70 | Ruby | koheiyamada/jenkins_test | /spec/models/grade_spec.rb | UTF-8 | 540 | 2.609375 | 3 | [] | no_license | # coding: utf-8
require 'spec_helper'
describe Grade do
it "16個ある" do
Grade.all.should have(16).items
end
describe '通常の学年一式' do
it "14個ある" do
Grade.normal.should have(14).items
end
end
describe '学年が上がる' do
it '小学3年生から浪人生まで順繰りでつながっている' do
%w(es3 es4 es5 es6 jh1 jh2 jh3 hs1 hs2 hs3 prep).each_cons(2) do |g1, g2|
Grade.find_by_code(g1).next_grade.should == Grade.find_by_code(g2)
end
end
end
end
| true |
77f441ae783af650a634ff36bf068792de759e55 | Ruby | DDKatch/dip | /app/controllers/homeworks_controller.rb | UTF-8 | 1,616 | 2.640625 | 3 | [] | no_license | class HomeworksController < ApplicationController
def index
init_variables
symb = case params[:operation]
when "and" then :and
when "or" then :or
when "xor" then :xor
when "not" then :not
when "+" then :-
when "-" then :+
when "*" then :*
when "/" then :/
else symb = :and
end
!symb.nil? && use_operation(symb)
end
def use_operation(operation)
case operation
when :slice then
when :add_p || :mult_p then
@images[1] = @images[4]
when :mask then
@images[1] = ChunkyPNG::Image.new_mask(@images[0])
when :-
@images[2] = @images[0].method(:+).call(@images[1]){|px| -1 * px}
when :/
@images[2] = @images[0].method(:*).call(@images[1]){|px| 1/px}
else
@images[1] = ChunkyPNG::Image.new_const(@images[0])
@images[2] = @images[0].method(operation).call(@images[1]){|px| px}
end
upload_images
end
def upload_images
@images.each_with_index do |img, ind|
Cloudinary::Uploader.upload(img.to_data_url,
:public_id => @image_name[ind].sub('.png', ''))
end
end
def init_charts
Array.new(3) {|ind| @images[ind].histogram(:bright)}
end
def init_images
images = Array.new(5)
@image_name.each_with_index do |name, i|
image_url = Cloudinary::Utils.cloudinary_url(name)
images[i] = ChunkyPNG::Image.from_blob(open(image_url).read)
end
return images
end
def init_variables
@image_name = %w{house.png const.png result.png mask.png other.png}
@images = init_images
@charts = init_charts
end
end
| true |
951106f4554354abc76352e4c0ea28887c78df31 | Ruby | emilwall/gitflow-repo-report | /tests/test_report_generator.rb | UTF-8 | 730 | 2.53125 | 3 | [] | no_license | require_relative '../report_generator.rb'
require_relative 'test_helper.rb'
class TestReportGenerator < Test::Unit::TestCase
def setup
tmp_repo_path = setup_tmp_repo_dir
@report_generator = ReportGenerator.new File.join(tmp_repo_path, 'test_repos')
end
def teardown
remove_tmp_repo_dir
end
def test_get_repos
repos = @report_generator.get_repos
assert_equal('test-repo-1', repos[0])
assert_equal('test-repo-2', repos[1])
assert_equal(2, repos.count)
end
def test_get_branch_names
branch_names = @report_generator.get_branch_names
assert_equal('test-repo-1 develop', branch_names[0])
assert_equal('test-repo-2 release/second-release', branch_names[6])
assert_equal(7, branch_names.count)
end
end | true |
a3be69c1f83816170f2d795236beecf78dbe143b | Ruby | SophiaLWu/chess | /spec/pawn_spec.rb | UTF-8 | 2,467 | 2.921875 | 3 | [
"MIT"
] | permissive | require "spec_helper"
module Chess
describe Pawn do
describe "#possible_moves" do
describe "when the white pawn is at location [1,1] and has not moved" do
let(:pawn) { Pawn.new("white", [1,1]) }
it "returns [[2,1],[3,1],[2,0],[2,2]]" do
expect(pawn.possible_moves).to eql([[2,1],[3,1],[2,0],[2,2]])
end
end
describe "when the white pawn is at location [2,1] and has moved" do
let(:pawn) { Pawn.new("white", [2,1]) }
it "returns [[3,1],[3,0],[3,2]]" do
pawn.instance_variable_set(:@moved, true)
expect(pawn.possible_moves).to eql([[3,1],[3,0],[3,2]])
end
end
describe "when the white pawn is at location [3,0] and has moved" do
let(:pawn) { Pawn.new("white", [3,0]) }
it "returns [[4,0],[4,1]]" do
pawn.instance_variable_set(:@moved, true)
expect(pawn.possible_moves).to eql([[4,0],[4,1]])
end
end
describe "when the white pawn is at location [4,7] and has moved" do
let(:pawn) { Pawn.new("white", [4,7]) }
it "returns [[5,7],[5,6]]" do
pawn.instance_variable_set(:@moved, true)
expect(pawn.possible_moves).to eql([[5,7],[5,6]])
end
end
describe "when the black pawn is at location [6,6] and has not moved" do
let(:pawn) { Pawn.new("black", [6,6]) }
it "returns [[5,6],[4,6],[5,7],[5,5]]" do
expect(pawn.possible_moves).to eql([[5,6],[4,6],[5,7],[5,5]])
end
end
describe "when the black pawn is at location [5,6] and has moved" do
let(:pawn) { Pawn.new("black", [5,6]) }
it "returns [[4,6],[4,7],[4,5]]" do
pawn.instance_variable_set(:@moved, true)
expect(pawn.possible_moves).to eql([[4,6],[4,7],[4,5]])
end
end
describe "when the black pawn is at location [4,7] and has moved" do
let(:pawn) { Pawn.new("black", [4,7]) }
it "returns [[3,7],[3,6]]" do
pawn.instance_variable_set(:@moved, true)
expect(pawn.possible_moves).to eql([[3,7],[3,6]])
end
end
describe "when the black pawn is at location [3,0] and has moved" do
let(:pawn) { Pawn.new("black", [3,0]) }
it "returns [[2,0],[2,1]]" do
pawn.instance_variable_set(:@moved, true)
expect(pawn.possible_moves).to eql([[2,0],[2,1]])
end
end
end
end
end | true |
16fa569504778601dff7542b15c318c98b310b74 | Ruby | bookinstock/the_robot | /spec/analyser_spec.rb | UTF-8 | 33,272 | 2.71875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'byebug'
require_relative 'spec_helper'
require_relative '../src/models/kline'
require_relative '../src/robots/analyser'
RSpec.describe 'analyser' do
describe 'strategy 1' do
describe 'only one kline' do
it 'one up' do
raw_klines = [
{
'open' => 1,
'close' => 2
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'one down' do
raw_klines = [
{
'open' => 2,
'close' => 1
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
expect(results).to eq []
end
end
describe 'two klines' do
it 'two perfect up' do
raw_klines = [
{
'open' => 1,
'close' => 2
},
{
'open' => 2,
'close' => 3
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'two perfect down' do
raw_klines = [
{
'open' => 3,
'close' => 2
},
{
'open' => 2,
'close' => 1
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'two overlap up' do
raw_klines = [
{
'open' => 1,
'close' => 3
},
{
'open' => 2,
'close' => 4
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'two overlap down' do
raw_klines = [
{
'open' => 4,
'close' => 2
},
{
'open' => 3,
'close' => 1
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'one big up and one little down' do
raw_klines = [
{
'open' => 1,
'close' => 3
},
{
'open' => 3,
'close' => 2
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'one big down and one little up' do
raw_klines = [
{
'open' => 4,
'close' => 2
},
{
'open' => 2,
'close' => 3
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'one up and one down' do
raw_klines = [
{
'open' => 1,
'close' => 3
},
{
'open' => 3,
'close' => 1
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
r1 = results.first
expect(results.size).to eq 1
expect(r1.kline.idx).to eq 1
expect(r1.action).to eq :sell
end
it 'one down and one up' do
raw_klines = [
{
'open' => 3,
'close' => 1
},
{
'open' => 1,
'close' => 3
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
r1 = results.first
expect(results.size).to eq 1
expect(r1.kline.idx).to eq 1
expect(r1.action).to eq :buy
end
it 'one little up and one big down' do
raw_klines = [
{
'open' => 2,
'close' => 3
},
{
'open' => 3,
'close' => 1
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
r1 = results.first
expect(results.size).to eq 1
expect(r1.kline.idx).to eq 1
expect(r1.action).to eq :sell
end
it 'one little down and one big up' do
raw_klines = [
{
'open' => 2,
'close' => 1
},
{
'open' => 1,
'close' => 3
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
r1 = results.first
expect(results.size).to eq 1
expect(r1.kline.idx).to eq 1
expect(r1.action).to eq :buy
end
end
describe 'more' do
it 'up up up up' do
raw_klines = [
{
'open' => 1,
'close' => 2
},
{
'open' => 2,
'close' => 4
},
{
'open' => 3,
'close' => 4
},
{
'open' => 4,
'close' => 5
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'down down down down' do
raw_klines = [
{
'open' => 5,
'close' => 4
},
{
'open' => 4,
'close' => 3
},
{
'open' => 3,
'close' => 3
},
{
'open' => 3,
'close' => 1
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'little down in ups' do
raw_klines = [
{
'open' => 1,
'close' => 2
},
{
'open' => 2,
'close' => 4
},
{
'open' => 4,
'close' => 3
},
{
'open' => 3,
'close' => 5
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'little up in downs' do
raw_klines = [
{
'open' => 5,
'close' => 3
},
{
'open' => 3,
'close' => 4
},
{
'open' => 4,
'close' => 3
},
{
'open' => 3,
'close' => 2
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'two little downs in ups' do
raw_klines = [
{
'open' => 1,
'close' => 5
},
{
'open' => 5,
'close' => 4
},
{
'open' => 4,
'close' => 3
},
{
'open' => 3,
'close' => 6
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'two little ups in downs' do
raw_klines = [
{
'open' => 6,
'close' => 3
},
{
'open' => 3,
'close' => 4
},
{
'open' => 4,
'close' => 5
},
{
'open' => 5,
'close' => 2
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'two downs in ups' do
raw_klines = [
{
'open' => 2,
'close' => 5
},
{
'open' => 5,
'close' => 4
},
{
'open' => 4,
'close' => 2
},
{
'open' => 2,
'close' => 3
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
r1 = results.first
expect(results.size).to eq 1
expect(r1.kline.idx).to eq 2
expect(r1.action).to eq :sell
end
it 'two ups in downs' do
raw_klines = [
{
'open' => 6,
'close' => 3
},
{
'open' => 3,
'close' => 4
},
{
'open' => 4,
'close' => 6
},
{
'open' => 6,
'close' => 5
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
r1 = results.first
expect(results.size).to eq 1
expect(r1.kline.idx).to eq 2
expect(r1.action).to eq :buy
end
it 'two big downs in ups' do
raw_klines = [
{
'open' => 2,
'close' => 5
},
{
'open' => 5,
'close' => 4
},
{
'open' => 4,
'close' => 1
},
{
'open' => 1,
'close' => 3
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
r1 = results.first
expect(results.size).to eq 1
expect(r1.kline.idx).to eq 2
expect(r1.action).to eq :sell
end
it 'two big ups in downs' do
raw_klines = [
{
'open' => 6,
'close' => 3
},
{
'open' => 3,
'close' => 4
},
{
'open' => 4,
'close' => 7
},
{
'open' => 7,
'close' => 5
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
r1 = results.first
expect(results.size).to eq 1
expect(r1.kline.idx).to eq 2
expect(r1.action).to eq :buy
end
it 'up down up down' do
raw_klines = [
{
'open' => 3,
'close' => 5
},
{
'open' => 5,
'close' => 2
},
{
'open' => 2,
'close' => 6
},
{
'open' => 6,
'close' => 1
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
r1, r2, r3 = results
expect(results.size).to eq 3
expect(r1.kline.idx).to eq 1
expect(r1.action).to eq :sell
expect(r2.kline.idx).to eq 2
expect(r2.action).to eq :buy
expect(r3.kline.idx).to eq 3
expect(r3.action).to eq :sell
end
it 'down up down up' do
raw_klines = [
{
'open' => 5,
'close' => 4
},
{
'open' => 4,
'close' => 6
},
{
'open' => 6,
'close' => 2
},
{
'open' => 2,
'close' => 10
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy1.new(klines)
results = analyser.execute
r1, r2, r3 = results
expect(results.size).to eq 3
expect(r1.kline.idx).to eq 1
expect(r1.action).to eq :buy
expect(r2.kline.idx).to eq 2
expect(r2.action).to eq :sell
expect(r3.kline.idx).to eq 3
expect(r3.action).to eq :buy
end
end
end
describe 'strategy 2' do
describe 'only one kline' do
it 'one up' do
raw_klines = [
{
'open' => 1,
'close' => 2
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'one down' do
raw_klines = [
{
'open' => 2,
'close' => 1
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
expect(results).to eq []
end
end
describe 'two' do
it 'up up' do
raw_klines = [
{
'open' => 1,
'close' => 2
},
{
'open' => 2,
'close' => 3
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'down down' do
raw_klines = [
{
'open' => 3,
'close' => 2
},
{
'open' => 2,
'close' => 1
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'up down' do
raw_klines = [
{
'open' => 2,
'close' => 3
},
{
'open' => 3,
'close' => 1
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'down up' do
raw_klines = [
{
'open' => 3,
'close' => 2
},
{
'open' => 2,
'close' => 4
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
expect(results).to eq []
end
end
describe 'three' do
it 'up down up' do
raw_klines = [
{
'open' => 2,
'close' => 3
},
{
'open' => 3,
'close' => 1
},
{
'open' => 1,
'close' => 2
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'down up down' do
raw_klines = [
{
'open' => 3,
'close' => 2
},
{
'open' => 2,
'close' => 4
},
{
'open' => 4,
'close' => 3
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
expect(results).to eq []
end
end
describe 'more' do
it 'up down up down' do
raw_klines = [
{
'open' => 2,
'close' => 3
},
{
'open' => 3,
'close' => 1
},
{
'open' => 1,
'close' => 2
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'down up down up' do
raw_klines = [
{
'open' => 3,
'close' => 2
},
{
'open' => 2,
'close' => 4
},
{
'open' => 4,
'close' => 3
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'up trend -> up down up down up' do
raw_klines = [
{
'open' => 1,
'close' => 3
},
{
'open' => 3,
'close' => 2
},
{
'open' => 2,
'close' => 4
},
{
'open' => 4,
'close' => 3
},
{
'open' => 3,
'close' => 5
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'down trend -> up down up down up (not break)' do
raw_klines = [
{
'open' => 6,
'close' => 7
},
{
'open' => 7,
'close' => 5
},
{
'open' => 5,
'close' => 6
},
{
'open' => 6,
'close' => 1
},
{
'open' => 1,
'close' => 2
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'down trend -> up down up down up (break)' do
raw_klines = [
{
'open' => 6,
'close' => 7
},
{
'open' => 7,
'close' => 5
},
{
'open' => 5,
'close' => 6
},
{
'open' => 6,
'close' => 3
},
{
'open' => 3,
'close' => 6
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
r1 = results.first
expect(results.size).to eq 1
expect(r1.action).to eq :buy
expect(r1.kline.idx).to eq 4
end
it 'down trend -> up down up (higher) down up (break)' do
raw_klines = [
{
'open' => 6,
'close' => 7
},
{
'open' => 7,
'close' => 5
},
{
'open' => 5,
'close' => 6
},
{
'open' => 6,
'close' => 3
},
{
'open' => 3,
'close' => 10
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
r1 = results.first
expect(results.size).to eq 1
expect(r1.action).to eq :buy
expect(r1.kline.idx).to eq 4
end
it 'down trend -> down up down up down' do
raw_klines = [
{
'open' => 6,
'close' => 4
},
{
'open' => 4,
'close' => 5
},
{
'open' => 5,
'close' => 3
},
{
'open' => 3,
'close' => 4
},
{
'open' => 4,
'close' => 1
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'up trend -> down up down up down (not break)' do
raw_klines = [
{
'open' => 2,
'close' => 1
},
{
'open' => 1,
'close' => 3
},
{
'open' => 3,
'close' => 2
},
{
'open' => 2,
'close' => 4
},
{
'open' => 4,
'close' => 3
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'up trend -> down up down up down (break)' do
raw_klines = [
{
'open' => 3,
'close' => 2
},
{
'open' => 2,
'close' => 4
},
{
'open' => 4,
'close' => 3
},
{
'open' => 3,
'close' => 5
},
{
'open' => 5,
'close' => 3
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
r1 = results.first
expect(results.size).to eq 1
expect(r1.action).to eq :sell
expect(r1.kline.idx).to eq 4
end
it 'down trend -> up down up (higher) down up (break)' do
raw_klines = [
{
'open' => 3,
'close' => 2
},
{
'open' => 2,
'close' => 4
},
{
'open' => 4,
'close' => 3
},
{
'open' => 3,
'close' => 5
},
{
'open' => 5,
'close' => 1
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
r1 = results.first
expect(results.size).to eq 1
expect(r1.action).to eq :sell
expect(r1.kline.idx).to eq 4
end
it 'complex' do
raw_klines = [
{
'open' => 7,
'close' => 8
},
{
'open' => 8,
'close' => 6
},
{
'open' => 6,
'close' => 7
},
{
'open' => 7,
'close' => 4
},
{
'open' => 4,
'close' => 5
},
{
'open' => 5,
'close' => 1
},
{
'open' => 1,
'close' => 5
},
{
'open' => 5,
'close' => 4
},
{
'open' => 4,
'close' => 3
},
{
'open' => 3,
'close' => 7
},
{
'open' => 7,
'close' => 2
},
{
'open' => 2,
'close' => 3
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy2.new(klines)
results = analyser.execute
r1, r2, r3 = results
expect(results.size).to eq 3
expect(r1.action).to eq :buy
expect(r1.kline.idx).to eq 6
expect(r2.action).to eq :buy
expect(r2.kline.idx).to eq 9
expect(r3.action).to eq :sell
expect(r3.kline.idx).to eq 10
end
end
end
describe 'strategy 3' do
describe 'only one kline' do
it 'one up' do
raw_klines = [
{
'open' => 1,
'close' => 2
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy3.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'one down' do
raw_klines = [
{
'open' => 2,
'close' => 1
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy3.new(klines)
results = analyser.execute
expect(results).to eq []
end
end
describe 'two' do
it 'up up' do
raw_klines = [
{
'open' => 1,
'close' => 2
},
{
'open' => 2,
'close' => 3
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy3.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'down down' do
raw_klines = [
{
'open' => 3,
'close' => 2
},
{
'open' => 2,
'close' => 1
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy3.new(klines)
results = analyser.execute
expect(results).to eq []
end
end
describe 'three' do
it 'up up up' do
raw_klines = [
{
'open' => 1,
'close' => 2
},
{
'open' => 2,
'close' => 3
},
{
'open' => 3,
'close' => 4
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy3.new(klines)
results = analyser.execute
expect(results).to eq []
end
it 'down down down' do
raw_klines = [
{
'open' => 3,
'close' => 2
},
{
'open' => 2,
'close' => 1
},
{
'open' => 1,
'close' => 0.1
}
]
klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
analyser = Robots::Analyser::Strategy3.new(klines)
results = analyser.execute
expect(results).to eq []
end
end
end
# describe 'strategy 4' do
# describe 'only one kline' do
# it 'one up' do
# raw_klines = [
# {
# 'open' => 1,
# 'close' => 2
# }
# ]
# klines = Models::KlinesBuilder.new(raw_klines).execute(reverse: false)
# analyser = Robots::Analyser::Strategy4.new(klines)
# results = analyser.execute
# expect(results).to eq []
# end
# end
# end
# context 'klines' do
# before(:example) do
# data = [{ 'amount' => 619.3034099946908,
# 'open' => 5363.03,
# 'close' => 5324.98,
# 'high' => 5372.27,
# 'id' => 1_584_542_700,
# 'count' => 3662,
# 'low' => 5315.44,
# 'vol' => 3_310_011.24424278 },
# { 'amount' => 1746.621948323623,
# 'open' => 5330.88,
# 'close' => 5363.02,
# 'high' => 5375.0,
# 'id' => 1_584_541_800,
# 'count' => 10_310,
# 'low' => 5318.5,
# 'vol' => 9_337_528.878822388 },
# { 'amount' => 1601.6863071289633,
# 'open' => 5365.12,
# 'close' => 5330.88,
# 'high' => 5379.0,
# 'id' => 1_584_540_900,
# 'count' => 8700,
# 'low' => 5297.28,
# 'vol' => 8_543_547.848085703 },
# { 'amount' => 3424.892319579545,
# 'open' => 5338.64,
# 'close' => 5366.0,
# 'high' => 5385.0,
# 'id' => 1_584_540_000,
# 'count' => 18_016,
# 'low' => 5300.01,
# 'vol' => 18_322_816.65707355 },
# { 'amount' => 3998.7522974410435,
# 'open' => 5214.95,
# 'close' => 5337.34,
# 'high' => 5380.0,
# 'id' => 1_584_539_100,
# 'count' => 21_453,
# 'low' => 5192.98,
# 'vol' => 21_205_114.4895674 },
# { 'amount' => 7339.38324966166,
# 'open' => 5160.09,
# 'close' => 5214.78,
# 'high' => 5280.0,
# 'id' => 1_584_538_200,
# 'count' => 26_305,
# 'low' => 5100.0,
# 'vol' => 38_225_175.2884537 },
# { 'amount' => 3174.160273385421,
# 'open' => 5075.43,
# 'close' => 5160.09,
# 'high' => 5200.0,
# 'id' => 1_584_537_300,
# 'count' => 14_970,
# 'low' => 5010.0,
# 'vol' => 16_120_765.467146443 },
# { 'amount' => 628.5184817831317,
# 'open' => 5112.02,
# 'close' => 5075.58,
# 'high' => 5112.83,
# 'id' => 1_584_536_400,
# 'count' => 4520,
# 'low' => 5071.0,
# 'vol' => 3_198_780.836202033 },
# { 'amount' => 497.8182924480013,
# 'open' => 5125.97,
# 'close' => 5113.81,
# 'high' => 5129.45,
# 'id' => 1_584_535_500,
# 'count' => 4206,
# 'low' => 5096.32,
# 'vol' => 2_545_253.8235769444 },
# { 'amount' => 668.8171413545598,
# 'open' => 5101.15,
# 'close' => 5127.22,
# 'high' => 5140.22,
# 'id' => 1_584_534_600,
# 'count' => 5184,
# 'low' => 5090.01,
# 'vol' => 3_420_375.8741301564 }]
# @klines = Models::KlinesBuilder.new(data).execute(reverse: false)
# end
# it 'find trun_klines' do
# @analyser = Robots::Analyser::Kline.new(@klines)
# result = @analyser.execute
# expect(result.ready?).to eq true
# expect(result.turn_klines.map(&:close)).to eq [5127.22, 5113.81, 5160.09, 5330.88, 5363.02, 5324.98]
# expect(result.turn_down_klines.map(&:close)).to eq [5113.81, 5330.88, 5324.98]
# expect(result.turn_up_klines.map(&:close)).to eq [5127.22, 5160.09, 5363.02]
# end
# it 'down trend line' do
# @analyser = Robots::Analyser::Kline.new(@klines)
# result = @analyser.execute
# @analyser.show_open_prices
# trend_line = Robots::Analyser::TrendLine.new(result)
# puts '---go down---'
# down_stack = trend_line.go_down
# puts '---go up---'
# up_stack = trend_line.go_up
# puts '---down stack---'
# down_stack.each { |k| puts k.open }
# puts '---up stack---'
# up_stack.each { |k| puts k.open }
# expect(true).to eq true
# end
# end
end
| true |
5e5133dac42c8a32fb95da4c4b9210b089047cc0 | Ruby | evavro/Jagmeister | /RubyCodeExamples/Blocks2.rb | UTF-8 | 396 | 4.34375 | 4 | [] | no_license | #
# Author: Jag Nandigam
#
# More on blocks in Ruby
#
class Test
def sum
x = 0
for i in 1..10
x += yield i
end
x
end
end
def main
t = Test.new()
y = t.sum { |i| i * i }
puts y
y = t.sum { |i| i % 2 } # % is remainder operator
puts y
y = t.sum { |i| i.next } # i.next returns i + 1
puts y
end
# call main
main() | true |
3ddc41e8857e41e948ae232a0d396367ca46a0d5 | Ruby | MarhicJeromeGIT/DancingLinks | /spec/cover_solver_spec.rb | UTF-8 | 2,168 | 2.9375 | 3 | [] | no_license | require "cover_solver"
require "byebug"
RSpec.describe CoverSolver do
subject { described_class.new(matrix) }
describe "#call" do
context "empty matrix" do
let(:matrix) do
[]
end
it "raises an error" do
expect { subject.call }.to raise_error(CoverSolver::InvalidMatrixSize)
end
end
context "when there is a solution" do
context "simple matrix" do
let(:matrix) do
[
[0, 1],
[1, 0]
]
end
it "finds the solution" do
solutions = subject.call
expect(solutions.count).to eq 1
expect(solutions.first).to eq(
[
[1, 0],
[0, 1]
]
)
end
end
context "complex matrix" do
let(:matrix) do
[
[0, 0, 1, 0, 1, 1, 0],
[1, 0, 0, 1, 0, 0, 1],
[0, 1, 1, 0, 0, 1, 0],
[1, 0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 1],
[0, 0, 0, 1, 1, 0, 1]
]
end
it "finds the only solution" do
solutions = subject.call
expect(solutions.count).to eq 1
expect(solutions.first).to eq(
[
[1, 0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 1],
[0, 0, 1, 0, 1, 1, 0]
]
)
end
end
end
context "when there are several solutions" do
let(:matrix) do
[
[1, 1],
[0, 1],
[1, 0]
]
end
it "enumerates all the solutions" do
solutions = subject.call
expect(solutions.to_a).to eq(
[
[[1, 1]],
[[1, 0], [0, 1]]
]
)
end
end
context "when there is no solution" do
context "simple matrix" do
let(:matrix) do
[
[0, 0],
[1, 0]
]
end
it "doesn't find any solution" do
solutions = subject.call
expect(solutions.count).to eq 0
expect(solutions.first).to be nil
end
end
end
end
end
| true |
e41b1212ab36873f2b03e9971fa00db7956033b9 | Ruby | CodeGreer/Ruby_Challenges | /fizzbuzz.rb | UTF-8 | 265 | 3.71875 | 4 | [] | no_license | fizzbuzz = (1..100).to_a
fizzbuzz.each do |number|
if number % 3 == 0 && number % 5 == 0
puts "fizzbuzz"
elsif
number % 5 == 0
puts "buzz"
elsif
number % 3 == 0
puts "fizz"
elsif
puts number
end
end | true |
cd189223f6d9116aa92e4569721e0337fbc22c73 | Ruby | MondayHealth/scraper | /app/jobs/scrapers/base.rb | UTF-8 | 1,087 | 2.546875 | 3 | [] | no_license | require 'nokogiri'
require 'csv'
require_relative '../concerns/logged_job'
module Jobs
module Scrapers
class MissingSourceError < Exception; end
class Base
extend Jobs::Concerns::LoggedJob
def self.initialize_csv(path, csv_fields)
unless File.exists?(path)
CSV.open(path, 'w+') do |csv|
csv << csv_fields
end
end
end
def self.page_source_for_key(key)
ssdb = SSDB.new url: "ssdb://#{ENV['SSDB_HOST']}:#{ENV['SSDB_PORT']}"
unless ssdb.exists(key)
raise MissingUpstreamDataError.new("No data upstream at SSDB server #{ENV['SSDB_HOST']} for key: #{key}")
end
ssdb.get(key)
end
def self.valid_license_type?(license_type)
@license_type_blacklist ||= open("config/license_type_blacklist.txt").read.split("\n").map(&:strip)
return !@license_type_blacklist.include?(license_type.to_s)
end
def self.strip_with_nbsp string
return nil if string.nil?
string.gsub(" ", " ").strip
end
end
end
end | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.