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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e7e3a52d8987cd011bf9bcaba8bb7a3d5bc07d69
|
Ruby
|
rahulpatel-tavant/hackerearth
|
/hackerearth-master/ruby/manan-and-toys.rb
|
UTF-8
| 243
| 3.15625
| 3
|
[] |
no_license
|
temp = gets.chomp.strip.split(' ').map(&:to_i)
n = temp[0]
k = temp[1]
arr = gets.chomp.strip.split(' ').map(&:to_i).sort
sum = 0
count = 0
(0...n).each do |i|
sum += arr[i]
count += 1
if sum > k
puts count - 1
break;
end
end
| true
|
ae192c9ddaab4f1d0ae72f217b19f0341c5aedb2
|
Ruby
|
highwide/abc_programming
|
/026/b.rb
|
UTF-8
| 254
| 3.234375
| 3
|
[] |
no_license
|
n = gets.chomp.to_i
rs = []
n.times do
rs << gets.chomp.to_i
end
rs.sort! {|a, b| b <=> a}
answer = rs.each_with_index.inject(0) do |sum, (r, i)|
if i % 2 == 0
sum + r ** 2 * Math::PI
else
sum - r ** 2 * Math::PI
end
end
puts answer
| true
|
0310655ff3986fe602af235a34bdf888a4a2a439
|
Ruby
|
HenriqueSaKi/Curso-Automacao-Testes-Ruby
|
/RubyBásico/time.rb
|
UTF-8
| 130
| 3.046875
| 3
|
[] |
no_license
|
#Determina a quantidade de vezes que o programa irá executar a ação
5.times{puts "Henrique"} #Irá imprimir 'Henrique' 5 vezes
| true
|
dce52fcaac3eaba7737353500a6f6a2f561e5570
|
Ruby
|
escray/geektime
|
/algo/05_Array/lc015_3_sum_v1.rb
|
UTF-8
| 722
| 3.578125
| 4
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'set'
# @param {Integer[]} nums
# @return {Integer[][]}
def three_sum(nums)
return [] if nums.size < 3
nums.sort!
# puts nums
result = Set.new
i = 0
until i > nums.size - 3
lo = i + 1
puts lo
hi = nums.size - 1
puts hi
sum = 0 - nums[i]
puts sum
while lo < hi
if nums[lo] + nums[hi] == sum
result.add([nums[i], nums[lo], nums[hi]])
lo += 1 while nums[lo] == nums[lo + 1]
hi -= 1 while nums[hi] == nums[hi - 1]
lo += 1
hi -= 1
elsif nums[lo] + nums[hi] < sum
lo += 1
else
hi -= 1
end
end
i += 1
end
result
end
puts three_sum([-1, 0, 1, 2, -1, -4])
| true
|
33beb0970f75467785cc2c845a25e3b21b8c0518
|
Ruby
|
chenyukang/rubytt
|
/tests/cases/index.rb
|
UTF-8
| 44
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
a = [1, 2, 3, "now"]
b = 1
c = a[b]
puts c
| true
|
0c47ad7c0486c0f5e17395d05d8701fb0eaefec4
|
Ruby
|
stubailo/Pantsdora
|
/app/lib/zappos.rb
|
UTF-8
| 1,069
| 2.765625
| 3
|
[] |
no_license
|
require 'open-uri'
require 'json'
class Zappos
@@api_key = "dafa6d39a387344ebf8582bb58806d535ce47dce"
def self.get_response(path = "", query = {})
query["key"] = @@api_key
query_list = []
query.each_pair{|k,v| query_list << "#{k}=#{v}"}
query_string = URI.escape(query_list.join("&"))
url = "http://api.zappos.com" + path + "?" + query_string
JSON.parse(open(url).read)
end
def self.get_pants(search_term = "")
num_pants = self.get_response("/Search", {"term" => "pants " + search_term})["totalResultCount"]
num_pages = num_pants.to_i / 10
page_to_get = rand(num_pages)
pants = self.get_response("/Search", {"term" => "pants " + search_term, "page" => page_to_get})["results"]
end
def self.get_random_pant(search_term = "")
pant = self.get_pants(search_term).sample
large_image_url = self.get_response("/Image", {"styleId" => pant["styleId"], "recipe" => "[\"DETAILED\"]"})[pant["styleId"]][0]["filename"]
pant["largeImageUrl"] = large_image_url
return pant
end
end
| true
|
8b062b46114df36a04bdb35fbd3a3a6e65ffa99f
|
Ruby
|
gjtorikian/commonmarker
|
/test/extensions_test.rb
|
UTF-8
| 2,262
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require "test_helper"
class TestExtensions < Minitest::Test
def setup
@markdown = fixtures_file("table.md")
end
def test_uses_specified_extensions
Commonmarker.to_html(@markdown, options: { extension: {} }).tap do |out|
assert_includes(out, "| a")
assert_includes(out, "| <strong>x</strong>")
assert_includes(out, "~~hi~~")
end
Commonmarker.to_html(@markdown, options: { extension: { table: true } }).tap do |out|
refute_includes(out, "| a")
["<table>", "<tr>", "<th>", "a", "</th>", "<td>", "c", "</td>", "<strong>x</strong>"].each { |html| assert_includes(out, html) }
assert_includes(out, "~~hi~~")
end
Commonmarker.to_html(@markdown, options: { extension: { strikethrough: true } }).tap do |out|
assert_includes(out, "| a")
refute_includes(out, "~~hi~~")
assert_includes(out, "<del>hi</del>")
end
end
def test_comments_are_kept_as_expected
options = { render: { unsafe: true }, extension: { tagfilter: true } }
assert_equal(
"<!--hello--> <blah> <xmp>\n",
Commonmarker.to_html("<!--hello--> <blah> <xmp>\n", options: options),
)
end
def test_definition_lists
markdown = <<~MARKDOWN
~strikethrough disabled to ensure options accepted~
Commonmark Definition
: Ruby wrapper for comrak (CommonMark parser)
MARKDOWN
extensions = { strikethrough: false, description_lists: true }
options = { extension: extensions, render: { hardbreaks: false } }
output = Commonmarker.to_html(markdown, options: options)
html = <<~HTML
<p>~strikethrough disabled to ensure options accepted~</p>
<dl><dt>Commonmark Definition</dt>
<dd>
<p>Ruby wrapper for comrak (CommonMark parser)</p>
</dd>
</dl>
HTML
assert_equal(output, html)
end
def test_emoji_renders_by_default
assert_equal(
"<p>Happy Friday! 😄</p>\n",
Commonmarker.to_html("Happy Friday! :smile:"),
)
end
def test_can_disable_emoji_renders
options = { extension: { shortcodes: false } }
assert_equal(
"<p>Happy Friday! :smile:</p>\n",
Commonmarker.to_html("Happy Friday! :smile:", options: options),
)
end
end
| true
|
1f2d6627d7259f0a14fc65c090db4163a1a9bd87
|
Ruby
|
Zarecki/week5_weekend_homework
|
/card_test_spec.rb
|
UTF-8
| 641
| 2.875
| 3
|
[] |
no_license
|
require('minitest/autorun')
require('minitest/rg')
require_relative('./card.rb')
require_relative('./testing_tast_3.rb')
class TestCard < Minitest::Test
def setup
@card1 = Card.new("hearts", 1)
@card2 = Card.new("clubs", 9)
@cardgame = CardGame.new
end
def test_check_for_ace
card1 = @card1
result = @cardgame.check_for_ace(card1)
assert_equal(true, result)
end
def test_highest_card
card1 = @card1
card2 = @card2
result = @cardgame.highest_card(card1, card2)
assert_equal(card2, result)
end
def test_cards_total
cards = [@card1, @card2]
result = CardGame.cards_total(cards)
assert_equal(10, result)
end
end
| true
|
013466c853b1386e71b55632a1db89566eaa5d50
|
Ruby
|
artistcoder/aAopen
|
/rspec_exercise_2/lib/part_1.rb
|
UTF-8
| 1,224
| 3.578125
| 4
|
[] |
no_license
|
def partition(arr, num)
less_than = []
greater_equal = []
final = []
arr.each do |n|
if n < num
less_than << n
else
greater_equal << n
end
end
final.push(less_than, greater_equal)
end
def merge(hash_1,hash_2)
final_hash = Hash.new(0)
hash_1.each do |k,v|
if !hash_2.has_key?(k)
final_hash[k] = v
end
end
hash_2.each do |k,v|
final_hash[k] = v
end
final_hash
end
def censor(str, arr)
vowels = "aeiouAEIOU"
new_str = []
str.split.each do |word|
if arr.include?(word.downcase)
new_word = ""
word.each_char do |let|
if vowels.include?(let)
new_word += "*"
else
new_word += let
end
end
new_str << new_word
else
new_str << word
end
end
new_str.join(" ")
end
def power_of_two?(n)
if n == 1
return true
end
(1...n).inject do |tot,ele|
if tot < n
tot * 2
elsif tot == n
return true
else
return false
end
end
end
| true
|
a5605cf93fbc29bec68776de19ecec12ac6ec654
|
Ruby
|
XYUnknown/image_editor
|
/process.rb
|
UTF-8
| 2,721
| 3.375
| 3
|
[] |
no_license
|
require_relative 'image_editor'
IMG = "images/"
EXT = ".jpg"
SUCCESS_MSG = "Done!"
def run
puts("Please enter your image name (please ensure it is under path images/):")
img = IMG + gets.strip! + EXT
begin
test_open_img(img)
rescue Exception
puts("Ooops... wrong image path!")
exit(status=1)
end
puts("Please enter your new image name:")
name = IMG+ gets.strip! + EXT
puts("Please enter your operation:")
puts("crop, compress, resize")
op = gets.downcase.strip!
case op
when "crop"
puts("Do you want to crop by ratio or size, i.e., width and length? (r/s)")
val = gets.downcase.strip!
case val
when "r"
puts("Please enter target ratio:")
r = gets.to_f
begin
run_ratio(img, r, name)
puts(SUCCESS_MSG)
rescue Exception
puts("Ooops... invalid input")
end
when "s"
puts("Please enter target width:")
w = gets.to_i
puts("Please enter target height:")
h = gets.to_i
begin
run_size(img, w, h, name)
puts(SUCCESS_MSG)
rescue Exception
puts("Ooops... invalid input")
end
else
puts("wrong arguments!")
end
when "compress"
puts("Please enter target quality (an integer range from 0-100)")
q = gets.to_i
begin
run_quality(img, q, name)
puts(SUCCESS_MSG)
rescue Exception
puts("Ooops... invalid input")
end
when "resize"
puts("Notice that original ratio will be maintained.")
puts("Please enter target width:")
w = gets.to_i
puts("Please enter target height:")
h = gets.to_i
begin
run_resize(img, w, h, name)
puts(SUCCESS_MSG)
rescue Exception
puts("Ooops... invalid input")
end
else
puts("wrong operation!")
end
end
def run_size(img, width, height, name)
# img = 'image/test.jpg'
ie = ImageEditor.new(img, width, height)
ie.crop_img
# name = 'image/my_img_s.jpg'
ie.save(name)
end
def run_ratio(img, ratio, name)
# img = 'image/test.jpg'
ie = ImageEditor.new(img, ratio)
ie.crop_img
# name = 'image/my_img_r.jpg'
ie.save(name)
end
def run_quality(img, quality, name)
# img = 'image/test.jpg'
ie = ImageEditor.new(img, 1000, 1000)
ie.reset_quality(quality)
# name = 'image/my_img_q.jpg'
ie.save(name)
end
def run_resize(img, width, height, name)
# img = 'image/test.jpg'
ie = ImageEditor.new(img, width, height)
ie.resize_img
# name = 'image/my_img_rs.jpg'
ie.save(name)
end
def test_open_img(img)
MiniMagick::Image.open(img)
end
## run programme
run
| true
|
e333f1a71bfd155353e3b5b9e3f965a2ad270ab4
|
Ruby
|
kpennachio/restaurant-tycoon
|
/tools/console.rb
|
UTF-8
| 398
| 2.96875
| 3
|
[] |
no_license
|
require_relative '../config/environment.rb'
essen = Restaurant.new("Essen")
potbelly = Restaurant.new("Potbelly")
place1 = Location.new(essen, "address", 200)
place2 = Location.new(essen, "another address", 100)
place3 = Location.new(potbelly, "here", 300)
em1 = Employee.new("Kevin", 8, place1)
em2 = Employee.new("Katie", 9, place1)
em3 = Employee.new("Julia", 10, place2)
binding.pry
| true
|
40aa996a42cdfc0501bfb870de025efb25eeb993
|
Ruby
|
halfalpine/learn-ruby
|
/03_simon_says/simon_says.rb
|
UTF-8
| 817
| 3.8125
| 4
|
[] |
no_license
|
def echo(echo_text)
echo_text
end
def shout(shout_text)
shout_text.upcase
end
def repeat(repeat_text, num_repeats = 2)
final_string = ""
while num_repeats > 0
final_string = final_string + " " + repeat_text
num_repeats -= 1
end
final_string.strip
end
def start_of_word(first_word, how_many)
starting_letters = first_word[0, how_many]
return starting_letters
end
def first_word(some_word)
some_word.split.first
end
def titleize(some_title)
small_words = ["and", "or", "if", "a", "an", "of", "over", "the"]
working_title = some_title.split(" ")
working_title.each do |word|
if
small_words.any? { |small_word| word === small_word }
else
word.capitalize!
end
working_title.first.capitalize!
end
final_edit = working_title.join(" ")
final_edit
end
| true
|
f738d8c93b4933b1abf10ba301ff42e8fe8f84ad
|
Ruby
|
lshimokawa/activegraph
|
/lib/active_graph/shared/declared_property/index.rb
|
UTF-8
| 1,273
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
module ActiveGraph::Shared
class DeclaredProperty
# None of these methods interact with the database. They only keep track of property settings in models.
# It could (should?) handle the actual indexing/constraining, but that's TBD.
module Index
def index_or_constraint?
index?(:exact) || constraint?(:unique)
end
def index?(type = :exact)
options.key?(:index) && options[:index] == type
end
def constraint?(type = :unique)
options.key?(:constraint) && options[:constraint] == type
end
def index!(type = :exact)
fail ActiveGraph::InvalidPropertyOptionsError, "Can't set index on constrainted property #{name} (constraints get indexes automatically)" if constraint?(:unique)
options[:index] = type
end
def constraint!(type = :unique)
fail ActiveGraph::InvalidPropertyOptionsError, "Can't set constraint on indexed property #{name} (constraints get indexes automatically)" if index?(:exact)
options[:constraint] = type
end
def unindex!(type = :exact)
options.delete(:index) if index?(type)
end
def unconstraint!(type = :unique)
options.delete(:constraint) if constraint?(type)
end
end
end
end
| true
|
b57481d59b56dc34be772d5979c93e079eb0f029
|
Ruby
|
chadjemmett/working_rogue
|
/bomb.rb
|
UTF-8
| 220
| 3.078125
| 3
|
[] |
no_license
|
#bombs
class Bomb
attr_reader :x, :y
def initialize(x, y)
@x = x
@y =y
@icon = Gosu::Font.new(15)
@color = Gosu::Color::RED
end
def draw
@icon.draw("B", @x, @y, 1, 1, 1, @color)
end
end
| true
|
4c98cf787136c09d678b71541a12db16468617e3
|
Ruby
|
jamieberrier/ruby-objects-has-many-lab-v-000
|
/lib/artist.rb
|
UTF-8
| 789
| 3.625
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# An artist should have many songs and a song should belong to an artist
require 'pry'
class Artist
attr_accessor :name
@@songs = []
def initialize(name)
@name = name
end
def songs
@@songs
end
# takes in an argument of a song and associates that song with the artist by telling the song that it belongs to that artist
def add_song(song)
@@songs << song
song.artist = self
end
# takes in an argument of a song name, creates a new song with it and associates the song and artist
def add_song_by_name(song_name)
song = Song.new(song_name)
@@songs << song
song.artist = self
end
# is a class method that returns the total number of songs associated to all existing artists
def self.song_count
@@songs.length
end
end
| true
|
985d95215dc630392f72b5b806eaf76fb7012357
|
Ruby
|
minixia/zhidequ2
|
/models/question.rb
|
UTF-8
| 1,774
| 2.53125
| 3
|
[] |
no_license
|
class Question < ActiveRecord::Base
after_initialize :default_value
belongs_to :account #asker
has_and_belongs_to_many :tags
has_many :answers
validates :title, :presence => true
validates :account_id, :presence => true
self.per_page = 10
def tag(name, type = nil)
tag = Tag.find_by_name(name)
if(!tag.nil?)
if(!self.tags.exists?(tag))
self.tags << tag
tag.count += 1
tag.save!
end
else
alias_tag = TagAlias.find_by_tag_alias(name)
if(!alias_tag.nil?)
self.tag(alias_tag.tag_name)
else
tag = Tag.new
tag.name = name
tag.tag_type = type
tag.count = 1
tag.save!
self.tags << tag
end
end
end
def untag(tag)
self.tags.delete(tag)
tag.count -= 1
tag.save!
end
def view(ip)
if QuestionView.count(:conditions=>{:question_id => self.id, :ip => ip}) == 0
qv = QuestionView.new
qv.question = self
qv.ip = ip
qv.save!
self.update_attribute('views', self.views + 1)
end
end
def self.list(tags, order)
main_tags = []
tags.each{|tag|
alias_tag = TagAlias.find_by_tag_alias(tag)
if (alias_tag)
main_tags << alias_tag.tag_name
else
main_tags << tag
end
}
main_tags_cond = main_tags.uniq.to_s.tr('[]', '').tr('"', '\'')
return Question.from("questions where not exists (select id from tags where tags.name in (#{main_tags_cond}) and not exists (select * from questions_tags as qt where qt.question_id=questions.id and qt.tag_id = tags.id))").order(order)
end
private
def default_value
self.asked_at ||= Time.now
self.views ||= 0
self.votes ||= 0
self.followers ||= 0
end
end
| true
|
6410fda79f352709b36246225c68bc01ff3ca6a1
|
Ruby
|
mariesonko/my-collect-dumbo-web-042318
|
/lib/my_collect.rb
|
UTF-8
| 175
| 3.375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def my_collect(collection)
n=0
my_collection =[]
while n < collection.length
my_collection << (yield collection[n])
n+=1
end
my_collection
end
| true
|
cc9e5a8311911e6f06d1858ffd098d03da3493a1
|
Ruby
|
vadimvny/basketballnyc
|
/models/court.rb
|
UTF-8
| 178
| 2.625
| 3
|
[] |
no_license
|
class Court < ActiveRecord::Base
def split_address
courts = Court.all
address = courts.each {|x| x.address}
address = address[0..100].map {|x| x.split(',')}
end
end
| true
|
a82c03634585f2a021c2e960e1c210829dd2a3ca
|
Ruby
|
cyb-/card-app
|
/app/models/rules/developer_vs_dragon.rb
|
UTF-8
| 896
| 2.75
| 3
|
[] |
no_license
|
class Rules::DeveloperVsDragon < Rule
# Configurations =============================================================
attr_reader :developer, :dragon
# Callbacks ==================================================================
after_initialize :identify_cards!
# Class Methods ==============================================================
# Instance Methods ===========================================================
protected #===================================================================
# def fight!
# super
# end
# def fightable?
# super
# end
private #=====================================================================
def fighting!
Rails.logger.info "Developer is the winner because it's a developer !!".colorize(:magenta)
@winner = developer
end
def identify_cards!
@developer = @card1
@dragon = @card2
end
end
| true
|
4e4f2b15d12fcb5f4128eed45660012d3ec5bf6a
|
Ruby
|
AlbayrakSanli/morpion
|
/app.rb
|
UTF-8
| 607
| 2.84375
| 3
|
[] |
no_license
|
require 'bundler'
Bundler.require
require_relative 'lib/boardcase'
require_relative 'lib/board'
require_relative 'lib/player'
require_relative 'lib/game'
require_relative 'lib/application'
require_relative 'lib/show'
my_board = Board.new
my_application = Application.new
puts "Veux-tu voir un moment fort ? [YES/no]"
response = "#{gets.chomp}"
if response == "YES" && !my_application.game.nil?
puts "Donne moi un chiffre compris entre 0 et #{my_application.photo.length}"
my_show = Show.new(my_application, gets.chomp.to_i)
else
puts "Sois tu n'as lancé aucun jeu, sois tu n'as pas dit YES !"
end
| true
|
76be707ae1aefc2744de1dfd7b2da54f8537ba10
|
Ruby
|
iastewar/chess_game
|
/pieces/king.rb
|
UTF-8
| 800
| 3.84375
| 4
|
[] |
no_license
|
require 'colorize'
require './piece.rb'
class King < Piece
def initialize(color)
super(color)
end
def to_string
if color
"K ".white
else
"K ".black
end
end
def to_sym
if color
return :kw
else
return :kb
end
end
# returns an array of possible moves from position parameter (an array with 2 elements) (e.g. [0,0] means piece is at position 0,0)
def possible_moves(position, board, color)
out_array = []
x = position[0]-1
y = position[1]-1
(x..x+2).each do |row|
break if row > 7
(y..y+2).each do |column|
break if column > 7
if !board[row][column] || board[row][column].color != color
out_array.push([row, column])
end
end
end
out_array
end
end
| true
|
3917188570fdf88a0251d39910c1d8d39f301490
|
Ruby
|
AbhiFalcao/RailsIntro
|
/Lesson5/code_alongs/lib/tiger.rb
|
UTF-8
| 194
| 3.171875
| 3
|
[] |
no_license
|
require 'lib/animal'
class Tiger > Animal
attr_accessor = :food_type
def initialize(food_type="meat", pet_name, zoo_keeper)
@food_type = food_type
super(pet_name, zoo_keeper)
end
end
| true
|
0d625b17eca91ee6e567bbafa32f224ff7e5986a
|
Ruby
|
immorsh/learn_ruby_rspec
|
/01_temperature/temperature.rb
|
UTF-8
| 123
| 2.625
| 3
|
[] |
no_license
|
def ftoc(fc)
return ((fc - 32.00) * (5.00/9.00))
end
def ctof(cf)
return(cf * 9.00 / 5.00 + 32.00)
end
| true
|
0ba114bbcebdfa5abab5206be3674accfde88d5d
|
Ruby
|
ppj/LearnRubyTheHardWay
|
/ex11.rb
|
UTF-8
| 346
| 3.875
| 4
|
[] |
no_license
|
# ex11.rb
print "How old are you again? "
age = gets.chomp
print "And how much did you say you weigh? "
wgt = gets.chomp
print "Whoa!!... Alright\nBut then, how tall are you? "
hgt = gets.chomp()
print "So, let me get this right\nYou are #{age}, #{hgt} tall, and weigh #{wgt}??!!"
print "No no no no... you've gotta do something about it buddy!'"
| true
|
2e0a680c720a0dcb4cd35000f2be6df99605a78b
|
Ruby
|
emystein/ruby-exercises
|
/lib/prime_factors.rb
|
UTF-8
| 203
| 3.265625
| 3
|
[] |
no_license
|
require 'prime'
# https://www.codewars.com/kata/54d512e62a5e54c96200019e
def prime_factors(number)
factors = number.prime_division
factors.map { |p, e| e == 1 ? "(#{p})" : "(#{p}**#{e})" }.join
end
| true
|
e66b861bfd861b5144b1797b03c4d91284e40422
|
Ruby
|
jeremyevans/roda
|
/lib/roda/plugins/error_handler.rb
|
UTF-8
| 4,616
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
# frozen-string-literal: true
#
class Roda
module RodaPlugins
# The error_handler plugin adds an error handler to the routing,
# so that if routing the request raises an error, a nice error
# message page can be returned to the user.
#
# You can provide the error handler as a block to the plugin:
#
# plugin :error_handler do |e|
# "Oh No!"
# end
#
# Or later via the +error+ class method:
#
# plugin :error_handler
#
# error do |e|
# "Oh No!"
# end
#
# In both cases, the exception instance is passed into the block,
# and the block can return the request body via a string.
#
# If an exception is raised, a new response will be used, with the
# default status set to 500, before executing the error handler.
# The error handler can change the response status if necessary,
# as well set headers and/or write to the body, just like a regular
# request. After the error handler returns a response, normal after
# processing of that response occurs, except that an exception during
# after processing is logged to <tt>env['rack.errors']</tt> but
# otherwise ignored. This avoids recursive calls into the
# error_handler. Note that if the error_handler itself raises
# an exception, the exception will be raised without normal after
# processing. This can cause some after processing to run twice
# (once before the error_handler is called and once after) if
# later after processing raises an exception.
#
# By default, this plugin handles StandardError and ScriptError.
# To override the exception classes it will handle, pass a :classes
# option to the plugin:
#
# plugin :error_handler, classes: [StandardError, ScriptError, NoMemoryError]
module ErrorHandler
DEFAULT_ERROR_HANDLER_CLASSES = [StandardError, ScriptError].freeze
# If a block is given, automatically call the +error+ method on
# the Roda class with it.
def self.configure(app, opts={}, &block)
app.opts[:error_handler_classes] = (opts[:classes] || app.opts[:error_handler_classes] || DEFAULT_ERROR_HANDLER_CLASSES).dup.freeze
if block
app.error(&block)
end
end
module ClassMethods
# Install the given block as the error handler, so that if routing
# the request raises an exception, the block will be called with
# the exception in the scope of the Roda instance.
def error(&block)
define_method(:handle_error, &block)
alias_method(:handle_error, :handle_error)
private :handle_error
end
end
module InstanceMethods
# If an error occurs, set the response status to 500 and call
# the error handler. Old Dispatch API.
def call
# RODA4: Remove
begin
res = super
ensure
_roda_after(res)
end
rescue *opts[:error_handler_classes] => e
_handle_error(e)
end
# If an error occurs, set the response status to 500 and call
# the error handler.
def _roda_handle_main_route
begin
res = super
ensure
_roda_after(res)
end
rescue *opts[:error_handler_classes] => e
_handle_error(e)
end
private
# Default empty implementation of _roda_after, usually
# overridden by Roda.def_roda_before.
def _roda_after(res)
end
# Handle the given exception using handle_error, using a default status
# of 500. Run after hooks on the rack response, but if any error occurs
# when doing so, log the error using rack.errors and return the response.
def _handle_error(e)
res = @_response
res.send(:initialize)
res.status = 500
res = _roda_handle_route{handle_error(e)}
begin
_roda_after(res)
rescue => e2
if errors = env['rack.errors']
errors.puts "Error in after hook processing of error handler: #{e2.class}: #{e2.message}"
e2.backtrace.each{|line| errors.puts(line)}
end
end
res
end
# By default, have the error handler reraise the error, so using
# the plugin without installing an error handler doesn't change
# behavior.
def handle_error(e)
raise e
end
end
end
register_plugin(:error_handler, ErrorHandler)
end
end
| true
|
053bdab90011d8380d96a0c639cbf4b8539ce247
|
Ruby
|
abadfish/deli-counter-v-000
|
/deli_counter.rb
|
UTF-8
| 600
| 4.09375
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Write your code here.
def line(katz_deli)
if katz_deli == []
puts "The line is currently empty."
else
new_deli = katz_deli.collect.with_index do |name,place|
"#{place+1}. #{name}"
end
puts "The line is currently: #{new_deli.join(" ")}"
end
end
def take_a_number(katz_deli, name)
katz_deli.push(name)
puts "Welcome, #{name}. You are number #{katz_deli.index(name)+1} in line."
end
def now_serving(katz_deli)
if katz_deli == []
puts "There is nobody waiting to be served!"
else
puts "Currently serving #{katz_deli.first}."
katz_deli.shift
end
end
| true
|
f33c26077eaf0a52d8bbc6977761721a019b1082
|
Ruby
|
nsw125/tic_tac_toe
|
/tictactoe.rb
|
UTF-8
| 3,876
| 3.90625
| 4
|
[] |
no_license
|
class Game
def initialize
puts "Enter a name for player one."
@player1 = Player.new(gets.chomp)
puts "Enter a name for player two."
@player2 = Player.new(gets.chomp)
puts "Our players are: #{@player1.name} and #{@player2.name}! Let's see who gets to decide turn order..."
puts
puts
coin_flip = rand(1..2)
if coin_flip == 1
@current_player = @player1
symbol_chooser = @player2
else
@current_player = @player2
symbol_chooser = @player1
end
puts "#{@current_player.name} wins the toss, and gets to go first!"
puts "But first, #{symbol_chooser.name}, would you like to be X's or O's? Enter (x/o)"
symbol = gets.chomp.downcase
until symbol == 'x' or symbol == 'o'
puts "You can't enter that, enter x or o."
symbol = gets.chomp
end
symbol == 'x' ? other_symbol = 'o' : other_symbol = 'x'
@current_player.symbol = other_symbol
@current_player == @player1 ? @player2.symbol = symbol : @player1.symbol = symbol
puts "#{symbol_chooser.name} will be #{symbol_chooser.symbol.upcase}'s and #{@current_player.name} will be #{@current_player.symbol.upcase}'s"
puts
@boxes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@boxes[0] = 'a'
@row1 = @boxes[1..3]
@row2 = @boxes[4..6]
@row3 = @boxes[7..9]
@winner = nil
end
def play_game
while @winner == nil
player_turn
end
end
def show_board
@row1 = @boxes[1..3]
@row2 = @boxes[4..6]
@row3 = @boxes[7..9]
puts " " + @row1.join(' | ')
puts "-----------------"
puts " " + @row2.join(' | ')
puts "-----------------"
puts " " + @row3.join(' | ')
end
def player_turn
puts "#{@current_player.name}, it's your turn!"
puts "Pick any open square by entering the number shown inside of it."
player_entry = gets.chomp.to_i
until @boxes[player_entry] != 0 and @boxes[player_entry].is_a? Integer
puts 'that is not a valid option'
player_entry = gets.chomp.to_i
end
@boxes[player_entry] = @current_player.symbol
show_board
win_checker
@current_player == @player1 ? @current_player = @player2 : @current_player = @player1
end
def win_checker
if @boxes[1] == @boxes[2] and @boxes[2] == @boxes[3] #Horizontal Wins
@winner = @boxes[1]
elsif @boxes[4] == @boxes[5] and @boxes[5] == @boxes[6]
@winner = @boxes[4]
elsif @boxes[7] == @boxes[8] and @boxes[8] == @boxes[9]
@winner = @boxes[7]
elsif @boxes[1] == @boxes[5] and @boxes[5] == @boxes[9] #Diagonal Wins
@winner = @boxes[1]
elsif @boxes[3] == @boxes[5] and @boxes[5] == @boxes[7]
@winner = @boxes[3]
elsif @boxes[1] == @boxes[4] and @boxes[4] == @boxes[7] #Vertical wins
@winner = @boxes[1]
elsif @boxes[2] == @boxes[5] and @boxes[5] == @boxes[8]
@winner = @boxes[2]
elsif @boxes[3] == @boxes[6] and @boxes[6] == @boxes[9]
@winner = @boxes[3]
elsif @boxes.all? String
@winner = false
puts "Its a cat! No winner.."
end
if @winner == 'x' or @winner == 'o'
if @winner == @player1.symbol
puts "#{@player1.name} is the winner!"
else
puts "#{@player2.name} is the winner!"
end
end
end
end
class Player
attr_accessor :name, :symbol
def initialize(name, symbol=nil)
@name = name
@symbol = symbol
end
end
game = Game.new
game.show_board
game.play_game
| true
|
42243009ba0ae9e5513d02677e3d9532b04ffdf2
|
Ruby
|
ElaErl/Fundations
|
/lesson_3/6.rb
|
UTF-8
| 404
| 3.546875
| 4
|
[] |
no_license
|
produce = {'apple' => 'Fruit', 'carrot' => 'Vegetable', 'pear' => 'Fruit', 'broccoli' => 'Vegetable'}
def select_fruit(hsh)
counter = 0
pairs = []
loop do
current_item = hsh.keys[counter]
current_group = hsh[current_item]
counter += 1
if 'Fruit'.include?(current_group.to_s)
pairs << [current_item, current_group]
end
break if counter > hsh.size
end
pairs.to_h
end
puts select_fruit(produce)
| true
|
3466e6f94fa30a1281abd5421c922eb0d0b0619f
|
Ruby
|
ConorOwens/CLI_Town
|
/CLI_Town/lib/scraper.rb
|
UTF-8
| 684
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
require 'open-uri'
require 'nokogiri'
class CLI_Town::Scraper
def self.scrape_monster_list(monster_list)
monsters = []
monster_list_html = Nokogiri::HTML(open(monster_list))
monster_list_html.css('ul.column li a').each do |mon|
name = mon.text
url = mon.attr('href')
monsters << {name: name, url: url}
end
monsters
end
def self.scrape_monster(url)
url_html = Nokogiri::HTML(open(url))
url_html.css('tr th')
end
def self.scrape_feats(feats)
end
def self.scrape_magic_shop(magic_shop)
end
def self.scrape_provisioner(provisioner)
end
end
| true
|
2e95ba5790cddd0d70b1413ed38e76f4d0aa5ff4
|
Ruby
|
TribalDev/tribal_blog
|
/db/seeds.rb
|
UTF-8
| 831
| 2.5625
| 3
|
[] |
no_license
|
require 'faker'
5.times do
user = User.new(
name: Faker::Name.name,
email: Faker::Internet.email,
password: Faker::Lorem.characters(10)
)
user.skip_confirmation!
user.save!
end
users = User.all
25.times do
Post.create!(
user: users.sample,
title: Faker::Lorem.sentence,
text: Faker::Lorem.paragraph(2),
created_at: Faker::Date.between(10.days.ago, Date.today)
)
end
posts = Post.all
100.times do
Comment.create!(
user: users.sample,
post: posts.sample,
body: Faker::Lorem.paragraph
)
end
user = User.first
user.skip_reconfirmation!
user.update_attributes!(
name: 'Ghost',
email: 'pretend@shufflebox.org',
password: 'password11'
)
puts "Seed finished"
puts "#{User.count} users created"
puts "#{Post.count} posts created"
puts "#{Comment.count} comments created"
| true
|
0cd40346cac2b063ea729ca63ea03cef44506141
|
Ruby
|
rjspotter/lumos_take_home
|
/spec/lumos_take_home_spec.rb
|
UTF-8
| 3,141
| 3.03125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "LumosTakeHome" do
let(:sample) do
[
[1, 4.00, "ham_sandwich"],
[1, 8.00, "burrito"],
[2, 5.00, "ham_sandwich"],
[2, 6.50, "burrito"]
]
end
let(:subject) {LumosTakeHome.new}
before {subject.menu = sample}
it "takes a csv file and parses it into the menus" do
s = LumosTakeHome.new(File.expand_path(File.dirname(__FILE__) + '/menu1.csv'))
s.menu.should == [[[4.00, "ham_sandwich"],[8.00, "burrito"]], [[5.00, "ham_sandwich"], [6.50, "burrito"]]]
end
it "translates menus into an internal state" do
subject.menu.should == [[[4.00, "ham_sandwich"],[8.00, "burrito"]], [[5.00, "ham_sandwich"], [6.50, "burrito"]]]
end
describe "optimizer" do
it "returns 2,11.5 for sample data" do
subject.optimize("ham_sandwich","burrito").
should == [2,11.5]
end
it "returns 2,11.5 even if there are more expensive items that match" do
sample << [2, 8.00, "ham_sandwich"]
subject.menu = sample
subject.optimize("ham_sandwich","burrito").
should == [2,11.5]
end
context "combo meals" do
it "returns 3,10 for the combo meal" do
sample << [3, 10.0, "ham_sandwich", "burrito"]
subject.menu = sample
subject.optimize("ham_sandwich","burrito").
should == [3,10.0]
end
it "returns the combo meal instead of less efficient options" do
sample = [[1,6.0,'ham_sandwich'],
[1,6.0,'burrito'],
[1, 10.0, "ham_sandwich", "burrito"]]
subject.menu = sample
subject.optimize("ham_sandwich","burrito").
should == [1,10.0]
end
it "returns the combo meal instead of less efficient options" do
sample = [[1,6.0,'ham_sandwich'],
[1,6.0,'burrito'],
[1, 10.0, "ham_sandwich", "burrito"]]
subject.menu = sample
subject.optimize("ham_sandwich","burrito").
should == [1,10.0]
end
end
end
context "given examples" do
it "returns nil" do
sample = [
[3, 4.00, "blt_sandwich"],
[3, 8.00, "chicken_wings"],
[4, 5.00, "chicken_wings"],
[4, 2.50, "coffee"]
]
subject.menu = sample
subject.optimize("blt_sandwich","coffee").
should == nil
end
it "returns 6,11" do
sample = [
[5, 4.00, 'fish_sandwich'],
[5, 8.00, 'milkshake'],
[6, 5.00, 'milkshake'],
[6, 6.00, 'fish_sandwich', "blue_berry_muffin", "chocolate_milk"]
]
subject.menu = sample
subject.optimize("milkshake","fish_sandwich").
should == [6,11.0]
end
end
end
describe "wrapper" do
it "should return the simple case" do
executable = File.expand_path(File.dirname(__FILE__) + '/../bin/program')
csv = File.expand_path(File.dirname(__FILE__) + '/menu1.csv')
`#{executable} #{csv} ham_sandwich burrito`.should == "2,11.5"
end
end
| true
|
969529641c32a102c25e1781ebc602f1cf4297d6
|
Ruby
|
DRAKYULA/Euler_Problems
|
/testpalindrome.rb
|
UTF-8
| 100
| 2.890625
| 3
|
[] |
no_license
|
x = 92
y = 99
z = x * y
puts z
puts z.to_s.reverse
for z in test
if puts z == z.to_s.reverse
| true
|
38a716e3fd1526ff0664b51a7a0c79f2b1c4d007
|
Ruby
|
nog/atcoder
|
/contests/abc238/g/main.rb
|
UTF-8
| 959
| 2.875
| 3
|
[] |
no_license
|
N, Q = gets.split.map(&:to_i)
A = gets.split.map(&:to_i)
primes = []
require 'prime'
Prime.each(A.max ** 0.5) do |pr|
primes.push(pr)
end
llist = {}
rlist = {}
hashes = Array.new(Q){ Hash.new 0 }
results = Array.new Q
Q.times do |i|
l, r = gets.split.map(&:to_i)
l-=1
r-=1
llist[l] ||= []
llist[l].push(i)
rlist[r] ||= []
rlist[r].push(i)
end
cur = {}
N.times do |i|
a = A[i]
plist = []
primes.each do |pr|
break if a < pr
next if a % pr > 0
cnt = 1
a = a / pr
while(a % pr == 0) do
cnt += 1
a /= pr
end
plist.push([pr, cnt])
end
if a > 1
plist.push([a, 1])
end
(llist[i] || []).each do |j|
cur[j] = true
end
cur.keys.each do |i|
h = hashes[i]
plist.each do |pr, cnt|
h[pr] += cnt
end
end
(rlist[i] || []).each do |j|
results[j] = hashes[j].all?{|k,v| (v % 3) == 0}
cur.delete(j)
end
end
puts results.map{|x| x ? 'Yes' : 'No'}.join("\n")
| true
|
13fba579ea2762184955983938d1f45329c34a47
|
Ruby
|
ksweta/Monopoly
|
/app/controllers/game_controller.rb
|
UTF-8
| 2,261
| 2.515625
| 3
|
[] |
no_license
|
class GameController < ApplicationController
before_filter :authenticate_user!
def index
@games = Game.all
@users = User.all
end
def show
@game = Game.find(params[:id])
end
def join
@game = Game.find(params[:id])
player_exists = false
if @game.players.length < 4
@game.players.each do |player|
if player.user_id == current_user.id
player_exists = true
end
end
end
if !player_exists && @game.players.length < 4
@game.players.create!(user: current_user, position: 0, balance: 2000.00, email: current_user.email)
Pusher.trigger('game-'+params[:id].to_s, 'new-player', {:player => @game.players.length})
end
redirect_to :action => "show", id: params[:id]
end
def create
@game = Game.create!(turn: 0, status: :initialized, host: current_user.email)
@game.players.create!(user: current_user, position: 0, balance: 2000.00, email: current_user.email)
redirect_to :action => "show", id: @game.id #welcome_path
end
#Game Chat Update
def chat_message
Pusher.trigger('game-'+params[:id].to_s+'-chat', 'new-message', {:message => params[:message], :uid => current_user.email})
end
def start_button
p "IN START GAME"
@game = Game.find(params[:id])
@game.update(status: :inprogress)
p @game.status
Pusher.trigger('game-'+params[:id].to_s+'-chat', 'game-started',
{:message => "The host has started the game. Goodluck and have fun!",
:player_turn => @game.players[@game.turn].email})
end
def roll_dice
@game = Game.find(params[:id])
roll = 2 + rand(11)
current_turn = @game.turn
next_turn = current_turn + 1
if next_turn == @game.players.length
next_turn = 0
end
position = @game.players[current_turn].position
position += roll
if position > 39
position -= 39
balance = @game.players[current_turn].balance
balance += 200
@game.players[current_turn].update(balance: balance)
end
@game.update(turn: next_turn)
@game.players[current_turn].update(position: position)
Pusher.trigger('game-'+params[:id].to_s, 'dice-roll',
{:current_turn => current_turn, #0-3
:roll => roll,
:next_turn => next_turn, #0-3
:email => @game.players[next_turn].email,
:position => position})
end
end
| true
|
4892f026e2617a72bf8f39f0aa0ffaf59f9cfbd6
|
Ruby
|
tmdgusya/RubyAlgorithm
|
/leetcode/add_two_number.rb
|
UTF-8
| 484
| 3.296875
| 3
|
[] |
no_license
|
require 'test/unit'
def add_two_numbers(l1, l2)
l1_toS = ""
l2_toS = ""
while !l1.nil?
l1_toS += l1.val.to_s
l1 = l1.next
end
while !l2.nil?
l2_toS += l2.val.to_s
l2 = l2.next
end
l1_toI = l1_toS.reverse.to_i
l2_toI = l2_toS.reverse.to_i
answer = l1_toI + l2_toI
ans = []
answer.to_s.reverse.each_char do |char|
ans.push(char.to_i)
end
ans
end
| true
|
bac9f4ec96c49203ef1cfcc290d21d5d49a5286c
|
Ruby
|
wallentx/slack-backup
|
/log_test.rb
|
UTF-8
| 1,613
| 2.796875
| 3
|
[] |
no_license
|
require 'minitest/autorun'
require_relative 'log'
require 'stringio'
class LogTest < Minitest::Test
def test_log
io = StringIO.new
log = Log.new io
clear = -> do
io.truncate 0
io.rewind
end
clear[]
log.debug "test"
assert_equal <<-EOS, io.string
DEBUG test
EOS
clear[]
log.sub("foo").debug "test"
assert_equal <<-EOS, io.string
DEBUG foo: test
EOS
clear[]
log.sub("foo").sub("bar").debug "test"
assert_equal <<-EOS, io.string
DEBUG foo: bar: test
EOS
clear[]
log.sub("foo", bar: "baz").debug "test"
assert_equal <<-EOS, io.string
DEBUG foo: test bar=baz
EOS
clear[]
log.sub("foo", bar: "baz", baz: "quux")[baz: "foo"].debug "test"
assert_equal <<-EOS, io.string
DEBUG foo: test bar=baz baz=foo
EOS
clear[]
log.sub(bar: "baz")[bar: "foo"].debug "test"
assert_equal <<-EOS, io.string
DEBUG test bar=foo
EOS
clear[]
log.sub("foo").debug("test") { 1+1 }
assert_equal <<-EOS, replace_times(io.string)
DEBUG foo: test... TIME0
EOS
clear[]
log.sub("foo").debug("test1") do
log.sub("bar").debug("test2")
end
assert_equal <<-EOS, replace_times(io.string)
DEBUG foo: test1...
DEBUG bar: test2
DEBUG foo: test1... TIME0
EOS
clear[]
log.level = :info
log.debug "some debug"
log.info "some info"
log.sub("foo").debug "some debug 2"
log.sub("foo").info "some info 2"
assert_equal <<-EOS, io.string
INFO some info
INFO foo: some info 2
EOS
end
private def replace_times(s)
n = -1
s.gsub(/\.\.\. .+s$/) { "... TIME%d" % [n += 1] }
end
end
| true
|
34a0043dc8d7877d6fbffbf54b7a292c3f96f34b
|
Ruby
|
carrierwaveuploader/carrierwave
|
/lib/carrierwave/processing/rmagick.rb
|
UTF-8
| 11,878
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
module CarrierWave
##
# This module simplifies manipulation with RMagick by providing a set
# of convenient helper methods. If you want to use them, you'll need to
# require this file:
#
# require 'carrierwave/processing/rmagick'
#
# And then include it in your uploader:
#
# class MyUploader < CarrierWave::Uploader::Base
# include CarrierWave::RMagick
# end
#
# You can now use the provided helpers:
#
# class MyUploader < CarrierWave::Uploader::Base
# include CarrierWave::RMagick
#
# process :resize_to_fit => [200, 200]
# end
#
# Or create your own helpers with the powerful manipulate! method. Check
# out the RMagick docs at http://www.imagemagick.org/RMagick/doc/ for more
# info
#
# class MyUploader < CarrierWave::Uploader::Base
# include CarrierWave::RMagick
#
# process :do_stuff => 10.0
#
# def do_stuff(blur_factor)
# manipulate! do |img|
# img = img.sepiatone
# img = img.auto_orient
# img = img.radial_blur(blur_factor)
# end
# end
# end
#
# === Note
#
# You should be aware how RMagick handles memory. manipulate! takes care
# of freeing up memory for you, but for optimum memory usage you should
# use destructive operations as much as possible:
#
# DON'T DO THIS:
# img = img.resize_to_fit
#
# DO THIS INSTEAD:
# img.resize_to_fit!
#
# Read this for more information why:
#
# http://rubyforge.org/forum/forum.php?thread_id=1374&forum_id=1618
#
module RMagick
extend ActiveSupport::Concern
included do
begin
require "rmagick"
rescue LoadError
begin
require "RMagick"
rescue LoadError => e
e.message << " (You may need to install the rmagick gem)"
raise e
end
end
prepend Module.new {
def initialize(*)
super
@format = nil
end
}
end
module ClassMethods
def convert(format)
process :convert => format
end
def resize_to_limit(width, height)
process :resize_to_limit => [width, height]
end
def resize_to_fit(width, height)
process :resize_to_fit => [width, height]
end
def resize_to_fill(width, height, gravity=::Magick::CenterGravity)
process :resize_to_fill => [width, height, gravity]
end
def resize_and_pad(width, height, background=:transparent, gravity=::Magick::CenterGravity)
process :resize_and_pad => [width, height, background, gravity]
end
def resize_to_geometry_string(geometry_string)
process :resize_to_geometry_string => [geometry_string]
end
end
##
# Changes the image encoding format to the given format
#
# See even http://www.imagemagick.org/RMagick/doc/magick.html#formats
#
# === Parameters
#
# [format (#to_s)] an abbreviation of the format
#
# === Yields
#
# [Magick::Image] additional manipulations to perform
#
# === Examples
#
# image.convert(:png)
#
def convert(format)
manipulate!(:format => format)
@format = format
end
##
# Resize the image to fit within the specified dimensions while retaining
# the original aspect ratio. Will only resize the image if it is larger than the
# specified dimensions. The resulting image may be shorter or narrower than specified
# in the smaller dimension but will not be larger than the specified values.
#
# === Parameters
#
# [width (Integer)] the width to scale the image to
# [height (Integer)] the height to scale the image to
#
# === Yields
#
# [Magick::Image] additional manipulations to perform
#
def resize_to_limit(width, height)
width = dimension_from width
height = dimension_from height
manipulate! do |img|
geometry = Magick::Geometry.new(width, height, 0, 0, Magick::GreaterGeometry)
new_img = img.change_geometry(geometry) do |new_width, new_height|
img.resize(new_width, new_height)
end
destroy_image(img)
new_img = yield(new_img) if block_given?
new_img
end
end
##
# From the RMagick documentation: "Resize the image to fit within the
# specified dimensions while retaining the original aspect ratio. The
# image may be shorter or narrower than specified in the smaller dimension
# but will not be larger than the specified values."
#
# See even http://www.imagemagick.org/RMagick/doc/image3.html#resize_to_fit
#
# === Parameters
#
# [width (Integer)] the width to scale the image to
# [height (Integer)] the height to scale the image to
#
# === Yields
#
# [Magick::Image] additional manipulations to perform
#
def resize_to_fit(width, height)
width = dimension_from width
height = dimension_from height
manipulate! do |img|
img.resize_to_fit!(width, height)
img = yield(img) if block_given?
img
end
end
##
# From the RMagick documentation: "Resize the image to fit within the
# specified dimensions while retaining the aspect ratio of the original
# image. If necessary, crop the image in the larger dimension."
#
# See even http://www.imagemagick.org/RMagick/doc/image3.html#resize_to_fill
#
# === Parameters
#
# [width (Integer)] the width to scale the image to
# [height (Integer)] the height to scale the image to
#
# === Yields
#
# [Magick::Image] additional manipulations to perform
#
def resize_to_fill(width, height, gravity=::Magick::CenterGravity)
width = dimension_from width
height = dimension_from height
manipulate! do |img|
img.crop_resized!(width, height, gravity)
img = yield(img) if block_given?
img
end
end
##
# Resize the image to fit within the specified dimensions while retaining
# the original aspect ratio. If necessary, will pad the remaining area
# with the given color, which defaults to transparent (for gif and png,
# white for jpeg).
#
# === Parameters
#
# [width (Integer)] the width to scale the image to
# [height (Integer)] the height to scale the image to
# [background (String, :transparent)] the color of the background as a hexcode, like "#ff45de"
# [gravity (Magick::GravityType)] how to position the image
#
# === Yields
#
# [Magick::Image] additional manipulations to perform
#
def resize_and_pad(width, height, background=:transparent, gravity=::Magick::CenterGravity)
width = dimension_from width
height = dimension_from height
manipulate! do |img|
img.resize_to_fit!(width, height)
filled = ::Magick::Image.new(width, height) { |image| image.background_color = background == :transparent ? 'rgba(255,255,255,0)' : background.to_s }
filled.composite!(img, gravity, ::Magick::OverCompositeOp)
destroy_image(img)
filled = yield(filled) if block_given?
filled
end
end
##
# Resize the image per the provided geometry string.
#
# === Parameters
#
# [geometry_string (String)] the proportions in which to scale image
#
# === Yields
#
# [Magick::Image] additional manipulations to perform
#
def resize_to_geometry_string(geometry_string)
manipulate! do |img|
new_img = img.change_geometry(geometry_string) do |new_width, new_height|
img.resize(new_width, new_height)
end
destroy_image(img)
new_img = yield(new_img) if block_given?
new_img
end
end
##
# Returns the width of the image.
#
# === Returns
#
# [Integer] the image's width in pixels
#
def width
rmagick_image.columns
end
##
# Returns the height of the image.
#
# === Returns
#
# [Integer] the image's height in pixels
#
def height
rmagick_image.rows
end
##
# Manipulate the image with RMagick. This method will load up an image
# and then pass each of its frames to the supplied block. It will then
# save the image to disk.
#
# === Gotcha
#
# This method assumes that the object responds to +current_path+.
# Any class that this module is mixed into must have a +current_path+ method.
# CarrierWave::Uploader does, so you won't need to worry about this in
# most cases.
#
# === Yields
#
# [Magick::Image] manipulations to perform
# [Integer] Frame index if the image contains multiple frames
# [Hash] options, see below
#
# === Options
#
# The options argument to this method is also yielded as the third
# block argument.
#
# Currently, the following options are defined:
#
# ==== :write
# A hash of assignments to be evaluated in the block given to the RMagick write call.
#
# An example:
#
# manipulate! do |img, index, options|
# options[:write] = {
# :quality => 50,
# :depth => 8
# }
# img
# end
#
# This will translate to the following RMagick::Image#write call:
#
# image.write do |img|
# self.quality = 50
# self.depth = 8
# end
#
# ==== :read
# A hash of assignments to be given to the RMagick read call.
#
# The options available are identical to those for write, but are passed in directly, like this:
#
# manipulate! :read => { :density => 300 }
#
# ==== :format
# Specify the output format. If unset, the filename extension is used to determine the format.
#
# === Raises
#
# [CarrierWave::ProcessingError] if manipulation failed.
#
def manipulate!(options={}, &block)
cache_stored_file! if !cached?
read_block = create_info_block(options[:read])
image = ::Magick::Image.read(current_path, &read_block)
frames = ::Magick::ImageList.new
image.each_with_index do |frame, index|
frame = yield(*[frame, index, options].take(block.arity)) if block_given?
frames << frame if frame
end
frames.append(true) if block_given?
write_block = create_info_block(options[:write])
if options[:format] || @format
frames.write("#{options[:format] || @format}:#{current_path}", &write_block)
move_to = current_path.chomp(File.extname(current_path)) + ".#{options[:format] || @format}"
file.content_type = Marcel::Magic.by_path(move_to).try(:type)
file.move_to(move_to, permissions, directory_permissions)
else
frames.write(current_path, &write_block)
end
destroy_image(frames)
rescue ::Magick::ImageMagickError
raise CarrierWave::ProcessingError, I18n.translate(:"errors.messages.processing_error")
end
private
def create_info_block(options)
return nil unless options
proc do |img|
options.each do |k, v|
if v.is_a?(String) && (matches = v.match(/^["'](.+)["']/))
ActiveSupport::Deprecation.warn "Passing quoted strings like #{v} to #manipulate! is deprecated, pass them without quoting."
v = matches[1]
end
img.public_send(:"#{k}=", v)
end
end
end
def destroy_image(image)
image.try(:destroy!)
end
def dimension_from(value)
return value unless value.instance_of?(Proc)
value.arity >= 1 ? value.call(self) : value.call
end
def rmagick_image
::Magick::Image.from_blob(self.read).first
end
end # RMagick
end # CarrierWave
| true
|
512d7f491b4a06bf5f02efa43788b734190d77be
|
Ruby
|
ytti/packet_via_dmem
|
/lib/packet_via_dmem/header/sent.rb
|
UTF-8
| 1,588
| 2.546875
| 3
|
[] |
no_license
|
class PacketViaDMEM
class Header
class Sent
attr_accessor :msg_type,
:statistics,
:increment_reference,
:fragment_info,
:drop_hash,
:decrement_reference,
:prequeue_priority,
:offset,
:table,
:color,
:queue_drop_opcode,
:queue_system,
:life,
:queue_number,
:port,
:type,
:magic1,
:magic2,
:magic3
def to_s(packet_number=1)
str = ''
str << '# TX %03d # ' % packet_number
str << (statistics ? 'S' : 's')
str << (increment_reference ? 'I' : 'i')
str << (fragment_info ? 'F' : 'f')
str << (drop_hash ? 'H' : 'h')
str << (decrement_reference ? 'D' : 'd')
str << (prequeue_priority ? 'P' : 'p')
str << ' # '
str << 'port: %x (%s) # ' % [port, port.divmod(64).join('/')]
str << 'type: %x # ' % type
str << 'QoS: %d@%d # ' % [queue_number, queue_system]
str << "QueueDropOp: %d\n" % [queue_drop_opcode]
str << '# '
str << 'color: %d # ' % color
str << 'offset: %d # ' % offset
str << 'table: %d # ' % table
str << 'life: %d # ' % life
str << 'magic: '
str << '%x/%x' % [magic1, magic2] if magic1
str << '/%x' % magic3 if magic3
str
end
end
end
end
| true
|
cc5c10c0db9ad3f91d6440a1bf74c1ef7c0590c0
|
Ruby
|
facano/effective_datatables
|
/app/models/effective/array_datatable_tool.rb
|
UTF-8
| 1,914
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
module Effective
# The collection is an Array of Arrays
class ArrayDatatableTool
attr_accessor :table_columns
delegate :order_column_index, :order_direction, :page, :per_page, :search_column, :to => :@datatable
def initialize(datatable, table_columns)
@datatable = datatable
@table_columns = table_columns
end
def order_column
@order_column ||= table_columns.find { |_, values| values[:index] == order_column_index }.try(:second) # This pulls out the values
end
def search_terms
@search_terms ||= @datatable.search_terms.select { |name, search_term| table_columns.key?(name) }
end
def order(collection)
if order_column.present?
if order_direction == 'ASC'
collection.sort! { |x, y| x[order_column[:index]] <=> y[order_column[:index]] }
else
collection.sort! { |x, y| y[order_column[:index]] <=> x[order_column[:index]] }
end
end
collection
end
def search(collection)
search_terms.each do |name, search_term|
column_search = search_column(collection, table_columns[name], search_term)
raise 'search_column must return an Array object' unless column_search.kind_of?(Array)
collection = column_search
end
collection
end
def search_column_with_defaults(collection, table_column, search_term)
search_term = search_term.downcase
collection.select! do |row|
value = row[table_column[:index]].to_s.downcase
if table_column[:filter][:type] == :select && table_column[:filter][:fuzzy] != true
value == search_term
else
value.include?(search_term)
end
end || collection
end
def paginate(collection)
Kaminari.paginate_array(collection).page(page).per(per_page)
end
end
end
# [
# [1, 'title 1'],
# [2, 'title 2'],
# [3, 'title 3']
# ]
| true
|
be9f20b262b6b2903b268a8527c7bb961657fabe
|
Ruby
|
slackerar/csv_parser
|
/app/models/analysis.rb
|
UTF-8
| 1,298
| 3.109375
| 3
|
[] |
no_license
|
class Analysis
MARKS = %w[ПЭТД ПЭТВ ПуГВ АПБ]
COLORS = %w[красный черный синий белый желтый голубой зеленый коричневый оранжевый фиолетовый розовый серый бордовый]
class << self
def get_type_produce(value)
result = value.match('ТУ(.[0-9\-_.]{1,20})*') unless value.match('ТУ(.[0-9\-_.]{1,20})*').nil?
result = value.match('ГОСТ(.[0-9\-_.]{1,20})*') unless value.match('ГОСТ(.[0-9\-_.]{1,20})*').nil?
result.nil? ? '-' : result
end
def get_marks(value)
res = '-'
MARKS.each do |t|
if value.downcase.index(t.downcase).present? && value.downcase.index(t.downcase) >= 0
res = t
end
end
res
end
def get_prop(value)
result = value.match('(([0-9]*[.,]*[0-9]*)[xх]([0-9]*[.,]*[0-9]*)[\/]*[0-9]*[.,]*[0-9]*)')
result.nil? ? result = value.match('([0-9][.,][0-9]*)') : nil
result.nil? ? '-' : result
end
def get_colors(value)
res = ''
COLORS.each do |t|
if value.downcase.index(t.downcase).present? && value.downcase.index(t.downcase) > 0
res.length > 0 ? res += ', ' + t : res = t
end
end
res
end
end
end
| true
|
2005c8138013be978f3b526081d304d5fe4b7387
|
Ruby
|
grzesiek/git_compound
|
/lib/git_compound/lock.rb
|
UTF-8
| 1,277
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
require 'yaml'
module GitCompound
# Class that represents lock file
#
class Lock
FILENAME = '.gitcompound.lock'
def self.exist?
File.exist?(FILENAME)
end
def initialize(file = FILENAME)
@file = file
@locked = YAML.load(File.read(file)) if File.exist?(file)
clean unless @locked.is_a? Hash
end
def clean
@locked = { manifest: '', components: [] }
self
end
def lock_manifest(manifest)
@locked[:manifest] = manifest.md5sum
end
def lock_component(component)
@locked[:components] << component.to_hash
end
def manifest
@locked[:manifest]
end
def components
@locked[:components].to_a.map do |locked|
Component.new(locked[:name].to_sym) do
sha locked[:sha]
source locked[:source]
destination locked[:destination]
end
end
end
def contents
@locked
end
def find(component)
components.find do |locked_component|
locked_component.path == component.path
end
end
def process(worker)
components.each { |component| worker.visit_component(component) }
end
def write
File.open(@file, 'w') { |f| f.puts @locked.to_yaml }
end
end
end
| true
|
2b3cb5bbbbc4b0e6f9906df44a877aee3655a446
|
Ruby
|
Will3240/programming-univbasics-3-methods-scope-lab-online-web-prework
|
/lib/catch_phrases.rb
|
UTF-8
| 253
| 2.671875
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
def mario
message="It's-a me, Mario!"
puts message
end
def toadstool
puts 'Thank You Mario! But Our Princess Is In Another Castle!'
end
def link
puts "It's Dangerous To Go Alone! Take This."
end
def any_phrase(phrase)
puts phrase
end
| true
|
dd9bcf33d6fd20cc3071a2246786c430c0ef2028
|
Ruby
|
Deceptio-Solutions/tapir
|
/lib/tapir/tasks/dns_reverse_lookup.rb
|
UTF-8
| 997
| 2.703125
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
def name
"dns_reverse_lookup"
end
def pretty_name
"DNS Reverse Lookup"
end
def authors
['jcran']
end
def description
"Look up the name of the given ip address"
end
## Returns an array of valid types for this task
def allowed_types
[Entities::Host]
end
## Returns an array of valid options and their description/type for this task
def allowed_options
[]
end
def setup(entity, options={})
super(entity, options)
end
def run
super
begin
resolved_name = Resolv.new.getname(@entity.name).to_s
if resolved_name
@task_logger.good "Creating domain #{name}"
# Create our new dns record entity with the resolved name
d = create_entity(Entities::DnsRecord, {:name => resolved_name})
# Add the dns record for this host
@entity.dns_records << d
else
@task_logger.log "Unable to find a name for #{@entity.name}"
end
rescue Exception => e
@task_logger.error "Hit exception: #{e}"
end
end
def cleanup
super
end
| true
|
704f632797f23f3281bb4e5abe515ab39428cebf
|
Ruby
|
jnunemaker/ag
|
/lib/ag/object.rb
|
UTF-8
| 485
| 3
| 3
|
[
"MIT"
] |
permissive
|
module Ag
class Object
Separator = ";".freeze
def self.from_key(key, separator = Separator)
new(*key.split(Separator))
end
attr_reader :type
attr_reader :id
def initialize(type, id)
@type = type
@id = id
end
def key(*suffixes)
[@type, @id].concat(Array(suffixes)).join(Separator)
end
def ==(other)
self.class == other.class &&
self.type == other.type &&
self.id == other.id
end
end
end
| true
|
d836faecd79c16ca70b9f44dfa65768c7c41615b
|
Ruby
|
icoluccio/criticas-app
|
/app/models/analyst.rb
|
UTF-8
| 478
| 2.53125
| 3
|
[] |
no_license
|
class Analyst < ApplicationRecord
belongs_to :newspaper, required: false
has_many :articles
has_many :favorite_countries
has_many :countries, through: :favorite_countries
def write(country)
Article.create!(title: title, figure: figure(country), analyst: self)
end
def title
raise 'Definilo, capo'
end
def figure(_country)
raise 'Definilo, capo'
end
def can_write?(country)
(articles.size < 3) && !name.include?(country.name)
end
end
| true
|
731fdc719d1b588a1477700fd4848d0614eec822
|
Ruby
|
jamie/adventofcode
|
/2018/01/solver.rb
|
UTF-8
| 264
| 3.234375
| 3
|
[] |
no_license
|
require "advent"
input = Advent.input(:to_i)
# Part 1
puts input.inject(0) { |memo, e| memo + e }
# Part 2
freqs = {}
freq = 0
freqs[freq] = true
loop do
i = input.shift
freq += i.to_i
break if freqs[freq]
freqs[freq] = true
input << i
end
puts freq
| true
|
db96c90e87ecf51d6397fbe66fb42a92757d6408
|
Ruby
|
khoinguyenkc/ruby-puppy-online-web-sp-000
|
/lib/dog.rb
|
UTF-8
| 509
| 3.71875
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Add your code here
require 'pry'
class Dog
attr_accessor :name
@@all = []
def initialize(name)
@name = name
self.save #self refers to the instance
end
def save #an INSTANCE method
@@all << self #push the object into the all array
end
def self.all
@@all
end
def self.print_all
@@all.each do | dogobject |
puts dogobject.name
end
end
def self.clear_all
@@all.clear
end
end
fifi = Dog.new("fifi")
fido = Dog.new("fido")
Dog.print_all
print Dog.all
| true
|
8355eb68097bf365851452a3e7d09f9f378f93c3
|
Ruby
|
mpermperpisang/bandung-telegram-bot
|
/command/add_staging.rb
|
UTF-8
| 2,722
| 2.625
| 3
|
[] |
no_license
|
module Bot
class Command
# untuk menambahkan staging ke daftar staging squad
class AddStaging < Command
def check_text
check_format if @txt.start_with?("/add_staging")
end
def check_format
@is_squad = Squad.new
return if @is_squad.empty?(@bot, @message.chat.id, @squad_name, @base_command, @username)
check_staging
end
def check_staging
@is_staging = Staging.new
return if @is_staging.empty?(@bot, @message.chat.id, @staging, @username, @txt)
check_staging_squad
end
def check_staging_squad
@db = Connection.new
@squad = @txt.scan(/\s[a-zA-Z]+/)
@staging = @txt.scan(/\d+/)
@squad_input = @squad.to_s.gsub('", "', ", ").delete('["').delete('"]').strip
@array_nil = []
@array_dupe = []
@staging.each do |stg|
unless (@array_nil.include? stg) || (@array_dupe.include? stg)
stg_squad = @db.check_staging(stg)
@squad_name = stg_squad.size.zero? ? nil : stg_squad.first['book_squad']
@squad_name.nil? ? @array_nil.push(stg) : @array_dupe.push(stg)
end
end
check_stg_exist unless @array_nil.empty?
duplicate_staging unless @array_dupe.empty?
end
def check_stg_exist
@array_add = []
@array_update = []
@array_nil.each do |stg|
check_exist = @db.check_stg_exist(stg)
stg_exist = check_exist.size.zero? ? nil : check_exist.first['book_squad']
stg_exist.nil? ? @array_add.push(stg) : @array_update.push(stg)
end
add_staging unless @array_add.empty?
update_staging unless @array_update.empty?
end
def add_staging
@array_add.each do |stg|
@db.add_staging_squad(stg, @squad_input)
end
@list = @array_add.to_s.gsub('", "', ", ").delete('["').delete('"]')
@bot.api.send_message(chat_id: @message.chat.id, text: msg_add_stg_squad(@list, @squad_input, @username), parse_mode: 'HTML')
end
def update_staging
@array_update.each do |stg|
@db.update_staging_squad(stg, @squad_input)
end
@list = @array_update.to_s.gsub('", "', ", ").delete('["').delete('"]')
@bot.api.send_message(chat_id: @message.chat.id, text: msg_update_stg_squad(@list, @squad_input, @username), parse_mode: 'HTML')
end
def duplicate_staging
@list = @array_dupe.to_s.gsub('", "', ", ").delete('["').delete('"]')
@bot.api.send_message(chat_id: @message.chat.id, text: msg_dupe_stg_squad(@list, @squad_name), parse_mode: 'HTML')
end
end
end
end
| true
|
77ff5f79711b82d3b48de3a4aec1f17e5f7e2be0
|
Ruby
|
meldefern/OpenWeatherAPI
|
/spec/weather_codes_spec.rb
|
UTF-8
| 676
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
include WeatherConditions
describe ConditionsCode do
before(:all) do
@first_condition = WeatherConditions::ConditionsCode.new("301")
@second_condition = WeatherConditions::ConditionsCode.new("501")
end
it 'should return a string for the description associated with the id' do
expect(@first_condition.meaning).to be_a String
expect(@second_condition.meaning).to be_a String
end
it 'should return an array of size 0, 1, or 2 for the icon' do
expect(@first_condition.icon).to be_a Array
expect(@second_condition.icon).to be_a Array
expect(@first_condition.icon.length).to be_between(0,2)
expect(@second_condition.icon.length).to be_between(0,2)
end
end
| true
|
cf6322ee62508dcb40ff3dd41049bee3e725a03c
|
Ruby
|
gongo/maizebox
|
/lib/maizebox/renderer.rb
|
UTF-8
| 3,496
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
require 'maizebox/js_loader'
require 'maizebox/capybara'
module Maizebox
class Renderer
include Maizebox::Capybara
FRAME_PADDING = '20' # pixel
def render_here
locator = current_locator
render(locator)
end
def render_to(element)
locator = element_locator(element)
render(locator)
end
private
##
#
# @param [Array] locators
#
def render(locators)
jsloader.run
script = create_frame_script(locators)
execute(script)
end
def create_frame_script(locators)
locator = locators.join('.')
<<-EOS
var node = $(document).#{locator};
var node_left = node.offset().left - #{FRAME_PADDING};
var node_width = node.width() + #{FRAME_PADDING}*2;
var node_top = node.offset().top - #{FRAME_PADDING};
var node_height = node.height() + #{FRAME_PADDING}*2;
var overlay = $('<div></div>');
overlay.css('position', 'absolute')
.css('zIndex', 10000)
.css('left', node_left)
.css('top', node_top)
.css('width', node_width)
.css('height', node_height).#{frame_style};
$(document.body).append(overlay);
EOS
end
##
#
# # => .css('border', '2px solid red').css('background-color', 'rgba(0, 0, 0, 0.2)')
#
# @return [String] String that call function to apply stylesheet jQuery syntax.
#
def frame_style
{
'border' => '2px solid red',
'background-color' => 'rgba(0, 0, 0, 0.2)',
}.map { |name, value| "css('#{name}', '#{value}')" }.join('.')
end
##
#
# # Without scope
# node = find(:css, '#library')
# element_locator(node) # => ["find('#library')"]
#
# # Within scope
# within(:xpath, '//*[@id="main"]') do
# within(:css, 'div#profile') do
# node = find(:xpath, '//p[@id="name"]')
# element_locator(node)
# # => ["xpath('//*[@id=\"main\"]')", "find('div#profile')", "xpath('//p[@id=\"name\"]')"]
# end
# end
#
# @return [Array] A part of jQuery and jquery-xpath syntax for find +element+
#
def element_locator(element)
current_locator << create_jquery_selector(element)
end
##
# # Without scope
# current_locator # => []
#
# # Within scope
# within(:xpath, '//*[@id="main"]') do
# within(:css, 'p#author') do
# current_locator # => ["xpath('//*[@id=\"main\"]')", "find('p#author')"]
# end
#
# current_locator # => ["xpath('//*[@id=\"main\"]')"]
# end
#
# @return [Array] A part of jQuery and jquery-xpath syntax for find current scope element.
#
def current_locator
# Skip first element (Capybara::Node::Document)
scopes = browser.send(:scopes)[1..-1]
scopes.empty? ? [] : scopes.map { |scope| create_jquery_selector(scope) }
end
#
# @param [Capybara::Node::Element] element
# @return [String] jQuery and jquery-xpath finder syntax
#
def create_jquery_selector(element)
format = element.query.selector.format
locator = element.query.send(format)
function = (format == :xpath) ? 'xpath' : 'find'
"#{function}('" + locator.gsub("'", "\\\\'") + "')"
end
def jsloader
@jsloader ||= JsLoader.new
end
end
end
| true
|
037eb6a9f411ea28fd743a4a9d2dfb3f3244a794
|
Ruby
|
fooheads/cucumber_ruby-atm
|
/features/step_definitions/atm_steps.rb
|
UTF-8
| 1,307
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
require 'atm'
Before do
@atm = ATM.new(0)
@account = Account.new(0)
@card = Card.new(@account, false)
@thrown_exception = nil
@dispensed_amount = 0
end
Given(/^the account balance is (\d+)$/) do |balance|
@account.balance = balance.to_i
end
Given(/^the card is valid$/) do
@card.valid = true
end
Given(/^the machine contains enough money$/) do
@atm.balance = 100000
end
When(/^the account holder requests (\d+)$/) do |amount|
begin
@dispensed_amount = @atm.withdraw(@card, amount.to_i)
rescue CardRetained => e
@thrown_exception = e
rescue InsufficientFunds => e
@thrown_exception = e
end
end
Then(/^the ATM should dispense (\d+)$/) do |amount|
@dispensed_amount.should == amount.to_i
end
Then(/^the account balance should be (\d+)$/) do |balance|
@account.balance.should == balance.to_i
end
Then(/^the card should be returned$/) do
@thrown_exception.class.should_not == CardRetained
end
Then(/^the ATM should not dispense any money$/) do
@dispensed_amount.should == 0
end
Then(/^the ATM should say there are insufficient funds$/) do
@thrown_exception.class.should == InsufficientFunds
end
Given(/^the card is disabled$/) do
@card.valid = false
end
Then(/^the ATM should retain the card$/) do
@thrown_exception.class.should == CardRetained
end
| true
|
bfbac5ba903eb6355033050438b167cdf740f5c1
|
Ruby
|
jeefberkey/advent-of-code-2017
|
/day04/day04b.rb
|
UTF-8
| 502
| 3.125
| 3
|
[] |
no_license
|
require 'pry'
def validate_passphrase(phrase)
p = phrase.split(' ')
sorted = p.map do |item|
item.chars.sort.join
end
# binding.pry
sorted.uniq.length == p.length
end
puts validate_passphrase('abcde fghij')
puts validate_passphrase('abcde xyz ecdab')
puts validate_passphrase('a ab abc abd abf abj')
puts validate_passphrase('iiii oiii ooii oooi oooo')
puts validate_passphrase('oiii ioii iioi iiio')
valid = 0
File.readlines('passphrases.txt').each do |phrase|
valid += 1 if validate_passphrase(phrase)
end
puts valid
| true
|
93c1871b647043d86655ceb89efa37bcbaeaba85
|
Ruby
|
rai-hi/pin-generator
|
/code/pin_generator.rb
|
UTF-8
| 915
| 3.265625
| 3
|
[] |
no_license
|
# frozen_string_literal: true
class PinGenerator
PIN_LENGTH = 4
def initialize(bank_account:, customer:, validator_classes: [])
@validator_classes = validator_classes
@bank_account = bank_account
@customer = customer
end
def generate
pin = random_pin
pin = random_pin until valid?(pin)
pin
end
private
def random_pin
Pin.new random_pin_value
end
def random_pin_value
PIN_LENGTH.times.map { rand(10) }.join('')
end
def valid?(pin)
@validator_classes.all? do |validator_class|
valid_according_to_validator_class?(validator_class, pin)
end
end
def valid_according_to_validator_class?(validator_class, pin)
validator = validator(validator_class, pin)
validator.valid?
end
def validator(validator_class, pin)
validator_class.new(
bank_account: @bank_account,
customer: @customer,
pin: pin
)
end
end
| true
|
8dea75a06c5b2e6010aa55205d4bbf263d9f3cfb
|
Ruby
|
yangchuanosaurus/RemoteDataCli
|
/lib/manipulate/manipulate.rb
|
UTF-8
| 2,519
| 2.671875
| 3
|
[
"Apache-2.0"
] |
permissive
|
require 'json'
require_relative 'field'
require_relative 'field_array'
module RemoteDataCli
module Mapping
class Manipulate
def initialize(name)
@name = upcase(name)
@class_instances = Hash.new
end
def generate(json)
data_json = JSON.parse(json)
if data_json.is_a?(Hash)
manipulate_hash(@name, data_json)
elsif data_json.is_a?(Array)
manipulate_array("#{@name}Item", data_json)
end
@class_instances
end
private
def upcase(str)
"#{str[0].upcase}#{str[1..-1]}"
end
def model_name(name)
"#{upcase(name)}.model"
end
def join_name(name, parent_name = nil)
if !parent_name.nil?
"#{upcase(parent_name)}#{upcase(name)}"
else
upcase(name)
end
end
def add_field(name, field, parent_name = nil)
model_name = join_name(model_name(name), parent_name)
@class_instances[model_name] = Array.new if @class_instances[model_name].nil?
@class_instances[model_name] << field # todo should update if the item in model_name exits
@class_instances[model_name] = @class_instances[model_name].uniq
end
def manipulate_hash(name, data_hash, parent_name = nil)
p_name = parent_name.nil? ? name : "#{upcase(parent_name)}#{upcase(name)}"
data_hash.keys.each do |key|
value = data_hash[key]
if value.is_a?(Hash)
model_name = "#{name}"
add_field(name, Field.new(key, model_name(join_name(key, p_name))), parent_name)
elsif value.is_a?(Array)
model_name = "#{name}#{upcase(key)}Item"
add_field(name, FieldArray.new(key, join_name(model_name(model_name), parent_name)), parent_name)
else
add_field(name, Field.new(key, value.class), parent_name)
end
end
data_hash.map do |key, value|
if value.is_a?(Hash)
manipulate_hash(key, value, p_name)
elsif value.is_a?(Array)
model_name = "#{upcase(key)}Item"
manipulate_array("#{model_name}", value, p_name)
end
end
end
def manipulate_array(name, data_array, parent_name)
p_name = parent_name.nil? ? name : "#{upcase(parent_name)}"
data_array.each do |value|
if value.is_a?(Hash)
manipulate_hash(name, value, p_name)
elsif value.is_a?(Array)
model_name = "#{upcase(name)}Item"
manipulate_array(name, value, join_name(name, p_name))
else
add_field(name, Field.new(model_name(value), "Array"))
end
end
end
end
end
end
| true
|
30d75650dea5b66fe721ab72ecedd52bfad58caa
|
Ruby
|
yukaitozu/obi
|
/db/seeds.rb
|
UTF-8
| 1,882
| 2.578125
| 3
|
[] |
no_license
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
require "open-uri"
require 'date'
KIMONOS = ["Red Kimono", "Edo Era Kimono", "Summer Yukata", "Embroidered Mens Kimono", "Purple Yukata", "Fancy Hakama", "Bridal Kimono", "Casual Kimono", "Graduation Hakama", "Playful Kids Kimono", "Beautiful Furisode", "Yellow Yukata", "Blue Short Kimono", "Formal Green Kimono"]
Review.destroy_all
Booking.destroy_all
Listing.destroy_all
User.destroy_all
20.times do
User.create!(
first_name: Faker::Name.first_name,
last_name: Faker::Name.last_name,
email: Faker::Internet.email,
password: "123456"
)
end
User.first(10).each do |user|
rand(1..5).times do
Listing.create!(user: user, title: KIMONOS.sample, price: Faker::Number.number(digits: 4), color: Listing::COLORS.sample, category: Listing::CATEGORIES.sample)
end
end
User.last(10).each do |user|
rand(1..3).times do
start_date = Faker::Date.in_date_period(month: 1)
Booking.create!(borrower: user, listing: Listing.all.sample, start_date: start_date , return_date: start_date + rand(1..3).days, approved: rand(0..2) > 0)
end
end
User.create!(
email: "yuka@gmail.com",
password: "123456",
first_name: "Yuka",
profile_info: "I am passionate about kimonos! I have a variety of different styles of kimonos from yukatas to hakamas!"
)
User.create!(
email: "noemi@gmail.com",
password: "123456",
first_name: "Noemi",
profile_info: "I love Japanese culture and traveling to different parts of Japan. I would love to rent a kimono and get the full Japanese experience!"
)
| true
|
78ef4bd62a6fe4a95dd0d56f6b8c56b625f921b8
|
Ruby
|
anthonyb/sorts
|
/sort.rb
|
UTF-8
| 462
| 3.484375
| 3
|
[] |
no_license
|
def sort(num)
num_array = num.to_s.split('')
done = false
len = num_array.length
while !done do
num_array.each_with_index do |n, i|
if (num_array[i+1]) and (num_array[i] > num_array[i+1])
low = num_array[i]
high = num_array[i+1]
num_array[i] = high
num_array[i+1] = low
done = false
break
end
done = true
end
p num_array
sleep(0.5)
end
end
num = 394621743189
sort(num)
| true
|
5f7b61365f1538c75714097460f4af1fcf853775
|
Ruby
|
dantelove/109_general_programming
|
/ruby_basics/10_strings/strings4.rb
|
UTF-8
| 56
| 2.859375
| 3
|
[] |
no_license
|
# strings4.rb
name = "Elizabeth"
puts "Hello #{name}!"
| true
|
6885cbf3fef407b7ea170d46f0751c43462ae94f
|
Ruby
|
clayton/ofcp_scoring
|
/lib/ofcp_scoring/three_of_a_kind.rb
|
UTF-8
| 268
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
class OfcpScoring::ThreeOfAKind < OfcpScoring::RankedHand
def <=>(other)
return super if super
highest_trip_card <=> other.highest_trip_card
end
def highest_trip_card
grouped_ranks.map{|card,matches| card if matches.size == 3}.compact.max
end
end
| true
|
4f716f6be8d93791bba87a42b16cb6d788e72768
|
Ruby
|
2peta/rhello
|
/lib/rhello.rb
|
UTF-8
| 523
| 2.65625
| 3
|
[] |
no_license
|
require 'optparse'
require 'rhello/version'
module Rhello
class Application
OPTS = {}
def run
optparser = optparse OPTS
optparser.parse!
puts "Hello, world!"
end
def optparse opts
parser = OptionParser.new
parser.banner = "Usage: #{parser.program_name} [OPTION]..."
parser.on('--help') {
puts parser.to_s
exit
}
parser.on('--version') {
puts "#{parser.program_name} #{VERSION}"
exit
}
parser
end
end
end
| true
|
ed909421cfe6c158ead5830f01f4a44f0f19c755
|
Ruby
|
cy2003/ruby-collaborating-objects-lab-web-1116
|
/lib/mp3_importer.rb
|
UTF-8
| 327
| 2.671875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class MP3Importer
attr_reader :path, :files
def initialize(path)
@path = path
end
def files
files = Dir["./spec/fixtures/mp3s/*"].collect do |file|
file.gsub("./spec/fixtures/mp3s/", "")
end
end
def import
files.each do |file_name|
Song.new_by_filename(file_name)
end
end
end
| true
|
c74ecab60a3fa05ed4613b2bae157123e3bc4661
|
Ruby
|
ElaineYu/shiny-octo-tyrion
|
/app/controller/controller.rb
|
UTF-8
| 1,290
| 2.9375
| 3
|
[] |
no_license
|
require 'pry'
require_relative '../../config/application'
require_relative '../models/list'
require_relative '../models/task'
# require_relative '../views/view'
class Controller
def initialize
# display = View.new
end
def add(task, list_name)
task = Task.create(description: task,
list_id: List.where(:name == list_name).first.id
)
# confirm_addition(task)
end
def get(condition, value)
task = Task.where(condition.to_sym => value)
# show_task(task)
end
def list
# show_list(Task.all)
Task.all
end
def update(id, updated_description)
task = get("id", id).first
task.description = updated_description
task.save
# confirm_update(task)
end
def delete(id)
task = get("id", id).first
# confirm_deletion(task)
task.destroy
end
end
(Controller.new).list
(Controller.new).add("cats", "BS LIST")
(Controller.new).get("id", 10)
(Controller.new).update(10, "dogs")
(Controller.new).delete(10)
(Controller.new).list
# cat = (Controller.new).get("id", 3)
# p (Controller.new).update(12, "don't walk the dog")
# show_list(List.all)
# confirm_addition(task)
# confirm_deletion(task)
# p (Controller.new).get("id",10)
# p (Controller.new).delete(10)
# p (Controller.new).list
| true
|
dae55fcc4738bcd9dded29c3af1f6729c0f033d5
|
Ruby
|
Alex808r/rubyschool
|
/les18/task2.rb
|
UTF-8
| 128
| 2.6875
| 3
|
[] |
no_license
|
input = File.open 'passwords.txt', 'r'
while (line = input.gets)
line.strip!
if line.size == 6
puts line
end
end
| true
|
35f82fea1d23450c9cc17bacae126c23a1b0d7ca
|
Ruby
|
OAGr/fermihub
|
/app/models/distribution.rb
|
UTF-8
| 751
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
require 'dis'
#encoding: utf-8
#!/bin/env ruby
# encoding: utf-8
class Distribution < ActiveRecord::Base
SIGNIFICANT_DIGITS = 8
has_and_belongs_to_many :outputs, :class_name => "Operation"
has_and_belongs_to_many :models
attr_accessible :name, :mean, :spread, :wideness
before_save :default_values
after_save :output_evaluate!
def default_values
self.spread ||= 0
end
def output_evaluate!
outputs.each {|o| o.evaluate!}
end
def to_dis
Dis.new(mean,spread,wideness)
end
def to_s
name || to_num
end
def to_num
#!/bin/env ruby
# encoding: utf-8
"#{round(mean)} +- #{round(spread)}"
end
"%.4g" % 1342254513
def round(float)
float.nil? ? "0" : "%.#{SIGNIFICANT_DIGITS}g" % float
end
end
| true
|
e9b5bad1dfed5e41204db992a8d58ffab58295b5
|
Ruby
|
vclee/phase-0-tracks
|
/ruby/shout.rb
|
UTF-8
| 510
| 3.8125
| 4
|
[] |
no_license
|
# module Shout
# def self.yell_angrily(words)
# words + "!!!" + " :("
# end
#
# def self.yell_happily(words)
# words + "!!!! :DDD"
# end
# end
module Shout
def yell_crazily(words)
puts words = "!blah@#blah$%^&blah*)"
end
end
class Me
include Shout
end
class You
include Shout
end
#DRIVER CODE ***********
# puts Shout.yell_angrily("WTF")
# puts Shout.yell_happily("WTF")
me = Me.new
me.yell_crazily("I don't know what I'm doing!")
you = You.new
you.yell_crazily("Me neither!")
| true
|
798a090e28062376b7ab95b2d6c58083fad83a84
|
Ruby
|
pasvistelik/ruby-exercises
|
/20.rb
|
UTF-8
| 65
| 2.796875
| 3
|
[] |
no_license
|
p (1..100).reduce(:*).to_s.chars.inject(0){|sum,i| sum + i.to_i}
| true
|
073cf00ab0cf4e202fdb115a52702f63cdcd5609
|
Ruby
|
thms/tic-tac-toe
|
/lib/game.rb
|
UTF-8
| 1,928
| 4
| 4
|
[] |
no_license
|
require_relative './board'
class Game
attr_accessor :board
attr_accessor :player_one
attr_accessor :player_two
attr_accessor :winner
STONES = {1.0 => 'x', -1.0 => 'o', 0 => ' '}
def initialize(player_one, player_two, params = {display_output: false})
@board = Board.new
@player_one = player_one
@player_one.stone = 'x'
@player_one.value = 1.0
@player_one.moves = []
@player_two = player_two
@player_two.stone = 'o'
@player_two.value = -1.0
@player_two.moves = []
@current_player = @player_one
@winner = nil
@display_output = params[:display_output]
end
# returns all the board positions and moves as one array of arrays, and the final outcome (which can be a tie)
def play
log = []
round = 1
while round <= 9 && @winner.nil?
log << make_move(@current_player)
@winner = has_winner?
puts "Win for #{@winner.stone}" if @winner && @display_output
round += 1
@current_player = @current_player == @player_one? @player_two : @player_one
end
outcome = has_winner? ? @winner.value : 0.0
# append the outcome to each row of the log
return log, outcome
end
# use the player's strategy to place a stone
def make_move(player)
# clone the board state, because the training data must have the state before the move and the move itself.
previous_state = @board.state.clone
position = player.select_move(@board)
@board.state[position] = player.value
player.moves << position
puts "#{player.stone} set on #{position}" if @display_output
move = [0] * 9
move[position] = player.value
return [previous_state, move].flatten
end
# determine if the current board presents a win, and for whom
def has_winner?
result = nil
if @board.is_win?(1.0)
result = @player_one
elsif @board.is_win?(-1.0)
result = @player_two
end
return result
end
end
| true
|
53121266c8b3b25751c98327b8c6ffab84374510
|
Ruby
|
MAPC/metrofuture-api
|
/app/models/project_manager.rb
|
UTF-8
| 803
| 2.609375
| 3
|
[] |
no_license
|
class ProjectManager < ActiveRecord::Base
self.table_name = 'OwnerBase'
self.primary_key = 'OwnerId'
default_scope { where("OwnerIdType" => 8) }
has_many :projects, class_name: 'Base::Project', foreign_key: 'OwnerId'
alias_attribute :base_name, :Name
def name(options={})
order = options.fetch(:format) { :first_last }
self.send(order)
end
private
TOKEN = ","
def name_array
if base_name.include? TOKEN
ary = base_name.partition(TOKEN).map(&:strip)
[ary.last, ary.first]
else
ary = base_name.partition(" ")
[ary.first, ary.last]
end
end
def first_last
first, last = name_array
"#{first} #{last}"
end
def last_first
first, last = name_array
"#{last}, #{first}"
end
end
| true
|
d1613b442009b4c035fce6fdb4125c1d0f402419
|
Ruby
|
zachholcomb/brownfield-of-dreams
|
/app/models/following.rb
|
UTF-8
| 173
| 2.625
| 3
|
[] |
no_license
|
class Following
attr_reader :name, :link
def initialize(name, link)
@name = name
@link = link
end
def user?
User.find_by(github_user: @name)
end
end
| true
|
6648aea3c8ccc5cc7fe22e25e632eb5a84b50f36
|
Ruby
|
AlexStoll/RB101
|
/SmallProblems/Easy_6/4.rb
|
UTF-8
| 519
| 4.625
| 5
|
[] |
no_license
|
# Swap Case
# Problem
# Swap the case of each letter in a string
# Example
# swapcase('CamelCase') == 'cAMELcASE'
# Data
# String split to a chars array, joined back to a string
# Algorithm
# Split into chars
# Map through chars, if upcase => downcase, if downcase => upcase
# join chars back to a string
# Code
def swapcase(string)
output = string.chars.map do |char|
char == char.upcase ? char.downcase : char.upcase
end
output.join
end
p swapcase('CamelCase')
p swapcase('CamelCase') == 'cAMELcASE'
| true
|
6cde5d6544cbc0402b2a0ac9d6342cc258d17882
|
Ruby
|
ruan20a/ga_change_machine
|
/machine.rb
|
UTF-8
| 1,770
| 3.59375
| 4
|
[] |
no_license
|
require 'pry'
require 'debugger'
require 'active_record'
require 'active_support/inflector'
class Machine
attr_accessor :currency_set
CURRENCY = {"penny" => 1, "nickel" => 5, "dime" => 10, "quarter" => 25}
def initialize
@currency_set = Machine::CURRENCY
end
#standardize methods are used to clean up inputs
def standardize_currency(input)
plurals = @currency_set.keys.map{|key| key.pluralize}
plurals.each do |word|
input.gsub!(/#{word}/,word.singularize)
end #standardize to singular word for lookup
input.gsub!(/\s/,"") #standardizes spacing
input.split(",")
end
def standardize_cents(input)
input.gsub!(/\D/,"") #in case people write cents
input.to_i
end
def convert_cents(number)
output=[]
value_set = {} #reverse
@currency_set.each_pair{|k,v| value_set[v] = k}
sorted_values = value_set.keys.sort.reverse #sorted desc to get the largest denominations first (99%25 before 99%1)
if number > 0
sorted_values.each do |divisor| #going through each key in reverse
currency = value_set[divisor] #store the current currency
quotient, number = number.divmod(divisor) #quotient = currency; resetting number to remainder
output << "#{quotient} #{currency}" if quotient > 0
end
end
output.join(", ")
end
def convert_currency(arr_input)
total_cents = 0
arr_input.each do |amount|
@currency_set.keys.each do |key|
number = amount.gsub!(/#{key}/,"").to_i #isolate # of current currency
multiplier = number == nil ? 0 : number
cents = multiplier * @currency_set[key] # (num * value)
total_cents += cents #add it to the running total
end
end
return "#{total_cents} cents"
end
end
| true
|
6a47102fe7ab0ef155722db4ed5ffd95191d118e
|
Ruby
|
sdbeng/ryby_stand_class
|
/hello_ruby.rb
|
UTF-8
| 223
| 2.765625
| 3
|
[] |
no_license
|
puts "Hello guys, welcome to my Lemonade Stand!"
puts spacing = "************ ***********"
hello = "This is Alan your friendly neighbor.I'm happy to see you."
puts time = Time.new
3.times do
puts hello
end
puts spacing
| true
|
80b51b36e3fe39b1015d92caaed33566bd04d08a
|
Ruby
|
kirbynator/Brain-Teasers
|
/EvenOrOdd.rb
|
UTF-8
| 665
| 3.84375
| 4
|
[] |
no_license
|
require "pry"
def initialize(go)
prng = Random.new
responce = prng.rand(10)
prng = Random.new
responce1 = prng.rand(10)
prng = Random.new
responce2 = prng.rand(10)
@numbers = [responce1,responce2,responce, 11, 4]
@prejuice = []
go == ("even") ? (seger("even")) : (seger("odd"))
end
def seger(input)
@input = input
@numbers.each do |number|
case number % 2
when 0
@prejuice << {digit: number, prej: "even"}
@input == "even" ? (puts number) : nil
else
@prejuice << {digit: number, prej: "odd"}
@input == "odd" ? (puts number) : nil
end
end
end
puts "what do you want to see?"
print "(even/odd)> "
initialize(gets.strip)
| true
|
b4c49062242ec93e7639ae2de19456a829d8eaa9
|
Ruby
|
onofricamila/TTPS-Ruby
|
/p1/p1e17.rb
|
UTF-8
| 1,022
| 3.890625
| 4
|
[] |
no_license
|
# Ejercicio hecho por Seba-
# Original --> https://github.com/SebaRaimondi/TTPS-Ruby-Practicas/tree/master/Practica-01
# 17. Cada nuevo término en la secuencia de Fibonacci es generado sumando los 2 términos
# anteriores. Los primeros 10 términos son: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55. Considerando los
# términos en la secuencia de Fibonacci cuyos valores no exceden los 4 millones,
# encontrá la suma de los términos pares.
# def sumOddFib(max = 4000000)
# pre = [1] # Array, contains the 2 previous terms.
# count = 1 # Int, counts terms processed.
# cur = 1 # Has current term.
# sum = 0
# while (1..max).include?(cur)
# pre[count % 2] = cur
# if (cur % 2 == 0)
# sum += cur
# end
# cur = pre.sum
# count += 1
# end
# return sum
# end
# p sumOddFib(4000000)
# Version 2
def fib prev1, prev2, sum, max
curr = prev1 + prev2
return sum if curr > max
sum += curr if curr % 2 == 0
fib prev2, curr, sum, max
end
def sumOddFib2 max
fib 1, 1, 0, max
end
puts sumOddFib2 4_000_000
| true
|
a8787c672f2af5a3cb7a387e632814779b7041db
|
Ruby
|
J-Y/RubyQuiz
|
/ruby_quiz/quiz101_sols/solutions/Peter Severin/program_manager.rb
|
UTF-8
| 1,080
| 3.296875
| 3
|
[
"MIT"
] |
permissive
|
class Time
def seconds
(hour * 60 + min) * 60 + sec
end
end
class Program
attr_reader :channel
def initialize(program_details)
@program_start = program_details[:start]
@program_end = program_details[:end]
@channel = program_details[:channel]
end
end
class SpecificProgram < Program
def record?(time)
time.between?(@program_start, @program_end)
end
end
class RepeatingProgram < Program
WEEKDAYS = %w(mon tue wed thu fri sat sun)
def initialize(program_details)
super
@days = program_details[:days].map {|day| WEEKDAYS.index(day) + 1}
end
def record?(time)
@days.include?(time.wday) && time.seconds.between?(@program_start, @program_end)
end
end
class ProgramManager
def initialize()
@programs = []
end
def add(program_details)
case program_details[:start]
when Numeric
@programs << RepeatingProgram.new(program_details)
when Time
@programs[0, 0] = SpecificProgram.new(program_details)
end
self
end
def record?(time)
program = @programs.find {|program| program.record?(time)}
program ? program.channel : nil
end
end
| true
|
ef46b3e91372d6ca346f208f70746d56defab66f
|
Ruby
|
lisunshiny/oo-chess
|
/lib/pieces/stepping_pieces/king.rb
|
UTF-8
| 188
| 2.578125
| 3
|
[] |
no_license
|
class King < SteppingPiece
def move_deltas
[ [1, 1], [0, 1], [1, 0], [-1, 0], [0, -1], [-1, -1], [1, -1], [-1, 1] ]
end
def render
color == :black ? "♚" : "♔"
end
end
| true
|
4526f6627f62deec22af846b14cedbd99bdd7a9e
|
Ruby
|
tubbo/nitro
|
/app/services/github/user.rb
|
UTF-8
| 241
| 2.890625
| 3
|
[] |
no_license
|
module Github
# Basic wrapper for a user on the GitHub API
class User
attr_reader :name
def initialize(name: '')
@name = name
@user = Octokit.user(name)
end
def valid?
@user.present?
end
end
end
| true
|
a3f4021452ecc29c3b57319fcc342928e489252b
|
Ruby
|
c7/scoped_search
|
/test/query_language_test.rb
|
UTF-8
| 5,454
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
require File.dirname(__FILE__) + '/test_helper'
class QueryLanguageTest < Test::Unit::TestCase
# change this function if you switch to another query language parser
def parse_query(query)
ScopedSearch::QueryLanguageParser.parse(query)
end
def test_empty_search_query
parsed = parse_query('')
assert_equal 0, parsed.length
parsed = parse_query("\t \n")
assert_equal 0, parsed.length
end
def test_single_keyword
parsed = parse_query('hallo')
assert_equal 1, parsed.length
assert_equal 'hallo', parsed.first.first
parsed = parse_query(' hallo ')
assert_equal 1, parsed.length
assert_equal 'hallo', parsed.first.first
end
def test_multiple_keywords
parsed = parse_query(' hallo willem')
assert_equal 2, parsed.length
assert_equal 'willem', parsed.last.first
parsed = parse_query(" hallo willem van\tbergen ")
assert_equal 4, parsed.length
assert_equal 'hallo', parsed[0].first
assert_equal 'willem', parsed[1].first
assert_equal 'van', parsed[2].first
assert_equal 'bergen', parsed[3].first
end
def test_quoted_keywords
parsed = parse_query(' "hallo"')
assert_equal 1, parsed.length
assert_equal 'hallo', parsed.first.first
parsed = parse_query(' "hallo willem"')
assert_equal 1, parsed.length
assert_equal 'hallo willem', parsed.first.first
parsed = parse_query(' "hallo willem')
assert_equal 2, parsed.length
assert_equal 'hallo', parsed[0].first
assert_equal 'willem', parsed[1].first
parsed = parse_query(' "hallo wi"llem"')
assert_equal 2, parsed.length
assert_equal 'hallo wi', parsed[0].first
assert_equal 'llem', parsed[1].first
end
def test_quote_escaping
parsed = parse_query(' "hallo wi\\"llem"')
assert_equal 3, parsed.length
assert_equal 'hallo', parsed[0].first
assert_equal 'wi', parsed[1].first
assert_equal 'llem', parsed[2].first
parsed = parse_query('"\\"hallo willem\\""')
assert_equal 2, parsed.length
assert_equal 'hallo', parsed[0].first
assert_equal 'willem', parsed[1].first
end
def test_negation
parsed = parse_query('-willem')
assert_equal 1, parsed.length
assert_equal 'willem', parsed[0].first
assert_equal :not, parsed[0].last
parsed = parse_query('hallo-world')
assert_equal 1, parsed.length
assert_equal 'hallo-world', parsed.first.first
parsed = parse_query('hallo -world')
assert_equal 2, parsed.length
assert_equal 'hallo', parsed.first.first
assert_equal 'world', parsed.last.first
assert_equal :not, parsed.last.last
parsed = parse_query('123 -"456 789"')
assert_equal 2, parsed.length
assert_equal '123', parsed[0].first
assert_equal :like, parsed[0].last
assert_equal '456 789', parsed[1].first
assert_equal :not, parsed[1].last
end
def test_or
parsed = parse_query('Wes OR Hays')
assert_equal 1, parsed.length
assert_equal 'Wes OR Hays', parsed[0][0]
assert_equal :or, parsed[0][1]
parsed = parse_query('"Man made" OR Dogs')
assert_equal 1, parsed.length
assert_equal 'Man made OR Dogs', parsed[0][0]
assert_equal :or, parsed[0][1]
parsed = parse_query('Cows OR "Frog Toys"')
assert_equal 1, parsed.length
assert_equal 'Cows OR Frog Toys', parsed[0][0]
assert_equal :or, parsed[0][1]
parsed = parse_query('"Happy cow" OR "Sad Frog"')
assert_equal 1, parsed.length
assert_equal 'Happy cow OR Sad Frog', parsed[0][0]
assert_equal :or, parsed[0][1]
end
def test_as_of_date
# parsed = parse_query('9/27/1980')
# assert_equal 1, parsed.length
# assert_equal '9/27/1980', parsed[0][0]
# assert_equal :as_of, parsed[0][1]
# parsed = parse_query('"Man made" OR Dogs')
# assert_equal 1, parsed.length
# assert_equal 'Man made OR Dogs', parsed[0][0]
# assert_equal :or, parsed[0][1]
#
# parsed = parse_query('Cows OR "Frog Toys"')
# assert_equal 1, parsed.length
# assert_equal 'Cows OR Frog Toys', parsed[0][0]
# assert_equal :or, parsed[0][1]
#
# parsed = parse_query('"Happy cow" OR "Sad Frog"')
# assert_equal 1, parsed.length
# assert_equal 'Happy cow OR Sad Frog', parsed[0][0]
# assert_equal :or, parsed[0][1]
end
def test_long_string
str = 'Wes -Hays "Hello World" -"Goodnight Moon" Bob OR Wes "Happy cow" OR "Sad Frog" "Man made" OR Dogs Cows OR "Frog Toys"'
parsed = parse_query(str)
assert_equal 8, parsed.length
assert_equal 'Wes', parsed[0].first
assert_equal :like, parsed[0].last
assert_equal 'Hays', parsed[1].first
assert_equal :not, parsed[1].last
assert_equal 'Hello World', parsed[2].first
assert_equal :like, parsed[2].last
assert_equal 'Goodnight Moon', parsed[3].first
assert_equal :not, parsed[3].last
assert_equal 'Bob OR Wes', parsed[4].first
assert_equal :or, parsed[4].last
assert_equal 'Happy cow OR Sad Frog', parsed[5].first
assert_equal :or, parsed[5].last
assert_equal 'Man made OR Dogs', parsed[6].first
assert_equal :or, parsed[6].last
assert_equal 'Cows OR Frog Toys', parsed[7].first
assert_equal :or, parsed[7].last
end
end
| true
|
90da036d3a896c63624bea197657e2581c20136c
|
Ruby
|
Nossborn/learn_ruby
|
/02_calculator/calculator.rb
|
UTF-8
| 364
| 3.921875
| 4
|
[] |
no_license
|
#write your code here
def add(x, y)
return x + y
end
def subtract(x, y)
return x - y
end
def sum(array)
res = 0
array.each do |n|
res += n
end
return res
end
def multiply(array)
res = 1
array.each do |n|
res *= n
end
return res
end
def power(x, y)
return x ** y
end
def factorial(n)
res = 1
while n > 1
res*= n
n -= 1
end
return res
end
| true
|
52acd120ae1794fa6e5353e40ce014d523eacaa3
|
Ruby
|
thanhnguyen9/portfolio
|
/Week-1/day1/homework.rb
|
UTF-8
| 1,110
| 4.03125
| 4
|
[] |
no_license
|
# Assign "Hello World" to a variable message
message = "Hello World"
# Assign a different string to a different variable
any = "First app"
# Assign a number to a variable
number = 9
# Use string interpolation to display the number in a string
# string interpolation = #{}
puts "#{number}"
# Make an array of your favorite movies or books or bands. Have at least 4 values.
favorite = ["Titanic", "Transformer", "Fast and Furious", "Expandable"]
# Make a hash of information about yourself. Have at least 4 keys+values
info = {:name=>"Thanh", :age=>28, :race=>"Asian", :location=>"Waco"}
puts info
# BONUS 1
# Make a blog and share the url in your homework
# BONUS 2
# Make an array of hashes containing more information
# about your favorite movies. The hash should have at least 3 keys+values
arrays = [{:action=>"Taken"}, {:romance=>"Titanic"}, {:horror=>"Saw"}]
p arrays
# BONUS 3
# Use .each to loop through the array of hashes and print only one property of the hash
# For example { title: "Gone with the Wind" } loop through and print only the [:title]
arrays.each {|array| puts array.keys}
| true
|
24edf4e49500531f934648f0a7e31a6a8b78c00d
|
Ruby
|
CedricLor/art_des_nations
|
/lib/my_modules/aktion_article_pictures.rb
|
UTF-8
| 2,292
| 2.515625
| 3
|
[] |
no_license
|
# lib/my_modules/aktion_article.rb
module AktionArticlePictures
def persist_picture_changes
if md_to_update
update_pictures(@main_model, md_to_update, md_for_carousel)
end
if new_md
create_pictures
end
if for_card && for_card.match(/existing_md_/)
pict_id = for_card.sub(/existing_md_/, '')
update_pictures_for_card(@main_model, pict_id)
end
if md_for_destruction
destroy_pictures(@main_model, md_for_destruction)
end
end
def create_pictures
new_md.each do |key,value|
unless value["file"].nil?
created_md = MediaContainer.create(
title: value["title"],
media: value["file"]
)
created_md.picturizings.create(
picturizable_id: @main_model.id,
picturizable_type: @main_model.class.name,
for_carousel: value["for_carousel"],
for_card: (for_card && for_card.sub(/new_md_/, '') == key) ? "true" : "false"
)
end
end
end
private
def update_pictures(item, md_to_update, md_for_carousel)
item.picturizings.each do |pict|
pict.update(
for_carousel: md_for_carousel["#{pict.id}"]
)
pict.media_container.update_attributes(
title: md_to_update["#{pict.id}"]["title"] || '',
crop_x: md_to_update["#{pict.id}"]["crop_x"],
crop_y: md_to_update["#{pict.id}"]["crop_y"],
crop_w: md_to_update["#{pict.id}"]["crop_w"],
crop_h: md_to_update["#{pict.id}"]["crop_h"]
)
end
end
def update_pictures_for_card(item, pict_id)
Picturizing::Translation.where(picturizing_id: item.picturizings.ids, locale: I18n.locale).update_all(for_card: "false")
Picturizing::Translation.where(picturizing_id: pict_id, locale: I18n.locale).update_all(for_card: "true")
end
def destroy_pictures(item, md_for_destruction)
# destroy each picturizings which id has been passed in for destruction
item.picturizings.each do | picturizing |
picturizing.destroy if md_for_destruction.keys.include?(picturizing.id.to_s)
end
# if the media_container marked for destruction is not associated with any other picturizing, destroy it
item.media_containers.each do |md|
md.destroy if md.picturizings.size == 0
end
end
end
| true
|
a23ceb25b6c476221a2b5b4d2100ab0b9c748d6d
|
Ruby
|
SazPavel/Ruby_on_Rails_Valera_SIBSUTIS
|
/spec/lib/valera_spec.rb
|
UTF-8
| 2,416
| 2.703125
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Valera do
let(:valera) { Valera.new(100, 100, 10, 10, 100) }
let(:dead_valera) { Valera.new(0, 0, 0, 0, 0) }
let(:invalid_valera) { Valera.new(10_000, -100, 1000, -1000, -1000) }
describe '#initializer' do
context 'when health > 100' do
it { expect(invalid_valera.health).to be 100 }
end
context 'when mana < 0' do
it { expect(invalid_valera.mana).to be 0 }
end
context 'when cheerfulness > 10' do
it { expect(invalid_valera.cheerfulness).to be 10 }
end
context 'when fatigue < 0' do
it { expect(invalid_valera.fatigue).to be 0 }
end
context 'when money < 0' do
it { expect(invalid_valera.money).to be 0 }
end
end
describe '#reinitializer' do
context 'when correct reinitialize' do
subject { Valera.new(0, 0, 0, 0, 0) }
it do
subject.reinitialize!(10, 10, 10, 10, 10)
expect(subject.health).to be 10
expect(subject.mana).to be 10
expect(subject.cheerfulness).to be 10
expect(subject.fatigue).to be 10
expect(subject.money).to be 10
end
end
context 'when incorrect reinitialize' do
subject { Valera.new(0, 0, 0, 0, 0) }
it do
subject.reinitialize!(1000, 1000, 1000, 1000, -1000)
expect(subject.health).to be 100
expect(subject.mana).to be 100
expect(subject.cheerfulness).to be 10
expect(subject.fatigue).to be 100
expect(subject.money).to be 0
end
end
end
describe '#change_properties!' do
context 'when mana decrease' do
it { expect(valera.change_properties!('mana', -50)).to be 50 }
end
context 'when health encrease' do
it { expect(dead_valera.change_properties!('health', 10)).to be 10 }
end
context 'when cheerfulness more then 10' do
it { expect(valera.change_properties!('cheerfulness', 50)).to be 10 }
end
context 'when fatigue less then 0' do
it { expect(valera.change_properties!('fatigue', -150)).to be 0 }
end
context 'when money more then 100' do
it { expect(valera.change_properties!('money', 150)).to be 250 }
end
end
describe '#alive?' do
context 'when true' do
it { expect(valera.alive?).to be true }
end
context 'when false' do
it { expect(dead_valera.alive?).to be false }
end
end
end
| true
|
f5426769792a6e2413408b203d33317360eae92d
|
Ruby
|
timdisab/ruby_tut
|
/methods/greeting.rb
|
UTF-8
| 83
| 3.375
| 3
|
[] |
no_license
|
def greeting(name)
"Hi, " + name + ". How's it going?"
end
puts greeting("Tim")
| true
|
c596775d261991e450bdf00fd77b38ed83fed2f6
|
Ruby
|
Yorkshireman/string_keys_to_syms
|
/lib/convert.rb
|
UTF-8
| 134
| 3.296875
| 3
|
[] |
no_license
|
def convert(hash)
new_hash = {}
hash.each_pair do |key, value|
new_hash.store(key.downcase.to_sym, value)
end
new_hash
end
| true
|
61eb52af25463cc35301160871fb8dd35c1adde5
|
Ruby
|
Icicleta/practical_object_oriented_design_in_ruby
|
/06_Inheritance/06.rb
|
UTF-8
| 2,280
| 3.953125
| 4
|
[] |
no_license
|
# The very calling of super itself below means that Roadbike expects, nay requires, that one of its superclasses has a spares method, and that it returns a hash.
# Both send super in their initialize and spares methods, which creates a strong dependency.
class Bike
attr_reader :size, :chain, :tire_size
def initialize(args={})
@size = args[:size]
@chain = args[:chain] || default_chain
@tire_size = args[:tire_size] || default_tire_size
end
def spares
{tire_size: tire_size,
chain: chain
}
end
def default_chain
'10-speed'
end
def default_tire_size
raise NotImplementedError
"This #{self.class} cannot respond to:"
end
end
class RoadBike < Bike
attr_reader :tape_color
def initialize(args)
@tape_color = args[:tape_color]
super(args)
end
def spares
super.merge({tape_color: tape_color})
end
def default_tire_size
'23'
end
#...
end
class MountainBike < Bike # This < is the code for 'inherits from'
attr_reader :front_shock, :rear_shock
def initialize(args)
@front_shock = args[:front_shock]
@rear_shock = args[:rear_shock]
super(args)
end
def spares
super.merge(rear_shock: rear_shock)
end
def default_tire_size
'2.1'
end
end
# If, for example, someone creates a new class (RecumbentBike) and forgets to send super in the initialize method, it will blow up...
class RecumbentBike < Bike
attr_reader :flag
def initialize(args)
@flag = args[:flag]
end
def spares
{flag: flag
}
end
def default_chain
'9-speed'
end
def default_tire_size
'28'
end
end
# It won't have a valid size, chain or tire size because it doesn't do the call to super on initialize.
# Also, because it didn't send super in it's spares method, you'll be missing the tire and chain spares it needs. If you don't catch this in time, the Mechanic will be calling you when the bike is broken down in the rain and he doesn't have the right kit.
bent = RecumbentBike.new(flag: "Tall and Orange")
p bent.spares # =>{:flag=>"Tall and Orange"}
# Subclasses SHOULD NOT know how they need to interact with their superclasses. This is overly tight coupling and will cause trouble down the line. You should use HOOK MESSAGES
| true
|
24aa29d066741e94f39dbe418c9aa16e83f28b10
|
Ruby
|
joshuaylee/advent-of-code
|
/2018/16/opcodes.rb
|
UTF-8
| 2,847
| 3.03125
| 3
|
[] |
no_license
|
require 'set'
def each_sample(file)
e = File.open(file).each_line
loop do
reg_pre, instr, reg_post, _blank = e.next, e.next, e.next, e.next
break unless reg_pre.match(/^Before:/)
yield(parse_regs(reg_pre), parse_instr(instr), parse_regs(reg_post))
end
end
def parse_regs(str)
str.match(/\[(.*)\]/)[1].split(", ").map(&:to_i)
end
def parse_instr(str)
str.split.map(&:to_i)
end
def op_procs
@op_procs ||= {
addr: -> (r,a,b,c) { r[c] = r[a] + r[b] },
addi: -> (r,a,b,c) { r[c] = r[a] + b },
mulr: -> (r,a,b,c) { r[c] = r[a] * r[b] },
muli: -> (r,a,b,c) { r[c] = r[a] * b },
banr: -> (r,a,b,c) { r[c] = r[a] & r[b] },
bani: -> (r,a,b,c) { r[c] = r[a] & b },
borr: -> (r,a,b,c) { r[c] = r[a] | r[b] },
bori: -> (r,a,b,c) { r[c] = r[a] | b },
setr: -> (r,a,b,c) { r[c] = r[a] },
seti: -> (r,a,b,c) { r[c] = a },
gtir: -> (r,a,b,c) { r[c] = a > r[b] ? 1 : 0 },
gtri: -> (r,a,b,c) { r[c] = r[a] > b ? 1 : 0 },
gtrr: -> (r,a,b,c) { r[c] = r[a] > r[b] ? 1 : 0 },
eqir: -> (r,a,b,c) { r[c] = a == r[b] ? 1 : 0 },
eqri: -> (r,a,b,c) { r[c] = r[a] == b ? 1 : 0 },
eqrr: -> (r,a,b,c) { r[c] = r[a] == r[b] ? 1 : 0 }
}.freeze
end
def op_names
op_procs.keys
end
def perform_op(op_name, a, b, c, registers)
@op_procs[op_name].call(registers, a, b, c)
end
def sample_acts_like_op?(op_name, instr, reg_pre, reg_expected)
regs = reg_pre.dup
perform_op(op_name, *instr.slice(1,3), regs)
regs == reg_expected
end
def part1
num_samples = 0
each_sample(ARGV[0]) do |reg_pre, instr, reg_post|
potential_ops = op_names.count do |op_name|
sample_acts_like_op?(op_name, instr, reg_pre, reg_post)
end
num_samples += 1 if potential_ops >= 3
end
puts "#{num_samples} samples act like 3 or more ops"
end
def eliminate_mappings(map, opcode)
op_name = map[opcode].first
map.each_with_index do |potential_ops, opcode|
next if potential_ops.one?
potential_ops.delete(op_name)
eliminate_mappings(map, opcode) if potential_ops.one?
end
end
def map_opcodes(file)
map = op_names.count.times.map { op_names.to_set }
each_sample(ARGV[0]) do |reg_pre, instr, reg_post|
op_names.each do |op_name|
opcode = instr.first
next if sample_acts_like_op?(op_name, instr, reg_pre, reg_post)
map[opcode].delete(op_name)
eliminate_mappings(map, opcode) if map[opcode].one?
end
end
map.map(&:first)
end
def part2
opcodes = map_opcodes(ARGV[0])
puts "Mapped opcodes"
opcodes.each_with_index do |op_name, opcode|
puts "#{opcode}: #{op_name}"
end
regs = [0, 0, 0, 0]
File.open(ARGV[1]).each do |line|
instr = parse_instr(line.strip)
op_name = opcodes[instr[0]]
perform_op(op_name, *instr.slice(1,3), regs)
end
puts "After test program: #{regs.inspect}"
end
part1
part2
| true
|
93d6015ba35b6e9ad62684a8e4e13d42707bc2fc
|
Ruby
|
yeatsphillis87/rotuka-rails-extender
|
/lib/rotuka/core_ext/hash.rb
|
UTF-8
| 865
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
# Imported from http://source.collectiveidea.com/public/rails/plugins/awesomeness/lib/awesomeness/core_ext/hash.rb
class Hash
# Usage { :a => 1, :b => 2, :c => 3}.only(:a) -> {:a => 1}
def only(*keys)
self.reject { |k,v| !keys.include? k.to_sym }
end
# Usage {:a => [1, 3, 4], :b => [2, 5]}.without(:a => 1)
# returns {:a => [3, 4], :b => [2, 5]}
def without(hash)
hash = hash.with_indifferent_access if self.instance_of?(HashWithIndifferentAccess)
# create a new hash using this class, so we get a new HashWithIndifferentAccess if this is one
inject(self.class.new) do |result, (k, v)|
result[k] = (hash[k] && v.respond_to?(:reject) ? v.reject {|v, _| v == hash[k] } : v)
result
end
end
def compact!
delete_if { |k, v| v.blank? }
end
def compact
dup.compact!
end
end
| true
|
244b0510a3bdef65ce8a8d5a40fe2b35d124f2e6
|
Ruby
|
oldGCdM/ruby-collaborating-objects-lab-london-web-060418
|
/lib/mp3_importer.rb
|
UTF-8
| 384
| 3.171875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class MP3Importer
attr_accessor :path, :files
def initialize(file_path)
@path = file_path
@files = self.files
end
def files
files_list = Dir[@path + '/*']
files_list.map do |song_path|
song_ary = song_path.split('/')
song_ary.last
end
end
def import
@files.each do |file_name|
Song.new_by_filename(file_name)
end
end
end
| true
|
e621cb7c39d137a59eeb94c56fba83bb8f3d4fc1
|
Ruby
|
jayshenk/algorithms
|
/binary_search.rb
|
UTF-8
| 351
| 3.890625
| 4
|
[] |
no_license
|
def binary_search(array, target)
left = 0
right = array.size - 1
while left + 1 < right
mid = left + (right - left) / 2
if array[mid] == target
return mid
elsif array[mid] > target
right = mid
else
left = mid
end
end
return left if array[left] == target
return right if array[right] == target
end
| true
|
18157d610338debef6aa667dea9cb81359b4f8b9
|
Ruby
|
lennhy/ruby-collaborating-objects-lab-v-000
|
/lib/artist.rb
|
UTF-8
| 1,236
| 3.78125
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# require "pry"
class Artist
attr_accessor :name, :songs
@@all =[]
def initialize(name)
@name= name
@songs = []
@@all << self
end
def self.all
@@all # to be able to use logic with @@all variable first define / expose the all class variable
end
def add_song(song)
@songs << song
end
def save
@@all << self unless @@all.include?(self)
end
#if find then return the name else create a new name
def self.find_or_create_by_name(name)
self.find(name) ? self.find(name) : self.create(name)
end
#option to look for artist.name that matches name
def self.find(name)
self.all.find {|artist| artist.name == name }
end
# gives us the option to create a new artist where we create
def self.create(name)
self.new(name).tap {|artist| artist.save}
end
# refactor
# def self.find_or_create_by_name(name)
# found_artist = self.all.find {|artist_name|}
# if found_artist
# found_artist
# else
# artist= Artist.new(name)
# end
# end
def print_songs
@songs.each do |song| #iterate thtough the instances
puts song.name #print out the song names by using name as the method for each song instance
end
end
end
| true
|
c877539297a3f028f1657974389075652643dbd9
|
Ruby
|
flores34000/exo_ruby
|
/exo5.rb
|
UTF-8
| 237
| 3.25
| 3
|
[] |
no_license
|
puts "on vas compter le nombre d'heures de travail à THP"
puts "travail : #{10*5*11} heure"
puts "en minutes ça fait : #{10*5*11*60} s"
puts "et en secondes:"
puts 10*5*11*60*60
puts 3 + 2 < 5 - 7
puts "ca fait combien 3 + 2 ? #{3+2}"
| true
|
3a736b9c6d54b64adad69f8b17d1b79f11974f02
|
Ruby
|
balanalina/Assignment2_CarService
|
/spec/test_spec.rb
|
UTF-8
| 3,943
| 2.765625
| 3
|
[] |
no_license
|
require_relative "../car_service/request_service"
describe 'test for one car, no waiting/scheduling' do
context 'leave it today, take it today' do
it 'should print Thursday 23-07-2020 17:30' do
service = RequestService.new
allow(Time).to receive(:now).and_return(Time.new(2020,07,23,15,30))
expect(service.add_request).to eq 'Thursday 23-07-2020 17:30'
end
end
context "leave it during the week, take it the next week day "do
it 'should print Friday 24-07-2020 09:30' do
service = RequestService.new
allow(Time).to receive(:now).and_return(Time.new(2020,07,23,17,30))
expect(service.add_request).to eq 'Friday 24-07-2020 09:30'
end
end
context "leave it on friday, take it on saturday" do
it 'should print Saturday 25-07-2020 10:30' do
service = RequestService.new
allow(Time).to receive(:now).and_return(Time.new(2020,07,24,17,30))
expect(service.add_request).to eq 'Saturday 25-07-2020 10:30'
end
end
context "leave it on saturday, take it on saturday" do
it 'should print Saturday 25-07-2020 12:30' do
service = RequestService.new
allow(Time).to receive(:now).and_return(Time.new(2020,07,25,10,30))
expect(service.add_request).to eq 'Saturday 25-07-2020 12:30'
end
end
context "leave it on saturday, take it on monday" do
it 'should print Monday 27-07-2020 09:20' do
service = RequestService.new
allow(Time).to receive(:now).and_return(Time.new(2020,07,25,14,20))
expect(service.add_request).to eq 'Monday 27-07-2020 09:20'
end
end
end
describe "test for more than one car" do
context "8 cars come at the same time" do
it 'for the 8 th car it should print Monday 27-07-2020 15:23' do
service = RequestService.new
allow(Time).to receive(:now).and_return(Time.new(2020, 07, 25, 14, 20))
expect(service.add_request).to eq 'Monday 27-07-2020 09:20'
expect(service.add_request).to eq 'Monday 27-07-2020 09:20'
expect(service.add_request).to eq 'Monday 27-07-2020 11:21'
expect(service.add_request).to eq 'Monday 27-07-2020 11:21'
expect(service.add_request).to eq 'Monday 27-07-2020 13:22'
expect(service.add_request).to eq 'Monday 27-07-2020 13:22'
expect(service.add_request).to eq 'Monday 27-07-2020 15:23'
expect(service.add_request).to eq 'Monday 27-07-2020 15:23'
end
end
context "9 cars come 1 hour and a half apart" do
it 'for the 5th car should print Tuesday 28-07-2020 13:30, for the 8th Tuesday 28-07-2020 18:00 car and for the 9th Wednesday 29-07-2020 09:30' do
service = RequestService.new
allow(Time).to receive(:now).and_return(Time.new(2020, 07, 27, 15, 30))
expect(service.add_request).to eq 'Monday 27-07-2020 17:30'
allow(Time).to receive(:now).and_return(Time.new(2020, 07, 27, 17))
expect(service.add_request).to eq 'Tuesday 28-07-2020 09:00'
allow(Time).to receive(:now).and_return(Time.new(2020, 07, 28, 8, 30))
expect(service.add_request).to eq 'Tuesday 28-07-2020 10:30'
allow(Time).to receive(:now).and_return(Time.new(2020, 07, 28, 10))
expect(service.add_request).to eq 'Tuesday 28-07-2020 12:00'
allow(Time).to receive(:now).and_return(Time.new(2020, 07, 28, 11, 30))
expect(service.add_request).to eq 'Tuesday 28-07-2020 13:30'
allow(Time).to receive(:now).and_return(Time.new(2020, 07, 28, 13))
expect(service.add_request).to eq 'Tuesday 28-07-2020 15:00'
allow(Time).to receive(:now).and_return(Time.new(2020, 07, 28, 14, 30))
expect(service.add_request).to eq 'Tuesday 28-07-2020 16:30'
allow(Time).to receive(:now).and_return(Time.new(2020, 07, 28, 16))
expect(service.add_request).to eq 'Tuesday 28-07-2020 18:00'
allow(Time).to receive(:now).and_return(Time.new(2020, 07, 28, 17, 30))
expect(service.add_request).to eq 'Wednesday 29-07-2020 09:30'
end
end
end
| true
|
25715a1cbedf7918784ed4db8b1d92c3cebbff77
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/cs169/combine_anagrams_latest/2514.rb
|
UTF-8
| 498
| 3.4375
| 3
|
[] |
no_license
|
def combine_anagrams(words)
anagramForms = Hash.new
words.each do |word|
anagramForms[word] = word.downcase.split(//).sort
end
groups=[]
anagramForms.hash_revert.each_value do |value|
groups.push(value)
end
groups
end
def anagram?(word1,word2)
word1.downcase.split(//).sort == word2.downcase.split(//).sort
end
class Hash
def hash_revert # reverts keys and values
r = Hash.new {|h,k| h[k] = []}
each {|k,v| r[v] << k}
r
end
end
| true
|
c1316f63cf88bd0b35595021ab22f09c10a3a447
|
Ruby
|
coding-git/ruby-basics
|
/loops/count_down.rb
|
UTF-8
| 114
| 3.484375
| 3
|
[] |
no_license
|
# Loops - exercise 4
def count_down(num)
puts num
if num > 0
count_down(num-1)
end
end
count_down(10)
| true
|
95425ffe56a791e6b82b3d20ea6f9ab7d1edc17c
|
Ruby
|
dwoznicki/spoonacular
|
/lib/spoonacular/querify.rb
|
UTF-8
| 493
| 3.359375
| 3
|
[
"MIT"
] |
permissive
|
class Object
def querify
if self.is_a? String
return self.gsub(/,\s?/, "%2C").gsub(" ", "+")
elsif self.is_a? Array
return self.join("%2C").gsub(" ", "+")
elsif self.is_a? Hash
result = []
self.each do |key, value|
result << "#{key.to_s.to_camel_case}=#{value.querify}"
end
return result.join("&")
end
end
def to_camel_case
self.chars.length.times do |i|
if self[i] == "_"
self[i+1] = self[i+1].upcase
end
end
return self.delete "_"
end
end
| true
|
398db8bf9479f4aedfda1f5b02ecec63e87fbf89
|
Ruby
|
ianagbip1oti/advent-of-code-2020
|
/ruby/day08.rb
|
UTF-8
| 6,099
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
require 'set'
INSTRUCTIONS = DATA.map(&:split).map { |op, arg| [op.to_sym, arg.to_i] }.freeze
def execute(instructions = INSTRUCTIONS)
executed = Set.new
ip = 0
acc = 0
while not executed.include? ip and ip < instructions.size
ins = instructions[ip]
executed << ip
case ins
in [:acc, arg]
acc += arg
in [:jmp, arg]
ip += arg - 1
else
nil
end
ip += 1
end
[acc, ip < instructions.size]
end
def fix
(0...INSTRUCTIONS.size).each do |idx|
ins_to_test = INSTRUCTIONS.dup
case INSTRUCTIONS[idx]
in [:jmp, arg]
ins_to_test[idx] = [:nop, arg]
in [:nop, arg]
ins_to_test[idx] = [:jmp, arg]
else
next
end
acc, looped = execute(ins_to_test)
return acc unless looped
end
raise 'No solution found'
end
p execute[0]
p fix
__END__
jmp +1
acc -18
acc +19
acc +19
jmp +202
acc +15
acc +42
acc +30
acc -7
jmp +535
acc +31
acc +9
jmp +581
nop +501
acc +44
acc +18
acc -4
jmp +545
acc +9
acc +5
nop -2
acc +3
jmp +475
acc -10
acc +14
acc +29
nop +471
jmp +470
acc +2
nop +375
acc +31
acc +6
jmp +420
acc -1
acc +2
nop +185
jmp +490
acc +2
jmp +317
nop +282
jmp +457
acc +37
jmp +254
acc +19
jmp +436
jmp +458
acc -7
acc -2
acc -17
jmp +454
acc +37
jmp +212
acc +6
acc +5
acc -7
jmp +104
acc +5
nop +134
acc +46
jmp +541
acc +4
acc +46
acc +18
jmp -53
acc +10
jmp +285
acc +39
acc +34
nop +109
acc +47
jmp +32
jmp +1
jmp +143
acc +36
jmp +429
acc +45
acc +22
jmp -59
acc +0
acc +23
acc +30
acc -7
jmp -45
acc +46
acc +31
jmp +164
acc +37
acc +34
acc +40
acc -1
jmp +246
nop -46
acc +2
acc +31
jmp +221
nop +413
jmp -51
acc -14
jmp +145
acc +1
nop +77
jmp +131
jmp +370
nop +513
acc +7
jmp +476
acc +22
acc +37
acc +44
jmp +334
acc +9
acc -1
acc +5
acc +27
jmp +351
acc +31
jmp +220
nop -61
acc +34
jmp +504
nop +471
acc +6
acc +48
jmp -17
jmp +217
acc +13
acc +0
acc +25
jmp +144
acc -5
acc +17
nop +341
jmp -26
acc -10
acc +34
jmp +168
nop -16
acc -6
acc -10
acc +38
jmp +30
acc -2
acc -14
jmp +419
acc +40
acc -17
acc +27
acc +8
jmp +101
nop +370
acc +2
acc -10
acc -7
jmp +224
nop +437
acc +42
acc +50
acc +39
jmp +81
jmp +11
jmp +143
acc +6
acc +46
jmp -107
acc +13
jmp -109
acc +5
jmp +1
jmp +467
jmp -159
nop +421
jmp +243
acc +44
nop +412
acc -6
acc +13
jmp +56
acc -12
acc +18
jmp +313
nop +151
acc +5
acc +49
jmp +120
acc +46
acc +23
nop -122
acc +21
jmp -55
acc -15
jmp -115
acc +19
nop +116
acc +32
acc +21
jmp +16
acc +27
acc +32
jmp +359
acc +16
acc +18
acc +15
jmp +54
nop +182
acc +4
jmp +361
acc +4
acc +38
acc +49
jmp -94
jmp +428
acc +0
acc +9
jmp +224
jmp +82
nop +57
acc +6
jmp +1
jmp +144
jmp +20
jmp +265
jmp +402
nop +114
acc -12
acc -11
acc +1
jmp +412
nop -163
acc +50
acc +1
acc -9
jmp -20
acc +10
acc +6
jmp +323
acc +10
jmp +1
acc +42
jmp +46
acc +35
acc +31
jmp -139
jmp +129
jmp -193
acc -4
nop +247
nop -163
acc +25
jmp -26
acc +34
acc +26
acc +40
jmp +220
acc -6
acc +6
jmp +311
acc +0
acc +14
acc +41
acc +6
jmp +284
acc +32
jmp -13
nop +157
acc -4
acc +47
jmp -146
acc +34
acc +6
nop +196
acc +5
jmp +268
acc -8
jmp -176
acc +34
acc +17
jmp +1
jmp +114
acc +32
acc +39
nop +313
acc +38
jmp -237
jmp -273
acc +21
acc +26
acc +31
jmp -231
acc +17
jmp -105
nop +333
nop +17
jmp +11
acc -9
acc +2
jmp -162
acc +3
acc +0
nop +318
jmp +215
acc +14
acc +32
jmp -196
jmp +33
acc -6
acc +45
acc +27
jmp -166
acc -1
jmp -25
acc +0
acc +4
acc -14
acc +0
jmp -115
nop +118
acc +28
nop +175
acc +45
jmp -97
jmp +78
jmp -284
acc +35
nop -248
acc -18
acc -6
jmp -308
jmp -95
acc -2
acc +0
jmp +255
acc +7
jmp -24
acc +17
acc +20
jmp -220
jmp +172
acc +40
acc +39
acc +19
jmp -238
nop +44
nop -99
nop +238
jmp +195
acc -14
acc +36
acc +40
acc -11
jmp -65
nop -54
nop +47
acc -11
jmp +18
jmp +98
jmp +252
nop -1
acc +1
acc +10
jmp -4
jmp -319
jmp -46
acc -8
acc +50
acc +43
jmp -174
acc +22
acc +4
acc +32
acc -6
jmp +73
acc +8
jmp -31
acc +16
nop +11
acc +26
jmp -98
acc -11
acc +40
jmp +101
acc +28
acc +30
acc -16
acc +7
jmp +239
jmp -179
acc +47
acc +15
acc +42
acc +26
jmp +30
acc +17
acc +3
acc -5
nop -98
jmp -236
acc +2
jmp +196
acc +39
acc -14
acc +36
acc +49
jmp +189
jmp +235
acc +27
acc -2
acc +16
acc +40
jmp -81
acc -5
acc +17
acc -1
jmp +1
jmp -129
nop -171
acc +47
jmp +169
acc -16
acc -5
jmp +172
nop -84
acc +8
acc +40
acc +43
jmp -33
acc +39
nop -12
jmp +53
acc +36
jmp -270
acc +17
acc -1
jmp -255
acc +0
acc -12
jmp -371
jmp -216
acc +45
acc -18
acc +23
acc -17
jmp -37
jmp -386
nop -302
acc -19
acc -16
jmp -297
acc -18
acc -7
acc +17
acc +17
jmp -173
jmp +114
acc +4
acc +19
nop -296
jmp -36
acc -18
acc -14
acc +6
nop -27
jmp -101
acc +15
nop -407
jmp +44
acc -18
acc -6
acc +33
acc +36
jmp +80
acc +43
jmp +73
acc -2
acc +7
acc +4
jmp -10
acc +46
nop -49
acc +7
jmp +65
acc +24
jmp +144
acc +13
acc +26
jmp -351
jmp +1
acc +34
nop +62
jmp -363
acc -4
acc -5
jmp +23
jmp +82
acc -7
acc -7
acc +15
jmp -468
acc +7
nop -423
jmp -178
nop -425
acc +23
jmp -181
acc +6
acc -11
jmp -321
acc +3
jmp -122
acc +12
jmp +44
acc -5
acc -16
acc +16
jmp -281
acc +33
acc -4
acc +15
jmp +9
jmp +63
acc +35
nop -12
acc +25
acc -10
jmp -452
acc +1
jmp -148
acc +8
acc +40
acc +48
jmp +2
jmp -315
nop -325
acc -4
acc +16
acc -4
jmp -369
acc +21
acc +3
jmp -153
nop -25
acc +0
jmp -84
acc +32
jmp +19
acc -18
acc -1
jmp -385
jmp +1
jmp -357
acc -13
acc -13
jmp -360
jmp -393
acc +4
nop -102
jmp -316
jmp -248
acc +4
nop -487
jmp -339
acc +3
jmp -190
acc +24
acc +31
jmp -166
jmp -482
acc +22
acc +32
jmp -290
acc +22
acc +48
acc +5
acc -6
jmp -330
nop -203
acc +7
acc +1
jmp -287
acc +15
acc +3
jmp -230
acc +37
nop -162
jmp +33
jmp -147
acc +16
acc +39
acc +49
jmp -560
acc +26
jmp +26
jmp -283
jmp -486
acc -9
jmp +1
acc +25
acc +1
jmp -514
acc +46
jmp -166
acc -5
acc +35
nop -204
jmp -175
nop -30
nop +11
jmp -400
acc +15
acc -7
acc -1
jmp +18
acc +31
acc +16
acc +43
acc +33
jmp -260
acc +1
acc +23
acc +25
acc -1
jmp -200
acc -15
jmp -314
jmp -238
jmp -75
jmp -192
acc +30
jmp -525
acc -14
jmp +17
acc +7
acc +9
acc -6
nop -312
jmp -559
acc +28
jmp -305
jmp -239
acc +0
acc -5
acc +9
jmp -471
nop -327
acc -5
acc -19
jmp -496
acc +17
jmp +1
jmp +1
acc +29
jmp +1
| true
|
30255dd0ddd531d9b377185e508ccdaa30861b9d
|
Ruby
|
mateuszkosc/udemy
|
/podstawy/wyrazenia.rb
|
UTF-8
| 344
| 3.125
| 3
|
[] |
no_license
|
a = b = 2
p a
p b
a, b = 1, 2
p a
p b
a, b, *c = [1, 2, 3, 4, 5]
p a
p b
p c
x = 1..10
p x.to_a
p [*x]
# Łańcuchowe wywoływanie wyrażeń
y = [1, 3, 2, 4, 5, 1, 3, 4, 5, 6]
# wypisanie wartości unikalnych
p y.uniq
# posotrowanie wartosci unikalnych
p y.uniq.sort
# odwrócenie posortowanych wartości unikalnych
p y.uniq.sort.reverse
| true
|
0637ea2a690d8231e6040f8b1a513704c4a4c143
|
Ruby
|
IanLawson8913/lesson_6
|
/testing/assertions.rb
|
UTF-8
| 1,221
| 3.921875
| 4
|
[] |
no_license
|
# assert(test) # Fails unless test is truthy.
# assert_equal(exp, act) # Fails unless exp == act.
# assert_nil(obj) # Fails unless obj is nil.
# assert_raises(*exp) { ... } # Fails unless block raises one of *exp.
# assert_instance_of(cls, obj) # Fails unless obj is an instance of cls.
# assert_includes(collection, obj) # Fails unless collection includes obj
class Car
attr_accessor :wheels, :name
def initialize
@wheels = 4
end
end
assert
def test_car_exists
car = Car.new
assert(car)
end
assert_equal
def test_wheels
car = Car.new
assert_equal(4, car.wheels)
end
assert_nil
def test_name_is_nil
car = Car.new
assert_nil(car.name)
end
assert_raises
def test_raise_initialize_with_arg
assert_raises(ArgumentError) do
car = Car.new(name: "Joey") # this code raises ArgumentError, so this assertion passes
end
end
assert_instance_of
def test_instance_of_car
car = Car.new
assert_instance_of(Car, car)
end
This test is more useful when dealing with inheritance. This example is a little contrived.
assert_includes
def test_includes_car
car = Car.new
arr = [1, 2, 3]
arr << car
assert_includes(arr, car)
end
| true
|
febf48b6460447dd6776f85bb2fb3a5ac03f7e58
|
Ruby
|
vagf0t/recursive
|
/spec/models/missing_integer_recursive_spec.rb
|
UTF-8
| 1,076
| 3.015625
| 3
|
[] |
no_license
|
require 'spec_helper'
describe Recursive::MissingIntegerRecursive do
context 'given an array with a gap' do
it 'should find the missing one' do
expect(subject.solution([1, 2, 5])).to eq 3
end
end
context 'given an array with no gap' do
it 'should find the next one' do
expect(subject.solution([1, 2, 3])).to eq 4
end
end
context 'given an array with only negative values' do
it 'should return 1' do
expect(subject.solution([-1, -2, -3])).to eq 1
end
end
context 'given an array with only one element' do
it 'should return the proper one' do
expect(subject.solution([3])).to eq 1
end
end
context 'given an array with only one elementof value 1' do
it 'should return the proper one' do
expect(subject.solution([1])).to eq 2
end
end
context 'given an array of 100000 integers including maximum and minimum values' do
it 'should return the proper one' do
a = Array.new(100000) { rand(-1000000...1000000) }
expect(subject.solution(a) > 0).to be true
end
end
end
| true
|
074b0091b018885a886807de843d9f1643c89251
|
Ruby
|
hari31582/jv
|
/spec/town_spec.rb
|
UTF-8
| 2,552
| 3.046875
| 3
|
[] |
no_license
|
# Test Town class
# Author: Haribhau Ingale
# Date: 30 April 2012
require 'csv'
require File.dirname(__FILE__)+'/../lib/town'
require File.dirname(__FILE__)+'/../lib/restaurant'
require File.dirname(__FILE__)+'/../lib/value_meal'
class FileReaderMoc
def read
<<-EOF
1, 1, i1
1, 2, i2
1, 3, i3
1, 4, i4
1, 4, i2, i3
1, 4.5, i1, i2, i3
1, 6.5, i1, i3, i4
2, 1, i1
2, 1.9, i2
2, 3, i3
2, 4, i4
2, 4.25, i2, i3
2, 4.75, i1, i2, i3
2, 6.55, i1, i3, i4
EOF
end
end
describe Town do
before(:each) do
@town = Town.new("ABC")
File.stub(:open).and_return(StringIO.new FileReaderMoc.new.read)
end
it "should display economical Hotel for order i1 , i4" do
result = @town.search_low_price_restaurant(['i1','i4'])
result.print.should == "Restaurant id:1,Price:5.0"
end
it "should display economical Hotel for order i1" do
result = @town.search_low_price_restaurant(['i1'])
result.print.should == "Restaurant id:1,Price:1.0"
end
it "should display economical Hotel for order i2" do
result = @town.search_low_price_restaurant(['i2'])
result.print.should == "Restaurant id:2,Price:1.9"
end
it "should display economical Hotel for order i2 , i3" do
result = @town.search_low_price_restaurant(['i2','i3'])
result.print.should == "Restaurant id:1,Price:4.0"
end
it "should display economical Hotel for order i2 , i4" do
result = @town.search_low_price_restaurant(['i2','i4'])
result.print.should == "Restaurant id:2,Price:5.9"
end
it "should display economical Hotel for order i3 , i4" do
result = @town.search_low_price_restaurant(['i3','i4'])
result.print.should == "Restaurant id:1,Price:6.5"
end
it "should display economical Hotel for order i2 , i3 , i4" do
result = @town.search_low_price_restaurant(['i2','i3','i4'])
result.print.should == "Restaurant id:1,Price:8.0"
end
it "should display economical Hotel for order i1,i2 , i3 , i4" do
result = @town.search_low_price_restaurant(['i1','i2','i3','i4'])
result.print.should == "Restaurant id:2,Price:8.45"
end
it "should display economical Hotel for order i1,i2,i2,i2,i3 ,i3,i3" do
result = @town.search_low_price_restaurant(['i1','i2','i2','i2','i3','i3','i3'])
result.print.should == "Restaurant id:1,Price:12.5"
end
it "should display economical Hotel for order i1 i1 i1 i1 i1 i2 i3 i3 i3 i4 i4" do
result = @town.search_low_price_restaurant(['i1','i1','i1','i1','i1','i2','i3','i3','i3','i4','i4'])
result.print.should == "Restaurant id:1,Price:19.5"
end
end
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.