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 |
---|---|---|---|---|---|---|---|---|---|---|---|
cb1f8562d985f983718e340a6ff30651947dcec9
|
Ruby
|
railsfactory-deepankar/mp1
|
/swap_string/swap_string.rb
|
UTF-8
| 225 | 3.609375 | 4 |
[] |
no_license
|
puts "Enter the two strings"
i = gets.chomp.to_s
j = gets.chomp.to_s
puts "Strings before swapping"
puts "First string : #{i}"
puts "Second string : #{j}"
puts "After swapping: \n First String : #{j} \n Second String : #{i}"
| true |
c4543f460d895b0a66924dfa68681e4776b61d56
|
Ruby
|
mauriballes/ruby-lessons
|
/ruby/numeros.rb
|
UTF-8
| 276 | 3.46875 | 3 |
[
"MIT"
] |
permissive
|
# Numeros
### Enteros
34
52
1
### Flotantes
20.0
25.54
2.52
# Para pasar de entero a float
10.to_f
# Para pasar de float a entero
12.2315.to_i
# Para valor absoluto
-10.abs
# Para saber si el valor es numero para
2.even?
# Para devolver el siguiente entero
3.next
| true |
0b8d930a2ce81bbed1f01ccccc4ca120ada60fbe
|
Ruby
|
PeterCamilleri/fOOrth
|
/lib/fOOrth/library/duration/formatter.rb
|
UTF-8
| 7,160 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
# coding: utf-8
#* library/duration/formatter.rb - Duration formatting support library.
module XfOOrth
#Formatter support for the \Duration class.
class Duration
#Extend this class with attr_formatter support.
extend FormatEngine::AttrFormatter
##
#The specification of the formatter method of the \Duration class.
#<br>Year Formats:
#* %{?}{$}{w}y - Whole years.
#* %{?}{$}{w{.p}}Y - Total (with fractional) years.
#<br>Month Formats:
#* %{?}{$}{w}o - Whole months in the year.
#* %{?}{$}{w{.p}}O - Total (with fractional) months.
#<br>Day Formats:
#* %{?}{$}{w}d - Whole days in the month.
#* %{?}{$}{w{.p}}D - Total (with fractional) days.
#<br>Hour Formats:
#* %{?}{$}{w}h - Whole hours in the day.
#* %{?}{$}{w{.p}}H - Total (with fractional) hours.
#<br>Minute Formats:
#* %{?}{$}{w}m - Whole minutes in the hour.
#* %{?}{$}{w{.p}}M - Total (with fractional) minutes.
#<br>Second Formats:
#* %{?}{$}{w{.p}}s - Total (with fractional) seconds in the minute.
#* %{?}{$}{w{.p}}S - Total (with fractional) seconds.
#<br>Brief Summary Formats:
#* %{?}{$}{w{.p}}B - Total (with fractional) of the largest, non-zero time unit.
#<br>Raw Formats (in seconds and fractions):
#* %{w{.p}}f - Total seconds in floating point format.
#* %{w}r - Total seconds in rational format.
#<br>Where:
#* \? is an optional flag indicating that the data should be suppressed if absent.
#* \$ is an optional flag indication to retrieve the corresponding text label.
#* w is an optional field width parameter.
#* p is an optional precision parameter.
attr_formatter :strfmt,
{
:before => lambda do
tmp[:all] = arr = src.to_a
tmp[:year] = arr[0]; tmp[0] = src.as_years
tmp[:month] = arr[1]; tmp[1] = src.as_months
tmp[:day] = arr[2]; tmp[2] = src.as_days
tmp[:hour] = arr[3]; tmp[3] = src.as_hours
tmp[:min] = arr[4]; tmp[4] = src.as_minutes
tmp[:sec] = arr[5]; tmp[5] = src.as_seconds
end,
"%y" => lambda {cat "%#{fmt.parm_str}d" % tmp[:year]},
"%?y" => lambda {cat "%#{fmt.parm_str}d" % tmp[:year] if tmp[:year] >= 1},
"%Y" => lambda {cat "%#{fmt.parm_str}f" % tmp[0]},
"%?Y" => lambda {cat "%#{fmt.parm_str}f" % tmp[0] if tmp[0] > 0},
"%$y" => lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(0, tmp[:year])},
"%?$y"=> lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(0, tmp[:year]) if tmp[:year] >= 1},
"%$Y" => lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(0, tmp[0])},
"%?$Y"=> lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(0, tmp[0]) if tmp[0] > 0},
"%o" => lambda {cat "%#{fmt.parm_str}d" % tmp[:month]},
"%?o" => lambda {cat "%#{fmt.parm_str}d" % tmp[:month] if tmp[:month] >= 1},
"%O" => lambda {cat "%#{fmt.parm_str}f" % tmp[1]},
"%?O" => lambda {cat "%#{fmt.parm_str}f" % tmp[1] if tmp[1] > 0},
"%$o" => lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(1, tmp[:month])},
"%?$o"=> lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(1, tmp[:month]) if tmp[:month] >= 1},
"%$O" => lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(1, tmp[1])},
"%?$O"=> lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(1, tmp[1]) if tmp[1] > 0},
"%d" => lambda {cat "%#{fmt.parm_str}d" % tmp[:day]},
"%?d" => lambda {cat "%#{fmt.parm_str}d" % tmp[:day] if tmp[:day] >= 1},
"%D" => lambda {cat "%#{fmt.parm_str}f" % tmp[2]},
"%?D" => lambda {cat "%#{fmt.parm_str}f" % tmp[2] if tmp[2] > 0},
"%$d" => lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(2, tmp[:day])},
"%?$d"=> lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(2, tmp[:day]) if tmp[:day] >= 1},
"%$D" => lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(2, tmp[2])},
"%?$D"=> lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(2, tmp[2]) if tmp[2] > 0},
"%h" => lambda {cat "%#{fmt.parm_str}d" % tmp[:hour]},
"%?h" => lambda {cat "%#{fmt.parm_str}d" % tmp[:hour] if tmp[:hour] >= 1},
"%H" => lambda {cat "%#{fmt.parm_str}f" % tmp[3]},
"%?H" => lambda {cat "%#{fmt.parm_str}f" % tmp[3] if tmp[3] > 0},
"%$h" => lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(3, tmp[:hour])},
"%?$h"=> lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(3, tmp[:hour]) if tmp[:hour] >= 1},
"%$H" => lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(3, tmp[3])},
"%?$H"=> lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(3, tmp[3]) if tmp[3] > 0},
"%m" => lambda {cat "%#{fmt.parm_str}d" % tmp[:min]},
"%?m" => lambda {cat "%#{fmt.parm_str}d" % tmp[:min] if tmp[:min] >= 1},
"%M" => lambda {cat "%#{fmt.parm_str}f" % tmp[4]},
"%?M" => lambda {cat "%#{fmt.parm_str}f" % tmp[4] if tmp[4] > 0},
"%$m" => lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(4, tmp[:min])},
"%?$m"=> lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(4, tmp[:min]) if tmp[:min] >= 1},
"%$M" => lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(4, tmp[4])},
"%?$M"=> lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(4, tmp[4]) if tmp[4] > 0},
"%s" => lambda {cat "%#{fmt.parm_str}f" % tmp[:sec]},
"%?s" => lambda {cat "%#{fmt.parm_str}f" % tmp[:sec] if tmp[:sec] >= 1},
"%S" => lambda {cat "%#{fmt.parm_str}f" % tmp[5]},
"%?S" => lambda {cat "%#{fmt.parm_str}f" % tmp[5] if tmp[5] > 0},
"%$s" => lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(5, tmp[:sec])},
"%?$s"=> lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(5, tmp[:sec]) if tmp[:sec] >= 1},
"%$S" => lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(5, tmp[5])},
"%?$S"=> lambda {cat "%#{fmt.parm_str}s" % Duration.pick_label(5, tmp[5]) if tmp[5] > 0},
"%B" => lambda {cat "%#{fmt.parm_str}f" % tmp[src.largest_interval]},
"%?B" => lambda {cat "%#{fmt.parm_str}f" % tmp[src.largest_interval] if src.period > 0},
"%$B" => lambda do
index = src.largest_interval
cat "%#{fmt.parm_str}s" % Duration.pick_label(index, tmp[index])
end,
"%?$B" => lambda do
if src.period > 0
index = src.largest_interval
cat "%#{fmt.parm_str}s" % Duration.pick_label(index, tmp[index])
end
end,
"%f" => lambda {cat "%#{fmt.parm_str}f" % src.period.to_f},
"%r" => lambda {cat "%#{fmt.parm_str}s" % src.period.to_s}
}
end
format_action = lambda do |vm|
begin
vm.poke(self.strfmt(vm.peek))
rescue => err
vm.data_stack.pop
error "F40: Formating error: #{err.message}."
end
end
# [a_time a_string] format [a_string]
Duration.create_shared_method('format', NosSpec, [], &format_action)
# [a_time] f"string" [a_string]
Duration.create_shared_method('f"', NosSpec, [], &format_action)
end
| true |
b22e014d1e616f1ed5bb2a9aeb825be53b3fd8f5
|
Ruby
|
Maikell84/advent-of-code-2020
|
/day_02/2.rb
|
UTF-8
| 1,549 | 3.59375 | 4 |
[] |
no_license
|
#!/usr/bin/env ruby
def find_occurances(haystack, needle, occurances = 0)
i = haystack.index(needle)
return occurances if i.nil?
occurances += 1
modified_haystack = String.new(haystack)
modified_haystack[i] = ''
find_occurances(modified_haystack, needle, occurances)
end
def part1_password_valid?(occurance, letter, password)
occurance = occurance.split('-').map(&:to_i)
found_occurances = find_occurances(password, letter)
occurance[0] <= found_occurances && found_occurances <= occurance[1]
end
def part2_password_valid?(positions, letter, password)
positions_array = positions.split('-').map(&:to_i)
(password[positions_array[0]-1] == letter && password[positions_array[1]-1] != letter) ||
(password[positions_array[0]-1] != letter && password[positions_array[1]-1] == letter)
end
file = File.open('2.txt')
password_array = file.readlines.map(&:chomp)
invalid_passwords_part1 = []
invalid_passwords_part2 = []
password_array.each do |password_entry|
entry = password_entry.split(' ')
target_numbers = entry[0]
target_letter = entry[1].split(':')[0]
target_password = entry[2].freeze
invalid_passwords_part1 << password_entry unless part1_password_valid?(target_numbers, target_letter, target_password)
invalid_passwords_part2 << password_entry unless part2_password_valid?(target_numbers, target_letter, target_password)
end
puts "Part 1: Valid passwords: #{password_array.count - invalid_passwords_part1.count}"
puts "Part 2: Valid passwords: #{password_array.count - invalid_passwords_part2.count}"
| true |
ee86c08246ed7fd82f21ee041c5a66caf8cf7f39
|
Ruby
|
alexperez2160/ls_exercises
|
/loops/loops_2_9.rb
|
UTF-8
| 195 | 3.3125 | 3 |
[] |
no_license
|
number_a = 0
number_b = 0
loop do
number_a += rand(2)
number_b += rand(2)
puts number_a
puts number_b
next unless number_b == 5 || number_a == 5
puts "5 was reached"
break
end
| true |
bce1fa0165edbc52cc32f548d746192740d79620
|
Ruby
|
matthewpeak/ruby-oo-fundamentals-object-attributes-lab-nyc-web-021720
|
/lib/dog.rb
|
UTF-8
| 244 | 3.203125 | 3 |
[] |
no_license
|
class Dog
def name
@name
end
def name= (name)
@name = name
end
def name
"#{@name}".strip
end
def breed
@breed
end
def breed= (breed)
@breed = breed
end
def breed
"#{@breed}".strip
end
end
| true |
6b093b6089dce6cec3a8c98fdba2e5cf72b0e289
|
Ruby
|
LukVik/helloword
|
/app/models/oop_projects/student.rb
|
UTF-8
| 739 | 3.5 | 4 |
[] |
no_license
|
class Student
attr_accessor :first_name, :last_name, :email, :password
attr_reader :username
@first_name
@last_name
@email
# @username = "lukas1" # a da se to do def set_username 22
@username
@password
# def first_name=(name)
# @first_name = name
# end
# def first_name
# @first_name
# end
def set_username
@username = "lukas1"
end
def to_s
"First name: #{@first_name}"
end
end
lukas = Student.new
lukas.first_name = "Lukas"
lukas.last_name = "Vik"
lukas.email = "[email protected]"
lukas.set_username # nastaveni username pomoci metody set_username 22
# lukas.username = "lukas1" # kdyz to dam do atrr_reader 11
puts lukas.first_name
puts lukas.last_name
puts lukas.email
puts lukas.username
| true |
121b7d2bac842931db2767eb338b26a856a2964e
|
Ruby
|
MedetaiAkaru/optional_exercises
|
/iterations_2.rb
|
UTF-8
| 397 | 4.34375 | 4 |
[] |
no_license
|
# Module: Iterations
# Write a method count_a(word) that takes in a string word
# The method returns the number of a's in the word.
# Note: The method should count both lowercase (a) and uppercase (A)
def count_a(word)
# Write your code here
end
puts count_a("application") # => 2
puts count_a("bike") # => 0
puts count_a("Ambassador") # => 3
puts count_a("Alvin") # => 1
| true |
9244159a207c4a01a6d38520987f2854cd608def
|
Ruby
|
tmikeschu/the-spoken-tour-api
|
/app/services/inreach_service.rb
|
UTF-8
| 901 | 2.578125 | 3 |
[] |
no_license
|
class InreachService
def self.latest_coordinates
new.latest_coordinates
end
def latest_coordinates
{
location: {
lat: latitude(response_data), lng: longitude(response_data)
},
date: date(response_data)
}
end
def latitude(response_data)
Nokogiri.XML(response_data).css("Data[name='Latitude'] value").text.to_d rescue 0
end
def longitude(response_data)
Nokogiri.XML(response_data).css("Data[name='Longitude'] value").text.to_d rescue 0
end
def date(response_data)
Nokogiri.XML(response_data).css("Data[name='Time'] value").text
end
private
def conn
@conn ||= Faraday.new("https://inreach.garmin.com") do |conn|
conn.request(:basic_auth, ENV["inreach_user"], ENV["inreach_pw"])
end
@conn
end
def response
conn.get("/feed/Share/TommyCrosby")
end
def response_data
response.body
end
end
| true |
46f3a58f822983f1881e54860b45b9c385ef6157
|
Ruby
|
mharris717/basketball_pbp
|
/lib/basketball_pbp/pbp_file/base.rb
|
UTF-8
| 783 | 2.5625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
module BasketballPbp
module PBPFile
class Base
attr_accessor :path
include FromHash
fattr(:dir) do
path.split("/")[-2]
end
fattr(:short_filename) do
path.split("/")[-2..-1].join("/")
end
def each_row
CSV.foreach(path,:headers => true, :col_sep => delimiter) do |row|
h = {}
row.each do |k,v|
h[k] = v
end
fill_row(h)
h["filename"] = short_filename
yield(h)
end
end
def rows
res = []
each_row { |x| res << x }
res
end
def save!
PBPFile.coll.remove(:filename => short_filename)
each_row do |row|
PBPFile.coll.save(row)
end
end
end
end
end
| true |
e1f6e41e524c486eb37c4d123b8c7c05a957b17f
|
Ruby
|
billonrails/TeaLeaf_Submissions
|
/my_calculator.rb
|
UTF-8
| 620 | 4.03125 | 4 |
[] |
no_license
|
def say(msg)
puts "=> #{msg}"
end
say "Please enter your your first number:"
first_num = gets.chomp
say "Please enter your second number:"
second_num = gets.chomp
say "What operation would you like to do? Type 1)addition 2)subtraction 3)multiplication 4)division"
operation = gets.chomp
if operation == "1"
solution = first_num.to_i + second_num.to_i
elsif operation == "2"
solution = first_num.to_i - second_num.to_i
elsif operation == "3"
solution = first_num.to_i * second_num.to_i
elsif operation == "4"
solution = first_num.to_f / second_num.to_f
end
puts "The solution is #{solution}"
| true |
42cc7b35abed9b18a7f4a628203a526d149daa2f
|
Ruby
|
tomas-stefano/rspec-i18n
|
/examples/i18n/de/german_spec.rb
|
UTF-8
| 634 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
# coding: UTF-8
require 'lib/spec-i18n'
Spec::Runner.configure do |config|
config.spec_language :de
end
class Person
end
# PLEASE - Replace with GOOD EXAMPLES
#
beschreibe Person do
vorher(:von_jeder) do
@vorher = 'Before Keyword!'
end
es 'wahr sollte wahr sein' do
true.sollte wahr_sein
end
es 'falsch sollte falsch sein' do
false.sollte falsch_sein
end
es '@vorher sollte nicht null sein' do
@vorher.sollte_nicht null_sein
end
es 'leer sollte leer sein' do
[].sollte leer_sein
end
es 'nicht leer sollte nicht leer sein' do
[1].sollte_nicht leer_sein
end
end
| true |
288e2748318408a8938b494ec2353eabcc37fe17
|
Ruby
|
barbarian611/High-Card-Dealer
|
/game.rb
|
UTF-8
| 1,221 | 3.90625 | 4 |
[] |
no_license
|
require 'pry'
# Note: we only need `require_relative` if we end up calling a class by name in our file's logic. As such, you may have to add more `require_relative` statements accordingly.
require_relative "lib/hand"
require_relative "lib/deck"
#GAME START
# Your game logic here.
fifty_two_effing_cards = Deck.new
puts "GAME START!"
puts ""
puts "There are #{fifty_two_effing_cards.cards.length} cards in the deck"
puts ""
hand_1 = Hand.new
hand_2 = Hand.new
puts "Player 1 got #{hand_1.hand_reader}"
puts "Player 2 got #{hand_2.hand_reader}"
puts ""
puts "Player 1's hand value is #{hand_1.value_of_hand}"
puts "Player 2's hand balue is #{hand_2.value_of_hand}"
puts ""
if hand_1.value_of_hand > hand_2.value_of_hand
puts "Player 1 wins!"
else
if hand_2.value_of_hand > hand_1.value_of_hand
puts "Player 2 wins"
else
puts "Its a tie"
end
end
#There are 52 cards in a deck it is universally accepted why do we have to do
#52 cards thing dynamically yes I am going to rant about this
#player 1 was dealt something with Hand
#player 2 was dealt somethin with Hand
#player 1's hand total
#player 2's hand total
#if/else statements involving who has the bigger total and then who will woin
| true |
480802c9326846e4ab2c656f8eef3a5cc9036b85
|
Ruby
|
bbeaird/coding_challenges
|
/consecutive.rb
|
UTF-8
| 349 | 3.59375 | 4 |
[] |
no_license
|
def consecutive(arr)
arr.sort!
count = 0
prev = nil
arr.each do |num|
count += (num - prev - 1) unless prev.nil?
prev = num
end
count
end
def consecutive2(arr)
arr.sort!
min = arr[0]
max = arr[-1]
return max - min - arr.size + 1
end
arr = [5,10,15]
p consecutive(arr)
p consecutive([1,2,100])
p consecutive2([1,2,100])
| true |
b18708ad429f35f3427f96c5979df50838788af8
|
Ruby
|
ManageIQ/virtfs
|
/lib/virtfs/delegate_module.rb
|
UTF-8
| 1,118 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
require "delegate"
module VirtFS
module DelegateModule
def delegate_module(superclass)
mod = Module.new
methods = superclass.instance_methods
methods -= ::Delegator.public_api
methods -= [:to_s, :inspect, :=~, :!~, :===]
mod.module_eval do
def __getobj__ # :nodoc:
unless defined?(@delegate_dc_obj)
return yield if block_given?
__raise__ ::ArgumentError, "not delegated"
end
@delegate_dc_obj
end
def __setobj__(obj) # :nodoc:
__raise__ ::ArgumentError, "cannot delegate to self" if self.equal?(obj)
@delegate_dc_obj = obj
end
methods.each do |method|
define_method(method, Delegator.delegating_block(method))
end
end
mod.define_singleton_method :public_instance_methods do |all = true|
super(all) - superclass.protected_instance_methods
end
mod.define_singleton_method :protected_instance_methods do |all = true|
super(all) | superclass.protected_instance_methods
end
mod
end
end
end
| true |
e5f82e756cc258a804b1f1554390900aa348bd4f
|
Ruby
|
jociemoore/ruby_practice
|
/I2P_ch7_Hashes/exercise3.rb
|
UTF-8
| 188 | 3.296875 | 3 |
[] |
no_license
|
# hash
store = {jacket:"$50", shirt:"$20", hat:"$10"}
store.each_key{ |item| puts item }
store.each_value{ |price| puts price}
store.each{|item, price| puts "The #{item} costs #{price}."}
| true |
392f3179c8677e610f1fc798892f4786b0ce7f49
|
Ruby
|
alisajedi/mys3ql
|
/lib/mys3ql/s3.rb
|
UTF-8
| 2,757 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
require 'mys3ql/shell'
require 'fog'
module Mys3ql
class S3
include Shell
def initialize(config)
@config = config
Fog::Logger[:warning] = nil
end
def store(file, dump = true)
key = key_for(dump ? :dump : :bin_log, file)
s3_file = save file, key
if dump && s3_file
copy_key = key_for :latest
s3_file.copy @config.bucket, copy_key
log "s3: copied #{key} to #{copy_key}"
end
end
def delete_bin_logs
each_bin_log do |file|
file.destroy
log "s3: deleted #{file.key}"
end
end
def each_bin_log(&block)
bucket.files.all(:prefix => "#{bin_logs_prefix}").sort_by { |file| file.key[/\d+/].to_i }.each do |file|
yield file
end
end
def retrieve(s3_file, local_file)
key = (s3_file == :latest) ? key_for(:latest) : s3_file.key
get key, local_file
end
private
def get(s3_key, local_file_name)
s3_file = bucket.files.get s3_key
File.open(local_file_name, 'wb') do |file|
file.write s3_file.body
end
log "s3: pulled #{s3_key} to #{local_file_name}"
end
# returns Fog::Storage::AWS::File if we pushed, nil otherwise.
def save(local_file_name, s3_key)
s3.sync_clock
unless bucket.files.head(s3_key)
s3_file = bucket.files.create(
:key => s3_key,
:body => File.open(local_file_name),
:storage_class => 'STANDARD_IA',
:public => false
)
log "s3: pushed #{local_file_name} to #{s3_key}"
s3_file
end
end
def key_for(kind, file = nil)
name = File.basename file if file
case kind
when :dump; "#{dumps_prefix}/#{name}"
when :bin_log; "#{bin_logs_prefix}/#{name}"
when :latest; "#{dumps_prefix}/latest.sql.gz"
end
end
def s3
@s3 ||= begin
s = Fog::Storage.new(
:provider => 'AWS',
:aws_secret_access_key => @config.secret_access_key,
:aws_access_key_id => @config.access_key_id,
:region => @config.region
)
log 's3: connected'
s
end
end
def bucket
@directory ||= begin
d = s3.directories.get @config.bucket
raise "S3 bucket #{@config.bucket} not found" unless d # create bucket instead (n.b. region/location)?
log "s3: opened bucket #{@config.bucket}"
d
end
end
def dumps_prefix
"#{@config.database}/dumps"
end
def bin_logs_prefix
"#{@config.database}/bin_logs"
end
def bin_logs_exist?
@config.bin_log && @config.bin_log.length > 0 && File.exist?(@config.bin_log)
end
end
end
| true |
a155e13cdb141fb5e315a38b925841eb558f03a7
|
Ruby
|
timsully/introduction_to_programming
|
/ruby_basics/user_input/print_something_01.rb
|
UTF-8
| 289 | 4.34375 | 4 |
[] |
no_license
|
=begin
Write a program that asks the user whether they want the program to
print "something", then print it if the user enters y. Otherwise, print nothing.
=end
puts "Do you want me to print \"something\"? (y/n)"
user_input = gets.chomp
if user_input == "y" || "Y"
puts "something"
end
| true |
27335cee03da3c01eead0ede4bca3682502e6972
|
Ruby
|
jsvensson/streamstatus
|
/lib/object_cache.rb
|
UTF-8
| 256 | 2.890625 | 3 |
[] |
no_license
|
class ObjectCache
def initialize(client, cache, ttl)
@cache = client.cache(cache)
@ttl = ttl
end
def get(object)
@cache.get(object)
end
def put(object, value, ttl = @ttl)
@cache.put(object, value, {expires_in: ttl})
end
end
| true |
e26ec7134505358dfe8d267a1dc12a4457f11ef8
|
Ruby
|
tdeschamps/projet_perso
|
/gosu_game/player.rb
|
UTF-8
| 420 | 3.046875 | 3 |
[] |
no_license
|
require 'gosu'
class Player
attr_accessor :player_x, :player_y
def initialize(window)
@image = Gosu::Image.new(window, "media/pharrel.png", false)
@player_x, @player_y = 400, 400
@vel_y = 0
end
def accelerate
@vel_y -= Gosu::offset_y(1,0.1)
end
def move
@player_y += @vel_y unless player_y > 750
@vel_y *= 0.95
end
def draw
@image.draw(@player_x, @player_y, 1)
end
end
| true |
0e4f01958bdf846aaa83d7988133ef6bb72734d4
|
Ruby
|
Scott2bReal/LS-ruby-basic-exercises
|
/debugging/multiply_by_five.rb
|
UTF-8
| 427 | 4.90625 | 5 |
[] |
no_license
|
# When the user inputs 10, we expect the program to print The result is 50!, but
# that's not the output we see. Why not
def multiply_by_five(n)
n * 5
end
puts "Hello! Which number would you like to multiply by 5?"
number = gets.chomp
puts "The result is #{multiply_by_five(number)}!"
# The program doesn't work because the return value of gets is a string, not an
# integer. number should be assigned to gets.chomp.to_i
| true |
7c543cc662a4112344d13f6f66d69cad67dd6b6f
|
Ruby
|
DWBayly/ar-exercises
|
/exercises/exercise_6.rb
|
UTF-8
| 763 | 3.046875 | 3 |
[] |
no_license
|
require_relative '../setup'
require_relative './exercise_1'
require_relative './exercise_2'
require_relative './exercise_3'
require_relative './exercise_4'
require_relative './exercise_5'
puts "Exercise 6"
puts "----------"
# Your code goes here ...
@store1.employees.create(first_name: "Khurram", last_name: "Virani", hourly_rate: 60)
@store1.employees.create(first_name: "David", last_name: "Bayly", hourly_rate: 40)
@store1.employees.create(first_name: "William", last_name: "Wallace", hourly_rate: 42)
@store2.employees.create(first_name: "Albert", last_name: "Fish", hourly_rate: 62)
@store2.employees.create(first_name: "George", last_name: "Cuthbert", hourly_rate: 60)
@store2.employees.create(first_name: "Lucy", last_name: "Baphomet", hourly_rate: 666)
| true |
3310128c767e5a4eae545ab40ae5047b734502d6
|
Ruby
|
carrot-u/assignments-2019
|
/assignment-2-ruby/rborder/guessing_game.rb
|
UTF-8
| 4,608 | 3.734375 | 4 |
[] |
no_license
|
# same robot from the room-cleaner app
def robot
sleep 1
puts " _______ "
puts " _/ \\_ "
puts " / | | \\ "
puts " / |__ __| \\ "
puts " |--(( )| |( ))--| "
puts " | | | | "
puts " |\\ |_| /| "
puts " | \\ / | "
puts " \\| / ___ \\ |/ "
puts " \\ | / _ \\ | / "
puts " \\_________/ "
puts " _|_____|_ "
puts " ____|_________|____ "
puts " / \\ "
sleep 1
end
# user guess
def user_guess(num)
goal = rand(1..num)
puts "The number has been set. Do your best!"
counter = 0
guess = 0
until guess == goal do
guess = gets.chomp.to_i
if guess > goal
puts "lower"
elsif guess < goal
puts "higher"
else
puts "Success!"
end
counter +=1
end
puts "You completed the game in #{counter} tries."
end
# random guess search
def compu_guess_random
goal = 0
counter = 0
guess = 0
print "Please provide a number between 1 and 100: "
until goal > 0 do
goal = gets.chomp.to_i
if goal == 0
puts "Please provide a valid number, idiot."
elsif goal < 0
puts "Nice try, but it needs to be a positive number."
else
puts "The game will now begin"
end
end
puts "I will begin guessing with a random strategy!"
until guess == goal do
guess = rand(1..100)
puts "I guess that the number is #{guess}."
sleep 0.1
counter += 1
end
puts "I was able to win your game and it only took me #{counter} tries."
end
# linear guess search
def compu_guess_linear
goal = 0
guess = 0
print "Please provide a number between 1 and 100: "
until goal > 0 do
goal = gets.chomp.to_i
if goal == 0
puts "Please provide a valid number, idiot."
elsif goal < 0
puts "Nice try, but it needs to be a positive number."
else
puts "The game will now begin"
end
end
puts "I will begin guessing with a linear strategy!"
until guess == goal do
guess += 1
puts "I guess that the number is #{guess}."
sleep 0.1
end
puts "I was able to win your game and it only took me #{guess} tries."
end
# linear binary search
def compu_guess_binary
first = 1
last = get_number
counter = 0
goal = 0
print "Please provide a number between 1 and #{last}: "
until goal > 0 do
goal = gets.chomp.to_i
if goal == 0
puts "Please provide a valid number, idiot."
elsif goal < 0
puts "Nice try, but it needs to be a positive number."
else
puts "The game will now begin"
end
end
puts "I will begin guessing with a binary search strategy!"
while first <= last
midpoint = (first + last) / 2
if midpoint == goal
return "I am becometh, death, finder of numbers. #{midpoint} was foolish of you to pick."
elsif midpoint < goal
first = midpoint + 1
else
last = midpoint - 1
end
counter += 1
puts "I guess that the number is #{midpoint}."
end
puts "The number is #{midpoint} and it only took me #{counter} tries."
end
# formatting methods
def line_break
puts "*" * 40
end
# prompts for valid number in difficult selection
def get_number
while 0 != nil
puts "Please select a positive integer to set the difficulty."
num = gets.chomp.to_i
if num == 0
puts "Is this what you call a number?"
elsif num < 0
puts "You aren't good a following instructions."
else
return num
end
end
end
# gives the user option to select from availale games
def game_select
line_break
puts "\n"
puts "Available Games:"
puts "\n"
puts "Classic - Human vs CPU"
puts "Reversed - CPU vs Human"
puts "\n"
selection = gets.chomp.downcase
if selection == "classic"
max_range = get_number
user_guess(max_range)
elsif selection == "reversed"
line_break
puts "Select the skill level of the CPU."
puts "Low - Random Search"
puts "Medium - Linear Search"
puts "Expert - Binary Search"
puts "\n"
difficulty = gets.chomp.downcase
if difficulty == "low"
robot
puts "My supreme intellect is grandiloquent."
compu_guess_random
elsif difficulty == "medium"
robot
puts "I have witnessed 14 million possible timelines, and in all of them you lose."
compu_guess_linear
elsif difficulty == "expert"
robot
puts "The end is nigh."
result = compu_guess_binary
puts result
else
puts "Not a valid difficulty. Try low, medium or expert."
end
else
puts "Exiting"
end
end
game_select
| true |
96e2f04f37d69fdf81ca2bab627e5c7a17b66bc6
|
Ruby
|
xelex/brute-dict
|
/dictionary.rb
|
UTF-8
| 2,014 | 3.921875 | 4 |
[
"Unlicense"
] |
permissive
|
##
# A simple brute dictionary class
class Dictionary
def initialize(opt = {})
@filters = []
@filters_negative = []
@power_cache = []
alphabet(opt[:abc])
length(opt[:len])
end
##
# Set alphabet
def alphabet(abc)
@alphabet = abc.to_s.chars.sort.uniq
return reset()
end
##
# Set word length
def length(len)
@length = len.to_i
return reset()
end
##
# Resets iterator
def reset
@iterator = 0
@total = nil
if @alphabet && [email protected]? && @length.to_i > 0
(@length + 1).times { |v|
@power_cache[v] = @alphabet.count ** v
}
end
return self
end
##
# Set positive filter (regexp)
# Operator "next" will return sorted items only
def match(regexp)
@filters.push(regexp)
return reset()
end
##
# Set filter (regexp)
# Operator "next" will return sorted items only
def nomatch(regexp)
@filters_negative.push(regexp)
return reset()
end
##
# Return number of variations.
# @return total number of variations (filters are not in use)
def total
if @total_cache.nil?
@total_cache = @alphabet.count ** @length
end
return @total_cache
end
##
# Return next part of variants (prioritized goes first)
def next(n = 1)
result = []
while @iterator < total() && result.count < n
word = n_to_word(@iterator)
if check_filter(word)
result.push(word)
end
@iterator += 1
end
return result
end
##
# Returns progress (in percents)
def progress
@iterator / total()
end
private
def n_to_word(n)
return '' if @alphabet.count == 0
div = [0] * @length
@length.times { |pow|
div[pow] = (n % @power_cache[pow + 1])/ @power_cache[pow]
}
return div.map{|i| @alphabet[i]}.join()
end
def check_filter(word)
return false if @filters.find{|filter| !filter.match(word)}
return false if @filters_negative.find{|filter| filter.match(word)}
return true
end
end
| true |
a1d860765b96abf0d07625cbdf2a90d10e22c447
|
Ruby
|
MichaelAldaba/random
|
/tictactoe/third_iteration/spec/board_spec.rb
|
UTF-8
| 6,803 | 3.234375 | 3 |
[] |
no_license
|
require 'spec_helper'
describe Board do
before :each do
@board = Board.new
end
describe ".new" do
it "should create a Board object" do
expect(@board).to be_an_instance_of Board
end
end
describe "#size" do
context "when :size is not given" do
it "size should return :size" do
@board = Board.new(:size => 4)
expect(@board.size).to eq 4
end
end
context "when :size is not given" do
it "size return 3" do
expect(@board.size).to eq 3
end
end
end
describe "#empty?" do
context "when board is empty" do
it "should return true" do
expect(@board.empty?).to be true
end
end
context "when board is not empty" do
it "should return false" do
@board.state = [nil, nil, nil, "X", nil, nil, nil, nil, nil]
expect(@board.empty?).to be false
end
end
end
describe "#tie?" do
context "when 3 X 3 board is full" do
it "should return true" do
@board.state = ["X", "O", "X", "O", "X", "O", "X", "O", "X"]
expect(@board.tie?).to be true
end
end
context "when 3 X 3 board is not full" do
it "should return false" do
@board.state = ["X", nil, "O", "X", "O", "X", "O", "X", "O"]
expect(@board.tie?).to be false
end
end
context "when 4 X 4 board is full" do
it "should return true" do
@board.state = ["X", "O", "X", "O", "X", "O", "X", "O", "X", "O", "X", "O", "X", "O", "X", "O"]
expect(@board.tie?).to be true
end
end
context "when 4 X 4 board is not full" do
it "should return false" do
@board.state = ["X", "O", "X", "O", "X", "O", "X", "O", "X", "O", "X", "O", "X", "O", "X", nil]
expect(@board.tie?).to be false
end
end
end
describe "#update" do
it "should add marker at index" do
@board.update(5, "X")
expect(@board.state).to eq([nil, nil, nil, nil, nil, "X", nil, nil, nil])
end
end
describe "#get_lines" do
context "when board is 3 X 3" do
it "should return an array with the 8 correct lines" do
expect(@board.get_lines).to eq([[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]])
end
end
context "when board is 4 X 4" do
it "should return an array with the 10 correct lines" do
@board = Board.new(:size => 4)
expect(@board.get_lines).to eq([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15], [0, 5, 10, 15], [3, 6, 9, 12]])
end
end
end
describe "#get_rows" do
context "when board is 3 X 3" do
it "should return 3 correct rows" do
expect(@board.get_rows).to eq([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
end
end
context "when board is 4 X 4" do
it "should return 4 correct rows" do
@board = Board.new(:size => 4)
expect(@board.get_rows).to eq([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]])
end
end
end
describe "#get_columns" do
context "when board is 3 X 3" do
it "should return 3 correct columns" do
expect(@board.get_columns).to eq([[0, 3, 6], [1, 4, 7], [2, 5, 8]])
end
end
context "when board is 4 X 4" do
it "should return 4 correct columns" do
@board = Board.new(:size => 4)
expect(@board.get_columns).to eq([[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15]])
end
end
end
describe "#get_diagonals" do
context "when board is 3 X 3" do
it "should return 2 correct diagonals" do
expect(@board.get_diagonals).to eq([[0, 4, 8], [2, 4, 6]])
end
end
context "when board is 4 X 4" do
it "should return 2 correct diagonals" do
@board = Board.new(:size => 4)
expect(@board.get_diagonals).to eq([[0, 5, 10, 15], [3, 6, 9, 12]])
end
end
end
describe "#space_available?" do
context "when space is filled" do
it "should return false" do
@board.state = ["X", "O", "X", nil, nil, nil, nil, nil, nil]
expect(@board.space_available?(0)).to be false
end
end
context "when space is not filled" do
it "should return true" do
@board.state = ["X", "O", "X", nil, nil, nil, nil, nil, nil]
expect(@board.space_available?(3)).to be true
end
end
end
describe "#available_spaces" do
it "should return an Array of available spaces" do
@board.state = ["X", "O", "X", nil, nil, nil, nil, nil, nil]
expect(@board.available_spaces).to eq([3, 4, 5, 6, 7, 8])
end
end
describe "#win?" do
context "with a winner on a 3 X 3 board" do
it "should return true" do
@board.state = ["X", "X", "X", "O", nil, "O", nil, nil, nil]
expect(@board.win?).to be true
end
end
context "with no winner on a 3 X 3 board" do
it "should return false" do
@board.state = ["X", "O", "X", "X", "O", "O", "O", "X", "X"]
expect(@board.win?).to be false
end
end
context "with a winner on a 4 X 4 board" do
it "should return true" do
@board = Board.new(:size => 4)
@board.state = ["X", "O", "O", "O", nil, "X", nil, nil, nil, nil, "X", nil, nil, nil, nil, "X"]
expect(@board.win?).to be true
end
end
context "with no winner on a 4 X 4 board" do
it "should return false" do
@board = Board.new({:size => 4})
@board.state = ["X", "O", "O", "O", nil, "X", nil, nil, nil, nil, "X", nil, nil, nil, nil, nil]
expect(@board.win?).to be false
end
end
end
describe "#winner" do
context "with first player as winner on a 3 X 3 board" do
it "should return first player" do
@board.state = ["X", "X", "X", "O", nil, "O", nil, nil, nil]
expect(@board.winner).to eq "X"
end
end
context "with second player as winner on a 3 X 3 board" do
it "should return second player" do
@board.state = ["X", nil, "X", "O", "O", "O", nil, nil, "X"]
expect(@board.winner).to eq "O"
end
end
context "with first player as winner on a 4 X 4 board" do
it "should return first player" do
@board = Board.new(:size => 4)
@board.state = ["X", "O", "O", "O", nil, "X", nil, nil, nil, nil, "X", nil, nil, nil, nil, "X"]
expect(@board.winner).to eq "X"
end
end
context "with second player as winner on a 4 X 4 board" do
it "should return second player" do
@board = Board.new(:size => 4)
@board.state = ["O", "O", "O", "O", "X", "X", nil, nil, nil, nil, "X", nil, nil, nil, nil, "X"]
expect(@board.winner).to eq "O"
end
end
end
end
| true |
198506f3cdb29e1730815b050e51740c14c203b7
|
Ruby
|
staunchRobots/lita-hipchat-extensions
|
/lib/lita/handlers/hipchat-extensions/timezone.rb
|
UTF-8
| 3,350 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
module Lita
module Handlers
class HipchatExtensions < Handler
# Handles Timezone shenanigans
class Timezone < Base
include RelativeDistances
route /^tz\s+(@\w+)/, :show, command: true
route /^tz\s+list/, :list, command: true
route /^tz\s+when\s+(.*)/, :when, command: true
route /^ls\s+(.*)/, :last_seen, command: true
# TODO: Document me
def show(response)
return unless enabled?
mention_name = response.args.first.gsub "@", ""
response.reply t("timezones.show.usage") and return unless mention_name
user = Lita::User.fuzzy_find(mention_name)
response.reply "#{mention_name}'s timezone is #{format_timezone(user.metadata["timezone"])}"
end
# TODO: Document me
def when(response)
return unless enabled?
time = response.args[1]
response.reply ("timezone.when.usage") and return unless time
Time.zone = current_timezone(response)
current_time = time == "now" ? Time.zone.now : Time.zone.parse(time)
user_timezones.each do |tz|
converted_time = current_time.in_time_zone(ActiveSupport::TimeZone[tz])
response.reply "#{tz}: #{format_time(converted_time)}"
end
end
# Responds with a human friendly translation on how long ago this user
# was last active
def last_seen(response)
return unless enabled?
name = extract_name(response.args[0])
response.reply t("timezones.last_seen.usage") and return unless name
# Get the latest info
ago = time_ago_in_words(Time.now, Time.at(last_active(name)) )
response.reply "#{name} was last seen #{ago} ago."
end
# TODO: Document me
def list(response)
response.reply user_timezones
end
protected
def user_timezones
lita_users.map { |u| u.metadata["timezone"] }.uniq.sort
end
def current_timezone(response)
fetch_timezone(response.user.mention_name)
end
def last_active(mention_name)
id = Lita::User.fuzzy_find(mention_name).metadata["id"]
return nil unless id
client.user(id)["last_active"].to_i
end
def fetch_timezone(mention_name)
ActiveSupport::TimeZone[ Lita::User.fuzzy_find(mention_name).metadata["timezone"] ]
end
def fetch_time(source_tz, target_tz)
# Fetch the timezones
tz_source = fetch_timezone(source)
tz_target = fetch_timezone(target)
# Check that we have them
raise "Nope" unless tz_user && tz_target
Time.zone = tz_user
# Parse the time locally
user_time = time == "now" ? Time.zone.now : Time.zone.parse(time)
# Move the time to the target's tz
target_time = user_time.in_time_zone(tz_target)
end
# TODO: Document me
def format_timezone(timezone)
tz = ActiveSupport::TimeZone[ timezone ]
"GMT#{tz.formatted_offset[0..2].to_i}"
end
# TODO: Document me
def format_time(time)
time.strftime("%I:%M%P")
end
end
Lita.register_handler(Timezone)
end
end
end
| true |
77e5a2b9c34ea37a042fb4551fca550ff9d92bb8
|
Ruby
|
zear/sdljava
|
/sdljava/src/org/gljava/opengl/native/ftgl/post-process.rb
|
UTF-8
| 2,289 | 3 | 3 |
[] |
no_license
|
#!/usr/bin/ruby -w
require "find"
require "ftools"
# temporary hack until I can figure out a better way to do this
# process the given files, change the methods names to start
# with lower case, remove the methods in remove_methods list
# then cat the contents of .post file to redefine or add new
# methods
files=[
"FTFont.java",
"FTGLBitmapFont.java",
"FTGLExtrdFont.java",
"FTGLPixmapFont.java",
"FTGLPolygonFont.java",
"FTGLPixmapFont.java",
"FTGLPolygonFont.java",
"FTGLTextureFont.java"
]
# these are the methods that need to be removed since they are redefined in the .post files
remove_methods=[
"public FTGLBitmapFont(String fontFilePath)"
]
java_src="../../../../../org/gljava/opengl/ftgl"
if not Dir::chdir java_src
print "Failed to change directory to: #{java_src}\n"
exit
end
print "Changed directory to: #{java_src}\n"
def fixMethodNames(lines)
for i in 0..lines.length
line = lines[i]
if line =~ /(public|protected) \w+ (\w+)[(]/
(access,return_type,name,r1,r2) = line.split(" ")
index = line.index name
line[index,1] = line[index,1].downcase
end
end
end
def doRemove(lines, remove_methods)
for i in 0..lines.length
line = lines[i]
next if line == nil
remove_methods.each{|m|
if line.index m
endOfMethod = findEndOfMethod(i, lines)
print "end=#{endOfMethod}\n"
remove = endOfMethod = i
for x in 0..remove
lines[i+x] = nil
end
i += remove
end
}
end
end
def findEndOfMethod(index, lines)
for i in index..lines.length
line = lines[i]
return i if line.index "}"
end
0
end
Find.find(".") do |path|
path = path[2..path.length] # strip off leading ./
next if not files.include? path
print "Processing #{path}\n"
lines = File.new(path).readlines
# get rid of last line
lines[lines.length-1] = nil
fixMethodNames(lines)
doRemove(lines, remove_methods)
# add any code from .post file if it exists
post_path = path[0..path.length-6] + ".post"
if File.exist?post_path
post = File.new(post_path).readlines
end
f = File.new("#{path}.tmp", "w+")
f << lines
f << post if not post == nil
f << "\n}"
f.close
# move it to the actual file now
File.move("#{path}.tmp", path)
end
| true |
c62e4f395940b8a62427ea12b9570061c9b5b68d
|
Ruby
|
danielmontgomery/ruby-prac
|
/block_practice.rb
|
UTF-8
| 2,366 | 4.5625 | 5 |
[] |
no_license
|
#ENUMERABLE
#**TODO ENTER CODE**
# * Output all the methods of the Enumerable class to the console
puts Enumerable.methods
# **TODO ENTER CODE **
# * create a class called Persons that hand rolls an 'each' iterator method, inside of which you
# define some names, the each method will allow you to iterate over these
# This means that the class you create...say Person... will respond to Person.each.
# * use a normal each loop to iterate over the class and output the names to the console.
class Persons
def self.each(*people)
people.each{|person| puts "#{person}"}
end
# you can also define names as
@names = ["Donald", "Mickey", "Mouse", "Aaron", "Alicia", "Mark", "Bob", "Zach Danger Brown"]
def self.name_method
puts "============================"
puts "here's your names:"
puts @names.each {|x| print x, ", " }
end
def self.start_with_a
puts "=============="
puts "The following names start with 'A':"
puts @names.select {|x| x[0] == ?A }
end
def self.is_bob_here
puts "=============="
puts "Is bob around?"
if @names.include?("Bob")
puts "Bob is around!"
else
puts "Bob isn't here"
end
puts "=============="
end
def self.spaces
if @names.include(" ")
puts "I'm still working on this one. It should print the name of the person with a space or two in their name."
end
puts "=============="
end
end
puts "============== Starting output =============="
Persons.each "Joe", "Jim", "Jack", "John", "Randy", "Whatever name you want"
Persons.name_method
# **TODO ENTER CODE**
# * Find a name starting with 'a', you will need to include the Enumerable module into Persons, make sure you have a name
# starting with 'a'
Persons.start_with_a
# **TODO ENTER CODE**
# * Check if 'bob' is included in your names
Persons.is_bob_here
# **TODO ENTER CODE**
#Search for if there is one name that has a space in it
Persons.spaces
# **TODO ENTER CODE**
# * Create an array of numbers 1-10
# * Search an array to find all matches for numbers greater than 5
# **TODO ENTER CODE**
# * Do the opposite as above, using the exact same block, but a different method, return all numbers that are less
# than 5
# **TODO ENTER CODE**
# * Create an array of colors: red, orange, yellow,green,violet,indigo
# * Using a regex search the array to see which entries contain 'o'
| true |
39661fdad9a63f407bc0df29ed04b65a40e96a94
|
Ruby
|
noelrappin/foot_travel
|
/spec_fast/roles/friend_spec.rb
|
UTF-8
| 1,250 | 2.796875 | 3 |
[] |
no_license
|
require 'fast_spec_helper'
require 'roles/buyer'
describe Friend do
let(:me) { OpenStruct.new(:first_name => "Fred", :last_name => "Flintstone") }
let(:friend) { OpenStruct.new(:first_name => "Barney") }
let(:enemy) { OpenStruct.new(:first_name => "Spacely") }
before(:each) do
me.extend(Friend)
friend.extend(Friend)
enemy.extend(Friend)
end
it "has a full name" do
me.full_name.should == "Fred Flintstone"
me.sort_name.should == ["Flintstone", "Fred"]
end
it "can create a friend" do
result = me.befriend(friend)
result.sender.should == me
result.receiver.should == friend
end
it "recognizes sends as friends" do
me.friends = [Relationship.new(:sender => me, :receiver => friend)]
me.friends_received = []
me.all_friends.should == [friend]
me.should be_friends_with(friend)
me.status_with(friend).should == "Friends"
me.should_not be_friends_with(enemy)
me.status_with(enemy).should == "No"
end
it "recognizes receives as friends" do
me.friends = []
me.friends_received = [Relationship.new(:sender => friend, :receiver => me)]
me.all_friends.should == [friend]
me.should be_friends_with(friend)
me.should_not be_friends_with(enemy)
end
end
| true |
fe08d48acea4953e54f93589fea406997b8dcf8a
|
Ruby
|
thiagoa/menu_maker
|
/lib/menu_maker/path.rb
|
UTF-8
| 638 | 3.1875 | 3 |
[
"MIT"
] |
permissive
|
module MenuMaker
class Path
Methods = %i[get post put patch delete]
def self.valid_method?(method)
Methods.include? method
end
attr_reader :method, :path
def initialize(method, path)
method = method.to_sym.downcase
unless self.class.valid_method? method
fail PathError, "Method must be one of: #{Methods.join(', ')}"
end
@method = method
@path = path.to_s
end
def ==(other)
other = Converter.convert(other)
method == other.method && path == other.path
end
def to_s
path
end
PathError = Class.new StandardError
end
end
| true |
b5df2a6c7e26f178e89b22c9648017ef0dfd4548
|
Ruby
|
PreetBhadana/Training
|
/Ruby/Ruby_Practice/FIle IO Practice Programs/Gets_statement.rb
|
UTF-8
| 65 | 2.6875 | 3 |
[] |
no_license
|
# Gets Statement
puts "Enter Input here : "
val1 = gets
puts val1
| true |
dcacc7d1ef0bfa41ab799803a4f9bc146ea739fb
|
Ruby
|
rejeep/evm
|
/lib/evm/command/config.rb
|
UTF-8
| 512 | 2.5625 | 3 |
[] |
no_license
|
module Evm
module Command
class Config
def initialize(argv, options = {})
key, value = argv
unless key
Evm.config.all.each do |k, v|
STDOUT.puts("#{k} => #{v}")
end
return
end
unless Evm::CONFIG_KEYS.include?(key.to_sym)
raise Evm::Exception, "Invalid config key: #{key}"
end
if value
Evm.config[key] = value
end
STDOUT.puts(Evm.config[key])
end
end
end
end
| true |
27ebfa68a3ef4584dc6a9d1dcada3890e3caa6cd
|
Ruby
|
SuzanneHuldt/robot-wars
|
/lib/action/action.rb
|
UTF-8
| 365 | 2.578125 | 3 |
[] |
no_license
|
class Action
def initialize
@move = Move.new
end
def new_action(timebank, info)
update_info(timebank, info)
@move.new_move(@my_id, @op_id, @info[:field], @timebank)
end
private
def update_info(timebank, info)
@info = info
@timebank = timebank
@my_id = @info[:your_botid].to_s
@op_id = @my_id == '0' ? '1' : '0'
end
end
| true |
34c96edb5825103b2b71df765fabfd9414ff7e94
|
Ruby
|
erik-krogh/ql
|
/ruby/ql/test/library-tests/dataflow/type-tracker/type_tracker.rb
|
UTF-8
| 211 | 3.171875 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
class Container
def field=(val)
puts self.field
@field = val
end
def field
@field
end
end
def m()
var = Container.new
var.field = "hello"
puts var.field
end
| true |
68353e7c0eec5de04a26fd0ca61aa8eedb15a1be
|
Ruby
|
Arnaudboscq/rails-stupid-coaching
|
/app/controllers/coaching_controller.rb
|
UTF-8
| 668 | 3.109375 | 3 |
[] |
no_license
|
class CoachingController < ApplicationController
def answer
@query = params[:query]
coach_answer_enhance
end
def ask
end
def home
end
end
private
def coach_answer
if @query.include? "?"
@query = "Silly question, get dressed and go to work!"
elsif @query == "I am going to work right now!"
@query = ""
else
@query = "I don't care, get dressed and go to work!"
end
end
def coach_answer_enhanced
basic_answer = coach_answer(@query)
if @query == "I AM GOING TO WORK RIGHT NOW!"
return ""
elsif @query == @query.upcase
return "I can feel your motivation! #{basic_answer}"
else
return basic_answer
end
end
| true |
9929170ce5e393c37d3cd84feb1ed9cbb1913c6e
|
Ruby
|
jessjchang/ruby-basics-exercises
|
/user_input/opposites_attract.rb
|
UTF-8
| 740 | 4 | 4 |
[] |
no_license
|
def valid_number?(number_string)
number_string.to_i.to_s == number_string && number_string.to_i != 0
end
num_1 = nil
num_2 = nil
loop do
loop do
puts ">> Please enter a positive or negative integer:"
num_1 = gets.chomp
break if valid_number?(num_1)
puts ">> Invalid input. Only non-zero integers are allowed."
end
loop do
puts ">> Please enter a positive or negative integer:"
num_2 = gets.chomp
break if valid_number?(num_2)
puts ">> Invalid input. Only non-zero integers are allowed."
end
break if num_1.to_i * num_2.to_i < 0
puts ">> Sorry. One integer must be positive, one must be negative.\n>> Please start over."
end
sum = num_1.to_i + num_2.to_i
puts "#{num_1} + #{num_2} = #{sum}"
| true |
d018a4550f03504fd504f982af88fc4101d4b77a
|
Ruby
|
BaptPrn/tabata_genetator
|
/db/seeds.rb
|
UTF-8
| 12,019 | 2.875 | 3 |
[] |
no_license
|
puts "Creating exercises"
Exercise.create(
name: "Abdos complets",
exercise_type: "Abdos",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Allongé sur le dos, remonter le buste et les genoux jusqu'à une position accroupie. Enchainer de manière dynamique."
)
puts "."
Exercise.create(
name: "Ciseaux",
exercise_type: "Abdos",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Position assise jambes tendues, croiser les jambes en alternant"
)
puts "."
Exercise.create(
name: "Complets avec mains au sol",
exercise_type: "Abdos",
equipment: "Aucun",
initial_status: nil,
available: nil,
description:
"Position assise avec mains au sol et jambes tendues, plier les jambes en remontant le buste puis les retendre les jambes en descendant le buste."
)
puts "."
Exercise.create(
name: "Corde à sauter",
exercise_type: "Cardio",
equipment: "Corde à sauter",
initial_status: nil,
available: nil,
description: ""
)
puts "."
Exercise.create(
name: "Dips",
exercise_type: "Tris",
equipment: "Chaise/banc",
initial_status: nil,
available: nil,
description: "Mains sur une chaise, fesses dans le vide et jambes tendues, alterner bras pliés / bras tendus"
)
puts "."
Exercise.create(
name: "Développé épaules avec haltères",
exercise_type: "Epaules",
equipment: "Haltères",
initial_status: nil,
available: nil,
description: "Bras écartés, coudes à 90°, remonter les altères au dessus de la tête et enchainer"
)
puts "."
Exercise.create(
name: "Elévations frontales avec haltères",
exercise_type: "Epaules",
equipment: "Haltères",
initial_status: nil,
available: nil,
description: "Debout bras tendus le long du corps, remonter une altère face à soi bras tendu puis alterner"
)
puts "."
Exercise.create(
name: "Elévations latérales avec haltères",
exercise_type: "Epaules",
equipment: "Haltères",
initial_status: nil,
available: nil,
description: "Bras semi-fléchis le long du corps, ramener les bras à hauteur des épaules en gardant les coudes au dessus des altères"
)
puts "."
Exercise.create(
name: "Fentes sautées",
exercise_type: "Cardio",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Enchainer les fentes jambe gauche/droite de manière dynamique"
)
puts "."
Exercise.create(
name: "Fentes sautées sur chaise",
exercise_type: "Cardio",
equipment: "Chaise/banc",
initial_status: nil,
available: nil,
description:
"1 pied sur le sol, l'autre sur une chaise, remonter le plus haut possible au dessus de la chaise en alternant la jambe de poussée."
)
puts "."
Exercise.create(
name: "Gainage abdos position assise",
exercise_type: "Abdos",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Assis sur le sol, descendre le buste le plus bas possible sans décoller les pieds. Tenir la position."
)
puts "."
Exercise.create(
name: "Gainage dorsal",
exercise_type: "Dos",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Sur le dos, coudes au sol et jambes tendues, tenir la position en essayant de pousser le ventre le plus haut possible"
)
puts "."
Exercise.create(
name: "I au TRX",
exercise_type: "Epaules",
equipment: "TRX",
initial_status: nil,
available: nil,
description:
"Position de départ bras tendus face à vous, remonter les bras serrés à la verticale (position I). Gérer la difficulté en avançant/reculant les pieds."
)
puts "."
Exercise.create(
name: "L'oiseau avec haltères",
exercise_type: "Dos",
equipment: "Haltères",
initial_status: nil,
available: nil,
description:
"Jambes semi-fléchies, poitrine face au sol et altères sous la poitrine, écarter les bras jusqu'à les ramener parallèles au sol "
)
puts "."
Exercise.create(
name: "Montée 2 genoux joints",
exercise_type: "Cardio",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Sur place, remonter en même temps les 2 genoux. Enchainer le plus vite possible"
)
puts "."
Exercise.create(
name: "Montées 2 genous mains au sol",
exercise_type: "Cardio",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Départ position gainage bras tendus. Ramener les pieds au niveau de la poitrine puis revenir en position de départ"
)
puts "."
Exercise.create(
name: "Montées de genous",
exercise_type: "Cardio",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Sur place, monter les genoux le plus vite et le plus haut possible"
)
puts "."
Exercise.create(
name: "Mountain climbers",
exercise_type: "Cardio",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Faire des montées de genoux avec les mains au sol"
)
puts "."
Exercise.create(
name: "Mountain climbers croisés (sans vitesse)",
exercise_type: "Abdos",
equipment: "Aucun",
initial_status: nil,
available: nil,
description:
"Position gainage bras tendus. Ramener le genoux au niveau du coude opposé puis revenir en position de départ et alterner"
)
puts "."
Exercise.create(
name: "Plank push-up",
exercise_type: "Tris",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Position gainage mains au sol, remonter jusqu'à avoir les 2 bras tendus puis redescendre et recommencer."
)
puts "."
Exercise.create(
name: "Pompes TRX",
exercise_type: "Pecs",
equipment: "TRX",
initial_status: nil,
available: nil,
description: "Pompes pieds au sol et mains dans le TRX"
)
puts "."
Exercise.create(
name: "Pompes classiques",
exercise_type: "Pecs",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Mains largeur d'épaules, descendre en gardant les coudes le long du corps"
)
puts "."
Exercise.create(
name: "Pompes déclinées",
exercise_type: "Pecs",
equipment: "Chaise/banc",
initial_status: nil,
available: nil,
description: "Pompes avec pieds sur une chaise/banc"
)
puts "."
Exercise.create(
name: "Pompes mains serrées sur les genous",
exercise_type: "Pecs",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Genoux au sol, mains serrées sous la poitrine, creuser le dos avant de tendre les bras."
)
puts "."
Exercise.create(
name: "Pompes mains écartées",
exercise_type: "Pecs",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Mains à 1,5x la largeur des épaules, descendre avec les coudes légèrement orientés vers l'extérieur"
)
puts "."
Exercise.create(
name: "Pompes spider-man",
exercise_type: "Pecs",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Pompes. Ramener le genoux au niveau du coude à la descente"
)
puts "."
Exercise.create(
name: "Pompes épaules",
exercise_type: "Epaules",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Pompes avec le corps en V inversé, fesses le plus haut possible"
)
puts "."
Exercise.create(
name: "Reverse snow angels",
exercise_type: "Dos",
equipment: "Aucun",
initial_status: nil,
available: nil,
description:
"Allongé sur le ventre, buste relevé et bras tendus le long du corps. Ramener les bras au dessus de la tête en les gardant tendus et les mains le plus haut possible."
)
puts "."
Exercise.create(
name: "Rings-rows au TRX",
exercise_type: "Dos",
equipment: "TRX",
initial_status: nil,
available: nil,
description:
"Pieds au sol et bras tendus face à soi, ramener les mains au niveau des côtes en tirant sur les coudes. Gérer la difficulté en avançant/reculant les pieds."
)
puts "."
Exercise.create(
name: "Rotations de buste",
exercise_type: "Abdos",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Position assise, toucher le plus loin possible derrière soi de chaque coté (avec ou sans altère)"
)
puts "."
Exercise.create(
name: "Rouleau",
exercise_type: "Abdos",
equipment: "Rouleau",
initial_status: nil,
available: nil,
description: nil
)
puts "."
Exercise.create(
name: "Rowing 2 althères",
exercise_type: "Dos",
equipment: "Haltères",
initial_status: nil,
available: nil,
description:
"Jambes légèrement fléchies, buste en avant, et bras tendus vers le sol, remonter les altères en tirant sur les coudes (les coudes restent le long du corps)"
)
puts "."
Exercise.create(
name: "Sit-ups avec haltère",
exercise_type: "Abdos",
equipment: "Haltères",
initial_status: nil,
available: nil,
description: "Position allongée jambes fléchies et haltère sur le ventre, remonter le buste avec l'haltère au dessus de soi"
)
puts "."
Exercise.create(
name: "Squats sautés",
exercise_type: "Cardio",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Fléchir les jambes jusqu'à 90° et remonter en sautant"
)
puts "."
Exercise.create(
name: "Statique avec élévation d'haltère",
exercise_type: "Abdos",
equipment: "Haltères",
initial_status: nil,
available: nil,
description:
"Position assise avec pieds au sol, descendre le buste le plus bas possible. Remonter l'haltère à la verticale puis la ramener à la poitrine en tenant la position"
)
puts "."
Exercise.create(
name: "Superman",
exercise_type: "Pecs/abdos",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Allongé sur le ventre, bras tendus à la verticale, lever le buste et les jambes puis revenir en position de départ"
)
puts "."
Exercise.create(
name: "T au TRX",
exercise_type: "Dos",
equipment: "TRX",
initial_status: nil,
available: nil,
description: "Position de départ bras tendus face à vous. Ecarter les bras jusqu'à former un T puis revenir en position de départ"
)
puts "."
Exercise.create(
name: "Tirage menton 1 haltère",
exercise_type: "Epaules",
equipment: "Haltères",
initial_status: nil,
available: nil,
description: "Bras tendus le long du corps avec une haltère, remonter l'haltère au menton en gardant les coudes le plus haut possible"
)
puts "."
Exercise.create(
name: "Touchés pieds à la verticale",
exercise_type: "Abdos",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Allongé sur le sol, jambes tendues à 90°, toucher les pieds/chevilles avec les mains"
)
puts "."
Exercise.create(
name: "Tractions en pronation",
exercise_type: "Dos",
equipment: "Barre de tractions",
initial_status: nil,
available: nil,
description: "Tractions mains écartées, paumes de mains vers l'avant (pouces à l'intérieur)"
)
puts "."
Exercise.create(
name: "Tractions en supination",
exercise_type: "Dos",
equipment: "Barre de tractions",
initial_status: nil,
available: nil,
description: "Tractions mains largeur d'épaules, paumes face à vous (pouces vers l'extérieur)"
)
puts "."
Exercise.create(
name: "Trio de pompes",
exercise_type: "Pecs",
equipment: "Aucun",
initial_status: nil,
available: nil,
description:
"1 tiers de pompes mains serrées, puis 1 tiers de pompes mains largeur d'épaules, puis 1 tiers de pompes mains écartées. Essayer de faire le même nombre de répétitions à chaque exercice."
)
puts "."
Exercise.create(
name: "Velo",
exercise_type: "Abdos",
equipment: "Aucun",
initial_status: nil,
available: nil,
description: "Allongé, une jambe pliée l'autre tendue, toucher le genou plié avec le coude opposé puis alterner."
)
puts "."
Exercise.create(
name: "Y au TRX",
exercise_type: "Epaules",
equipment: "TRX",
initial_status: nil,
available: nil,
description:
"Position de départ bras tendus face à vous, remonter les bras à la verticale en les écartant à 45° (position Y). Gérer la difficulté en avançant/reculant les pieds."
)
| true |
d697bf1fb650ea89b5f47a6ab4fbfb235d4f6940
|
Ruby
|
hamza3202/repositext
|
/lib/repositext/services/extract_content_at_main_titles.rb
|
UTF-8
| 1,544 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
class Repositext
class Services
# This service extracts a file's main titles: The first level 1 header by
# default, and the first level 2 header if requested.
#
# Usage:
# main_title = ExtractContentAtMainTitles.call(content_at, :content_at).result
#
class ExtractContentAtMainTitles
# @param content_at [String]
# @param format [Symbol] one of :content_at or :plain_text
def self.call(content_at, format=:content_at, include_level_2_title=false)
new(content_at, format, include_level_2_title).call
end
# @param content_at [String]
def initialize(content_at, format, include_level_2_title)
@content_at = content_at
@format = format
@include_level_2_title = include_level_2_title
end
# @return [String, Array<String>] Either just level 1 header, or array
# of level 1 and level 2 headers.
def call
level_1_title = @content_at[/^# [^\n]+/] || ''
level_2_title = @content_at[/^## [^\n]+/] || ''
r = case @format
when :content_at
[level_1_title, level_2_title].map { |e| e.sub(/^#+ /, '') }
when :plain_text
[level_1_title, level_2_title].map { |e|
Kramdown::Document.new(e).to_plain_text.strip
}
else
raise "Handle this: #{ @format.inspect }"
end
if @include_level_2_title
Outcome.new(true, r, [])
else
Outcome.new(true, r.first, [])
end
end
end
end
end
| true |
8e5736c854b456fad6b944f891ced50bb24e5a7e
|
Ruby
|
alekvuka/ttt-with-ai-project-v-000
|
/lib/players/computer.rb
|
UTF-8
| 553 | 3.34375 | 3 |
[] |
no_license
|
module Players
class Computer < Player
def move(board)
@board = board
decision = move_to_make
puts "The computer has chosen to occupy cell #{decision}"
puts "Please examine the updated board below:"
decision
end
def move_to_make
if @board.turn_count == 0
decision = 5
else
decision = Random.new.rand(10)
while @board.valid_move?(decision) == false
decision = Random.new.rand(10)
end
decision
end
decision.to_s
end
end
end
| true |
32a42db01781c232e08f377bd51d99f7b69711fe
|
Ruby
|
freddywaiganjo/rubySample
|
/condFile.rb
|
UTF-8
| 230 | 3.015625 | 3 |
[] |
no_license
|
class ConditionTest
def check_even(a)
if a < 0
puts('no less than 0')
elsif a == 0
puts('no is zero')
elsif a > 0 || a.even?
puts('even no')
else
puts('Odd number')
end
end
end
| true |
6fa7f35c52743cf840d555465a082d57a72d0600
|
Ruby
|
bguthrie/speed_racer
|
/pkg/speed_racer-0.1.0/lib/speed_racer/comparison.rb
|
UTF-8
| 1,388 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
module SpeedRacer
class Comparison
attr_reader :baseline, :measurements, :times
def initialize(n)
@times = n
@measurements = []
end
def measure(name, &block)
@measurements << Measurement.new(name, times, *data, &block)
end
def against(name, &block)
@baseline = Measurement.new(name, times, *data, &block)
end
def data(*args)
if args.empty?
@data ||= []
@data
else
@data = args
end
end
def to_s
a = []
a << baseline.to_s
a << ( '-' * a.first.length )
a << measurements.sort_by {|m| m.differential(baseline) * -1}.map do |m|
m.to_s(baseline)
end
a.join("\n")
end
alias :report :to_s
def run
ensure_equivalent_results!
report
end
protected
def ensure_equivalent_results
measurements.each do |measurement|
unless measurement.result == baseline.result
raise EquivalenceFailure, "#{measurement.name} failed to match baseline #{baseline.name}; expected #{baseline.result.inspect}, but was #{measurement.result.inspect}"
end
end
end
def include(*modules)
singleton_class.send(:include, *modules)
end
def singleton_class
class << self; self; end
end
end
class EquivalenceFailure < RuntimeError
end
end
| true |
0df5bbf33706c40f6abe2fc1bca5237167ef647e
|
Ruby
|
ianberman/App-Academy-Open
|
/Intro to Programming/Hashes/hashes_lecture_notes_1.rb
|
UTF-8
| 909 | 4.28125 | 4 |
[] |
no_license
|
# arrays group data within a single variable with indices
# hashes have values indicated by keys
# hashes in Ruby use curly braces {} - organized by key and value pairs
my_hash = {
"name" => "App Academy",
"color" => "red",
"age" => 5,
42 => "hello"
}
my_hash["color"] = "pink" # manipulation of hashes is like variables
puts my_hash[42]
puts my_hash.length # gives num of pairs
my_hash["location"] = "NY" # add a key/value pair to end
puts my_hash
# hash methods:
# .length
# .has_key?(k)
# .has_value?(v)
# .keys - evaluates to array of all keys
puts my_hash.keys[1]
# .values
# iterating thru hashes :
pizza = {
"style" => "New York",
"slices" => 8,
"diameter" => "15 inches",
"toppings" => ["mushrooms", "green peppers"],
"is_tasty" => true
}
# pizza.each do |key, value|
# puts key
# puts value
# puts "---"
# end
pizza.each_key do |k| # also works for each_value
puts k
end
| true |
5ef19475eebeb3c7deafd7ec57ac07ca2765ccff
|
Ruby
|
rspeicher/invision_bridge
|
/lib/authlogic/crypto_providers/invision_power_board.rb
|
UTF-8
| 1,627 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
require 'digest/md5'
module Authlogic
module CryptoProviders
class InvisionPowerBoard
class << self
def encrypt(*tokens)
tokens = tokens.flatten
digest = tokens.shift
digest = filter_input(digest)
# Invision's hash: MD5(MD5(salt) + MD5(raw))
digest = Digest::MD5.hexdigest(Digest::MD5.hexdigest(tokens.join('')) + Digest::MD5.hexdigest(digest))
digest
end
# Does the crypted password match the tokens? Uses the same tokens that were used to encrypt.
def matches?(crypted, *tokens)
encrypt(*tokens) == crypted
end
private
def filter_input(input)
# Invision's input filtering replaces a bunch of characters before
# the password gets hashed, some of which may be used in a strong
# password. We have to apply the same changes so that the md5'd
# string ends up the same on our end
input.gsub!('&[^amp;]?', '&')
input.gsub!('<!--', '<!--')
input.gsub!('-->', '-->')
input.gsub!(/<script/i, '<script')
input.gsub!('>', '>')
input.gsub!('<', '<')
input.gsub!('"', '"')
input.gsub!("\\\$", '$')
input.gsub!('!', '!')
input.gsub!("'", ''')
# NOTE: Invision does these, but I doubt they'll show up in a real user's password
# input.gsub!("\n", '<br />')
# input.gsub!("\r", '')
input
end
end
end
end
end
| true |
61ae5e254578af6f41d58ad051025d2b682a74f7
|
Ruby
|
khiav223577/ChineseCheckersBot
|
/lib/ruby/alpha_beta_ai.rb
|
UTF-8
| 2,344 | 2.765625 | 3 |
[] |
no_license
|
require File.expand_path('../ai_base', __FILE__)
class AI::AlphaBeta < AI::Base
MAX_DEEP = 3
def initialize(color_idx, players, board_states, goals, output)
pidx = players.index(color_idx)
[goals, players].each{|s| s.push(*s.shift(pidx)) } #rearrange the order of players
@player_size = players.size
@players_xys = players.map{|player_color_idx|
board_states.each_index.select{|bidx| board_states[bidx] == player_color_idx}.map{|bidx| Board::ALL_BOARD_XY[bidx]}.shuffle
}
@goals_xys = goals.map{|goal| goal.map{|bidx| Board::ALL_BOARD_XY[bidx]} }
@board_states = board_states
@cache_rule_execs = []
@output = output
end
def search
@players_heuristic_cost = Array.new(@player_size){|i| heuristic_function(@players_xys[i], @goals_xys[i]) }
alpha_beta(1, -INFINITY, INFINITY)
@current_output.each_with_index{|s, idx| @output[idx] = s }
end
def evaluation_function
return -(@players_heuristic_cost[0] - @players_heuristic_cost[1..-1].min)
end
def get_player_idx_by_depth(depth)
return (depth - 1) % @player_size
end
def get_rule_obj_by(depth)
return (@cache_rule_execs[depth - 1] ||= RuleExec.new(self, @players_xys[get_player_idx_by_depth(depth)]))
end
private
def alpha_beta(depth, alpha, beta)
return evaluation_function if depth > MAX_DEEP
player_idx = get_player_idx_by_depth(depth)
rule_obj = get_rule_obj_by(depth)
original_cost = @players_heuristic_cost[player_idx]
max_node = (player_idx == 0) #find max
current_value = (max_node ? -INFINITY : INFINITY)
rule_obj.for_each_legal_move{|xys|
new_cost = heuristic_function(xys, @goals_xys[player_idx])
next if new_cost > original_cost
@players_heuristic_cost[player_idx] = new_cost
value = alpha_beta(depth + 1, alpha, beta)
if max_node
next if value <= current_value
if (current_value = value) > alpha
alpha = current_value
@current_output = rule_obj.get_output if depth == 1
next :cut if alpha > beta
end
else
next if value >= current_value
if (current_value = value) < beta
beta = current_value
next :cut if alpha > beta
end
end
}
@players_heuristic_cost[player_idx] = original_cost
return evaluation_function
end
end
| true |
5e880629784529ba608280564898a189e874eaa6
|
Ruby
|
harshitamukesh/ruby_set2
|
/Polymorphism/polymorphism2.rb
|
UTF-8
| 1,133 | 4.375 | 4 |
[] |
no_license
|
# Create a class called Person.
# Define three other classes i.e student, teacher and parent which should have all the properties of Person.
# Define a method which introduces the person with his firstname, lastname, age, city and state.
class Person
def firstname(fname)
@fname = fname
end
def lastname(lname)
@lname = lname
end
def age(num)
@num = num
end
def city(ct)
@ct = ct
end
def state(st)
@st=st
end
end
class Student < Person
end
class Teacher < Person
end
class Parent < Person
end
puts "===========Student Details============"
objs=Student.new
puts objs.firstname("Harshita")
puts objs.lastname("Santoshi")
puts objs.age("23")
puts objs.city("Mysore")
puts objs.state("Karnataka")
puts "===========Teacher Details============"
objt=Teacher.new
puts objt.firstname("Sam")
puts objt.lastname("Mary")
puts objt.age("30")
puts objt.city("Mysore")
puts objt.state("Karnataka")
puts "===========Parent Details============"
objp=Parent.new
puts objp.firstname("Mukesh")
puts objp.lastname("Santoshi")
puts objp.age("57")
puts objp.city("Mysore")
puts objp.state("Karnataka")
| true |
63b4b750d3c7d66612286e383c4777e328f1c878
|
Ruby
|
jensjap/curator2
|
/archive/add_internal_id.rb
|
UTF-8
| 1,399 | 2.59375 | 3 |
[] |
no_license
|
#encoding: utf-8
require "./lib/environment.rb"
require "csv"
FILE_PATH = "./output/assignments.csv"
PROJECT_ID = 163
def main
data = CSV.table(FILE_PATH, { :encoding => "ISO8859-1", :col_sep => "\t" })
data.each do |row|
pmid = row[:pubmed_id]
refid = row[:internal_id]
primary_publications = _find_lof_primary_publications_with_pmid(project_id=PROJECT_ID, pmid=pmid)
if primary_publications.length == 1
pp_id = primary_publications[0][:id]
ppn = _find_primary_publication_number_record_by_primary_publication_id(pp_id)
ppn.number = refid
ppn.number_type = "internal"
if ppn.save
puts "#{ppn} created successfully"
else
puts "Failed to created #{ppn}"
end
else
puts "Too many results found for pmid: #{pmid}"
end
end
end
def _find_primary_publication_number_record_by_primary_publication_id(pp_id)
ppn = PrimaryPublicationNumber.find_by_primary_publication_id(pp_id)
if ppn.blank?
ppn = PrimaryPublicationNumber.new(:primary_publication_id => pp_id)
puts "Primary Publication Number record not found."
puts "Created a new one for pp_id (#{pp_id}): #{ppn.inspect}"
end
return ppn
end
def _find_lof_primary_publications_with_pmid(project_id, pmid)
PrimaryPublication.find(:all, :conditions => { :pmid => pmid })
end
if __FILE__ == $0
load_rails_environment
main()
end
| true |
51102ccae28c5fd57fb23f8c5ae5cd79662ba15b
|
Ruby
|
nataliemac81/phase_0_unit_3
|
/week_8_and_9/4_Ruby/fibonacci_sequence/my_solution.rb
|
UTF-8
| 1,266 | 4.15625 | 4 |
[] |
no_license
|
# U3.W8-9:
# I worked on this challenge by myself.
# 2. Pseudocode
=begin
***A positive number is a fibonacci number if (5 * n**2 + 4) or (5 * n**2 - 4) is a perfect square.
create a method called perfect_sq that takes a number and tests whether it is a perfect square or not.
call the Math.sqrt method on number and convert to an integer. Set equal to the result.
end method.
create a method called is_fib? that takes a number and tests if the number is a fibonacci number or not.
call the perfect_sq method on fibonacci formulas.
end method.
=end
# 3. Initial Solution
def perfect_sq(num)
Math.sqrt(num).to_i==Math.sqrt(num)
def is_fib?(num)
perfect_sq(5 * n**2 + 4) || (5 * n**2 - 4)
end
# 4. Refactored Solution
#This solution seems pretty concise to me.
# 1. DRIVER TESTS GO BELOW THIS LINE
def assert
raise "Assertion failed!" unless
yield
end
assert { is_fib?(0) == true}
assert { is_fib?(1) == true}
assert { is_fib?(4) == false}
assert { is_fib?(34) == true}
assert { is_fib?(39) == false}
# 5. Reflection
=begin
This challenge wasn't too bad. Once I figured out the formula for finding a fibonacci number the rest was pretty easy.
I just followed the steps and pseudocoded and coded up the initial solution.
=end
| true |
8ed117c7101f5230715de6ed3a66537722920499
|
Ruby
|
aortbals/specs_watcher
|
/lib/specs_watcher/parsers/searcher.rb
|
UTF-8
| 985 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
require 'nokogiri'
module SpecsWatcher
module Parsers
class Searcher
def self.parse(raw_html)
new(raw_html).parse
end
attr_reader :raw_html
def initialize(raw_html)
@raw_html = raw_html
end
def parse
doc = Nokogiri::HTML(raw_html)
rows = doc.css('tr[valign="TOP"]')
rows.map { |r| parse_row(r) }
end
def parse_row(r)
td = r.css("td")
{
title: td[1].children[0].text.strip,
price: td[4].children[0].text.strip.to_f,
size: td[2].text.strip,
case_price: td[4].children[2].text.strip.to_f,
case_size: td[3].children[2].text.strip,
description: td[1].children[3].text.strip,
image: image_base_uri + r.css("img").first["src"],
upc: td.css('a').last['onclick'][/showavail\('(.*)'\)/, 1]
}
end
def image_base_uri
"http://www.specsonline.com"
end
end
end
end
| true |
39870d1cb02c78228faf4ffde176140166f98ae3
|
Ruby
|
soutaro/steep
|
/smoke/enumerator/b.rb
|
UTF-8
| 264 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
# @type var b: Array[String]
# @type var c: Array[Integer]
a = [1]
b = a.each.with_object([]) do |i, xs|
xs << i.to_s
end
c = a.each.with_object([]) do |i, xs|
xs << i.to_s
end
# @type var d: String
d = a.each.with_object([]) do |i, xs|
xs << i.to_s
end
| true |
a1c93931b85f8164566bb18e2b62c4784e270522
|
Ruby
|
prokizzle/sit_stand
|
/sit_stand.rb
|
UTF-8
| 607 | 2.953125 | 3 |
[] |
no_license
|
require 'timers'
require 'daemons'
Fixnum.class_eval do
def seconds
self
end
def minutes
self * 60
end
def hours
self * 60 * 60
end
end
class SitStand
def initialize
@timers = Timers::Group.new
@every_five_seconds = @timers.every(20.minutes) { notify }
@position = "sit"
notify
end
def sit_or_stand
@position = @position == "sit" ? "stand" : "sit"
end
def notify
%x{terminal-notifier -message "Time to #{sit_or_stand}!"}
end
def run
loop { @timers.wait }
end
end
Daemons.run_proc('SitStand') do
app = SitStand.new
app.run
end
| true |
df75633652402bda2c97cfbe6dcdeaeb0f4fd7be
|
Ruby
|
nathanworden/RB101-Programming-Foundations
|
/RB101-RB109_small_problems/06.easy_6/03.fibonacci_number_location_by_length.rb
|
UTF-8
| 2,807 | 4.75 | 5 |
[] |
no_license
|
#PEDAC
# Problem
# Write a method that calculates and returns the index of the first Fibonacci numbers that
# has the number of digits specified as an argument. (The first Fibonacci number has index 1)
# Example / Test Cases
# find_fibonacci_index_by_length(2) == 7 # 1 1 2 3 5 8 13
# find_fibonacci_index_by_length(3) == 12 # 1 1 2 3 5 8 13 21 34 55 89 144
# find_fibonacci_index_by_length(4) == 17 # 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
# find_fibonacci_index_by_length(10) == 45
# find_fibonacci_index_by_length(100) == 476
# find_fibonacci_index_by_length(1000) == 4782
# find_fibonacci_index_by_length(10000) == 47847
# Data Structure
# integer, array
# Algorithm
# define a method called 'find_fibonacci_index_by_length' that takes an integer as an argument
# assign the first fibonacci number to a variable called 'fibonacci'
# assign the second fibonacci number (1) to a variable called 'next_fib'
# subtract one from the initial 'integer' argument and then save 10 to the power of this in a variable called 'comparison'
# initiate an array called 'fib_set' with two elements: 'fibonacci' and 'next_fib'
# while fibonacci is less than 'comparison':
# - fibonacci, next = (fibonacci + next), fibonacci
# - fib_set << fibonacci
# fib_set.index(fibonacci)
# Code
# def find_fibonacci_index_by_length(integer)
# fibonacci = 1
# next_fib = 1
# comparison = 10 ** (integer - 1)
# fib_set = [1, 1]
# while fibonacci < comparison
# fibonacci, next_fib = (fibonacci + next_fib), fibonacci
# fib_set << fibonacci
# end
# fib_set.index(fibonacci) + 1
# end
# p find_fibonacci_index_by_length(2) == 7 # 1 1 2 3 5 8 13
# p find_fibonacci_index_by_length(3) == 12 # 1 1 2 3 5 8 13 21 34 55 89 144
# p find_fibonacci_index_by_length(4) == 17 # 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
# p find_fibonacci_index_by_length(10) == 45
# p find_fibonacci_index_by_length(100) == 476
# p find_fibonacci_index_by_length(1000) == 4782
# p find_fibonacci_index_by_length(10000) == 47847
def find_fibonacci_index_by_length(number_digits)
fibonacci = 1
next_fib = 1
fib_set = [1, 1]
while fibonacci.to_s.size < number_digits
fibonacci, next_fib = (fibonacci + next_fib), fibonacci
fib_set << fibonacci
end
fib_set.index(fibonacci) + 1
end
p find_fibonacci_index_by_length(2) == 7 # 1 1 2 3 5 8 13
p find_fibonacci_index_by_length(3) == 12 # 1 1 2 3 5 8 13 21 34 55 89 144
p find_fibonacci_index_by_length(4) == 17 # 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
p find_fibonacci_index_by_length(10) == 45
p find_fibonacci_index_by_length(100) == 476
p find_fibonacci_index_by_length(1000) == 4782
p find_fibonacci_index_by_length(10000) == 47847
| true |
92324a7a5208838edf6a5c3be560fcf47bb9b3cd
|
Ruby
|
hiro0911/NaganoCakeSlim
|
/app/helpers/application_helper.rb
|
UTF-8
| 160 | 2.53125 | 3 |
[] |
no_license
|
module ApplicationHelper
def total_price(cart_items)
price = 0
cart_items.each do |cart_item|
price += cart_item.subtotal
end
return price
end
end
| true |
b1ee10f0c6ce07644db539259140105594523c05
|
Ruby
|
markryall/songbirdsh
|
/lib/songbirdsh/command/search.rb
|
UTF-8
| 736 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
require 'songbirdsh/command'
class Songbirdsh::Command::Search
include Songbirdsh::Command
usage '*<word>'
help <<EOF
searches for tracks containing the specified words (in artist, title or album)
ids are placed on the clipboard for convenient use with +
EOF
execute do |text|
terms = text.split(/\W/)
matches = []
@player.library.reload unless @player.library.tracks
matches = []
@player.library.tracks.each do |track|
if terms.all? {|term| track.search_string.include? term }
puts track
matches << track.search_id
end
end
puts "Found #{matches.size} matches (ids have been placed on clipboard)"
matches.join(' ').to_clipboard
@player.matches = matches
end
end
| true |
d64c4fbaa7bbd556e84af43c67d223598d501bdf
|
Ruby
|
TaylorBeeston/ExercismAnswers
|
/ruby/pangram/pangram.rb
|
UTF-8
| 182 | 3.375 | 3 |
[] |
no_license
|
class Pangram
def self.pangram?(sentence)
pangram = true
for letter in 'a'..'z'
pangram = false if sentence.downcase.count(letter) == 0
end
pangram
end
end
| true |
03a44df63799de548dbbab7e5c049ad517b7b428
|
Ruby
|
bartoszdyja/learn_ruby
|
/08_book_titles/book.rb
|
UTF-8
| 226 | 3.390625 | 3 |
[] |
no_license
|
class Book
attr_reader :title
def title=(title)
@title=title.split.map do |word|
%w(a an the in and of).include?(word) ? word : word.capitalize
end.join(' ')
@title[0] = @title[0].capitalize
end
end
| true |
a7b1cb6ff06f13181eae593531013b26fd4c4d15
|
Ruby
|
TongCui/t_tools
|
/doc/ruby/rails/edgeguides/models/active-record-callback.rb
|
UTF-8
| 1,262 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
## Callback
class User < ApplicationRecord
validates :login, :email, presence: true
before_validation :ensure_login_has_a_value
protected
def ensure_login_has_a_value
if login.nil?
self.login = email unless email.blank?
end
end
end
or
class User < ApplicationRecord
validates :login, :email, presence: true
before_create do
self.name = login.capitalize if name.blank?
end
end
class User < ApplicationRecord
before_validation :normalize_name, on: :create
# :on takes an array as well
after_validation :set_location, on: [ :create, :update ]
protected
def normalize_name
self.name = name.downcase.titleize
end
def set_location
self.location = LocationService.query(self)
end
end
## Available Callbacks
3.1 Creating an Object
- before_validation
- after_validation
- before_save
- around_save
- before_create
- around_create
- after_create
- after_save
- after_commit/after_rollback
3.2 Updating an Object
- before_validation
- after_validation
- before_save
- around_save
- before_update
- around_update
- after_update
- after_save
- after_commit/after_rollback
3.3 Destroying an Object
- before_destroy
- around_destroy
- after_destroy
| true |
fcf8334647294cb77f96ec43e5106fc2b44c3042
|
Ruby
|
azhang9328/ruby-enumerables-generalized-map-and-reduce-lab-seattle-web-120919
|
/lib/my_code.rb
|
UTF-8
| 431 | 3.578125 | 4 |
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# Your Code Here
def map(array)
newarray = []
i = 0
while i < array.length do
newarray.push(yield(array[i]))
i += 1
end
newarray
end
def reduce(array, starting_point = nil)
i = 0
if starting_point
total = starting_point
else
total = array[0]
i = 1
end
while i < array.length do
total = yield(total, array[i])
puts array[i]
puts total
i += 1
end
total
end
| true |
000c66f21b84ca3cb9fead601e2e7b1682813e2c
|
Ruby
|
zstrick/battleship
|
/player.rb
|
UTF-8
| 383 | 3.046875 | 3 |
[] |
no_license
|
class Player
attr_reader :grid
def initialize
@grid = Grid.new
end
def ships
grid.ships
end
def record_hit(coordinates)
grid.hit_opponent(coordinates)
end
def record_miss(coordinates)
grid.miss_opponent(coordinates)
end
def fire_at_coordinates(coordinates)
grid.fire_at_coordinates(coordinates)
end
def sunk?
grid.sunk?
end
end
| true |
b539c2ade9366e06f9dbed4903a53e3d055888e3
|
Ruby
|
coconatsuki/ruby_spec_testing
|
/06_timer/timer.rb
|
UTF-8
| 1,233 | 3.875 | 4 |
[] |
no_license
|
class Timer
attr_accessor :seconds
def initialize seconds=0
@seconds = seconds
@hours_string = "00"
@minutes_string = "00"
@seconds_string = "00"
end
def time_string
if @seconds >= 3600
hours
elsif @seconds >= 60 && @seconds < 3600
minutes
elsif @seconds > 0
sec
else
p "#{@hours_string}:#{@minutes_string}:#{@seconds_string}"
end
end
def hours
hours_number = @seconds / 3600
if hours_number < 10
@hours_string = "0#{hours_number}"
else
@hours_string = "#{hours_string}"
end
# calcul of the remaining time
@seconds = @seconds - hours_number * 3600
if @seconds >= 60
minutes
else
sec
end
end
def minutes
minutes_number = @seconds / 60
if minutes_number < 10
@minutes_string = "0#{minutes_number}"
else
@minutes_string = "#{minutes_string}"
end
# calcul of the remaining time
@seconds = @seconds - minutes_number * 60
if @seconds > 0
sec
else
time_string
end
end
def sec
if @seconds < 10
@seconds_string = "0#{@seconds}"
else
@seconds_string = "#{@seconds}"
end
@seconds = 0
time_string
end
end
| true |
3a1981843273c2af4e64e9c332529f95e12303d1
|
Ruby
|
tperdue321/sample_app
|
/ruby_solutions.rb
|
UTF-8
| 1,778 | 4.25 | 4 |
[] |
no_license
|
# original string
string = "This is a string in reverse"
# change to array to manipulate
array = string.split("")
index = 0
# new array to save reverse version
reverse_array = []
#until loop iterating through array starting with first item in array working up and saving it to reverse_array
until index == array.length
reverse_array = reverse_array.prepend(array[index])
index += 1
end
# save reversed characters to string
reverse_string = reverse_array.join
#attempting same thing as lines 1-16 in less code -- success
string = "This is a string in reverse"
string_reverse = ""
index = 0
until index == string.length
string_reverse = string_reverse.prepend(string[index])
index += 1
end
# reverses a string and puts it into a new string -- success
string = "This is a string in reverse"
reverse_string = ""
string.each_char { |c| string_reverse = string_reverse.prepend(c) }
str = r
# reverse string prob using recursion -- success
s = "This is a string"
r = ""
num = 0
def r_str(x, y, z)
return y if (x.length == y.length)
y = y.prepend(x[z])
z += 1
r_str(x, y, z)
end
# reverse string prob using recursion r must be a blank string
string = "This is a string in reverse"
r = ""
def r_str(s, r)
r = r.prepend(s.slice!(s.first))
if s == ""
s = r
return s
end
r_str(s, r)
end
# fizzbuzz problem using for loop -- success
for num in 0..1000
if num % 15 == 0
puts "fizzbuzz"
elsif num % 5 == 0
puts "buzz"
elsif num % 3 == 0
puts "fizz"
else
puts num
end
end
# fizzbuzz problem using until loop -- success
x = 0
until x == 1000
x += 1
if x % 15 == 0
puts "fizzbuzz"
elsif x % 5 == 0
puts "buzz"
elsif x % 3 == 0
puts "fizz"
else
puts x
end
end
| true |
25f1e37061eb4fb1a95afd2efff3b995e7223e46
|
Ruby
|
JohnMahowald/potd
|
/mobile-6.rb
|
UTF-8
| 182 | 3.296875 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
x = 16
def shift_six num
num_str = num.to_s
num_str = num_str[-1] + num_str[0..-2]
num_str.to_i
end
until shift_six(x) == (x * 4)
x += 10
end
puts x
| true |
c03b7d40172ecefc3ee564de157a1b59fc5f6f15
|
Ruby
|
swa-gitlab/documentation
|
/metrics/retrieve_github_issues.rb
|
UTF-8
| 1,992 | 3.078125 | 3 |
[] |
no_license
|
# encoding: UTF-8
require 'rubygems'
require 'httparty'
require 'pp'
require 'json'
##
# GitHub issue downloader
#
# Downloads the issues posted for a given project and writes the responses to a JSON file.
# Example dataset produced by this script can be obtained from https://dl.dropboxusercontent.com/u/710158/issues.json.zip
#
# Requirements:
# * Ruby
# * rubygems
# * httparty
#
# Usage:
# * Enter your GitHub oauth token
# * Customize the API URLs to retrieve on lines 66-67
# * ruby retrieve_github_issues
##
USER_TOKEN="yourtoken"
def get_response(url, retries = 0)
response = HTTParty.get(url, :headers => {'Authorization' => "token #{USER_TOKEN}", 'User-Agent' => '@yholkamp'})
if response.headers['status'] != "200 OK"
puts "Received response: #{response.headers['status']}"
get_response(url, retries - 1) if retries > 0
else
response
end
end
def collect_api_results(url)
all_data = []
while url do
puts url
response = get_response(url, 2)
puts response.headers['X-RateLimit-Remaining']
data = JSON.parse response.body
if data.is_a? Array
all_data += data
else
pp data
end
# Figure out what the next request should be
linkbits = response.headers['Link'].scan /<(https:\/\/.+?)>; rel="next"/
if linkbits == nil || linkbits == [] || linkbits.flatten! == []
pp response.headers['Link'].scan /<(https:\/\/.+?)>; rel="next"/
# we're done
puts "Link header is empty, we're done!"
url = nil
else
url = linkbits[0]
end
end
all_data
end
closed_url = "https://api.github.com/repos/gitlabhq/gitlabhq/issues?direction=asc&sort=created&state=closed"
open_url = "https://api.github.com/repos/gitlabhq/gitlabhq/issues?direction=asc&sort=created&state=open"
all_data = collect_api_results(closed_url)
puts "Found #{all_data.count} closed issues"
all_data += collect_api_results(open_url)
puts "Found #{all_data.count} total issues"
File.open('issues.json', 'w') do |file|
file.write JSON.generate all_data
end
| true |
5e723875d730ee430b3303dd9c020786dd17acea
|
Ruby
|
kat-siu/ruby-notes
|
/string_util.rb
|
UTF-8
| 351 | 3.515625 | 4 |
[] |
no_license
|
def repeat(str, count)
result = ''
# Approach 1
#0.upto(count) do
# result = result + str
#end
# Approach 2
#count.downto 0 do
# result = result + str
#end
# Approach 3
#count.times { result += str }
#result
# Approach 4 (awesomeness!)
str * count
end
puts(repeat 'test', 5)
| true |
cf32ed53d9c169023e9d91298a1ebab52216209d
|
Ruby
|
ese-unibe-ch/ese2012-team1
|
/trade/app/models/Messenger/message.rb
|
UTF-8
| 2,674 | 3.453125 | 3 |
[] |
no_license
|
module Models
##
#
# A Message stores a single message
#
##
class Message
@@message_count = 1
#unique id of the message
attr_reader :message_id
#message itself
attr_accessor :message
#sender of the message
attr_accessor :sender
#date when the message was created
attr_accessor :date
#subject of the message
attr_accessor :subject
#message id of the message this message replies to
attr_accessor :reply_to
#depth of the message indicating how deep this message is in the message tree
attr_accessor :depth
#receivers of this message
attr_accessor :receivers
def initialize
@message_id = @@message_count
@@message_count += 1
self.depth = 0
self.receivers = Array.new
end
##
#
# Creates a new message
#
# ==== Parameters
#
# +from+:: sender (can't be nil)
# +to+:: receiver as Array
# +subject+:: subject of the message (can't be nil)
# +date+:: date of the message as Time (can't be nil)
# +message+:: the message itself (can't be nil and can't be an empty string)
# +reply_to+:: id of the message this message replies to (must be nil or positive integers)
#
##
def self.create(from, to, subject, date, message, reply_to)
fail "sender should be given" if from.nil?
fail "receiver should be given" if to.nil?
fail "date should be set" if date.nil?
fail "message should be set" if message.nil? || message.size == 0
fail "reply_to must either be nil or positive integer" unless reply_to.nil? || reply_to.to_s.is_positive_integer?
mes = Message.new
mes.sender = from
mes.receivers = to
mes.subject = subject.nil? ? "" : subject
mes.date = date
mes.message = message
mes.reply_to = reply_to
mes
end
##
#
# Checks if a given user is the receiver
# of this message.
#
# Returns true if the user is a receiver
# false otherwise.
#
# === Parameters
#
# +user_id+:: id of the user that shall be checked
#
##
def is_receiver?(user_id)
receivers.one? { |receiver| receiver.to_s == user_id.to_s }
end
##
#
# Checks if a given user is the sender
# of this message.
#
# Returns true if the user is the sender
#
# === Parameters
#
# +user_id+:: id of the user to be checked
#
##
def is_sender?(user_id)
user_id.to_s == self.sender.to_s ? out = true : out = false
return out
end
end
end
| true |
7531ec9d9aa769ea4539583e8bdd846edca416ef
|
Ruby
|
kjferris/launch_school_101
|
/lesson_3/exercises_easy_2.rb
|
UTF-8
| 727 | 3.046875 | 3 |
[] |
no_license
|
# Question 1
ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 }
ages.has_key?("Spot")
# Question 2
ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237 }
ages.value.inject(:+)
# Question 3
ages.keep_if { |name, age| age < 100 }
# Question 4
munsters_description.capitalize!
munsters_description.swapcase!
munsters_description.downcase!
munsters_description.upcase!
# Question 5
ages.merge!(additional_ages)
# Question 6
ages.values.min
# Question 7
advice.include?("Dino")
# Question 8
flintstones.index { |name| name[0, 2] == "Be" }
# Question 9
flintstones.map! do |name|
name[0, 3]
end
# Question 10
flintstones.map! { |name| name[0, 3] }
| true |
24d55ece20906fb5d45008feddf9ae24ef6229c7
|
Ruby
|
gvquiroz/aydoo2016-ruby
|
/factores-primos-ruby/spec/formateador_quiett_spec.rb
|
UTF-8
| 726 | 2.671875 | 3 |
[] |
no_license
|
require 'rspec'
require_relative '../model/formateador_quiett'
class FormateadorQuiettSpec
describe 'FormateadorQuiett' do
it 'should return 2\n2\n3\n5 when get contenido formateado' do
array_con_contenido = [2, 2, 3, 5]
expected_string = "2\n2\n3\n5"
formateador = FormateadorQuiett.new
expect(formateador.get_contenido_formateado(array_con_contenido)).to eq(expected_string)
end
it 'should return a\nb\nc\nd when get contenido formateado' do
array_con_contenido = ["a", "b", "c", "d"]
expected_string = "a\nb\nc\nd"
formateador = FormateadorQuiett.new
expect(formateador.get_contenido_formateado(array_con_contenido)).to eq(expected_string)
end
end
end
| true |
ccd780f0f796a37dc007d961db4aaf5c6f59b090
|
Ruby
|
tri-dang/anti-pattern-test
|
/lib/liar.rb
|
UTF-8
| 274 | 3.3125 | 3 |
[] |
no_license
|
class Liar
@@big_liar = true
def initialize(liar)
@liar = liar
end
attr_reader :liar
def self.big_liar
@@big_liar
end
def self.big_liar=(big_liar)
@@big_liar = big_liar
end
def to_s
liar ? 'You are liar' : 'You are not liar'
end
end
| true |
c6b0259a1a18406f4c26cdaee28059ad598d6be5
|
Ruby
|
caneroj1/BlackjackRb
|
/lib/blackjack_rb/deck.rb
|
UTF-8
| 1,739 | 4.03125 | 4 |
[] |
no_license
|
module BlackjackRb
class Deck
# a deck will have 52 cards and it will have certain actions
# that it can do, such as give a card, or shuffle
attr_reader :cards
# this will initialize the deck by calling another method to create the cards
# in order to have a nice, proper deck, and then we shuffle the cards
def initialize
@cards = create_cards
shuffle_cards
end
# draw card method. this will pop a card off the top of the deck and return it
def draw_card
@cards.pop
end
## PRIVATE METHODS
private
# this method will instantiate 4 groups of 13 cards.
# the groups will be created by suit
def create_cards
# create clubs
clubs = Array.new(13) { |rank| BlackjackRb::Card.new(rank + 1, :club) }
# create diamonds
diamonds = Array.new(13) { |rank| BlackjackRb::Card.new(rank + 1, :diamond) }
# create spades
spades = Array.new(13) { |rank| BlackjackRb::Card.new(rank + 1, :spade) }
# create hearts
hearts = Array.new(13) { |rank| BlackjackRb::Card.new(rank + 1, :heart) }
# join them all together
(clubs + diamonds + spades + hearts)
end
# shuffle the cards via the following algorithm: start at the last card and generate a random index
# between the beginning and the index of the current card and swap the current card with the card
# at the generated index. decrement pointer.
def shuffle_cards
51.downto(0) do |current|
random_index = rand(current + 1)
swap(current, random_index)
end
end
# classic 3 line swape. classic.
def swap(a, b)
tmp = @cards[a]
@cards[a] = @cards[b]
@cards[b] = tmp
end
end
end
| true |
f7d843bd86416bc1f42866a23a284739d6e4bfec
|
Ruby
|
francomac/ruby-concepts
|
/inject.rb
|
UTF-8
| 184 | 3.984375 | 4 |
[] |
no_license
|
puts (1..10).inject {|memo, i| memo + i} # 55
array = [*1..10]
sum1 = array.inject {|memo, i| memo + i}
puts sum1 # 55
sum2 = array.inject(100) {|memo, i| memo + i}
puts sum2 # 155
| true |
ea1227513ef564adb9fa5b52592ebeeb3a1c6942
|
Ruby
|
VincentFeildel/Backend-Drivy
|
/backend/level1/main.rb
|
UTF-8
| 6,807 | 3.15625 | 3 |
[] |
no_license
|
require 'json'
require 'date'
# Helpers
def simple_p_calc(car, distance, days)
price_per_km = car['price_per_km']
price_per_day = car ['price_per_day']
rental_price = price_per_km * distance + price_per_day * days
end
def prog_p_calc(car, distance, days)
price_per_km = car['price_per_km']
price_per_day = car ['price_per_day']
case days
when 1
price_days = price_per_day
when 2 .. 4
price_days = price_per_day + (price_per_day * 0.9 * (days - 1))
when 5 .. 10
price_days = price_per_day + (price_per_day * 0.9 * 3) + (price_per_day * 0.7 * (days - 4))
else
price_days = price_per_day + (price_per_day * 0.9 * 3) + (price_per_day * 0.7 * 6) + (price_per_day * 0.5 * (days - 10))
end
rental_price = price_per_km * distance + price_days
end
def dates_to_days(start_date, end_date)
days = (Date.parse(end_date) - Date.parse(start_date) + 1).to_i
end
def actions_array(rental_price, fees_h)
driver_due = rental_price + fees_h[:deductible_reduction]
insurance_due = fees_h[:insurance_fee]
assistance_due = fees_h[:assistance_fee]
drivy_due = fees_h[:drivy_fee] + fees_h[:deductible_reduction]
owner_due = driver_due - insurance_due - assistance_due - drivy_due
return [
{
"who": "driver",
"type": driver_due > 0 ? "debit" : "credit",
"amount": driver_due.abs.to_i
},
{
"who": "owner",
"type": owner_due > 0 ? "credit" : "debit",
"amount": owner_due.abs.to_i
},
{
"who": "insurance",
"type": insurance_due > 0 ? "credit" : "debit",
"amount": insurance_due.abs.to_i
},
{
"who": "assistance",
"type": assistance_due > 0 ? "credit" : "debit",
"amount": assistance_due.abs.to_i
},
{
"who": "drivy",
"type": drivy_due > 0 ? "credit" : "debit",
"amount": drivy_due.abs.to_i
}
]
end
def fees_hash(deductible, rental_price, days)
# Deductible reduction
deductible_reduction = deductible ? 400 * days : 0
# Commission details
insurance_fee = 0.3 * 0.5 * rental_price
assistance_fee = days * 100
drivy_fee = 0.3 * 0.5 * rental_price - assistance_fee
return { deductible_reduction: deductible_reduction, insurance_fee: insurance_fee, assistance_fee: assistance_fee, drivy_fee: drivy_fee }
end
# Main program (levels 1 to 5)
def generate_rental_output(input_path, output_path, price_calc_method = 'simple', price_format = 'short', disp_deductible = false, disp_actions = false)
input_data = JSON.parse(File.read(input_path))
output_rentals = []
input_data['rentals'].each do |rental|
car = input_data['cars'].find { |car| car['id'] == rental['car_id']}
# Setting pricing variables
distance = rental['distance']
days = dates_to_days(rental['start_date'], rental['end_date'])
# Calculating price with relevant method
case price_calc_method
when 'simple'
rental_price = simple_p_calc(car, distance, days)
else
rental_price = prog_p_calc(car, distance, days)
end
# -------Calculating commissions & reductions------------------
fees_h = fees_hash(rental['deductible_reduction'], rental_price, days)
# Populating output data
rental_with_price = { id: rental['id'] }
if disp_actions
rental_with_price[:actions] = actions_array(rental_price, fees_h)
else
rental_with_price[:price] = rental_price.to_i
rental_with_price[:options] = { deductible_reduction: fees_h[:deductible_reduction].to_i } if disp_deductible
rental_with_price[:commission] = {
insurance_fee: fees_h[:insurance_fee].to_i,
assistance_fee: fees_h[:assistance_fee].to_i,
drivy_fee: fees_h[:drivy_fee].to_i
} if price_format == 'full'
end
output_rentals << rental_with_price
end
File.open(output_path, 'wb') do |file|
file.write(JSON.generate( { rentals: output_rentals } ))
end
end
# Level 6 program
def modification_output(input_path, output_path)
# Initialization
input_data = JSON.parse(File.read(input_path))
output_hash = {
rental_modifications: []
}
# Looping rental modifications:
input_data['rental_modifications'].each do |modif|
rental = input_data['rentals'].find { |rental| rental['id'] == modif['rental_id'] }
car = input_data['cars'].find { |car| car['id'] == rental['car_id'] }
# First transaction dates & distance
distance = rental['distance']
days = dates_to_days(rental['start_date'], rental['end_date'])
rental_price = prog_p_calc(car, distance, days)
# First transaction action array
deductible = rental['deductible_reduction']
prev_action_array = actions_array(rental_price, fees_hash(deductible, rental_price, days))
# ----------------------------------------------------
# Second transaction dates & distance
distance = modif['distance'].nil? ? distance : modif['distance']
start_date = modif['start_date'].nil? ? rental['start_date'] : modif['start_date']
end_date = modif['end_date'].nil? ? rental['end_date'] : modif['end_date']
days_new = dates_to_days(start_date, end_date)
# Price variation new transaction (total)
rental_price_diff = prog_p_calc(car, distance, days_new) - rental_price
# Price variation new transaction (detailed)
days_diff = days_new - days
diff_action_array = actions_array(rental_price_diff, fees_hash(deductible, rental_price_diff, days_diff))
# Recording rental modification with price variation
rental_modification = {
"id": modif['id'],
"rental_id": modif['rental_id'],
"actions": diff_action_array
}
output_hash[:rental_modifications] << rental_modification
end
File.open(output_path, 'wb') do |file|
file.write(JSON.generate(output_hash))
end
end
# ________________________________________________________________
# ________________________________________________________________
# Generating output files for each level:
# LEVEL 1
input_path = 'data.json'
output_path = 'output.json'
generate_rental_output(input_path, output_path)
# LEVEL 2
input_path = '../level2/data.json'
output_path = '../level2/output.json'
generate_rental_output(input_path, output_path, 'prog')
# LEVEL 3
input_path = '../level3/data.json'
output_path = '../level3/output.json'
generate_rental_output(input_path, output_path, 'prog', 'full')
# LEVEL 4
input_path = '../level4/data.json'
output_path = '../level4/output.json'
generate_rental_output(input_path, output_path, 'prog', 'full', true)
# LEVEL 5
input_path = '../level5/data.json'
output_path = '../level5/output.json'
generate_rental_output(input_path, output_path, 'prog', 'full', true, true)
# LEVEL 6
input_path = '../level6/data.json'
output_path = '../level6/output.json'
modification_output(input_path, output_path)
| true |
cd92e587ffa90c3ba1cafe46feb332fa5aa43c6f
|
Ruby
|
VictorHolanda21/cursoRuby
|
/exercicios/exercicio01/quest13.rb
|
UTF-8
| 762 | 4.46875 | 4 |
[] |
no_license
|
=begin
13 Tendo como dados de entrada a altura e o sexo de uma pessoa, construa um algoritmo
que calcule seu peso ideal, utilizando as seguintes fórmulas: a. Para homens: (72.7*h) -
58 b. Para mulheres: (62.1*h) - 44.7 (h = altura) c. Peça o peso da pessoa e informe se
ela está dentro, acima ou abaixo do peso. 4
=end
print "Digite seu sexo (M ou F): "
sexo = gets.chomp.capitalize
print "Digite sua altura: "
h = gets.chomp.to_f
print "Digite seu peso: "
p = gets.chomp.to_f
if (sexo == "M")
peso = (72.7 * h) - 58
elsif (sexo == "F")
peso = (62.1 * h) - 44.7
end
puts "Peso ideal é: #{peso}"
if (p < peso)
puts "Seu peso esta abaixo do ideal."
elsif (p > peso)
puts "Seu peso esta acima do ideal."
else
puts "Você está com o peso ideal."
end
| true |
096a3fc39bdff5587bb6fc601408a7de7f950afc
|
Ruby
|
nburkley/follower-maze
|
/spec/follower-maze/user_spec.rb
|
UTF-8
| 1,134 | 2.734375 | 3 |
[] |
no_license
|
require_relative '../spec_helper'
module FollowerMaze
describe User do
before do
@user = User.new(1, nil)
end
it "adds followers" do
@user.followers.size.should be(0)
fanboy = User.new(1, nil)
@user.add_follower(fanboy)
@user.followers.size.should be(1)
@user.followers.shift.should be(fanboy)
end
it "removes followers" do
fanboy = User.new(1, nil)
@user.add_follower(fanboy)
@user.remove_follower(fanboy)
@user.followers.empty?.should be_true
end
context "with a collection of user" do
before do
user_two = User.new(2, nil)
user_three = User.new(3, nil)
@users = { @user.id=>@user, user_two.id=>user_two, user_three=>user_three }
end
it "creates a new user if they don't exist" do
new_user = User.create_or_update(4, nil, @users)
@users.has_value?(new_user).should be_false
end
it "updates a user if they already exist" do
updated_user = User.create_or_update(2, nil, @users)
@users.has_value?(updated_user).should be_true
end
end
end
end
| true |
a8f9c057fe30afcf40a4e4bbcff3e5bd2481a27c
|
Ruby
|
ForeverZer0/open-image
|
/lib/open_image/colors.rb
|
UTF-8
| 34,529 | 3 | 3 |
[
"MIT"
] |
permissive
|
module OpenImage
##
# Module containing convenience methods for defining, retrieving, and
# enumerating preset named {Color} objects.
module Colors
# @!group Helper Methods
##
# Dynamically defines a static method to return a named color.
#
# @param name [String, Symbol] The name of the color.
# @param uint [Integer] An unsigned integer defining the color in AARRGGBB
# format.
#
# @return [void]
def self.define_color(name, uint)
define_singleton_method(name) { Color.new(uint) }
@names ||= []
@names << name.to_s.split('_').map(&:capitalize).join(' ')
end
##
# Returns an array containing the formatted names of each color defined in
# the {Colors} module.
#
# Formatted where each `_` will be replaced with a space, and each word
# segment is capitalized.
#
# `:alice_blue` becomes `"Alice Blue"`
#
# `:light_goldenrod_yellow` becomes `"Light Goldenrod Yellow"`
#
# @return [Array<String>] the names array.
def self.names
@names
end
##
# Enumerates the pre-defined colors.
#
# @overload each
# When called with a block, yields each color to the block.
#
# @yield [color] Yields a color to the block.
# @yieldparam color [Color] The currently enumerated color object.
#
# @return [void]
#
# @overload each
# When called without a block, returns an enumerator for the colors.
#
# @return [Enumerator]
def self.each
return enum_for __method__ unless block_given?
@names.each do |name|
sym = name.downcase.tr(' ', '_').to_sym
yield method(sym).call rescue next
end
end
# @!endgroup
define_color :alice_blue, 0xFFF0F8FF
define_color :antique_white, 0xFFFAEBD7
define_color :aqua, 0xFF00FFFF
define_color :aquamarine, 0xFF7FFFD4
define_color :azure, 0xFFF0FFFF
define_color :beige, 0xFFF5F5DC
define_color :bisque, 0xFFFFE4C4
define_color :black, 0xFF000000
define_color :blanched_almond, 0xFFFFEBCD
define_color :blue, 0xFF0000FF
define_color :blue_violet, 0xFF8A2BE2
define_color :brown, 0xFFA52A2A
define_color :burly_wood, 0xFFDEB887
define_color :cadet_blue, 0xFF5F9EA0
define_color :chartreuse, 0xFF7FFF00
define_color :chocolate, 0xFFD2691E
define_color :coral, 0xFFFF7F50
define_color :cornflower_blue, 0xFF6495ED
define_color :cornsilk, 0xFFFFF8DC
define_color :crimson, 0xFFDC143C
define_color :cyan, 0xFF00FFFF
define_color :dark_blue, 0xFF00008B
define_color :dark_cyan, 0xFF008B8B
define_color :dark_goldenrod, 0xFFB8860B
define_color :dark_gray, 0xFFA9A9A9
define_color :dark_green, 0xFF006400
define_color :dark_khaki, 0xFFBDB76B
define_color :dark_magenta, 0xFF8B008B
define_color :dark_olive_green, 0xFF556B2F
define_color :dark_orange, 0xFFFF8C00
define_color :dark_orchid, 0xFF9932CC
define_color :dark_red, 0xFF8B0000
define_color :dark_salmon, 0xFFE9967A
define_color :dark_sea_green, 0xFF8FBC8F
define_color :dark_slate_blue, 0xFF483D8B
define_color :dark_slate_gray, 0xFF2F4F4F
define_color :dark_turquoise, 0xFF00CED1
define_color :dark_violet, 0xFF9400D3
define_color :deep_pink, 0xFFFF1493
define_color :deep_sky_blue, 0xFF00BFFF
define_color :dim_gray, 0xFF696969
define_color :dodger_blue, 0xFF1E90FF
define_color :firebrick, 0xFFB22222
define_color :floral_white, 0xFFFFFAF0
define_color :forest_green, 0xFF228B22
define_color :fuchsia, 0xFFFF00FF
define_color :gainsboro, 0xFFDCDCDC
define_color :ghost_white, 0xFFF8F8FF
define_color :gold, 0xFFFFD700
define_color :goldenrod, 0xFFDAA520
define_color :gray, 0xFF808080
define_color :green, 0xFF008000
define_color :green_yellow, 0xFFADFF2F
define_color :honeydew, 0xFFF0FFF0
define_color :hot_pink, 0xFFFF69B4
define_color :indian_red, 0xFFCD5C5C
define_color :indigo, 0xFF4B0082
define_color :ivory, 0xFFFFFFF0
define_color :khaki, 0xFFF0E68C
define_color :lavender, 0xFFE6E6FA
define_color :lavender_blush, 0xFFFFF0F5
define_color :lawn_green, 0xFF7CFC00
define_color :lemon_chiffon, 0xFFFFFACD
define_color :light_blue, 0xFFADD8E6
define_color :light_coral, 0xFFF08080
define_color :light_cyan, 0xFFE0FFFF
define_color :light_goldenrod_yellow, 0xFFFAFAD2
define_color :light_green, 0xFF90EE90
define_color :light_gray, 0xFFD3D3D3
define_color :light_pink, 0xFFFFB6C1
define_color :light_salmon, 0xFFFFA07A
define_color :light_sea_green, 0xFF20B2AA
define_color :light_sky_blue, 0xFF87CEFA
define_color :light_slate_gray, 0xFF778899
define_color :light_steel_blue, 0xFFB0C4DE
define_color :light_yellow, 0xFFFFFFE0
define_color :lime, 0xFF00FF00
define_color :lime_green, 0xFF32CD32
define_color :linen, 0xFFFAF0E6
define_color :magenta, 0xFFFF00FF
define_color :maroon, 0xFF800000
define_color :medium_aquamarine, 0xFF66CDAA
define_color :medium_blue, 0xFF0000CD
define_color :medium_orchid, 0xFFBA55D3
define_color :medium_purple, 0xFF9370DB
define_color :medium_sea_green, 0xFF3CB371
define_color :medium_slate_blue, 0xFF7B68EE
define_color :medium_spring_green, 0xFF00FA9A
define_color :medium_turquoise, 0xFF48D1CC
define_color :medium_violet_red, 0xFFC71585
define_color :midnight_blue, 0xFF191970
define_color :mint_cream, 0xFFF5FFFA
define_color :misty_rose, 0xFFFFE4E1
define_color :moccasin, 0xFFFFE4B5
define_color :navajo_white, 0xFFFFDEAD
define_color :navy, 0xFF000080
define_color :old_lace, 0xFFFDF5E6
define_color :olive, 0xFF808000
define_color :olive_drab, 0xFF6B8E23
define_color :orange, 0xFFFFA500
define_color :orange_red, 0xFFFF4500
define_color :orchid, 0xFFDA70D6
define_color :pale_goldenrod, 0xFFEEE8AA
define_color :pale_green, 0xFF98FB98
define_color :pale_turquoise, 0xFFAFEEEE
define_color :pale_violet_red, 0xFFDB7093
define_color :papaya_whip, 0xFFFFEFD5
define_color :peach_puff, 0xFFFFDAB9
define_color :peru, 0xFFCD853F
define_color :pink, 0xFFFFC0CB
define_color :plum, 0xFFDDA0DD
define_color :powder_blue, 0xFFB0E0E6
define_color :purple, 0xFF800080
define_color :red, 0xFFFF0000
define_color :rosy_brown, 0xFFBC8F8F
define_color :royal_blue, 0xFF4169E1
define_color :saddle_brown, 0xFF8B4513
define_color :salmon, 0xFFFA8072
define_color :sandy_brown, 0xFFF4A460
define_color :sea_green, 0xFF2E8B57
define_color :sea_shell, 0xFFFFF5EE
define_color :sienna, 0xFFA0522D
define_color :silver, 0xFFC0C0C0
define_color :sky_blue, 0xFF87CEEB
define_color :slate_blue, 0xFF6A5ACD
define_color :slate_gray, 0xFF708090
define_color :snow, 0xFFFFFAFA
define_color :spring_green, 0xFF00FF7F
define_color :steel_blue, 0xFF4682B4
define_color :tan, 0xFFD2B48C
define_color :teal, 0xFF008080
define_color :thistle, 0xFFD8BFD8
define_color :tomato, 0xFFFF6347
define_color :transparent, 0x00FFFFFF
define_color :turquoise, 0xFF40E0D0
define_color :violet, 0xFFEE82EE
define_color :wheat, 0xFFF5DEB3
define_color :white, 0xFFFFFFFF
define_color :white_smoke, 0xFFF5F5F5
define_color :yellow, 0xFFFFFF00
define_color :yellow_green, 0xFF9ACD32
class << self
##
# @!method alice_blue
# @return [Color] the newly-created color
# <span style="background-color:#f0f8ff; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method antique_white
# @return [Color] the newly-created color
# <span style="background-color:#faebd7; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method aqua
# @return [Color] the newly-created color
# <span style="background-color:#00ffff; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method aquamarine
# @return [Color] the newly-created color
# <span style="background-color:#7fffd4; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method azure
# @return [Color] the newly-created color
# <span style="background-color:#f0ffff; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method beige
# @return [Color] the newly-created color
# <span style="background-color:#f5f5dc; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method bisque
# @return [Color] the newly-created color
# <span style="background-color:#ffe4c4; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method black
# @return [Color] the newly-created color
# <span style="background-color:#000000; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method blanched_almond
# @return [Color] the newly-created color
# <span style="background-color:#ffebcd; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method blue
# @return [Color] the newly-created color
# <span style="background-color:#0000ff; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method blue_violet
# @return [Color] the newly-created color
# <span style="background-color:#8a2be2; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method brown
# @return [Color] the newly-created color
# <span style="background-color:#a52a2a; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method burly_wood
# @return [Color] the newly-created color
# <span style="background-color:#deb887; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method cadet_blue
# @return [Color] the newly-created color
# <span style="background-color:#5f9ea0; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method chartreuse
# @return [Color] the newly-created color
# <span style="background-color:#7fff00; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method chocolate
# @return [Color] the newly-created color
# <span style="background-color:#d2691e; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method coral
# @return [Color] the newly-created color
# <span style="background-color:#ff7f50; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method cornflower_blue
# @return [Color] the newly-created color
# <span style="background-color:#6495ed; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method cornsilk
# @return [Color] the newly-created color
# <span style="background-color:#fff8dc; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method crimson
# @return [Color] the newly-created color
# <span style="background-color:#dc143c; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method cyan
# @return [Color] the newly-created color
# <span style="background-color:#00ffff; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_blue
# @return [Color] the newly-created color
# <span style="background-color:#00008b; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_cyan
# @return [Color] the newly-created color
# <span style="background-color:#008b8b; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_goldenrod
# @return [Color] the newly-created color
# <span style="background-color:#b8860b; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_gray
# @return [Color] the newly-created color
# <span style="background-color:#a9a9a9; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_green
# @return [Color] the newly-created color
# <span style="background-color:#006400; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_khaki
# @return [Color] the newly-created color
# <span style="background-color:#bdb76b; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_magenta
# @return [Color] the newly-created color
# <span style="background-color:#8b008b; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_olive_green
# @return [Color] the newly-created color
# <span style="background-color:#556b2f; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_orange
# @return [Color] the newly-created color
# <span style="background-color:#ff8c00; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_orchid
# @return [Color] the newly-created color
# <span style="background-color:#9932cc; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_red
# @return [Color] the newly-created color
# <span style="background-color:#8b0000; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_salmon
# @return [Color] the newly-created color
# <span style="background-color:#e9967a; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_sea_green
# @return [Color] the newly-created color
# <span style="background-color:#8fbc8f; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_slate_blue
# @return [Color] the newly-created color
# <span style="background-color:#483d8b; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_slate_gray
# @return [Color] the newly-created color
# <span style="background-color:#2f4f4f; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_turquoise
# @return [Color] the newly-created color
# <span style="background-color:#00ced1; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dark_violet
# @return [Color] the newly-created color
# <span style="background-color:#9400d3; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method deep_pink
# @return [Color] the newly-created color
# <span style="background-color:#ff1493; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method deep_sky_blue
# @return [Color] the newly-created color
# <span style="background-color:#00bfff; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dim_gray
# @return [Color] the newly-created color
# <span style="background-color:#696969; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method dodger_blue
# @return [Color] the newly-created color
# <span style="background-color:#1e90ff; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method firebrick
# @return [Color] the newly-created color
# <span style="background-color:#b22222; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method floral_white
# @return [Color] the newly-created color
# <span style="background-color:#fffaf0; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method forest_green
# @return [Color] the newly-created color
# <span style="background-color:#228b22; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method fuchsia
# @return [Color] the newly-created color
# <span style="background-color:#ff00ff; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method gainsboro
# @return [Color] the newly-created color
# <span style="background-color:#dcdcdc; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method ghost_white
# @return [Color] the newly-created color
# <span style="background-color:#f8f8ff; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method gold
# @return [Color] the newly-created color
# <span style="background-color:#ffd700; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method goldenrod
# @return [Color] the newly-created color
# <span style="background-color:#daa520; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method gray
# @return [Color] the newly-created color
# <span style="background-color:#808080; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method green
# @return [Color] the newly-created color
# <span style="background-color:#008000; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method green_yellow
# @return [Color] the newly-created color
# <span style="background-color:#adff2f; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method honeydew
# @return [Color] the newly-created color
# <span style="background-color:#f0fff0; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method hot_pink
# @return [Color] the newly-created color
# <span style="background-color:#ff69b4; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method indian_red
# @return [Color] the newly-created color
# <span style="background-color:#cd5c5c; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method indigo
# @return [Color] the newly-created color
# <span style="background-color:#4b0082; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method ivory
# @return [Color] the newly-created color
# <span style="background-color:#fffff0; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method khaki
# @return [Color] the newly-created color
# <span style="background-color:#f0e68c; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method lavender
# @return [Color] the newly-created color
# <span style="background-color:#e6e6fa; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method lavender_blush
# @return [Color] the newly-created color
# <span style="background-color:#fff0f5; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method lawn_green
# @return [Color] the newly-created color
# <span style="background-color:#7cfc00; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method lemon_chiffon
# @return [Color] the newly-created color
# <span style="background-color:#fffacd; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method light_blue
# @return [Color] the newly-created color
# <span style="background-color:#add8e6; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method light_coral
# @return [Color] the newly-created color
# <span style="background-color:#f08080; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method light_cyan
# @return [Color] the newly-created color
# <span style="background-color:#e0ffff; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method light_goldenrod_yellow
# @return [Color] the newly-created color
# <span style="background-color:#fafad2; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method light_green
# @return [Color] the newly-created color
# <span style="background-color:#90ee90; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method light_gray
# @return [Color] the newly-created color
# <span style="background-color:#d3d3d3; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method light_pink
# @return [Color] the newly-created color
# <span style="background-color:#ffb6c1; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method light_salmon
# @return [Color] the newly-created color
# <span style="background-color:#ffa07a; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method light_sea_green
# @return [Color] the newly-created color
# <span style="background-color:#20b2aa; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method light_sky_blue
# @return [Color] the newly-created color
# <span style="background-color:#87cefa; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method light_slate_gray
# @return [Color] the newly-created color
# <span style="background-color:#778899; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method light_steel_blue
# @return [Color] the newly-created color
# <span style="background-color:#b0c4de; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method light_yellow
# @return [Color] the newly-created color
# <span style="background-color:#ffffe0; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method lime
# @return [Color] the newly-created color
# <span style="background-color:#00ff00; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method lime_green
# @return [Color] the newly-created color
# <span style="background-color:#32cd32; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method linen
# @return [Color] the newly-created color
# <span style="background-color:#faf0e6; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method magenta
# @return [Color] the newly-created color
# <span style="background-color:#ff00ff; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method maroon
# @return [Color] the newly-created color
# <span style="background-color:#800000; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method medium_aquamarine
# @return [Color] the newly-created color
# <span style="background-color:#66cdaa; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method medium_blue
# @return [Color] the newly-created color
# <span style="background-color:#0000cd; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method medium_orchid
# @return [Color] the newly-created color
# <span style="background-color:#ba55d3; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method medium_purple
# @return [Color] the newly-created color
# <span style="background-color:#9370db; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method medium_sea_green
# @return [Color] the newly-created color
# <span style="background-color:#3cb371; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method medium_slate_blue
# @return [Color] the newly-created color
# <span style="background-color:#7b68ee; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method medium_spring_green
# @return [Color] the newly-created color
# <span style="background-color:#00fa9a; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method medium_turquoise
# @return [Color] the newly-created color
# <span style="background-color:#48d1cc; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method medium_violet_red
# @return [Color] the newly-created color
# <span style="background-color:#c71585; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method midnight_blue
# @return [Color] the newly-created color
# <span style="background-color:#191970; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method mint_cream
# @return [Color] the newly-created color
# <span style="background-color:#f5fffa; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method misty_rose
# @return [Color] the newly-created color
# <span style="background-color:#ffe4e1; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method moccasin
# @return [Color] the newly-created color
# <span style="background-color:#ffe4b5; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method navajo_white
# @return [Color] the newly-created color
# <span style="background-color:#ffdead; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method navy
# @return [Color] the newly-created color
# <span style="background-color:#000080; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method old_lace
# @return [Color] the newly-created color
# <span style="background-color:#fdf5e6; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method olive
# @return [Color] the newly-created color
# <span style="background-color:#808000; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method olive_drab
# @return [Color] the newly-created color
# <span style="background-color:#6b8e23; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method orange
# @return [Color] the newly-created color
# <span style="background-color:#ffa500; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method orange_red
# @return [Color] the newly-created color
# <span style="background-color:#ff4500; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method orchid
# @return [Color] the newly-created color
# <span style="background-color:#da70d6; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method pale_goldenrod
# @return [Color] the newly-created color
# <span style="background-color:#eee8aa; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method pale_green
# @return [Color] the newly-created color
# <span style="background-color:#98fb98; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method pale_turquoise
# @return [Color] the newly-created color
# <span style="background-color:#afeeee; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method pale_violet_red
# @return [Color] the newly-created color
# <span style="background-color:#db7093; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method papaya_whip
# @return [Color] the newly-created color
# <span style="background-color:#ffefd5; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method peach_puff
# @return [Color] the newly-created color
# <span style="background-color:#ffdab9; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method peru
# @return [Color] the newly-created color
# <span style="background-color:#cd853f; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method pink
# @return [Color] the newly-created color
# <span style="background-color:#ffc0cb; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method plum
# @return [Color] the newly-created color
# <span style="background-color:#dda0dd; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method powder_blue
# @return [Color] the newly-created color
# <span style="background-color:#b0e0e6; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method purple
# @return [Color] the newly-created color
# <span style="background-color:#800080; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method red
# @return [Color] the newly-created color
# <span style="background-color:#ff0000; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method rosy_brown
# @return [Color] the newly-created color
# <span style="background-color:#bc8f8f; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method royal_blue
# @return [Color] the newly-created color
# <span style="background-color:#4169e1; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method saddle_brown
# @return [Color] the newly-created color
# <span style="background-color:#8b4513; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method salmon
# @return [Color] the newly-created color
# <span style="background-color:#fa8072; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method sandy_brown
# @return [Color] the newly-created color
# <span style="background-color:#f4a460; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method sea_green
# @return [Color] the newly-created color
# <span style="background-color:#2e8b57; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method sea_shell
# @return [Color] the newly-created color
# <span style="background-color:#fff5ee; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method sienna
# @return [Color] the newly-created color
# <span style="background-color:#a0522d; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method silver
# @return [Color] the newly-created color
# <span style="background-color:#c0c0c0; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method sky_blue
# @return [Color] the newly-created color
# <span style="background-color:#87ceeb; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method slate_blue
# @return [Color] the newly-created color
# <span style="background-color:#6a5acd; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method slate_gray
# @return [Color] the newly-created color
# <span style="background-color:#708090; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method snow
# @return [Color] the newly-created color
# <span style="background-color:#fffafa; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method spring_green
# @return [Color] the newly-created color
# <span style="background-color:#00ff7f; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method steel_blue
# @return [Color] the newly-created color
# <span style="background-color:#4682b4; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method tan
# @return [Color] the newly-created color
# <span style="background-color:#d2b48c; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method teal
# @return [Color] the newly-created color
# <span style="background-color:#008080; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method thistle
# @return [Color] the newly-created color
# <span style="background-color:#d8bfd8; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method tomato
# @return [Color] the newly-created color
# <span style="background-color:#ff6347; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method transparent
# @return [Color] the newly-created color
# <span style="background-color:#ffffff; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method turquoise
# @return [Color] the newly-created color
# <span style="background-color:#40e0d0; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method violet
# @return [Color] the newly-created color
# <span style="background-color:#ee82ee; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method wheat
# @return [Color] the newly-created color
# <span style="background-color:#f5deb3; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method white
# @return [Color] the newly-created color
# <span style="background-color:#ffffff; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method white_smoke
# @return [Color] the newly-created color
# <span style="background-color:#f5f5f5; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method yellow
# @return [Color] the newly-created color
# <span style="background-color:#ffff00; display: inline-block; width: 20px; height: 20px;"></span>
##
# @!method yellow_green
# @return [Color] the newly-created color
# <span style="background-color:#9acd32; display: inline-block; width: 20px; height: 20px;"></span>
end
end
end
| true |
9692e46146a0128db7ac9e37f5c17f2eaf3b5321
|
Ruby
|
ykz1/LS_101_foundations
|
/0_exercises/easy_7/5_staggered_caps_1.rb
|
UTF-8
| 867 | 3.828125 | 4 |
[] |
no_license
|
# 5_staggered_caps_1.rb
# Start 12:31PM
# Finish 12:37PM
# Extras 12:46PM
# ARgument: string
# Return: new string
# Transformation: upcase every other char, downcase rest
def staggered_case(str)
str.chars.map.with_index { |char, idx| idx.even? ? char.upcase : char.downcase }.join
end
def staggered_case2(str)
str[0] == str[0].downcase ? toggle = 1 : toggle = 0
str.chars.map.with_index { |char, idx| idx % 2 == toggle ? char.upcase : char.downcase }.join
end
p staggered_case('I Love Launch School!') == 'I LoVe lAuNcH ScHoOl!'
p staggered_case('ALL_CAPS') == 'AlL_CaPs'
p staggered_case('ignore 77 the 444 numbers') == 'IgNoRe 77 ThE 444 NuMbErS'
puts
p staggered_case2('I Love Launch School!') == 'I LoVe lAuNcH ScHoOl!'
p staggered_case2('ALL_CAPS') == 'AlL_CaPs'
p staggered_case2('ignore 77 the 444 numbers') #== 'IgNoRe 77 ThE 444 NuMbErS'
| true |
dc0a5079c6f379f65a42611426e95b3e27ab6a07
|
Ruby
|
sherpc/cryptography
|
/lab3/main.rb
|
UTF-8
| 852 | 3.640625 | 4 |
[] |
no_license
|
#!/usr/bin/ruby
def make_sqrt_list
cache = { 1 => 1 }
last_key = 1
lambda { |x|
return cache if cache.has_value?(x)
while(last_key != x) do
last_key += 1
#p last_key
cache[last_key * last_key] = last_key
end
cache
}
end
Sqrt_list = make_sqrt_list
def is_sqrt? x, n
y2 = x * x - n
Sqrt_list[Math.sqrt(y2).ceil][y2]
end
def factorize n
return 2, n / 2 if n % 2 == 0
x = Math.sqrt(n).floor
y = nil
while(not y)
x += 1
y = is_sqrt?(x, n)
end
return x+y, x-y
end
def assert n
x, y = factorize(n)
p [x, y]
raise "Error!" unless n == (x * y)
end
def read_number i
File.open(ARGV[i], "r") do |f|
f.readline.to_i
end
end
def write_answer x, y
File.open(ARGV[1], "w") do |f|
f.puts "#{x} #{y}"
end
end
if __FILE__ == $0
write_answer(*factorize(read_number(0)))
end
| true |
ac4ffdb96cee401115af582b1ca0037fd4f69836
|
Ruby
|
need4spd/eulerproject
|
/need4spd/euler_21.rb
|
UTF-8
| 942 | 3.484375 | 3 |
[] |
no_license
|
def getDivisors(num)
divisors=Array.new(0)
startnum = 1
if num==1
divisors.push(1)
return divisors
end
while true
if num%startnum == 0
divisors.push(startnum)
end
startnum+=1
if num==startnum
break
end
end
return divisors
end
targetnum=10000
resultList=Array.new(1, 0)
while (true)
if resultList.count(targetnum) > 0
targetnum=targetnum-1
next
end
divisors=getDivisors(targetnum) #targetnum 220
sumOfDivisors=divisors.inject(:+) #sumofDivisors 284
tempDivisors=getDivisors(sumOfDivisors)
tempSumOfDivisors=tempDivisors.inject(:+)
if targetnum==tempSumOfDivisors and targetnum != sumOfDivisors
resultList.push(targetnum)
resultList.push(sumOfDivisors)
end
targetnum=targetnum-1
if targetnum==0
break
end
end
puts "result #{resultList}"
puts resultList.inject(:+)
| true |
affc11649c01cba7e019dfd1ad2c457e46b5a39d
|
Ruby
|
DianaLuciaRinconBl/Ruby-book-exercises
|
/Arrays/ex_7.rb
|
UTF-8
| 447 | 4.25 | 4 |
[] |
no_license
|
#Write a program that iterates over an array and builds a new
#array that is the result of incrementing each value in the
#original array by a value of 2. You should have two arrays at
#the end of this program, The original array and the new array
#you've created. Print both arrays to the screen using the p
#method instead of puts.
arr = [1,2,3,4,5]
arr2 = []
arr.each do |num|
num += 2
arr2 << num
#or arr2 << num + 2
end
p arr
p arr2
| true |
327c9ed76c9c0a59664fd3cd7a0014783305be74
|
Ruby
|
adellanno/Chris-Pine-s-Learn-to-Program
|
/ch8-arrays-and-iterators/ex8-0.rb
|
UTF-8
| 346 | 3.609375 | 4 |
[] |
no_license
|
# Arrays:
names = ['Ada', 'Belle', 'Chris']
puts names
puts
puts names[0]
puts names[1]
puts names[2]
puts names[3] # This is out of range
other_peeps = []
other_peeps[3] = 'beebee Meaner'
other_peeps[0] = 'Ah-ha'
other_peeps[1] = 'Seedee'
other_peeps[0] = 'beebee Ah-ha'
puts other_peeps
# Notice how [2] is automatically with nil by default
| true |
89b80ee7c29e05aad448b4def7b9136425c8df3d
|
Ruby
|
KyleBWilson49/Recusion_Practice
|
/exponent.rb
|
UTF-8
| 348 | 3.515625 | 4 |
[] |
no_license
|
def recursion1(number, exponent)
return 1 if exponent == 0
number * recursion1(number, exponent - 1)
end
def recursion2(number, exponent)
return 1 if exponent == 0
if exponent.even?
result = recursion2(number, exponent / 2)
result * result
else
exp = recursion2(number, (exponent - 1) / 2)
number * exp * exp
end
end
| true |
9418e539e3292fd25dca98f340c6cf9f5b3e05be
|
Ruby
|
kristianmandrup/jwt_auth
|
/lib/jwt_auth/token_validator.rb
|
UTF-8
| 568 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
module JwtAuth
class TokenValidator
attr_reader :token
def initialize(token)
@token = token
end
def valid_jwt_token?
user_identifier == token_identifier if decoded_data.present?
end
def user_identifier
user.email
end
def token_identifier
decoded_data.first[user_id.to_s]
end
def user
@user ||= User.find_by_id(user_id)
end
def user_id
@user_id ||= decoded_data.first.keys.first.to_i
end
def decoded_data
JWT.decode(token, nil, false) rescue ""
end
end
end
| true |
d333ce374575e00fb3c3bdbd41e23dc06bb49eed
|
Ruby
|
Theoonetj/cartoon-collections-online-web-ft-120919
|
/cartoon_collections.rb
|
UTF-8
| 1,506 | 3.75 | 4 |
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
def roll_call_dwarves(array) # code an argument here
i = 0 # Your code here
while i < array.length
puts "#{i + 1}. #{array[i]}"
i += 1
end
end
dwarvesName = ["Doc", "Dopey", "Bashful", "Grumpy"]
roll_call_dwarves(dwarvesName)
def summon_captain_planet(array) # code an argument here
# Your code here
i = 0
returnArray = []
while i < array.length
returnArray << array[i].capitalize + "!"
i = i + 1
end
returnArray
end
planeteer_calls = ["earth", "wind", "fire", "water", "heart"]
summon_captain_planet(planeteer_calls)
def long_planeteer_calls(array) # code an argument here
# Your code here
i = 0
if array.any?{|i| i.length > 4}
return true
else
return false
i = i + 1
end
end
short_words = ["puff", "go", "two"]
long_planeteer_calls(short_words)
assorted_words = ["two", "go", "industrious", "bop"]
long_planeteer_calls(assorted_words)
def find_the_cheese(array) # code an argument here
# the array below is here to help
cheese_types = ["cheddar", "gouda", "camembert"]
array.find do |type|
cheese_types.include?(type)
end
end
snacks = ["crackers", "gouda", "thyme"]
find_the_cheese(snacks)
soup = ["tomato soup", "cheddar", "oyster crackers", "gouda"]
find_the_cheese(soup)
ingredients = ["garlic", "rosemary", "bread"]
find_the_cheese(ingredients)
| true |
e8a935c170d3df0de9c08ac9fc3e0b129f6e31e1
|
Ruby
|
zekrullah97/scutiger
|
/test/template
|
UTF-8
| 240 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require 'erb'
class Template
def name
@name ||= 0
@name += 1
"name_a#{@name}"
end
def erb(file)
ERB.new(File.read(file), nil, '-', name).result(binding)
end
end
puts Template.new.erb(ARGV[0])
| true |
d647daa3f28b470a5d6d27f57260399d23741033
|
Ruby
|
c1iff/clock_angle
|
/lib/clock_angle.rb
|
UTF-8
| 397 | 3.0625 | 3 |
[] |
no_license
|
class String
define_method(:clock_angle) do
hands = self.split(":")
hour_hand = hands.at(0).to_f()
minute_hand = hands.at(1).to_f()
minute_degrees = minute_hand * 6
hour_degrees = ((hour_hand * 30) + (minute_hand/2))
degrees_apart = (hour_degrees - minute_degrees).abs
if (degrees_apart > 180)
360 - degrees_apart
else
degrees_apart
end
end
end
| true |
4a480f9dea6ced061862d6aef761057265e54dd2
|
Ruby
|
vitaliel/push_chat
|
/script/comet-push-consume.rb
|
UTF-8
| 1,202 | 2.515625 | 3 |
[] |
no_license
|
require 'rubygems'
require 'em-http'
def subscribe(opts)
listener = EventMachine::HttpRequest.new('http://127.0.0.5/activity?id='+ opts[:channel]).get :head => opts[:head]
listener.callback {
# print recieved message, re-subscribe to channel with
# the last-modified header to avoid duplicate messages
puts "Listener recieved: " + listener.response + "\n"
modified = listener.response_header['LAST_MODIFIED']
subscribe({:channel => opts[:channel], :head => {'If-Modified-Since' => modified}})
}
end
EventMachine.run {
channel = "pub"
# Publish new message every 5 seconds
EM.add_periodic_timer(5) do
time = Time.now
publisher = EventMachine::HttpRequest.new('http://127.0.0.5/publish?id='+channel).post :body => "Hello @ #{time}"
publisher.callback {
puts "Published message @ #{time}"
puts "Response code: " + publisher.response_header.status.to_s
puts "Headers: " + publisher.response_header.inspect
puts "Body: \n" + publisher.response
puts "\n"
}
end
# open two listeners (aka broadcast/pubsub distribution)
subscribe(:channel => channel)
subscribe(:channel => channel)
}
| true |
e36c373fc6f291e8fbfcb052b96b8f8eede21c01
|
Ruby
|
agbaber/2018-advent-of-code
|
/day_01/day_1.rb
|
UTF-8
| 497 | 3.515625 | 4 |
[] |
no_license
|
@input = []
@value = 0
@new_vals = [0]
@i = 0
def read_file
File.open("input.txt", "r") do |f|
f.each_line do |line|
@input << line.chomp
end
end
end
def run
@input.each do |i|
# puts "sending #{i[0]} #{i[1..-1]} "
@value = @value.send(i[0], i[1..-1].to_i)
if @new_vals.include?(@value)
puts "Returned to:"
puts @value
puts "#{@i} iterations"
exit
else
@new_vals << @value
@i += 1
end
end
run
end
read_file
run
| true |
7d733866fdfc1f019a81e08ade21438326334771
|
Ruby
|
ballman/hoops
|
/app/models/cstv_team_game.rb
|
UTF-8
| 412 | 2.65625 | 3 |
[] |
no_license
|
class CstvTeamGame < TeamGame
def validate_player_total_for_stat(stat)
player_total = player_games.inject(0) { | total, player | total + player.send(stat) }
team_total = self.send(stat)
if (player_total != team_total)
"Team total of #{stat} does not sum. Players = #{player_total} Team = #{team_total}"
end
end
def boxscore_name(player)
return player.cstv_bs_name
end
end
| true |
0f5c74f4cae4707e0e4f49535a4e9b5fbe9278a3
|
Ruby
|
lpenzey/interview_exercises
|
/cracking_the_code_interview/chapter_1/1.2_check_permutation/lib/check_permutation.rb
|
UTF-8
| 266 | 3.53125 | 4 |
[] |
no_license
|
# frozen_string_literal: true
# Given two strings, write a method to decide
# if one is a permutation of the other.
class CheckPermutation
def check(thing1, thing2)
all_combos = thing1.chars.permutation.map &:join
all_combos.include?(thing2)
end
end
| true |
34a6c5a9ef4fb9d1b0aeb609dbd9fddbf7cc5ff1
|
Ruby
|
greenygh0st/coursemology2
|
/app/helpers/course/assessment/question/programming_helper.rb
|
UTF-8
| 2,328 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module Course::Assessment::Question::ProgrammingHelper
# Displays the result alert for an import job.
#
# @return [String] If there is an import job for the question.
# @return [nil] If there is no import job for the question.
def import_result_alert
import_job = @programming_question.import_job
return nil unless import_job
if import_job.completed?
successful_import_alert
elsif import_job.errored?
errored_import_alert
end
end
# Checks if the import job errored.
#
# @return [Boolean]
def import_errored?
!@programming_question.import_job.nil? && @programming_question.import_job.errored?
end
# Determines if the build log should be displayed.
#
# @return [Boolean]
def display_build_log?
import_errored? &&
@programming_question.import_job.error['class'] ==
Course::Assessment::ProgrammingEvaluationService::Error.name
end
private
def successful_import_alert
content_tag(:div, class: ['alert', 'alert-success']) do
t('course.assessment.question.programming.form.import_result.success')
end
end
def errored_import_alert
content_tag(:div, class: ['alert', 'alert-danger']) do
t('course.assessment.question.programming.form.import_result.error',
error: import_error_message(@programming_question.import_job.error))
end
end
# Translates an error object serialised in the +TrackableJobs+ table to a user-readable message.
#
# @param [Hash] error The error object in the +TrackableJobs+ table.
# @return [String]
def import_error_message(error) # rubocop:disable Metrics/MethodLength
case error['class']
when InvalidDataError.name
t('course.assessment.question.programming.form.import_result.errors.invalid_package')
when Timeout::Error.name
t('course.assessment.question.programming.form.import_result.errors.evaluation_timeout')
when Course::Assessment::ProgrammingEvaluationService::TimeLimitExceededError.name
t('course.assessment.question.programming.form.import_result.errors.time_limit_exceeded')
when Course::Assessment::ProgrammingEvaluationService::Error.name
t('course.assessment.question.programming.form.import_result.errors.evaluation_error')
else
error['message']
end
end
end
| true |
52a35cdc767c216beb5bea466c584d3e2257d3fe
|
Ruby
|
J-Y/RubyQuiz
|
/ruby_quiz/quiz36_sols/solutions/James Edward Gray II/chess/lib/chess.rb
|
UTF-8
| 365 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/local/bin/ruby -w
# chess.rb
#
# Created by James Edward Gray II on 2005-06-13.
# Copyright 2005 Gray Productions. All rights reserved.
#
# Require this file to gain access to the entire chess library.
require "chess/board"
require "chess/piece"
require "chess/pawn"
require "chess/knight"
require "chess/bishop"
require "chess/rook"
require "chess/queen"
require "chess/king"
| true |
646459252f16449b28bd457e693e12e595db4e5d
|
Ruby
|
hyphenized/c2-module2
|
/week-1/day-3/reduce.rb
|
UTF-8
| 855 | 4.15625 | 4 |
[] |
no_license
|
def reduce(arr, initial)
for x in arr do
initial = yield initial,x
end
initial
end
test_array = [2, 3, 4, 5]
puts reduce(test_array, 0) { |total_sum, current_value| total_sum + current_value }
# Result: 14
# The execution of the method would be:
# First execution the block is provided the arguments 0 (initial value) and 2 (current value). It sums the values, returns 2.
# Second execution the block is provided the arguments 2 (last result) and 3 (current value). It sums the values and returns 5.
# Third execution the block is provided the arguments 5 (last result) and 4 (current value). It sums the values and returns 9.
# Forth execution the block is provided the arguments 9 (last result) and 5 (current value). It sums the values and returns 14.
# The last iteration returns 14, and that is the value that the method returns.
| true |
27ced908bdb2659e1b569ac5d694c16ae20d72b0
|
Ruby
|
alexpapworth/fizzbuzz-app
|
/app/helpers/application_helper.rb
|
UTF-8
| 144 | 2.5625 | 3 |
[] |
no_license
|
module ApplicationHelper
def check_fizzbuzz(number)
"#{"fizz" if number.to_i % 3 == 0}#{'buzz' if number.to_i % 5 == 0}".capitalize
end
end
| true |
fa727ee1df93180325a9736741b2b45be8f78b86
|
Ruby
|
ryanduchin/ActiveRecordLite
|
/lib/01_sql_object.rb
|
UTF-8
| 2,999 | 3.171875 | 3 |
[] |
no_license
|
require_relative 'db_connection'
require 'active_support/inflector'
class SQLObject
def self.columns
#get COLUMNS from TABLES (not just instance variables)
#returns array of symbols
DBConnection::execute2(<<-SQL).first.map { |val| val.to_sym }
SELECT
*
FROM
#{table_name}
SQL
end
def self.finalize!
columns.each do |col|
# define_method("#{col}") { instance_variable_get("@#{col}") }
# define_method("#{col}=") { |val| instance_variable_set("@#{col}", val) }
define_method("#{col}") { attributes[col] }
define_method("#{col}=") { |val| attributes[col] = val }
end
end
def self.table_name=(table_name)
@table_name = table_name
end
def self.table_name
@table_name ||= self.to_s.tableize #also sets it if null...
# @table_name || self.to_s.tableize #doesn't set, and passes
end
def self.all
results = DBConnection::execute(<<-SQL)
SELECT
#{table_name}.*
FROM
#{table_name}
SQL
parse_all(results)
end
def self.parse_all(results)
results.map { |result| self.new(result) }
end
def self.find(id)
result = DBConnection::execute(<<-SQL, id)
SELECT
#{table_name}.*
FROM
#{table_name}
WHERE
#{table_name}.id == ?
SQL
return nil if result.empty?
self.new(result.first)
end
def initialize(params = {})
params.each do |attr_name, value|
attr_name = attr_name.to_sym
#why doesn't this call setter method?
#there is no literal 'attr_name' accessor method, it isn't interpolated!!
raise "unknown attribute '#{attr_name}'" if !self.class.columns.include?(attr_name)
self.send("#{attr_name}=", value)
#need to interpolate this because not actually called "attr_name ="
#send (method, arg) to self (instance for instance variable setter) s
end
end
def attributes
@attributes ||= {}
end
def attribute_values
self.class.columns.map {|attr_name| self.send("#{attr_name}")}
end
def insert
cols = self.class.columns
col_names = cols.join(", ")
question_marks = (["?"] * cols.count).join(", ")
newobj = DBConnection::execute(<<-SQL, *attribute_values)
INSERT INTO
#{self.class.table_name} (#{col_names})
VALUES
(#{question_marks})
SQL
#don't forget scope of SQL query - needs a self.class to access table name!
self.id = DBConnection::last_insert_row_id #self is the cat object you are inserting
end
def update
set_line = self.class.columns.map {|col| "#{col} = ?"}.join(", ")
DBConnection::execute(<<-SQL, *attribute_values, self.id)
UPDATE
#{self.class.table_name}
SET
#{set_line}
WHERE
id = ?
SQL
#don't forget scope of SQL query - needs a self.class to access table name!
#also forgot to interpolate set_line!!!
end
def save
if self.id.nil?
self.insert
else
self.update
end
end
end
| true |
ae7e3cd361e980ee2279b6fb8de0894d9b2daf74
|
Ruby
|
thetauri/skystone
|
/SkyStone/plugin.rb
|
UTF-8
| 563 | 2.515625 | 3 |
[] |
no_license
|
module SkyStone
class Plugin
include Singleton
def setup(plugin)
@plugin = plugin
end
def debug(text)
broadcast "SkyStone: #{text}"
end
def event(*args)
@plugin.event(*args)
end
def public_command(*args)
@plugin.public_command(*args)
end
def broadcast(message, color = nil)
message = case color
when :red
red(message)
else
message
end
@plugin.server.broadcast_message message
end
private
def plugin
@plugin
end
end
end
| true |
5b69545c038de9f633610010432dab7a4161e281
|
Ruby
|
da99/megauni.ruby
|
/models/Argumentor.rb
|
UTF-8
| 1,207 | 3.15625 | 3 |
[
"MIT"
] |
permissive
|
class Argumentor
class Bag
def initialize hash
hash.each { |key, val|
eval %~
def self.#{key}
#{val.inspect}
end
~
}
end
end # === class Bag
def self.argue args, &blok
obj = new
obj.instance_eval {
@args = args
@allow = []
@order = []
@values = {}
}
obj.instance_eval( &blok )
obj.argue args
end
def allow raw_hash
hash = raw_hash.to_a.map { |pair|
[pair.first.to_sym, pair.last]
}
@values = @values.merge( Hash[*(hash.flatten)] )
@args = ( @args + @values.keys )
@values
end
def single raw_key
multi raw_key
end
def multi *args
if @order[args.size]
raise ArgumentError, "Argument size taken: #{@order[args.size].inspect}. New: #{args.inspect}"
end
@order[args.size] = args
end
def argue args
unless @order[args.size]
raise ArgumentError, "Invalid number of arguments: #{args.inspect}"
end
@order[args.size].each_index { |index|
name = @order[args.size][index]
@values[name] = args[index]
}
Bag.new( @values )
end
end # === class Argumentor
| true |
4941aefd803e277f3445c8af86547518d25d9388
|
Ruby
|
imogenmisso/oystercard-1
|
/spec/journey_spec.rb
|
UTF-8
| 1,010 | 3 | 3 |
[] |
no_license
|
require 'journey'
require 'pry'
describe Journey do
let (:oyster) {double :oyster}
let (:station_1) {double :station_1, name: "Aldgate East", zone: 1}
let (:station_2) {double :station_2, name: "Waterloo", zone: 1}
it "has an entry station" do
journey = Journey.new(station_1)
expect(journey.entry_station).to eq "Aldgate East"
end
it "has an exit station" do
journey = Journey.new(station_1)
allow(oyster).to receive(:touch_out).with(station_2).and_return station_2
exit_station = oyster.touch_out(station_2)
journey.add_exit_station(exit_station)
expect(journey.exit_station).to eq "Waterloo"
end
it "returns 1 when journey completed" do
journey = Journey.new(station_1)
allow(oyster).to receive(:deduct).with(1)
expect(journey.fare(true, oyster)).to eq 1
end
it "returns 6 when journey incomplete" do
journey = Journey.new(station_1)
allow(oyster).to receive(:deduct).with(6)
expect(journey.fare(false, oyster)).to eq 6
end
end
| true |
eb59599d1c36043e00269b7c0df84451a9574e8b
|
Ruby
|
anytimesoon/sinatra-mvc-lab-v-000
|
/models/piglatinizer.rb
|
UTF-8
| 808 | 3.625 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class PigLatinizer
def piglatinize(text)
answer = text.split(' ').collect do |word|
if first_letter_helper(word) > 0
first_letter = word.slice!(0 .. first_letter_helper(word) - 1 )
word + first_letter + "ay"
else
word + "way"
end
end
answer.join(' ')
end
def to_pig_latin(text)
piglatinize(text)
end
def first_letter_helper(word)
vowels = ['a', 'e', 'i', 'o', 'u']
arr = ''
word.downcase.split('').each do |letter|
break if vowels.include?(letter)
arr << letter
end
arr.length
# if word[0].scan(/[aeiou]/i).length == 1
# "vowel"
# elsif word[0].scan(/[aeiou]/i).length == 0 && word[1].scan(/[aeiou]/i).length == 0
# "double consonant"
# else
# "consonant"
# end
end
end
| true |
24828d962915179a91a9ab3102a9db56a45e3fa2
|
Ruby
|
ScStew/tic_tac_toe_app
|
/console_game_remake.rb
|
UTF-8
| 3,490 | 3.453125 | 3 |
[] |
no_license
|
require_relative "board.rb"
require_relative "player.rb"
require_relative "ai.rb"
def how_many_players
num = " "
p "how many players 1:2"
until num != " "
num = gets.chomp
# num = "0"
if num == "1"
num = "1"
elsif num == "2"
num = "2"
elsif num == "0"
num = "0"
else
num = " "
p "not a valid choice"
end
end
num
end
def choose_ai
p "difficulty 1:2:3"
ai = " "
until ai != ' ' do
ai = gets.chomp
# ai = "3"
if ai == "1"
ai = Random_ai.new
elsif ai == "2"
ai = Sequence_ai.new
elsif ai == "3"
ai = Hard_ai.new
else
ai = " "
p "invalid choice"
end
end
ai
end
def first_or_second
p "would you like to go first(y/n)"
choice = " "
until choice != " " do
choice = gets.chomp.upcase
if choice == "Y"
choice = "player"
elsif choice == "N"
choice = "ai"
else
p "invalid input"
choice = " "
end
end
choice
end
def game
board_class = Board.new
player_class = Player.new
# board = board_class.game_board
num = how_many_players
game = "start"
ai = ""
ai_2 = ""
order =""
if num == "1"
ai = choose_ai
if first_or_second == "player"
order = {"o" => "ai", "x" => "player"}
else
order = {"o" => "player", "x" => "ai"}
end
elsif num == "2"
order = {"o" => "player", "x" => "player"}
else
ai = choose_ai
ai_2 = choose_ai
order = {"o" => "ai_2", "x" => "ai"}
end
player_class.player = "x"
until game == "done" do
board = board_class.game_board
player = player_class.player
p "#{player}'s turn'"
board_class.print
if order[player_class.player] == "player"
p "choose one"
choice = gets.chomp
elsif order[player_class.player] == "ai"
choice = ai.move(board_class.game_board,player_class.player)
else
choice = ai_2.move(board_class.game_board,player_class.player)
end
if board_class.key_check?(choice) == true
if board_class.valid_spot?(choice) == true
board_class.update(player,choice)
if board_class.winner? == true
ret = "#{player} wins"
game = "done"
else
if board_class.board_not_full? == true
player_class.change_players
else
ret = "tie game"
game = "done"
end
end
else
p "invalid move"
end
else
p "invalid move"
end
end
board_class.print
p ret
end
game
# def ai_test
# counter = 0
# 10587.times do
# ret = game
# counter += 1
# p "#{ret} #{counter}"
# if ret != "tie game"
# break
# end
# end
# end
# ai_test
| true |
b65313ccf9ba0681376a6001c4ac439349dd78db
|
Ruby
|
olessiap/learningruby
|
/Weekly-Projects/week-1/part4.rb
|
UTF-8
| 142 | 3 | 3 |
[] |
no_license
|
require "CSV"
name = "COLIN"
CSV.foreach("/Users/Olie/coding/learningruby/part2.csv") do |row|
if row[0] == name
puts row[3]
end
end
| true |
8888d93887d2264aef3c25aa16eefb4b70268c2a
|
Ruby
|
gde-unicamp/gde
|
/app/crawlers/faculty_mech.rb
|
UTF-8
| 921 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
#
# A Mech to visit DAC's website and extract
# Faculty and a list of Course codes
#
class FacultyMech < GdeMech
attr_reader :term, :faculty
def initialize(term, faculty)
@faculty = faculty
@term = term
super()
get(dac_page)
end
def dac_page
"http://www.dac.unicamp.br/sistemas/horarios/grad/#{dac_url_period_param}/#{faculty.acronym}.htm"
end
def courses
@courses ||= course_codes.reduce([]) do |courses, course_code|
course = Course.find_by(code: course_code) || Course.create!(code: course_code)
course.update!(faculty: faculty)
courses << course
courses
end
end
#
# Edgecase: F_128 and similars (The real course code is F 128, but in the URL it's F_128)
#
def course_codes
@course_codes ||= page.search("//a[@href!='javascript:history.go (-1)()']").map do |node|
node.get_attribute('href')[/\w+/].tr('_', ' ')
end
end
end
| true |
f2dba6ceb83dfe03b1b28608be196b150637afd8
|
Ruby
|
travislavery/triangle-classification-v-000
|
/lib/triangle.rb
|
UTF-8
| 908 | 3.3125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Triangle
attr_accessor :type
attr_reader :side1, :side2, :side3
def initialize(side1, side2, side3)
@side1 = side1
@side2 = side2
@side3 = side3
end
def kind
if (check_sides)
if (@side1 == @side2 && @side1 == @side3)
@type = :equilateral
elsif (@side1 == @side2 || @side1 == @side3 || @side2 == @side3)
@type = :isosceles
else (@side1 != @side2 && @side1 != @side3 && @side2 != @side3)
@type = :scalene
end
puts "#{self.type}"
self.type
else
begin
raise TriangleError
#rescue TriangleError => error
puts error.message
end
end
end
def check_sides
if ((@side1>0) && (@side2>0) && (@side3>0))
if (@side1 + @side2 > @side3) && (@side2 + @side3 > @side1) && (@side3 + @side1 > @side2)
return true
end
else false
end
end
end
class TriangleError < StandardError
def message
"bad"
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.