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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8c2bac7f28930bd78094233dd3135a053b904bfb | Ruby | railis/challenge | /puzzles/string_equation_evaluator/spec.rb | UTF-8 | 1,450 | 3.109375 | 3 | [] | no_license | Challenge::Spec.new do
context "when expression is invalid" do
context "when it includes invalid characters" do
let(:exp) { "1 + 2a" }
it "raises error" do
expect { @solution_class.new(exp).calculate }.to raise_error("Invalid character 'a'")
end
end
context "when there are not closed parentheses" do
let(:exp) { "((1 + 2 + 3) + 1" }
it "raises error" do
expect { @solution_class.new(exp).calculate }.to raise_error("Unmatched '('")
end
end
context "when parentheses are closed more than once" do
let(:exp) { "((1 + 2) + 1) + 4)" }
it "raises error" do
expect { @solution_class.new(exp).calculate }.to raise_error("Unmatched ')'")
end
end
end
context "when expression is valid" do
context "allows negative" do
let (:exp) { "(-2) + 1" }
it "returns calculated value" do
expect(@solution_class.new(exp).calculate).to eq(-1)
end
end
context "handles basic ordering" do
it "returns calculated value based on attributes order" do
expect(@solution_class.new("2+2*2").calculate).to eq(6)
expect(@solution_class.new("10-4/2").calculate).to eq(8)
end
it "returns calculated value based on parentheses" do
expect(@solution_class.new("(2+2)*2").calculate).to eq(8)
expect(@solution_class.new("(10-4)/2").calculate).to eq(3)
end
end
end
end
| true |
2fe8dde7139ee38543a4e962b9de251b80b17b10 | Ruby | ecksma/wdi-darth-vader | /04_ruby/d01/Myron_Johnson/test.rb | UTF-8 | 84 | 3.78125 | 4 | [] | no_license | # puts stands for put string
name = 'Myron'
puts 'hello, world!' ' from, ' + name
| true |
007d8ae1ca4537a009e1300d5e9f9a32f5aec4e0 | Ruby | gabrielpelo/work-time-calculations | /tests.rb | UTF-8 | 847 | 3.359375 | 3 | [] | no_license | require_relative 'instant'
a = Instant.new("1012")
b = Instant.new("2021")
w = Instant.new("948")
puts a
puts a + 30
puts a + w
puts "\n"
puts b
puts b - 30
puts b - w
puts "\n"
puts a.to_i
puts a
puts "\n"
puts b.to_i
puts b
puts "\n"
times = %w{ 10:12 935 8:30 7.50 0637 1130 11.15 0 24 23:59 }
same_times = %w{ 09:35 09.35 9:35 9.35 935 0935 9 }
(times + same_times).map { |t| Instant.new(t) }.each do |t|
puts "time: #{t} time_in_min: #{t.to_i}"
end
puts "\n"
a = Instant.new("2033")
b = Instant.new("2034")
c = Instant.new("2033")
d = Instant.new("2133")
x = %w{ 2033 2034 2033 2133}
x.map! { |t| Instant.new(t) }
puts x
puts "\n"
puts x.map { |t| t.to_i }
puts "\n"
(2..x.length).each do |i|
a = x[i-2]
b = x[i-1]
c = b - a
puts "#{b} - #{a} = #{c}"
puts "#{b.to_i} - #{a.to_i} = #{c.to_i}"
puts "\n"
end
| true |
5d9642fdc1129e8836730f7ce6cb162f3cebaa6f | Ruby | trishgarrett/square_array-v-000 | /square_array.rb | UTF-8 | 292 | 3.578125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def square_array(array)
# this method should return 'an' array that has the numbers squared
variable = []
array.each do|i|
# how can we store this value? And what do we use to store multiple values?
variable << i**2
end
# modified array will be returned here
variable
end
| true |
1f202fbc72c62ec294de7732b84b39cba0565588 | Ruby | jeroenvandijk/nokogiri_jquery | /vendor/plugins/steam/lib/steam/matchers/html_unit.rb | UTF-8 | 1,586 | 2.84375 | 3 | [
"MIT"
] | permissive | module Steam
module Matchers
module HtmlUnit
class HasContent #:nodoc:
def initialize(content)
@content = content
end
def matches?(target)
@target = target
!!@target.locate_element(@content)
end
def failure_message
"expected the following element's content to #{content_message}:\n#{squeeze_space(@target.page.body)}"
end
def negative_failure_message
"expected the following element's content to not #{content_message}:\n#{squeeze_space(@target.page.body)}"
end
def squeeze_space(inner_text)
(inner_text || '').gsub(/^\s*$/, "").squeeze("\n")
end
def content_message
case @content
when String
"include \"#{@content}\""
when Regexp
"match #{@content.inspect}"
end
end
end
# Matches the contents of an HTML document with
# whatever string is supplied
def contain(content)
HasContent.new(content)
end
# Asserts that the body of the response contain
# the supplied string or regexp
def assert_contain(content)
hc = HasContent.new(content)
assert hc.matches?(response_body), hc.failure_message
end
# Asserts that the body of the response
# does not contain the supplied string or regepx
def assert_not_contain(content)
hc = HasContent.new(content)
assert !hc.matches?(response_body), hc.negative_failure_message
end
end
end
end | true |
d7d31337667bbdd185510e1f946085662b3157d8 | Ruby | gvoicu/pag_seguro | /spec/pag_seguro/shipping_spec.rb | UTF-8 | 1,668 | 2.65625 | 3 | [] | no_license | # encoding: utf-8
require "spec_helper"
valid_attributes = {
type: PagSeguro::Shipping::SEDEX,
state: "SP",
city: "São Paulo",
postal_code: "05363000",
district: "Jd. PoliPoli",
street: "Av. Otacilio Tomanik",
number: "775",
complement: "apto. 92"
}
describe PagSeguro::Shipping do
context "instance" do
before { @shipping = PagSeguro::Shipping.new }
it { @shipping.should have_attribute_accessor(:type) }
it { @shipping.should have_attribute_accessor(:state) }
it { @shipping.should have_attribute_accessor(:city) }
it { @shipping.should have_attribute_accessor(:postal_code) }
it { @shipping.should have_attribute_accessor(:district) }
it { @shipping.should have_attribute_accessor(:street) }
it { @shipping.should have_attribute_accessor(:number) }
it { @shipping.should have_attribute_accessor(:complement) }
describe "types" do
it "should be pac if type is 1" do
@shipping.stub( :type ){ 1 }
@shipping.should be_pac
end
it "should be sedex if type is 2" do
@shipping.stub( :type ){ 2 }
@shipping.should be_sedex
end
it "should be unidentified if type is 3" do
@shipping.stub( :type ){ 3 }
@shipping.should be_unidentified
end
end
end
it "should be able to initialize all attributes" do
PagSeguro::Shipping.new(valid_attributes).should be_valid
end
it "should not show postal code unless valid" do
PagSeguro::Shipping.new(valid_attributes).postal_code.should == "05363000"
PagSeguro::Shipping.new(valid_attributes.merge(postal_code: 1234567)).postal_code.should be_blank
end
end | true |
91a326a78f33517b34cf3a199e1256708569380a | Ruby | donwildman/rover | /app/controllers/commands_controller.rb | UTF-8 | 2,037 | 2.8125 | 3 | [] | no_license | class CommandsController < ApplicationController
DIRECTIONS = 'NSEW'
COMMANDS = 'LRM'
def index
@X = 0
@Y = 0
@direction = 'N'
@commands = {
:x => @X,
:y => @Y,
:direction => @direction,
:error => nil
}
@rover_count = ENV['ROVER_COUNT'].to_i
end
def do_command(c)
if (c == 'L')
if (@direction == 'N')
change_direction('W')
elsif (@direction == 'W')
change_direction('S')
elsif (@direction == 'S')
change_direction('E')
elsif (@direction == 'E')
change_direction('N')
end
else
if (c == 'R')
if (@direction == 'N')
change_direction('E')
elsif (@direction == 'E')
change_direction('S')
elsif (@direction == 'S')
change_direction('W')
elsif (@direction == 'W')
change_direction('N')
end
elsif (c == 'M')
do_move
end
end
end
def do_move
if (@direction == 'N')
@Y = @Y + 1
elsif (@direction == 'E')
@X = @X + 1
elsif (@direction == 'S')
@Y = @Y - 1
elsif (@direction == 'W')
@X = @X - 1
end
end
def change_direction(d)
@direction = ( DIRECTIONS.index(d)) ? d : @direction
end
def parse_input(c)
multi = c.split(//)
multi.length.times do |i|
_c = multi[i]
if COMMANDS.index(_c)
do_command(_c)
end
end
end
def show
@rover_id = params[:rover_id].to_i
@X = params[:X].to_i
@Y = params[:Y].to_i
@direction = params[:direction]
cmd = params[:command]
unless cmd.nil?
parse_input(cmd)
end
if @X < 0 || @Y < 0
@commands = {:x => params[:X],:y => params[:Y],:direction => @direction, :error => "Out of bounds!"}
else
@commands = {:x => @X,:y => @Y,:direction => @direction, :error => nil}
end
end
end
| true |
607fdebe663ac4d38beefce74fb37b12f5bdbb4f | Ruby | sadiqmmm/mlist | /lib/mlist/email_post.rb | UTF-8 | 3,428 | 2.78125 | 3 | [
"MIT"
] | permissive | module MList
# The simplest post that can be made to an MList::MailList. Every instance
# must have at least the text content and a subject. Html may also be added.
#
# It is important to understand that this class is intended to be used by
# applications that have some kind of UI for creating a post. It assumes
# Rails form builder support is desired, and that there is no need for
# manipulating the final TMail::Mail object that will be delivered to the
# list outside of the methods provided herein.
#
class EmailPost
include MList::Util::EmailHelpers
ATTRIBUTE_NAMES = %w(copy_sender html text mailer subject subscriber)
ATTRIBUTE_NAMES.each do |attribute_name|
define_method(attribute_name) do
@attributes[attribute_name]
end
define_method("#{attribute_name}=") do |value|
@attributes[attribute_name] = value
end
end
attr_reader :parent_identifier, :reply_to_message
def initialize(attributes)
@attributes = {}
self.attributes = {
:mailer => 'MList Client Application'
}.merge(attributes)
end
def attributes
@attributes.dup
end
def attributes=(new_attributes)
return if new_attributes.nil?
attributes = new_attributes.dup
attributes.stringify_keys!
attributes.each do |attribute_name, value|
send("#{attribute_name}=", value)
end
end
def copy_sender=(value)
@attributes['copy_sender'] = %w(true 1).include?(value.to_s)
end
def reply_to_message=(message)
if message
@parent_identifier = message.identifier
else
@parent_identifier = nil
end
@reply_to_message = message
end
def subject
@attributes['subject'] || (reply_to_message ? "Re: #{reply_to_message.subject}" : nil)
end
def to_s
to_tmail.to_s
end
def to_tmail
raise ActiveRecord::RecordInvalid.new(self) unless valid?
builder = MList::Util::TMailBuilder.new(TMail::Mail.new)
builder.mime_version = "1.0"
builder.mailer = mailer
if parent_identifier
builder.in_reply_to = parent_identifier
builder.references = [bracket(parent_identifier)]
end
builder.from = subscriber_name_and_address(subscriber)
builder.subject = subject
if html
builder.add_text_part(text)
builder.add_html_part(html)
builder.set_content_type('multipart/alternative')
else
builder.body = text
builder.set_content_type('text/plain')
end
builder.tmail
end
# vvv ActiveRecord validations interface implementation vvv
def self.human_name(options = {})
self.name.humanize
end
def self.self_and_descendants_from_active_record #nodoc:
[self]
end
def self.human_attribute_name(attribute_key_name, options = {})
attribute_key_name.humanize
end
def errors
@errors ||= ActiveRecord::Errors.new(self)
end
def validate
errors.clear
errors.add(:subject, 'required') if subject.blank?
errors.add(:text, 'required') if text.blank?
errors.add(:text, 'needs to be a bit longer') if !text.blank? && text.strip.size < 25
errors.empty?
end
def valid?
validate
end
end
end | true |
915ef42972c6bea8f5501d045efde9a95a8bdf26 | Ruby | Sydneyc44/learn-co-sandbox | /mmpractice.rb | UTF-8 | 84 | 3.328125 | 3 | [] | no_license | def greeting(name)
puts "Hi, I'm #{name}"
end
greeting("Sydney")
greeting("Alex") | true |
8c9c4c9ce598e0a6e5ec426df031f9088689acd9 | Ruby | targess/ironhack-week-2 | /day4/sinatra-blog/spec/blog_spec.rb | UTF-8 | 532 | 2.734375 | 3 | [] | no_license | require 'Blog'
RSpec.describe Post do
let (:my_blog) {Blog.new}
describe "#posts" do
it "returns an array of posts" do
expect(my_blog.posts.class).to be(Array)
end
end
describe "#latest_posts" do
it "return array of sorted posts" do
first_post = Post.new("post 1","10/23/2016", "Lorem Ipsum Dolor")
second_post = Post.new("post 2","10/22/2016","Lorem Ipsum Dolor")
my_blog.add_post(first_post)
my_blog.add_post(second_post)
expect(my_blog.latest_posts).to eq([second_post, first_post])
end
end
end | true |
5841aa1023cc0b1be5dc547cd230a17c7fa2f74c | Ruby | karrkode/recursion | /recursion.rb | UTF-8 | 1,504 | 3.8125 | 4 | [
"MIT"
] | permissive | # require 'pry'
class Game
attr_reader :board, :position
def initialize(board)
@position = {x: 0,y: 0}
@board = create_board(board)
end
def create_board(board)
board[position[:y]][position[:x]] = "X"
board
end
def update_board(board,move)
board[position[:x]] = 'X'
if move == "A"
board[position[:x]+1] = " "
elsif move == "D"
board[position[:x]-1] = " "
end
# board
end
def play_game(full_board=@board)
# if self.position ==
move = validate_move(gets_move)
update_board(board,move)
p print_board
play_game(board)
end
def gets_move
print "Press A/D/W/Z to move your piece! "
gets.chomp.upcase
# ans
end
def validate_move(move)
if move != "A" && move != "D" && move != "W" && move != "Z"
puts "Sorry, please choose a valid position"
validate_move(gets_move)
end
if move == "A"
validate_move(gets_move) if position[:x] - 1 < 0
elsif move == "D"
validate_move(gets_move) if position[:x] + 1 > board.first.length
elsif move == 'W'
validate_move(gets_move) if position[:y] - 1 < 0
elsif move == 'Z'
validate_move(gets_move) if position[:y] + 1 > board.length
end
move_to_position(move)
move
end
def move_to_position(input)
if input == "D"
position[:x]+=1
elsif input == "A"
position[:x]-=1
elsif input == 'W'
position[:y]+=1
else
position[:y]-=1
end
# input
end
def print_board
board.each {|line| line}
end
end
a = Game.new(([" "," "," "," "],[" "," "," ","$"]))
# a.play_game
| true |
c151b245cd19ce1c47ef97778ea004c05ade7a6d | Ruby | cha63506/basset-2 | /spec/basset/feature_collection_spec.rb | UTF-8 | 4,119 | 2.78125 | 3 | [
"MIT"
] | permissive | require File.dirname(__FILE__) + '/../spec_helper'
describe "feature collection" do
describe "numbering features" do
before(:each) do
@collection = Basset::FeatureCollection.new
@collection.add_row %w[hello paul hello]
end
it "takes rows of features" do
@collection.features.should == %w[hello paul]
end
it "counts how many rows have been added" do
@collection.row_count.should == 1
end
it "counts the number of unique features" do
@collection.feature_count.should == 2
end
it "keeps the index of a feature" do
@collection.index_of("hello").should == 0
@collection.index_of("paul").should == 1
end
it "returns nil as the index for a feature not in the collection" do
@collection.index_of("whatevs").should == nil
end
it "knows the number of rows a feature occurs in" do
@collection.add_row %w[code hello paul and paul]
@collection.document_frequency("code").should == 1
@collection.document_frequency("hello").should == 2
@collection.document_frequency("paul").should == 2
end
it "should remove features that occur under a given number of times and renumber all others while preserving insertion order" do
collection = Basset::FeatureCollection.new
collection.add_row %w[hello basset library hello library]
collection.add_row %w[basset is sweet hello]
collection.purge_features_occuring_less_than(2)
collection.features.size.should == 2
collection.index_of("hello").should == 0
collection.index_of("basset").should == 1
end
end
describe "extracing feature vectors" do
before(:each) do
@collection = Basset::FeatureCollection.new()
@collection.add_row %w[hello paul basset]
@collection.add_row %w[basset is a ruby library]
end
it "can return a regular array with feature counts" do
@collection.features_to_vector(%w[basset is written by paul is]).should == [0, 1, 1, 2, 0, 0, 0]
end
it "can extract a sparse vector format" do
@collection.features_to_sparse_vector(%w[basset is written by paul is library]).should == [[1,1], [2,1], [3,2], [6,1]]
end
it "calculates a sparse vector with tf counts" do
@collection.features_to_sparse_vector(%w[basset is written by paul is library], :value => :tf).should == [[1,1], [2,1], [3,2], [6,1]]
end
it "calculates a sparse vector with booleans on if a feature appeared" do
@collection.features_to_sparse_vector(%w[basset is written by paul is library], :value => :boolean).should == [[1,1], [2,1], [3,1], [6,1]]
end
it "calculates a sparse vector with tf-idf counts and should exclude values of 0" do
@collection.features_to_sparse_vector(%w[basset is written by paul is library], :value => :tf_idf).inspect.should == [[1, 0.301029995663981], [3, 0.602059991327962], [6, 0.301029995663981]].inspect
end
it "calculates a sparse vector with sublinear tf-idf counts and should exclude values of 0" do
@collection.features_to_sparse_vector(%w[basset is written by paul is library], :value => :sublinear_tf_idf).inspect.should == [[1, 0.301029995663981], [3, 0.391649053953438], [6, 0.301029995663981]].inspect
end
end
describe "serializin a feature collection" do
it "can serialize to json" do
collection = Basset::FeatureCollection.new
collection.add_row %w[hello paul]
collection.add_row %w[basset by paul]
JSON.parse(collection.to_json).should == {
"row_count" => 2,
"feature_map" => {
"hello" => [0, 1],
"paul" => [1, 2],
"basset" => [2, 1],
"by" => [3, 1]
}
}
end
it "can marshall from json" do
collection = Basset::FeatureCollection.new
collection.add_row %w[paul hello paul]
collection.add_row %w[basset by paul]
marshalled_collection = Basset::FeatureCollection.from_json(collection.to_json)
marshalled_collection.document_frequency("paul").should == 2
marshalled_collection.index_of("by").should == 3
end
end
end
| true |
fedcf4a07553774cb64d94b4f6bb55b69be67276 | Ruby | YashTotale/learning-ruby | /basics/control-structures/conditionals/case.rb | UTF-8 | 332 | 3.859375 | 4 | [
"MIT"
] | permissive | count = 3
# Case with booleans
case
when count == 0
puts "nobody"
when count ==1
puts "1 person"
when (2..5).include?(count)
puts "several people"
else
puts "many people"
end
# Case with comparisons
case count
when 0
puts "nobody"
when 1
puts "1 person"
when 2..5
puts "several people"
else
puts "many people"
end
| true |
e7086f632f7d4985a5a1f36f641ed1452325a941 | Ruby | jimmy2/launchschool_ruby_basics | /methods/exercise_08.rb | UTF-8 | 138 | 3.40625 | 3 | [] | no_license | # exercise_08.rb
# Name Not Found
def assign_name(name="Bob")
name
end
puts assign_name('Kevin') == 'Kevin'
puts assign_name == 'Bob' | true |
0f217147173280127197fe952feae52d2cb23813 | Ruby | jginor/ttt-6-position-taken-rb-bootcamp-prep-000 | /lib/position_taken.rb | UTF-8 | 209 | 3.171875 | 3 | [] | no_license | # code your #position_taken? method here!
def position_taken?(board, index)
if board[index]==" " || board[index]=="" || board[index]==nil
false
elsif board[index] == ""
true
else
true
end
end
| true |
909cd9b2c0187072eefe0408a021a713d458f1e5 | Ruby | feedbin/feedbin | /app/models/sourceable.rb | UTF-8 | 421 | 2.765625 | 3 | [
"MIT"
] | permissive | class Sourceable
ATTRIBUTES = %i[title type id section jumpable]
attr_accessor *ATTRIBUTES
def initialize(type:, id:, title:, section: nil, jumpable: false)
@title = title
@type = type.downcase
@id = id
@section = section
@jumpable = jumpable
end
def to_h
{}.tap do |hash|
ATTRIBUTES.each do |attribute|
hash[attribute] = self.send(attribute)
end
end
end
end | true |
b159e9ad1b259da8257513bf5b43222274c47d6c | Ruby | gilesbowkett/citrus | /test/match_test.rb | UTF-8 | 2,211 | 2.921875 | 3 | [
"MIT"
] | permissive | require File.expand_path('../helper', __FILE__)
class MatchTest < Test::Unit::TestCase
def test_string_equality
match = Match.new('hello')
assert_equal('hello', match)
end
def test_match_equality
match1 = Match.new('a')
match2 = Match.new('a')
assert(match1 == match2)
assert(match2 == match1)
end
def test_match_inequality
match1 = Match.new('a')
match2 = Match.new('b')
assert_equal(false, match1 == match2)
assert_equal(false, match2 == match1)
end
def test_names
a = Rule.for('a')
a.name = 'a'
b = Rule.for('b')
b.name = 'b'
c = Rule.for('c')
c.name = 'c'
s = Rule.for([ a, b, c ])
s.name = 's'
r = Repeat.new(s, 0, Infinity)
r.name = 'r'
events = [
r,
s,
a, CLOSE, 1,
b, CLOSE, 1,
c, CLOSE, 1,
CLOSE, 3,
s,
a, CLOSE, 1,
b, CLOSE, 1,
c, CLOSE, 1,
CLOSE, 3,
s,
a, CLOSE, 1,
b, CLOSE, 1,
c, CLOSE, 1,
CLOSE, 3,
CLOSE, 9
]
match = Match.new("abcabcabc", events)
assert(match.names)
assert_equal([:r], match.names)
match.matches.each do |m|
assert_equal([:s], m.names)
end
end
def test_matches
a = Rule.for('a')
b = Rule.for('b')
c = Rule.for('c')
s = Rule.for([ a, b, c ])
s.name = 's'
r = Repeat.new(s, 0, Infinity)
events = [
r,
s,
a, CLOSE, 1,
b, CLOSE, 1,
c, CLOSE, 1,
CLOSE, 3,
s,
a, CLOSE, 1,
b, CLOSE, 1,
c, CLOSE, 1,
CLOSE, 3,
s,
a, CLOSE, 1,
b, CLOSE, 1,
c, CLOSE, 1,
CLOSE, 3,
CLOSE, 9
]
match = Match.new("abcabcabc", events)
assert(match.matches)
assert_equal(3, match.matches.length)
sub_events = [
s,
a, CLOSE, 1,
b, CLOSE, 1,
c, CLOSE, 1,
CLOSE, 3
]
match.matches.each do |m|
assert_equal(sub_events, m.events)
assert_equal(:s, m.name)
assert_equal("abc", m)
assert(m.matches)
assert_equal(3, m.matches.length)
end
end
end
| true |
19364d7ed937bcc61eb9c501a13f1dfe88d322f2 | Ruby | breadbaker/jana | /app/models/user.rb | UTF-8 | 1,564 | 2.546875 | 3 | [] | no_license | class User < ActiveRecord::Base
attr_accessible(
:email,
:pwd_hash,
:token, :password,
:first_name,
:image,
:last_name,
:uid,
:confirmed,
:confirm_token
)
before_save :legit_email
before_create :set_admin, :set_confirm_token
validates_presence_of :email
validates_uniqueness_of :email
def legit_email
raise "Invalid Email" unless self.email && self.email.match(/^.+@.+$/)
end
def set_admin
if ['janabake@gmail.com','danielebaker@gmail.com'].include?(self.email)
self.admin = true
end
end
def set_confirm_token
self.confirm_token = generate_token
end
def change_pass!(data)
if data[:new] != data[:confirm]
raise 'Passwords do not match'
end
self.password= data[:new]
end
def change_email!(data)
user_with = User.find_by_email(data[:email])
raise 'Email Taken' if user_with
self.email = data[:email]
return "Email Changed"
end
def self.find_by_credentials!( user )
@user = User.find_by_email!(user[:email])
raise "Invalid Password" unless @user.has_password?(user[:password])
@user
end
def reset_token!
self.token = generate_token
self.save! unless self.email.nil?
end
def generate_token
SecureRandom.urlsafe_base64(16)
end
def password=(password)
raise 'Password Cannot Be Blank' if password.nil?
raise 'Password is too short' if password.length < 6
self.pwd_hash = BCrypt::Password.create(password)
end
def has_password?(password)
BCrypt::Password.new(self.pwd_hash).is_password?(password)
end
end
| true |
bd73e05b3275dd3ceba9fe98e5d8d370305b5882 | Ruby | durrellchamorro/Twenty-One | /app/game.rb | UTF-8 | 1,771 | 3.875 | 4 | [] | no_license | require_relative 'dealer'
require_relative 'deck'
require_relative 'player'
class Game
attr_accessor :deck, :dealer, :player
def initialize
@deck = Deck.new
@dealer = Dealer.new
@player = Player.new
end
def play
system 'clear'
puts "Let's play twenty-one."
shuffle_cards!
deal_initial_cards
show_dealers_face_up_card
show_players_cards
gameplay_loop
show_final_cards
puts "Good Bye"
end
private
def shuffle_cards!
deck.cards.shuffle!
end
def deal_initial_cards
deck.deal(2, dealer)
deck.deal(2, player)
end
def show_dealers_face_up_card
value = dealers_last_card.value
suit = dealers_last_card.suit
puts "Dealers face up card: #{value} of #{suit} "
end
def dealers_hand
dealer.hand
end
def dealers_last_card
dealers_hand.last
end
def show_players_cards
player.show_cards
end
def gameplay_loop
player.take_turn(deck)
dealer.take_turn(deck)
announce_game_outcome
end
def enumerate_gameplay_results
case
when player.hand_busted?
-1
when dealer.hand_busted?
1
when player.hand_value < dealer.hand_value
-2
when player.hand_value > dealer.hand_value
2
when player.hand_value == dealer.hand_value
0
end
end
def announce_game_outcome
result = ""
case enumerate_gameplay_results
when -1
result << "You busted!"
when 1
result << "You win! The dealer busted!"
when -2
result << "Dealer wins!"
when 2
result << "You won!"
else
result << "Push."
end
system 'clear'
puts result
end
def show_final_cards
puts "Final cards:"
show_players_cards
dealer.show_cards
end
end
Game.new.play | true |
23ae047a99175a9a113d9e2873e46632161410ff | Ruby | antoinelyset/novify | /app/models/track.rb | UTF-8 | 703 | 2.53125 | 3 | [] | no_license | class Track < ActiveRecord::Base
after_save :update_radio_started_at, :update_radio_ended_at
belongs_to :radio
attr_accessible :href, :played_at
attr_accessible :radio_name, :radio_artist
attr_accessible :formatted_name, :formatted_artist
attr_accessible :spotify_name, :spotify_artist
validates_presence_of :played_at, :radio_name, :radio_artist, :radio
private
def update_radio_started_at
if radio.started_at.nil? || played_at < radio.started_at
radio.started_at = played_at
radio.save!
end
end
def update_radio_ended_at
if radio.ended_at.nil? || played_at > radio.ended_at
radio.ended_at = played_at
radio.save!
end
end
end
| true |
7607770981ac802d69cb8c95d21fbd088456c553 | Ruby | carolfly86/altar | /lib/crosstab.rb | UTF-8 | 2,091 | 2.5625 | 3 | [] | no_license | module Crosstab
# attr_accessor :total_true, :total_false, :passed_true, :passed_false
def self.ranking_calculation
query = "select passed_cnt,failed_cnt,
total_passed_cnt,total_failed_cnt,
branch_name||'-'||node_name as bn_name,
eval_result
from tarantular_tbl"
rst = DBConn.exec(query)
result = {}
rst.each do |r|
puts "bn_name: #{r['bn_name']}"
puts "eval: #{r['eval_result']}"
result[r['bn_name']] = 0 if result[r['bn_name']].nil?
score = Crosstab.ranking_score(r['passed_cnt'].to_f, r['failed_cnt'].to_f, r['total_passed_cnt'].to_f, r['total_failed_cnt'].to_f)
# query = "update tarantular_result set mw_score = #{ms_score} where bn_name = '#{r['bn_name']}'"
puts score
result[r['bn_name']] = result[r['bn_name']] + score
puts result[r['bn_name']]
end
SFL_Ranking.ranking_update('crosstab', result)
end
def self.ranking_score(passed_cnt, failed_cnt, total_passed_cnt, total_failed_cnt)
n_s = total_passed_cnt.to_f
n_f = total_failed_cnt.to_f
n_cf = failed_cnt.to_f
n_cs = passed_cnt.to_f
n = n_s + n_f
n_c = n_cs + n_cf
n_u = n - n_c
n_uf = n_f - n_cf
n_us = n_s - n_cs
return 1 if n_s == 0
return -1 if (n_f == 0) || (n_c == 0)
return 0 if (n_f == n_cf) || (n_s == n_cs)
# if (n_f == 0) ||\
# (n_s == 0) ||\
# (n_u == 0) ||\
# (n_c == 0)
e_cf = (n_c * n_f) / n
e_cs = (n_c * n_s) / n
e_uf = (n_u * n_f) / n
e_us = (n_u * n_s) / n
chi_square = (n_cf - e_cf)**2 / e_cf + \
(n_cs - e_cs)**2 / e_cs + \
(n_uf - e_uf)**2 / e_uf + \
(n_us - e_us)**2 / e_us
contig_coef = (chi_square / n)
p_f = n_cf / n_f
p_s = n_cs / n_s
p = p_f / p_s
puts "chi_square : #{chi_square}"
# puts p
susp_score = if p == 1 then 0
elsif p > 1 then contig_coef
else -contig_coef
end
susp_score
end
end
| true |
b0174ac13ae8a2596479bf16ce5e017b5f056539 | Ruby | yann021/thp_training | /formation/s3/j4/mon_projet/lib/show.rb | UTF-8 | 1,644 | 3.46875 | 3 | [] | no_license | class Show
def initialize
end
def creation_player
print "What is your name player 1 ............: "
$players["name1"] = gets.chomp
print "what is your symbole player 1 (x ou o) : "
$players["symbole1"] = gets.chomp
while $players["symbole1"] != "x" && $players["symbole1"] != "o"
print "what is your symbole player 1 (x ou o) : "
$players["symbole1"] = gets.chomp
end
print "What is your name player 2 ............: "
$players["name2"] = gets.chomp
if $players["symbole1"] == "x"
$players["symbole2"] = "o"
else $players["symbole1"] == "o"
$players["symbole2"] = "x"
end
end
=begin
creation_player demande aux utilisateur leur nom et leurs symbole,
le tout es rentré dans un hash que l'on return a la classe game
il ya une boucle, qui fais recommencer l'utilisateur si il ne rentre pas
un des deux ymbole définie. Le joueur deux ne choisis pas sont symbole,
il a celui restant par defaut.
=end
def show_board
#TO DO : affiche sur le terminal l'objet de classe Board en entrée. S'active avec un Show.new.show_board(instance_de_Board)
system("clear")
puts "BIENVENUE DANS TIC-TAC-TOE"
puts ""
puts "#{$players["symbole1"]} : #{$players["name1"]}"
puts "#{$players["symbole2"]} : #{$players["name2"]}"
puts ""
puts "
a b c
| |
1 #{$board[$liscase[0]]} | #{$board[$liscase[3]]} | #{$board[$liscase[6]]}
-----|-----|-----
2 #{$board[$liscase[1]]} | #{$board[$liscase[4]]} | #{$board[$liscase[7]]}
-----|-----|-----
3 #{$board[$liscase[2]]} | #{$board[$liscase[5]]} | #{$board[$liscase[8]]}
| |"
puts ""
end
end | true |
f248a3da48723da311eb0170514dada91c833f22 | Ruby | jake-007/rxruby | /examples/subscribe_on.rb | UTF-8 | 799 | 3.03125 | 3 | [
"Apache-2.0"
] | permissive | require 'rx'
def in_a_second(n)
Rx::Observable.create do |observer|
sleep(1)
observer.on_next(n)
observer.on_completed
end
end
# subscribe_on will schedule ancestry on given scheduler; each sleep happens in a separate thread
source = Rx::Observable.of(
in_a_second(1)
.map {|v| v + 1 }
.subscribe_on(Rx::DefaultScheduler.instance),
in_a_second(2)
.map {|v| v + 1 }
.subscribe_on(Rx::DefaultScheduler.instance)
).merge_all
.time_interval
subscription = source.subscribe(
lambda {|x|
puts 'Next: ' + x.to_s
},
lambda {|err|
puts 'Error: ' + err.to_s
},
lambda {
puts 'Completed'
})
# => Next: (3)@(1.004153)
# => Next: (2)@(0.000251)
while Thread.list.size > 1
(Thread.list - [Thread.current]).each &:join
end
| true |
1ed5a0c6918d1afe3077f5a59ead26d5ce7e7edd | Ruby | laurenelee/hotel | /lib/booking.rb | UTF-8 | 399 | 2.921875 | 3 | [] | no_license | require 'date'
module Hotel
class Booking
attr_reader :id, :dates, :rooms
def initialize(checkin, checkout, rooms, id)
@dates = DateRange.new(checkin, checkout)
@id = id
@rooms = rooms
end
def total_cost
total_cost = 0
@rooms.each do |room|
total_cost += room.cost * @dates.total_nights
end
return total_cost
end
end
end
| true |
4fa38fed87bfc07972a0b69e6a3aeb241a87bf94 | Ruby | luisfoxi/teste | /files/paises.rb | UTF-8 | 450 | 2.609375 | 3 | [] | no_license | require 'open-uri'
require "yaml"
config = YAML.load_file('../config/app_config.yml')
source = config['source']
country= source['country']
uri = URI.parse(country)
open(uri) do |file|
file.each_line do |linha|
puts "\nCreated: #{linha}"
end
# puts file.read()
end
# File.open('http://www.bcb.gov.br/rex/ftp/paises.txt', 'r') do |f1|
# while linha = f1.gets
# puts "\nCreated: #{linha}"
# end
# end
| true |
79f1d32d2f6aa2a6a07c6f4061407ab681f03299 | Ruby | shiningflint/learn_web_scrape_ruby | /index.rb | UTF-8 | 685 | 3.078125 | 3 | [] | no_license | require 'httparty'
require 'nokogiri'
# RESOURCE RELATED
def get_from_file
File.read("sample-file.txt")
end
def get_resource(url = "")
if url == ""
get_from_file()
else
HTTParty.get(url, verify: false)
end
end
# NOKOGIRI RELATED
def get_jpy_jual(htmlResource)
nokogiriObject = Nokogiri::HTML(htmlResource)
theElement = nokogiriObject.css("table.table > tbody > tr:nth-child(12) > td:nth-child(2)")
theElement.children
end
# START THE PROGRAM
def init
# url = "https://www.bca.co.id/id/Individu/Sarana/Kurs-dan-Suku-Bunga/Kurs-dan-Kalkulator"
url = ""
htmlResource = get_resource(url)
goodStuff = get_jpy_jual(htmlResource)
puts goodStuff
end
init
| true |
9b6fc0d364744838010471cc8c3f16aa45ae40dc | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/hamming/6ad0b37876194c03b14f11ec283fd79b.rb | UTF-8 | 222 | 3.21875 | 3 | [] | no_license | class Hamming
def self.compute(dna1,dna2)
length = [ dna1.length, dna2.length ].min - 1
( 0..length ).inject( 0 ) do | diff_count, i |
dna1[i] == dna2[i] ? diff_count : diff_count += 1
end
end
end
| true |
fc5253eef90f337f2c30223b8e8bba4d8149a982 | Ruby | acastemoreno/c2-module2 | /week-1/day-3/non-duplicates-values.rb | UTF-8 | 217 | 3.34375 | 3 | [] | no_license | def non_duplicated_values(values)
values.uniq.select{|i| values.count(i) == 1}
end
puts non_duplicated_values([1,2,2,3,3,4,5]).inspect #Return [1,4,5]
puts non_duplicated_values([1,2,2,3,4,4]).inspect #Return [1,3] | true |
2e5a41298a0ff9c4c3c7b07e2aebc8f0e9fb04b0 | Ruby | afhight/NameVersioning | /warmup.rb | UTF-8 | 358 | 3.765625 | 4 | [] | no_license |
visited = []
puts "Enter all the states you have been to, and type 'done' when complete."
keepgoing = true
while keepgoing
state = gets.chomp.upcase
if state != 'DONE'
visited.push(state)
else
keepgoing = false
end
end
# while (state != 'DONE')
# visited.push(state)
# end
puts "you have visited the following states:"
puts visited.join(", ")
| true |
795f7bae7dfb137fddef15fe8183aeffe827f025 | Ruby | kkalpakloglou/banking-app | /app/models/account.rb | UTF-8 | 633 | 2.546875 | 3 | [] | no_license | class Account < ApplicationRecord
# Associations
belongs_to :user
has_many :transactions
# Validations
validates :number, presence: true, uniqueness: true
validates :user_id, presence: true
# Callbacks
before_validation :set_account_number, on: [:create]
def balance
Money.new(sum_of_credit_in_cents - sum_of_debit_in_cents)
end
private
def sum_of_credit_in_cents
transactions.credit.sum(:amount_cents)
end
def sum_of_debit_in_cents
transactions.debit.sum(:amount_cents)
end
def set_account_number
self.number ||= GenerateRandomCodeService.perform(self.class, :number)
end
end
| true |
df6b0850045da332d02341cea76425f79aeb06b0 | Ruby | bborn/eschaton | /slices/google_maps/google/marker.rb | UTF-8 | 11,638 | 2.8125 | 3 | [
"MIT"
] | permissive | module Google
# Represents a marker that can be added to a Map using Map#add_marker. If a method or event is not documented here please
# see googles online[http://code.google.com/apis/maps/documentation/reference.html#GMarker] docs for details. See MapObject#listen_to on how to use
# events not listed on this object.
#
# You will most likely use click, open_info_window and set_tooltip to get some basic functionality going.
#
# === General examples:
#
# Google::Marker.new :location => {:latitude => -34, :longitude => 18.5}
#
# Google::Marker.new :location => {:latitude => -34, :longitude => 18.5},
# :draggable => true,
# :title => "This is a marker!"
#
# Google::Marker.new :location => {:latitude => -34, :longitude => 18.5},
# :icon => :green_circle #=> "/images/green_circle.png"
#
# Google::Marker.new :location => {:latitude => -34, :longitude => 18.5},
# :icon => '/images/red_dot.gif'
#
# === Tooltip examples:
#
# Google::Marker.new :location => {:latitude => -34, :longitude => 18.5},
# :tooltip => {:text => 'This is sparta!'}
#
# Google::Marker.new :location => {:latitude => -34, :longitude => 18.5},
# :tooltip => {:text => 'This is sparta!', :show => :always}
#
# Google::Marker.new :location => {:latitude => -34, :longitude => 18.5},
# :tooltip => {:partial => 'spot_information', :show => :always}
#
# === Gravatar examples:
# Google::Marker.new :location => {:latitude => -34, :longitude => 18.5},
# :gravatar => 'yawningman@eschaton.com'
#
# Google::Marker.new :location => {:latitude => -34, :longitude => 18.5},
# :gravatar => {:email_address => 'yawningman@eschaton.com', :size => 50}
#
# === Circle examples:
# Google::Marker.new :location => {:latitude => -33.947, :longitude => 18.462},
# :circle => true
#
# Google::Marker.new :location => {:latitude => -33.947, :longitude => 18.462},
# :circle => {:radius => 500, :border_width => 5}
#
# === Info windows using open_info_window:
#
# marker.open_info_window :text => 'Hello there...'
#
# marker.open_info_window :partial => 'spot_information'
#
# marker.open_info_window :partial => 'spot_information', :locals => {:information => information}
#
# map.open_info_window :url => {:controller => :spot, :action => :show, :id => @spot}
#
# === Using the click event:
#
# # Open a info window and circle the marker.
# marker.click do |script|
# marker.open_info_window :url => {:controller => :spot, :action => :show, :id => @spot}
# marker.circle!
# end
class Marker < MapObject
attr_accessor :icon
attr_reader :circle, :circle_var
include Tooltipable
# ==== Options:
# * +location+ - Required. A Location or whatever Location#new supports which indicates where the marker must be placed on the map.
# * +icon+ - Optional. The Icon that should be used for the marker otherwise the default marker icon will be used.
# * +gravatar+ - Optional. Uses a gravatar as the icon. If a string is supplied it will be used for the +email_address+
# option, see Gravatar#new for other valid options.
# * +circle+ - Optional. Indicates if a circle should be drawn around the marker, also supports styling options(see Circle#new)
# * +tooltip+ - Optional. See Google::Tooltip#new for valid options.
#
# See addtional options[http://code.google.com/apis/maps/documentation/reference.html#GMarkerOptions] that are supported.
def initialize(options = {})
options.default! :var => 'marker', :draggable => false
super
@circle_var = "circle_#{self}"
if create_var?
location = Google::OptionsHelper.to_location(options.extract(:location))
#@location = OptionsHandler.to_location!(options) #:extract => true
self.icon = if icon = options.extract(:icon)
Google::OptionsHelper.to_icon(icon)
elsif gravatar = options.extract(:gravatar)
Google::OptionsHelper.to_gravatar_icon(gravatar)
end
options[:icon] = self.icon if self.icon
circle_options = options.extract(:circle)
tooltip_options = options.extract(:tooltip)
self << "#{self.var} = new GMarker(#{location}, #{options.to_google_options});"
self.draggable = options[:draggable]
self.set_tooltip(tooltip_options) if tooltip_options
if circle_options
circle_options = {} if circle_options == true
self.circle! circle_options
end
end
end
# The location at which the marker is currently placed on the map.
def location
"#{self}.getLatLng()"
end
# Opens a information window on the marker using either +url+, +partial+ or +text+ options as content.
#
# ==== Options:
# * +url+ - Optional. URL is generated by rails #url_for. Supports standard url arguments and javascript variable interpolation.
# * +partial+ - Optional. Supports the same form as rails +render+ for partials, content of the rendered partial will be
# placed inside the info window.
# * +text+ - Optional. The html content that will be placed inside the info window.
# * +include_location+ - Optional. Works in conjunction with the +url+ option and indicates if latitude and longitude parameters of
# +location+ should be sent through with the +url+, defaulted to +true+. Use <tt>params[:location]</tt> or <tt>params[:location][:latitude]</tt> and <tt>params[:location][:longitude]</tt> in your action.
# ==== Examples:
#
# marker.open_info_window :text => 'Hello there...'
#
# marker.open_info_window :partial => 'spot_information'
#
# marker.open_info_window :partial => 'spot_information', :locals => {:information => information}
#
# map.open_info_window :url => {:controller => :spot, :action => :show, :id => @spot}
def open_info_window(options)
info_window = InfoWindow.new(:object => self)
info_window.open_on_marker options
end
# If called with a block it will attach the block to the "click" event of the marker.
# If +info_window_options+ are supplied an info window will be opened with those options and the block will be ignored.
#
# ==== Example:
#
# # Open a info window and circle the marker.
# marker.click do |script|
# marker.open_info_window :url => {:controller => :spot, :action => :show, :id => @spot}
# marker.circle!
# end
def click(info_window_options = nil, &block) # :yields: script
if info_window_options
self.click do
self.open_info_window info_window_options
end
elsif block_given?
self.listen_to :event => :click, &block
end
end
# This event is fired when the marker is "picked up" at the beginning of being dragged.
#
# ==== Yields:
# * +script+ - A JavaScriptGenerator to assist in generating javascript or interacting with the DOM.
def when_picked_up(&block)
self.listen_to :event => :dragstart, &block
end
# This event is fired when the marker is being "dragged" across the map.
#
# ==== Yields:
# * +script+ - A JavaScriptGenerator to assist in generating javascript or interacting with the DOM.
# * +current_location+ - The location at which the marker is presently hovering.
def when_being_dragged
self.listen_to :event => :drag do
script << "current_location = #{self.var}.getLatLng();"
yield script, :current_location
end
end
# This event is fired when the marker is "dropped" after being dragged.
#
# ==== Yields:
# * +script+ - A JavaScriptGenerator to assist in generating javascript or interacting with the DOM.
# * +drop_location+ - The location on the map where the marker was dropped.
def when_dropped
self.listen_to :event => :dragend do |script|
script << "drop_location = #{self.var}.getLatLng();"
yield script, :drop_location
end
end
# Opens an info window that contains a blown-up view of the map around this marker.
#
# ==== Options:
# * +zoom_level+ - Optional. Sets the blowup to a particular zoom level.
# * +map_type+ - Optional. Set the type of map shown in the blowup.
def show_map_blowup(options = {})
options[:map_type] = options[:map_type].to_map_type if options[:map_type]
self << "#{self.var}.showMapBlowup(#{options.to_google_options});"
end
# Changes the foreground icon of the marker to the given +image+. Note neither the print image nor the shadow image are adjusted.
#
# marker.change_icon :green_cicle #=> "/images/green_circle.png"
# marker.change_icon "/images/red_dot.gif"
def change_icon(image)
image = Google::OptionsHelper.to_image(image)
self << "#{self.var}.setImage(#{image.to_js});"
end
# Draws a circle around the marker, see Circle#new for valid styling options.
#
# ==== Examples:
# marker.circle!
#
# marker.circle! :radius => 500, :border_width => 5
def circle!(options = {})
options[:var] = self.circle_var
options[:location] = self.location
@circle = Google::Circle.new options
if self.draggable?
self.when_being_dragged do |script, current_location|
@circle.move_to current_location
end
end
@circle
end
def circled? # :nodoc:
@circle.not_nil?
end
# See Tooltipable#set_tooltip about valid +options+
def set_tooltip(options)
super
if self.draggable?
self.when_picked_up do |script|
self.tooltip.marker_picked_up
end
self.when_dropped do |script, location|
self.tooltip.marker_dropped
end
self.when_being_dragged do
self.tooltip.force_redraw
end
end
end
def draggable=(value) # :nodoc:
@draggable = value
if self.draggable?
self.when_picked_up{ self.close_info_window }
end
end
def draggable? # :nodoc:
@draggable
end
# This event is fired when the mouse "moves over" the marker.
#
# ==== Yields:
# * +script+ - A JavaScriptGenerator to assist in generating javascript or interacting with the DOM.
def mouse_over(&block)
self.listen_to :event => :mouseover, &block
end
# This event is fired when the mouse "moves off" the marker.
#
# ==== Yields:
# * +script+ - A JavaScriptGenerator to assist in generating javascript or interacting with the DOM.
def mouse_off(&block)
self.listen_to :event => :mouseout, &block
end
# Moves the marker to the given +location+ on the map.
def move_to(location)
location = Google::OptionsHelper.to_location(location)
self.lat_lng = location
self.tooltip.force_redraw if self.tooltip
self.circle.move_to(location) if self.circled?
end
def added_to_map(map) # :nodoc:
self.add_tooltip_to_map(map)
end
def removed_from_map(map) # :nodoc:
self.close_info_window
self.remove_tooltip_from_map(map)
self.script.if "typeof(#{self.circle_var}) != 'undefined'" do
map.remove_overlay self.circle_var
end
end
end
end | true |
2fe3284774807e1df42af4a3ef61275e071fa6b4 | Ruby | wwb0709/ruby | /rubywork/student.rb | UTF-8 | 797 | 3.953125 | 4 | [] | no_license | load "person.rb"
module Me
def sqrt(num, rx=1, e=1e-10)
num*=1.0
(num - rx*rx).abs <e ? rx : sqrt(num, (num/rx + rx)/2, e)
end
end
class Student < Person
@@count=0
# def initialize
# @@count+=1
# end
def talk
super
puts "I am a student. my name is "+@name+", age is "+@age.to_s
puts "I am #@name, This class have #@@count students."
end # talk 方法结束
end # Student 类结束
p3=Student.new("kaichuan",25);
p3.talk
p4=Student.new("Ben");
p4.talk
p4.extend(Me)
puts p4.sqrt(93.1, 25)
# 9.64883412646315
def one_block
for num in 1..3
yield(num)
end
end
one_block do|i|
puts "This is block #{i}."
end
class Array
def one_by_one
for i in 0..size
yield(self[i] )
end
puts end
end
arr = [1,3,5,7,9]
arr.one_by_one {|k| print k,","} | true |
e7a22b21d0478d9c8ea9359bf8591cbbf27d2325 | Ruby | danachen/Ruby | /LS130/Exercises/easy/easy2_6.rb | UTF-8 | 413 | 4.1875 | 4 | [] | no_license | # Easy, #select method
# with iterator
def each_with_index(arr)
arr.each do |el|
yield(el, arr.find_index(el))
end
end
# without iterator
def each_with_index(arr)
counter = 0
arr.each do |el|
yield(el, counter)
counter += 1
end
end
result = each_with_index([1, 3, 6]) do |value, index|
puts "#{index} -> #{value**index}"
end
puts result == [1, 3, 6]
# 0 -> 1
# 1 -> 3
# 2 -> 36
# true | true |
be13dbaea0307787ee7dbc0a9f88078f17359998 | Ruby | MikeAllison/tealeaf_oop | /05_workbook/intermediate/quiz_1/03.rb | UTF-8 | 426 | 3.4375 | 3 | [] | no_license | class InvoiceEntry
attr_reader :product_name, :quantity
def initialize(product_name, number_purchased)
@quantity = number_purchased
@product_name = product_name
end
def update_quantity(updated_count)
# prevent negative quantities from being set
@quantity = updated_count if updated_count >= 0
end
end
line1 = InvoiceEntry.new("socks", 2)
line1.update_quantity(4)
p line1.quantity
| true |
4178f9079a4ebff19ff92f8dae3c8949df24ac86 | Ruby | eric-wood/roomba | /lib/rumba/dsl.rb | UTF-8 | 1,890 | 3.875 | 4 | [] | no_license | # Define the Rumba "DSL"
# Lots of easy to use methods for basic tasks
class Rumba
module Dsl
# Remember, Roomba speeds are defined in mm/s (max is 200)
DEFAULT_SPEED = 200
# move both wheels at the same speed in a certain direction!
# NOTE THAT THIS BLOCKS UNTIL COMPLETE
def straight_distance(distance, speed: DEFAULT_SPEED)
total = 0
straight(speed)
loop do
total += get_sensor(:distance).abs
break if total >= distance
end
halt
end
# distance is in mm!
def forward(distance, speed: DEFAULT_SPEED)
straight_distance(distance, speed: speed)
end
# distance is in mm!
def backward(distance, speed: DEFAULT_SPEED)
straight_distance(distance, speed: -speed)
end
# Direction can either be a Fixnum for number of degrees,
# or a symbol for the direction (:left, :right)
def rotate(direction, speed: DEFAULT_SPEED)
# handle symbols...
# note that counter-clockwise is positive
case direction
when :left
direction = 90
when :right
direction = -90
end
direction > 0 ? spin_right(speed) : spin_left(speed)
total = 0
goal = direction.abs / 2
loop do
raw_angle = get_sensor(:angle)
# taken from the official docs to convert output to degrees...
degrees = (360 * raw_angle)/(258 * Math::PI)
total += degrees.abs
break if total >= goal
end
halt
end
# eh, why not?
alias_method :forwards, :forward
alias_method :backwards, :backward
alias_method :turn, :rotate
end
end
# MEASUREMENT HELPERS
class Fixnum
def inches
25.4 * self
end
alias_method :inch, :inches
def feet
self.inches * 12
end
alias_method :foot, :feet
def meters
self * 1000
end
alias_method :meter, :meters
end
| true |
ab43358b1fd1acb957deb3db0cc54e6049a1ef90 | Ruby | cielavenir/procon | /atcoder/arc/tyama_atcoderARC044A.rb | UTF-8 | 104 | 3.296875 | 3 | [
"0BSD"
] | permissive | #!/usr/bin/ruby
n=gets.to_i
puts n==2||n==3||n==5||(n!=1&&n%2!=0&&n%3!=0&&n%5!=0) ? :Prime : 'Not Prime' | true |
29f6d36bff26c1a399484bc85caeaebf9b5c3ecf | Ruby | AlineFreitas/AdventOfCode | /2019/day01/spec/fuel_counter_spec.rb | UTF-8 | 2,245 | 3.03125 | 3 | [] | no_license | require_relative '../fuel_counter'
RSpec.describe "Fuel Counter" do
context "Calculate fuel by mass" do
it "returns 2 when mass is 12" do
# Given
mass = 12
# When
needed_fuel = FuelCounter.fuel_by_mass(mass)
# Then
expect(needed_fuel).to eq(2)
end
it "returns 2 when mass is 14" do
# Given
mass = 14
# When
needed_fuel = FuelCounter.fuel_by_mass(mass)
# Then
expect(needed_fuel).to eq(2)
end
it "returns 654 when fuel is 1969" do
# Given
mass = 1969
# When
needed_fuel = FuelCounter.fuel_by_mass(mass)
# Then
expect(needed_fuel).to eq(654)
end
it "returns 33583 when fuel is 100756" do
# Given
mass = 100756
# When
needed_fuel = FuelCounter.fuel_by_mass(mass)
# Then
expect(needed_fuel).to eq(33583)
end
end
context "Calculate fuel for the fuel, by mass" do
it "returns 2 when mass is 12" do
# Given
mass = 12
# When
needed_fuel = FuelCounter.fuel_for_fuel(mass)
# Then
expect(needed_fuel).to eq(2)
end
it "returns 2 when mass is 14" do
# Given
mass = 14
# When
needed_fuel = FuelCounter.fuel_for_fuel(mass)
# Then
expect(needed_fuel).to eq(2)
end
it "returns 966 when fuel is 1969" do
# Given
mass = 1969
# When
needed_fuel = FuelCounter.fuel_for_fuel(mass)
# Then
expect(needed_fuel).to eq(966)
end
it "returns 50346 when fuel is 100756" do
# Given
mass = 100756
# When
needed_fuel = FuelCounter.fuel_for_fuel(mass)
# Then
expect(needed_fuel).to eq(50346)
end
end
end | true |
334b25a0a4863d43cce3dd6ff57a85b344d6423c | Ruby | msanroman/gilded-rose | /spec/normal_item_spec.rb | UTF-8 | 560 | 2.5625 | 3 | [] | no_license | require File.expand_path(File.dirname(__FILE__)+'/../lib/normal_item.rb')
describe NormalItem do
it "decreases it's quality and it's sell_in in one point every day when the sell day hasn't passed yet" do
item = NormalItem.new("+5 Dexterity Vest", 10, 20)
item.update_stats
item.sell_in.should equal 9
item.quality.should equal 19
end
it "decreases it's quality twice if it's sell day has passed" do
item = NormalItem.new("item", 0, 10)
item.update_stats
item.sell_in.should equal -1
item.quality.should equal 8
end
end | true |
bba7d7bb03d3ac2f70a3a3e91e5b4251055ce5dd | Ruby | Zheka1988/ruby_replay | /lesson_1/prymougol_treugolnik.rb | UTF-8 | 562 | 3.46875 | 3 | [] | no_license | puts "Vvedite storony treugol'nika!"
puts 'a?'
a = gets.chomp.to_i
puts 'b?'
b = gets.chomp.to_i
puts 'c?'
c = gets.chomp.to_i
sides = [a, b, c].sort
def pryamougolniy?(sides)
sides[2]**2 == sides[0]**2 + sides[1]**2 ? 'prymougolniy' : 'ne prymougolniy'
end
def ravnobedrenniy?(a, b, c)
a == b || a == c || c == b ? 'ravnobedrenniy' : 'ne ravnobedrenniy'
end
def ravnostoronniy?(a, b, c)
a == b && a == c ? 'ravnostoronniy' : 'ne ravnostoronniy'
end
puts "treugol'nik #{pryamougolniy?(sides)} #{ravnobedrenniy?(a, b, c)}
#{ravnostoronniy?(a, b, c)}"
| true |
a1ec5b92a555989165bae11a33eeb337b1a9b3d4 | Ruby | hyx131/TwO-O-Player-Math-Game | /game.rb | UTF-8 | 1,308 | 3.78125 | 4 | [] | no_license | require './player'
require './math_question'
class Game
def initialize
@players = [
Player.new('Player 1', 'P1'),
Player.new('Player 2', 'P2')
]
@round = 0
@index = 0
end
def play
while !game_over? do
header "NEW TURN"
question = Question.new
puts question.generate_question("#{@players[@index].name}")
print ">"
user_answer = gets.chomp.to_i
user_answer != question.answer ? wrong : correct
if user_answer != question.answer
@players[@index].wrong_answer
end
summary
next_round
@index = @round % @players.length
end
puts "#{winner.name} wins with a score of #{winner.score}."
header "GAME OVER"
puts "Goody bye!"
end
private
def summary
@players.each.with_index do |player, index|
print 'vs ' if index != 0
print "#{player.summary_line} "
end
puts
end
def wrong
puts "Seriously? No!"
end
def correct
puts "CORRECT! You got it!"
end
def game_over?
@players.find { |r| r.dead? }
end
def winner
@players.find { |r| !r.dead? }
end
def next_round
@round += 1
end
def header (info)
puts "======="
puts info
puts "======="
end
end
# game = Game.new
# puts game.play
| true |
8c6e07131604f545458ffc131911625ab040149c | Ruby | tomoakin/DepthHist | /range_compress.rb | UTF-8 | 493 | 2.546875 | 3 | [] | no_license | #!/bin/env ruby
#
lastref=nil
lastpos=0
min_depth=100000
cur_range_start = nil
ARGF.each_line do |l|
a=l.chomp.split
ref=a[0]
pos=a[1].to_i
depth=a[2].to_i
min_depth = depth if depth < min_depth
if lastpos == 0
cur_range_start = pos
lastref = ref
lastpos = pos
next
end
if ref!=lastref or pos != lastpos + 1
puts "#{lastref}:#{cur_range_start}-#{lastpos}\t#{min_depth}"
lastref=ref
cur_range_start=pos
min_depth=100000
end
lastpos=pos
end
| true |
55f649ce9f1f2d8a6657646df3ea8e63ba731254 | Ruby | pelf/New-Scientist-Enigmas | /1688.rb | UTF-8 | 1,249 | 3.40625 | 3 | [] | no_license | # find primes in the first 1000 integers
primes = Array.new(1000,true)
for i in 2...1000
next unless primes[i]
for j in 2...1000
prod = i*j
break if prod > 1000
primes[prod] = false
end
end
prime_nrs = []
for i in 2...1000
prime_nrs << i if primes[i]
end
#puts prime_nrs.inspect
products = []
products_primes = {}
# find products of two primes with 2 digits
prime_nrs.each do |i|
prime_nrs.each do |j|
next if i == j # they need to be different
p = i*j
break if p > 200
if p > 9 # and have 2 digits
products << p
products_primes[p] = [i,j]
end
end
end
#puts products.sort.inspect
products.uniq!.sort!
# pair products and check their difference and sum for 'primeness'
products.each do |p1|
break if p1 > 99
products.each do |p2|
break if p2 > 99
dif = (p1-p2).abs
# is the difference a product of primes?
next unless products.include? dif
sum = p1+p2
# and the sum?
next unless products.include? sum
# prime factors must be distinct
break if (products_primes[p1]+products_primes[p2]+products_primes[dif]+products_primes[sum]).uniq.size < 8
puts "match: #{p1}, #{p2}, #{dif}, #{sum}"
puts (products_primes[p1]+products_primes[p2]+products_primes[dif]+products_primes[sum]).inspect
end
end
| true |
1a53bc10ee0689d7f67004b1f95a439de62ccfb7 | Ruby | turingschool-examples/battleshift | /app/services/turn_processor.rb | UTF-8 | 828 | 3.28125 | 3 | [] | no_license | class TurnProcessor
def initialize(game, target)
@game = game
@target = target
@messages = []
end
def run!
begin
attack_opponent
ai_attack_back
game.save!
rescue InvalidAttack => e
@messages << e.message
end
end
def message
@messages.join(" ")
end
private
attr_reader :game, :target
def attack_opponent
result = Shooter.fire!(board: opponent.board, target: target)
@messages << "Your shot resulted in a #{result}."
game.player_1_turns += 1
end
def ai_attack_back
result = AiSpaceSelector.new(player.board).fire!
@messages << "The computer's shot resulted in a #{result}."
game.player_2_turns += 1
end
def player
Player.new(game.player_1_board)
end
def opponent
Player.new(game.player_2_board)
end
end
| true |
cd58a02390e3e16c67825e444f08072921917bfe | Ruby | kahohonda917/rubykakunin | /lesson6.rb | UTF-8 | 229 | 3.109375 | 3 | [] | no_license | total_price=105
if total_price>100
puts "みかんを購入。所持金に余りあり"
elsif total_price ==100
puts "みかんを購入。所持金は0円"
else
puts "みかんを購入することはできません"
end | true |
328871de2690d58eab658e03d4e5752d59c52f20 | Ruby | mongodb/mongoid | /lib/mongoid/errors/callback.rb | UTF-8 | 656 | 2.515625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
# rubocop:todo all
module Mongoid
module Errors
# This error is raised when calling #save! or .create! on a model when one
# of the callbacks returns false.
class Callback < MongoidError
# Create the new callbacks error.
#
# @example Create the new callbacks error.
# Callbacks.new(Post, :create!)
#
# @param [ Class ] klass The class of the document.
# @param [ Symbol ] method The name of the method.
def initialize(klass, method)
super(
compose_message("callbacks", { klass: klass, method: method })
)
end
end
end
end
| true |
1552f28873f700174305a6e86f533cad2d7b0a8f | Ruby | cies/mostfit | /lib/rules.rb | UTF-8 | 12,343 | 3.15625 | 3 | [
"MIT"
] | permissive | module Mostfit
module Business
class BasicCondition
# attr_accessor :appliesOn, :operator, :compareWith, :validator
attr_accessor :var1, :binaryoperator, :var2, :comparator, :const_value, :validator
def self.get_basic_condition(cond)
if(cond.keys.length < 3)
return nil
else
a = BasicCondition.new
a.var1 = cond[:var1]
a.var2 = cond[:var2]
a.binaryoperator = cond[:binaryoperator].to_s #plus or minus
a.comparator = cond[:comparator].to_s #less_than, greater_than etc.
regex = Regexp.new(/.count/)
matchdata = regex.match(a.var1)
if matchdata
a.const_value = (cond[:const_value] - 1 )
else
a.const_value = cond[:const_value]
end
# a.const_value = cond[:const_value]
if(a.comparator == "less_than")
a.comparator = :<
elsif(a.comparator == "less_than_equal")
a.comparator = :<=
elsif(a.comparator == "greater_than")
a.comparator = :>
elsif(a.comparator == "greater_than_equal")
a.comparator = :>=
elsif( (a.comparator == "equal1") or (a.comparator == "equal2") or (a.comparator == "equal") )
a.comparator = :==
elsif( (a.comparator == "not1") or (a.comparator == "not2") or (a.comparator == "not") )
a.comparator = "!=".to_sym
else
a.comparator = :UNKNOWN_COMPARATOR
end
if(a.binaryoperator == "plus" or a.binaryoperator == "+")
a.binaryoperator = :+
elsif(a.binaryoperator == "minus" or a.binaryoperator == "-")
a.binaryoperator = :-
else
a.binaryoperator = :UNKOWN_BINARY_OPERATOR
end
a.validator = Proc.new{|obj| #obj is effectively an object of model_name class
if((a.var2 == nil) or (a.var2 == 0))#single variable has to be handled
#var1 is a string
obj1 = a.var1.split(".").map{|x| x.to_sym}.inject(obj){|s,x|
s.send(x) if s!= nil
}
if obj1 == nil
false #this has happend when the condition is ill-formed (say wrong spelling)
elsif a.comparator == "!=".to_sym
obj1 != a.const_value
else#otherwise
obj1.send(a.comparator, a.const_value)
end
else #two variables to be handled
#get obj1
obj1 = a.var1.split(".").map{|x| x.to_sym}.inject(obj){|s,x|
s.send(x) if s!= nil
}
next if obj1 == nil #this can happend when the condition is ill-formed (say wrong spelling)
#get obj2
obj2 = a.var2.split(".").map{|x| x.to_sym}.inject(obj){|s,x|
if s!= nil then s.send(x) end
}
next if obj2 == nil #this can happend when the condition is ill-formed (say wrong spelling)
obj3 = obj1.send(a.binaryoperator, obj2)
obj3 != a.const_value if a.comparator == "!=".to_sym
#otherwise
if obj3.class == Rational
obj3.send(a.comparator, a.const_value.to_i)
else
obj3.send(a.comparator, a.const_value)
end
end
}
return a
end
end
def to_s
return "#{@appliesOn} #{@operator} #{@compareWith}"
end
private_class_method :initialize #to prevent direct object creation
end
class ComplexCondition
attr_accessor :is_basic_condition , :basic_condition #makes sense only if its a basic condition
attr_accessor :operator #makes sense only if its not a basic condition
attr_accessor :condition1, :condition2 #makes sense only if its not a basic condition
def self.get_condition(cond)
if((cond[:linking_operator] != nil) and (cond[:linking_operator].to_sym == :not)) then
c = ComplexCondition.new
c.operator = :not
c.condition1 = ComplexCondition.get_condition(cond[:first_condition])
c.condition2 = nil
c.is_basic_condition = false
return c
elsif((cond[:linking_operator] != nil) and (cond[:linking_operator].to_sym == :and) || (cond[:linking_operator].to_sym == :or)) then
c = ComplexCondition.new
c.operator = cond[:linking_operator]
c.condition1 = ComplexCondition.get_condition(cond[:first_condition])
c.condition2 = ComplexCondition.get_condition(cond[:second_condition])
c.is_basic_condition = false
return c
else
c = ComplexCondition.new
c.is_basic_condition = true
c.basic_condition = BasicCondition.get_basic_condition(cond)
return c
end
end
def check_condition(obj)
if is_basic_condition
return @basic_condition.validator.call(obj)
elsif operator == :not
return (not @condition1.check_condition(obj))
elsif operator == :and or operator == "and"
return (@condition1.check_condition(obj) && @condition2.check_condition(obj))
elsif operator == :or or operator == "or"
return (@condition1.check_condition(obj) || @condition2.check_condition(obj))
end
end
def to_s
if is_basic_condition
basic_condition.to_s
else
"[#{@operator}: [#{@condition1}] [#{@condition2}]]"
end
end
private :initialize
end
class Rules
@@rules = {}
REJECT_REGEX = /^(Merb|merb)::*/
def self.deploy #apply the business rules
#debugger
begin
Rule.all.each do |r|
r.apply_rule
end
rescue Exception => e#TODO find a better way of handling situation when rules table is missing
puts "Rules Engine not deployed. continuing"
end
# load(File.join(Merb.root, "config", "rules.rb"))
end
def initialize
end
def self.all_models #this is use to retrieve the list of all models
#on which rules can be applied
DataMapper::Model.descendants.reject{|x| x.superclass!=Object}.map{|d| d.to_s.snake_case.to_sym}
end
def self.tree
DataMapper::Model.descendants.to_a.collect{|m|
{m => m.relationships}
}.inject({}){|s,x| s+=x}.reject{|k,v| v.length==0}
end
def self.prepare(&blk) # blk contains a set of calls to allow() and
# reject() to implement rules
self.new.instance_eval(&blk)
end
def self.get_value_obj(obj, type)
if type == "date"
return obj.blank? ? nil : Date.parse(obj)
elsif type== "int"
return obj.to_i
elsif type== "float"
return obj.to_f
else
return obj
end
end
def self.apply_rule(rule)
h = {:name => rule[:name], :on_action => rule[:on_action], :model_name => rule[:model_name],
:permit => rule[:permit], :condition => convert_to_polish_notation(rule[:condition]),
:precondition => convert_to_polish_notation(rule[:precondition]) }
self.add h
end
#this is used for converting condition and precondition to polish notation
def self.convert_to_polish_notation(marshalled_condition)
condition1 = Hash.new
if marshalled_condition == nil
return condition1 #blank
end
Marshal.restore(marshalled_condition).to_a.reverse!.each do |idx, cond|
var2 = nil
if cond[:variable]["2"] != nil
var2 = cond[:variable]["2"][:complete]
end
if (var2 != nil) and (var2 == "0")
var2 = 0 #now this can be generically handled with all cases of int and date
end
const_value = 0
if (cond[:valuetype] == "date") and (var2 != 0)#this implies that var1 and var2 both are date, so a date subtraction is going on, so const_value has to be int
const_value = get_value_obj(cond[:const_value], "int")
else
const_value = get_value_obj(cond[:const_value], cond[:valuetype])
end
condition_expression = {
:var1 => cond[:variable]["1"][:complete],
:binaryoperator => cond[:binaryoperator],
:var2 => var2,
:comparator => cond[:comparator].to_s,
:const_value => const_value }
if cond[:linking_operator] != ""
hash1 = Hash.new
hash1[:second_condition] = condition1.dup
hash1[:linking_operator] = cond[:linking_operator]
#condition format - Variable1, binary opearator(+/-), Variable2, comparator, const_value
hash1[:first_condition]= condition_expression
condition1 = hash1
elsif
condition1 = condition_expression
end
end
return condition1
end
#should not be called directly
#only apply_rule should call this func
def self.add(hash)
if(hash[:model_name].class != Class)
hash[:model_name] = Kernel.const_get(hash[:model_name].camelcase)
end
function_name = hash[:name].to_s.downcase.gsub(" ", "_")
hash[:model_name].send(:define_method, function_name) do
if hash.key?(:permit)
if(hash[:permit] == "false")
hash1 = {:linking_operator => :not, :first_condition => hash[:condition].dup}
hash[:condition] = hash1
end
end
if hash.key?(:precondition) and hash[:precondition].length != 0 #result = not precondition OR (precondition AND condition)
c = hash[:condition].dup
p = hash[:precondition].dup
hash[:condition] = {:linking_operator => :or,
:first_condition => {:linking_operator =>:not, :first_condition => p},
:second_condition => {:linking_operator =>:and, :first_condition => p,
:second_condition => c } }
end
c = ComplexCondition.get_condition(hash[:condition])
if c.check_condition(self)
return true
else
return [false, "#{hash[:name]} violated"]
end
end
opts = {}
if hash[:on_action] == :update
opts[:unless] = :new?
elsif hash[:on_action] == :create
opts[:if] = :new?
elsif hash[:on_action] == :destroy
opts[:when] = :destroy
end
return hash[:model_name].descendants.to_a.map{|model| model.validates_with_method(function_name, opts)}
end
def self.remove_rule(hash)
self.remove(hash)
end
#not to be called directly, call remove_rule instead
#to remove a validation
def self.remove(hash)
if(hash[:model_name].class != Class)
hash[:model_name] = Kernel.const_get(hash[:model_name].camelcase)
end
hash[:name] = hash[:name].to_s.downcase.gsub(" ", "_")
if hash[:model_name].new.respond_to?(hash[:name])
hash[:model_name].send(:define_method, hash[:name]) do
return true #overwrite the old function
end
return true
else
return false
end
end
def self.rules
@@rules
end
private
def get_condition(condition)
if condition.class==Array
condition[1] = :< if hash[:condition][1] == :less_than
condition[1] = :<= if hash[:condition][1] == :less_than_equal
condition[1] = :> if hash[:condition][1] == :greater_than
condition[1] = :>= if hash[:condition][1] == :greater_than_equal
condition[1] = :== if hash[:condition][1] == :equal
validator = Proc.new{|obj|
condition[0].split(".").map{|x|
x.to_sym
}.inject(obj){|s,x|
s.send(x)
}.send(condition[1], condition[2])
}
end
validator
end
end
end
end
| true |
d0aa5dd0b1b703f7bc6d646502e79ef6284be5aa | Ruby | rclegend/bewd_11_nyc_homework | /_Kelly_Lo/Midterm/lib/Images.rb | UTF-8 | 202 | 2.890625 | 3 | [] | no_license | class Image
attr_accessor :image_url :username :tags :likes
def initialize (image_url, username, tags, likes)
@image_url = image_url
@username = username
@tags = tags
@likes = likes
end
end
| true |
09c64ff25dae8816bb54fab73715aa056c45ebc7 | Ruby | wilcoxst/red_lodge_town_series.1 | /app/models/time_entry.rb | UTF-8 | 2,228 | 3.09375 | 3 | [] | no_license | require 'csv'
class TimeEntry < ActiveRecord::Base
belongs_to :week
belongs_to :racer
def self.getSet(gender, discipline, classification, week)
set = TimeEntry.joins(:racer).where({racers: {gender: gender, discipline_id: discipline.id, classification_id: classification.id},
time_entries: {week_id: week.id}}).sort_by { |time_entry| time_entry.combined }
set.each_with_index do |time_entry, i|
time_entry = set[i]
time_entry.set_points i+1
# handle ties (if times of previous skier are the same, give this racer the same number of points)
if (i > 0)
previous_time_entry = set[i-1]
if time_entry.combined == previous_time_entry.combined
time_entry.set_points(previous_time_entry.get_points)
end
end
end
set
end
def self.last_week_entries
last_week = Week.get_last_week
puts 'last_week.id: ' + last_week.id.to_s
TimeEntry.joins(:racer).where(week_id: last_week.id).sort_by { |time_entry| time_entry.combined}
end
def combined
run1 + run2
end
def set_points(points)
@points = points
end
def get_points
@points
end
def exclude_from_team
@excluded_from_team = true
end
def is_excluded_from_team?
not @excluded_from_team.nil?
end
def to_s
"run1: #{run1}, run2: #{run2}"
end
def self.import_csv(file)
# Entries will be applied to latest week
week_id = Week.get_max_week_id
puts 'last week id is ' + week_id.to_s
# We only care about which racer, and the 2 run times
#data = file.read()
file_name = file.path
text = File.read(
file_name,
{encoding: 'bom|utf-8'}
)
CSV.parse(text, headers:true, ) do |row|
if row['Id'] != nil and row['Run1'] != nil and row['Run2'] != nil
time_entry = TimeEntry.new
time_entry.week_id = week_id
puts 'row[:id] is ' + row['Id']
puts 'row[:id].to_i is ' + row['Id'].to_i.to_s
time_entry.racer_id = row['Id'].to_i
time_entry.run1 = row['Run1'].to_f
time_entry.run2 = row['Run2'].to_f
time_entry.save
else
puts 'empty row in csv'
end
end
end
end
| true |
4aa771d03def2b5b1967889cdabe2a0c8f9ea2a4 | Ruby | Pantapone/RB101 | /small_problems/easy_9.rb | UTF-8 | 2,899 | 3.9375 | 4 | [] | no_license | #1
def greetings(arr, hash)
name = arr.join(" ")
title = hash[:title]
occupation = hash[:occupation]
puts "=> Hello, #{name}! Nice to have a #{title} #{occupation} around."
end
greetings(['John', 'Q', 'Doe'], { title: 'Master', occupation: 'Plumber' })
#2
#3
def negative(num)
num.negative? ? num : -num
end
negative(5) == -5
negative(-3) == -3
negative(0) == 0 # There's no such thing as -0 in ruby
#4
# - 5, 4, 3, 2, 1 until int == 0
# 1 + 2 + 3 + 4, until
# int -> to array
# 1.upto(5)
def sequence(int)
arr = "1".upto(int.to_s).to_a
arr.map {|ele| ele.to_i}
end
def sequence_2(int)
1.upto(int).to_a {|i| i }
end
p sequence(5) == [1, 2, 3, 4, 5]
p sequence(3) == [1, 2, 3]
p sequence(1) == [1]
p sequence_2(5) == [1, 2, 3, 4, 5]
p sequence_2(3) == [1, 2, 3]
p sequence_2(1) == [1]
p sequence_2(-1)
def sequence_3(int)
if int > 0
1.upto(int).to_a {|i| i }
else
int.upto(1).to_a {|i| i }
end
end
p sequence_3(5)
p sequence_3(0)
p sequence_3(-5)
#5
def uppercase?(string)
string.upcase == string ? true : false
end
p uppercase?('t') == false
p uppercase?('T') == true
p uppercase?('Four Score') == false
p uppercase?('FOUR SCORE') == true
p uppercase?('4SCORE!') == true
p uppercase?('') == true
#6
def word_lengths(string)
arr = string.split(" ")
arr.map do |word|
word << (" " + word.size.to_s)
end
end
p word_lengths("cow sheep chicken") == ["cow 3", "sheep 5", "chicken 7"]
p word_lengths("baseball hot dogs and apple pie") ==
["baseball 8", "hot 3", "dogs 4", "and 3", "apple 5", "pie 3"]
p word_lengths("It ain't easy, is it?") == ["It 2", "ain't 5", "easy, 5", "is 2", "it? 3"]
p word_lengths("Supercalifragilisticexpialidocious") ==
["Supercalifragilisticexpialidocious 34"]
p word_lengths("") == []
#7
def swap_name(string)
words = string.split
new_string = ""
words.reverse_each do |word|
new_string << word.to_s + ", "
end
new_string.chop.chop
end
def swap_name_2(string)
words = string.split
words.reverse!
"#{words[0]}, #{words[1]}"
end
def swap_name_3(string)
words = string.split
"#{words[1]}, #{words[0]}"
end
def swap_name_4(string)
string.split.reverse.join(", ")
end
p swap_name('Joe Roberts')
p swap_name_2('Joe Roberts')
p swap_name_3('Joe Roberts')
p swap_name_4('Joe Roberts')
#8
#9
def get_grade(grade1, grade2, grade3)
mean = (grade1 + grade2 + grade3) / 3
case mean
when 0..60 then "F"
when 60..70 then "D"
when 70..80 then "C"
when 80..90 then "B"
when 90..100 then "A"
else "You got extra points!"
end
end
p get_grade(95, 90, 93) == "A"
p get_grade(50, 50, 95) == "D"
#10
def buy_fruit(arr)
new_arr = []
arr.each do |subarray|
subarray[1].times do |i|
new_arr << subarray[0]
end
end
new_arr
end
p buy_fruit([["apples", 3], ["orange", 1], ["bananas", 2]]) ==
["apples", "apples", "apples", "orange", "bananas","bananas"]
| true |
d897df3ca34a0a72a0c15c1dee8f8c39348ae5e8 | Ruby | hoelzro/dev-study | /maze-generation/maze.rb | UTF-8 | 3,681 | 3.40625 | 3 | [] | no_license | class Edge
def initialize
@closed = true
end
def open?
not closed?
end
def closed?
@closed
end
def open
@closed = false
end
end
class Cell
attr_reader :x
attr_reader :y
def initialize(maze, x, y)
@maze = maze
@x = x
@y = y
@edges = []
end
def open_outer_edge
# XXX should the RNG be used to select which edge for corners?
if @maze.top_row.include? self
top_edge.open
return
end
if @maze.bottom_row.include? self
bottom_edge.open
return
end
if @maze.left_column.include? self
left_edge.open
return
end
if @maze.right_column.include? self
right_edge.open
return
end
end
%w(top bottom left right).each_with_index do |name, index|
define_method (name + '_edge').to_sym do
@edges[index]
end
define_method (name + '_edge=').to_sym do |value|
@edges[index] = value
end
end
end
class Maze
attr_accessor :start
attr_accessor :finish
def initialize(width, height)
if width != height
raise 'Non-square mazes are not yet supported'
end
@rows = build_rows width, height
build_edges
end
def each_cell(&block)
each_row do |row|
row.each &block
end
end
def each_row(&block)
@rows.each &block
end
def each_column
first_row = @rows.first
(0 .. first_row.length - 1).each do |index|
column = @rows.map { |row| row[index] }
yield column
end
end
def edge_cells
[ top_row, bottom_row, left_column, right_column ].flatten.uniq
end
def start=(cell)
@start = cell
cell.open_outer_edge
end
def finish=(cell)
@finish = cell
cell.open_outer_edge
end
def top_row
@rows[0]
end
def bottom_row
@rows[-1]
end
def left_column
columns[0]
end
def right_column
columns[-1]
end
def find_neighbors(cell)
x = cell.x
y = cell.y
neighbors = []
if x != 0
neighbors.push @rows[y][x - 1]
end
if y != 0
neighbors.push @rows[y - 1][x]
end
if x != @rows.length - 1
neighbors.push @rows[y][x + 1]
end
if y != columns.length - 1 # XXX inefficient
neighbors.push @rows[y + 1][x]
end
neighbors
end
def open_edge(cell1, cell2)
if cell1.x < cell2.x
cell1.right_edge.open
elsif cell1.x > cell2.x
cell1.left_edge.open
elsif cell1.y < cell2.y
cell1.bottom_edge.open
else
cell1.top_edge.open
end
end
def width
@rows[0].size
end
def height
@rows.size
end
private
def columns
columns = []
each_column do |column|
columns.push column
end
columns
end
def build_rows(width, height)
(1 .. height).map do |y|
(1 .. width).map do |x|
Cell.new self, x - 1, y - 1
end
end
end
def build_edges
each_row do |row|
row.inject do |left, right|
left.right_edge = right.left_edge = Edge.new
right
end
end
index = 0
last_column_index = @rows.first.length - 1
each_column do |column|
column.inject do |top, bottom|
top.bottom_edge = bottom.top_edge = Edge.new
bottom
end
if index == 0
column.each do |cell|
cell.left_edge = Edge.new
end
elsif index == last_column_index
column.each do |cell|
cell.right_edge = Edge.new
end
end
index += 1
end
@rows.first.each do |cell|
cell.top_edge = Edge.new
end
@rows.last.each do |cell|
cell.bottom_edge = Edge.new
end
end
end
| true |
8e4b8f1dd7bc06d52891be7cae66f7b117a97d4a | Ruby | harrietc52/the_well_grounded_rubyist | /chapter_08/numerical_objects.rb | UTF-8 | 164 | 3.578125 | 4 | [] | no_license | n = 99.8
m = n.round
puts m
x = 12
if x.zero?
puts "x is zero"
else
puts "x is not zero"
end
puts "The ASCII character equivalent of 97 is #{97.chr}"
| true |
0f4c40a0b84661989fa75ddc0cf4e059d7584d21 | Ruby | CenCalRuby/test-doubles | /lib/twitter_client.rb | UTF-8 | 401 | 2.796875 | 3 | [
"MIT"
] | permissive | require 'net/http'
require 'uri'
require 'json'
class TwitterClient
def self.post(username, message)
uri = URI("https://api.twitter.com/#{username}/tweets")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path, {'Content-Type' =>'application/json'})
request.body = {:tweet => message}.to_json
http.request(request)
end
end
| true |
b7b10ee0f8fcc873345f9f70cb5eebf7cf6e0365 | Ruby | Quang7hong81/ruby-xdr | /spec/lib/xdr/dsl/enum_spec.rb | UTF-8 | 928 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | require "spec_helper"
describe XDR::DSL::Enum, "#member" do
subject do
Class.new(XDR::Enum) do
member :one, 1
member :two, 2
end
end
it "adds to the members collection of the class" do
expect(subject.members.length).to eq(2)
expect(subject.members[:one]).to eq(subject.one)
expect(subject.members[:two]).to eq(subject.two)
end
it "raises ArgumentError if a non-integer value is used" do
expect {
Class.new(XDR::Enum) do
member :one, "hi!"
end
}.to raise_error(ArgumentError)
end
end
describe XDR::DSL::Enum, "#seal" do
subject do
Class.new(XDR::Enum) do
member :one, 1
member :two, 2
seal
end
end
it "marks the class as sealed" do
expect(subject.sealed).to eq(true)
end
it "prevents you from adding members after being sealed" do
expect { subject.member :three, 3 }.to raise_error(ArgumentError)
end
end
| true |
f0f03309fc7b3f1725a7b0bc4eceeafeb630841c | Ruby | camsys/transam_core | /spec/models/notice_spec.rb | UTF-8 | 3,166 | 2.59375 | 3 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | require 'rails_helper'
RSpec.describe Notice, :type => :model do
let(:notice) {build_stubbed(:notice)}
#------------------------------------------------------------------------------
#
# Class Methods
#
#------------------------------------------------------------------------------
describe '.new' do
it 'validates the correct fields' do
n = Notice.new(subject: nil, details: nil, notice_type: nil, display_datetime: nil, end_datetime: nil, organization: nil)
# presence validators
expect(n).not_to be_valid
# display- and end_datetime have defaults set, and organization allows nil. Leaves three invalid fields
expect(n.errors.count).to be(3)
end
it 'accepts valid virtual attributes' do
n = Notice.new(subject: "Test", summary: "Summary", notice_type: NoticeType.first,
display_datetime_date: "10-17-2014", display_datetime_hour: "15",
end_datetime_date: "10-17-2014", end_datetime_hour: "16")
expect(n).to be_valid
expect(n.display_datetime).to eq(Time.new(2014, 10, 17, 15))
expect(n.end_datetime).to eq(Time.new(2014, 10, 17, 16))
end
end
#------------------------------------------------------------------------------
#
# Scope Methods
#
#------------------------------------------------------------------------------
# Scopes are tested by changes, since they require changes to the DB
describe '.system_level_notices' do
it 'returns notices with no organization set' do
expect{
FactoryBot.create(:system_notice)
}.to change{Notice.system_level_notices.count}.by(1)
end
end
describe '.active_for_organizations' do
it 'returns system notices and organization-specific notices' do
test_org = create(:organization)
expect{
FactoryBot.create(:system_notice)
FactoryBot.create(:notice, organization: test_org)
}.to change{Notice.active_for_organizations([test_org]).count}.by(2) # 1 for system, 1 for organization
end
end
#------------------------------------------------------------------------------
#
# Instance Methods
#
#------------------------------------------------------------------------------
describe '#duration_in_hours' do
it 'returns a whole number' do
notice.display_datetime = DateTime.new(2014, 10, 17, 0)
notice.end_datetime = DateTime.new(2014, 10, 17, 10, 30) # 10.5 hours later
expect(notice.duration_in_hours).to be(11)
end
it 'can handle simultaneous start and end' do
notice.display_datetime = DateTime.new(2014, 10, 17, 0)
notice.end_datetime = DateTime.new(2014, 10, 17, 0)
expect(notice.duration_in_hours).to be(0)
end
end
describe '#set_defaults' do
it 'sets the active, start and stop attributes' do
n = Notice.new
expect(n.active).to be(true)
expect(n.display_datetime).to eq(DateTime.current.beginning_of_hour)
expect(n.end_datetime).to eq(DateTime.current.end_of_day.change(usec: 0)) #change(usec: 0) rounds down to the nearest second so 23:59:59 instead of 23:59:59.99999
end
end
end
| true |
2c4928e27ddef8aa525712ac29e64848f6e77170 | Ruby | nasum/scracket_tool | /scracket_tool.rb | UTF-8 | 555 | 2.640625 | 3 | [] | no_license | require 'thor'
require './lib/db_connector.rb'
class ScracketTool < Thor
desc "hello NAME", "say hello to NAME"
def hello(name)
puts "Hello #{name}"
end
desc "show-tables DBNAME", "show table"
option :h
option :u
option :p
def show_tables(db_name)
DBConnector.show_tables(db_name, options[:h], options[:u], options[:p])
end
desc "images QUERY", "image download"
option :h
option :u
option :p
def images(query)
DBConnector.connect(query, options[:h], options[:u], options[:p])
end
end
ScracketTool.start(ARGV)
| true |
4ea99afa66124f1464fb0b704dd54a88dc0521c5 | Ruby | cielavenir/procon | /codeforces/tyama_codeforces719B.rb | UTF-8 | 131 | 2.890625 | 3 | [
"0BSD"
] | permissive | #!/usr/bin/ruby
gets
s=[0]*4
x=0
gets.chomp.chars{|c|
f=c!='r' ? 2 : 0
s[f|x]+=1
x^=1
}
p [[s[0],s[3]].max,[s[1],s[2]].max].min
| true |
f08ff49f3308dd80d97508cddb6904a72b4e75e5 | Ruby | VishnuHaasan/KnightTravails | /main.rb | UTF-8 | 1,336 | 3.875 | 4 | [] | no_license | class Knight
STEPS = [[1,2],[1,-2],[-1,2],[-1,-2],[2,1],[2,-1],[-2,1],[-2,-1]]
attr_accessor :steps, :position, :parent
@@visited = []
def initialize(position,parent)
@position = position
@steps = []
@parent = parent
end
def check(element)
return element[0]>7 || element[0]<0 || element[1]>7 || element[1]<0
end
def possible_paths
return STEPS.map{|e| [e[0]+@position[0],e[1]+@position[1]]}.reject{|e| check(e)}.reject{|e| @@visited.include?(e)}
.map{|e| Knight.new(e,self)}
end
end
def print_path(n1,n2)
puts "The path followed : "
queue = []
until n1.parent === nil do
n1 = n1.parent
queue.push(n1)
end
position = queue.map {|e| e.position}
p position.reverse
end
def knight_travails
puts "enter the x value of starting coordinate: "
x_start = gets.chomp.to_i
puts "enter the y value of starting coordinate: "
y_start = gets.chomp.to_i
puts "enter the x value of destination coordinate: "
x_dest = gets.chomp.to_i
puts "enter the y value of destination coordinate: "
y_dest = gets.chomp.to_i
n1 = [x_start,y_start]
n2 = [x_dest,y_dest]
q = []
t = n2
new_knight = Knight.new(n1,nil)
while new_knight.position != t do
new_knight.possible_paths.map{|e| q.push(e)}
new_knight = q.shift
end
print_path(q[0],n2)
end
knight_travails | true |
9b566d1298c5f4668a9cf193036dec4576ae8a07 | Ruby | kixton/rock-paper-scissors | /spec/rock_pape_scis_spec.rb | UTF-8 | 1,010 | 2.90625 | 3 | [
"MIT"
] | permissive | require_relative './spec_helper.rb'
describe 'RockPapeScis' do
let(:kim) { {id: 1, move: 'rock'} }
let(:jeff) { {id: 2, move: 'paper'} }
let(:peng) { {id: 3, move: 'scissors'} }
let(:pong) { {id: 4, move: 'scissors'} }
describe 'play' do
it 'player has id and move' do
expect(kim[:id]).to eq(1)
expect(kim[:move]).to eq('rock')
end
it 'rock beats scissors' do
game = RockPapeScis.play(player_1: kim, player_2: peng)
expect(kim[:move]).to eq('rock')
expect(peng[:move]).to eq('scissors')
expect(game).to eq(1)
end
it 'paper beats rock' do
game = RockPapeScis.play(player_1: jeff, player_2: kim)
expect(game).to eq(2)
end
it 'scissors beats paper' do
game = RockPapeScis.play(player_1: peng, player_2: jeff)
expect(game).to eq(3)
end
it 'two scissors tie' do
game = RockPapeScis.play(player_1: peng, player_2: pong)
expect(game).to eq(-1)
end
end # end of play
end
| true |
f18ee7ab40daa75eae5d6c885490a0e47c8735c4 | Ruby | mfirmanakbar/ruby-basic | /17-reading-files.rb | UTF-8 | 533 | 3.59375 | 4 | [] | no_license | # File.open("D:/ruby/ruby-basic/17-students-list.txt")
# r: read, storing do into variable files
File.open("17-students-list.txt", "r") do |file|
# puts file.read() #read all
# puts file.read().include? "Akbar" #read all and checking
# puts file.readline() #read first line
# puts file.readlines()[2] #getting index row 2 --> Ahmad, 23
# puts file.readchar() #read foreach line
for line in file.readlines()
puts line
end
end
puts "\n"
filex = File.open("17-students-list.txt", "r")
puts filex.read
filex.close()
| true |
30626c0fc201a4a347f4d195f25ab35ddf35d655 | Ruby | cha63506/rbx-trepanning | /processor/command/info_subcmd/breakpoints.rb | UTF-8 | 2,082 | 2.703125 | 3 | [] | no_license | require 'rubygems'; require 'require_relative'
require_relative '../base/subcmd'
class Trepan::Subcommand::InfoBreakpoints < Trepan::Subcommand
HELP = <<-EOH
info breakpoints [num1 ...] [verbose]
Show status of user-settable breakpoints. If no breakpoint numbers are
given, the show all breakpoints. Otherwise only those breakpoints
listed are shown and the order given. If VERBOSE is given, more
information provided about each breakpoint.
The "Disp" column contains one of "keep", "del", the disposition of
the breakpoint after it gets hit.
The "enb" column indicates whether the breakpoint is enabled.
The "Where" column indicates where the breakpoint is located.
EOH
MIN_ABBREV = 'br'.size
NAME = File.basename(__FILE__, '.rb')
PREFIX = %w(info breakpoints)
SHORT_HELP = 'Status of user-settable breakpoints'
def run(args)
# FIXME: Originally was
# section "Breakpoints"
# Add section?
show_all =
if args.size > 2
opts = {
:msg_on_error =>
"An '#{PREFIX.join(' ')}' argument must eval to a breakpoint between 1..#{@proc.brkpts.max}.",
:min_value => 1,
:max_value => @proc.brkpts.max
}
bp_nums = @proc.get_int_list(args[2..-1])
false
else
true
end
bpmgr = @proc.brkpts
if bpmgr.empty? && @proc.dbgr.deferred_breakpoints.empty?
msg('No breakpoints.')
else
# There's at least one
bpmgr.list.each do |bp|
msg "%3d: %s" % [bp.id, bp.describe]
end
msg('Deferred breakpoints...')
@proc.dbgr.deferred_breakpoints.each_with_index do |bp, i|
if bp
msg "%3d: %s" % [i+1, bp.describe]
end
end
end
end
end
if __FILE__ == $0
# Demo it.
require_relative '../../mock'
name = File.basename(__FILE__, '.rb')
dbgr, cmd = MockDebugger::setup('info')
subcommand = Trepan::Subcommand::InfoBreakpoints.new(cmd)
puts '-' * 20
subcommand.run(%w(info break))
puts '-' * 20
subcommand.summary_help(name)
puts
puts '-' * 20
end
| true |
16142b2f87deea05ef891aeae1ee19e563efd06b | Ruby | proprietary/twitter-name-finder | /twitter-name-finder.rb | UTF-8 | 6,215 | 3.1875 | 3 | [] | no_license | #!/usr/bin/env ruby
# coding: utf-8
require 'unirest'
require 'optparse'
class Twitter
def initialize
@csrf_token = self.get_csrf_token
@backoff = 2.0 # seconds to wait before hitting Twitter again
end
def get_csrf_token
r = Unirest.get "https://twitter.com"
r.headers[:set_cookie].each do |hdr|
return $~[1] if (/ct0=(\w+);/ =~ hdr) != nil
end
raise "Unable to find CSRF token. Update the method 'get_csrf_token'."
end
def available? name
sleep @backoff
raise "Twitter requires all names to be at least 5 characters" if name.size < 5
r = Unirest.get "https://api.twitter.com/i/users/username_available.json?username=#{name}", headers: {"x-csrf-token" => @csrf_token}
STDERR.puts "Unable to ask Twitter if '#{name}' is available. HTTP status code returned: #{r.code}" if r.code != 200
case r.code
when 200
when 429
@backoff *= 2
puts "You have been hitting Twitter too hard. "\
"Waiting #{@backoff} seconds before making a request from now on. "\
"But first we're actually waiting 5 minutes for the dust to settle."
sleep 60*5 # Wait 5 minutes before even trying again
self.available? name # TODO potential stack overflow
else
puts "HTTP status code = #{r.code}"
raise "Unable to ask Twitter if '#{name}' is available. You probably need "\
"to change the implementation of `available?`."
end
raise "Twitter gave us an unexpected response when we asked "\
"to check the availability of '#{name}'. Update the "\
"Twitter::available? method to the new "\
"response schema." unless r.body.has_key? "valid"
return r.body["valid"]
end
end
class NameGenerator
attr_accessor :must_start_with, :conditions
def initialize n_chars
@n_chars = n_chars
@skip_until_this_name = nil
@must_start_with = ""
@last = -1
@alphabet = ('a'..'z').to_a # everything must be unique!
# `conditions` is an array of procs that take the username and determine whether to use it
@conditions = Array.new
@number_when_alphabet_sequence_overflows = @alphabet.size**n_chars
end
def alphabet= alphabet
@alphabet = alphabet.uniq
end
def skip_until_this_name= skip_until_this_name
@skip_until_this_name = skip_until_this_name
@last = self.encode_name_to_number(skip_until_this_name)
end
def decode_number_to_alphabet_sequence n
=begin
The alphabet sequence is an array of characters from our alphabet.
Each username to try is identified by a number, which is here decoded to an alphabet sequence aka a string representing the name to try. This allows to easily stop and start the lengthy checking of usernames.
=end
alphabet_size = @alphabet.size
ret = Array.new @n_chars, @alphabet[0]
i = @n_chars - 1
while n > 0 and i >= 0
ret[i] = @alphabet[n % alphabet_size]
n /= alphabet_size
i -= 1
end
ret
end
def encode_name_to_number name
ret = 0
alphabet_size = @alphabet.size
name.chars.reverse.each_with_index do |c, pow|
idx = @alphabet.index c
ret += (alphabet_size**pow) * idx
end
ret
end
def current_name
self.decode_number_to_alphabet_sequence(@last).join
end
def next
@last += 1
while @last < @number_when_alphabet_sequence_overflows \
and not @conditions.all? {|p| p.call self.current_name}
@last += 1
end
return nil if @last >= @number_when_alphabet_sequence_overflows
self.current_name
end
end
MY_VOWELS = "aeiou".split ""
def count_vowels s
cnt = 0
s.each_char {|c| cnt += 1 if MY_VOWELS.include? c}
cnt
end
if ARGV.size > 0
flags = {:prefix_str => ""}
conditions = Array.new
OptionParser.new do |o|
o.banner = "Usage: ./twitter-name-finder.rb [options]"
o.on(:REQUIRED, "--max-chars n", Integer, "Max chars in username") do |mx|
flags[:max_chars] = mx
end
o.on("--min-vowels mv", Integer) do |mv|
conditions << lambda do |username|
count_vowels(username) >= mv
end
end
o.on("--no-repeated-chars") do
conditions << lambda do |username|
return true if username.size < 2
for i in 1..(username.size-1) do
return false if username[i] == username[i-1]
end
true
end
end
o.on("--prefix STR", String, "This string must be the first characters of the username") do |prefix_str|
raise "You asked for a prefix string that is longer than or equal to the maximum characters you asked for. That doesn't make any sense." if prefix_str.size >= flags[:max_chars]
flags[:prefix_str] = prefix_str
end
o.on("--skip-ahead-until USERNAME", String,
"Username that the name generator will advance to before "\
"asking Twitter. Useful when restarting from a crash.") do |s|
flags[:skip_until_this_name] = s
end
o.on("-h", "--help", "Display the complete help message") do
puts o
exit
end
end.parse!
twtr = Twitter.new
ng = NameGenerator.new flags[:max_chars] - flags[:prefix_str].size
ng.conditions = conditions
ng.must_start_with = flags[:prefix_str]
if flags.has_key? :skip_until_this_name
if flags[:prefix_str].size > 0 and flags[:prefix_str] != flags[:skip_until_this_name].slice(0, flags[:prefix_str].size)
puts "If you are skipping ahead until a username, "\
"the first characters of that username must be "\
"the same as that of the prefix string you also "\
"provided."
exit
elsif flags[:prefix_str].size > 0
ng.skip_until_this_name =
flags[:skip_until_this_name].slice flags[:prefix_str].size..-1
else
ng.skip_until_this_name = flags[:skip_until_this_name]
end
end
while (generated = ng.next) != nil
name_to_try = "#{flags[:prefix_str]}#{generated}"
# puts "trying #{name_to_try}…"
begin
available = twtr.available? name_to_try
# puts "#{name_to_try} was available? #{available}"
puts name_to_try if available
rescue => e # TODO this is a temporary hack
puts "Failed on #{name_to_try}"
puts e
redo
end
end
end
| true |
b298a6503d8e70deae9a27b9252ffe509eb8e7b0 | Ruby | barrym/penguin | /examples/Rakefile | UTF-8 | 1,765 | 3.046875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #! /usr/bin/env ruby
require '../lib/penguin'
def green(text)
"\e[32m#{text}\e[0m"
end
def red(text)
"\e[31m#{text}\e[0m"
end
# I apologise to the programming gods for what is about to happen
def as_table(data)
headers = data.first.keys.sort
widths = {}
data.each do |e|
e.each do |k,v|
bigger = k.to_s.size > v.to_s.size ? k.to_s.size : v.to_s.size
if widths[k] == nil || widths[k] < bigger
widths[k] = bigger
end
end
end
table = ""
# headers
table << "+"
headers.each do |h|
v = widths[h]
table << "-" * (v + 2) << "+"
end
table << "\n"
table << "|"
headers.each do |h|
table << " " << h << " " * (widths[h] - h.size + 1) << "|"
end
table << "\n"
table << "+"
headers.each do |h|
v = widths[h]
table << "-" * (v + 2) << "+"
end
table << "\n"
# rows
data.each do |e|
table << "|"
headers.each do |h|
if e[h].is_a?(TrueClass) || e[h].is_a?(FalseClass)
value = e[h] ? green(e[h].to_s) : red(e[h].to_s)
else
value = e[h].to_s
end
table << " " << value << " " * (widths[h] - e[h].to_s.size + 1) << "|"
end
table << "\n"
end
# footer
table << "+"
headers.each do |h|
v = widths[h]
table << "-" * (v + 2) << "+"
end
table << "\n"
table
end
namespace :daemons do
desc "Daemon status"
task :status do
c = Penguin::Client.new
status = c.status
puts "Monitor started : #{status["started_at"]}, uptime : #{status["uptime"]}"
data = []
status["daemons"].each do |key, value|
data << {"id" => key}.merge(value)
end
data = data.sort_by {|e| e["name"]}
puts as_table(data)
end
desc "Starts GUI"
task :gui do
Penguin::GUI.start
end
end
| true |
2b362134f4c28cb96be626500489bcd8667ca5ba | Ruby | imazen/ruby-vips-riapi | /web.rb | UTF-8 | 769 | 2.640625 | 3 | [] | no_license | require 'fileutils'
require 'riapi'
require 'sinatra'
require 'level1/image_resizer.rb'
IN_DIR = 'samples/images'
OUT_DIR = 'out'
# list available sample images
get '/samples' do
images = Dir[File.join(IN_DIR, '*')].map { |path| File.basename(path) }
images.map { |img| "#{img}\n" } .join
end
# perform an image resize
get '/:img' do |img|
# get sample images and check if the given image is among them
images = Dir[File.join(IN_DIR, '*')].map { |path| File.basename(path) }
unless images.include? img
raise Sinatra::NotFound
end
FileUtils.mkdir_p(OUT_DIR)
input_path = File.join(IN_DIR, img)
output_path = File.join(OUT_DIR, img)
ImageResizer.resize_image(input_path, output_path, RIAPI::parse_params(params))
"#{output_path}\n"
end
| true |
5bb4bff2d572b618262da1209404bdc03adc8856 | Ruby | danielribeiro/hamster | /lib/hamster/stack.rb | UTF-8 | 1,200 | 3.0625 | 3 | [
"MIT"
] | permissive | require 'forwardable'
require 'hamster/immutable'
require 'hamster/list'
module Hamster
def self.stack(*items)
items.reduce(EmptyStack) { |stack, item| stack.push(item) }
end
class Stack
extend Forwardable
include Immutable
def initialize
@list = EmptyList
end
def empty?
@list.empty?
end
def size
@list.size
end
def_delegator :self, :size, :length
def top
@list.head
end
def push(item)
transform { @list = @list.cons(item) }
end
def_delegator :self, :push, :<<
def pop
list = @list.tail
if list.empty?
EmptyStack
else
transform { @list = list }
end
end
def clear
EmptyStack
end
def eql?(other)
return true if other.equal?(self)
return false unless other.class.equal?(self.class)
@list.eql?(other.instance_eval{@list})
end
def_delegator :self, :eql?, :==
def to_a
@list.to_a
end
def_delegator :self, :to_a, :entries
def to_ary
@list.to_ary
end
def to_list
@list
end
def inspect
@list.inspect
end
end
EmptyStack = Stack.new
end
| true |
54acde4cbd3a709cee89550d5a353c2dbd57b261 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/etl/56320335ffc748a48cc551a5ba3700b6.rb | UTF-8 | 199 | 2.890625 | 3 | [] | no_license | class ETL
def self.transform(old)
new = {}
old.each do |score,letters|
letters.each do |letter|
new[letter.downcase] = score
end
end
new
end
end
| true |
9a01e79e7fa47b2fab5c0d7fe624f28311d0addc | Ruby | khu/newwordsforme | /app/models/tabs.rb | UTF-8 | 814 | 2.8125 | 3 | [] | no_license | class Tabs
def initialize
@tabs = []
end
def logged_in user
@tabs = []
@tabs << Tab.new(:home , 'Home', root_path)
@tabs << Tab.new(:addons, 'Addons', addons_path)
@tabs << Tab.new(:signin, 'Sign out', signout_path)
@tabs.reverse!
return self
end
def logged_out
@tabs = []
@tabs << Tab.new(:home , 'Home', root_path)
@tabs << Tab.new(:addons, 'Addons', addons_path)
@tabs.reverse!
return self
end
def select id
@tabs.each { |tab|
tab.css = "" unless tab.id == id
tab.css = "selected" if tab.id == id
}
return self
end
def each(&blk)
@tabs.each(&blk)
end
end
class Tab
attr_accessor :id, :label, :url, :css
def initialize id, label, url
@id = id
@label = label
@url = url
end
end
| true |
4270a28b4144f5a10818f318624e378013ec3229 | Ruby | xdkernelx/personality-analyzer | /app/helpers/result_helper.rb | UTF-8 | 2,427 | 2.78125 | 3 | [] | no_license | helpers do
MAX_SCORE = 100
NEG_TRAIT_SCORE_MULT = 0.125
# Original base score: 0.10
POS_TRAIT_SCORE_MULT = 0.05
DEDUCT_POINT = 5
EMPLOYER_REQS = ["Politician", "Charmer", "Closer", "Evangelist"]
def assessment
if logged_in?
@assessment = Assessment.find_by(user_id: @user.id)
end
end
def completed_at
assessment.updated_at.strftime('%b %d, %Y') if assessment.completed
end
def shorten(results)
shortened_results = {}
results['personality_types'].each do |personality|
shortened_results[personality['personality_type']['name']] = personality['score']
end
return shortened_results
end
# Subtracts from the MAX score
def simple_rate(results_arr)
result = MAX_SCORE
results_arr.each_with_index do |trait, idx|
if !EMPLOYER_REQS.include?(trait.first) && idx < EMPLOYER_REQS.length
multiplier = 1 - (idx * 0.2)
result -= DEDUCT_POINT * multiplier + (trait[1] * NEG_TRAIT_SCORE_MULT)
elsif EMPLOYER_REQS.include?(trait.first)
# Original didn't have plus(1), added since we weren't reducing results.
# Same goes for the else branch.
multiplier = (EMPLOYER_REQS.index(trait.first) - idx + 1).abs * 0.2
result -= ((MAX_SCORE - trait[1]) * POS_TRAIT_SCORE_MULT) * multiplier
else
multiplier = (results_arr.length - idx + 1) * 0.2
result -= DEDUCT_POINT * multiplier + (trait[1] * NEG_TRAIT_SCORE_MULT)
end
end
return result.round(2)
end
def slide_rate(slides_arr, current_score)
negative_questions = ["I'll Swallow You Whole",
"Revenge",
"I Could Hurt You"]
positive_questions = ["All Must Be Equal",
"I'm Working For You"]
slides_arr.each do |slide|
if negative_questions.include?(slide.caption) && slide.response
current_score -= 2
elsif positive_questions.include?(slide.caption) && !slide.response
current_score -= 1
elsif positive_questions.include?(slide.caption) && slide.response
current_score += 1
end
end
return current_score
end
def traitify_results
access = User.traitify_access
results = access.find_results(assessment.key)
slides = access.find_slides(assessment.key)
short_results = shorten(results)
return slide_rate(slides, simple_rate(short_results) )
end
end
| true |
5b39169f97be2d1f40299c170dc295a477e34839 | Ruby | whitemage12380/dungeon_generator | /lib/connector.rb | UTF-8 | 5,809 | 3.078125 | 3 | [] | no_license | require_relative 'configuration'
require_relative 'map_object'
require_relative 'map_object_square'
class Connector
include DungeonGeneratorHelper
attr_reader :map_object, :connecting_map_object, :square, :facing, :width, :map_x, :map_y
def initialize(map_object:, square: nil, facing: nil, width: nil, map_x: nil, map_y: nil)
@map_object = map_object
@square = square if square
@facing = facing if facing
@width = width
@map_x = map_x if map_x
@map_y = map_y if map_y
end
def type()
case self
when Door
return "door"
else
return "connector"
end
end
def exit_string(starting_connector = false, include_destination = true, include_coordinates = true)
case type
when "connector"
exit_type = "Exit"
when "door"
exit_type = door_description()
else
raise "Exit type #{type} not supported"
end
if starting_connector
connecting_to = @map_object.name
facing_string = opposite_facing(facing)
else
connecting_to = @connecting_map_object ? @connecting_map_object.name : "nothing!"
facing_string = @facing
end
return [
exit_type,
include_coordinates ? "at (#{map_x}, #{map_y})" : nil,
"facing #{facing_string}",
include_destination ? "to #{connecting_to}" : nil
].compact.join(" ")
end
def x()
map_x - map_object.map_offset_x
end
def y()
map_y - map_object.map_offset_y
end
def pos()
{x: x, y: y}
end
def map_pos()
{x: map_x, y: map_y}
end
# North/West-most map coordinates regardless of facing, shifting if facing East or South to align with the grid edge the door is on
def abs_map_pos()
cursor = new_cursor()
cursor.shift!(:right, width-1) if [:west, :south].include?(facing)
cursor.forward! if [:east, :south].include?(facing)
{x: cursor.map_x, y: cursor.map_y}
end
def new_cursor()
return Cursor.new(map: map_object.map,
x: x,
y: y,
facing: facing,
map_offset_x: map_object.map_offset_x,
map_offset_y: map_object.map_offset_y,
)
end
def connect_to(map_object)
@connecting_map_object = map_object
end
def disconnect()
@connecting_map_object = nil
end
# Returns true if there is a map object in front of the connector that can be connected to
def can_connect_forward?()
unless connecting_map_object.nil?
debug "Cannot connect forward because connector is already connected"
return false
end
map = @map_object.map
cursor = Cursor.new(map: map,
x: map_x,
y: map_y,
facing: facing)
cursor.forward!()
cursor.turn!(:back)
(@width-1).times do |p|
square = map.square(cursor.pos)
if square.nil? # Squares must exist
debug "Cannot connect forward because square #{p} is either solid rock or the end of the map"
return false
end
unless square.edges[cursor.facing] == :wall # Squares must have a wall between them and the connector
debug "Cannot connect forward because square #{p} does not have a wall against the connector"
return false
end
unless square.edges[cursor.left].nil? # Squares must not have anything between themselves
debug "Cannot connect forward because square #{p} has a wall or connector between it and square #{p+1}"
return false
end
cursor.shift!(:left)
end
square = map.square(cursor.pos)
if square.nil? # Last square must exist
debug "Cannot connect forward because square #{@width} is either solid rock or the end of the map"
return false
end
unless square.edges[cursor.facing] == :wall # Last square must have a wall between it and the connector
debug "Cannot connect forward because square #{@width} does not have a wall against the connector"
return false
end
return true
end
def connect_forward()
raise "Cannot connect forward!" unless can_connect_forward?
map = @map_object.map
cursor = Cursor.new(map: map,
x: map_x,
y: map_y,
facing: facing)
cursor.forward!()
cursor.turn!(:back)
cursor.shift!(:left, @width-1)
connecting_map_object = map.square(cursor.pos).map_object
log "Connecting #{@map_object.name} to #{connecting_map_object.name}"
connect_to(connecting_map_object)
other_cursor = Cursor.new(map: map,
x: cursor.x - connecting_map_object.map_offset_x,
y: cursor.y - connecting_map_object.map_offset_y,
facing: cursor.facing,
map_offset_x: connecting_map_object.map_offset_x,
map_offset_y: connecting_map_object.map_offset_y)
debug "Creating reciprocal connection back to #{@map_object.name}"
if self.kind_of? Door
other_connector = connecting_map_object.create_door(other_cursor, @width)
else
other_connector = connecting_map_object.create_connector(other_cursor, @width)
end
connecting_map_object.add_connector(other_connector, cursor: other_cursor)
other_connector.connect_to(@map_object)
end
def to_s()
output = self.kind_of?(Door) ? "Door: " : "Exit: "
output += "Connects from #{map_object.name} " if map_object
output += "Connects to #{connecting_map_object.name}. " if connecting_map_object
output += "facing: #{facing}, width: #{width}, coordinates: (#{map_x}, #{map_y})."
return output
end
end
| true |
b35b4c8dafd5f52d3fbf862601cfe1d6eb643895 | Ruby | fox3000wang/BASH_SHELL | /ruby/RubyLearning/1.5.Hash/4.rb | UTF-8 | 176 | 3.203125 | 3 | [] | no_license | a = {1 => "a", 2 => "b", 3 => "c"}
print "1: "
b = a.reject {|key, value| value == 'b'}
puts b.inspect
print "2: "
puts a.merge({1 => 'A', 3 => 'C', 4 => 'd'}).inspect | true |
5251f385435f62d9ba0ec60238f81ee27a534141 | Ruby | isundaylee/2048 | /lib/core.rb | UTF-8 | 1,918 | 3.71875 | 4 | [] | no_license | class GameCore
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
VALID = 0
INVALID = 1
WINNING = 2
LOSING = 3
attr_reader :dimension
attr_reader :board
def initialize(dimension = 4)
@dimension = dimension
@board = Array.new(dimension) { Array.new(dimension) }
2.times { generate_new_tile }
end
def move(direction)
old_board = (0...dimension).map { |x| (0...dimension).map { |y| @board[x][y] }}
# Allow me to implement only the LEFT direction by transposing and/or reversing
if (direction == UP || direction == DOWN)
@board = @board.transpose
end
if (direction == RIGHT || direction == DOWN)
@board.each { |x| x.reverse! }
end
winning = false
0.upto(dimension - 1) do |x|
@board[x].compact!
0.upto(@board[x].size - 2) do |i|
if @board[x][i] == @board[x][i + 1] && !@board[x][i].nil?
@board[x][i] *= 2
@board[x][i + 1] = nil
winning = true if @board[x][i] == 2048
end
end
@board[x].compact!
@board[x] << nil while @board[x].size < dimension
end
# Transpose and/or reverse back
if (direction == RIGHT || direction == DOWN)
@board.each { |x| x.reverse! }
end
if (direction == UP || direction == DOWN)
@board = @board.transpose
end
return WINNING if winning
0.upto(dimension - 1) do |x|
0.upto(dimension - 1) do |y|
if old_board[x][y] != @board[x][y]
generate_new_tile
return VALID
end
end
end
return INVALID
end
private
def generate_new_tile
tile = [2, 4].shuffle.first
x, y = (0...dimension).to_a.product((0...dimension).to_a).select { |x, y| @board[x][y].nil? }.shuffle.first
x.nil? ? nil : (@board[x][y] = tile)
end
def in_range?(x, y)
(x >= 0 && x < dimension) && (y >= 0 && y < dimension)
end
end
| true |
3be66f1de0a5f28aadae37da15d9670f5cff3480 | Ruby | facingsouth/project_tdd_minesweeper | /lib/minesweeper.rb | UTF-8 | 823 | 3.234375 | 3 | [] | no_license | require_relative './board.rb'
require_relative './space.rb'
require_relative './player.rb'
require 'yaml'
class Minesweeper
attr_reader :board, :player
def initialize
@board = Board.new
@player = Player.new
@file = File.new("save.txt", "w")
end
def play
@move = 0
until defeat?
@board.render
@move = @player.get_move
# break if defeat?
@board.reveal_space(@move)
save
end
@board.render
end
def game_end?
victory? || defeat? || quit?
end
def defeat?
puts @board.gamestate[@move]
@board.gamestate[@move].is_a_mine
end
def victory?
false
end
def quit?
false
end
def save
File.open("save.txt", "w") do |file|
file.write (@board.gamestate.to_yaml)
end
end
end
| true |
c90f54a1700ea8d8890b9b903e6311d2ad1e1424 | Ruby | mcbain220/intro_to_programming | /more_stuff/other_stuff_exercise_1.rb | UTF-8 | 181 | 2.875 | 3 | [] | no_license | # other stuff exercise 1
words = ["laboratory","experiment","Pan's Labyrinth", "elaborate", "polar bear"]
words.each do |word|
if word.downcase =~ /lab/
puts word
end
end
| true |
eece6862d7c9e0b2992f74caad1416e83c7c9054 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/bob/12c6939d57304267866de4dec7e98bc1.rb | UTF-8 | 636 | 3.90625 | 4 | [] | no_license | class Bob
def hey(message)
return 'Fine. Be that way!' if silent? message
return 'Woah, chill out!' if shouting? message
return 'Sure.' if question? message
'Whatever.'
end
private
def silent?(message)
message.strip.empty?
end
def question?(message)
message.end_with? '?'
end
def shouting?(message)
already_upcased?(message) && contains_letters?(message)
end
def already_upcased?(str)
str.upcase!.nil? # String#upcase! returns nil if no changes made
end
def contains_letters?(str)
str.upcase =~ /[A-Z]/ # ensures message contains letters
end
end
| true |
f4e2fd641990fd29f65e6ea7ab0ef26d5ab5ec80 | Ruby | lly123/FT | /_0.rb | UTF-8 | 3,191 | 2.5625 | 3 | [] | no_license | alias L lambda
$_0C = L{|x| L{|y| L{|f| f[x][y]}}}
$_0Car = L{|p| p[L{|x| L{|y| x}}]}
$_0Cdr = L{|p| p[L{|x| L{|y| y}}]}
$_Y = L{|f| L{|g|
u = L{|x| f[ L{|g| x[x][g]} ]}
u[u][g]}}
# ---------------------
$_00 = L{|f| L{|x| x}}
$_01 = L{|f| L{|x| f[x]}}
$_0Add1 = L{|n| L{|f| L{|x| f[n[f][x]] }}}
$_0Add = L{|n| L{|m| n[$_0Add1][m]}}
$_02 = $_0Add[$_01][$_01]
$_03 = $_0Add[$_01][$_02]
$_04 = $_0Add1[$_03]
$_05 = $_0Add1[$_04]
$_06 = $_0Add1[$_05]
$_07 = $_0Add1[$_06]
$_08 = $_0Add1[$_07]
$_09 = $_0Add1[$_08]
$_010 = $_0Add1[$_09]
$_011 = $_0Add1[$_010]
$_012 = $_0Add1[$_011]
$_013 = $_0Add1[$_012]
$_014 = $_0Add1[$_013]
$_015 = $_0Add1[$_014]
$_016 = $_0Add1[$_015]
$_017 = $_0Add1[$_016]
$_018 = $_0Add1[$_017]
$_0Pow = L{|n| L{|m| m[n]}}
# ---------------------
#TRUE := λx.λy.x
#FALSE := λx.λy.y
#AND := λp.λq.p q p
#OR := λp.λq.p p q
#NOT := λp.λa.λb.p b a
#IFTHENELSE := λp.λa.λb.p a b
$_0TRUE = L{|x| L{|y| x}}
$_0FALSE = L{|x| L{|y| y}}
$_0AND = L{|p| L{|q| p[q][p] }}
$_0OR = L{|p| L{|q| p[p][q] }}
$_0NOT = L{|p| L{|x| L{|y| p[y][x]}}}
$_0IF = L{|p| L{|x| L{|y| p[x][y]}}}
_0IsZERO = L{|n| n[L{|x| $_0FALSE}][$_0TRUE]}
# ---------------------
#PRED := λn.λf.λx.n (λg.λh.h (g f)) (λu.x) (λu.u)
#SUB := λn.λm.m PRED n
_0Sub0 = L{|n| L{|f| L{|x| n[ L{|g| L{|h| h[g[f]]}} ][ L{|u| x} ][ L{|u| u} ] }}}
$_0Sub = L{|n| L{|m| m[_0Sub0][n]}}
$_0Sub1 = L{|n| $_0Sub[n][$_01]}
#MULT := λn.λm.n (PLUS m) 0
$_0Mul = L{|n| L{|m| n[$_0Add[m]][$_00]}}
# ---------------------
#LEQ := λn.λm.IS_ZERO (SUB n m)
_0LEQ = L{|n| L{|m| _0IsZERO[$_0Sub[n][m]]}}
$_0EQ = L{|n| L{|m| $_0IF[$_0AND[_0LEQ[n][m]][_0LEQ[m][n]]][$_0TRUE][$_0FALSE]}}
$_0LT = L{|n| L{|m| $_0IF[$_0AND[_0LEQ[n][m]][$_0NOT[$_0EQ[n][m]]]][$_0TRUE][$_0FALSE]}}
$_0GT = L{|n| L{|m| $_0IF[$_0AND[$_0NOT[_0LEQ[n][m]]][$_0NOT[$_0EQ[n][m]]]][$_0TRUE][$_0FALSE]}}
# ---------------------
# Logic With Pair
=begin
$_0IF = L{|b| L{|m| L{|n| b[$_0C[m][n]]}}}
$_0TRUE = $_0Car
$_0FALSE = $_0Cdr
=end
# Arithmetic with Pair
=begin
$_0Sub1 = L{|n| L{|f| L{|x|
w = L{|f| L{|p| $_0C[$_0FALSE][$_0IF[$_0Car[p]][$_0Cdr[p]][ f[$_0Cdr[p]] ]]}}
$_0Cdr[n[w[f]][$_0C[$_0TRUE][x]]]
}}}
_0Sub0 = L{|s| L{|n| L{|m| $_0IF[_0IsZERO[m]][n][ L{|g| s[$_0Sub1[n]][$_0Sub1[m]][g]} ]}}}
$_0Sub = $_Y[_0Sub0]
_Mul0 = L{|s| L{|n| L{|m| $_0IF[_0IsZERO[m]][$_00][ L{|g| $_0Add[n][s[n][$_0Sub1[m]]][g]} ]}}}
$_0Mul = $_Y[_Mul0]
=end
# Logic Expression With Low Performance
=begin
$_0AND = L{|x| L{|y| $_0IF[x][ L{|g| $_0IF[y][$_0TRUE][$_0FALSE][g]} ][$_0FALSE]}}
$_0OR = L{|x| L{|y| $_0IF[x][$_0TRUE][ L{|g| $_0IF[y][$_0TRUE][$_0FALSE][g]} ]}}
$_0NOT = L{|x| $_0IF[x][$_0FALSE][$_0TRUE]}
_CMP0 = L{|s| L{|n| L{|m|
$_0IF[$_0AND[_0IsZERO[n]][_0IsZERO[m]]][$_00][
$_0IF[_0IsZERO[n]][$_01][
$_0IF[_0IsZERO[m]][$_02][
L{|g| s[$_0Sub1[n]][$_0Sub1[m]][g]}
]
]
]
}}}
_CMP = $_Y[_CMP0]
$_0EQ = L{|n| L{|m| $_0IF[_0IsZERO[_CMP[n][m]]][$_0TRUE][$_0FALSE] }}
$_0LT = L{|n| L{|m|
$_0IF[$_0NOT[$_0EQ[n][m]]][
L{|g| $_0IF[_0IsZERO[$_0Sub1[_CMP[n][m]]]][$_0TRUE][$_0FALSE][g]}
][$_0FALSE]
}}
$_0GT = L{|n| L{|m| $_0IF[$_0OR[$_0EQ[n][m]][$_0LT[n][m]]][$_0FALSE][$_0TRUE] }}
=end
| true |
f42f6a4a5ea7dfd0f0793542fe1f228079a3ae06 | Ruby | tsetsefly/launch_school-prepwork | /back_end_prep/ruby_basics_exercises/user_input/login.rb | UTF-8 | 328 | 3.078125 | 3 | [] | no_license | response = [nil, nil]
USERNAME = 'admin'
PASSWORD = 'SecreT'
loop do
puts '>> Please enter your user name:'
response[0] = gets.chomp
puts '>> Please enter your password:'
response[1] = gets.chomp
break if response[0] == 'admin' && response[1] == 'SecreT'
puts '>> Authorization failed!'
end
puts 'Welcome!' | true |
3a7d8f66eafeb9f4f656e9c59c72d5e799a41eac | Ruby | almostwhitehat/mailcatcher-api | /lib/mailcatcher/api/mailbox/message.rb | UTF-8 | 1,116 | 2.625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'uri'
require 'mail'
module MailCatcher
module API
class Mailbox
class Message
attr_reader :id, :raw
attr_reader :message_id, :date
attr_reader :from, :to, :subject, :body, :decoded_body, :header_fields
attr_reader :mime_type, :charset, :content_type
def initialize(msg)
@id = msg['id'].to_i
@raw = msg['source']
mail = Mail.new(@raw)
@message_id = mail.message_id
@header_fields = mail.header_fields
@date = mail.date
@from = mail.from
@to = mail.to
@subject = mail.subject
@body = mail.body.raw_source
@decoded_body = mail.decode_body
@mime_type = mail.mime_type
@charset = mail.charset
@content_type = mail.content_type
end
def links
@links ||= URI.extract(@decoded_body).select { |s| s.start_with? 'http' }
end
def headers
@headers ||= @header_fields.inject({}) {|hsh, header| hsh[header.name] = header.value; hsh}
end
end
end
end
end
| true |
35a58c5ade3dd850db25d9b66b986f8d2241ecb6 | Ruby | bver/GERET | /lib/sampling.rb | UTF-8 | 1,682 | 3.265625 | 3 | [
"MIT"
] | permissive |
require 'lib/roulette'
module Selection
# Stochastic Universal Sampling selection method. The probability of the individual selection is
# proportional to some (usually fitness) non-negative value (as in Roulette selection).
# However, more individuals can be selected at once by the single run of a wheel, which brings
# a better spread of the results (in comparision with Roulette method).
#
# See http://en.wikipedia.org/wiki/Stochastic_universal_sampling
#
class Sampling < Roulette
# Set the proportional_by or the block for obtaining invividual's proportion.
# See Roulette#proportional_by
def initialize( proportional_by=nil, &block )
super
end
# Select individuals from the population.
# It can be specified how_much individuals will be selected.
def select( how_much, population=self.population )
raise "Sampling: cannot select from an empty population" if population.empty?
raise "Sampling: cannot select more than population.size" if how_much > population.size
return [] if how_much == 0
@sum,@wheel = wheel_core population
@population = population
step = @sum.to_f/how_much
ballot = step * @random.rand
width = 0.0
winners = []
@wheel.each_with_index do |slot,index|
width += slot.width
next if ballot > width
winners.push slot.original
ballot += step
end
winners
end
# Select one individual from the population (same as Roulette#select_one, but a bit less effective).
def select_one population=self.population
select( 1, population ).first
end
end
end # Selection
| true |
01d7ce28e68eb204e2d43477c4dbd229cbc89bca | Ruby | dan3lson/leksi | /app/models/words_api.rb | UTF-8 | 1,936 | 2.84375 | 3 | [] | no_license | class WordsApi
class NoWordError < StandardError
end
def initialize(name)
@name = name
end
def define
response = self.everything
words = []
api_words = response["results"]
api_words.each do |word|
syllables = response["syllables"]
joined_syllables = syllables["list"].join("·") if syllables
new_word = Word.new(
name: name,
definition: word["definition"],
part_of_speech: word["partOfSpeech"],
phonetic_spelling: joined_syllables
)
examples = word["examples"]
if examples
text = examples.count > 1 ? examples.join("***") : examples.first
example = Example.new(text: text, word: new_word)
new_word.examples << example
end
words << new_word
end
words
rescue
msg = [
"Sorry, we didn\'t find '#{name}' from your search. ",
"Please check the spelling and try again."
].join
raise WordsApi::NoWordError, msg
nil
end
def everything
get_everything
end
def syllables
response = get_everything("syllables")
return nil if response.class == String ||
response.code != 200 ||
response["syllables"].empty?
response["syllables"]["list"].join("·")
end
def examples
response = get_everything("examples")
return nil if response.class == String ||
response.code != 200 ||
response["examples"].empty?
response["examples"].join("***")
end
private
attr_reader :name
def get_everything(specifically_get = nil)
key = "jxec7LMiQymshHsPPG7i86q1rdXNp1Ndvi0jsnTSbYjDIDo0Kk"
begin
HTTParty.get(
"#{url}/#{name}/#{specifically_get}",
headers: {
"X-Mashape-Key" => key,
"Accept" => "application/json"
}
)
rescue => e
if e.message.include?("Failed to open TCP connection")
"Error: Offline; come back when you connect to the Internet!"
else
"Error: Accessing Word Info; details: #{e.message}."
end
end
end
def url
URI.parse(URI.encode("https://wordsapiv1.p.mashape.com/words"))
end
end
| true |
f1450e5aaac32998208edf434f5cbff82c23e0fe | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/cs169/800/spectral_cluster/cluster6/25627.rb | UTF-8 | 360 | 3.75 | 4 | [] | no_license | def combine_anagrams(words)
res = Hash.new([])
words.each do |word|
w = word.downcase.chars.sort.join
res[w] = res[w] + [word]
end
res.values
end
puts combine_anagrams(['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream'])
# => output: [["cars", "racs", "scar"], ["four"], ["for"], ["potatoes"],["creams", "scream"]] | true |
a495613abfc62969240aa444cce83431c77625e4 | Ruby | bogusoft/cukehead | /lib/cukehead/feature_node_child.rb | UTF-8 | 1,489 | 3.171875 | 3 | [
"MIT"
] | permissive | require 'rexml/document'
require 'cukehead/feature_node_tags'
module Cukehead
# Responsible for extracting the contents of a mind map node representing
# a sub-section of a feature (such as a Background or Scenario) and
# providing it as text for a feature file.
#
class FeatureNodeChild
# Extracts the feature section described in the given node.
# ===Parameters
# <tt>node</tt> - REXML::Element
#
def initialize(node)
@description = []
@tags = FeatureNodeTags.new
@title = node.attributes["TEXT"]
from_mm_node node
end
# Returns the title, tags, and descriptive text extracted from the
# mind map as a string of text formatted for output to a feature file.
# ===Parameters
# <tt>pad</tt> - String of whitespace to use to indent the section.
#
def to_text(pad)
s = "\n"
@description.each {|d| s += pad + " " + d + "\n"}
pad + @tags.to_text(pad) + @title + s
end
private
# Extracts tags and descriptive text from child nodes of the given node.
# ===Parameters
# <tt>node</tt> - REXML::Element
#
def from_mm_node(node)
if node.has_elements?
node.elements.each do |e|
text = e.attributes["TEXT"]
unless text.nil?
if text =~ /^Tags:*/i
@tags.from_text text
else
@description << text
end
end
end
end
end
end
end | true |
2b40c87ddbb01b0f49b363bc68d522cef0983fbd | Ruby | nstielau/reptile | /lib/reptile/delta_monitor.rb | UTF-8 | 2,939 | 2.890625 | 3 | [
"MIT"
] | permissive | module Reptile
# This monitor compares the row counts for each table for each master and slave.
class DeltaMonitor
# Set the user settings for a user that has global SELECT privilidgess
def self.user=(user_settings)
@user = user_settings
end
# The user settings for a user that has global select privilidgess
def self.user
raise "You need to specify a user!" if @user.nil?
@user
end
# Retrieve the active database connection. Nil of none exists.
def self.connection
ActiveRecord::Base.connection
end
# Compares the row counts for master tables and slave tables
# Returns a hash of TABLE_NAME => ROW COUNT DELTAs
def self.diff(db_name, master_configs, slave_configs)
ActiveRecord::Base.establish_connection(slave_configs.merge(user))
slave_counts = get_table_counts
ActiveRecord::Base.establish_connection(master_configs.merge(user))
master_counts = get_table_counts
deltas= {}
master_counts.each do |table, master_count|
if slave_counts[table].nil?
Log.error "Table '#{table}' exists on master but not on slave."
next
end
delta = master_count.first.to_i - slave_counts[table].first.to_i
deltas[table] = delta
end
print_deltas(db_name, deltas, master_configs)
deltas
rescue Exception => e
Log.error "Error: Caught #{e}"
Log.error "DB Name: #{db_name}"
Log.error "Master Configs: #{master_configs.inspect}"
Log.error "Slave Configs: #{slave_configs.inspect}"
raise e
end
# Prints stats about the differences in number of rows between the master and slave
def self.print_deltas(db_name, deltas, configs)
non_zero_deltas = deltas.select{|table, delta| not delta.zero?}
if non_zero_deltas.size.zero?
Log.info "Replication counts A-OK for #{db_name} on #{configs['host']} @ #{Time.now}"
else
Log.info "Replication Row Count Deltas for #{db_name} on #{configs['host']} @ #{Time.now}"
Log.info "There #{non_zero_deltas.size > 1 ? 'are' : 'is'} #{non_zero_deltas.size} #{non_zero_deltas.size > 1 ? 'deltas' : 'delta'}"
non_zero_deltas.each do |table, delta|
Log.info " #{table} table: #{delta}" unless delta.zero?
end
end
end
# Returns an array of strings containing the table names
# for the current database.
def self.get_tables
tables = []
connection.execute('SHOW TABLES').each { |row| tables << row }
tables
end
# Returns a hash of TABLE_NAME => # Rows for all tables in current db
def self.get_table_counts
tables = get_tables
tables_w_count = {}
tables.each do |table|
connection.execute("SELECT COUNT(*) FROM #{table}").each do |table_count|
tables_w_count["#{table}"] = table_count
end
end
tables_w_count
end
end
end | true |
f578b551fdfacd449bd578282b95bd43e0f5cfbf | Ruby | petrucioata/fakerbot | /lib/fakerbot/cli.rb | UTF-8 | 1,629 | 2.65625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'thor'
require 'fakerbot/cli'
require 'fakerbot/version'
require 'fakerbot/commands/list'
require 'fakerbot/commands/search'
module FakerBot
class CLI < Thor
Error = Class.new(StandardError)
desc 'version', 'fakerbot version'
def version
require_relative 'version'
puts "v#{FakerBot::VERSION}"
end
map %w[--version -v] => :version
desc 'list', 'List all Faker constants'
method_option :help, aliases: '-h', type: :boolean,
desc: 'Display usage information'
method_option :show_methods, aliases: '-m', type: :boolean, default: true,
desc: 'Display Faker constants with methods'
method_option :verbose, aliases: '-v', type: :boolean,
desc: 'Include sample Faker output'
def list(*)
if options[:help]
invoke :help, ['list']
else
FakerBot::Commands::List.new(options).execute
end
end
desc 'search [Faker]', 'Search Faker method(s)'
method_option :help, aliases: '-h', type: :boolean,
desc: 'Display usage information'
method_option :show_methods, aliases: '-m', type: :boolean, default: true,
desc: 'Display Faker constants with methods'
method_option :verbose, aliases: '-v', type: :boolean,
desc: 'Include sample Faker output'
def search(query)
if options[:help]
invoke :help, ['search']
else
FakerBot::Commands::Search.new(options).execute(query)
end
end
end
end
| true |
bda7379cb7f68048ce2872dd9b675424f5d94b4f | Ruby | zklamm/ruby-basics | /0_the_basics/exercise_1.rb | UTF-8 | 97 | 2.875 | 3 | [] | no_license | first_name = 'Zac'
last_name = 'Klammer'
full_name = first_name + ' ' + last_name
puts full_name | true |
3d5e63c66f109bbd8549c6683077ea5af4460ad4 | Ruby | btmccollum/oo-banking-v-000 | /lib/bank_account.rb | UTF-8 | 1,368 | 3.671875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class BankAccount
attr_accessor :balance, :status
attr_reader :name
#upon instantiation the object is created with a given name, and a default
#@status of open and @balance of $1000
def initialize(name)
@name = name
@status = "open"
@balance = 1000
end
def display_balance
"Your balance is $#{self.balance}."
end
#allows for deposit of a valid amount to its @balance
def deposit(amount)
# binding.pry
@balance = @balance + amount unless amount < 0
end
#allows for withdraw of a valid amount from its @balance
def withdraw(amount)
@balance = @balance - amount unless amount < 0
end
#confirms an account is valid if @status is set to "open" and #balance
#returns a value greater than 0
def valid?
@status == "open" && @balance > 0 ? true : false
end
#changes @status to closed if the account is currently valid
def close_account
self.valid? ? @status = "closed" : "Unable to close account at this time."
#Additional functionality to preven the closure of a funded or negative account:
# if @status == "open" && @balance == 0
# @status = "closed"
# elsif @status == "open" && @balance > 0
# "Unable to close a funded account."
# else @status == "open" && @balance < 0
# "Unable to close account with a negative balance."
# end
end
end
| true |
fd133dbbc0313dfaddf6a259edd30b5782dd1e89 | Ruby | AllPurposeName/mastermind | /lib/printer.rb | UTF-8 | 5,048 | 3.828125 | 4 | [] | no_license | require 'colorize'
class Printer
def mm
"#{"M".red}#{"A".red}#{"S".red}#{"T".red}#{"E".red}#{"R".red}#{"M".light_black}#{"I".light_black}#{"N".light_black}#{"D".light_black}"
end
def intro
"Welcome to DJ's MASTERMIND challenge!
You are to determine the number and order of four colors:
#{"Blue".blue}
#{"Green".green}
#{"Red".red}
and #{"Yellow".yellow}
Good luck. Perhaps we will see who is the true #{mm}!
Press (#{"p".green})#{"lay".green}, (#{"i".yellow})#{"nstructions".yellow}, or (#{"q".light_black})#{"uit".light_black} to continue."
end
def instructions
"At any time, press \"#{"q".light_black}\" to quit.
Determine your difficulty and follow the prompts to take an appropriately sized guess.
You will be guessing which colors fall into which positions.
The game will give you hints back, but it is up to you to solve
the secret code.
Enter your answers in this format: gbgr
Do not include spaces or other characters which don't correspond to
the valid color.
Don't forget, it is extremely shameful to lose at this easy game
and you should probably #{"quit".light_black} before admitting true defeat.
Press (#{"p".green})#{"lay".green}, (#{"i".yellow})#{"nstructions".yellow}, or (#{"q".light_black})#{"uit".light_black} to continue."
end
def difficulty
"There are four levels of difficulty in DJ's #{mm}.
Enter #{"e".light_black}(#{"x".light_black})#{"pert".light_black}, #{"in".red}(#{"t".red})#{"ermediate".red}, (#{"n".magenta})#{"ormal".magenta}, or enter anything else (except \"#{"q".red}\") to play as a whiny #{"beginner".cyan}.
For more on difficulties and how they change the game, press (#{"i".yellow})#{"nstructions".yellow}"
end
def take_first_guess
"Now, guess which colors are where?!"
end
def take_guess
"Try again..."
end
def try_again(printables)
"Your guess included #{printables[0]} of the appropriate colors and #{printables[1]} out of #{printables[2]} colors in the correct position.\"
Your guess count is #{printables[3]}. "
end
def game_lost
"You ran out of guesses. Keep your chin up and always remember:
losing is fun.
Buuuut perhaps you would like to regain your dignity and try again?
> "
end
def game_won
"CONGRATULATIONS! It seems you have conquered the puzzle afterall.
Prepare to be a huge dork and start calling yourself the MASTERMIND!"
end
def play_again_win
"
Well, MASTERMIND, would you like to prove yourself further
and gain unprecidented bragging rights?
Press (#{"p".green})#{"lay".green} to #{"play".green} again, (#{"i".yellow})#{"nstructions".yellow}, or (#{"q".light_black})#{"uit".light_black} to #{"give up".light_black}.
> "
end
def goodbye
"Goodbye and good games"
end
def beginner
"You have chosen... *yawn*... beginner.
You have to guess 4 positions the random sequence from colors
XXXX
#{"Blue".blue}
#{"Green".green}
#{"Red".red}
and #{"Yellow".yellow}
Good luck. Srs who needs luck on beginner though?
"
end
def normal
"You have chosen normal. As good a place to start as any.
You have to guess 6 positions the random sequence from colors
XXXXXX
#{"Blue".blue}
#{"Green".green}
#{"Red".red}
#{"Yellow".yellow}
and #{"Magenta".magenta}
"
end
def intermediate
"You have chosen intermediate. Welcome to the big leagues!
You have to guess 8 positions the random sequence from colors
XXXXXXXX
#{"Blue".blue}
#{"Green".green}
#{"Red".red}
#{"Yellow".yellow}
#{"Magenta".magenta}
and #{"Cyan".cyan}
Free hi-fives if you beat this difficulty level!
"
end
def expert
"Welcome, #{mm}.
On expert level there are 10 positions in the random sequence.
It is composed of some or all of the following colours
XXXXXXXXXX
#{"Blue".blue}
#{"Green".green}
#{"Red".red}
#{"Yellow".yellow}
#{"Magenta".magenta}
#{"Cyan".cyan}
and lastly #{"Grey".light_black}LIGHT BLACK
Test your might!
"
end
def instructions_on_difficulty
"In DJ's #{mm} these are the four difficulty levels:
#{"Beginner".cyan} -- 4 colors with 4 positions and infinite guesses
#{"Normal".magenta} -- 5 colors with 6 positions and 10 guesses
#{"Intermediate".red} -- 6 colors with 8 positions and 13 guesses
#{"Expert".light_black} -- 7 colors with 10 positions and 16 guesses
Enter #{"e".light_black}(#{"x".light_black})#{"pert".light_black}, #{"in".red}(#{"t".red})#{"ermediate".red}, (#{"n".magenta})#{"ormal".magenta}, or enter anything else (except \"#{"q".red}\") to play as a whiny #{"beginner".cyan}.
For more on difficulties and how they change the game, press (#{"i".yellow})#{"nstructions".yellow}
> "
end
def too_long
"Your entry was too long, please enter a valid guess."
end
def too_short
"Your entry was too short, please enter a valid guess."
end
def invalid_entry
"Your entry is invalid, please enter a valid guess."
end
end
| true |
79f07e54f4e538d7ef897000e75ce61c7991d6f9 | Ruby | JDittles/intro-to-ruby-book | /4_methods/return.rb | UTF-8 | 179 | 3.65625 | 4 | [] | no_license | def add_three(number)
number + 3 # <== we don't need to put return here, Ruby always returns on the last line of a method
end
returned_value = add_three(4)
puts returned_value | true |
33802efa5c54694c5f783ceb6a6da6b2c2e3accf | Ruby | geeksam/hangman | /spec/hangman_spec.rb | UTF-8 | 3,486 | 3.453125 | 3 | [] | no_license | require 'rubygems'
require 'rspec'
require './hangman.rb'
describe Hangman do
ValidPuzzle = File.open("spec/sample_puzzle.txt").read
describe "#new_game" do
end
describe "#guess" do
before(:each) do
@hangman = Hangman.new_game(ValidPuzzle)
end
it "should throw game over if there are no guesses remaining" do
@hangman.guesses_remaining = 1
symbol_not_in_solution = "z"
# I don't often see throw/catch used in Ruby. Still working through Exceptional Ruby myself, though, so maybe I'll find more reasons to use them.
# Brent: I might be wrong in doing it but my justification is that I believe catch and throw should be used to break from a loop / control flow, and in this instance we are trying to break from the 'game loop' so it seems like it's a good use case. What do you usually see used instead of catch/throw in these situations?
# Sam: Exceptions, mostly (intentional and otherwise).
expect { @hangman.guess(symbol_not_in_solution) }.to throw_symbol(:game_over)
end
it "should return the number of occurrences when the symbol is in the puzzle" do
@hangman.guess("a").should == 2
@hangman.guess("r").should == 2
@hangman.guess("i").should == 1
end
it "should return 0 when the symbol is valid but is not in the puzzle" do
@hangman.guess("z").should == 0
end
it "should accept guesses with more than one symbol at a time and apply them in order from left to right" do
@hangman.guess("abc")
#How do I test this?
end
it "should raise an InvalidGuessError if it is not an acceptable guess string" do
# Sam: Underscores have been known to appear in the answer key as well. Not sure this behavior makes sense.
# Possibly a guess of "abc" should be treated as .guess('a'); .guess('b'); .guess('c') ?
# Brent: Good point, I will look at incorporating this. If this is the case, I can't think of any invalid guesses! I'll leave this here nonetheless
invalid_characters = %w()
invalid_characters.each do |invalid_character|
lambda { @hangman.guess(invalid_character) }.should raise_error(InvalidGuessError)
end
end
it "should have one less guess remaining if the guess is incorrect" do
#Brent: What's the reasoning behind including abs? Doesn't seem to work when I do it - Rspec says it was not changed
expect { @hangman.guess("z") }.to change{@hangman.guesses_remaining}.by(-1)
end
it "should not affect the number of guesses if the guess is correct" do
expect { @hangman.guess("a") }.not_to change{@hangman.guesses_remaining}
end
it "should raise an InvalidGuessError if it has already been guessed" do
# Sam: Or, consider this a no-op
# Brent: What is a no-op?
# Sam: "No Operation" -- the machine instruction you used on ancient computers when
# you needed to waste some time. ;> aka "NOP", for one assembly version of same.
pending "This test may no longer be necessary - if someone wants to guess the same letter twice, that's their fault!"
#lambda { 2.times do; @hangman.guess("a"); end }.should raise_error(InvalidGuessError)
end
it "should add (in)correctly guessed symbols to guessed[:(in)correct]" do
guesses = %w[a b z x]
guesses.each { |e| @hangman.guess(e) }
@hangman.guessed[:correct].should == %w(a b)
@hangman.guessed[:incorrect].should == %w(z x)
end
end
end
| true |
2aea02b53d76a178272ccbc1b5912a2ba6e3c99c | Ruby | flatiron-lessons/ruby-collaborating-objects-lab-web-071717 | /lib/artist.rb | UTF-8 | 519 | 3.609375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class Artist
attr_accessor :name
@@all = []
def initialize(name)
@name = name
@songs = []
end
def songs
@songs
end
def save
@@all << self
end
def self.find_or_create_by_name(artist)
x = @@all.find do |instance|
instance.name == artist
end
if x == nil
y = self.new(artist)
y.save
y
else
x
end
end
def print_songs
@songs.each do |song|
puts song.name
end
end
def self.all
@@all
end
def add_song(song)
@songs << song
end
end
| true |
12730af4cce5ff3e71d8bf9a00e4b1009bc1b7da | Ruby | RomanVarhola/order_lunch | /app/services/calculate_total_price_for_orders.rb | UTF-8 | 261 | 3.328125 | 3 | [] | no_license | class CalculateTotalPriceForOrders
attr_reader :orders
def initialize(orders)
@orders = orders
end
def call
total_price = 0
@orders.each do |order|
total_price += order.food.price + order.drink.price
end
total_price
end
end | true |
f3f68bdd431b1c5bb4180d98a853fc829a83f601 | Ruby | recortable/letamendi | /app/controllers/alquileres_controller.rb | UTF-8 | 2,632 | 2.546875 | 3 | [] | no_license | class AlquileresController < ApplicationController
layout 'cinemascope'
def index
params[:id] = Time.now
lista
render :action => 'lista'
end
def lista
ms = params[:id].to_i
now = Time.at(ms) if ms > 0
now = Time.now if ms == 0
@report = Report.new(now)
end
def close_rent
@rent = Rent.find(params[:id]);
@rent.close
@msg = "#{@rent.member.name} ha hecho los deberes..."
render :action => 'update_rent'
end
def undo_close_rent
@rent = Rent.find(params[:id]);
@rent.reopen
logger.info "state: #{@rent.state}"
render :action => 'update_rent'
end
def close_item
@item = RentItem.find(params[:id]);
@rent = @item.rent
@item.close
items = RentItem.find_all_by_rent_id(@rent.id,
:conditions => ['closed = 0'])
if items.size == 0
@rent.update_attributes(:closed => true,
:close_date => Time.now)
render :action => 'update_rent'
else
@msg = "#{@item.movie.title} marcada como devuelta"
render :action => 'update_item'
end
end
def undo_close_item
@item = RentItem.find(params[:id])
@rent = @item.rent
@item.reopen
if @rent.closed?
@rent.update_attributes(:closed => false,
:close_date => nil);
render :action => 'update_rent'
else
@msg = "#{@item.movie.title} marcada como no devuelta"
render :action => 'update_item'
end
end
def prorrogue
change_prorrogue 'le tendremos que dar un día más', 1
end
def undo_prorrogue
change_prorrogue 'un día menos... a ver si espabila', -1
end
def change_prorrogue(msg, num)
@msg = msg
@rent = Rent.find(params[:id])
@rent.update_attribute(:prorrogue,
@rent.prorrogue + num)
render :action => 'update_item'
end
private
def build_report(time)
@today = Time.utc(time.year, time.month, time.day)
report = Hash.new
report[:day] = @today
report[:next_day] = @today + 1.day
report[:prev_day] = @today - 1.day
report[:distance] = distance(Time.now, report[:day])
report[:opened] = Rent.find_all_begins_on @today
report[:closed] = Rent.find_all_closed_on @today
report[:waiting] = Rent.find_all_ends_on @today
report[:delayed] = Rent.find_all_delayed_on @today
report[:rented] = Rent.find_all_rented_on @today
report[:rents] = report[:rented].size
today_items = report[:rented].map {|r| RentItem.count(
:conditions => ['rent_id = ?', r.id])}
total = 0;
today_items.each {|n| total += n}
report[:items] = total
report
end
end
| true |
b00a1610b4c1b65f04635fe2859bce61f8892641 | Ruby | smcand92/week2_weekend_hw | /specs/room_spec.rb | UTF-8 | 1,427 | 3.21875 | 3 | [] | no_license | require('minitest/autorun')
require('minitest/rg')
require_relative('../rooms')
require_relative('../songs')
require_relative('../guests')
class RoomTest < MiniTest::Test
def setup
@song1 = Song.new("Dancing Queen")
@song2 = Song.new("Silly Boy")
@song3 = Song.new("Younger Now")
@song4 = Song.new("Naturally")
@song5 = Song.new("Finish Her!")
@guest1 = Guest.new("Alex")
@guest2 = Guest.new("Stewart")
@guest3 = Guest.new("Steven")
@guest4 = Guest.new("Louise")
@guest5 = Guest.new("Robbie")
@room1 = Room.new(1, 3)
@room2 = Room.new(2, 4)
end
def test_create_new_room()
assert_equal(Room, @room1.class())
end
def test_check_in_guest()
@room1.check_in_guest(@guest1)
assert_equal(1, @room1.occupancy.length())
end
def test_check_out_guest()
@room1.check_in_guest(@guest1)
@room1.check_in_guest(@guest2)
assert_equal(2, @room1.occupancy.length())
@room1.check_out_guest(@guest2)
assert_equal(1, @room1.occupancy.length())
end
def test_song_added_to_room()
@room1.song_added_to_room(@song4)
assert_equal(1, @room1.music.length())
end
def test_room_capacity
@room1.check_in_guest(@guest1)
@room1.check_in_guest(@guest2)
@room1.check_in_guest(@guest3)
assert_equal(3, @room1.occupancy.length())
# @room1.check_in_guest(@guest4)
# assert_equal("room is full", @room1.capacity())
end
end
| true |
cc2af552a1802579c65dad041da1804f353e9f85 | Ruby | Rockster160/Portfolio | /lib/core_extensions/core_extensions.rb | UTF-8 | 1,199 | 2.890625 | 3 | [] | no_license | module CoreExtensions
refine Hash do
def deep_set(path, new_value)
return self unless path.any?
new_hash = new_value
path.reverse.each do |path_key|
new_hash = {path_key => new_hash}
end
self.deep_merge!(new_hash) { |key, this_val, other_val| this_val + other_val }
self
end
def clean!
delete_if do |k, v|
if v.is_a?(Hash)
v.clean!.blank?
else
v.blank?
end
end
end
def all_paths
found_paths = []
self.each do |hash_key, hash_values|
path = [hash_key]
if hash_values.is_a?(Hash)
hash_values.all_paths.each do |new_path|
found_paths << path + new_path
end
elsif hash_values.is_a?(Array)
hash_values.each do |new_path|
if new_path.is_a?(Hash)
new_path.all_paths.each do |new_array_path|
found_paths << path + new_array_path
end
else
found_paths << path + [new_path]
end
end
else
found_paths << path + [hash_values]
end
end
found_paths
end
end
end
| true |
384629b5afbaaa7a169d30489340cd4010ee7098 | Ruby | yaoyunchen/LH_warcraft3 | /spec/test_11.rb | UTF-8 | 1,155 | 3.296875 | 3 | [] | no_license | require_relative 'spec_helper'
# In most strategy games, like Warcraft III, buildings can also be attacked by units. Since a barracks is a building, it has substantial more HP (500) To make matters worse, a Footman does only HALF of its AP as damage to a Barracks. This is because they are quite ineffective against buildings.
# Note: The damage amount should be an integer (Fixnum). Take the ceil division result.
describe Barracks do
before :each do
@barracks = Barracks.new
end
it "should be a Building." do
expect(@barracks).to be_an_instance_of(Barracks)
expect(@barracks).to be_a(Building)
end
it "has and knows its health points" do
expect(@barracks.health_points).to eql(500)
end
describe "#damage" do
it "should reduce the unit's health_points by the attack_power specified" do
@barracks.damage(10)
expect(@barracks.health_points).to eq(490)
end
it "should take half damage from enemy footmen." do
enemy = Footman.new
#expect(@barracks).to receive(:damage).with(5)
enemy.attack_building!(@barracks)
expect(@barracks.health_points).to eq(495)
end
end
end
| true |
e0accbb1165810de9d0fc4b529d2c396996d6c1c | Ruby | levkk/emoji_differ | /lib/emoji_differ/slack_api.rb | UTF-8 | 655 | 2.765625 | 3 | [
"MIT"
] | permissive | require "net/https"
require "emoji_differ/list"
module EmojiDiffer
class SlackApi < Struct.new(:token)
API_ENDPOINT = 'https://slack.com/api/emoji.list'
def emoji
EmojiDiffer::List.new.load_json(get_emoji.to_s)
end
def api_endpoint
API_ENDPOINT
end
def build_query
uri = URI(api_endpoint)
uri.query = URI.encode_www_form({
token: token,
})
uri
end
def get_emoji
handle = Net::HTTP.get_response(build_query)
if !handle.is_a?(Net::HTTPSuccess)
raise "Slack API is out of business today, #{handle.inspect}"
end
handle.body
end
end
end
| true |
3ac9e915161ebce4d2fdec60ae85b84a6a3a7511 | Ruby | guyviner/codecorelife | /day2/day2/quiz3.rb | UTF-8 | 176 | 3.1875 | 3 | [] | no_license | # sandra
puts "how many sides does a hexagon have?"
response = gets.chomp
case response
when "six", "Six", 6.to_s
puts "that is correct"
else
puts "that is incorrect"
end
| true |
ffa988d764d5752d69060807e1b3c999fc17229d | Ruby | tommfernandes/rubypragmatic | /rubypragmatic-sources/p33-metods-class/song_test.rb | UTF-8 | 357 | 3.1875 | 3 | [] | no_license | require_relative 'song.rb'
require_relative 'song_list.rb'
class SongTest
s1 = Song.new("Song 1", "Artista 1", 179)
puts "Song #{s1.name}, with #{s1.duration} seconds, is too long? #{SongList.is_too_long(s1)}"
s2 = Song.new("Song 2", "Artista 2", 475)
puts "Song #{s2.name}, with #{s2.duration} seconds, is too long? #{SongList.is_too_long(s2)}"
end | true |
4971ccb8919676bf09eab4ec5601d88c33ef1f2f | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/word-count/3f570100ff444fc382eb8458a831598e.rb | UTF-8 | 227 | 3.1875 | 3 | [] | no_license | class Phrase < Struct.new(:text)
def word_count
counts = {}
counts.default = 0
words.each do |word|
counts[word] += 1
end
counts
end
private
def words
text.downcase.scan /\w+/
end
end
| true |
af87de318d77ee5ca5e3c5bc6aa45dd0b5cfb821 | Ruby | TheArQu/TDCGExplorer | /batora/lib/authenticated_system.rb | UTF-8 | 900 | 2.546875 | 3 | [] | no_license | module AuthenticatedSystem
protected
def logged_in?
!!current_user
end
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def current_user=(user)
session[:user_id] = user ? user.id : nil
@current_user = user
end
def login_required
logged_in? || access_denied
end
def access_denied
redirect_to new_session_path
end
def store_location
store_location
session[:return_to] = request.request_uri
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
def logout_killing_session!
@current_user = nil
session[:user_id] = nil
end
def self.included(base)
base.send :helper_method, :current_user, :logged_in? if base.respond_to? :helper_method
end
end
| true |
e7c8d3d1f6ad875ac2a5f5f9423719bbe3b6658a | Ruby | tk0358/meta_programming_ruby2 | /chapter5/23module_trouble_extend.rb | UTF-8 | 201 | 3.421875 | 3 | [] | no_license | module MyModule
def my_method; 'hello'; end
end
obj = Object.new
obj.extend MyModule
p obj.my_method #=> "hello"
class MyClass
extend MyModule
end
p MyClass.my_method #=> "hello" | true |
018b70a4c7983d21168a41d3cc700542ec12816f | Ruby | maht0rz/otvorenezmluvy | /lib/core_ext/recursive_openstruct.rb | UTF-8 | 866 | 3.125 | 3 | [] | no_license | # use optimized OpenStruct without slow method creation
class OpenStruct
def initialize(hash = {})
@table = hash.with_indifferent_access
end
def method_missing(method, *args)
member = method.to_s
if member.chomp!('=')
@table[member] = args[0]
else
@table[member]
end
end
def respond_to?(member)
@table.include?(member)
end
end
# http://www.fngtps.com/2007/using-openstruct-as-mock-for-activerecord/
OpenStruct.__send__(:define_method, :id) { @table[:id] }
# http://www.rubyquiz.com/quiz81.html
class NilClass
def to_openstruct
self
end
end
class Object
def to_openstruct
self
end
end
class Array
def to_openstruct
map(&:to_openstruct)
end
end
class Hash
def to_openstruct
mapped = {}
each { |key, value| mapped[key] = value.to_openstruct }
OpenStruct.new(mapped)
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.