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 |
---|---|---|---|---|---|---|---|---|---|---|---|
d46fb0fc803d9d988670f7d7c408496809777f61
|
Ruby
|
stevenb-nz/AdventOfCode2017
|
/day18a.rb
|
UTF-8
| 1,312 | 3.25 | 3 |
[
"MIT"
] |
permissive
|
def day18(input)
lines = input.split("\n")
next_line = 0
registers = Hash.new
sounds = []
recovered_sounds = []
begin
this_line = lines[next_line].split(' ')
val1 = get_val(this_line[1],registers)
if ('a'..'z').include?(this_line[1]) then
reg = this_line[1]
end
if this_line.size > 2 then
val2 = get_val(this_line[2],registers)
end
case this_line[0]
when "snd"
sounds.push val1
next_line += 1
when "set"
registers[reg] = val2
next_line += 1
when "add"
registers[reg] += val2
next_line += 1
when "mul"
registers[reg] *= val2
next_line += 1
when "mod"
registers[reg] %= val2
next_line += 1
when "rcv"
if val1 != 0 then
recovered_sounds.push sounds[-1]
break
else
next_line += 1
end
when "jgz"
if val1 > 0 then
next_line += val2
else
next_line += 1
end
else
print "error"
break
end
end until !(0...lines.size).include?(next_line)
return recovered_sounds[0]
end
def get_val(s,r)
if ('a'..'z').include?(s) then
if !r.has_key?(s) then
r[s] = 0
end
return r[s]
else
return s.to_i
end
end
input = File.read("day18_input.txt").chomp
puts day18(input)
| true |
bd1940112e982f327057a8295d2e30e7d145dcce
|
Ruby
|
pratikmshah/phase-0
|
/week-6/guessing-game/my_solution.rb
|
UTF-8
| 3,150 | 4.25 | 4 |
[
"MIT"
] |
permissive
|
# Build a simple guessing game
# I worked on this challenge [by myself, with: ].
# I spent [#] hours on this challenge.
# Pseudocode
# Input: a guess on the ranomly generated number
# Output: 3 cases guess is high, low, or correct
# Steps:
# step1: Initialize game with random integer
# step2: create METHOD and check user guess to see if it is too high, low or correct
# step3: create METHOD solved? to return true or false based on the last guess
Initial Solution
class GuessingGame
def initialize(answer)
@answer = answer
end
attr_accessor :high, :low, :correct, :guess
def guess(guess)
@guess = guess
if(guess > @answer)
@high = guess
p :high
elsif(guess < @answer)
@low = guess
p :low
else
@correct = guess
p :correct
end
end
def solved?
if(@answer == @guess)
p true
else
p false
end
end
end
# ---Refactored Solution---
class GuessingGame
def initialize(answer)
@answer = answer
end
def guess(guess)
@guess = guess
if(guess > @answer)
p :high
elsif(guess < @answer)
p :low
else
p :correct
end
end
def solved?
@solve = true if(@answer == @guess)
end
end
# Tests
game = GuessingGame.new(15)
while !game.solved?
print "Enter a number between 1-15: "
answer = gets.chomp.to_i
game.guess(answer)
game.solved?
end
# Reflection
=begin
How do instance variables and methods represent the characteristics and behaviors (actions) of a real-world object?
- instant variables represent and methods represent the behaviors of a real world object becuase you can think of
variables as storing the attriubtes of the object while the methods being the actions of and object. For instance
take human body we have eyes, ears, nose, mouth etc... examples of variables would be eyes color and method would
be to see, to eat, smell, hear etc...
When should you use instance variables? What do they do for you?
- Instance variables are good for tracking data within a class that objects that are apart of that class can
access without first having to define them. The instance variables do not lose scope outside of the class as long
as you have an object that can call on them.
Explain how to use flow control. Did you have any trouble using it in this challenge? If so, what did you struggle with?
- flow control is implemented by using if else statements and loops to guide the ruby interpreter on what to do when
in different scenarios. I only had one issue and it was on how to transfer the user input to the solved? method but I
found out you could create an instance variable inside of a method and it is still accessable outside.
Why do you think this code requires you to return symbols? What are the benefits of using symbols?
- Symbols allow you to represet names and strings all in one which makes it more memory efficient.
For example when you create a hash ruby has to create a new string object in a different memory location vs
when you use a symbol which gets created once stored in memory and reusable multiple times over serveral instances.
=end
| true |
4e0398a7e9d9663ae6c822b2e82f02c0353a5c1a
|
Ruby
|
CodeMonkeySteve/fast_xor
|
/benchmark
|
UTF-8
| 515 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
$: << File.dirname(__FILE__)+'/lib'
require 'benchmark'
require 'xor'
class String
def slow_xor!(other)
s = ''
other.each_byte.with_index { |b, i| s << (self[i].ord ^ b).chr }
replace(s)
end
require 'xor'
alias_method :fast_xor!, :xor!
end
a = ([255].pack('C')) * (2**17) # 128k
b = a.dup
n = (ARGV.first || 100).to_i
Benchmark.bm do |x|
x.report('Ruby :') do n.times { a.slow_xor! b } end
x.report('C (x1000):') do (n*1000).times { a.fast_xor! b } end
end
| true |
d35e8437116e5b323592e0a538a7e619ff15225a
|
Ruby
|
marloncarvalho/hackerrank
|
/two_characters.rb
|
UTF-8
| 697 | 3.53125 | 4 |
[] |
no_license
|
def solution(s)
r = 0
a = s.split ''
u = a.uniq
return 0 if s.length == 1 || u.length == 1
return 2 if u.length == 2
# Vamos fazer todas as combinações possíveis de dois caracteres e manter esses
# dois caracteres, apagando os demais. Aí checamos se a string resultante
# segue a regra do exercício.
u.combination(2).each do |comb|
t = (a - (a - comb))
joined = t.join
# Não podemos ter dois caracteres iguais juntos.
if !joined.include?("#{comb[0]}#{comb[0]}") && !joined.include?("#{comb[1]}#{comb[1]}")
r = t.length if t.length > r
end
end
r
end
puts solution('beabeefeab')
puts solution('a')
puts solution('ab')
puts solution('abc')
| true |
231dd0d170392161b88aabd54187f7647019d22d
|
Ruby
|
L-Y/ruby_file
|
/socket-server.rb
|
UTF-8
| 343 | 2.625 | 3 |
[] |
no_license
|
#_*_ coding:UTF-8 _*_
require "socket"
port=2000
s = TCPServer.open(port)
=begin
loop {
client =s.accept
client.puts(Time.now.ctime)
client.puts "closing the connection,bye!"
client.close
}
=end
loop{
Thread.start(s.accept) do |client|
client.puts(Time.now.ctime)
client.puts "closing the connection.Bye!"
client.close
end
}
| true |
258c495674eae06ef6fce691fec41a2eb660cfa0
|
Ruby
|
rossenhansen/Ruby
|
/087-8_Ways_to_create_Arrays.rb
|
UTF-8
| 463 | 3.9375 | 4 |
[] |
no_license
|
names = %w[Jack Jill John James] #Doesn't require quotes or delimiters but can't accept two word names
p names #=> ["Jack", "Jill", "John", "James"]
p Array.new(5) #=> [nil, nil, nil, nil, nil]
p Array.new(10, "Hello") #=> ["Hello", "Hello", "Hello", "Hello", "Hello", "Hello", "Hello", "Hello", "Hello", "Hello"]
p Array.new(3, [1, 2, 3]) #=> [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
p Array.new(3, Array.new(3)) #=> [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
| true |
dd6c4690a70f1304d97f9abddaaddb5f5617da63
|
Ruby
|
rubidine/rbiz
|
/test/unit/customer_test.rb
|
UTF-8
| 1,041 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
context 'A new customer' do
setup do
Customer.delete_all
CartLib.activate_test_stubs
@customer = Customer.new(
:email => 'testie@localhost',
:passphrase => 'testie00'
)
end
specify 'should have a hashed passphrase' do
assert_not_equal 'testie00', @customer.passphrase
assert @customer.passphrase_eql?('testie00')
end
end
context 'The Customer class' do
setup do
Customer.delete_all
CartLib.activate_test_stubs
end
specify 'should generate random passphrases' do
all = []
90.times do
all << Customer.generate_random_passphrase
assert_match /^[a-zA-Z0-9_\-]{10,15}$/, all.last
end
# doesn't have to be true, but in reality is likely to
assert_equal 90, all.uniq.length, "Non unique passphrases (not fatal)"
end
specify 'should not let the super_user attribute be set on creation' do
c = Customer.new(:super_user => true)
assert !c.super_user?
c.super_user = true
assert c.super_user?
end
end
| true |
d94e13974efe411fe28227eed511579d7676776a
|
Ruby
|
gmitrev/inactive_support
|
/spec/lib/hash_spec.rb
|
UTF-8
| 2,790 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
# encoding: utf-8
require 'spec_helper'
require 'inactive_support/hash/delete_blank'
require 'inactive_support/hash/deep_delete_blank'
describe Hash do
describe '#delete_blank' do
it 'deletes nils' do
initial = {
id: 1,
name: nil
}
expected = {
id: 1
}
expect(initial.delete_blank).to eq expected
end
it 'deletes empty strings' do
initial = {
id: 1,
name: ''
}
expected = {
id: 1
}
expect(initial.delete_blank).to eq expected
end
it 'preserves false values' do
initial = {
id: 1,
name: false
}
expected = {
id: 1,
name: false
}
expect(initial.delete_blank).to eq expected
end
it 'deletes empty arrays' do
initial = {
id: 1,
name: []
}
expected = {
id: 1
}
expect(initial.delete_blank).to eq expected
end
it 'deletes empty hashes' do
initial = {
id: 1,
name: {}
}
expected = {
id: 1
}
expect(initial.delete_blank).to eq expected
end
end
describe '#deep_delete_blank' do
it 'deletes nils' do
initial = {
id: 1,
name: {
first: nil,
middle: 'Peter'
}
}
expected = {
id: 1,
name: {
middle: 'Peter'
}
}
expect(initial.deep_delete_blank).to eq expected
end
it 'deletes empty strings' do
initial = {
id: 1,
name: {
first: '',
middle: 'Peter'
}
}
expected = {
id: 1,
name: {
middle: 'Peter'
}
}
expect(initial.deep_delete_blank).to eq expected
end
it 'preserves false values' do
initial = {
id: 1,
name: {
first: false,
middle: 'Peter'
}
}
expected = {
id: 1,
name: {
first: false,
middle: 'Peter'
}
}
expect(initial.deep_delete_blank).to eq expected
end
it 'deletes empty arrays' do
initial = {
id: 1,
name: {
addresses: [],
middle: 'Peter'
}
}
expected = {
id: 1,
name: {
middle: 'Peter'
}
}
expect(initial.deep_delete_blank).to eq expected
end
it 'deletes empty hashes' do
initial = {
id: 1,
name: {
children: {},
middle: 'Peter'
}
}
expected = {
id: 1,
name: {
middle: 'Peter'
}
}
expect(initial.deep_delete_blank).to eq expected
end
end
end
| true |
77ac9efaad98f2bef642e8f543879d9c5d8f258b
|
Ruby
|
devscrapper/statupweb
|
/test/hashdomain.rb
|
UTF-8
| 562 | 2.78125 | 3 |
[] |
no_license
|
#function hash(d){
# var a=1,c=0,h,o;
# if(d){
# a=0;
# for(h=d["length"]-1;h>=0;h--){
# o=d.charCodeAt(h);
# a=(a<<6&268435455)+o+(o<<14);
# c=a&266338304;
# a=c!=0?a^c>>21:a
# }
# }
# return a
#}
def hashdomain(d)
a = 0
c = 0
d.split(//).reverse_each{|h|
o = h.ord
a=(a<<6&268435455)+o+(o<<14);
c=a&266338304;
a=c!=0?a^c>>21:a
}
a
end
a = "a"
p a.ord
p hashdomain("w3schools.com")
| true |
267ce327cfdbf2fc5a7dbae0e9107edd5f08496b
|
Ruby
|
kunjut/notepad
|
/notepad.rb
|
UTF-8
| 603 | 3.09375 | 3 |
[] |
no_license
|
require_relative 'post'
require_relative 'link'
require_relative 'memo'
require_relative 'task'
puts 'Привет, я твой блокнот!',
'Что хотите записать в блокнот?'
choices = Post.post_types
choice = nil
until (1..3).include?(choice)
# until choice > 0 && choice <= choices.size
puts "\nВыберите цифру соответствующую типу записи:"
choices.each_with_index do |type, index|
puts "\t#{index + 1}: #{type}"
end
choice = STDIN.gets.to_i
end
entry = Post.create(choice - 1)
entry.read_from_console
entry.save
| true |
4b4c1ed1b3974855c46e5d9c38fb46fa1682818e
|
Ruby
|
doboy/euler
|
/ruby/p058.rb
|
UTF-8
| 412 | 3.53125 | 4 |
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
require 'prime'
def spiral_gen
end
def spiral_primes(under)
prime_count = 0
total_count = 0
i = 1
inc = 2
while true
1.upto(4) do
i += inc
sprial_num = i
if Prime.prime? sprial_num
prime_count += 1
end
total_count += 1
if prime_count / total_count.to_f < under
return inc - 1
end
end
inc += 2
end
end
puts spiral_primes 0.1
| true |
c3e80cd7b5c2ab8329c4abb370250ca9fc0e4639
|
Ruby
|
xristocodos/compressiondemo
|
/compress.rb
|
UTF-8
| 2,130 | 3.828125 | 4 |
[] |
no_license
|
# compress text files
def compress
puts "Please enter the filename of text to compress?"
filename = gets.chomp
text = File.open(filename, "r"){|file| file.read}
text_stripped = text.gsub("\n", " ").gsub(",", "").gsub(".", "").gsub("...", "").gsub("!","")
puts "\n"
puts "Please enter compression factor (cipher key quantity):"
factor = gets.chomp
factor = factor.to_i
puts "\n"
puts "[1] for LOSSLESS, [2] for LOSSY"
lossy = gets.chomp.to_i
lossy -= 1 # boolean for lossy [0] = lossless, [1] = lossy
lyrical_array = text_stripped.split(" ")
lyrical_db = {}
# iterate over array, store each unique word into hash
lyrical_array.each do |word|
if lyrical_db.keys.include?(word)
lyrical_db[word] += 1
else
lyrical_db[word] = 1
end
end
# translation time!
translation_hash = {}
freq_array = []
freq_array = lyrical_db.values.sort.reverse
lyrical_db.each do |word, count|
if count >= freq_array[factor]
if lossy == 1
translation_hash[word] = word[0]
elsif lossy == 0
translation_hash[word] = "%" + word[0]
end
end
end
puts "\n"
puts "translation_hash"
puts translation_hash
text_compressed = text
translation_hash.each do | key, value |
text_compressed = text_compressed.gsub(key, value)
end
puts "///////////COMPRESSED TEXT///////////"
puts text_compressed
puts "////////COMPRESSED TEXT END//////////"
text_decompressed = text_compressed
translation_hash.each do | key, value |
text_decompressed = text_decompressed.gsub(value, key)
end
puts "\n"
puts "///////////DECOMPRESSED TEXT///////////"
puts text_decompressed
puts "////////DECOMPRESSED TEXT END//////////"
puts "\n\n\n"
puts "//////////STATS///////////"
if lossy == 1
puts "Mode: \t\tLOSSY"
elsif lossy == 0
puts "Mode: \t\tLOSSLESS"
end
puts "ORIGINAL:\t\t#{text.length} chars/bytes"
puts "FACTOR: \t#{factor}"
puts "COMPRESSED: \t#{text_compressed.length} chars/bytes"
puts "UNCOMPRESSED:\t#{text_decompressed.length} chars/bytes"
#puts lyrical_array
end
compress
# end
| true |
a77d9899ef567742faee8739b0bd08395d8838b5
|
Ruby
|
Tan2Pi/rlox
|
/src/stmt.rb
|
UTF-8
| 1,969 | 2.875 | 3 |
[] |
no_license
|
class Stmt
class Visitor
def visit_expression_statement(stmt);end
def visit_print_statement(stmt);end
def visit_var_statement(stmt);end
def visit_block_statement(stmt);end
def visit_if_statement(stmt);end
def visit_while_statement(stmt);end
def visit_break_statement(stmt);end
def visit_class_statement(stmt);end
def visit_function_statement(stmt);end
def visit_return_statement(stmt);end
end
@@names = {
'Expression' => [:expression],
'Print' => [:expression],
'Var' => [:name, :initializer],
'Block' => [:statements],
'If' => [:condition, :then_branch, :else_branch],
'While' => [:condition, :body],
'Break' => [:break],
'Function' => [:name, :function],
'Return' => [:keyword, :value]
}
Block = Struct.new(*@@names['Block']) do
def accept(visitor)
visitor.visit_block_statement(self)
end
end
Break = Struct.new(*@@names['Break']) do
def accept(visitor)
visitor.visit_break_statement(self)
end
end
Expression = Struct.new(*@@names['Expression']) do
def accept(visitor)
visitor.visit_expression_statement(self)
end
end
Function = Struct.new(*@@names['Function']) do
def accept(visitor)
visitor.visit_function_statement(self)
end
end
If = Struct.new(*@@names['If']) do
def accept(visitor)
visitor.visit_if_statement(self)
end
end
Print = Struct.new(*@@names['Print']) do
def accept(visitor)
visitor.visit_print_statement(self)
end
end
Return = Struct.new(*@@names['Return']) do
def accept(visitor)
visitor.visit_return_statement(self)
end
end
Var = Struct.new(*@@names['Var']) do
def accept(visitor)
visitor.visit_var_statement(self)
end
end
While = Struct.new(*@@names['While']) do
def accept(visitor)
visitor.visit_while_statement(self)
end
end
end
| true |
9a8a05aa0fc82c8602272ff14e42973a37de6111
|
Ruby
|
koenhandekyn/rails-whist-stimulus
|
/app/models/round.rb
|
UTF-8
| 1,994 | 2.90625 | 3 |
[] |
no_license
|
# == Schema Information
#
# Table name: rounds
#
# id :bigint(8) not null, primary key
# game_id :uuid
# score1 :integer
# score2 :integer
# score3 :integer
# score4 :integer
# roundtype :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Round < ApplicationRecord
belongs_to :game
validate :correct_score
before_save :derive
def correct_score
case scores.compact.count
when 1
errors.add :base, "single score should be divisible by 3" if scores.compact.first % 3 != 0
when 2
errors.add :base, "two scores should be equal" if scores.compact.first != scores.compact.second
when 4
errors.add :base, "scores should sum up to 0" if scores.compact.sum != 0
errors.add :base, "there cannot be more than 2 different score valeus" if scores.uniq.count > 2
end
end
def derive
if valid?
case scores.compact.count
when 1
score = -max_score/3
self.score1 = score if score1.blank?
self.score2 = score if score2.blank?
self.score3 = score if score3.blank?
self.score4 = score if score4.blank?
when 2
score = -max_score
self.score1 = score if score1.blank?
self.score2 = score if score2.blank?
self.score3 = score if score3.blank?
self.score4 = score if score4.blank?
when 3
score = -max_score*3
self.score1 = score if score1.blank?
self.score2 = score if score2.blank?
self.score3 = score if score3.blank?
self.score4 = score if score4.blank?
end
end
self
end
def score_sign1
score1 >= 0 ? 'pos' : 'neg'
end
def score_sign2
score2 >= 0 ? 'pos' : 'neg'
end
def score_sign3
score3 >= 0 ? 'pos' : 'neg'
end
def score_sign4
score4 >= 0 ? 'pos' : 'neg'
end
def scores
[score1, score2, score3, score4]
end
def max_score
scores.compact.max
end
end
| true |
e73ac4170d7212bce0c6703d4baf012497593d14
|
Ruby
|
luqiuyuan/reactjs_course_backend
|
/test/test_helper.rb
|
UTF-8
| 4,419 | 2.765625 | 3 |
[] |
no_license
|
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
def json_response
ActiveSupport::JSON.decode @response.body
end
# Check if expected is included in actual
# If they contains array, the array is handled in unordered way
#
# @param [Hash] expected
# @param [Model] actual
# @return [Boolean]
#
# Comment
# The argument expected must be assigned to a variable first, otherwise it might be recognized as a block (Maybe)
# Right way:
# expected = {id:1, name:"abc"}
# hash_equal expected, actual_model
# or
# hash_equal({id:1, name:"abc"}, actual_model)
# Wrong way:
# hash_equal {id:1, name:"abc"}, actual_model
def hash_included_unordered(expected, actual)
expected.each do |key, value|
if expected[key].class == Hash and actual[key.to_s].class == Hash
if !hash_included_unordered expected[key], actual[key.to_s]
return false
end
elsif expected[key].class == Array and actual[key.to_s].class == Array
if !hash_included_array_unordered expected[key], actual[key.to_s]
return false
end
else
if expected[key] != actual[key.to_s]
return false
end
end
end
return true
end
# Check if all elements in expected are included in actual
#
# @param [Array] expected
# @param [Array] actual
# @return [Boolean]
def hash_included_array_unordered(expected, actual)
# the two array must be consistent in size
if expected.size != actual.size
return false
end
expected.each do |item|
found = false # indicates if the item is found
if item.class == Hash
for i in 0...actual.size
if hash_included_unordered item, actual[i] # equal remaining to true indicates that the item has been found, break and test next item
found = true
break
end
end
else
if actual.include? item
found = true
end
end
if !found # if any item is not found, return false
return false
end
end
return true # every thing is fine...
end
# Check if expected is included in actual
# If they contains array, the array is handled in ordered way
#
# @param [Hash] expected
# @param [Model] actual
# @return [Boolean]
#
# Comment
# The argument expected must be assigned to a variable first, otherwise it might be recognized as a block (Maybe)
# Right way:
# expected = {id:1, name:"abc"}
# hash_equal expected, actual_model
# or
# hash_equal({id:1, name:"abc"}, actual_model)
# Wrong way:
# hash_equal {id:1, name:"abc"}, actual_model
def hash_included_ordered(expected, actual)
expected.each do |key, value|
if expected[key].class == Hash and actual[key.to_s].class == Hash
if !hash_included_ordered expected[key], actual[key.to_s]
return false
end
elsif expected[key].class == Array and actual[key.to_s].class == Array
if !hash_included_array_ordered expected[key], actual[key.to_s]
return false
end
else
if expected[key] != actual[key.to_s]
return false
end
end
end
return true
end
# Check if all elements in expected are included in actual in ordered way
#
# @param [Array] expected
# @param [Array] actual
# @return [Boolean]
def hash_included_array_ordered(expected, actual)
# the two array must be consistent in size
if expected.size != actual.size
return false
end
for i in 0...expected.size
if expected[i].class == Hash # Use hash_included_ordered if item is Hash, != otherwise
if !hash_included_ordered expected[i], actual[i]
return false
end
else
if expected[i] != actual[i]
return false
end
end
end
return true # every thing is fine...
end
def login_as(user_symbol)
# Setup user token
user = users(user_symbol)
user_token = UserToken.new(user)
user_token.save
return { Authorization: '{"user_token":{"user_id":"' + user.id.to_s + '", "key":"' + user_token.key + '"}}' }
end
end
| true |
0431803f4cd2ab5317cd045c6b7b09514b46eb93
|
Ruby
|
GrahamMThomas/SudokuSolver
|
/sudoku_test.rb
|
UTF-8
| 3,973 | 3.015625 | 3 |
[] |
no_license
|
require 'minitest/autorun'
require_relative 'sudoku_class'
require_relative 'sudoku_utils'
class SudokuTest < Minitest::Test
@@puzzle = Sudoku.zero(9)
@@puzzle.load_matrix_from_file('Puzzles/SudokuDefault.txt')
@@hard_puzzle = Sudoku.zero(9)
@@hard_puzzle.load_matrix_from_file('Puzzles/SudokuHard1.txt')
def test_available_numbers_in_row_or_col_valid_col_success
method_output = @@puzzle.available_numbers_in_row_or_col { |i, arr| arr.push(@@puzzle[0, i].to_s) }
method_expected = ['3','4','5','8','9']
assert (method_output == method_expected),
"Did not return expected numbers.\nExpected:#{method_expected}\nGot:#{method_output}"
end
def test_available_numbers_in_row_or_col_valid_row_success
method_output = @@puzzle.available_numbers_in_row_or_col { |i,arr| arr.push(@@puzzle[i, 0].to_s) }
method_expected = ['2','3','4','5','9']
assert (method_output == method_expected),
"Did not return expected numbers.\nExpected:#{method_expected}\nGot:#{method_output}"
end
def test_available_numbers_in_box_valid_success
method_output = @@puzzle.available_numbers_in_box(0, 0)
method_expected = ['2','3','4','5','7']
assert (method_output == method_expected),
"Did not return expected numbers.\nExpected:#{method_expected}\nGot:#{method_output}"
end
def test_calculate_possible_numbers_for_square_valid_success
method_output = @@puzzle.calculate_possible_numbers_for_square(0, 0)
method_expected = ['3','4','5']
assert (method_output == method_expected),
"Did not return expected numbers.\nExpected:#{method_expected}\nGot:#{method_output}"
end
def test_check_row_availability_for_square_valid_success
@@hard_puzzle.calculate_possible_numbers_for_square(0,8)
method_output = @@hard_puzzle.check_row_availability_for_square(0, 8)
method_expected = ['3']
assert (method_output == method_expected) ,
"Did not return expected numbers.\nExpected:#{method_expected}\nGot:#{method_output}"
end
def test_check_col_availability_for_square_valid_success
@@hard_puzzle.calculate_possible_numbers_for_square(0,8)
method_output = @@hard_puzzle.check_col_availability_for_square(0, 8)
method_expected = ['3']
assert (method_output == method_expected),
"Did not return expected numbers.\nExpected:#{method_expected}\nGot:#{method_output}"
end
def test_check_box_availability_for_square_valid_success
@@hard_puzzle.calculate_possible_numbers_for_square(0, 8)
method_output = @@hard_puzzle.check_box_availability_for_square(0, 8)
method_expected = ['3']
assert (method_output == method_expected),
"Did not return expected numbers.\nExpected:#{method_expected}\nGot:#{method_output}"
end
def test_check_availability_for_square_valid_success
@@hard_puzzle.calculate_possible_numbers_for_square(0, 8)
method_output = @@hard_puzzle.check_availability_for_square(0, 8)
method_expected = ['3']
assert (method_output == method_expected),
"Did not return expected numbers.\nExpected:#{method_expected}\nGot:#{method_output}"
end
def test_insert_number_into_blank_valid_success
default_puzzle = Sudoku.zero(9).load_matrix_from_file('Puzzles/SudokuDefault.txt')
default_puzzle.insert_number_into_blank(0, 0, 0)
method_expected = 0
assert (default_puzzle[0,0] == method_expected),
"Did not return expected numbers.\nExpected:#{method_expected}\nGot:#{default_puzzle[0,0]}"
end
def test_insert_number_into_each_blank_valid_success
default_puzzle = Sudoku.zero(9).load_matrix_from_file('Puzzles/SudokuDefault.txt')
default_puzzle.calculate_possible_numbers_for_each_square
default_puzzle.insert_number_into_each_blank
method_expected = '3'
assert (default_puzzle[0,1] == method_expected),
"Did not return expected numbers.\nExpected:#{method_expected}\nGot:#{default_puzzle[0,1]}"
end
end
| true |
4e634ddf75ff86c53f126005ece37c82c2826bc4
|
Ruby
|
omaroaburto/Curso-ruby
|
/15-clases/clases.rb
|
UTF-8
| 275 | 3.09375 | 3 |
[] |
no_license
|
class Persona
attr_accessor :nombre, :edad
def aumentar_edad()
end
def definir_ciudad_nacimiento(a)
end
end
persona1 = Persona.new
persona2 = Persona.new
persona1.nombre = "juan"
persona2.nombre = "pedro"
puts persona1.nombre
puts persona2.nombre
| true |
90b1b4c13a33548f3bc7e4e53bfbb377eaa035e8
|
Ruby
|
nougu/Pitchfork
|
/lib/pf/cli/build.rb
|
UTF-8
| 1,000 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
require 'thor'
module Pf
class CLI < Thor
desc "build [OPTIONS] (-|PATH)", "Build device stack from the YAML file"
option :"dry-run", :type => :boolean, :default => false, :desc => "Try to build device stack"
def build(file)
Pf.context(file, options) {
if opts[:"dry-run"]
puts "-> Execute (dry-run): Build a stack"
else
puts "-> Execute: Build a stack"
end
stack.map {|param|
assemble(param)
}.each {|dev, param|
if dev.exists?
puts "---> Skip device: #{param['Path']}"
elsif opts[:"dry-run"]
puts "---> Push device (dry-run): #{param['Path']}"
else
puts "---> Push device: #{param['Path']}"
dev.create
end
}
if opts[:"dry-run"]
puts "-> Complete (dry-run): Stack would be built"
else
puts "-> Complete: Stack is built"
end
output
}
end
end
end
| true |
3e940d63a85d1d27aa18972322b5c3308672a922
|
Ruby
|
calebhearth/passivesupport
|
/spec/core_ext/hash/leaves_spec.rb
|
UTF-8
| 865 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
require 'spec_helper'
require 'passive_support/core_ext/hash/leaves'
describe Hash do
describe "#leaves" do
it "returns an array containing a single value for a simple Hash" do
subject = { this: :that }
subject.leaves.should eq([:that])
end
it "returns all of the values when there are more than one" do
subject = { this: [:that, :the_other] }
subject.leaves.should eq([:that, :the_other])
end
it "finds the endpoint of a chain" do
subject = { I: { am: { a: :leaf } } }
subject.leaves.should eq([:leaf])
end
it "handles multiple keys" do
subject = {
beverages: { caffinated: [:coffee, :tea] },
vehicles: [:car, :truck, :airplane],
dessert: :ice_cream,
}
subject.leaves.should == [:coffee, :tea, :car, :truck, :airplane, :ice_cream]
end
end
end
| true |
e073d53e540c53993a98593fa82dae9d1b7fc7a9
|
Ruby
|
pythonandchips/being-dynamic-in-ruby
|
/1_methods_return_value.rb
|
UTF-8
| 636 | 3.859375 | 4 |
[] |
no_license
|
class Zombie
def kill_human
return "I just want a hug"
end
def eat_human
"hmmm, tastes of chicken"
end
def infect_human hungry
if hungry
"Please welcome David Heinemeier Hansson"
end
end
end
zombie = Zombie.new
puts("kill human")
puts(zombie.kill_human)
puts("-------------------------------------------------")
#puts("eat human")
#puts(zombie.eat_human)
#puts("-------------------------------------------------")
#puts("infect_human when not hungry")
#puts(zombie.infect_human(false))
#puts("-------------------------------------------------")
#puts("infect_human when hungry")
#puts(zombie.infect_human(true))
| true |
c3eb98d754da0059f512d2e27b1b13f5f1ca454c
|
Ruby
|
alma-frankenstein/anagramsAndAntigrams
|
/ruby_script.rb
|
UTF-8
| 403 | 3.46875 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require ('./lib/anagramChecker')
puts "Let's check for anagrams! Please enter a word"
word1 = gets.chomp
puts "Enter another word to compare"
word2 = gets.chomp
anaCheck = AnagramChecker.new(word1, word2)
puts " *************** "
puts anaCheck.all_together()
if anaCheck.all_together() == "not anagrams"
puts " *************** "
puts anaCheck.antigram_check()
end
| true |
eef1a3b9d80f7d37264e01fdfbb886f13b7533f5
|
Ruby
|
gPrado/mc747-portal
|
/app/models/address.rb
|
UTF-8
| 959 | 2.796875 | 3 |
[] |
no_license
|
class Address
attr_accessor :cep, :logradouro, :bairro, :localidade, :uf, :numero, :complemento
def initialize(params)
@cep = params[:cep]
@logradouro = params[:logradouro]
@bairro = params[:bairro]
@localidade = params[:localidade]
@uf = params[:uf]
@numero = params[:numero]
@complemento = params[:complemento]
end
def to_s
"#<Address @cep=#{cep} @logradouro=#{logradouro} @bairro=#{bairro} @localidade=#{localidade}> @uf=#{uf} @numero=#{numero} @complemento=#{complemento}"
end
class << self
def from_user(user_id)
user = UserFactory.instance.find(user_id)
begin
AddressFactory.instance.cep_address(user.cep)
rescue Exception => e
Rails.logger.info e
Address.new(:cep => user.cep)
end.tap do |a|
a.numero = user.numero_endereco
a.complemento = user.complemento_endereco
end
end
end
end
| true |
5de059e3183e23be70976a5e4510b32744d41e66
|
Ruby
|
holywyvern/carbuncle
|
/gems/carbuncle-math/mrblib/matrix.rb
|
UTF-8
| 2,660 | 3.34375 | 3 |
[
"Apache-2.0"
] |
permissive
|
module Carbuncle
module Vectorizable; end
# A matrix is a table of numbers, in a 4x4 grid.
# Useful for doing some mathematical operations.
class Matrix
include Enumerable
# A line is a row or column of a matrix.
class Line
include Carbuncle::Vectorizable
attr_reader :matrix
def initialize(matrix, index, vertical)
@matrix = matrix
@index = index
@indexes =
Array.new(4) do |v|
vertical ? [index, v] : [v, index]
end
end
def [](index)
i, j = @indexes[index]
matrix[i, j]
end
def []=(index, value)
i, j = @indexes[index]
matrix[i, j] = value
end
def to_a
@indexes.map do |indexes|
i, j = indexes
matrix[i, j]
end
end
def inspect
"#{self.class.name}[#{@index}](#{to_a.join(', ')})"
end
def size
4
end
end
# Represents a row in the matrix.
class Row < Carbuncle::Matrix::Line
def initialize(matrix, i)
super(matrix, i, false)
end
end
# Represents a column in the matrix.
class Column < Carbuncle::Matrix::Line
def initialize(matrix, j)
super(matrix, j, true)
end
end
# @!method initialize
# Creates a new matrix, the values are the values of an Identity matrix.
# @return [self]
# @overload initialize(matrix)
# Creates a new matrix, with the same values as the one given.
# @param [Matrix] matrix The matrix to copy.
# @return [self]
# @!method initialize_copy(matrix)
# Creates a new matrix, with the same values as the one given.
# @param [Matrix] matrix The matrix to copy.
# @return [self]
def each(&block)
rows.map(&:to_a).flatten.each(&block)
end
def rows
@rows ||= [
Carbuncle::Matrix::Row.new(self, 0),
Carbuncle::Matrix::Row.new(self, 1),
Carbuncle::Matrix::Row.new(self, 2),
Carbuncle::Matrix::Row.new(self, 3)
]
end
def columns
@columns ||= [
Carbuncle::Matrix::Column.new(self, 0),
Carbuncle::Matrix::Column.new(self, 1),
Carbuncle::Matrix::Column.new(self, 2),
Carbuncle::Matrix::Column.new(self, 3)
]
end
def to_s
inspect
end
def inspect
result = <<-HEREDOC
Matrix:
#{rows[0].to_a.join(', ')},
#{rows[1].to_a.join(', ')},
#{rows[2].to_a.join(', ')},
#{rows[3].to_a.join(', ')},
HEREDOC
result.strip_heredoc
end
def size
16
end
end
end
| true |
cd429210d335cd1057dd379c4e7559b2e1f06d0c
|
Ruby
|
ttuffy/docker_design_pattern
|
/app/models/observer/other.rb
|
UTF-8
| 883 | 2.796875 | 3 |
[] |
no_license
|
class EmployeeObserver < ActiveRecord::Observer
def after_create(employee)
# 新しいemployeeレコードが生成されました。
end
def after_update(employee)
# employeeレコードが更新されました。
end
def after_destroy(employee)
# employeeレコードが削除されました。
end
end
###############################################################################
require 'rexml/parsers/sax2parser'
require 'rexml/sax2listener'
#
# 独自のXMLパーサを作成
#
xml = File.read('data.xml')
parser = REXML::Parsers::SAX2Parser.new(xml)
#
# 要素の開始と終了の通知を受けるオブザーバを追加
#
parser.listen(:start_element) do |uri, local, qname, attrs|
puts("start element: #{local}")
end
parser.listen(:end_element) do |uri, local, qname|
puts("end element #{local}")
end
#
# XMLを解析
#
parser.parse
| true |
b56b0d1bb09540b2ad3ebe7f42cb71d65559e15c
|
Ruby
|
Tmgree/Boris_Bikes_Challenge
|
/spec/docking_station_spec.rb
|
UTF-8
| 6,692 | 3.03125 | 3 |
[] |
no_license
|
require 'docking_station'
describe DockingStation do
describe '#release_bike' do
it 'responds to release_bike' do
expect(subject).to respond_to :release_bike
end
it 'must release a bike' do
bike=double(:bike, broken: false)
subject.dock(bike)
expect(subject.release_bike).to eq bike
end
it 'raises an error when there are no bikes available' do
expect { subject.release_bike }.to raise_error 'No bikes available'
end
it 'must not release a broken bike' do
bike=double(:bike, broken: true)
subject.dock(bike)
expect{subject.release_bike}.to raise_error 'No bikes available'
end
end
describe '#dock' do
it { is_expected.to respond_to(:dock).with(1).argument }
it 'can dock a bike' do
bike=double(:bike, broken: false)
expect(subject.dock(bike)).to eq [bike]
end
it 'allows the user to set their own capacity' do
station = DockingStation.new(50)
50.times { station.dock(bike=double(:bike, broken: false)) }
expect{ station.dock(Bike.new) }.to raise_error 'Docking Station is Full'
end
it 'must accept a returning working bike' do
bike=double(:bike, broken: false)
subject.dock(bike)
subject.release_bike
expect(subject.dock(bike)).to eq [bike]
end
end
describe '#full?' do
it 'should identify when the dock is full' do
station=DockingStation.new(1)
bike=double(:bike, broken: false)
station.dock(bike)
expect(station.full?).to eq(true)
end
end
describe '#empty?' do
it 'should identify when the dock is empty' do
station=DockingStation.new
expect(station.empty?).to eq(true)
end
end
describe '#dock_size' do
it 'Must display the number of bikes stored in a docking station' do
station = DockingStation.new(28)
25.times { station.dock(bike=double(:bike, broken: false)) }
expect( station.dock_size ).to eq(25)
end
end
describe 'no_working_bikes?' do
it 'must identify that there are no working bikes docked' do
bike=double(:bike, broken: true)
subject.dock(bike)
expect(subject.no_working_bikes?).to eq(true)
end
end
describe '#working_bikes' do
it { is_expected.to respond_to(:working_bikes) }
it 'must count number of working bikes stored in docking station' do
18.times { subject.dock(bike=double(:bike, broken: false)) }
expect(subject.working_bikes).to eq(18)
end
it 'must add 1 to working bikes if a working bike is docked' do
bike=double(:bike, broken: false)
subject.dock(bike)
expect(subject.working_bikes).to eq(1)
end
it 'must remove 1 to working bikes if a working bike is removed' do
bike=double(:bike, broken: false)
subject.dock(bike)
subject.release_bike
expect(subject.working_bikes).to eq(0)
end
end
describe '#broken_bikes' do
it { is_expected.to respond_to(:broken_bikes) }
it 'must count number of broken bikes stored in docking station' do
18.times { subject.dock(bike=double(:bike, broken: false)) }
expect(subject.broken_bikes).to eq(0)
end
it 'must add 1 to broken bikes if a broken bike is docked' do
bike=double(:bike, broken: true)
subject.dock(bike)
expect(subject.broken_bikes).to eq(1)
end
end
describe '#bikes' do
it { is_expected.to respond_to(:bikes) }
it 'returns a docked bike' do
bike=double(:bike, broken: false)
subject.dock(bike)
expect(subject.bikes[0]).to eq bike
end
it 'should take not list a removed bike' do
bike=double(:bike, broken: false)
subject.dock(bike)
subject.release_bike
expect(subject.bikes).not_to include bike
end
end
describe '#capacity' do
it { is_expected.to respond_to(:capacity) }
it 'has a default capacity' do
expect( subject.capacity ).to eq DockingStation::DEFAULT_CAPACITY
end
it 'can change the default capacity' do
station=DockingStation.new(5)
expect(station.capacity).to eq(5)
end
end
describe '#working_bikes_array' do
it { is_expected.to respond_to(:working_bikes_array) }
it 'must store all working bikes docked in the station as a sub arry' do
bike=double(:bike, broken: false)
subject.dock(bike)
expect(subject.working_bikes_array).to include(bike)
end
it 'must remove a bike if the bike is released from the docking station' do
bike=double(:bike, broken: false)
subject.dock(bike)
subject.release_bike
expect(subject.working_bikes_array).not_to include bike
end
end
describe '#broken_bikes_array' do
it { is_expected.to respond_to(:broken_bikes_array) }
it 'must store all working bikes docked in the station as a sub arry' do
bike=double(:bike, broken: true)
subject.dock(bike)
expect(subject.broken_bikes_array).to include(bike)
end
end
describe '#total' do
it { is_expected.to respond_to(:total) }
it 'must count total number of bikes stored in docking station' do
bike1=double(:bike, broken: false)
bike2 = double(:bike, broken: true)
subject.dock(bike1)
subject.dock(bike2)
expect(subject.total).to eq(2)
end
it 'must subtract a bike if a bike is released from the station'do
bike=double(:bike, broken: false)
subject.dock(bike)
subject.release_bike
expect(subject.total).to eq(0)
end
end
describe '#add_to_array' do
it { is_expected.to respond_to(:add_to_array) }
it 'should store a working docked bike in the working_bikes_array' do
bike=double(:bike, broken: false)
expect(subject.add_to_array(bike)).to eq [bike]
end
it 'should store a broken docked bike in the broken_bikes_array' do
bike=double(:bike, broken: true)
expect(subject.add_to_array(bike)).to eq [bike]
end
end
describe '#reset_bikes' do
it 'must reset the bikes array' do
bike=double(:bike, broken: true)
subject.dock(bike)
bike1=double(:bike, broken: false)
subject.dock(bike1)
expect(subject.reset_bikes).to eq [bike1]
end
end
describe '#reset_broken_bikes' do
it 'must reset the broken bikes array' do
bike=double(:bike, broken: true)
subject.dock(bike)
expect(subject.reset_broken_bikes).to eq []
end
end
describe '#take_bikes_from_van' do
it 'must take the bikes from the van' do
van=double(:van, bikes_van: [1], reset_broken_bikes_van: [])
expect(subject.take_bikes_from_van(van)).to eq [1]
end
end
end
| true |
e6887489208f97645980397a1e04b84e6e8727df
|
Ruby
|
lindellcarternyc/Launch-School----Intro-to-Programming
|
/hashes/exercises.rb
|
UTF-8
| 1,868 | 4.53125 | 5 |
[] |
no_license
|
# Exercise 1
# Given a hash of family members, with keys as the title and an array of names
# as the values, use Ruby's built-in select method to gather only immediate
# family members' names into a new array.
family = { uncles: ["bob", "joe", "steve"],
sisters: ["jane", "jill", "beth"],
brothers: ["frank","rob","david"],
aunts: ["mary","sally","susan"]
}
immediate_family = family.select { |k, v| k == :sisters || k == :brothers }
puts immediate_family
# Exercise 2
# `merge` returns a new hash
# `merge!` mutates the original hash
h1 = {'a' => 1, 'b' => 2, '3' => 'c'}
h2 = {'b' => 2, 't' => 't', 'g' => 456}
h3 = h1.merge(h2) {|key, oldval, newval| oldval.to_s + newval.to_s}
puts "After merge"
puts "h1 => #{h1}"
puts "h2 => #{h2}"
puts "h3 => #{h3}"
h1.merge!(h2) {|key, oldval, newval| oldval.to_s + newval.to_s}
puts "After merge"
puts "h1 => #{h1}"
puts "h2 => #{h2}"
# Exercise 3
person = {name: 'Bob', occupation: 'web developer', hobbies: 'painting'}
person.each_key {|k| puts k}
person.each_value {|v| puts v}
person.each_pair {|k,v| puts "#{k} ==> #{v}"}
# Exercise 4
name = person[:name]
# Exercise 5
# you can use `has_value?`
if person.has_value?('Bob')
puts "His name is Bob"
else
puts "nope"
end
# Exercise 6
words = ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live',
'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide',
'flow', 'neon']
anagrams = {}
words.each do |word|
k = word.split('').sort.join
if anagrams.has_key?(k)
anagrams[k].push(word)
else
anagrams[k] = [word]
end
end
anagrams.each do |k, v|
p v
end
# Exercise 7
# The first hash is created using the symbol `x` as a key.
# The second hash is created using the string value stored in variable `x` as a key.
# Exercise 8
# There is no method named `keys` for Array objects.
| true |
0febc4647ab50c07f4ceea9e2f908fdb927dc608
|
Ruby
|
IrinaOvdii/ruby_codaisseur
|
/day-2/booleans.rb
|
UTF-8
| 854 | 4.53125 | 5 |
[] |
no_license
|
=begin
puts "Put your age:"
age = gets.chomp.to_i
if age < 18
puts "You can not drink your beer!"
elsif age > 50
puts "It's too late to dring a beer, sorry..."
else
puts "Take your beer!"
end
=end
puts "Welcome to Manipulating Your Strings!"
print "Let us know the string you want to modify: "
text = gets.chomp
print "How would you like to modify it?\nType 'uppercase', 'lowercase', 'capitalize' or 'reverse': "
method = gets.chomp
case method
when "reverse"
puts "This is your string backwards:"
puts text.reverse
when "uppercase"
puts "This is your string in all uppercase letters:"
puts text.upcase
when "lowercase"
puts "This is your string in all lowercase letters:"
puts text.downcase
when "capitalize"
puts "This is your string with its first character uppercased:"
puts text.capitalize
else
puts "Never mind!"
end
| true |
17b2c49b17f1f2629f69a32b67db5011df738e0d
|
Ruby
|
choihz/study-ruby
|
/Chapter 5/design.rb
|
UTF-8
| 4,364 | 3.34375 | 3 |
[] |
no_license
|
# 상속과 믹스인은 둘 다 코드를 한 곳에 모아놓고 그 코드를 다른 클래스들에서 효과적으로 재사용할 수 있게 해 준다. 언제 상속을 사용하고, 언제 믹스인을 사용하면 좋을까?
# 디자인에 관한 대부분의 질문에 대한 답이 그렇듯이 그건 상황에 달려 있다. 하지만 오랜 시간에 걸친 경험을 기반으로 프로그래머들은 상속과 믹스인을 선택하는 데 대한 일반적인 가이드라인을 제시하고 있다.
# 먼저 서브클래스화를 살펴보자. 루비에서 클래스는 타입이라는 개념과 연관이 있다. "cat"은 문자열이고 [1, 2]는 배열이라고 이야기하는 것은 자연스럽지만, 좀 더 엄밀하게 말하면 "cat"의 클래스는 String이고, [1, 2]의 클래스는 Array라고 말할 수 있다. 새로운 클래스를 추가하는 것은 그 언어에 새로운 타입을 추가하는 것이라고 봐도 무방하다. 또한 내장 클래스나 직접 만든 클래스를 서브 클래스화하는 것도 새로운 하위 타입을 만드는 것과 같다.
# 타입 추론에 대한 많은 연구가 진행되어 왔다. 유명한 연구 결과 중 하나로 리스코프 치환 원칙이 있다. 이 원칙은 "타입 T의 객체 x에 관해 참이 되는 속성을 q(x)라고 하자. 이때 S가 T에서 파생된 타입이라면 타입 S의 객체 y에 대해 q(y)도 참이 된다"로 정식화된다. 다르게 말하자면 부모 클래스의 객체는 자식 클래스의 객체로 바꿔서 사용할 수 있어야 한다는 의미다. 즉, 자식 클래스는 반드시 부모 클래스의 규약을 따라야만 한다. 이를 다르게 해석하면, 자식 클래스는 한 종류의 부모 클래스라고 말해질 수 있어야 한다(is-a). 이를 자연어로 풀어 써 보면 "자동차는 운송 수단이다", "고양이는 동물이다" 같이 표현된다. 이 말은 고양이라면 적어도 우리가 동물이 할 수 있다고 이야기하는 모든 것이 가능해야 한다는 이야기다.
# 따라서 애플리케이션을 설계할 때 자식 클래스로 만들어야 하는 부분을 찾고자 할 때는 이러한 is-a 관계를 확인하는 것이 좋다.
# 현실에서는 오히려 대상들 사이에 포함하거나 사용하는 관계에 있는 경우가 훨씬 더 일반적이다. 현실 세계는 다양한 조합으로 구성되며 엄밀한 계층 관계로 구성되지 않는다.
# 상속은 두 구성 요소 간에 지나치게 강한 결합을 만들어 낸다. 부모 클래스가 변경되면 자식 클래스에 문제가 생길 가능성이 있다. 더욱 나쁜 것은 자식 클래스를 사용하는 코드가 부모 클래스에서 정의된 메서드를 사용하고 있다면 이러한 코드들에도 문제가 생길 것이다. 부모 클래스의 구현은 자식 클래스에서 사용되고 이는 다시 코드 전체에서 사용된다. 좀 더 규모 있는 프로그램을 상상해 보자. 이러한 이유로 코드를 변경하는 것은 더욱 어려워질 것이다.
# 바로 이러한 이유에서 상속을 통한 디자인에서 멀어질 필요가 있다. 그 대신 A와 B가 A uses a B 또는 A has B 관계를 가진다고 보이면 구성(composition)을 사용하는 것이 좋다. 더 이상 Person은 DataWrapper의 자식 클래스여서는 안 된다. 이를 자식 클래스로 만드는 대신 DataWrapper에 대한 참조를 만들고 그 객체를 사용해 자신을 저장하거나 다시 읽어올 수 있도록 해야 한다.
# 하지만 이 역시 코드를 복잡하게 만들 수 있다. 여기서 믹스인과 메타프로그래밍이 등장한다. 이를 사용하면 다음과 같이 코드를 작성할 수 있다.
class Person
include Persistable
# ...
end
# 더 이상 다음과 같이 작성하지 않아도 된다.
class Person < DataWrapper
# ...
end
# 아직 객체 지향에 익숙하지 않다면 이러한 논의가 잘 와 닿지 않고 추상적으로 느껴질 것이다. 하지만 점점 더 큰 프로그램을 만들게 된다면, 이 문제에 대해 더 생각해 보기를 바란다. 상속은 정말로 상속이 필요한 데서만 사용하자. 그리고 좀 더 유연하고 구성 요소 간의 결합을 줄여주는 방법인 믹스인에 대해 더 탐색해 보자.
| true |
16ed62c7240b4c086008588f25d0dae12fddacf4
|
Ruby
|
liamzhang40/aA-projects
|
/W1D5/tree_node/lib/00_tree_node.rb
|
UTF-8
| 1,407 | 3.6875 | 4 |
[] |
no_license
|
class PolyTreeNode
# attr_reader :parent, :children, :value
def initialize(value)
@value = value
@parent = nil
@children = []
end
def add_child(node)
children << node
node.parent = self
end
def remove_child(node)
if children.include?(node)
children.delete(node)
node.parent = nil
else raise "No such children found!"
end
end
def parent
@parent
end
def children
@children
end
def value
@value
end
def parent=(node)
parent.children.delete(self) if parent
@parent = node
node.children << self unless (node.nil? || node.children.include?(self))
end
def dfs(target_value)
return self if self.value == target_value
children.each do |child|
previous_res = child.dfs(target_value)
return previous_res if previous_res
end
nil
# Very wrong method
# nil(returned from d) is returned prematurely from b skipping e
# return self if self.value == target_value
# children.each do |child|
# previous_res = child.dfs(target_value)
# return previous_res unless previous_res.is_a? Array
# end
# nil
end
# not a recursive method
def bfs(target_value)
queue = [self]
until queue.empty?
queue_first = queue.shift
return queue_first if queue_first.value == target_value
queue.concat(queue_first.children)
end
end
end
| true |
2db691d3f1250cec86bf8fc6ac408ea38db109cb
|
Ruby
|
kak79/prime-ruby-onl01-seng-ft-061520
|
/prime.rb
|
UTF-8
| 151 | 3.453125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def prime?(num)
if num < 2
return false
else
(2..num-1).to_a.all? {|possible_divisor| num % possible_divisor != 0}
end
end
| true |
08ed92ab8a608188863a93b46a439288e0cd8cb3
|
Ruby
|
portableworld/FizzBuzz
|
/Ruby.rb
|
UTF-8
| 698 | 4.28125 | 4 |
[] |
no_license
|
#####
# Tested on Windows 7 32-bit
# With Ruby version 1.9.2p0 [i386-mingw32]
#####
# Create a loop that'll run 100 times,
# each time passing a number into the block
1.upto(100) do |num|
if (num % 3 == 0) && (num % 5 == 0)
# This tests whether the number passed in will divide into 3
# with no remainder and then divide into 5 with no remaider.
# The '()'s are simply to make it a little more readable
# Note that the test for 'FizzBuzz' comes first. That is important!
puts "FizzBuzz"
elsif num % 3 == 0 # If the number can divide into 3 with no remainder
puts "Fizz"
elsif num % 5 == 0 # If the number can divide into 5 with no remainder
puts "Buzz"
else
puts num
end
end
| true |
8761e162acb32949305802661bcc34f4aa21bf35
|
Ruby
|
tigep37/RubyWork
|
/palindrome.rb
|
UTF-8
| 280 | 3.9375 | 4 |
[] |
no_license
|
def pal_check(word)
#the reverse function is case sensitive so downcase the word
lc_word = word.downcase
if lc_word == lc_word.reverse
puts "#{word} is a palindrome!"
else
puts "nah, #{word} is just regular"
end
end
pal_check("toot")
pal_check("ToOT")
pal_check("nope")
| true |
5d323da3c293447c69be4e06aeff19764260ee1f
|
Ruby
|
nejcjelovcan/sswaffles
|
/lib/sswaffles/storage.rb
|
UTF-8
| 1,635 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
module SSWaffles
# Storage abstracts out different storage systems (S3, memory, disk, mongo)
# bucket_type:
# nil default S3 API is used (needs s3 instance as :s3 options)
# :Memory buckets are in-memory hashes of key=>value
# :Disk buckets are folders on disk with keys in subfolders (basedir: ./s3/)
# :Mongo buckets are collections in a mongo db, (host: localhost, port: 27017, db: 'sswaffles')
# :Amazonreadonly buckets on S3 are used for reading, writing is ignored (needs s3 instance as :s3 option)
class Storage
attr_reader :buckets, :bucket_type, :options, :s3, :global
def initialize bucket_type=MemoryBucket, options={}
@bucket_type = if bucket_type.is_a?(Class) && bucket_type < Bucket
bucket_type
else
SSWaffles.const_get("#{bucket_type.to_s.capitalize}Bucket")
end
@global = {}
@options = options
@s3 = options.fetch(:s3, options.fetch('s3', nil))
@buckets = bucket_type.nil? ? @s3.buckets : BucketCollection.new(self)
end
def Bucket
@bucket_type
end
def import_bucket other_storage, bucket_name, options = {}, &block
target_bucket = buckets[bucket_name]
source_objects = other_storage.buckets[bucket_name].objects
source_objects = source_objects.select &block unless block.nil?
source_objects.each do |obj|
puts "Importing #{obj.key}"
unless options.fetch(:new_only, false) and target_bucket.objects[obj.key].exists?
target_bucket.objects[obj.key].write(obj.read)
end
end
end
end
end
| true |
dbfe9ab3f6ef89375be87591b0e2853c1390b6e0
|
Ruby
|
hamza3202/repositext
|
/spec/kramdown/parser/folio/helper.rb
|
UTF-8
| 1,255 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
# Provides helper methods for testing Folio parser
# Wraps xml_fragment in infobase tags
# @param [String] xml_fragment
def wrap_in_xml_infobase(xml_fragment)
%(<infobase>#{ xml_fragment }</infobase)
end
# Wraps xml_fragment in record tags
# @param [String] xml_fragment
def wrap_in_xml_record(xml_fragment)
wrap_in_xml_infobase(%(
<record class="NormalLevel" fullPath="/50000009/50130009/50130229" recordId="50130229">
#{ xml_fragment }
</record>)
)
end
# Constructs a kramdown tree from data.
# CAUTION: Two trees will be connected if you use the same Kramdown::ElementRt
# objects to construct them.
# @param [Array<Array>] tuple: An array with first as the parent and
# last as a single child or an array of children:
# [root, [
# [para, [
# text1,
# blank1,
# [em, [text2]]
# ]]
# ]]
def construct_kramdown_rt_tree(data)
parent, children = data
parent_clone = parent.clone
children.each do |child|
case child
when Array
parent_clone.add_child(construct_kramdown_rt_tree(child))
when Kramdown::ElementRt
parent_clone.add_child(child.clone)
else
raise(ArgumentError.new("invalid child: #{ child.inspect }"))
end
end
parent_clone
end
| true |
48f6c226750d11a68ef6cd11fbb43a2645156c86
|
Ruby
|
keyonce/ttt-5-move-rb-cb-gh-000
|
/bin/move
|
UTF-8
| 346 | 3.375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
#!/usr/bin/env ruby
require_relative '../lib/move.rb'
# Code your CLI Here
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
puts "Welcome to Tic Tac Toe!"
puts "Please enter 1-9:"
userInput = gets.strip # gets the user input and calls input_to_index
index = input_to_index(userInput)
move(board, index, char="X")
display_board(board)
| true |
914e50cfd4b0b4cf4c3d330c8ec7ec353a4878a7
|
Ruby
|
stevepolitodesign/po-notes
|
/test/models/user_test.rb
|
UTF-8
| 3,145 | 2.53125 | 3 |
[] |
no_license
|
require "test_helper"
class UserTest < ActiveSupport::TestCase
def setup
@plan = plans(:one)
@user = User.new(email: "[email protected]", password: "password", password_confirmation: "password", confirmed_at: Time.zone.now, plan: @plan)
end
test "should be valid" do
assert @user.valid?
end
test "should destroy associated notes" do
@user.save!
5.times do |n|
@note = @user.notes.build(title: "title #{n}", body: "body #{n}")
assert @note.valid?
@note.save!
end
assert_equal @user.reload.notes.length, 5
notes_count = @user.reload.notes.length
assert_difference("Note.count", -notes_count.to_s.to_i) do
@user.destroy
end
end
test "should destroy associated tasks" do
@user.save!
5.times do |n|
@task = @user.tasks.build(title: "title #{n}")
assert @task.valid?
@task.save!
end
assert_equal @user.reload.tasks.length, 5
tasks_count = @user.reload.tasks.length
assert_difference("Task.count", -tasks_count.to_s.to_i) do
@user.destroy
end
end
test "should destroy associated task items" do
@user.save!
@task = @user.tasks.build(title: "My Task")
@task.save!
@task_item = @task.task_items.build
@task_item.save!
assert_difference("TaskItem.count", -1) do
@user.destroy
end
end
test "should have a default plan of 'Free'" do
@user.plan = nil
@user.save!
assert_equal "Free", @user.reload.plan.name
end
test "should not set default plan on create if user has a plan" do
@plan = Plan.create(name: "Somehing unique")
@user.plan = @plan
@user.save!
assert_equal "Somehing unique", @user.reload.plan.name
end
test "should have time_zone" do
@user.time_zone = nil
assert_not @user.valid?
end
test "should have default time_zone of 'UTC'" do
assert_equal "UTC", @user.time_zone
end
test "should be a valid time_zone" do
invalid_time_zones = %w[foo bar bax]
invalid_time_zones.each do |invalid_time_zone|
@user.time_zone = invalid_time_zone
assert_not @user.valid?
end
valid_time_zones = ActiveSupport::TimeZone.all.map { |tz| tz.name }
valid_time_zones.each do |valid_time_zone|
@user.time_zone = valid_time_zone
assert @user.valid?
end
end
test "should destroy associated reminders" do
Reminder.destroy_all
@user.save
@user.reminders.create(name: "My Reminder", body: "Some text", time: Time.zone.now + 1.day)
assert_difference("Reminder.count", -1) do
@user.destroy
end
end
test "should be valid without telephone" do
@user.telephone = nil
assert @user.valid?
end
test "should be invalid if telephone is invalid" do
invalid_numbers = ["12345", "foo bar", "555-555"]
invalid_numbers.each do |invalid_number|
@user.telephone = invalid_number
assert_not @user.valid?
end
end
test "should be valid if telephone is valid" do
valid_numbers = ["617-555-0173", "(508) 555-0193"]
valid_numbers.each do |valid_number|
@user.telephone = valid_number
assert @user.valid?
end
end
end
| true |
947b1351484392d0f2f641e7eabb17c14c680947
|
Ruby
|
TamerL/credit_card_validator
|
/app/models/credit_card.rb
|
UTF-8
| 1,582 | 2.546875 | 3 |
[] |
no_license
|
# frozen_string_literal: true
# to check the credit card numbers find the type and validate the digits
class CreditCard < ApplicationRecord
# before_save :check_number_errors
# skip_before_action :verify_authenticity_token
# protect_from_forgery prepend: true, with: :exception
belongs_to :card_type
belongs_to :user
# add uniqueness to number
validates :number, presence: true # pls add database level constraints for the presence, also for the card_type
def self.create_credit_card!(num)
validator = CreditCardNumberValidator.new(num)
card = CreditCard.new(number: num)
card_type = CardType.new
begin
validator.validate!
card_type.name = validator.type!
card_type.save! unless CardType.pluck(:name).include?(card_type.name)
# binding.pry
card.card_type= card_type
card.number = num[-4..-1].to_s
# binding.pry
card.save!
rescue => e
# binding.pry
puts e.message
card.errors.add(:base, e.message)
end
card
end
protected
def check_number_errors
begin
# binding.pry
validator = CreditCardNumberValidator.new(self.number.to_s)
validator.valid!
self.card_type = validator.type
valid = validator.valid?
return true
rescue => e
# binding.pry
puts e.message
self.errors.add(:base, e.message)
return false
end
end
# TODO:
# fix strong migration, also add restrictions to the column
# uniqness(num), be present(type and num), 2 levels restrictions:
# database level and model level
end
| true |
c201206085655bd1a297eeb3d5543e4d4c3fce33
|
Ruby
|
wichru/codesensei_course
|
/homework_1/highest_number.rb
|
UTF-8
| 153 | 3.390625 | 3 |
[] |
no_license
|
def highest_number(number)
number.to_s.split('').sort.reverse.join
end
puts highest_number(132)
puts highest_number(1464)
puts highest_number(165423)
| true |
25dd63a214bd21942d2c1b876eee3914ba1a2184
|
Ruby
|
esauter5/Tealeaf
|
/RubyWebDev/blackjackV2.rb
|
UTF-8
| 6,455 | 3.8125 | 4 |
[] |
no_license
|
class Player
attr_accessor :name, :bank_roll, :hand, :bet, :status
def initialize(name, bank_roll)
@hand = Hand.new
@name = name
@bank_roll = bank_roll
@bet = 5
@status = 'active'
end
def hit_or_stay
if @hand.cards.size == 2
puts "Would you like to hit or stay or double down? (h/s/dd)"
else
puts "Would you like to hit or stay? (h/s)"
end
case gets.chomp
when 'h'
return 'h'
when 's'
return 's'
when 'dd'
if @bet > @bank_roll/2
puts "You don't have enough money to double down!"
hit_or_stay
elsif @hand.cards.size == 2
return 'dd'
else
puts "You cannot currently double down!"
hit_or_stay
end
end
end
end
#*****************************
class Dealer
attr_accessor :hand, :status
def initialize
@hand = Hand.new
@status = "active"
end
def hit_or_stay
if @hand.score < 17
'h'
else
's'
end
end
end
#*****************************
class Deck
attr_accessor :cards, :num_decks
def initialize(num_decks)
@cards = []
@num_decks = num_decks
generate_deck
end
def initialize_values
card_values = Hash.new(0)
(2..9).each {|i| card_values[i.to_s.to_sym] = i }
card_values[:"1"] = 10 #Represents 10 since I read first character
card_values[:J] = 10
card_values[:Q] = 10
card_values[:K] = 10
card_values[:A] = 11
card_values
end
def generate_deck
ranks = %w{ 2 3 4 5 6 7 8 9 10 Jack Queen King Ace }
suits = %w{ Diamonds Hearts Spades Clubs }
card_values = initialize_values
@num_decks.times do
suits.each do |suit|
ranks.each do |rank|
card = Card.new(suit, rank)
card.value = card_values[card.rank[0].to_sym]
@cards << card
end
end
end
@cards.shuffle!
end
end
#*****************************
class Hand
attr_accessor :cards, :score
def initialize
@cards = []
@score = 0
end
def hand_value
@score = 0
non_aces = @cards.select { |card| card.rank != "A"}
aces = @cards.select { |card| card.rank == "A"}
num_aces = aces.size
non_aces.each { |card| @score += card.value }
aces.each_with_index do |ace, i|
if i == 0 && (score <= 10 - (num_aces - 1))
@score += 11
else
@score += 1
end
end
score
end
def print_hand(name = "Player", status = "hit")
cards.each_with_index do |card, i|
if name == "Dealer" && i == 0 && status == "hit"
puts "#{name} Card #{i}: Hidden "
else
print "#{name} Card #{i}: "
card.print_card
end
end
end
end
#*****************************
class Card
attr_accessor :suit, :rank, :value
def initialize(suit, rank)
@suit = suit
@rank = rank
end
def print_card
puts "#{rank} of #{suit}"
end
end
#*****************************
class GameEngine
attr_accessor :player, :dealer, :deck
def initialize(player)
@player = player
@dealer = Dealer.new
end
def shuffle(num_decks)
@deck = Deck.new(num_decks)
end
def initial_deal
@player.hand.cards << @deck.cards.pop
@dealer.hand.cards << @deck.cards.pop
@player.hand.cards << @deck.cards.pop
@dealer.hand.cards << @deck.cards.pop
end
def print_hands(status = "hit")
@player.hand.print_hand(player.name)
@dealer.hand.print_hand("Dealer",status)
end
def calculate_scores
@player.hand.hand_value
@player.status = "bust" if @player.hand.score > 21
@dealer.hand.hand_value
@dealer.status = "bust" if @dealer.hand.score > 21
end
def player_decision
case @player.hit_or_stay
when 'h'
@player.hand.cards << @deck.cards.pop
@player.status = 'active'
when 's'
@player.status = 'stay'
when 'dd'
@player.hand.cards << @deck.cards.pop
@player.status = 'stay'
end
end
def dealer_decision
case @dealer.hit_or_stay
when 'h'
@dealer.hand.cards << @deck.cards.pop
@dealer.hand.score = @dealer.hand.hand_value
@dealer.status = "active"
when 's'
@dealer.status = "stay"
end
end
def player_turn
until @player.status == "stay" || @player.status == "bust"
player_decision
print_hands
calculate_scores
print_player_score
end
end
def dealer_turn
until @dealer.status == "stay" || @dealer.status == "bust"
dealer_decision
calculate_scores
end
end
def check_blackjack
if @player.hand.score == 21
@player.status = "blackjack"
@player.bank_roll += @player.bet
puts "BLACKJACK!"
elsif @dealer.hand.score == 21
@dealer.status = "blackjack"
@player.bank_roll -= @player.bet
end
end
def print_player_score
puts "Player Score: #{@player.hand.score}", ""
end
def print_dealer_score
puts "Dealer Score: #{@dealer.hand.score}", ""
end
def determine_winner
if @player.hand.score == @dealer.hand.score
puts "TIE!!!"
elsif @player.status == "blackjack"
puts "YOU WIN!!!"
@player.bank_roll += @player.bet
elsif @dealer.status == "blackjack"
puts "DEALER WINS!!!"
@player.bank_roll -= @player.bet
elsif @player.status == "bust"
puts "BUST!!! YOU LOSE!!!"
@player.bank_roll -= @player.bet
elsif @dealer.status == "bust"
puts "DEALER BUST!!! YOU WIN!!!"
@player.bank_roll += @player.bet
elsif @player.hand.score > @dealer.hand.score
puts "YOU WIN!!!"
@player.bank_roll += @player.bet
else
puts "DEALER WINS!!!"
@player.bank_roll -= @player.bet
end
end
def play(player)
initial_deal
print_hands
calculate_scores
check_blackjack
print_player_score
unless @player.status == "blackjack" || @dealer.status == "blackjack"
player_turn
dealer_turn
end
print_hands("stay")
print_player_score
print_dealer_score
determine_winner
end
end
puts "What is your name?"
name = gets.chomp
puts "How many decks would you like to use?"
num_decks = gets.chomp.to_i
#puts "Current money: #{$bank}", ""
#puts "How much would you like to bet?"
#bet = gets.chomp.to_i
continue = 'y'
until continue == 'n'
player = Player.new(name, 2000)
engine = GameEngine.new(player)
engine.shuffle(2)
engine.play(player)
puts "Would you like to play again?"
continue = gets.chomp
end
| true |
824bccf15932e8992fb2e21dbf0b5f50264258f3
|
Ruby
|
microsoftgraph/msgraph-sdk-ruby
|
/lib/models/calendar_sharing_message.rb
|
UTF-8
| 5,463 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
require 'microsoft_kiota_abstractions'
require_relative '../microsoft_graph'
require_relative './models'
module MicrosoftGraph
module Models
class CalendarSharingMessage < MicrosoftGraph::Models::Message
include MicrosoftKiotaAbstractions::Parsable
##
# The canAccept property
@can_accept
##
# The sharingMessageAction property
@sharing_message_action
##
# The sharingMessageActions property
@sharing_message_actions
##
# The suggestedCalendarName property
@suggested_calendar_name
##
## Gets the canAccept property value. The canAccept property
## @return a boolean
##
def can_accept
return @can_accept
end
##
## Sets the canAccept property value. The canAccept property
## @param value Value to set for the canAccept property.
## @return a void
##
def can_accept=(value)
@can_accept = value
end
##
## Instantiates a new calendarSharingMessage and sets the default values.
## @return a void
##
def initialize()
super
@odata_type = "#microsoft.graph.calendarSharingMessage"
end
##
## Creates a new instance of the appropriate class based on discriminator value
## @param parse_node The parse node to use to read the discriminator value and create the object
## @return a calendar_sharing_message
##
def self.create_from_discriminator_value(parse_node)
raise StandardError, 'parse_node cannot be null' if parse_node.nil?
return CalendarSharingMessage.new
end
##
## The deserialization information for the current model
## @return a i_dictionary
##
def get_field_deserializers()
return super.merge({
"canAccept" => lambda {|n| @can_accept = n.get_boolean_value() },
"sharingMessageAction" => lambda {|n| @sharing_message_action = n.get_object_value(lambda {|pn| MicrosoftGraph::Models::CalendarSharingMessageAction.create_from_discriminator_value(pn) }) },
"sharingMessageActions" => lambda {|n| @sharing_message_actions = n.get_collection_of_object_values(lambda {|pn| MicrosoftGraph::Models::CalendarSharingMessageAction.create_from_discriminator_value(pn) }) },
"suggestedCalendarName" => lambda {|n| @suggested_calendar_name = n.get_string_value() },
})
end
##
## Serializes information the current object
## @param writer Serialization writer to use to serialize this model
## @return a void
##
def serialize(writer)
raise StandardError, 'writer cannot be null' if writer.nil?
super
writer.write_boolean_value("canAccept", @can_accept)
writer.write_object_value("sharingMessageAction", @sharing_message_action)
writer.write_collection_of_object_values("sharingMessageActions", @sharing_message_actions)
writer.write_string_value("suggestedCalendarName", @suggested_calendar_name)
end
##
## Gets the sharingMessageAction property value. The sharingMessageAction property
## @return a calendar_sharing_message_action
##
def sharing_message_action
return @sharing_message_action
end
##
## Sets the sharingMessageAction property value. The sharingMessageAction property
## @param value Value to set for the sharingMessageAction property.
## @return a void
##
def sharing_message_action=(value)
@sharing_message_action = value
end
##
## Gets the sharingMessageActions property value. The sharingMessageActions property
## @return a calendar_sharing_message_action
##
def sharing_message_actions
return @sharing_message_actions
end
##
## Sets the sharingMessageActions property value. The sharingMessageActions property
## @param value Value to set for the sharingMessageActions property.
## @return a void
##
def sharing_message_actions=(value)
@sharing_message_actions = value
end
##
## Gets the suggestedCalendarName property value. The suggestedCalendarName property
## @return a string
##
def suggested_calendar_name
return @suggested_calendar_name
end
##
## Sets the suggestedCalendarName property value. The suggestedCalendarName property
## @param value Value to set for the suggestedCalendarName property.
## @return a void
##
def suggested_calendar_name=(value)
@suggested_calendar_name = value
end
end
end
end
| true |
8efc2df205e56af2b2e2ad00e6692815997677ae
|
Ruby
|
jtb1137/trending-stocks-gem
|
/lib/trending-stocks-gem/cli.rb
|
UTF-8
| 1,436 | 3.3125 | 3 |
[] |
no_license
|
class TrendingStocksGem::CLI
def call
TrendingStocksGem::Scraper.new.build_stocks
puts ""
puts "----------- TODAYS TRENDING STOCKS -----------"
puts ""
menu
end
def menu
list_stocks
puts ""
puts "Which stock would you like to know more about?"
input = gets.strip
stock = TrendingStocksGem::Stock.find(input)
display_stock_info(stock)
puts ""
puts 'To return to the list of stocks, type "list"'
puts 'To exit, type "exit"'
input = input.strip.downcase
if input == "list"
menu
else
exit
end
end
def list_stocks
TrendingStocksGem::Stock.all.each.with_index(1) do |stock, i|
puts "#{i}. #{stock.name} - Last: #{stock.last} - Change: #{stock.change}"
end
end
def display_stock_info(stock)
puts ""
puts "----------- #{stock.name} -----------"
puts ""
puts "Last: #{stock.last}"
puts "High: #{stock.high}"
puts "Low: #{stock.low}"
puts "Change: #{stock.change}"
puts "Change %: #{stock.change_percent}"
puts "Trade Volume: #{stock.volume}"
puts ""
#puts "Market Cap: #{@this_stock.market_cap}"
#puts "ROI: #{@this_stock.roi}"
#puts "Beta: #{@this_stock.beta}"
#puts "----------- Technical Analysis -----------"
#puts "Hourly: #{}"
#puts "Daily: #{}"
#puts "Monthly: #{}"
end
end
| true |
e25b4d24125784f07402bec45789b8b9189f49f7
|
Ruby
|
yubrew/projecteuler
|
/problem34.rb
|
UTF-8
| 202 | 3.640625 | 4 |
[] |
no_license
|
def factorial(n)
(1..n).inject(:*) || 1
end
max = 7 * factorial(9)
sum = 0
(10..max).each do |n|
if n == n.to_s.chars.map { |i| factorial(i.to_i) }.inject(:+)
puts n
sum += n
end
end
puts sum
| true |
d17a90a6a4fc9f2594a815310531bfac83ccf614
|
Ruby
|
woolfayeee79/IT-212-Projects-
|
/Project2/bowling.rb
|
UTF-8
| 912 | 3.375 | 3 |
[] |
no_license
|
# Megan Woolschlager IT 212
# Project number 2
# submission date: 1/29/2018
require "./read-ragged-array"
require "./frame-score"
#read file name from keyboard
print "name of input file: "
input_file = gets.chomp
frames = read_ragged_array(input_file)
score = 0
for i in 1..10
# case of strike with next ball also strike
if frames[i][0] == 10 && frames[i+1][0] == 10
bonus1 = 10
bonus2 = frames[i+2][0]
# case of strike with next ball not a stike
elsif frames[i][0] == 10 && frames[i+1][0] < 10
bonus1 = frames[i+1][0]
bonus2 = frames[i+1][1]
# case of spare
elsif frames[i][0] + frames[i][1] == 10
bonus1 = frames[i+1][0]
bonus2 = 0
# case of open frame
else
bonus1 = 0
bonus2 = 0
end
# add frame score to the running total(+=)
score += frame_score(frames[i], bonus1, bonus2)
end
print score, "\n"
| true |
f7659425852bf9f0bccf2f28c20d3f3ff56a61a0
|
Ruby
|
angieappiah/method-scope-lab-onl01-seng-ft-012120
|
/spec/catch_phrase_spec.rb
|
UTF-8
| 242 | 2.84375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require "spec_helper"
describe "#catch_phrase" do
phrase = 'It's-a me, Mario!'
expect{catch_phrase}.to output("It's-a me, Mario!\n").to_stdout
end
def catch_phrase
phrase = " It's a me"
puts "#{phrase}", Mario!.
end
| true |
4fb02e81261eb16a8c2ea9429d15895daa264d7b
|
Ruby
|
levabd/nice-tv-dashboard
|
/jobs/jira_list_current_sprint_issues.rb
|
UTF-8
| 3,044 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
require 'jira'
require 'net/http'
require 'json'
# Settings to configure:
# PROJECT: the project path/name
# RAPID_VIEW_ID: id for the rapid view board
# JIRA_CONFIG: credentials to access JIRA
# ISSUE_LISTS: a widget per entry for different statuses (see JIRA_STATUSES)
PROJECT = "WIP"
RAPID_VIEW_ID = 2
JIRA_CONFIG = {
:username => ENV['JIRA_USERNAME'],
:password => ENV['JIRA_PASSWORD'],
:site => "https://your-jira-instance.atlassian.net",
:auth_type => :basic,
:context_path => ''
}
ISSUE_LISTS = [
{:widget_id => 'jira_open_issues', :status_id => 1}, # Lists all open issues
{:widget_id => 'jira_in_prog_issues', :status_id => 3} # Lists all issues in progress
]
# Constants (do not change)
JIRA_URI = URI.parse(JIRA_CONFIG[:site])
JIRA_ANON_AVATAR_ID = 10123
JIRA_STATUSES = {
1 => "Open",
3 => "In Progress",
4 => "Reopened",
5 => "Resolved",
6 => "Closed"
}
# gets the view for a given view id
def get_view_for_viewid(view_id)
http = create_http
request = create_request("/rest/greenhopper/1.0/rapidviews/list")
response = http.request(request)
views = JSON.parse(response.body)['views']
views.each do |view|
if view['id'] == view_id
return view
end
end
end
# gets the active sprint for the view
def get_active_sprint_for_view(view_id)
http = create_http
request = create_request("/rest/greenhopper/1.0/sprintquery/#{view_id}")
response = http.request(request)
sprints = JSON.parse(response.body)['sprints']
sprints.each do |sprint|
if sprint['state'] == 'ACTIVE'
return sprint
end
end
end
# create HTTP
def create_http
http = Net::HTTP.new(JIRA_URI.host, JIRA_URI.port)
if ('https' == JIRA_URI.scheme)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
return http
end
# create HTTP request for given path
def create_request(path)
request = Net::HTTP::Get.new(JIRA_URI.path + path)
if JIRA_CONFIG[:username]
request.basic_auth(JIRA_CONFIG[:username], JIRA_CONFIG[:password])
end
return request
end
ISSUE_LISTS.each do |list_config|
SCHEDULER.every '5m', :first_in => 0 do |job|
issues = []
status_id = list_config[:status_id]
client = JIRA::Client.new(JIRA_CONFIG)
client.Issue.jql("PROJECT = \"#{PROJECT}\" AND STATUS = \"#{status_id}\" AND SPRINT in openSprints()").each { |issue|
assigneeAvatarUrl = issue.assignee.nil? ? URI.join(JIRA_URI.to_s, "secure/useravatar?avatarId=#{JIRA_ANON_AVATAR_ID}") : issue.assignee.avatarUrls["48x48"]
assigneeName = issue.assignee.nil? ? "unassigned" : issue.assignee.name
issues.push({
id: issue.key,
title: issue.summary,
assigneeName: assigneeName,
assigneeAvatarUrl: assigneeAvatarUrl
})
}
issue_type = JIRA_STATUSES[status_id]
active_sprint = get_active_sprint_for_view(RAPID_VIEW_ID)
sprint_name = active_sprint['name']
send_event(list_config[:widget_id], { header: "#{sprint_name} Issues", issue_type: issue_type, issues: issues})
end
end
| true |
f12d75df75b7f19896a25cc406a7d25230f0a216
|
Ruby
|
oriolgual/fizz_buzz_pro
|
/lib/fizz_buzzer.rb
|
UTF-8
| 809 | 3.40625 | 3 |
[] |
no_license
|
require 'buzz_rule'
require 'default_rule'
require 'fizz_rule'
require 'fizz_buzz_rule'
require 'meeek_rule'
require 'default_processor'
require 'even_string_processor'
require 'odd_number_processor'
class FizzBuzzer
attr_reader :number
def initialize(number)
@number = number
end
def to_fizz_buzz
processors.each do |processor_class|
processor = processor_class.new(result, number)
return processor.process if processor.applies?
end
end
private
def result
selected_rule.new(number).result
end
def selected_rule
rules.find do |rule|
rule.new(number).applies?
end
end
def rules
[FizzBuzzRule, FizzRule, BuzzRule, MeeekRule, DefaultRule]
end
def processors
[EvenStringProcessor, OddNumberProcessor, DefaultProcessor]
end
end
| true |
e1c08f10d5aa1f168eab3dd741fe89bff3639164
|
Ruby
|
phifty/agraph
|
/lib/allegro_graph/proxy/query.rb
|
UTF-8
| 901 | 2.578125 | 3 |
[] |
no_license
|
module AllegroGraph
module Proxy
# The Query class acts as proxy that bypasses SparQL and Prolog queries to the AllegroGraph server.
class Query
LANGUAGES = [ :sparql, :prolog ].freeze unless defined?(LANGUAGES)
attr_reader :server
attr_reader :resource
attr_reader :language
def initialize(resource)
@resource = resource
@language = :sparql
end
def path
@resource.path
end
def language=(value)
value = value.to_sym
raise NotImplementedError, "query langauge [#{value}] is not implemented" unless LANGUAGES.include?(value)
@language = value
end
def perform(query)
parameters = { :query => query, :queryLn => @language.to_s }
@resource.request_json :get, self.path, :parameters => parameters, :expected_status_code => 200
end
end
end
end
| true |
832a2bbd0778e9e2cab0612cc442ca272839386f
|
Ruby
|
xsuchy/foreman_api
|
/lib/foreman_api/base.rb
|
UTF-8
| 3,714 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
require 'rest_client'
require 'oauth'
require 'json'
require 'foreman_api/rest_client_oauth'
module ForemanApi
class Base
API_VERSION = "2"
attr_reader :client, :config
def initialize(config, options = {})
@client = RestClient::Resource.new(
config[:base_url],
{ :user => config[:username],
:password => config[:password],
:oauth => config[:oauth],
:headers => { :content_type => 'application/json',
:accept => "application/json;version=#{API_VERSION}" }
}.merge(options))
@config = config
end
def call(method, path, params = { }, headers = { })
headers ||= { }
args = [method]
if [:post, :put].include?(method)
args << params.to_json
else
headers[:params] = params if params
end
args << headers if headers
process_data client[path].send(*args)
end
def self.doc
raise NotImplementedError
end
def self.validation_hash(method)
validation_hashes[method.to_s]
end
def self.method_doc(method)
method_docs[method.to_s]
end
def validate_params!(params, rules)
return unless params.is_a?(Hash)
invalid_keys = params.keys.map(&:to_s) - (rules.is_a?(Hash) ? rules.keys : rules)
raise ArgumentError, "Invalid keys: #{invalid_keys.join(", ")}" unless invalid_keys.empty?
if rules.is_a? Hash
rules.each do |key, sub_keys|
validate_params!(params[key], sub_keys) if params[key]
end
end
end
protected
def process_data(response)
data = begin
JSON.parse(response.body)
rescue JSON::ParserError
response.body
end
return data, response
end
def check_params(params, options = { })
raise ArgumentError unless (method = options[:method])
return unless config[:enable_validations]
case options[:allowed]
when true
validate_params!(params, self.class.validation_hash(method))
when false
raise ArgumentError, "this method '#{method}' does not support params" if params && !params.empty?
else
raise ArgumentError, "options :allowed should be true or false, it was #{options[:allowed]}"
end
end
# @return url and rest of the params
def fill_params_in_url(url, params)
params ||= { }
# insert param values
url_param_names = params_in_path(url)
url = params_in_path(url).inject(url) do |url, param_name|
param_value = params[param_name] or
raise ArgumentError, "missing param '#{param_name}' in parameters"
url.sub(":#{param_name}", param_value.to_s)
end
return url, params.reject { |param_name, _| url_param_names.include? param_name }
end
private
def self.method_docs
@method_docs ||= doc['methods'].inject({ }) do |hash, method|
hash[method['name']] = method
hash
end
end
def self.validation_hashes
@validation_hashes ||= method_docs.inject({ }) do |hash, pair|
name, method_doc = pair
hash[name] = construct_validation_hash method_doc
hash
end
end
def self.construct_validation_hash(method)
if method['params'].any? { |p| p['params'] }
method['params'].reduce({ }) do |h, p|
h.update(p['name'] => (p['params'] ? p['params'].map { |pp| pp['name'] } : nil))
end
else
method['params'].map { |p| p['name'] }
end
end
def params_in_path(url)
url.scan(/:([^\/]*)/).map { |m| m.first }
end
end
end
| true |
cd04661bb73ff6a28b9d9817bfa9d2abb7b56892
|
Ruby
|
ben-altman/parrot-ruby-online-web-sp-000
|
/parrot.rb
|
UTF-8
| 148 | 3.25 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Create method `parrot` that outputs a given phrase and
# returns the phrase
def parrot (verbiage = "Squawk!")
puts "#{verbiage}"
verbiage
end
| true |
37a17039e891f8d535ae800509225a27312627e9
|
Ruby
|
attribution/sequel-redshift
|
/lib/sequel/extensions/redshift_string_agg.rb
|
UTF-8
| 3,151 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
# frozen-string-literal: true
#
# Please consider using patched `string_agg` extension, it properly handles all supported DB adapters
# including Redshift out of the box.
#
# The redshift_string_agg extension adds the ability to perform database-independent
# aggregate string concatentation on Amazon Redshift.
# Related module: Sequel::SQL::RedshiftStringAgg
module Sequel
module SQL
module Builders
# Return a RedshiftStringAgg expression for an aggregate string concatentation.
def redshift_string_agg(*a)
RedshiftStringAgg.new(*a)
end
end
# The RedshiftStringAgg class represents an aggregate string concatentation.
class RedshiftStringAgg < GenericExpression
include StringMethods
include StringConcatenationMethods
include InequalityMethods
include AliasMethods
include CastMethods
include OrderMethods
include PatternMatchMethods
include SubscriptMethods
# These methods are added to datasets using the redshift_string_agg
# extension, for the purposes of correctly literalizing RedshiftStringAgg
# expressions for the appropriate database type.
module DatasetMethods
# Append the SQL fragment for the RedshiftStringAgg expression to the SQL query.
def redshift_string_agg_sql_append(sql, sa)
unless db.adapter_scheme == :redshift
raise Error, "redshift_string_agg is not implemented on #{db.adapter_scheme}"
end
expr = sa.expr
separator = sa.separator || ","
order = sa.order_expr
distinct = sa.is_distinct?
if distinct
raise Error, "redshift_string_agg with distinct is not implemented on #{db.database_type}"
end
literal_append(sql, Function.new(:listagg, expr, separator))
if order
sql << " WITHIN GROUP (ORDER BY "
expression_list_append(sql, order)
sql << ")"
else
sql << " WITHIN GROUP (ORDER BY 1)"
end
end
end
# The string expression for each row that will concatenated to the output.
attr_reader :expr
# The separator between each string expression.
attr_reader :separator
# The expression that the aggregation is ordered by.
attr_reader :order_expr
# Set the expression and separator
def initialize(expr, separator=nil)
@expr = expr
@separator = separator
end
# Whether the current expression uses distinct expressions
def is_distinct?
@distinct == true
end
# Return a modified RedshiftStringAgg that uses distinct expressions
def distinct
sa = dup
sa.instance_variable_set(:@distinct, true)
sa
end
# Return a modified RedshiftStringAgg with the given order
def order(*o)
sa = dup
sa.instance_variable_set(:@order_expr, o.empty? ? nil : o)
sa
end
to_s_method :redshift_string_agg_sql
end
end
Dataset.register_extension(:redshift_string_agg, SQL::RedshiftStringAgg::DatasetMethods)
end
| true |
c4ca1eb16ca7db0cea5a0a8b62f1fbb45bd4ab20
|
Ruby
|
ianagbip1oti/advent-of-code-2020
|
/ruby/day07.rb
|
UTF-8
| 45,332 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
require 'set'
def parse_line(str)
bag, contains = str.split 'bags contain'
contains = contains.split(',').map do
words = _1.split
qty = words[0].to_i
color = words[1..2].join ' '
[color, qty]
end
[ bag.strip, contains.to_h ]
end
BAGS = DATA.map { parse_line _1 }.to_h
def select_containing(bag)
BAGS.select { |k, v| v.key? bag }.keys
end
def count_containing(bag)
q = [bag]
result = Set.new()
while not q.empty?
select_containing(q.pop).each do
q.push _1
result.add _1
end
end
result.size
end
def count_contained_in(bag)
BAGS.fetch(bag, []).map { |b, c| c * (1 + count_contained_in(b)) }.sum
end
p count_containing('shiny gold')
p count_contained_in('shiny gold')
__END__
pale turquoise bags contain 3 muted cyan bags, 5 striped teal bags.
light tan bags contain 5 posh tomato bags.
shiny coral bags contain 2 muted bronze bags.
wavy orange bags contain 4 faded tomato bags.
light plum bags contain 3 drab orange bags, 4 faded coral bags.
pale purple bags contain 5 bright crimson bags.
bright blue bags contain 1 pale beige bag, 1 light teal bag.
pale bronze bags contain 1 dotted salmon bag, 1 striped blue bag, 2 clear tan bags.
muted maroon bags contain 5 pale crimson bags.
clear lavender bags contain 4 vibrant black bags, 2 posh red bags.
pale cyan bags contain 4 light olive bags, 2 dull lime bags, 4 faded black bags, 4 plaid red bags.
faded blue bags contain 1 posh tan bag, 1 dotted violet bag, 3 posh gold bags.
wavy teal bags contain 3 pale brown bags.
striped red bags contain 2 light bronze bags, 3 dark cyan bags.
drab brown bags contain 3 striped magenta bags, 3 clear silver bags.
posh salmon bags contain 4 bright purple bags, 5 mirrored green bags, 3 pale gold bags, 5 dull crimson bags.
light black bags contain 2 wavy coral bags.
striped tan bags contain 3 clear blue bags, 3 mirrored teal bags, 5 striped red bags.
posh plum bags contain 3 drab orange bags.
striped blue bags contain 4 bright violet bags, 5 dotted gray bags, 3 dotted violet bags, 1 dotted blue bag.
shiny white bags contain 4 dotted orange bags, 1 faded silver bag, 1 drab coral bag.
plaid maroon bags contain 3 light gold bags.
shiny fuchsia bags contain 2 dotted olive bags, 3 vibrant white bags, 3 dark salmon bags, 4 pale white bags.
muted bronze bags contain 4 vibrant bronze bags, 2 posh yellow bags, 1 shiny turquoise bag.
wavy cyan bags contain 2 striped crimson bags, 4 plaid tan bags.
vibrant indigo bags contain 4 pale gold bags, 3 posh gold bags, 1 drab red bag, 4 dull crimson bags.
drab tan bags contain 3 dark indigo bags, 3 striped black bags.
dull tan bags contain 3 drab blue bags, 3 pale green bags, 3 dotted red bags, 3 striped maroon bags.
dark red bags contain 4 bright chartreuse bags.
drab beige bags contain 5 bright teal bags, 1 faded cyan bag, 2 muted yellow bags, 1 dim lime bag.
dim black bags contain 5 wavy fuchsia bags, 3 muted tomato bags, 4 faded blue bags.
pale red bags contain 2 drab gray bags, 5 dull coral bags, 4 striped purple bags.
light cyan bags contain 4 mirrored gold bags, 3 vibrant bronze bags.
posh orange bags contain 2 dark silver bags, 3 striped chartreuse bags.
shiny cyan bags contain 5 dark turquoise bags.
vibrant cyan bags contain 2 light turquoise bags, 2 clear cyan bags, 4 dark cyan bags, 4 dotted orange bags.
vibrant gray bags contain 5 dark purple bags, 5 dark lime bags.
posh green bags contain 4 bright salmon bags, 2 muted tan bags.
posh tan bags contain 2 dotted indigo bags, 1 dull purple bag.
clear blue bags contain 5 dull purple bags.
wavy gray bags contain 4 pale cyan bags, 2 pale tomato bags.
posh red bags contain 4 dim green bags, 2 pale teal bags.
light tomato bags contain 5 dotted chartreuse bags.
faded yellow bags contain 3 plaid orange bags, 4 mirrored maroon bags.
dark black bags contain 1 faded gold bag, 3 striped purple bags, 2 dim teal bags.
light red bags contain 5 dark magenta bags, 3 striped purple bags.
dotted violet bags contain no other bags.
faded gold bags contain 1 dotted aqua bag, 2 light turquoise bags, 5 wavy violet bags.
dotted beige bags contain 5 vibrant turquoise bags, 5 clear maroon bags, 3 dim tomato bags, 4 pale maroon bags.
pale lavender bags contain 5 muted red bags, 3 dark teal bags, 3 faded black bags, 1 dim fuchsia bag.
clear tomato bags contain 3 dull white bags, 3 mirrored gold bags, 1 dark black bag.
vibrant silver bags contain 4 plaid orange bags, 2 shiny chartreuse bags, 3 dark salmon bags, 4 light silver bags.
plaid cyan bags contain 1 dark black bag.
drab green bags contain 1 plaid white bag.
posh turquoise bags contain 3 posh plum bags, 3 light gold bags, 1 bright crimson bag.
pale lime bags contain 3 pale olive bags, 3 vibrant chartreuse bags, 1 dotted tan bag, 5 striped cyan bags.
wavy fuchsia bags contain 3 shiny chartreuse bags, 3 vibrant tomato bags, 3 posh salmon bags, 1 light cyan bag.
shiny beige bags contain 1 muted orange bag, 3 clear olive bags.
posh tomato bags contain 5 muted tomato bags, 5 drab coral bags, 4 pale gold bags.
dark fuchsia bags contain 3 wavy blue bags, 5 faded indigo bags.
dotted green bags contain 5 dull plum bags, 5 muted lavender bags, 3 faded magenta bags, 4 clear white bags.
light salmon bags contain 2 muted purple bags, 5 shiny turquoise bags, 4 muted red bags, 5 posh red bags.
plaid purple bags contain 1 muted indigo bag, 4 pale silver bags, 4 dull crimson bags, 1 posh cyan bag.
light chartreuse bags contain 2 posh brown bags.
dotted black bags contain 3 dull gray bags, 5 muted gray bags, 5 pale maroon bags, 1 vibrant green bag.
mirrored teal bags contain 4 light gold bags, 5 striped maroon bags, 2 pale maroon bags.
dotted coral bags contain 3 dull teal bags.
shiny lime bags contain 3 mirrored gray bags.
shiny chartreuse bags contain no other bags.
clear red bags contain 4 dim tan bags, 4 dotted brown bags, 2 striped orange bags.
clear magenta bags contain 3 pale blue bags, 2 pale crimson bags.
faded black bags contain 5 dark turquoise bags.
wavy violet bags contain 5 light purple bags.
vibrant crimson bags contain 1 shiny gold bag, 1 dotted tomato bag, 1 plaid black bag, 1 drab olive bag.
plaid violet bags contain 1 shiny tan bag, 3 muted gray bags, 4 drab chartreuse bags.
vibrant lime bags contain 3 dark magenta bags, 2 dotted white bags, 4 muted tan bags.
faded violet bags contain 2 drab red bags.
plaid black bags contain 2 clear aqua bags, 2 wavy silver bags, 4 dim violet bags, 2 plaid red bags.
dull orange bags contain 1 clear tan bag, 1 plaid crimson bag, 1 pale chartreuse bag.
vibrant magenta bags contain 4 striped blue bags.
plaid fuchsia bags contain 1 vibrant lime bag, 4 faded indigo bags, 2 wavy fuchsia bags, 1 dim purple bag.
mirrored olive bags contain 1 dark teal bag, 1 pale brown bag, 1 light violet bag, 1 shiny yellow bag.
wavy plum bags contain 5 vibrant cyan bags, 1 pale gold bag, 2 wavy gray bags, 5 pale gray bags.
striped magenta bags contain 5 faded silver bags, 1 mirrored teal bag.
light indigo bags contain 1 light olive bag.
mirrored crimson bags contain 2 vibrant crimson bags.
muted crimson bags contain 2 plaid olive bags.
muted yellow bags contain 1 muted brown bag, 4 striped lavender bags, 1 bright violet bag.
posh lavender bags contain 2 wavy coral bags, 3 light tan bags.
striped indigo bags contain 4 dark brown bags.
dotted red bags contain 4 pale olive bags, 3 dark teal bags, 1 posh fuchsia bag.
plaid indigo bags contain 5 faded gold bags, 4 clear coral bags, 3 dull purple bags, 5 pale brown bags.
plaid magenta bags contain 5 faded black bags, 3 drab aqua bags, 5 vibrant green bags.
light coral bags contain 1 bright gray bag, 4 wavy orange bags, 2 drab coral bags, 1 dark coral bag.
clear brown bags contain 4 plaid aqua bags, 4 plaid coral bags, 5 drab red bags.
drab black bags contain 2 dotted white bags, 1 muted purple bag, 3 posh gold bags.
dull magenta bags contain 1 dull tomato bag, 4 posh gray bags, 4 wavy white bags, 1 pale cyan bag.
muted violet bags contain 3 posh chartreuse bags, 1 dotted magenta bag.
vibrant turquoise bags contain 4 plaid brown bags, 5 drab indigo bags, 4 mirrored green bags.
striped aqua bags contain 2 posh violet bags, 5 shiny blue bags, 3 pale tomato bags.
light teal bags contain 4 faded cyan bags, 2 clear turquoise bags.
clear turquoise bags contain 3 shiny aqua bags, 5 posh tomato bags.
dark maroon bags contain 2 shiny gold bags, 5 faded green bags.
vibrant beige bags contain 5 plaid turquoise bags, 2 shiny gold bags, 2 clear tan bags, 1 wavy black bag.
muted chartreuse bags contain 2 muted white bags, 2 striped tan bags, 1 muted brown bag, 5 posh lime bags.
pale maroon bags contain 5 pale teal bags, 4 dim violet bags, 5 posh teal bags.
vibrant white bags contain 5 light bronze bags, 1 wavy silver bag.
plaid olive bags contain 5 mirrored teal bags, 5 faded gray bags, 4 light olive bags.
dull silver bags contain 5 clear cyan bags, 1 dim tan bag, 5 dim black bags.
bright crimson bags contain 5 dotted indigo bags.
muted teal bags contain 3 striped aqua bags, 4 dotted gray bags, 2 bright salmon bags.
wavy salmon bags contain 5 posh tomato bags.
bright purple bags contain 4 light maroon bags, 2 dotted violet bags.
plaid green bags contain 3 faded black bags, 2 plaid red bags, 4 clear turquoise bags.
wavy gold bags contain 1 bright white bag.
drab violet bags contain 4 vibrant tomato bags.
posh maroon bags contain 3 clear tan bags, 3 light gold bags, 1 dim lime bag.
muted beige bags contain 4 clear white bags, 5 light maroon bags, 2 clear orange bags.
dull turquoise bags contain 4 posh blue bags, 1 mirrored green bag, 5 dotted orange bags, 5 wavy fuchsia bags.
shiny red bags contain 4 dark magenta bags.
light turquoise bags contain 3 dark cyan bags.
posh olive bags contain 3 clear green bags, 5 bright bronze bags, 5 light olive bags.
dim chartreuse bags contain 5 vibrant plum bags.
dark salmon bags contain 1 dotted orange bag, 3 light brown bags, 3 dotted chartreuse bags.
dull teal bags contain 4 wavy gold bags, 5 faded red bags, 4 light turquoise bags.
dark green bags contain 3 pale silver bags, 5 clear tan bags.
bright cyan bags contain 2 striped maroon bags, 1 clear silver bag, 1 dark maroon bag.
wavy crimson bags contain 3 wavy tan bags.
mirrored white bags contain 4 mirrored teal bags, 2 muted silver bags.
dark magenta bags contain 1 drab blue bag, 4 light white bags, 3 dark black bags.
light gold bags contain 4 posh red bags, 1 striped maroon bag, 5 bright purple bags, 4 dotted violet bags.
pale tomato bags contain 5 drab coral bags, 3 posh teal bags, 4 dotted blue bags.
dull purple bags contain 4 posh gold bags.
mirrored gold bags contain 3 mirrored teal bags, 1 striped maroon bag, 2 dotted indigo bags.
dotted turquoise bags contain 2 dim violet bags.
muted magenta bags contain 1 muted red bag.
bright maroon bags contain 3 wavy fuchsia bags, 2 dark magenta bags, 2 dim maroon bags, 1 dotted teal bag.
bright aqua bags contain 5 dim green bags, 2 striped tan bags, 1 faded olive bag.
striped silver bags contain 5 striped aqua bags, 2 striped purple bags, 3 dim blue bags, 3 faded olive bags.
light brown bags contain 4 posh red bags, 3 clear gold bags.
dark brown bags contain 4 clear olive bags.
dim crimson bags contain 4 dotted teal bags, 3 dark salmon bags.
wavy black bags contain 3 drab coral bags, 1 striped purple bag, 2 light brown bags, 4 plaid red bags.
striped coral bags contain 2 plaid blue bags, 5 drab tan bags, 5 light violet bags.
dull blue bags contain 3 pale gold bags, 1 posh crimson bag.
pale blue bags contain 4 dotted blue bags, 3 muted beige bags, 1 faded red bag.
mirrored yellow bags contain 4 muted cyan bags, 2 mirrored tan bags.
dim maroon bags contain 1 muted aqua bag.
drab plum bags contain 2 shiny magenta bags.
clear maroon bags contain 2 drab orange bags, 3 shiny red bags, 1 clear brown bag.
muted red bags contain 5 pale teal bags, 3 dim fuchsia bags, 1 light maroon bag.
dark plum bags contain 5 light salmon bags, 4 dim olive bags.
faded indigo bags contain 1 mirrored red bag, 3 faded lime bags.
bright coral bags contain 3 posh gold bags, 3 vibrant crimson bags.
dark indigo bags contain 5 faded silver bags, 2 dull tomato bags.
drab white bags contain 5 light silver bags.
vibrant violet bags contain 2 pale gray bags, 4 bright white bags, 3 light aqua bags.
mirrored maroon bags contain 1 pale cyan bag, 4 clear bronze bags.
wavy chartreuse bags contain 1 bright brown bag, 4 dim lime bags.
dull brown bags contain 3 bright olive bags.
vibrant yellow bags contain 3 shiny white bags, 2 clear blue bags.
posh bronze bags contain 1 light bronze bag.
dim aqua bags contain 5 wavy yellow bags, 3 muted purple bags, 3 pale crimson bags.
clear gray bags contain 4 faded coral bags, 1 striped violet bag, 5 pale crimson bags, 4 muted lavender bags.
muted plum bags contain 4 mirrored cyan bags.
dim lime bags contain 2 clear plum bags, 2 dim green bags, 5 posh tan bags.
dim red bags contain 2 plaid brown bags.
drab bronze bags contain 4 faded plum bags, 4 clear plum bags, 1 posh cyan bag, 1 dark cyan bag.
shiny purple bags contain 5 posh beige bags, 4 pale fuchsia bags, 2 wavy brown bags, 2 shiny maroon bags.
dull beige bags contain 1 mirrored indigo bag, 2 drab cyan bags, 1 dim fuchsia bag.
wavy blue bags contain 4 dotted maroon bags, 3 light maroon bags.
faded white bags contain 2 vibrant purple bags, 1 muted purple bag.
pale teal bags contain no other bags.
bright tan bags contain 3 clear indigo bags, 2 pale orange bags.
dull crimson bags contain 3 pale maroon bags, 3 vibrant bronze bags.
posh black bags contain 1 muted tomato bag.
vibrant maroon bags contain 5 mirrored crimson bags, 4 wavy beige bags.
dark lime bags contain 4 dim yellow bags, 1 pale beige bag, 1 vibrant beige bag.
bright white bags contain 2 dark turquoise bags.
faded plum bags contain 1 vibrant indigo bag, 5 dotted maroon bags, 1 vibrant bronze bag.
pale violet bags contain 2 pale lavender bags, 4 light brown bags, 5 vibrant tomato bags.
wavy purple bags contain 2 shiny tomato bags, 2 clear maroon bags, 3 posh bronze bags, 4 dull aqua bags.
plaid yellow bags contain 4 pale tomato bags, 2 dotted magenta bags, 5 wavy violet bags.
bright silver bags contain 5 light gold bags, 2 posh tan bags, 4 faded gray bags.
dark orange bags contain 4 dull yellow bags, 5 dull salmon bags.
wavy coral bags contain 5 dim lavender bags, 2 mirrored teal bags, 1 shiny chartreuse bag, 2 light gold bags.
pale aqua bags contain 1 faded plum bag, 5 vibrant plum bags.
dotted brown bags contain 2 light purple bags, 4 dim beige bags, 5 pale white bags.
plaid blue bags contain 1 shiny red bag, 5 light silver bags, 5 clear orange bags.
dim violet bags contain 3 posh teal bags.
dull yellow bags contain 5 muted aqua bags.
shiny yellow bags contain 5 muted aqua bags, 2 drab white bags, 5 muted purple bags.
dotted maroon bags contain 4 dim green bags, 2 faded silver bags.
bright brown bags contain 4 striped bronze bags.
posh crimson bags contain 2 posh red bags, 1 dotted indigo bag, 4 muted red bags.
dim orange bags contain 2 light tan bags, 4 dotted salmon bags.
mirrored beige bags contain 4 dim bronze bags, 5 vibrant salmon bags, 4 dim maroon bags.
shiny olive bags contain 5 dotted orange bags.
wavy tan bags contain 1 wavy brown bag, 1 faded silver bag.
mirrored magenta bags contain 5 drab teal bags, 3 striped bronze bags, 3 striped magenta bags, 5 dark tan bags.
muted brown bags contain 1 light indigo bag, 4 dotted blue bags.
vibrant aqua bags contain 1 shiny red bag, 5 wavy gold bags.
dark violet bags contain 2 dim orange bags, 5 dark purple bags, 2 pale yellow bags.
plaid teal bags contain 3 vibrant bronze bags.
shiny gold bags contain 5 drab red bags, 2 mirrored green bags, 2 muted tomato bags, 1 striped magenta bag.
wavy bronze bags contain 2 vibrant green bags, 2 plaid orange bags, 2 vibrant orange bags.
dark tomato bags contain 4 posh indigo bags.
drab red bags contain no other bags.
clear silver bags contain 1 plaid olive bag.
striped cyan bags contain 3 wavy silver bags, 2 faded indigo bags.
dark purple bags contain 1 wavy violet bag, 5 clear olive bags, 3 drab indigo bags, 5 striped purple bags.
dotted plum bags contain 4 vibrant purple bags, 3 muted lavender bags, 1 wavy coral bag.
posh yellow bags contain 5 light salmon bags, 2 light bronze bags.
dim tomato bags contain 3 pale white bags.
drab lime bags contain 3 drab chartreuse bags, 4 clear silver bags, 4 drab aqua bags.
plaid coral bags contain 2 bright olive bags.
mirrored salmon bags contain 3 plaid green bags.
faded chartreuse bags contain 2 light cyan bags, 5 pale tomato bags.
pale crimson bags contain 5 bright white bags, 3 shiny turquoise bags.
pale brown bags contain 4 bright silver bags.
shiny bronze bags contain 5 dull chartreuse bags, 4 dotted gray bags, 3 shiny blue bags, 1 dull blue bag.
faded red bags contain 2 muted gray bags.
dark lavender bags contain 5 dim coral bags, 4 muted gray bags, 1 shiny yellow bag.
faded purple bags contain 2 dotted white bags.
mirrored silver bags contain 3 pale maroon bags, 2 pale cyan bags, 4 dark chartreuse bags, 3 bright plum bags.
dull violet bags contain 1 dim coral bag, 3 wavy lavender bags.
faded beige bags contain 4 plaid bronze bags, 1 light salmon bag, 2 light brown bags.
vibrant orange bags contain 1 faded cyan bag, 2 vibrant olive bags, 2 bright plum bags.
vibrant purple bags contain 5 dotted orange bags, 1 striped aqua bag, 4 clear white bags, 3 dim olive bags.
faded crimson bags contain 1 clear lavender bag, 3 dim lavender bags, 3 dim cyan bags, 2 wavy tan bags.
dark yellow bags contain 1 plaid silver bag, 3 wavy maroon bags.
vibrant brown bags contain 5 dotted chartreuse bags, 4 clear silver bags, 4 dull lavender bags.
wavy lavender bags contain 4 dull gray bags.
bright green bags contain 5 striped gold bags.
faded magenta bags contain 5 dull beige bags.
posh white bags contain 2 dark coral bags.
muted green bags contain 1 wavy lavender bag, 1 striped aqua bag.
plaid turquoise bags contain 1 striped brown bag, 4 mirrored maroon bags.
plaid lavender bags contain 4 striped tan bags, 2 posh brown bags, 5 shiny brown bags.
pale fuchsia bags contain 5 light brown bags, 3 vibrant lime bags.
light gray bags contain 3 drab violet bags.
dim green bags contain no other bags.
light olive bags contain 4 vibrant bronze bags.
dotted aqua bags contain 5 muted red bags.
vibrant fuchsia bags contain 5 dull crimson bags, 5 dotted violet bags.
clear crimson bags contain 5 dotted tomato bags, 3 posh crimson bags, 5 vibrant magenta bags.
pale orange bags contain 5 mirrored indigo bags, 5 muted purple bags, 4 plaid orange bags.
mirrored lavender bags contain 4 dotted orange bags, 3 posh violet bags.
dotted tan bags contain 5 mirrored gray bags.
dim bronze bags contain 3 mirrored olive bags, 3 plaid magenta bags, 5 dim black bags, 2 drab blue bags.
clear olive bags contain 3 bright purple bags, 4 dim lime bags, 5 dim fuchsia bags.
dotted blue bags contain 1 dim green bag, 3 drab red bags, 2 posh gold bags.
shiny gray bags contain 3 pale lavender bags, 1 clear gold bag, 2 drab violet bags, 2 clear bronze bags.
bright plum bags contain 3 muted yellow bags, 4 posh chartreuse bags, 3 posh brown bags, 3 dim orange bags.
shiny violet bags contain 5 dim coral bags.
posh lime bags contain 3 plaid silver bags.
light beige bags contain 5 pale yellow bags, 3 light bronze bags, 5 pale turquoise bags.
drab gray bags contain 4 bright purple bags, 5 faded gold bags, 2 dim green bags.
muted aqua bags contain 4 clear white bags.
mirrored blue bags contain 2 vibrant green bags, 2 drab gray bags.
posh magenta bags contain 2 striped magenta bags, 5 dim cyan bags, 5 plaid orange bags, 1 wavy black bag.
dim yellow bags contain 2 muted purple bags, 1 striped black bag, 3 wavy coral bags.
dull indigo bags contain 3 posh fuchsia bags, 1 dotted beige bag.
posh gray bags contain 5 drab black bags.
dark blue bags contain 4 dim gold bags, 3 drab olive bags, 1 light cyan bag, 2 light tomato bags.
mirrored red bags contain 5 shiny white bags, 1 mirrored green bag, 4 wavy black bags, 1 dark brown bag.
mirrored violet bags contain 3 dim tan bags, 4 dark fuchsia bags, 4 pale turquoise bags.
shiny black bags contain 5 clear orange bags, 2 vibrant silver bags, 2 plaid maroon bags, 3 light olive bags.
vibrant chartreuse bags contain 4 dull salmon bags, 3 bright beige bags, 1 faded blue bag, 2 plaid brown bags.
dull cyan bags contain 3 faded green bags.
bright gold bags contain 3 posh plum bags.
vibrant olive bags contain 5 mirrored coral bags, 3 dotted lime bags, 5 drab blue bags, 2 dotted green bags.
faded maroon bags contain 4 mirrored green bags, 2 light lime bags, 3 light bronze bags.
vibrant red bags contain 2 posh lime bags, 1 dull maroon bag.
dull bronze bags contain 5 vibrant chartreuse bags.
vibrant bronze bags contain 2 vibrant tomato bags, 3 mirrored teal bags.
pale black bags contain 1 muted silver bag, 5 mirrored teal bags, 2 shiny blue bags.
dull maroon bags contain 1 clear cyan bag.
dotted crimson bags contain 5 posh black bags, 1 dotted teal bag, 4 vibrant salmon bags, 4 shiny silver bags.
striped tomato bags contain 5 drab tomato bags, 2 faded coral bags, 2 dim salmon bags.
bright bronze bags contain 5 plaid red bags, 4 striped yellow bags.
dark aqua bags contain 4 bright purple bags, 1 striped gold bag.
striped teal bags contain 4 striped black bags, 3 clear indigo bags.
dark olive bags contain 2 pale cyan bags, 5 mirrored tan bags.
dark teal bags contain 1 posh gold bag, 1 plaid orange bag, 1 vibrant bronze bag, 1 mirrored teal bag.
faded green bags contain 5 vibrant fuchsia bags, 3 dim olive bags.
posh brown bags contain 4 drab lime bags, 2 mirrored fuchsia bags, 3 shiny lime bags, 2 dim violet bags.
striped lavender bags contain 2 plaid red bags, 5 dark brown bags, 3 clear turquoise bags.
shiny indigo bags contain 2 striped lavender bags, 1 light gray bag.
plaid orange bags contain 1 pale teal bag, 5 dim violet bags, 5 vibrant bronze bags, 3 light maroon bags.
dull salmon bags contain 1 striped bronze bag, 4 shiny aqua bags, 4 dark brown bags.
plaid white bags contain 1 dim green bag.
drab lavender bags contain 2 dotted maroon bags, 3 pale aqua bags, 1 light olive bag.
striped olive bags contain 5 striped magenta bags.
mirrored gray bags contain 2 dim lavender bags, 2 shiny chartreuse bags.
dull coral bags contain 1 mirrored gold bag, 5 clear gold bags, 5 clear olive bags, 2 posh tomato bags.
pale beige bags contain 2 dark indigo bags, 4 dim beige bags.
posh teal bags contain 1 dim green bag, 3 dim fuchsia bags, 1 pale teal bag, 2 dotted indigo bags.
mirrored turquoise bags contain 4 dim olive bags, 2 plaid tomato bags.
dim turquoise bags contain 2 bright yellow bags, 1 striped lavender bag.
light violet bags contain 4 faded gold bags, 3 clear plum bags, 1 dark teal bag.
dark cyan bags contain 3 drab red bags, 4 pale maroon bags.
shiny crimson bags contain 5 dotted turquoise bags, 1 vibrant fuchsia bag, 5 dotted lime bags, 2 wavy green bags.
muted lime bags contain 2 light brown bags, 5 plaid tomato bags, 4 plaid aqua bags.
vibrant tan bags contain 4 wavy fuchsia bags.
wavy maroon bags contain 4 dull white bags, 5 dark crimson bags, 5 mirrored salmon bags, 4 vibrant purple bags.
muted indigo bags contain 5 shiny red bags.
clear violet bags contain 2 plaid green bags.
drab teal bags contain 2 pale cyan bags, 1 shiny turquoise bag.
wavy green bags contain 5 plaid indigo bags, 3 muted silver bags, 5 light brown bags.
striped crimson bags contain 3 shiny aqua bags.
drab purple bags contain 3 drab orange bags, 3 dark aqua bags, 1 bright lavender bag.
plaid aqua bags contain 1 plaid tomato bag.
striped green bags contain 2 vibrant tomato bags, 2 faded plum bags.
drab tomato bags contain 4 posh black bags, 3 dull brown bags, 1 drab cyan bag.
dotted bronze bags contain 1 clear indigo bag.
pale white bags contain 5 mirrored green bags, 2 dark turquoise bags, 3 dull olive bags, 4 drab indigo bags.
drab yellow bags contain 2 dotted orange bags, 4 light turquoise bags, 4 light salmon bags, 2 dotted tomato bags.
pale green bags contain 3 muted gold bags, 3 shiny turquoise bags.
dark tan bags contain 4 muted cyan bags, 5 dotted tomato bags, 2 dark indigo bags.
plaid tan bags contain 4 vibrant olive bags, 1 plaid aqua bag, 3 dotted coral bags, 4 bright violet bags.
shiny aqua bags contain 2 dull brown bags, 1 vibrant cyan bag, 2 dim lime bags, 5 light bronze bags.
bright turquoise bags contain 2 plaid yellow bags, 3 posh lavender bags, 1 pale yellow bag.
vibrant gold bags contain 1 clear tomato bag, 4 clear turquoise bags, 4 dark bronze bags.
posh cyan bags contain 3 dotted green bags, 5 plaid tomato bags, 3 wavy crimson bags, 2 striped olive bags.
clear salmon bags contain 3 plaid fuchsia bags, 5 muted bronze bags, 5 dull green bags, 2 pale brown bags.
drab maroon bags contain 5 dull crimson bags, 2 shiny white bags, 5 light purple bags.
clear tan bags contain 5 dull lime bags, 5 muted red bags, 2 clear cyan bags.
pale gray bags contain 3 shiny white bags.
vibrant teal bags contain 1 clear green bag, 1 dull beige bag.
vibrant plum bags contain 4 muted red bags, 2 faded blue bags, 5 vibrant tomato bags.
dark coral bags contain 2 plaid tomato bags, 1 bright yellow bag, 2 mirrored gray bags.
wavy indigo bags contain 1 mirrored tan bag, 1 wavy lavender bag.
dotted fuchsia bags contain 2 vibrant silver bags, 3 mirrored tan bags.
muted gold bags contain 3 muted red bags, 1 clear olive bag.
striped fuchsia bags contain 2 clear aqua bags, 4 mirrored coral bags, 3 muted gray bags, 2 dark beige bags.
striped maroon bags contain no other bags.
bright lavender bags contain 2 faded indigo bags, 1 dotted violet bag, 5 posh tomato bags, 3 clear indigo bags.
posh gold bags contain 1 dim violet bag, 2 shiny chartreuse bags.
drab olive bags contain 4 faded silver bags.
pale chartreuse bags contain 4 striped teal bags.
mirrored lime bags contain 5 dotted plum bags, 1 light yellow bag, 3 pale fuchsia bags.
clear bronze bags contain 4 plaid brown bags.
wavy tomato bags contain 4 faded lavender bags, 3 dull aqua bags, 1 drab green bag, 3 vibrant gray bags.
dim brown bags contain 4 dull teal bags, 2 vibrant black bags, 1 mirrored gold bag.
bright fuchsia bags contain 4 faded lavender bags, 1 dull crimson bag, 1 mirrored brown bag, 5 dark indigo bags.
muted gray bags contain 1 dull olive bag.
dull white bags contain 1 light maroon bag, 4 dark lavender bags, 2 posh red bags.
dull black bags contain 5 dark green bags, 4 bright lime bags, 4 mirrored gray bags.
dull tomato bags contain 4 dotted tomato bags.
pale coral bags contain 1 mirrored white bag, 5 clear aqua bags, 4 dim blue bags.
posh indigo bags contain 2 bright bronze bags.
plaid gold bags contain 4 dark maroon bags, 4 shiny lavender bags, 1 plaid tomato bag, 3 bright yellow bags.
plaid gray bags contain 4 muted bronze bags, 2 posh chartreuse bags, 5 pale tomato bags, 3 drab coral bags.
dim beige bags contain 4 dim blue bags, 4 dark lavender bags.
bright olive bags contain no other bags.
clear aqua bags contain 4 wavy fuchsia bags, 5 dim green bags.
posh violet bags contain 2 vibrant indigo bags, 3 posh tomato bags, 4 clear gold bags, 5 dim green bags.
faded coral bags contain 4 light purple bags, 4 mirrored salmon bags, 5 pale maroon bags.
dotted chartreuse bags contain 2 clear aqua bags, 4 plaid coral bags.
striped orange bags contain 5 bright tan bags, 5 pale white bags, 5 mirrored lavender bags.
bright tomato bags contain 5 muted white bags.
shiny silver bags contain 1 dotted orange bag, 2 light olive bags, 1 striped gold bag.
striped yellow bags contain 1 shiny turquoise bag.
faded aqua bags contain 5 shiny cyan bags, 3 dotted indigo bags, 4 faded fuchsia bags.
striped beige bags contain 1 bright white bag, 5 dim lavender bags, 5 striped black bags, 1 wavy black bag.
shiny orange bags contain 4 dark aqua bags.
striped white bags contain 3 vibrant fuchsia bags, 1 dotted teal bag, 5 dotted green bags, 2 shiny white bags.
bright black bags contain 5 pale blue bags, 2 drab teal bags, 1 dull gray bag.
shiny lavender bags contain 1 pale gold bag, 2 bright crimson bags, 2 pale maroon bags.
shiny maroon bags contain 2 wavy white bags, 2 muted aqua bags, 3 plaid gold bags.
drab cyan bags contain 4 posh crimson bags, 5 drab red bags, 5 bright purple bags.
dark bronze bags contain 5 posh teal bags.
shiny turquoise bags contain 2 shiny gold bags, 5 mirrored teal bags, 5 mirrored gray bags, 1 drab cyan bag.
dark turquoise bags contain 1 dim violet bag, 5 mirrored teal bags.
light lime bags contain 4 drab chartreuse bags.
light yellow bags contain 5 wavy olive bags, 2 wavy gray bags, 4 bright red bags, 5 shiny violet bags.
posh aqua bags contain 3 vibrant salmon bags.
drab silver bags contain 3 pale tan bags.
pale tan bags contain 3 wavy white bags.
light white bags contain 4 wavy black bags, 2 dark teal bags, 2 faded blue bags.
shiny teal bags contain 5 wavy gold bags.
shiny tomato bags contain 3 faded violet bags.
wavy brown bags contain 1 dim black bag, 1 bright yellow bag.
dim tan bags contain 2 clear teal bags, 5 drab teal bags, 4 posh lime bags.
faded cyan bags contain 1 pale plum bag, 4 posh gold bags, 4 posh yellow bags.
dotted magenta bags contain 4 drab tomato bags, 5 drab yellow bags, 2 clear maroon bags.
clear green bags contain 5 striped maroon bags, 4 shiny aqua bags.
clear fuchsia bags contain 5 dotted chartreuse bags, 5 pale plum bags, 2 muted red bags.
bright lime bags contain 3 dark salmon bags, 3 bright cyan bags, 4 striped black bags, 4 posh violet bags.
bright violet bags contain 1 light olive bag, 2 dark coral bags, 1 dull beige bag, 5 plaid maroon bags.
vibrant lavender bags contain 5 dim green bags, 1 plaid violet bag, 4 dotted coral bags.
wavy silver bags contain 2 mirrored green bags, 4 clear olive bags, 5 dark beige bags, 5 plaid orange bags.
clear orange bags contain 4 dotted orange bags, 3 bright silver bags, 5 dotted tomato bags, 4 striped purple bags.
light crimson bags contain 5 striped teal bags, 1 striped coral bag, 1 pale tomato bag, 2 dark crimson bags.
bright gray bags contain 3 posh tan bags.
mirrored indigo bags contain 1 mirrored green bag.
dull chartreuse bags contain 4 pale gold bags, 2 drab lavender bags, 3 shiny cyan bags.
pale salmon bags contain 5 drab purple bags, 2 dark olive bags, 4 mirrored silver bags.
bright indigo bags contain 5 striped beige bags, 5 shiny lime bags.
dim lavender bags contain 5 striped maroon bags.
bright magenta bags contain 2 plaid coral bags, 5 shiny aqua bags, 1 light purple bag.
muted purple bags contain 4 shiny turquoise bags, 1 shiny chartreuse bag, 3 muted tomato bags, 1 dotted aqua bag.
muted cyan bags contain 4 wavy black bags, 2 faded plum bags, 1 dull coral bag, 3 light tomato bags.
shiny plum bags contain 5 pale gray bags, 3 vibrant aqua bags.
dull lime bags contain 4 drab cyan bags, 1 posh gold bag, 4 bright purple bags, 3 posh tan bags.
faded teal bags contain 3 bright purple bags, 4 dotted magenta bags, 4 plaid olive bags.
clear chartreuse bags contain 2 dark brown bags, 1 pale lavender bag, 2 dark coral bags.
dotted tomato bags contain 1 dim green bag, 2 posh tomato bags.
pale silver bags contain 2 pale teal bags, 4 light purple bags, 4 bright yellow bags, 4 clear plum bags.
posh purple bags contain 2 faded tan bags, 3 clear aqua bags, 4 striped lavender bags, 3 dark teal bags.
striped bronze bags contain 4 drab red bags, 5 mirrored gray bags.
striped black bags contain 3 wavy coral bags, 3 faded blue bags, 5 bright olive bags, 2 dark bronze bags.
dark chartreuse bags contain 5 posh tomato bags.
muted white bags contain 2 mirrored gray bags, 5 dark cyan bags, 3 dotted indigo bags.
clear indigo bags contain 3 dark coral bags, 1 pale green bag, 2 plaid orange bags, 4 dim lime bags.
faded tan bags contain 3 dull purple bags, 2 dim orange bags.
clear yellow bags contain 1 vibrant fuchsia bag, 5 faded silver bags, 5 faded black bags.
dark gray bags contain 5 striped cyan bags.
clear plum bags contain 2 drab indigo bags, 5 pale maroon bags.
posh fuchsia bags contain 2 muted lavender bags, 5 posh red bags.
vibrant black bags contain 1 posh gold bag, 1 shiny white bag.
dim salmon bags contain 5 muted tan bags, 2 muted green bags, 2 pale bronze bags.
faded brown bags contain 3 dim tan bags.
mirrored brown bags contain 1 drab bronze bag, 3 wavy coral bags, 4 posh fuchsia bags.
dim gold bags contain 2 mirrored lavender bags, 5 pale gray bags.
faded fuchsia bags contain 3 wavy lavender bags, 5 shiny blue bags, 4 muted tomato bags.
mirrored chartreuse bags contain 2 faded aqua bags, 4 dark coral bags, 4 wavy beige bags, 5 dark orange bags.
muted fuchsia bags contain 3 light olive bags.
dotted silver bags contain 5 dotted turquoise bags, 3 dark cyan bags, 2 plaid red bags.
plaid lime bags contain 5 dull blue bags.
dim gray bags contain 4 striped magenta bags, 3 dotted indigo bags, 2 dim violet bags, 3 light olive bags.
wavy lime bags contain 2 bright salmon bags, 3 shiny cyan bags, 4 light gray bags, 4 shiny plum bags.
striped lime bags contain 5 posh teal bags.
dull red bags contain 3 mirrored tan bags, 3 dim tomato bags, 5 striped crimson bags.
faded lavender bags contain 1 bright indigo bag, 1 dim purple bag, 5 mirrored gray bags, 4 clear cyan bags.
wavy aqua bags contain 1 wavy gray bag, 3 dark crimson bags.
faded turquoise bags contain 1 drab plum bag, 5 dull gray bags, 4 plaid black bags, 1 wavy crimson bag.
dotted salmon bags contain 4 posh teal bags.
clear coral bags contain 5 drab tomato bags.
vibrant blue bags contain 4 dim lavender bags, 4 dark cyan bags.
muted coral bags contain 5 vibrant olive bags, 1 clear plum bag, 1 clear blue bag.
vibrant coral bags contain 5 vibrant silver bags, 2 plaid brown bags, 4 wavy brown bags.
mirrored aqua bags contain 4 bright lavender bags, 4 striped lavender bags, 1 posh fuchsia bag.
clear gold bags contain 1 posh tan bag, 1 dark beige bag, 5 striped gold bags.
dull aqua bags contain 4 dull plum bags, 2 light indigo bags.
clear cyan bags contain 5 light maroon bags, 5 posh tan bags, 3 dim lavender bags.
dotted olive bags contain 1 mirrored maroon bag, 2 dotted red bags, 4 drab lime bags.
wavy yellow bags contain 4 light silver bags, 4 dotted orange bags.
faded salmon bags contain 1 shiny lavender bag, 4 muted tomato bags, 3 plaid coral bags, 3 pale green bags.
dim blue bags contain 2 dim black bags.
faded tomato bags contain 3 shiny magenta bags.
light magenta bags contain 5 dim olive bags, 3 muted lavender bags.
muted turquoise bags contain 4 posh gold bags, 2 wavy beige bags, 3 posh magenta bags.
light purple bags contain 3 light maroon bags.
pale indigo bags contain 2 light green bags, 5 plaid bronze bags.
dim fuchsia bags contain no other bags.
plaid chartreuse bags contain 3 shiny silver bags, 1 posh teal bag.
plaid salmon bags contain 5 drab lime bags, 4 light aqua bags, 2 striped tan bags.
drab coral bags contain no other bags.
dotted gold bags contain 2 clear teal bags, 2 posh salmon bags, 1 plaid green bag, 5 muted tomato bags.
dull olive bags contain 2 dim lavender bags.
dotted purple bags contain 5 vibrant white bags, 5 wavy black bags.
dark crimson bags contain 4 posh chartreuse bags, 3 muted green bags, 3 dull plum bags, 5 muted beige bags.
mirrored tomato bags contain 2 clear crimson bags, 4 mirrored indigo bags, 2 muted black bags, 2 dark gray bags.
muted blue bags contain 5 pale brown bags.
wavy beige bags contain 5 plaid red bags.
muted black bags contain 3 muted magenta bags, 2 clear tomato bags, 1 pale red bag.
mirrored bronze bags contain 5 bright olive bags, 5 vibrant cyan bags, 2 drab cyan bags.
vibrant green bags contain 2 dull brown bags, 4 wavy white bags, 3 pale teal bags, 4 dark bronze bags.
dotted orange bags contain 5 light gold bags, 5 vibrant tomato bags, 3 light silver bags, 4 drab cyan bags.
clear purple bags contain 4 dull fuchsia bags.
mirrored green bags contain 2 muted red bags, 2 dim lavender bags.
wavy red bags contain 1 posh yellow bag, 2 shiny coral bags.
drab chartreuse bags contain 5 dull purple bags, 2 bright purple bags, 3 faded silver bags, 4 muted lavender bags.
dim indigo bags contain 1 light red bag, 4 wavy olive bags.
drab crimson bags contain 5 muted indigo bags, 5 vibrant crimson bags.
wavy olive bags contain 3 light black bags, 2 wavy plum bags.
dark silver bags contain 4 dull fuchsia bags, 3 dotted chartreuse bags.
pale olive bags contain 1 dark purple bag, 1 drab yellow bag, 1 vibrant coral bag.
posh silver bags contain 4 faded magenta bags, 5 muted coral bags, 4 posh cyan bags, 2 faded gray bags.
clear white bags contain 4 shiny blue bags.
light silver bags contain 3 mirrored green bags, 2 muted red bags, 1 muted tomato bag, 3 clear olive bags.
faded gray bags contain 5 dim green bags, 5 pale teal bags, 4 posh crimson bags, 3 dotted indigo bags.
clear teal bags contain 2 posh chartreuse bags, 2 posh blue bags.
dull green bags contain 5 muted tan bags, 3 faded gray bags, 2 dark tan bags.
dotted yellow bags contain 1 dim aqua bag, 5 dotted blue bags, 1 plaid teal bag, 2 dim salmon bags.
dotted indigo bags contain 1 muted red bag.
pale gold bags contain 1 mirrored green bag, 2 faded gray bags, 4 drab olive bags.
pale magenta bags contain 1 pale gray bag.
drab orange bags contain 4 dull beige bags, 1 dim gray bag.
light maroon bags contain no other bags.
dim silver bags contain 2 dull olive bags, 2 muted lavender bags, 5 dark fuchsia bags, 5 dotted tan bags.
shiny magenta bags contain 5 light purple bags.
shiny green bags contain 2 dim green bags, 1 pale plum bag, 2 striped teal bags.
drab magenta bags contain 1 plaid yellow bag, 3 bright crimson bags, 4 shiny salmon bags.
shiny salmon bags contain 4 dark bronze bags, 1 pale aqua bag, 5 posh red bags, 2 light gold bags.
mirrored cyan bags contain 2 bright olive bags, 2 bright aqua bags, 4 shiny turquoise bags.
drab aqua bags contain 1 drab olive bag, 5 shiny white bags, 2 dim gray bags.
wavy white bags contain 1 plaid red bag.
clear black bags contain 1 dim fuchsia bag, 5 pale white bags, 3 drab fuchsia bags.
dotted cyan bags contain 3 wavy aqua bags, 4 shiny brown bags, 4 faded tan bags.
dim magenta bags contain 4 striped orange bags, 2 mirrored turquoise bags, 3 vibrant turquoise bags, 3 pale chartreuse bags.
faded silver bags contain 5 dim fuchsia bags, 2 bright purple bags.
faded olive bags contain 3 dull lavender bags, 2 striped salmon bags, 1 bright yellow bag.
faded lime bags contain 4 posh tan bags, 4 dotted lavender bags, 3 striped magenta bags.
dark white bags contain 2 bright beige bags, 3 shiny chartreuse bags.
striped brown bags contain 5 muted lavender bags.
dotted lime bags contain 1 mirrored green bag, 4 dotted chartreuse bags, 2 shiny cyan bags, 1 bright purple bag.
bright beige bags contain 4 dull gray bags, 3 wavy violet bags, 5 light silver bags, 5 drab white bags.
dark beige bags contain 3 light gold bags, 1 muted tomato bag, 4 pale teal bags, 4 posh crimson bags.
dim olive bags contain 4 dark cyan bags.
plaid plum bags contain 1 clear tan bag, 4 posh brown bags.
wavy magenta bags contain 4 dotted plum bags, 2 dull tan bags.
drab gold bags contain 4 dark cyan bags, 2 clear yellow bags.
muted orange bags contain 2 faded tan bags, 5 vibrant salmon bags.
pale yellow bags contain 3 light turquoise bags, 3 plaid maroon bags, 2 dull salmon bags.
plaid tomato bags contain 2 dark beige bags.
dim purple bags contain 5 posh salmon bags, 2 dim lime bags, 2 dotted white bags.
bright red bags contain 4 dark teal bags, 3 shiny cyan bags.
bright salmon bags contain 4 pale aqua bags, 3 clear orange bags, 3 plaid black bags, 5 faded aqua bags.
plaid crimson bags contain 4 plaid tan bags, 4 dim aqua bags.
striped violet bags contain 2 dotted olive bags, 2 dotted red bags, 4 shiny gold bags.
vibrant tomato bags contain 3 dim lime bags.
drab turquoise bags contain 5 shiny purple bags, 1 light green bag, 1 pale chartreuse bag.
wavy turquoise bags contain 1 dark teal bag, 5 shiny fuchsia bags, 4 muted brown bags, 4 bright green bags.
striped plum bags contain 3 bright chartreuse bags, 1 dotted violet bag, 1 posh maroon bag.
mirrored plum bags contain 4 plaid indigo bags, 5 dotted white bags.
muted salmon bags contain 5 faded magenta bags, 3 plaid blue bags.
shiny brown bags contain 3 drab salmon bags.
drab blue bags contain 3 drab olive bags, 5 muted red bags, 2 bright purple bags.
striped gray bags contain 3 clear olive bags, 2 muted coral bags.
bright yellow bags contain 2 dull olive bags, 5 dark turquoise bags, 5 posh teal bags.
dim plum bags contain 2 dim cyan bags, 5 vibrant crimson bags.
muted lavender bags contain 2 clear bronze bags.
muted silver bags contain 3 vibrant salmon bags, 5 muted cyan bags, 1 dotted black bag.
mirrored orange bags contain 2 dull olive bags, 4 striped beige bags, 3 shiny aqua bags, 2 striped salmon bags.
dim teal bags contain 2 drab blue bags.
plaid brown bags contain 1 pale maroon bag, 4 light salmon bags, 1 vibrant indigo bag, 5 clear cyan bags.
bright chartreuse bags contain 4 plaid coral bags, 2 dull crimson bags, 3 plaid aqua bags, 2 faded blue bags.
dotted gray bags contain 1 dotted indigo bag, 2 posh crimson bags.
drab indigo bags contain 1 dotted violet bag, 1 dim fuchsia bag, 4 muted red bags, 4 striped maroon bags.
plaid bronze bags contain 3 drab plum bags, 1 posh violet bag, 2 dark tan bags, 3 plaid white bags.
striped salmon bags contain 3 clear brown bags.
dull lavender bags contain 4 pale green bags.
dull gray bags contain 4 drab indigo bags, 4 light salmon bags, 2 plaid coral bags, 3 striped magenta bags.
mirrored purple bags contain 2 vibrant brown bags, 1 plaid teal bag, 4 drab red bags, 4 plaid turquoise bags.
dull gold bags contain 3 drab teal bags.
light fuchsia bags contain 2 clear tan bags, 1 posh tan bag.
dim white bags contain 1 bright beige bag.
light green bags contain 1 dotted red bag, 4 muted gray bags, 5 dotted orange bags, 3 dim chartreuse bags.
bright teal bags contain 5 bright bronze bags, 2 pale green bags.
striped purple bags contain 1 dark beige bag.
muted tan bags contain 4 pale silver bags, 2 bright lavender bags, 4 drab cyan bags.
light blue bags contain 5 drab white bags, 1 pale olive bag.
dim cyan bags contain 1 wavy fuchsia bag, 5 posh teal bags.
striped chartreuse bags contain 4 bright beige bags, 1 muted lavender bag.
light lavender bags contain 2 posh lavender bags, 1 dim lavender bag.
striped gold bags contain 1 posh salmon bag, 3 mirrored gray bags, 1 faded silver bag.
light orange bags contain 4 dark black bags.
plaid silver bags contain 5 posh salmon bags, 3 vibrant tomato bags.
dotted white bags contain 3 dim fuchsia bags, 4 shiny gold bags, 2 bright olive bags, 4 muted purple bags.
faded bronze bags contain 3 pale green bags, 3 light yellow bags, 1 clear teal bag.
striped turquoise bags contain 4 mirrored aqua bags, 2 wavy orange bags, 1 pale lavender bag, 4 drab aqua bags.
clear lime bags contain 1 plaid green bag, 3 pale gold bags, 2 bright gray bags.
drab salmon bags contain 3 dull tomato bags.
plaid red bags contain 5 pale brown bags.
posh coral bags contain 2 dim violet bags, 4 dotted teal bags, 2 plaid red bags, 4 muted green bags.
light bronze bags contain 4 light purple bags.
faded orange bags contain 2 light teal bags.
dotted lavender bags contain 2 light olive bags, 3 muted tomato bags.
bright orange bags contain 3 light gray bags, 4 striped purple bags, 5 dull tomato bags.
mirrored coral bags contain 3 faded gray bags, 5 pale green bags, 4 pale aqua bags, 4 muted bronze bags.
dull plum bags contain 4 posh crimson bags, 4 clear cyan bags, 4 shiny white bags, 2 dotted maroon bags.
shiny blue bags contain 5 dim lime bags, 2 dim gray bags, 5 dark cyan bags, 3 posh teal bags.
mirrored fuchsia bags contain 4 muted tomato bags, 5 dotted chartreuse bags, 1 light red bag, 2 bright yellow bags.
dotted teal bags contain 1 dotted gray bag, 1 muted brown bag.
mirrored tan bags contain 2 clear aqua bags, 4 dim violet bags, 1 wavy gray bag.
posh chartreuse bags contain 2 faded blue bags, 4 dark coral bags, 2 light maroon bags, 5 dark purple bags.
shiny tan bags contain 1 wavy salmon bag, 2 shiny red bags, 5 clear coral bags, 3 wavy gold bags.
vibrant salmon bags contain 3 clear brown bags, 3 pale gold bags, 5 clear blue bags.
plaid beige bags contain 5 vibrant lavender bags, 2 dim brown bags, 4 dull yellow bags.
muted olive bags contain 3 vibrant blue bags, 5 shiny crimson bags, 5 pale beige bags, 2 dotted chartreuse bags.
clear beige bags contain 4 drab coral bags, 4 dark maroon bags, 1 light indigo bag.
dull fuchsia bags contain 2 pale magenta bags, 1 dotted indigo bag.
dark gold bags contain 3 posh crimson bags, 3 mirrored lavender bags.
pale plum bags contain 1 light bronze bag, 5 dotted violet bags, 2 dark salmon bags.
drab fuchsia bags contain 4 dull brown bags, 5 muted bronze bags.
mirrored black bags contain 1 muted silver bag, 3 plaid gray bags, 4 bright purple bags.
posh blue bags contain 3 dull beige bags, 5 dull olive bags.
posh beige bags contain 3 vibrant turquoise bags, 3 dotted lime bags.
light aqua bags contain 2 mirrored teal bags, 1 vibrant lime bag, 1 dim olive bag.
muted tomato bags contain 5 dim lavender bags.
dim coral bags contain 4 shiny magenta bags, 4 drab violet bags, 5 clear brown bags.
| true |
23535d09eecb2552b0ca9ce654720ae53f3c7c60
|
Ruby
|
yuya-takeyama/flagship
|
/lib/flagship.rb
|
UTF-8
| 1,840 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
require "flagship/version"
require "flagship/context"
require "flagship/dsl"
require "flagship/feature"
require "flagship/features"
require "flagship/flagset"
require "flagship/flagsets_container"
module Flagship
class NoFlagsetSelectedError < ::StandardError; end
class << self
def define(key, options = {}, &block)
context = self.default_context
base = options[:extend] ? self.get_flagset(options[:extend]) : nil
default_flagsets_container.add ::Flagship::Dsl.new(key, context, base, &block).flagset
end
def enabled?(key)
current_flagset.enabled?(key)
end
def set_context(key_or_hash, value=nil)
if key_or_hash.is_a?(Hash)
key_or_hash.each { |k, v| default_context.__set(k, v) }
else
default_context.__set(key_or_hash, value)
end
end
def with_context(values, &block)
default_context.with_values values do
block.call
end
end
def select_flagset(key)
@current_flagset = default_flagsets_container.get(key)
end
def features
current_flagset.features
end
def get_flagset(key)
default_flagsets_container.get(key)
end
def default_flagsets_container
@default_flagsts_container ||= ::Flagship::FlagsetsContainer.new
end
def current_flagset
@current_flagset or raise NoFlagsetSelectedError.new('No flagset is selected')
end
def default_context
@default_context ||= ::Flagship::Context.new
end
def clear_state
clear_flagsets_container
clear_current_flagset
clear_context
end
def clear_flagsets_container
@default_flagsts_container = nil
end
def clear_current_flagset
@current_flagset = nil
end
def clear_context
@default_context && @default_context.clear
end
end
end
| true |
76c196b38c1654f2a6e13145c0b9025186de2ebf
|
Ruby
|
swistak35/polish-bank-to-qif
|
/konwertuj.rb
|
UTF-8
| 9,131 | 2.9375 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
require 'csv'
require 'bigdecimal'
require 'ostruct'
module Heuristics
class Heuristic
def call(entry)
if satisfied?(entry)
Result.new(result_account(entry), result_title(entry))
end
end
def result_title(entry)
entry.title
end
end
class AccountHeuristic < Heuristic
def initialize(account_number, expense_name)
@account_number = account_number
@expense_name = expense_name
end
def satisfied?(entry)
entry.account == account_number
end
def result_account(_entry)
expense_name
end
attr_reader :account_number, :expense_name
end
class ReceiverRegexHeuristic < Heuristic
def initialize(receiver_regex, account_name, title = nil)
@receiver_regex = receiver_regex
@account_name = account_name
@title = title
end
def satisfied?(entry)
entry.receiver =~ @receiver_regex
end
def result_account(_entry)
@account_name
end
def result_title(_entry)
@title || super
end
end
class TitlePrefixHeuristic < Heuristic
def initialize(prefix, account_name)
@prefix = prefix
@account_name = account_name
end
def satisfied?(entry)
entry.title.start_with?(@prefix)
end
def result_account(entry)
@account_name
end
end
class AccountNumberAndTitleIncludeHeuristic < Heuristic
def initialize(account_number, title_include_phrase, account_name)
@account_number = account_number
@title_include_phrase = title_include_phrase
@account_name = account_name
end
def satisfied?(entry)
entry.account == @account_number && entry.title.include?(@title_include_phrase)
end
def result_account(_entry)
@account_name
end
end
class CatchAllHeuristic < Heuristic
def initialize(account_name)
@account_name = account_name
end
def satisfied?(_entry)
true
end
def result_title(entry)
"#{entry.title} #{entry.receiver}"
end
def result_account(_entry)
@account_name
end
end
class AmountAndTitleIncludeHeuristic < Heuristic
def initialize(amount_string, title_include_phrase, account_name)
@amount_string = amount_string
@title_include_phrase = title_include_phrase
@account_name = account_name
end
def satisfied?(entry)
entry.title.include?(@title_include_phrase) && entry.amount === BigDecimal(@amount_string)
end
def result_account(_entry)
@account_name
end
end
class TitleIncludeHeuristic < Heuristic
def initialize(title_include_phrase, account_name)
@title_include_phrase = title_include_phrase
@account_name = account_name
end
def satisfied?(entry)
entry.title.include?(@title_include_phrase)
end
def result_account(_entry)
@account_name
end
end
class Result
def initialize(account, title)
@account = account
@title = title
end
attr_reader :account, :title
end
class Runner
def initialize(my_accounts, heuristics)
@my_accounts = my_accounts
@heuristics = heuristics
end
def call(history)
transactions = history.entries.map do |entry|
result = run_for_one(entry)
raise "Didnt found matching account for entry" if result.nil?
Qif::Entry.new(
entry.accounting_date,
entry.amount,
result.account,
result.title
)
end
Qif::Package.new(my_accounts.fetch(history.account_number), transactions)
end
def run_for_one(imported_entry)
matching_heuristic = heuristics.find do |heuristic|
heuristic.call(imported_entry)
end
return matching_heuristic.call(imported_entry) unless matching_heuristic.nil?
end
attr_reader :my_accounts, :heuristics
end
end
module Importers
class Entry
def initialize(operation_date, accounting_date, description, title, receiver, account, amount)
@operation_date = operation_date
@accounting_date = accounting_date
@description = description
@title = title
@receiver = receiver
@account = account
@amount = amount
end
attr_reader :operation_date, :accounting_date, :description, :title, :receiver, :account, :amount
end
class History
def initialize(account_number, entries)
@account_number = account_number
@entries = entries
end
attr_reader :account_number, :entries
end
class Mbank
def import_from_file(csv_path)
original_lines = CSV.readlines(csv_path, col_sep: ";", encoding: "Windows-1250:UTF-8")
account_number_line = original_lines.index {|l| l[0] == "#Numer rachunku" } + 1
account_number = original_lines[account_number_line][0].gsub(/[ ]/, "") # These are not two spaces, these are different blank characters
first_transaction_line = original_lines.index {|l| l[0] == "#Data operacji" } + 1
last_transaction_line = original_lines.rindex {|l| l[6] == "#Saldo końcowe" } - 1
imported_entries = original_lines[first_transaction_line..last_transaction_line].reject(&:empty?).map do |operation_date, accounting_date, description, title, receiver, account, amount, _balance|
amount_number = BigDecimal(amount.gsub(" ", "").gsub(",", "."))
Entry.new(
Date.parse(operation_date),
Date.parse(accounting_date),
description,
title,
receiver,
account.gsub(/'/, ""),
amount_number
)
end
return [Importers::History.new(account_number, imported_entries)]
end
end
class MilleniumBank
def import_from_file(csv_path)
lines = CSV.readlines(csv_path, col_sep: ",", encoding: "bom|UTF-8")
lines.shift
accounts = {}
lines.each do |my_account, operation_date, accounting_date, description, account, receiver, title, amount_minus, amount_plus, _balance, _currency|
cleaned_my_account = cleanup_account_number(my_account)
amount_number = if amount_minus.empty?
BigDecimal(amount_plus)
else
BigDecimal(amount_minus)
end
accounts[cleaned_my_account] ||= []
accounts[cleaned_my_account] << Entry.new(
Date.parse(operation_date),
Date.parse(accounting_date),
description,
title,
receiver,
cleanup_account_number(account),
amount_number
)
end
return accounts.map do |account_number, transactions|
History.new(account_number, transactions)
end
end
private
def cleanup_account_number(account_number)
account_number.gsub(/[A-Z ]/, "")
end
end
end
module Qif
class Entry
def initialize(date, amount, account, description)
raise "date is not a Date" unless date.is_a?(Date)
@date = date
raise "amount is not BigDecimal" unless amount.is_a?(BigDecimal)
@amount = amount
@account = account
@description = description
end
attr_reader :date, :amount, :account, :description
end
class Package
def initialize(account_name, transactions)
@account_name = account_name
@transactions = transactions
end
attr_reader :account_name, :transactions
end
class Exporter
def export_to_file(qif_package, export_file_path)
raise "Is not a QIF package" unless qif_package.is_a?(Package)
File.open(export_file_path, "w") do |f|
f.puts export_to_string(qif_package)
end
end
def export_to_string(qif_package)
export = []
export << "!Account"
export << "N#{qif_package.account_name}"
export << "^"
export << "!Type:Bank"
qif_package.transactions.each do |transaction|
export << "D#{format_date(transaction.date)}"
export << "T#{format_amount(transaction.amount)}"
export << "L#{transaction.account}" unless transaction.account.nil?
export << "P#{transaction.description}" unless transaction.description.nil?
export << "^"
end
export.join("\n")
end
private
def format_date(date)
date.strftime("%d.%m'%Y")
end
def format_amount(amount)
sprintf("%.2f", amount)
end
end
end
configuration_file = ARGV[0]
load configuration_file
importer = case ARGV[1]
when "mbank" then Importers::Mbank.new
when "milleniumbank" then Importers::MilleniumBank.new
else raise "Unknown importer"
end
csv_path = ARGV[2]
export_dir = ARGV[3]
histories = importer.import_from_file(csv_path)
histories.each do |history|
package = Heuristics::Runner.new($my_accounts, $my_heuristics).call(history)
export_path = File.join(export_dir, "#{package.account_name}.qif")
Qif::Exporter.new.export_to_file(package, export_path)
puts "Finished #{package.account_name}"
end
# TODO: maybe package step, with resulting balances? - comment would be enough, but nice for reconciliation
# TODO: split into files
# TODO: package into gem
# TODO: handle revolut
# TODO: minor - dont rely on globals
| true |
ac93858875316ebc75342c0534ebd5460902088b
|
Ruby
|
roykim79/react-rails-go-fish
|
/spec/models/go_fish_spec.rb
|
UTF-8
| 3,878 | 3.296875 | 3 |
[] |
no_license
|
require 'rails_helper'
RSpec.describe GoFish do
let(:player1) { Player.new('Jim', 1) }
let(:player2) { Player.new('Bob', 2) }
let(:game) { GoFish.new([player1, player2]) }
describe '#initialization' do
it 'has a deck' do
expect(game.deck).not_to be_nil
end
end
describe '#start' do
it 'deals out cards to each player' do
game.start
game.players.each { |player| expect(player.hand.count).to eq 7 }
end
end
describe '#current_player' do
it 'returns the player whose turn the game is on' do
expect(game.current_player).to be player1
end
end
describe '#next_player' do
it 'changes the current_player to the next index of players' do
game.next_player
expect(game.current_player).to be player2
game.next_player
expect(game.current_player).to be player1
end
end
describe '#play_turn' do
it 'will change the number of cards current player has' do
game.start
expect { game.play_turn(player2, 'A') }.to change(player1, :card_count)
end
end
describe '#pick_target' do
it 'returns a random player that is not the current player' do
expect(game.current_player).to be player1
expect(game.pick_target).to be player2
end
end
describe '#play_for_bot' do
it 'plays for the current player if they have autoplay set to true' do
game.start
player1.toggle_autoplay
expect { game.play_for_bot }.to change(player1, :card_count)
end
it 'does nothing if the current player is not a robot' do
game.start
expect { game.play_for_bot }.not_to change(player1, :card_count)
end
end
describe '#winner' do
it 'is nill at first' do
game.start
expect(game.winner).to be_nil
end
it 'returns the player with no cards left' do
player1.take(%w[A].flat_map { |rank| %w[S H].map { |suit| PlayingCard.new(rank, suit) } })
player2.take(%w[A K].flat_map { |rank| %w[C D].map { |suit| PlayingCard.new(rank, suit) } })
rigged_game = GoFish.new([player1, player2])
rigged_game.play_turn(player2, 'A')
expect(rigged_game.winner).to be player1
end
it 'returns the player with the most sets if the deck count is 0' do
rigged_hand1 = %w[A Q].flat_map { |rank| %w[S H C].map { |suit| PlayingCard.new(rank, suit) } }
rigged_hand2 = %w[K].flat_map { |rank| %w[S H C].map { |suit| PlayingCard.new(rank, suit) } }
rigged_deck = CardDeck.new(%w[A].flat_map { |rank| %w[D].map { |suit| PlayingCard.new(rank, suit) } })
player1.take(rigged_hand1)
player2.take(rigged_hand2)
rigged_game = GoFish.new([player1, player2], rigged_deck)
expect { rigged_game.play_turn(player2, 'A') }.to change { rigged_game.winner }.to player1
end
end
describe '#state_for' do
it 'returns the state of the game that is relevent for the player' do
game.start
state = game.state_for(player1)
expect(state['deckCount']).to eq 2
expect(state['player']).to eq player1.as_json
expect(state['currentPlayer']).to eq player1.name
expect(state['opponents'][0]['name']).to eq player2.name
expect(state['opponents'].length).to eq 1
expect(state['opponents'][0]['card_count']).to eq 7
expect(state['opponents'][0]['set_count']).to eq 0
end
end
context 'saving and reading json data' do
let(:json_game) { game.as_json }
describe '#as_json' do
it 'returns a hash of the Game object' do
expect(json_game).to be_a Hash
expect(json_game['players'].count).to eq 2
end
end
describe '.from_json' do
it 'returns a GoFish object from json data' do
return_object = GoFish.from_json(json_game)
expect(return_object).to be_instance_of GoFish
expect(return_object.players.count).to eq 2
end
end
end
end
| true |
345739a785fe03ae15d502724496e92fac1d5feb
|
Ruby
|
clirdlf/hc-reminders
|
/excel.rb
|
UTF-8
| 3,224 | 2.84375 | 3 |
[] |
no_license
|
#! /usr/bin/env ruby
# frozen_string_literal: true
require 'erb'
require 'optparse'
require 'pp'
require 'active_support'
require 'active_support/core_ext'
require 'mail'
require 'roo'
##
# Script for generating emails for Hidden Collections Grantees
#
# Author:: Wayne Graham (mailto:[email protected])
# Copyright:: Copyright (c) 2016 Council on Library and Information Resources
# License:: MIT
Mail.defaults do
delivery_method :smtp, address: "localhost", port: 1025
end
##
# Read the export for the Hidden Collections Filemaker Database
#
def read_spreadsheet(file = 'HiddenCollectionsFM.xlsx')
@workbook = Roo::Spreadsheet.open(file)
@workbook.default_sheet = @workbook.sheets[0]
end
##
# Read the first row of the spreadsheet and store headers and their index
def set_headers
@headers = {}
@workbook.row(1).each_with_index { |header, i| @headers[header] = i }
end
##
# Extract data from the Excel cells
def extract_fields(i)
{
id: @workbook.row(i)[@headers['Grant Contract No.']],
last_name: @workbook.row(i)[@headers['Grants_Contracts LOG::Contact Name Last']],
first_name: @workbook.row(i)[@headers['Grants_Contracts LOG::Contact Name First']],
email: @workbook.row(i)[@headers['Grants_Contracts LOG::Contact Email']],
organization: @workbook.row(i)[@headers['Grants_Contracts LOG::Contact Organization']],
project: @workbook.row(i)[@headers['Grants_Contracts LOG::Description']],
date_end: @workbook.row(i)[@headers['Grants_Contracts LOG::Date End']],
narrative_end: @workbook.row(i)[@headers['Grants_Contracts LOG::Narr 1 Due']],
active: @workbook.row(i)[@headers['Grants_Contracts LOG::Disposition']],
final_due: @workbook.row(i)[@headers['Grants_Contracts LOG::Final Narr Due']]
}
end
##
# Calculate the difference between the beginning of the current month and the
# due date
def check_date(date)
# calculate the first day of the month
# uses ActiveSupport DateAndTime#Calculations
# http://apidock.com/rails/DateAndTime/Calculations
start_of_month = Date.today.beginning_of_month
(date - start_of_month).to_i
end
##
# Send an email
def narrative_email(row)
html_template = ERB.new(File.read("templates/30_day_email.html.erb"))
text_template = ERB.new(File.read("templates/30_day_email.txt.erb"))
Mail.deliver do
to (row[:email]).to_s
from 'Hidden Collections Grant <[email protected]>'
subject 'Hidden Collections Report Reminder'
text_part do
body text_template.result(binding)
end
html_part do
content_type 'text/html; charset=UTF-8'
body html_template.result(binding)
end
end
end
##
# Parse the Excel export
def parse_file
((@workbook.first_row + 1)[email protected]_row).each do |row|
row_data = extract_fields(row)
next unless row_data[:active] == 'Active'
diff = check_date(row_data[:date_end])
# 30 - check_date(row_data[:date_end]) # TODO
if diff >= 25 && diff <= 35
narrative_email(row_data)
puts "Sending an email to #{row_data[:first_name]} #{row_data[:last_name]} at #{row_data[:organization]}; their report is due #{row_data[:date_end]}."
end
end
end
read_spreadsheet
set_headers
parse_file
| true |
4ff6dc83e242341ecd23c86ce962d91cd539c3b6
|
Ruby
|
drewemartin/temp_athena
|
/system/x_recycle_bin/tables/SCHOOL_START_DATES.rb
|
UTF-8
| 3,361 | 2.5625 | 3 |
[] |
no_license
|
#!/usr/local/bin/ruby
require "#{$paths.base_path}athena_table"
class SCHOOL_START_DATES < Athena_Table
#---------------------------------------------------------------------------
def initialize()
super()
@table_structure = nil
end
#---------------------------------------------------------------------------
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
public
def xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxPUBLIC_METHODS
end
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
##sample->
#def sample_record(arg) #call when search results should be a single row.
# params = Array.new
# params.push( Struct::WHERE_PARAMS.new("field_name", "evaluator", arg) )
# where_clause = $db.where_clause(params)
# record(where_clause)
#end
#
##sample->
#def sample_records(arg) #call when search results can be more than a single row.
# params = Array.new
# params.push( Struct::WHERE_PARAMS.new("field_name", "evaluator", arg) )
# where_clause = $db.where_clause(params)
# records(where_clause)
#end
#
##sample->
#def sample_type_with_records
# $db.get_data_single("SELECT column_name FROM #{table_name}")
#end
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
def x______________TRIGGER_EVENTS
end
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
def x______________VALIDATION
end
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
private
def xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxPRIVATE_METHODS
end
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
def table
if !@table_structure
structure_hash = {
"name" => "school_start_dates",
"file_name" => "school_start_dates.csv",
"file_location" => "school_start_dates",
"source_address" => nil,
"source_type" => nil,
"audit" => nil
}
@table_structure = set_fields(structure_hash)
end
return @table_structure
end
def set_fields(structure_hash)
field_order = Array.new
structure_hash["fields"] = Hash.new
structure_hash["fields"]["start_date"] = {"data_type"=>"date", "file_field"=>"start_date"} if field_order.push("start_date")
structure_hash["fields"]["grade_range"] = {"data_type"=>"text", "file_field"=>"grade_range"} if field_order.push("grade_range")
structure_hash["fields"]["deadline_without_computer"] = {"data_type"=>"date", "file_field"=>"deadline_without_computer"} if field_order.push("deadline_without_computer")
structure_hash["fields"]["deadline_with_computer"] = {"data_type"=>"date", "file_field"=>"deadline_with_computer"} if field_order.push("deadline_with_computer")
structure_hash["field_order"] = field_order
return structure_hash
end
end
| true |
285b255be135617d75bd4e2503156976e0fb2243
|
Ruby
|
nabe-pot/ruby-practices
|
/05.ls/ls.rb
|
UTF-8
| 3,879 | 3.046875 | 3 |
[] |
no_license
|
# frozen_string_literal: true
require 'optparse'
require 'etc'
# ハードリンク数・ユーザ・グループ・ファイルサイズ・作成時間取得
# @param [String] file_name
def get_hardlink(file_name)
"#{File.stat(file_name).nlink} "
end
def get_user(file_name)
"#{Etc.getpwuid(File.stat(file_name).uid).name} "
end
def get_group(file_name)
"#{Etc.getgrgid(File.stat(file_name).gid).name} "
end
def get_file_size(file_name)
"#{File.stat(file_name).size} "
end
# 月の表示を数字から略称に
def convert_month_num(file_name)
{
'1' => 'Jan',
'2' => 'Feb',
'3' => 'Mar',
'4' => 'Apr',
'5' => 'May',
'6' => 'June',
'7' => 'July',
'8' => 'Aug',
'9' => 'Sept',
'10' => 'Oct',
'11' => 'Nov',
'12' => 'Dec'
}[file_name]
end
def get_month(file_name)
time = File.stat(file_name).mtime.to_s
month = "#{time.gsub(/\d{4}-0?(\d+)-0?\d+ \d{2}:\d{2}:\d{2} \+\d{4}/, '\1')} "
convert_month_num(month.strip)
end
def get_time(file_name)
time = File.stat(file_name).mtime.to_s
"#{time.gsub(/\d{4}-0?\d+-0?(\d+) (\d{2}:\d{2}):\d{2} \+\d{4}/, '\1 \2')} "
end
def convert_filetype(file_name)
{
'file' => '-',
'directory' => 'd',
'characterSpecial' => 'c',
'fifo' => 'f',
'link' => 'l',
'socket' => 's'
}[file_name]
end
def convert_permission(file_name)
{
'7' => 'rwx',
'6' => 'rw-',
'5' => 'r-x',
'4' => 'r--',
'3' => '-wx',
'2' => '-w-',
'1' => '--x',
'0' => '---'
}[file_name]
end
def get_permission(file_name)
file_permission = []
file_type = File.ftype(file_name)
file_permission << convert_filetype(file_type)
permission_eight = File.stat(file_name).mode.to_s(8).chars
(-3..-1).each do |i|
file_permission << convert_permission(permission_eight[i])
end
"#{file_permission.join} "
end
# コマンドライン引数の処理
options = ARGV.getopts('alr')
dir_file_ary = if options['a']
Dir.glob('*', File::FNM_DOTMATCH).sort
else
Dir.glob('*', 0).sort
end
dir_file_ary.sort!
dir_file_ary.reverse! if options['r']
## -lオプションの場合はここで表示処理
if options['l']
total_blocks = dir_file_ary.map do |f|
fs = File::Stat.new(f)
fs.blocks
end
puts "total #{total_blocks.sum}"
dir_file_ary.each do |f|
puts "#{get_permission(f)} #{get_hardlink(f)}#{get_user(f)}#{get_group(f)}#{get_file_size(f)}#{get_month(f)} #{get_time(f)} #{f}"
end
return
end
# -lオプションがない場合の表示処理
## 取得したディレクトリで、一番長いファイル名 + スペース3個を行の幅に設定する
longest_file_name = dir_file_ary.max_by(&:length)
row_width = longest_file_name.size + 3
dir_file_ary.each_with_index do |a, i|
file_name_length = a.size
dir_file_ary[i] = a + ' ' * (row_width - file_name_length)
end
## column_numberに設定した値を、列数に指定して表示
column_number = 3
### 取得したディレクトリのファイル数を、column_numberで割った際に不足する数値を足し、分割するファイル数を求める
split_number = (dir_file_ary.size + (column_number - 1)) / column_number
formatted_dir_file_ary = []
### split_numberで、取得したディレクトリのファイル数を分割
dir_file_ary.each_slice(split_number) do |a|
formatted_dir_file_ary << a
end
### transposeメソッドで行と列を入れ替える際に、余りの数だけ空白の値を配列に追加
(split_number - formatted_dir_file_ary[-1].size).times do
formatted_dir_file_ary[-1] << ''
end
transposed_ary = formatted_dir_file_ary.transpose
### 子配列の末尾に改行を追加
transposed_ary.each.with_index do |_, i|
transposed_ary[i][transposed_ary[i].size - 1] += "\n" if i < split_number
end
puts transposed_ary.join('').gsub(/\n /, "\n")
| true |
9a427752b312f08fbf3abbca38ca33754d04d1c1
|
Ruby
|
Cyfon7/Ciclos
|
/solo_pares2.rb
|
UTF-8
| 60 | 2.828125 | 3 |
[] |
no_license
|
numero = ARGV[0].to_i
for i in (1..numero)
puts i*2
end
| true |
4660fae6c28e9859b74de7741f93eb6d42d419e9
|
Ruby
|
m0h4x/eloquent-ruby
|
/chapter_20/module_inclusion_hook.rb
|
UTF-8
| 636 | 3.53125 | 4 |
[] |
no_license
|
# the module analog of inherited is included
module WritingQuality
def self.included(klass)
puts "Hey, I've been included in #{klass}"
end
def number_of_cliches
# omited...
end
end
# combination of class & instance methods mixed into a class as a unit.
module UsefulMethods
module ClassMethods
def a_class_method
end
end
def self.included( host_class )
puts "UsefulMethods included in #{host_class}"
host_class.extend(ClassMethods)
end
def an_instance_method
end
# rest of the module deleted...
end
class Host
include UsefulMethods
at_exit do
puts "Goodbye!"
end
end
| true |
3bfc35e92e9db789c44b446087382293576f52c3
|
Ruby
|
sarcilav/google-docs-ruby
|
/model/state.rb
|
UTF-8
| 1,166 | 2.984375 | 3 |
[] |
no_license
|
class State
attr_accessor :id, :name, :cities
def initialize(id, name, cities)
@id = id
@name = name
@cities = cities
end
def to_s
"#{@name}\n\t\t#{@cities}"
end
def self.getState(key)
parse_instance(API::Gdocs.getSheet(key),key)
end
def get_totals
if @totales.nil?
@totales ||= {:piedad => 0, :reyes => 0, :jojoy => 0}
@cities.each do |city|
city.get_totals.each_pair do |c,v|
@totales[c] += v
end
end
end
@totales
end
protected
def self.parse_instance(attributes, id)
begin
table = attributes["table"]
name = table["rows"][0]["c"][1]["v"]
rows = table["rows"]
cities_content = []
blanks = false
rows.each do |r|
if r["c"][0]["v"].blank?
blanks = true
end
if blanks and not r["c"][0]["v"].blank?
cities_content << r["c"][1]["v"]
end
end
cities = cities_content.map do |c|
City.getCity(c)
end
State.new(id,name,cities)
rescue Exception => e
raise Exception.new("Problems with the sheet #{id}, #{e}")
end
end
end
| true |
b0b31e17ea0e61293ee0e4b68a08ec950c1cea29
|
Ruby
|
ucsblibrary/geniza
|
/config/initializers/add_uploads_from_csv.rb
|
UTF-8
| 1,051 | 2.609375 | 3 |
[] |
no_license
|
require 'spotlight/add_uploads_from_csv'
class Spotlight::AddUploadsFromCSV
##
# Re-define the perform method so it will process an image that comes in
# as a file as well as images that come in via a url
def perform(csv_data, exhibit, _user)
encoded_csv(csv_data).each do |row|
# The CSV row must have either a url or a file
url = row.delete('url')
file = row.delete('file')
next unless url.present? || file.present?
resource = Spotlight::Resources::Upload.new(
data: row,
exhibit: exhibit
)
resource.build_upload(remote_image_url: url) if url
resource.upload = fetch_image_from_local_disk(file) if file
resource.save_and_index
end
end
##
# Given a filepath, ensure the file exists and make a Spotlight::FeaturedImage object
def fetch_image_from_local_disk(file)
image = Spotlight::FeaturedImage.new
import_dir = ENV['IMPORT_DIR'] || ''
filepath = File.join(import_dir, file)
image.image.store!(File.open(filepath))
image
end
end
| true |
4825b5ebc132c6ff0225ee6c947f97566ef7f105
|
Ruby
|
aquach/advent-of-code
|
/2020/ruby/22/solve.rb
|
UTF-8
| 659 | 3.0625 | 3 |
[] |
no_license
|
require 'set'
if !true
a = File.readlines('sampleinput.txt').map(&:chomp)
else
a = File.readlines('input.txt').map(&:chomp)
end
if !true
def p(*args)
$a = args
end
at_exit { Kernel.p(*$a) }
end
a = a.slice_when { |f| f == '' }.to_a.map { |f|
if f.last == ''
f.pop
end
f
}
p1, p2 = a
p1.shift
p2.shift
p1 = p1.map(&:to_i)
p2 = p2.map(&:to_i)
p p1
p p2
loop do
if p1.empty? || p2.empty?
winner = p1.empty? ? p2 : p1
p winner.reverse.each_with_index.map { |v, i| v * (i + 1) }.sum
exit
end
p1c = p1.shift
p2c = p2.shift
if p1c > p2c
p1 << p1c
p1 << p2c
else
p2 << p2c
p2 << p1c
end
end
| true |
864116cd6a56e0337cf03878d477f05fd00fad80
|
Ruby
|
prachyathit/befed-base
|
/lib/modules/omise_gateway.rb
|
UTF-8
| 672 | 2.671875 | 3 |
[] |
no_license
|
module OmiseGateway
Omise.api_key = ENV['omise_secret_key']
class << self
def create_charge(order, token)
charge = Omise::Charge.create({
amount: (order.total * 100).to_i,
currency: "thb",
card: token
})
if charge.paid
Rails.logger.info("Successfully paid by credit card")
charge
else
Rails.logger.error("Unsuccessfully paid by credit card: #{charge.failure_code} #{charge.inspect}")
raise InvalidCreditCardInfo.new("Credit Card info is incorrect.")
end
end
end
class InvalidCreditCardInfo < StandardError
def initialize(data)
@data = data
end
end
end
| true |
51914b296133e40f05cd8e0185aa94c899183ded
|
Ruby
|
plantran/learn2shell
|
/games/admin_game.rb
|
UTF-8
| 3,488 | 3.125 | 3 |
[] |
no_license
|
module Games
# Contains all the methods and logic for the admin game part.
class AdminGame
require_relative '../helpers/custom_admin_system'
def initialize
@cs = Helpers::CustomAdminSystem.new
@admin_path = "#{__dir__}/../#{ENV['ADMIN_PATH']}/admin"
@root_path = "#{__dir__}/../#{ENV['ROOT_PATH']}"
set_sonneries
end
# Starts the admin game
def play
return unless check_admin_password
setup_dirs_and_files
display_welcome_screen
start_prompt
end
private
# Prevents user from starting admin game without the password
def check_admin_password
print("#{'Entrez le mot de passe pour la session admin'.underline}: ")
user_input = $stdin.gets.chomp
if user_input == ENV['ADMIN_PASSWORD']
true
else
puts 'Mauvais mot de passe.'
false
end
end
# Creates admin directories and files
def setup_dirs_and_files
system("mkdir -p #{@admin_path}")
system("cp #{__dir__}/../docs/liste_mails.txt #{@admin_path}/liste_mails.txt")
write_sonneries
Dir.chdir(@admin_path)
end
# Initialize the sonneries file with instances values
def write_sonneries
File.open("#{@admin_path}/set_sonneries.txt", 'w') do |f|
txt = <<~TXT
sonnerie pause = #{@sonneries[:break]}
alarme incendie = #{@sonneries[:fire]}
son sonnerie = #{@sonneries[:sound]}
TXT
f.puts(txt)
end
end
# Set default values for the sonneries
def set_sonneries
@sonneries = { break: 55, fire: 1, sound: 'sonnerie normale' }
end
# Outputs the admin game welcome screen
def display_welcome_screen
puts <<~TXT
Bienvenue dans le mode admin. Pour pouvez quitter à tout moment en tapant la commande exit.
Tapez "aide" pour voir ce que vous pouvez faire.
TXT
end
def start_prompt
loop do
user_input = @cs.prompt_and_user_input_with_path
next if user_input.empty?
cmd = user_input.split(' ').first.downcase
args = user_input.split(' ')[1..]
next if cmd_status?(cmd)
return finish_admin_game if cmd == 'exit'
@cs.execute_custom_command(cmd, *args)
end
end
# Ends admin game, deletes folders and files, and change directory to root game
def finish_admin_game
Dir.chdir(@root_path)
system("rm -rf #{@admin_path}")
puts 'Fermeture du mode admin.'
end
# Handles the custom status command (displays status of "sonneries")
def cmd_status?(cmd)
update_sonneries
return false unless cmd == 'status'
puts <<~TXT
La sonnerie de cours sonnera toutes les #{@sonneries[:break].bold.pink} minutes.
L'alarme incendie sonnera #{@sonneries[:fire].bold.pink} fois par mois.
La musique de la sonnerie de cours est #{@sonneries[:sound].bold.pink}.
TXT
true
end
# Update instance variable @sonneries based on values found inside the sonneries file.
def update_sonneries
File.readlines("#{@admin_path}/set_sonneries.txt").each do |line|
identifier, value = line.chomp.split('=').map(&:strip)
case identifier
when 'sonnerie pause'
@sonneries[:break] = value
when 'alarme incendie'
@sonneries[:fire] = value
when 'son sonnerie'
@sonneries[:sound] = value
end
end
end
end
end
| true |
c73a4aab52e6f6ecdb1bc8f2b537e13fe9275e4b
|
Ruby
|
petertseng/exercism-problem-specifications
|
/exercises/beer-song/verify.rb
|
UTF-8
| 924 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
require 'json'
require_relative '../../verify'
def verse(n)
pre = "#{bottles(n).to_s.capitalize} on the wall, #{bottles(n)}."
post = ", #{bottles((n - 1) % 100)} on the wall."
mid = case n
when 0; 'Go to the store and buy some more'
when 1; 'Take it down and pass it around'
else 'Take one down and pass it around'
end
[pre, mid + post]
end
def bottles(n)
"#{n == 0 ? 'no more' : n} bottle#{?s if n != 1} of beer"
end
module Intersperse refine Enumerable do
def intersperse(x)
map { |e| [x, e] }.flatten(1).drop(1)
end
end end
using Intersperse
def verses(a, b)
a.step(b, by: -1).map { |n| verse(n) }.intersperse('').flatten(1)
end
json = JSON.parse(File.read(File.join(__dir__, 'canonical-data.json')))
verify(json['cases'].flat_map { |c| c['cases'].flat_map { |cc| cc['cases'] } }, property: 'recite') { |i, _|
verses(i['startBottles'], i['startBottles'] - i['takeDown'] + 1)
}
| true |
d7505ad78b3bec0c0d4e340b50aecd5fb40d69be
|
Ruby
|
orhanna14/oo-tic-tac-toe
|
/spec/player_input_spec.rb
|
UTF-8
| 723 | 2.859375 | 3 |
[] |
no_license
|
require "spec_helper"
require_relative "../lib/player_input.rb"
require_relative "../lib/coordinates.rb"
require_relative "../lib/grid.rb"
require_relative "../lib/printer.rb"
RSpec.describe PlayerInput do
describe "#get_valid_coordinate" do
it "repeatedly asks for valid coordinate, returns the value when valid" do
invalid_format = StringIO.new
grid = Grid.new
printer = Printer.new(invalid_format)
player_input = PlayerInput.new(invalid_format, grid, printer)
allow(invalid_format).to receive(:gets).and_return("A6", "B7", "A1")
coordinates = Coordinates.new(invalid_format)
result = player_input.get_valid_coordinate
expect(result).to eq("A1")
end
end
end
| true |
43b82ad64da99c072b4ef3cab79a31f55f1cfa43
|
Ruby
|
GuttermanA/spellbook-api
|
/lib/tasks/scheduled.rake
|
UTF-8
| 856 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
namespace :update do
desc "Checks if current Magic Sets match the https://api.magicthegathering.io sets. If not, seed cards from missing set."
task :seed_new_set => :environment do
puts "Checking for new set(s)"
new_sets = MagicSet.check_for_new_sets
if new_sets
new_sets_list = new_sets.join(',')
puts "Found #{new_sets_list} set(s)"
new_cards_dataset = MTG::Card.where(setName: new_sets_list).all
count = Card.seed(new_cards_dataset)
puts "Added cards from #{new_sets_list}"
puts "Added #{count} cards"
# new_sets.each do |set|
# new_cards_dataset = MTG::Card.where(setName: set).all
# count = Card.seed(new_cards_dataset)
# puts "Added #{count} cards from #{set}"
# end
else
puts "No new sets at this time"
end
end
end
| true |
05774a6a3751237eafe7df968cbb82bf9254c7d0
|
Ruby
|
khamla719/phase-0
|
/week-5/group-research-methods/my_solution.rb
|
UTF-8
| 2,098 | 4.3125 | 4 |
[
"MIT"
] |
permissive
|
# Research Methods
# I spent 2 hours on this challenge.
# Person 2: Modifying Existing Data
i_want_pets = ["I", "want", 3, "pets", "but", "only", "have", 2]
my_family_pets_ages = {"Evi" => 6, "Ditto" => 3, "Hoobie" => 3, "George" => 12, "Bogart" => 4, "Poly" => 4, "Annabelle" => 0}
def my_array_modification_method!(source, thing_to_modify)
modded_array = source.map! {|x|
if x.is_a? Fixnum then x + thing_to_modify
else
x
end}
p modded_array
end
my_array_modification_method!(i_want_pets, 3)
# This method takes in an array and a number to be added to all internal numbers. The output replaces the original array with the updated numbers. The first method I used was "map!". This method allows you to invoke the given block once for each element in the array and then replaces the element returned by the block. In this block, we asked if the element was a Fixnum, and if so then we add the element to the number given in the argument. The next method I used is the "is_a?". This method simply asks if the object is a certain class. In the block, we asked if the element was a Fixnum using "is_a?" and if so, then we continue applying the rest of the code. The result is that the array would update any Fixnum inside the array and add them by the desired number.
def my_hash_modification_method!(source, thing_to_modify)
modded_hash = source.update(source){|k, v| v + thing_to_modify}
p modded_hash
end
my_hash_modification_method!(my_family_pets_ages, 2)
# This method takes in a hash and a number to modify the existing value. The output replaces the original hash with a new one that adds the desired number to the values. The method that I used is "update". This method allows you to update a hash with specific instructions given in the block. In this case, we called the update method to modify the desired hash and add all values by the number given in the argument. The result is an updated array with the changes called in the argument.
# Release 3: Reflect!
# What did you learn about researching and explaining your research to others?
#
#
#
#
| true |
3fbc2b9cc381e9dff0c311dd964965c7faaf1405
|
Ruby
|
woobaik/Alorithm_Practice
|
/recursion/factorial.rb
|
UTF-8
| 574 | 4.0625 | 4 |
[] |
no_license
|
def factorial(num)
return 1 if num == 1
num * factorial(num -1)
end
# factorial(10)
def palindrome(str)
return true if str.length == 1 || str.length == 0
if str[0] == str[-1]
palindrome(str[1..-2])
else
false
end
end
def z_counter(n)
if n == 0
puts "nomore bottles of beer on the wall"
return true
else
puts "#{n} bottles of beer on the wall"
z_counter(n-1)
end
end
def flatten(arrs)
result = []
arrs.each do |arr|
if arr.length == 1
result << arr
else
flatten(arr)
end
end
result
end
| true |
89ddacc405f50902b2ebe3b269578e9718e18023
|
Ruby
|
sfroestl/onespark
|
/lib/tools/github/resources/org.rb
|
UTF-8
| 1,193 | 2.515625 | 3 |
[] |
no_license
|
##
# The Org Model class
#
# this sub class represents a GitHubApi Org resource
#
# Author:: Sebastian Fröstl (mailto:[email protected])
# Last Edit:: 21.07.2012
class GitHubApi
# Represents a single GitHub Org and provides access to its data attributes.
class Org < Entity
attr_reader :avatar_url, :billing_email, :blog, :collaborators,
:company, :created_at, :disk_usage, :email, :followers, :following,
:html_url, :id, :location, :login, :name, :owned_private_repos, :plan,
:private_gists, :private_repos, :public_gists, :public_repos, :space,
:total_private_repos, :type, :url
# Returns an array of GitHubApi::Repo instances representing the repos
# that belong to this org
def repos
api.list_repos(login)
end
# Returns an array of GitHubApi::User instances representing the users
# who are members of the organization
def members
api.list_members(login)
end
# Returns an array of GitHubApi::User instances representing the users
# who are public members of the organization
def public_members
api.list_public_members(login)
end
private
def natural_key
[data['login']]
end
end
end
| true |
8fe08d1992a88859293338708b22c6f3b13c07e3
|
Ruby
|
rokn/Count_Words_2015
|
/fetched_code/ruby/in_spec.rb
|
UTF-8
| 1,575 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
# encoding: utf-8
RSpec.describe TTY::Prompt::Question, '#in' do
subject(:prompt) { TTY::TestPrompt.new }
it "reads range from option" do
prompt.input << '8'
prompt.input.rewind
answer = prompt.ask("How do you like it on scale 1-10?", in: '1-10')
expect(answer).to eq('8')
end
it 'reads number within string range' do
prompt.input << '8'
prompt.input.rewind
answer = prompt.ask("How do you like it on scale 1-10?") do |q|
q.in('1-10')
end
expect(answer).to eq('8')
expect(prompt.output.string).to eq([
"How do you like it on scale 1-10? ",
"\e[1000D\e[K\e[1A",
"\e[1000D\e[K",
"How do you like it on scale 1-10? \e[32m8\e[0m\n",
].join)
end
it 'reads number within digit range' do
prompt.input << '8.1'
prompt.input.rewind
answer = prompt.ask("How do you like it on scale 1-10?") do |q|
q.in(1.0..11.5)
end
expect(answer).to eq('8.1')
expect(prompt.output.string).to eq([
"How do you like it on scale 1-10? ",
"\e[1000D\e[K\e[1A",
"\e[1000D\e[K",
"How do you like it on scale 1-10? \e[32m8.1\e[0m\n",
].join)
end
it 'reads letters within range' do
prompt.input << 'E'
prompt.input.rewind
answer = prompt.ask("Your favourite vitamin? (A-K)") do |q|
q.in('A-K')
end
expect(answer).to eq('E')
expect(prompt.output.string).to eq([
"Your favourite vitamin? (A-K) ",
"\e[1000D\e[K\e[1A",
"\e[1000D\e[K",
"Your favourite vitamin? (A-K) \e[32mE\e[0m\n"
].join)
end
end
| true |
83b840b695035fc06c79ee4c8bd31995f60064b4
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/nth-prime/c8ada55a580d4c54a6b38817d8f11c0e.rb
|
UTF-8
| 519 | 3.8125 | 4 |
[] |
no_license
|
class Prime
def self.nth(number)
new.nth(number)
end
def nth(number)
raise ArgumentError, "must be greater than zero" unless number > 0
primes = (1..Float::INFINITY).lazy.select { |integer|
is_prime?(integer)
}.take(number).reduce([]) { |primes, prime| primes << prime }
primes[number - 1]
end
def is_prime?(number)
square_root = Math.sqrt(number).ceil
return false if number < 2
return true if number == 2
(2..square_root).all? { |i| number % i != 0 }
end
end
| true |
dff0117ef15cdde20e83a9e34bf143387fd6fdff
|
Ruby
|
steve-c-thompson/RubyBattleship
|
/lib/battleship.rb
|
UTF-8
| 1,017 | 2.890625 | 3 |
[] |
no_license
|
class Battleship
def self.run
b = Battleship.new
b.welcome
end
def initialize
end
def welcome
puts "Welcome to BATTLESHIP"
puts
options_list
end
def options_list
user_input = ""
options = ["p", "i", "q"]
until options.include?(user_input)
puts "Would you like to (#{options[0]})lay, read the (#{options[1]})nstructions, or (#{options[2]})uit?"
print "> "
user_input = gets.chomp
case user_input.downcase
when "i"
puts "Instructions..."
user_input = "" # reset to stay in loop
when "q"
puts "Goodbye"
when "p"
init_game
game_loop
end
end
end
def game_loop
end
def init_game
# create board
# create computer player
# create human player
end
# Call the method to place the player's ships
def place_ships(player, board)
end
def take_turn(player, board)
end
end
Battleship.run
| true |
52600e08bda3dcf793acfc4d261ec3e5da222a74
|
Ruby
|
iboard/yarb
|
/app/models/email_confirmation.rb
|
UTF-8
| 731 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
# -*- encoding : utf-8 -*-"
# EmailConfirmations generates a random token for a user and email
# When confirmed! the attribute confirmed_at is set to now.
class EmailConfirmation
include Persistable
key_method :token
attribute :token, unique: true
attribute :email, unique: true
attribute :user_id, unique: true
attribute :confirmed_at, type: Time
# @param [Hash] args
# @option args [String] :email
# @option args [String] :token
def initialize args={}
set_attributes args
end
# Sets the EmailConfirmation to be confirmed
def confirm!
self.confirmed_at = Time.now
save
end
# @return [Boolean] true if confirmed_at is set
def confirmed?
!self.confirmed_at.nil?
end
end
| true |
1ef0f8782a3f18fa4c06d95b83dafdff5091157a
|
Ruby
|
RubyCamp/rc2013w_g4
|
/lib/gameover.rb
|
UTF-8
| 371 | 2.640625 | 3 |
[] |
no_license
|
# encoding: utf-8
class Gameover < Scene
def initialize
@bg_img = Image.load("images/tokiojo_gameover.png")
end
def init(*args)
@score = args[0]
end
def play
if Input.keyPush?(K_RETURN)
Scene.delete_scene(:game)
game = Game.new
Scene.add_scene(:game, game)
Scene.set_scene(:game)
end
Window.draw(0, 0, @bg_img)
end
end
| true |
1ef9679d189ea3953e940015356552df7d5a4506
|
Ruby
|
iliankostov/Sandbox
|
/Ruby/loops_and_iterators.rb
|
UTF-8
| 384 | 3.5625 | 4 |
[] |
no_license
|
counter = 1
until counter > 10
puts counter
counter += 1
end
puts "-------------------"
for num in 1..15
puts num
end
puts "-------------------"
i = 20
loop do
i -= 1
next if i % 2 == 1
puts "#{i}"
break if i <= 0
end
puts "-------------------"
array = [1,2,3,4,5]
array.each do |x|
x += 10
puts "#{x}"
end
puts "-------------------"
5.times { print "ha " }
| true |
8ef629f4b6c3346077798a25a910ec5213a47f68
|
Ruby
|
PetePhx/basic-ruby
|
/small_problems/medium_2/05_triangle_sides.rb
|
UTF-8
| 688 | 4.25 | 4 |
[] |
no_license
|
# Triangle Sides
# Write a method that takes the lengths of the 3 sides of a triangle as
# arguments, and returns a symbol :equilateral, :isosceles, :scalene, or
# :invalid depending on whether the triangle is equilateral, isosceles, scalene,
# or invalid.
def triangle(a, b, c)
sides = [a, b, c].sort
return :invalid if (sides[0] <= 0) || (sides[0] + sides[1] <= sides[2])
return :equilateral if sides[0] == sides[2]
return :isosceles if sides[0] == sides[1] || sides[1] == sides[2]
:scalene
end
p [
triangle(3, 3, 3) == :equilateral,
triangle(3, 3, 1.5) == :isosceles,
triangle(3, 4, 5) == :scalene,
triangle(0, 3, 3) == :invalid,
triangle(3, 1, 1) == :invalid
]
| true |
34c0c92a78ace3eb6d0f7ea97a39f89afb8b29e0
|
Ruby
|
jchen623/tip_calculator
|
/tip_calculator.rb
|
UTF-8
| 409 | 3.171875 | 3 |
[] |
no_license
|
meal = 20
tax = 0.12
tip = 0.2
tax_value = meal*tax
meal_with_tax = meal+tax_value
tip_value = meal_with_tax*tip
total_cost = meal_with_tax+tip_value
puts "The pre-tax cost of your meal was $%.2f." % meal
puts "At %d%%, tax for this meal was $%.2f." % [tax*100, tax_value]
puts "For a %d%% tip, you should leave $%.2f." % [tip*100, tip_value]
puts "The grand total for this meal is then $%.2f." % total_cost
| true |
db3102e1108330ecf74db627369a909cee18a43d
|
Ruby
|
gfcharles/euler
|
/ruby/euler034.rb
|
UTF-8
| 585 | 3.890625 | 4 |
[] |
no_license
|
#!/usr/bin/ruby
def factorialList(n)
(2..n).inject([1,1]) {|list, i| list << i * list.last}
end
def sum_of_digits?(n, factorials)
n == n.to_s.split(//).inject(0) {|sum, digit| sum += factorials[digit.to_i] }
end
def get_upper_bound(nineFactorial)
base = nineFactorial
digit_count = 2
upper_bound = 0
while (digit_count += 1) do
return upper_bound if ((digit_count * base).to_s).length < digit_count
upper_bound = digit_count * base
end
end
f = factorialList(9)
puts (10..get_upper_bound(f[9])).select {|n| sum_of_digits?(n, f)}.inject {|sum, x| sum + x}
| true |
118faabb45f5ce432799402f5937c96e7125a80e
|
Ruby
|
mathildathompson/wdi_sydney_feb
|
/students/anne_homann/mtalab.rb
|
UTF-8
| 795 | 3.4375 | 3 |
[] |
no_license
|
# nline: ['Times Square', '34th', '28th', '23rd', 'Union Square', '8th']
# is the new syntax used in Ruby
# old one is being used below
subway = {
"N_line" => ['Times Square', '34th', '28th', '23rd', 'Union Square', '8th'],
"L_line" => ['8th', '6th', 'Union Square', '3rd', '1st'],
"Six_line" => ['Grand Central', '33rd', '28th', '23rd', 'Union Square', 'Astor Place']
}
puts "Which line are you taking ? #{subway.keys}"
start_line = gets.chomp
puts "From which stop? #{subway[start_line]}"
start_station = gets.chomp
puts "Which line will you be getting off from? #{subway.keys}"
end_line = gets.chomp
puts "And which stop will you be hopping off? #{subway[end_line]}"
end_station = gets.chomp
puts "There will be a total of #{[]} stops before you reach #{subway[end_station]}"
| true |
6575559233ac58d870a7f10bc01d9b8f89456339
|
Ruby
|
rkstarnerd/LS
|
/Exercises/Easy_3/palindrome1.rb
|
UTF-8
| 55 | 2.734375 | 3 |
[] |
no_license
|
def palindrome?(object)
object == object.reverse
end
| true |
4b6e3eb1821337615247089812d8cfd88a24c517
|
Ruby
|
karthick-soolapani/code-problems
|
/coderbyte/easy/q25_number_search.rb
|
UTF-8
| 745 | 4.40625 | 4 |
[] |
no_license
|
# Using the Ruby language, have the function NumberSearch(str) take the str parameter,
# search for all the numbers in the string, add them together, then return that final
# number. For example: if str is "88Hello 3World!" the output should be 91. You will
# have to differentiate between single digit numbers and multiple digit numbers like in
# the example above. So "55Hello" and "5Hello 5" should return two different answers.
# Each string will contain at least one letter or symbol.
def NumberAddition(str)
str.scan(/\d+/).map(&:to_i).sum
end
p NumberAddition("88Hello 3World!") == 91
p NumberAddition("55Hello") == 55
p NumberAddition("75Number9") == 84
p NumberAddition("10 2One Number*1*") == 13
p NumberAddition("3Hello 9") == 12
| true |
3648b21087f39d6a6165bd649e6d036c2f9592f4
|
Ruby
|
TigerWolf/cherby
|
/spec/task_spec.rb
|
UTF-8
| 1,490 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
require_relative 'spec_helper'
require 'cherby/task'
require 'cherby/journal_note'
module Cherby
describe Task do
context "Instance methods" do
before(:each) do
@task_xml = File.read(File.join(DATA_DIR, 'task.xml'))
end
describe "#id" do
it "returns the value from the TaskID field" do
task = Task.new(@task_xml)
task['TaskID'] = '9876'
task.id.should == '9876'
end
end #id
describe "#exists?" do
it "true if task ID is non-nil" do
task = Task.new(@task_xml)
task['TaskID'] = '9876'
task.exists?.should be_true
end
it "false if task ID is nil" do
task = Task.new(@task_xml)
task['TaskID'] = nil
task.exists?.should be_false
end
it "false if task ID is empty string" do
task = Task.new(@task_xml)
task['TaskID'] = ''
task.exists?.should be_false
end
end #exists?
describe "#add_journal_note" do
it "adds a note to the Task" do
task = Task.new(@task_xml)
journal_note = JournalNote.create({
'Details' => 'New note on task',
'LastModDateTime' => DateTime.now,
})
task.add_journal_note(journal_note)
task['CompletionDetails'].should =~ /New note on task/
end
end #add_journal_note
end # Instance methods
end # describe Task
end # module Cherby
| true |
8bfc760a96f6b73d57d27db4a400b40d94be12c8
|
Ruby
|
flood4life/health-practice
|
/app/services/health_checker.rb
|
UTF-8
| 889 | 2.71875 | 3 |
[] |
no_license
|
# frozen_string_literal: true
class HealthChecker
Status = Struct.new(:healthy, :services, keyword_init: true)
Services = Struct.new(:mongodb, :redis, keyword_init: true)
def initialize
@mongodb_client = Mongoid.default_client
@redis_conn = RedisConnection.new.get
end
def status
services = services_status
Status.new(
healthy: services.values.all?,
services: services
)
end
private
attr_reader :mongodb_client, :redis_conn
def services_status
Services.new(
mongodb: mongodb_status,
redis: redis_status
)
end
def mongodb_status
# the application can't function if it can't write to DB
mongodb_client.cluster.has_writable_server?
end
def redis_status
# we consider redis to be fine if it responds to our pings
redis_conn.ping == 'PONG'
rescue Redis::BaseError => _e
false
end
end
| true |
3b4d7bb082ea00dd1459f7139941ed1cfaae8176
|
Ruby
|
jashmenn/poolparty
|
/test/lib/core/integer_test.rb
|
UTF-8
| 547 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
require "#{File.dirname(__FILE__)}/../../test_helper"
class IntegerTest < Test::Unit::TestCase
context "Integer" do
should "have months defined" do
# 60 seconds * 60 minutes * 24 hours * 30 days
assert_equal 60*60*24*30, 1.months
assert_equal 60*60*24*30*2, 2.months
assert_equal 60*60*24*30*12, 12.months
end
should "have years set" do
# 60 seconds * 60 minutes * 24 hours * 365.25 days
assert_equal 60*60*24*365.25, 1.year
assert_equal 60*60*24*365.25*2, 2.years
end
end
end
| true |
f3d952740905db0427d3e4d282f2a219fc483b0f
|
Ruby
|
cassar/skrol_basic
|
/lib/users/enrolment_manager.rb
|
UTF-8
| 1,515 | 2.640625 | 3 |
[] |
no_license
|
class EnrolmentManager
def initialize(enrolment)
@enrolment = enrolment
@course = enrolment.course
@course_manager = CourseManager.new(@course)
@existing_scores = @enrolment.user_scores.pluck(:word_id)
end
attr_reader :enrolment
attr_reader :course
attr_reader :course_manager
def next_word
score = max_score
return score.word unless score.nil?
word = word_from_ranks
word
end
def associated_scripts
@course_manager.associated_scripts
end
def available_sentences(word)
word.sentences & @course.sentences - @enrolment.sentences
end
def user_score(word)
@enrolment.user_scores.find_by(word: word)
end
def assign_status(target_word, status)
score = @enrolment.user_scores.find_by word: target_word
if score.nil?
start_score = @course_manager.word_score(target_word).entry
@enrolment.user_scores.create(status: status, entry: start_score,
word: target_word)
@existing_scores << target_word.id
else
score.update(status: status)
end
end
private
def max_score
@enrolment.user_scores.where('entry < ? AND status = ?', ACQUIRY_POINT,
TESTED).order(entry: :desc).first
end
def word_from_ranks
batch_size = @existing_scores.count + 1
ranked_words = @course_manager.limited_batch(batch_size).pluck(:word_id)
word_id = (ranked_words - @existing_scores).first
Word.find(word_id) if word_id.present?
end
end
| true |
a051617d9af5101db04c1dd0fe7e5dc05a786608
|
Ruby
|
sciencehistory/chf-sufia
|
/lib/chf/reports/metadata_completion_report.rb
|
UTF-8
| 2,745 | 2.5625 | 3 |
[
"Apache-2.0"
] |
permissive
|
module CHF
module Reports
class MetadataCompletionReport
attr_reader :lookup, :published, :full, :totals
def initialize
@lookup = {
Rails.configuration.divisions[0] => :archives,
Rails.configuration.divisions[1] => :oral,
Rails.configuration.divisions[2] => :museum,
Rails.configuration.divisions[3] => :library,
"Rare Books" => :rare_books,
"" => :unknown
}
@published = lookup.values.inject({}) { |h, k| h.merge({k => 0}) }
@full = published.deep_dup
@totals = published.deep_dup
@rb_curator = '[email protected]'
end
def run
i = 0
total = GenericWork.count
GenericWork.all.find_each do |w|
i += 1
puts "Analyzing work #{i} of #{total}: #{w.id} #{w.title.first}"
division = w.division.nil? ? "" : w.division
if lookup[division] == :library
# figure out who can edit
can_edit = []
w.permissions.each do |perm|
can_edit << perm.agent_name if perm.access == "edit"
end
division = "Rare Books" if can_edit.include? @rb_curator
end
@totals[lookup[division]] = totals[lookup[division]] + 1
if is_published(w)
@published[lookup[division]] = published[lookup[division]] + 1
if has_description(w)
@full[lookup[division]] = full[lookup[division]] + 1
end
end
end
end
def get_output()
output = []
lookup.each do |k, v|
k = k.empty? ? "Uncategorized" : k
output << get_line(k, published[v], totals[v], "records are published")
output << get_line(k, full[v], totals[v], "records are published with descriptions")
end
output << get_line('All divisions', published.values.reduce(0, :+), totals.values.reduce(0, :+), "records are published")
output << get_line('All divisions', full.values.reduce(0, :+), totals.values.reduce(0, :+), "records are published with descriptions")
return output.join("\n")
end
def get_line(category, numerator, denominator, text)
"#{category}: #{numerator} / #{denominator} (#{percent(numerator, denominator)}%) #{text}"
end
def percent(num, denom)
# special case for denom == 0
return 100 if num == denom
return (num.fdiv(denom) * 100).to_i
end
# return true if the visibility is open/public
def is_published(w)
return w.visibility.eql? 'open'
end
def has_description(w)
return !(w.description.empty? or w.description.first.empty?)
end
end
end
end
| true |
7896cc8bafc318192e4c63c1f090a0c01cdf4349
|
Ruby
|
lakshmananmurugesan/mesoketes_problem
|
/attack.rb
|
UTF-8
| 1,534 | 3.40625 | 3 |
[] |
no_license
|
class Attack
attr_accessor :attack_count
def initialize
@attack_count = 0
end
# Check if attack happened
def attacked? wall_strength, tribal_strength, direction
strength = 0
case direction
when "N"
strength = wall_strength.north_side
when "S"
strength = wall_strength.south_side
when "E"
strength = wall_strength.east_side
when "W"
strength = wall_strength.west_side
end
(tribal_strength > strength)
end
# Rebuild wall at the end of the day's battle
def rebuild_wall wall_strength, attack_details_arr
attack_details_arr.each do |attack_detail|
tribal, direction, tribal_strength = attack_detail.split(" - ")
tribal = Tribal.new(tribal, tribal_strength)
direction = Direction.new(direction)
strengthen_the_wall(wall_strength, tribal.tribal_strength.to_i, direction.current_direction)
end
end
# Check and update wall strength
def strengthen_the_wall wall_strength, tribal_strength, direction
strength = 0
case direction
when "N"
wall_strength.north_side = tribal_strength if (tribal_strength > wall_strength.north_side)
when "S"
wall_strength.south_side = tribal_strength if (tribal_strength > wall_strength.south_side)
when "E"
wall_strength.east_side = tribal_strength if (tribal_strength > wall_strength.east_side)
when "W"
wall_strength.west_side = tribal_strength if (tribal_strength > wall_strength.west_side)
end
end
end
| true |
ecc4f40e9990b9870adbb2b37bc320d54691d726
|
Ruby
|
laarchambault/ruby-oo-self-cash-register-lab-atlanta-web-021720
|
/lib/cash_register.rb
|
UTF-8
| 1,096 | 3.328125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class CashRegister
attr_reader :discount, :items
attr_accessor :total
def initialize(employee=nil)
@total = 0.0
@discount = employee
@items = []
@price_array = []
@last_transaction_items = []
@last_transaction_prices = []
end
def add_item(title, price, qty=1)
@total += (price * qty)
qty.times do
@items << title
end
@last_transaction_items << title
@last_transaction_prices << price * qty
end
def apply_discount
if @discount
@discount = @discount.to_f * 0.01
@total -= (@total * @discount)
if @total == @total.to_i
zero_free_total = @total.to_i
else
zero_free_total = @total
end
"After the discount, the total comes to $#{zero_free_total}."
else
"There is no discount to apply."
end
end
def void_last_transaction
@last_transaction_items.pop()
@total -= @last_transaction_prices.pop()
end
end
| true |
7b74526917a5eb3c32c95cffbd2b9f210acfba09
|
Ruby
|
jpheos/batch-481
|
/05-Rails/03-Rails-restaurant-reviews/Livecode/parks_and_plants/db/seeds.rb
|
UTF-8
| 1,389 | 2.6875 | 3 |
[] |
no_license
|
puts 'Clean DB'
Garden.destroy_all
puts 'Seeds DB'
gardens = [
{
name: 'Jardin des plantes',
banner_url: 'https://images.unsplash.com/photo-1483809715206-0499044b5b69?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80'
},
{
name: 'Jardin du Luxembourg',
banner_url: 'https://images.unsplash.com/photo-1571192776145-9f563c1df686?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=675&q=80'
}
]
plants = [
{
name: 'Ficus',
image_url: 'https://images.unsplash.com/photo-1591656884447-8562e2373a66?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80'
},
{
name: 'Menthe',
image_url: 'https://images.unsplash.com/photo-1588908933351-eeb8cd4c4521?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60'
},
{
name: 'Bananier',
image_url: 'https://images.unsplash.com/photo-1552901633-210088e17486?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60'
},
{
name: 'Fleur de Lys',
image_url: 'https://images.unsplash.com/photo-1596571242677-c1dc2d4bca79?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80'
}
]
gardens.each do |attributes|
garden = Garden.create!(attributes)
7.times do
plant = Plant.new(plants.sample)
plant.garden = garden
plant.save!
end
end
puts "#{Garden.count} gardens created !"
puts "#{Plant.count} gardens created !"
| true |
42f19bc91ab76941daedb9999e913cc7affaf569
|
Ruby
|
marioa7770/apples-and-holidays-onl01-seng-pt-061520
|
/lib/holiday.rb
|
UTF-8
| 533 | 2.96875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
holiday_supplies = {
:winter => {
:christmas => ["Lights", "Wreath"],
:new_years => ["Party Hats"]
},
:summer => {
:fourth_of_july => ["Fireworks", "BBQ"]
},
:fall => {
:thanksgiving => ["Turkey"]
},
:spring => {
:memorial_day => ["BBQ"]
}
}
def second_supply_for_fourth_of_july(holiday_hash)
holiday_hash.each do |seasons, holidays|
holidays.each do |days, characteristics|
if days == :fourth_of_july
return characteristics[1]
end
end
| true |
938a0ebf68d70917f47ef844ea9e3fadafb4bc2f
|
Ruby
|
equivalent/maze_magic
|
/lib/maze_magic/renderer/console_renderer.rb
|
UTF-8
| 491 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
module MazeMagic
module Renderer
class ConsoleRenderer
attr_reader :cells_grid
attr_writer :printer
def initialize(cells_grid:)
@cells_grid = cells_grid
end
def call
cells_grid.each do |row|
row.each do |cell|
printer.call(cell.to_console_print)
end
printer.call("\n")
end
nil
end
def printer
@printer ||= ->(*args){print(*args)}
end
end
end
end
| true |
078ecfd5131b65cfb968f7ce894a32cc89e23417
|
Ruby
|
theIanMilan/avion
|
/rubyactivities/century_from_year.rb
|
UTF-8
| 399 | 3.609375 | 4 |
[] |
no_license
|
def centuryFromYear(year)
return 1 if year < 100
if year.to_s[-2..-1].to_i.between?(01,99)
year += 100
end
year.to_s[0..(year.to_s.length - 3)].to_i
end
p centuryFromYear(1705) == 18
p centuryFromYear(1900) == 19
p centuryFromYear(1601) == 17
p centuryFromYear(2000) == 20
p centuryFromYear(900) == 9
p centuryFromYear(901) == 10
p centuryFromYear(90) == 1
p centuryFromYear(9) == 1
| true |
85d70d545c1c7039780eeb2d0df8e889f67aa949
|
Ruby
|
peter/rails101
|
/code/ruby/exceptions.rb
|
UTF-8
| 466 | 2.578125 | 3 |
[] |
no_license
|
begin
raise(ArgumentError, "No file_name provided") if !file_name
content = load_blog_data(file_name)
raise "Content is nil" if !content
rescue BlogDataNotFound
STDERR.puts "File #{file_name} not found"
rescue BlogDataConnectError
@connect_tries ||= 1
@connect_tries += 1
retry if @connect_tries < 3
STDERR.puts "Invalid blog data in #{file_name}"
rescue Exception => exc
STDERR.puts "Error loading #{file_name}: #{exc.message}"
raise
end
| true |
da7ebc098175a95c6eb0da40799b0e88a9a00e19
|
Ruby
|
shachsan/collections_practice-dumbo-web-102918
|
/collections_practice.rb
|
UTF-8
| 579 | 3.8125 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def sort_array_asc(arr)
arr.sort
end
def sort_array_desc(arr)
arr.sort.reverse
end
def sort_array_char_count(arr)
arr.sort_by{|ele|ele.length}
end
def swap_elements(arr)
new_arr = [arr[0]]+ (arr[1],arr[2] = arr[2], arr[1])
end
def reverse_array(arr)
arr.reverse
end
def kesha_maker(names)
names.map {|name|name.chars.map.with_index{|ch, i|i==2 ? '$' : ch}.join}
end
def find_a(words)
words.select {|word|word[0]=='a'}
end
def sum_array(arr)
arr.reduce(:+)
end
def add_s(words)
words.map.with_index { |word, i|i != 1 ? word+"s" : word }
end
| true |
f084a125705499333e447933435435059773d4fc
|
Ruby
|
AnnaAguilar/registro_academico
|
/registro.rb
|
UTF-8
| 280 | 3.3125 | 3 |
[] |
no_license
|
class Registro
attr_accessor :codigo
attr_accessor :nome
def initialize (codigo, nome)
@nome = nome
@codigo = codigo
end
#Compara o nome e codigo do curso
def == (outro)
@codigo == outro.codigo && @nome == outro.nome
end
end
| true |
bff7d0c54d79f39581941c9175f5a60878da2aa9
|
Ruby
|
bedwardsphoto/oo-email-parser-v-000
|
/lib/email_parser.rb
|
UTF-8
| 405 | 3.671875 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Build a class EmailParser that accepts a string of unformatted
# emails. The parse method on the class should separate them into
# unique email addresses. The delimiters to support are commas (',')
require 'pry'
class EmailParser
def initialize(email_string)
@email_string=email_string
end
def parse
holder=@email_string.split(/[\s ,]/)
holder.delete_if {|email| email.empty?}
holder.uniq
end
end
| true |
942aa54c82cdd0278c4c356e825bd70849e68761
|
Ruby
|
lilyylarsen/ttt-1-welcome-rb-q-000
|
/lib/welcome.rb
|
UTF-8
| 175 | 2.953125 | 3 |
[] |
no_license
|
# Edit this file to output "Welcome to Tic Tac Toe!"
# You can seeput what this file does by running:
# ruby lib/welcome.rb from your terminal.
puts "Welcome to Tic Tac Toe!"
| true |
356c19d7854cf0e0a83240dd3a0a8c5f1ed70971
|
Ruby
|
pedz/Raptor
|
/app/models/ldap_user.rb
|
UTF-8
| 2,366 | 2.578125 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
#
# Copyright 2007-2011 Ease Software, Inc. and Perry Smith
# All Rights Reserved
#
#
# This is a class that fetches LDAP entries from Bluepages of type
# ibmPerson. The default key is uid which is the "employee number".
# Thus the following would find me:
#
# LdapUser.find('C-5UEV897')
#
# The ActiveLdap::find is very powerful and versatile. To fine me via
# mail intranet id:
#
# LdapUser.find(:first, :attribute => 'mail', :value => '[email protected]')
#
# Or, to find everyone in a department:
#
# LdapUser.find(:all, :attribute => 'dept', :value => '5IEA')
#
# Note that these classes are called LdapXxxx pretending to be general
# LDAP classes but really they are Bluepages specific since they
# depend upon the structure of Bluepages.
class LdapUser < ActiveLdap::Base
ldap_mapping(:dn_attribute => 'uid',
:prefix => 'ou=bluepages',
:classes => [ 'ibmPerson' ])
##
# :attr: mgr
# A belongs_to association to an LdapUser for the user's manager.
belongs_to :mgr, :class => 'LdapUser', :foreign_key => 'manager', :primary_key => 'dn'
##
# :attr: deptmnt
# (I have to be careful not to collide with existing Bluepages
# attributes -- thus the funky name). A belongs_to association to
# an LdapDept for the user's department.
belongs_to :deptmnt, :class => 'LdapDept', :foreign_key => 'dept', :primary_key => 'dept'
##
# :attr: manages
# A has_many association returning the LdapUser entries for this user.
has_many :manages, :class => 'LdapUser', :foreign_key => 'manager', :primary_key => 'dn'
##
# Authenticate the intranet email address and password against
# Bluepages.
def self.authenticate_from_email(email, password)
return nil unless (u = find(:first, :attribute => 'mail', :value => email, :attributes => [ 'dn']))
begin
# dn = u.dn.to_s.gsub(/\+/, "\\\\+")
dn = u.dn.to_s
logger.info("authenticate_from_email #{email} => #{dn}")
u.connection.rebind(:allow_anonymous => false, :password => password, :bind_dn => dn)
rescue => e
# logger.debug("authenticate_from_email denied #{e.class} #{e.message}")
nil
end
end
# A silly method to return my entry used for testing and such. The
# 'q' is for 'quick'
def self.q
find(:first, :attribute => 'mail', :value => '[email protected]')
end
end
| true |
669a1e5d15f4bd0db1195e4e6e3f2b23117ac365
|
Ruby
|
geebabygee/food-dev-livecode1
|
/app/repositories/customer_repository.rb
|
UTF-8
| 912 | 3.0625 | 3 |
[] |
no_license
|
require_relative "base_repository"
require_relative "../models/customer"
class CustomerRepository < BaseRepository
private
def load_csv # From CSV strings ---> Ruby instances of element
csv_options = {headers: :first_row, header_converters: :symbol}
CSV.foreach(@csv_file, csv_options) do |row|
#row is now a hash --> {id: "1", name: "Iri", address: "Lisbon"}
row[:id] = row[:id].to_i
row[:address] = row[:address]
@elements << Customer.new(row) # @elements because this is now found in the Base Repository
end
@next_id = @elements.last.id + 1 unless @elements.empty?
end
def save_to_csv # From ruby instances ---> csv strings
CSV.open(@csv_file, 'wb') do |row|
row << ["id", "name", "address"]
@elements.each do |customer| # @elements because this is now found in the Base Repository
row << [customer.id, customer.name, customer.address]
end
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.